Search is not available for this dataset
content
stringlengths 60
399M
| max_stars_repo_name
stringlengths 6
110
|
---|---|
<|start_filename|>src/dataLayer/mongo/event-datalayer.test.js<|end_filename|>
/* global expect beforeAll afterAll */
import {
createCommunityEvent,
getCommunityEvent,
getCommunityEvents,
deleteCommunityEvent
} from './communityEvent';
import { createUser } from './user';
import CommunityEvent from '../model/communityEvent.js';
import { isObject, isEmpty } from 'lodash';
import mongoose from 'mongoose';
import uuid from 'uuid/v4';
import { isDate, isArray } from 'util';
const validContextForBrian = global.mockedContextWithValidTokenForBrian;
const validContextForDennis = global.mockedContextWithValidTokenForDennis;
const validContextForKen = global.mockedContextWithValidTokenForKen;
const event = {
title: 'epoch',
description: 'The start of POSIX time',
date: 'Thu 1 Jan 1970 00:00:00'
};
const eventValidAttendees = {
...event,
attendees: [
{ email: '<EMAIL>' },
{ email: '<EMAIL>' }
]
};
const eventInValidAttendees = {
...event,
attendees: [{ email: '<EMAIL>' }]
};
beforeAll(async function beforeAllTests() {
await mongoose.connect(global.__MONGO_URI__);
// Create some users for our tests
await createUser({}, {}, validContextForBrian);
await createUser({}, {}, validContextForDennis);
await createUser({}, {}, validContextForKen);
// Create an event
await createCommunityEvent({}, eventValidAttendees, validContextForBrian);
});
afterAll(async function afterAllTests() {
await mongoose.connection.db.dropDatabase();
await mongoose.disconnect();
});
describe('createCommunityEvent', () => {
it('should return an Event object', done => {
expect.assertions(7);
createCommunityEvent({}, eventValidAttendees, validContextForBrian)
.then(result => {
const {
externalId,
title,
description,
owner,
date,
attendees
} = result;
// there is some weird Promise thing going on with `result`
// which screws with lodash.has()
// TODO: DRY this please
const hasKeys =
!isEmpty(externalId) &&
!isEmpty(title) &&
!isEmpty(description) &&
!isEmpty(owner) &&
isDate(date) &&
isArray(attendees);
const hasOwnerKeys = !isEmpty(owner.name) && !isEmpty(owner.email);
const hasAttendeeKeys =
!isEmpty(attendees[0].name) && !isEmpty(attendees[0].email);
expect(isObject(result)).toBe(true);
expect(isObject(result.owner)).toBe(true);
expect(isObject(result.attendees[0])).toBe(true);
expect(result.attendees).toHaveLength(2);
expect(hasKeys).toBe(true);
expect(hasOwnerKeys).toBe(true);
expect(hasAttendeeKeys).toBe(true);
return;
})
.then(done)
.catch(done);
});
it('should throw if an attendee does yet exist', done => {
expect.assertions(2);
createCommunityEvent({}, eventInValidAttendees, validContextForBrian).catch(
err => {
expect(err).toMatchSnapshot();
expect(err).toContain('Unable to find attendee');
done();
return;
}
);
});
it('should throw if an imageUrl is not a valid URL', done => {
expect.assertions();
createCommunityEvent(
{},
{
...event,
imageUrl: 'notaUrl'
},
validContextForBrian
).catch(err => {
expect(err).toMatchSnapshot();
expect(err).toContain('Expected valid URL string');
done();
return;
});
});
it('should throw if an isLocked is not a Boolean', done => {
expect.assertions(2);
createCommunityEvent(
{},
{
...event,
isLocked: 'notaBoolean'
},
validContextForBrian
).catch(err => {
expect(err).toMatchSnapshot();
expect(err).toContain('Expected a Boolean value');
done();
return;
});
});
});
describe('getCommunityEvent', () => {
it('should return an Event object for a valid request', done => {
expect.assertions(7);
getCommunityEvent({}, { title: 'epoch' }, validContextForBrian)
.then(result => {
const {
externalId,
title,
description,
owner,
date,
attendees
} = result;
// there is some weird Promise thing going on with `result`
// which screws with lodash.has()
const hasKeys =
!isEmpty(externalId) &&
!isEmpty(title) &&
!isEmpty(description) &&
!isEmpty(owner) &&
isDate(date) &&
isArray(attendees);
const hasOwnerKeys = !isEmpty(owner.name) && !isEmpty(owner.email);
const hasAttendeeKeys =
!isEmpty(attendees[0].name) && !isEmpty(attendees[0].email);
expect(isObject(result)).toBe(true);
expect(isObject(owner)).toBe(true);
expect(isObject(attendees[0])).toBe(true);
expect(attendees).toHaveLength(2);
expect(hasKeys).toBe(true);
expect(hasOwnerKeys).toBe(true);
expect(hasAttendeeKeys).toBe(true);
return;
})
.then(done)
.catch(done);
});
it('title search non existing event should return null', done => {
expect.assertions(1);
getCommunityEvent({}, { title: 'Yeah nah' }, validContextForBrian).then(
data => {
expect(data).toBe(null);
done();
}
);
});
it('externalId search for non existing event should return null', done => {
expect.assertions(1);
getCommunityEvent({}, { externalId: uuid() }, validContextForBrian).then(
data => {
expect(data).toBe(null);
done();
}
);
});
// function validateError(err) {
// expect(err).toBeInstanceOf(TypeError);
// expect(err.message).toContain('Expected a valid externalId or title');
// }
function getCommunityEventPromiseForTestCase(testCase) {
return getCommunityEvent(
{},
{ externalId: testCase },
validContextForBrian
).catch(err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
});
}
// TODO: DRY please
it('should throw if the externalId is not valid', done => {
expect.assertions(8);
Promise.all([
getCommunityEventPromiseForTestCase(1),
getCommunityEventPromiseForTestCase('abc'),
getCommunityEventPromiseForTestCase(['yeah nah']),
getCommunityEventPromiseForTestCase(false)
]).then(() => {
done();
});
});
it('should throw if the title is not valid', done => {
expect.assertions(6);
Promise.all([
getCommunityEvent({}, { title: 1 }, validContextForBrian).catch(err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
}),
getCommunityEvent(
{},
{ title: ['yeah nah'] },
validContextForBrian
).catch(err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
}),
getCommunityEvent({}, { title: false }, validContextForBrian).catch(
err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
}
)
]).then(() => {
done();
});
});
});
describe('getCommunityEvents', () => {
it('should return multiple Event objects for a valid request', done => {
expect.assertions(8);
getCommunityEvents({}, { title: 'epoch' }, validContextForBrian)
.then(result => {
const {
externalId,
title,
description,
owner,
date,
attendees
} = result[0];
// there is some weird Promise thing going on with `result`
// which screws with lodash.has()
const hasKeys =
!isEmpty(externalId) &&
!isEmpty(title) &&
!isEmpty(description) &&
!isEmpty(owner) &&
isDate(date) &&
isArray(attendees);
const hasOwnerKeys = !isEmpty(owner.name) && !isEmpty(owner.email);
const hasAttendeeKeys =
!isEmpty(attendees[0].name) && !isEmpty(attendees[0].email);
// TODO: 2 depend on other tests to create events for us,
// this is a bit brittle..
expect(result).toHaveLength(3);
expect(isObject(result)).toBe(true);
expect(isObject(owner)).toBe(true);
expect(isObject(attendees[0])).toBe(true);
expect(attendees).toHaveLength(2);
expect(hasKeys).toBe(true);
expect(hasOwnerKeys).toBe(true);
expect(hasAttendeeKeys).toBe(true);
return;
})
.then(done)
.catch(done);
});
it('title search non existing event should return null', done => {
expect.assertions(1);
getCommunityEvents({}, { title: 'Yeah nah' }, validContextForBrian).then(
data => {
expect(data).toBe(null);
done();
}
);
});
it('externalId search for non existing event should return null', done => {
expect.assertions(1);
getCommunityEvents({}, { externalId: uuid() }, validContextForBrian).then(
data => {
expect(data).toBe(null);
done();
}
);
});
// TODO: DRY please
it('should throw if the externalId is not valid', done => {
expect.assertions(8);
Promise.all([
getCommunityEvents({}, { externalId: 1 }, validContextForBrian).catch(
err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
}
),
getCommunityEvents({}, { externalId: 'abc' }, validContextForBrian).catch(
err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
}
),
getCommunityEvents(
{},
{ externalId: ['yeah nah'] },
validContextForBrian
).catch(err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
}),
getCommunityEvents({}, { externalId: false }, validContextForBrian).catch(
err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
}
)
]).then(() => {
done();
});
});
it('should throw if the title is not valid', done => {
expect.assertions(6);
Promise.all([
getCommunityEvents({}, { title: 1 }, validContextForBrian).catch(err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
}),
getCommunityEvents(
{},
{ title: ['yeah nah'] },
validContextForBrian
).catch(err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
}),
getCommunityEvents({}, { title: false }, validContextForBrian).catch(
err => {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toContain('Expected a valid externalId or title');
}
)
]).then(() => {
done();
});
});
});
describe('deleteCommunityEvent', () => {
it('should delete an existing event', async done => {
const event = {
title: 'deleteCommunityEvent event',
description: 'A boring test event',
date: 'Thu 1 Jan 1970 00:00:00'
};
const createdEvent = await createCommunityEvent(
{},
event,
validContextForBrian
);
const deletedEvent = await deleteCommunityEvent(
{},
{ externalId: createdEvent.externalId },
validContextForBrian
);
expect(createdEvent.externalId).toMatch(deletedEvent.externalId);
const foundEvent = await CommunityEvent.findOne({
externalId: deletedEvent.externalId
}).exec();
expect(foundEvent).toBe(null);
done();
});
it('should return with an error for a non existing event', async done => {
try {
await deleteCommunityEvent(
{},
{ externalId: uuid() },
validContextForBrian
);
} catch (err) {
expect(err).toBeInstanceOf(Error);
expect(err.message).toContain('Event not found');
expect(err).toMatchSnapshot();
}
done();
});
it('should refuse deletion of events owned by other users', async done => {
const e = await CommunityEvent.findOne({ title: 'epoch' }).exec();
try {
await deleteCommunityEvent(
{},
{ externalId: e.externalId },
validContextForKen
);
} catch (err) {
expect(err).toBeInstanceOf(Error);
expect(err.message).toContain('Only allowed to delete events you own');
expect(err).toMatchSnapshot();
}
done();
});
});
| kalidp/open-api |
<|start_filename|>govuk_frontend_jinja/templates/components/accordion/macro.html<|end_filename|>
{% macro govukAccordion(params) %}
{% set id = params.id %}
{% set headingLevel = params.headingLevel if params.headingLevel else 2 %}
<div class="govuk-accordion {%- if params.classes %} {{ params.classes }}{% endif -%}" data-module="govuk-accordion" id="{{ id }}"
{%- for attribute, value in (params.attributes.items() if params.attributes else {}.items()) %} {{attribute}}="{{value}}"{% endfor %}>
{% for item in params['items'] %}
{% if item %}
<div class="govuk-accordion__section {% if item.expanded %}govuk-accordion__section--expanded{% endif %}">
<div class="govuk-accordion__section-header">
<h{{ headingLevel }} class="govuk-accordion__section-heading">
<span class="govuk-accordion__section-button" id="{{ id }}-heading-{{ loop.index }}">
{{ item.heading.html | safe if item.heading.html else item.heading.text }}
</span>
</h{{ headingLevel }}>
{% if item.summary and (item.summary.html or item.summary.text) %}
<div class="govuk-accordion__section-summary govuk-body" id="{{ id }}-summary-{{ loop.index }}">
{{ item.summary.html | safe if item.summary.html else item.summary.text }}
</div>
{% endif %}
</div>
<div id="{{ id }}-content-{{ loop.index }}" class="govuk-accordion__section-content" aria-labelledby="{{ id }}-heading-{{ loop.index }}">
{{ item.content.html | safe if item.content.html else item.content.text }}
</div>
</div>
{% endif %}
{% endfor %}
</div>
{% endmacro %}
<|start_filename|>govuk_frontend_jinja/templates/components/tag/macro.html<|end_filename|>
{% macro govukTag(params) %}
<strong class="govuk-tag{% if params.classes %} {{ params.classes }}{% endif %}"{% for attribute, value in (params.attributes.items() if params.attributes else {}.items()) %} {{ attribute }}="{{ value }}"{% endfor %}>
{{ params.html | safe if params.html else params.text }}
</strong>
{% endmacro %}
<|start_filename|>govuk_frontend_jinja/templates/components/table/macro.html<|end_filename|>
{% macro govukTable(params) %}
<table class="govuk-table
{%- if params.classes %} {{ params.classes }}{% endif %}"{% for attribute, value in (params.attributes.items() if params.attributes else {}.items()) %} {{ attribute }}="{{ value }}"{% endfor %}>
{% if params.caption %}
<caption class="govuk-table__caption
{%- if params.captionClasses %} {{ params.captionClasses }}{% endif %}">{{ params.caption }}</caption>
{% endif %}
{% if params.head %}
<thead class="govuk-table__head">
<tr class="govuk-table__row">
{% for item in params.head %}
<th scope="col" class="govuk-table__header
{%- if item.format %} govuk-table__header--{{ item.format }}{% endif %}
{%- if item.classes %} {{ item.classes }}{% endif %}"
{%- if item.colspan %} colspan="{{ item.colspan }}"{% endif %}
{%- if item.rowspan %} rowspan="{{ item.rowspan }}"{% endif %}{% for attribute, value in (item.attributes.items() if item.attributes else {}.items()) %} {{ attribute }}="{{ value }}"{% endfor %}>{{ item.html |safe if item.html else item.text }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tbody class="govuk-table__body">
{% for row in params.rows %}
{% if row %}
<tr class="govuk-table__row">
{% for cell in row %}
{% set commonAttributes %}
{%- if cell.colspan %} colspan="{{ cell.colspan }}"{% endif %}
{%- if cell.rowspan %} rowspan="{{ cell.rowspan }}"{% endif %}{% for attribute, value in (cell.attributes.items() if cell.attributes else {}.items()) %} {{ attribute }}="{{ value }}"{% endfor %}
{% endset %}
{% if loop.first and params.firstCellIsHeader %}
<th scope="row" class="govuk-table__header{%- if cell.classes %} {{ cell.classes }}{% endif %}"
{{- commonAttributes | safe -}}
>{{ cell.html | safe if cell.html else cell.text }}</th>
{% else %}
<td class="govuk-table__cell
{%- if cell.format %} govuk-table__cell--{{ cell.format }}{% endif %}
{%- if cell.classes %} {{ cell.classes }}{% endif %}"
{{- commonAttributes | safe -}}
>{{ cell.html | safe if cell.html else cell.text }}</td>
{% endif %}
{% endfor %}
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
{% endmacro %}
<|start_filename|>govuk_frontend_jinja/templates/components/summary-list/macro.html<|end_filename|>
{% macro govukSummaryList(params) %}
{%- macro _actionLink(action) %}
<a class="govuk-link {%- if action.classes %} {{ action.classes }}{% endif %}" href="{{ action.href }}" {%- for attribute, value in (action.attributes.items() if action.attributes else {}.items()) %} {{attribute}}="{{value}}"{% endfor %}>
{{ action.html | safe if action.html else action.text }}
{%- if action.visuallyHiddenText -%}
<span class="govuk-visually-hidden"> {{ action.visuallyHiddenText }}</span>
{% endif -%}
</a>
{% endmacro -%}
{# Determine if we need 2 or 3 columns #}
{% set ns = namespace(anyRowHasActions=False) %}
{% for row in params.rows %}
{% set ns.anyRowHasActions = True if row.actions and row.actions['items'] | length else ns.anyRowHasActions %}
{% endfor -%}
<dl class="govuk-summary-list {%- if params.classes %} {{ params.classes }}{% endif %}"{% for attribute, value in (params.attributes.items() if params.attributes else {}.items()) %} {{attribute}}="{{value}}"{% endfor %}>
{% for row in params.rows %}
{% if row %}
<div class="govuk-summary-list__row {%- if row.classes %} {{ row.classes }}{% endif %}">
<dt class="govuk-summary-list__key {%- if row.key.classes %} {{ row.key.classes }}{% endif %}">
{{ row.key.html | safe if row.key.html else row.key.text }}
</dt>
<dd class="govuk-summary-list__value {%- if row.value.classes %} {{ row.value.classes }}{% endif %}">
{{ row.value.html | trim | safe if row.value.html else row.value.text }}
</dd>
{% if row.actions and row.actions['items'] | length %}
<dd class="govuk-summary-list__actions {%- if row.actions.classes %} {{ row.actions.classes }}{% endif %}">
{% if row.actions and row.actions['items'] | length == 1 %}
{{ _actionLink(row.actions['items'][0]) | trim }}
{% else %}
<ul class="govuk-summary-list__actions-list">
{% for action in row.actions['items'] %}
<li class="govuk-summary-list__actions-list-item">
{{ _actionLink(action) | trim }}
</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% elif ns.anyRowHasActions %}
{# Add dummy column to extend border #}
<span class="govuk-summary-list__actions"></span>
{% endif %}
</div>
{% endif %}
{% endfor %}
</dl>
{% endmacro %}
<|start_filename|>govuk_frontend_jinja/templates/components/warning-text/macro.html<|end_filename|>
{% macro govukWarningText(params) %}
<div class="govuk-warning-text {{- ' ' + params.classes if params.classes else ''}}"
{%- for attribute, value in (params.attributes.items() if params.attributes else {}.items()) %} {{attribute}}="{{value}}"{% endfor -%}
>
<span class="govuk-warning-text__icon" aria-hidden="true">!</span>
<strong class="govuk-warning-text__text">
<span class="govuk-warning-text__assistive">{{ params.iconFallbackText }}</span>
{{ params.html | safe if params.html else params.text }}
</strong>
</div>
{% endmacro %}
| andymantell/govuk-frontend-jinja |
<|start_filename|>app/src/main/java/ru/semper_viventem/pixel4scanner/libs/renderer/OnTouchEventListener.java<|end_filename|>
package ru.semper_viventem.pixel4scanner.libs.renderer;
import android.view.MotionEvent;
public interface OnTouchEventListener {
void onTouchEvent(MotionEvent motionEvent, float f, float f2);
}
<|start_filename|>app/src/main/java/ru/semper_viventem/pixel4scanner/ultradepth/apps/frame/Frame.java<|end_filename|>
package ru.semper_viventem.pixel4scanner.ultradepth.apps.frame;
import android.media.Image;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
public class Frame {
private volatile boolean closed;
private final short[] depth16Data;
private final int depth16Height;
private final int depth16Width;
private long timestamp = 0;
private final byte[] yuvData;
private final int yuvHeight;
private final int yuvWidth;
public int getYuvWidth() {
return this.yuvWidth;
}
public int getYuvHeight() {
return this.yuvHeight;
}
public byte[] getYuvData() {
return this.yuvData;
}
public int getDepth16Width() {
return this.depth16Width;
}
public int getDepth16Height() {
return this.depth16Height;
}
public short[] getDepth16Data() {
return this.depth16Data;
}
public void close() {
this.closed = true;
}
Frame(int yuvWidth2, int yuvHeight2, int depth16Width2, int depth16Height2) {
this.yuvWidth = yuvWidth2;
this.yuvHeight = yuvHeight2;
this.yuvData = new byte[(yuvWidth2 * yuvHeight2 * 3)];
this.depth16Width = depth16Width2;
this.depth16Height = depth16Height2;
this.depth16Data = new short[(depth16Width2 * depth16Height2)];
this.closed = true;
}
/* access modifiers changed from: 0000 */
public void packYuvData(Image yuvImage) {
ByteBuffer yBuffer = yuvImage.getPlanes()[0].getBuffer();
ByteBuffer uBuffer = yuvImage.getPlanes()[1].getBuffer();
ByteBuffer vBuffer = yuvImage.getPlanes()[2].getBuffer();
int yRowStride = yuvImage.getPlanes()[0].getRowStride();
int uvRowStride = yuvImage.getPlanes()[1].getRowStride();
int uvPixelStride = yuvImage.getPlanes()[1].getPixelStride();
for (int y = 0; y < this.yuvHeight; y++) {
int yRow = yRowStride * y;
int uvRow = (y >> 1) * uvRowStride;
int yuvRow = this.yuvWidth * y;
int x = 0;
while (x < this.yuvWidth) {
int uvPixel = ((x >> 1) * uvPixelStride) + uvRow;
int yuvPixel = yuvRow + x;
this.yuvData[yuvPixel] = yBuffer.get(yRow + x);
ByteBuffer yBuffer2 = yBuffer;
int yRowStride2 = yRowStride;
this.yuvData[(this.yuvWidth * this.yuvHeight) + yuvPixel] = uBuffer.get(uvPixel);
this.yuvData[(this.yuvWidth * this.yuvHeight * 2) + yuvPixel] = vBuffer.get(uvPixel);
x++;
yBuffer = yBuffer2;
yRowStride = yRowStride2;
}
int i = yRowStride;
}
}
/* access modifiers changed from: 0000 */
public void packDepth16Data(Image depth16Image) {
ShortBuffer depth16Buffer = depth16Image.getPlanes()[0].getBuffer().asShortBuffer();
for (int y = 0; y < this.depth16Height; y++) {
int depth16Row = this.depth16Width * y;
for (int x = 0; x < this.depth16Width; x++) {
int depth16Pixel = depth16Row + x;
this.depth16Data[depth16Pixel] = depth16Buffer.get(depth16Pixel);
}
}
}
/* access modifiers changed from: 0000 */
public long getTimestamp() {
return this.timestamp;
}
/* access modifiers changed from: 0000 */
public void setTimestamp(long timestamp2) {
this.timestamp = timestamp2;
}
/* access modifiers changed from: 0000 */
public boolean isClosed() {
return this.closed;
}
/* access modifiers changed from: 0000 */
public void open() {
this.closed = false;
}
}
<|start_filename|>app/src/main/java/ru/semper_viventem/pixel4scanner/libs/renderer/DefaultRenderConfiguration.java<|end_filename|>
package ru.semper_viventem.pixel4scanner.libs.renderer;
public class DefaultRenderConfiguration {
public static final int IMAGE_HEIGHT = 480;
public static final int IMAGE_WIDTH = 640;
}
<|start_filename|>app/src/main/java/ru/semper_viventem/pixel4scanner/LicenseActivity.kt<|end_filename|>
package ru.semper_viventem.pixel4scanner
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
private const val LICENSE = """
Google uDepth demo project
AndroidX activity library
AndroidX animated vectordrawable library
AndroidX annotation library
AndroidX appcompat library
AndroidX asynclayoutinflater library
AndroidX concurrent futures library
AndroidX core library
AndroidX documentfile library
AndroidX fragment library
AndroidX legacy coreui library
AndroidX legacy v4 library
AndroidX print library
AndroidX savedstate library
AndroidX slidingpanelayout library
AndroidX swiperefreshlayout library
AndroidX v7 library
AndroidX vectordrawable base library
AndroidX viewpager library
AndroidX architecture core library
AndroidX architecture library
AndroidX lifecycle base library
AndroidX lifecycle common library
AndroidX lifecycle livedatacore library
AndroidX lifecycle runtime library
AndroidX lifecycle viewmodel savedstate library
AndroidX collection library
AndroidX coordinatorlayout library
AndroidX cursoradapter library
AndroidX customview library
AndroidX drawerlayout library
AndroidX interpolator library
AndroidX loader library
AndroidX localbroadcastmanager library
AndroidX legacy coreutils library
AndroidX media base library
AndroidX versionedparcelable library
Animal Sniffer
Checker Framework Annotations
Error Prone
Guava JDK5
J2ObjC
Guava JDK7
JSR 305
"""
class LicenseActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val text = TextView(this).apply {
layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT).apply {
val gap = resources.getDimensionPixelSize(R.dimen.big_gap)
setMargins(gap, gap, gap, gap)
}
text = LICENSE
}
val backButton = ImageView(this).apply {
layoutParams = FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
val gap = resources.getDimensionPixelSize(R.dimen.normal_gap)
setPadding(gap, gap, gap, gap)
setImageResource(R.drawable.ic_arrow_back)
setOnClickListener { finish() }
}
val container = FrameLayout(this).apply {
layoutParams = ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)
addView(text)
addView(backButton)
}
setContentView(container)
}
companion object {
fun getInstance(context: Context) = Intent(context, LicenseActivity::class.java)
}
}
<|start_filename|>app/src/main/java/ru/semper_viventem/pixel4scanner/libs/renderer/PointCloudRenderer.java<|end_filename|>
package ru.semper_viventem.pixel4scanner.libs.renderer;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLU;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class PointCloudRenderer implements Renderer {
private static final float FAR_DISTANCE = 10.0f;
private static final float NEAR_DISTANCE = 0.1f;
private final Object bufferLock = new Object();
private FloatBuffer colorBuffer;
private float height = 1.0f;
private float[] points0;
private float[] points1;
private float renderScale = 1.0f;
private Config rendererConfig = new Config();
private boolean rotationLocked = false;
private boolean useBackBuffer = false;
private FloatBuffer vertexBuffer;
private float width = 1.0f;
private boolean inMotion = false;
private float lastX = 0.5f;
private float lastY = 0.5f;
private float xAngle = 0.5f;
private float yAngle = 0.5f;
public static class Config {
public float imageHeight = 480.0f;
public float imageWidth = 640.0f;
public float maxDepth = 0.8f;
public float minDepth = 0.3f;
public boolean showPictureInPicture = true;
public float viewportScale = 0.25f;
}
public void setDepthProperties(Config config) {
this.rendererConfig = config;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
synchronized (this.bufferLock) {
this.width = (float) w;
this.height = (float) h;
}
}
public void onDrawFrame(GL10 gl) {
boolean useBackBufferLocal;
float xAngle;
float yAngle;
float[] points;
synchronized (this.bufferLock) {
useBackBufferLocal = this.useBackBuffer;
xAngle = this.xAngle;
yAngle = this.yAngle;
}
if (useBackBufferLocal) {
points = this.points1;
} else {
points = this.points0;
}
if (points != null) {
int numPoints = points.length / 7;
if (numPoints > 0) {
setupVertexAndColorBuffers(points, numPoints);
drawMain3dView(gl, xAngle, yAngle, numPoints);
if (this.rendererConfig.showPictureInPicture) {
drawPictureInPicture(gl, numPoints);
}
}
}
}
public void setPoints(float[] points) {
boolean useBackBufferLocal;
synchronized (this.bufferLock) {
useBackBufferLocal = this.useBackBuffer;
this.useBackBuffer = !this.useBackBuffer;
}
if (useBackBufferLocal) {
this.points0 = points;
} else {
this.points1 = points;
}
}
public void startMotion(float x, float y) {
inMotion = true;
lastX = x / width;
lastY = y / height;
}
public void stopMotion() {
inMotion = false;
lastX = 0.0f;
lastY = 0.0f;
}
public void setTouchPoint(float x, float y) {
if (!this.rotationLocked && inMotion) {
float newX = x / width;
float newY = y / height;
float dX = lastX - newX;
float dY = lastY - newY;
xAngle -= dX;
yAngle -= dY;
lastX = newX;
lastY = newY;
}
}
public void setScale(float scale) {
synchronized (this.bufferLock) {
if (!this.rotationLocked) {
this.renderScale = scale;
}
}
}
public void resetAndLockOrientation() {
synchronized (this.bufferLock) {
this.xAngle = 0.5f;
this.yAngle = 0.5f;
this.renderScale = 1.0f;
this.rotationLocked = true;
}
}
public void unlockOrientation() {
this.rotationLocked = false;
}
private void setupCanonicalDepthSpace(GL10 gl) {
gl.glMatrixMode(5888);
gl.glLoadIdentity();
gl.glTranslatef(-0.05f, -0.05f, 0.0f);
gl.glScalef(1.0f, 1.0f, -1.0f);
gl.glRotatef(-90.0f, 0.0f, 0.0f, 1.0f);
}
private void rotateModelViewByTouchPoint(GL10 gl, float xAngle, float yAngle) {
gl.glMatrixMode(5888);
float centeredDisp = (this.rendererConfig.minDepth + this.rendererConfig.maxDepth) * 0.5f;
gl.glTranslatef(0.0f, 0.0f, centeredDisp);
gl.glRotatef((xAngle * 180.0f) - 90.0f, 1.0f, 0.0f, 0.0f);
gl.glRotatef((180.0f * yAngle) - 90.0f, 0.0f, 1.0f, 0.0f);
gl.glTranslatef(0.0f, 0.0f, -centeredDisp);
}
private void setupVertexAndColorBuffers(float[] points, int numPoints) {
ByteBuffer pointBytes = ByteBuffer.allocateDirect(numPoints * 32 * 7);
pointBytes.order(ByteOrder.nativeOrder());
FloatBuffer asFloatBuffer = pointBytes.asFloatBuffer();
this.vertexBuffer = asFloatBuffer;
asFloatBuffer.put(points, 0, numPoints * 7);
this.vertexBuffer.position(0);
FloatBuffer duplicate = this.vertexBuffer.duplicate();
this.colorBuffer = duplicate;
duplicate.position(3);
}
private void drawPointCloud(GL10 gl, int numPoints) {
gl.glEnableClientState(32884);
gl.glVertexPointer(3, 5126, 28, this.vertexBuffer);
gl.glEnableClientState(32886);
gl.glColorPointer(4, 5126, 28, this.colorBuffer);
gl.glDrawArrays(0, 0, numPoints);
gl.glDisableClientState(32886);
gl.glDisableClientState(32884);
}
private void drawMain3dView(GL10 gl, float xAngle, float yAngle, int numPoints) {
gl.glViewport(0, 0, (int) this.width, (int) this.height);
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
gl.glClear(16640);
gl.glEnable(2929);
gl.glMatrixMode(5889);
gl.glLoadIdentity();
gl.glScalef(1.0f, -1.0f, 1.0f);
GLU.gluPerspective(gl, 55.0f / this.renderScale, this.width / this.height, NEAR_DISTANCE, FAR_DISTANCE);
setupCanonicalDepthSpace(gl);
rotateModelViewByTouchPoint(gl, xAngle, yAngle);
gl.glPointSize(this.renderScale * 4.0f);
drawPointCloud(gl, numPoints);
}
private void drawPictureInPicture(GL10 gl, int numPoints) {
int pipWidth = (int) (this.width * this.rendererConfig.viewportScale);
int pipHeight = (int) (((float) pipWidth) * (this.rendererConfig.imageWidth / this.rendererConfig.imageHeight));
gl.glViewport(0, 0, pipWidth, pipHeight);
gl.glScissor(0, 0, pipWidth, pipHeight);
gl.glEnable(3089);
gl.glClearColor(NEAR_DISTANCE, NEAR_DISTANCE, NEAR_DISTANCE, 1.0f);
gl.glClear(16640);
gl.glMatrixMode(5889);
gl.glLoadIdentity();
gl.glScalef(1.0f, -1.0f, 1.0f);
GLU.gluPerspective(gl, 55.0f, ((float) pipWidth) / ((float) pipHeight), NEAR_DISTANCE, FAR_DISTANCE);
setupCanonicalDepthSpace(gl);
gl.glPointSize(2.0f);
drawPointCloud(gl, numPoints);
gl.glDisable(3089);
}
}
<|start_filename|>app/src/main/java/ru/semper_viventem/pixel4scanner/ultradepth/apps/frame/FrameReader.java<|end_filename|>
package ru.semper_viventem.pixel4scanner.ultradepth.apps.frame;
import android.media.Image;
public class FrameReader {
private final int frameCount;
private volatile int frameIndex;
private final Frame[] frames;
private OnFrameAvailableListener onFrameAvailableListener = null;
public interface OnFrameAvailableListener {
void onFrameAvailable(FrameReader frameReader);
}
public static FrameReader newInstance(int yuvWidth, int yuvHeight, int depth16Width, int depth16Height, int maxFrames) {
try {
return new FrameReader(yuvWidth, yuvHeight, depth16Width, depth16Height, maxFrames);
} catch (IllegalStateException e) {
return null;
}
}
public void setOnFrameAvailableListener(OnFrameAvailableListener listener) {
this.onFrameAvailableListener = listener;
}
public void onDepth16ImageAvailable(Image depth16Image) {
if (this.frames[this.frameIndex].getTimestamp() <= depth16Image.getTimestamp()) {
this.frames[this.frameIndex].packDepth16Data(depth16Image);
onImageAvailable(depth16Image.getTimestamp());
}
}
public void onYuvImageAvailable(Image yuvImage) {
if (this.frames[this.frameIndex].getTimestamp() <= yuvImage.getTimestamp()) {
this.frames[this.frameIndex].packYuvData(yuvImage);
onImageAvailable(yuvImage.getTimestamp());
}
}
private void onImageAvailable(long timestamp) {
int index = this.frameIndex;
if (this.frames[index].getTimestamp() != timestamp) {
this.frames[index].setTimestamp(timestamp);
return;
}
this.frames[index].open();
int nextFrameIndex = (index + 1) % this.frameCount;
if (this.frames[nextFrameIndex].isClosed()) {
this.frameIndex = nextFrameIndex;
}
OnFrameAvailableListener onFrameAvailableListener2 = this.onFrameAvailableListener;
if (onFrameAvailableListener2 != null) {
onFrameAvailableListener2.onFrameAvailable(this);
}
}
public Frame acquireLatestFrame() {
int prevFrameIndex = this.frameIndex - 1;
if (prevFrameIndex < 0) {
prevFrameIndex += this.frameCount;
}
if (this.frames[prevFrameIndex].isClosed()) {
return null;
}
return this.frames[prevFrameIndex];
}
private FrameReader(int yuvWidth, int yuvHeight, int depth16Width, int depth16Height, int maxFrames) {
if (maxFrames > 0) {
int i = maxFrames + 2;
this.frameCount = i;
this.frames = new Frame[i];
for (int i2 = 0; i2 < this.frameCount; i2++) {
this.frames[i2] = new Frame(yuvWidth, yuvHeight, depth16Width, depth16Height);
}
this.frameIndex = 0;
return;
}
throw new IllegalStateException("Invalid parameters for FrameReader");
}
}
<|start_filename|>app/src/main/java/ru/semper_viventem/pixel4scanner/libs/renderer/PointCloudRendererView.java<|end_filename|>
package ru.semper_viventem.pixel4scanner.libs.renderer;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;
import ru.semper_viventem.pixel4scanner.libs.renderer.PointCloudRenderer.Config;
public class PointCloudRendererView extends GLSurfaceView {
PointCloudRenderer renderer;
ScaleGestureDetector scaleListener = null;
OnTouchEventListener touchListener = null;
protected static class ScaleListener extends SimpleOnScaleGestureListener {
private final PointCloudRenderer renderer;
private float scale = 1.0f;
ScaleListener(PointCloudRenderer rendererIn) {
this.renderer = rendererIn;
}
public boolean onScale(ScaleGestureDetector detector) {
float scaleFactor = this.scale * detector.getScaleFactor();
this.scale = scaleFactor;
float min = Math.min(Math.max(0.5f, scaleFactor), 4.0f);
this.scale = min;
this.renderer.setScale(min);
return true;
}
}
public PointCloudRendererView(Context context) {
super(context);
PointCloudRenderer pointCloudRenderer = new PointCloudRenderer();
this.renderer = pointCloudRenderer;
setRenderer(pointCloudRenderer);
this.scaleListener = new ScaleGestureDetector(context, new ScaleListener(this.renderer));
}
public PointCloudRendererView(Context context, AttributeSet attrs) {
super(context, attrs);
PointCloudRenderer pointCloudRenderer = new PointCloudRenderer();
this.renderer = pointCloudRenderer;
setRenderer(pointCloudRenderer);
this.scaleListener = new ScaleGestureDetector(context, new ScaleListener(this.renderer));
}
public void setDepthProperties(Config config) {
this.renderer.setDepthProperties(config);
}
public boolean onTouchEvent(final MotionEvent event) {
queueEvent(() -> {
scaleListener.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_DOWN && !scaleListener.isInProgress()) {
renderer.startMotion(event.getRawX(), event.getRawY());
}
if (event.getAction() == MotionEvent.ACTION_UP && !scaleListener.isInProgress()) {
renderer.stopMotion();
}
if (event.getAction() == MotionEvent.ACTION_MOVE && !scaleListener.isInProgress()) {
renderer.setTouchPoint(event.getRawX(), event.getRawY());
}
if (touchListener != null && !scaleListener.isInProgress()) {
OnTouchEventListener onTouchEventListener = touchListener;
MotionEvent motionEvent = event;
onTouchEventListener.onTouchEvent(motionEvent, motionEvent.getX(), event.getY());
}
});
return true;
}
public void setPoints(float[] points) {
this.renderer.setPoints(points);
}
public void setCaptureMode(boolean lockRotationLocal) {
if (lockRotationLocal) {
this.renderer.resetAndLockOrientation();
} else {
this.renderer.unlockOrientation();
}
}
public void registerOnTouchEventListener(OnTouchEventListener listener) {
this.touchListener = listener;
}
}
| Semper-Viventem/PixelScanner |
<|start_filename|>fluid-simulator/src/com/fluidsimulator/utils/Vector2.java<|end_filename|>
package com.fluidsimulator.utils;
public class Vector2 extends com.badlogic.gdx.math.Vector2 {
private static final long serialVersionUID = -1049661215629475906L;
public Vector2 () {
}
public Vector2 (float x, float y) {
this.x = x;
this.y = y;
}
public Vector2 (Vector2 v) {
set(v);
}
public float Length() {
float length = x * x + y * y;
return (float) Math.sqrt(length);
}
public float LengthSquare(){
return x * x + y * y;
}
public static Vector2 Normalize(Vector2 vec){
float length = vec.Length();
if(length != 0){
return new Vector2(vec.x / length, vec.y / length);
}else{
return vec;
}
}
public static Vector2 Multiply(Vector2 vec, float coe) {
return new Vector2(vec.x * coe, vec.y * coe);
}
public static Vector2 Add(Vector2 a, Vector2 b) {
return new Vector2(a.x + b.x, a.y + b.y);
}
public static Vector2 Substract(Vector2 a, Vector2 b) {
return new Vector2(a.x - b.x, a.y - b.y);
}
public static float DotProduct(Vector2 a, Vector2 b) {
float product = a.x * b.x + a.y * b.y;
return product;
}
public static Vector2 Scale(Vector2 vec, float scale){
return new Vector2(vec.x * scale, vec.y * scale);
}
public void Add(Vector2 vec){
this.x += vec.x;
this.y += vec.y;
}
public void Substract(Vector2 vec){
this.x -= vec.x;
this.y -= vec.y;
}
public void Scale(float scale){
this.x *= scale;
this.y *= scale;
}
}
<|start_filename|>fluid-simulator-android/assets/data/default1.vert<|end_filename|>
attribute vec4 a_position;
attribute vec4 a_color;
varying vec4 v_color;
void main() {
v_color = a_color;
gl_Position = a_position;
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/Camera3DController.java<|end_filename|>
package com.fluidsimulator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.MathUtils;
public class Camera3DController extends CameraInputController {
private int touched;
private boolean multiTouch;
private FluidSimulatorGeneric simulator;
public Camera3DController(final Camera camera) {
super(camera);
}
protected Camera3DController(final CameraGestureListener gestureListener, final Camera camera) {
super(gestureListener, camera);
}
public void setFluidSimulator(FluidSimulatorGeneric simulator) {
this.simulator = simulator;
}
@Override
public boolean keyUp (int keycode) {
boolean toReturn = super.keyUp(keycode);
if (keycode == Keys.C) {
Gdx.input.setInputProcessor(simulator);
simulator.camera3D.position.set(0, 130f, 250f);
simulator.camera3D.lookAt(0,150f,0);
simulator.camera3D.near = 0.1f;
simulator.camera3D.far = 300f;
update();
}
return toReturn;
}
@Override
public boolean touchDown (int screenX, int screenY, int pointer, int button) {
boolean toReturn = super.touchDown(screenX, screenY, pointer, button);
touched |= (1 << pointer);
multiTouch = !MathUtils.isPowerOfTwo(touched);
if (multiTouch) {
// Gdx.input.setInputProcessor(simulator);
}
return toReturn;
}
@Override
public boolean touchUp (int screenX, int screenY, int pointer, int button) {
boolean toReturn = super.touchUp(screenX, screenY, pointer, button);
touched &= -1 ^ (1 << pointer);
multiTouch = !MathUtils.isPowerOfTwo(touched);
return toReturn;
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/gameobjects/fluid/SpatialTable.java<|end_filename|>
package com.fluidsimulator.gameobjects.fluid;
import java.util.ArrayList;
import java.util.Iterator;
import com.fluidsimulator.FluidSimulatorGeneric;
abstract public class SpatialTable<V> implements Iterable<V> {
/** default nearby table sizes
*
* These two variables can be tweaked to affect the accuracy
* and performance of PBF and SPH neighbors search
*/
public int MAX_NEIGHBORS = FluidSimulatorGeneric.IS_DESKTOP ? 300 : 300;
public int MAX_NEIGHBORS2 = FluidSimulatorGeneric.IS_DESKTOP ? 300 : 300;
// the actual spatial table
public final ArrayList<V> table;
// a void list initialized here for reuse
private ArrayList<V> voidList = new ArrayList<V>(1);
// the nearby elements table
// private FastMap<Integer, ArrayList<V>> nearby;
private ArrayList<V>[][] nearby;
// row and column of the spatial table
private int row;
private int column;
// temporary variables for faster iterations and optimized object allocations
private int i;
private int j;
private int tempSize;
private int z;
private int x;
private int y;
private int x2;
private int y2;
private int xPrev;
private int yPrev;
private int xPrev2;
private int yPrev2;
// abstract position variables must be implemented on actual class instantiation
abstract protected int posX(V value);
abstract protected int posY(V value);
abstract protected int prevPosX(V value);
abstract protected int prevPosY(V value);
abstract protected void setPrevGridPos(V value, int x, int y);
abstract protected int getPrevGridPosX(V value);
abstract protected int getPrevGridPosY(V value);
abstract protected void savePosX(V value, int x);
abstract protected void savePosY(V value, int y);
abstract protected int getPosX(V value);
abstract protected int getPosY(V value);
abstract protected int getHash(V value);
@SuppressWarnings("unchecked")
public SpatialTable(int column, int row, int size) {
this.row = row;
this.column = column;
table = new ArrayList<V>(size);
nearby = new ArrayList[column][row];
}
/**
* Initialize the nearby table to the default size
*/
public void initialize() {
for (i = 0; i < column; ++i) {
for (j = 0; j < row; ++j) {
nearby[i][j] = new ArrayList<V>(MAX_NEIGHBORS2);
}
}
}
public boolean add(V value) {
addInCell(value);
table.add(value);
return true;
}
public Iterator<V> iterator() {
return table.iterator();
}
public V get(int i) {
return table.get(i);
}
public boolean remove(V value) {
table.remove(value);
return true;
}
public void clear() {
for (i = 0; i < column; ++i) {
for (j = 0; j < row; ++j) {
nearby[i][j].clear();
nearby[i][j] = null;
}
}
table.clear();
}
/**
* Clear only neighbors map
*/
public void clearNeighbors() {
for (i=0; i<column; i++) {
for (j=0; j<row; j++) {
if (nearby[i][j] != null) {
nearby[i][j].clear();
}
}
}
}
public int size() {
return table.size();
}
/**
* Returns an array of neighbors for the provided central object
*/
public ArrayList<V> nearby(V value) {
x = getPosX(value);
y = getPosY(value);
if (!isInRange(x, y))
return voidList;
return nearby[x][y];
}
/**
* Update position for an item
*/
public void updatePosition(V value) {
x = getPosX(value);
y = getPosY(value);
xPrev = getPrevGridPosX(value);
yPrev = getPrevGridPosY(value);
setPrevGridPos(value, x, y);
for (i = -1; i < 2; ++i) {
for (j = -1; j < 2; ++j) {
xPrev2 = xPrev+i;
yPrev2 = yPrev+j;
x2 = x+i;
y2 = y+j;
if (isInRange(xPrev2, yPrev2))
nearby[xPrev2][yPrev2].remove(value);
if (isInRange(x2, y2) && nearby[x2][y2].size() < MAX_NEIGHBORS2)
nearby[x2][y2].add(value);
}
}
}
public int sizeNearby(V value) {
return nearby(value).size();
}
/**
* Updates the spatial table based on new values position
*/
public void rehash() {
clearNeighbors();
tempSize = table.size();
for (z=0; z<tempSize; z++) {
addInCell(table.get(z));
}
}
/**
* Add element to its position and neighbor cells.
*/
private void addInCell(V value) {
x = posX(value);
y = posY(value);
savePosX(value, x);
savePosY(value, y);
for (i = -1; i < 2; ++i) {
for (j = -1; j < 2; ++j) {
x2 = x+i;
y2 = y+j;
// x2 = x;
// y2 = y;
if (isInRange(x2, y2)/* && nearby[x2][y2].size() < MAX_NEIGHBORS2*/) {
nearby[x2][y2].add(value);
// if (nearby[x2][y2].size() > 50)
// System.out.println(nearby[x2][y2].size());
}
}
}
}
private boolean isInRange(float x, float y) {
return (x >= 0 && x < column && y >= 0 && y < row);
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/CameraGestureListener.java<|end_filename|>
package com.fluidsimulator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.input.GestureDetector.GestureAdapter;
public class CameraGestureListener extends GestureAdapter {
public CameraInputController controller;
private float previousZoom;
@Override
public boolean touchDown (float x, float y, int pointer, int button) {
previousZoom = 0;
return false;
}
@Override
public boolean tap (float x, float y, int count, int button) {
return false;
}
@Override
public boolean longPress (float x, float y) {
return false;
}
@Override
public boolean fling (float velocityX, float velocityY, int button) {
return false;
}
@Override
public boolean pan (float x, float y, float deltaX, float deltaY) {
return false;
}
@Override
public boolean zoom (float initialDistance, float distance) {
float newZoom = distance - initialDistance;
float amount = newZoom - previousZoom;
previousZoom = newZoom;
float w = Gdx.graphics.getWidth(), h = Gdx.graphics.getHeight();
return controller.zoom(amount / ((w > h) ? h : w));
}
};
<|start_filename|>fluid-simulator/src/com/fluidsimulator/pbf/Box.java<|end_filename|>
package com.fluidsimulator.pbf;
import com.badlogic.gdx.math.Vector2;
public class Box {
private float left;
private float right;
private float top;
private float bottom;
public Box(float left, float right, float bottom, float top) {
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
}
public boolean isInBox(Vector2 position) {
if (position.x < left || position.x > right)
return false;
if (position.y < bottom || position.y > top)
return false;
return true;
}
public void forceInsideBox(Vector2 position, Vector2 velocity) {
float padding = 0.01f;
if (position.x < left + padding) {
position.x = left + padding;
if (velocity != null && velocity.x < 0)
velocity.x *= -0.5f;
// velocity.x = 0;
}
if (position.x > right - padding) {
position.x = right - padding;
if (velocity != null && velocity.x > 0)
velocity.x *= -0.5f;
// velocity.x = 0;
}
if (position.y < bottom + padding) {
position.y = bottom + padding;
if (velocity != null && velocity.y < 0)
velocity.y *= -0.5f;
// velocity.y = 0;
}
if (position.y > top - padding) {
position.y = top - padding;
if (velocity != null && velocity.y > 0)
velocity.y *= -0.5f;
// velocity.y = 0;
}
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/utils/Vector3.java<|end_filename|>
package com.fluidsimulator.utils;
public class Vector3 extends com.badlogic.gdx.math.Vector3 {
private static final long serialVersionUID = 1788027793834557077L;
public Vector3 () {
}
public Vector3 (float x, float y, float z) {
this.set(x, y, z);
}
public Vector3 (final Vector3 vector) {
this.set(vector);
}
public float Length() {
float length = x * x + y * y + z * z;
return (float) Math.sqrt(length);
}
public float LengthSquare(){
return x * x + y * y + z * z;
}
public static Vector3 Normalize(Vector3 vec){
float length = vec.Length();
if(length != 0){
return new Vector3(vec.x / length, vec.y / length, vec.z / length);
}else{
return vec;
}
}
public static Vector3 Multiply(Vector3 vec, float coe) {
return new Vector3(vec.x * coe, vec.y * coe, vec.z * coe);
}
public static Vector3 Add(Vector3 a, Vector3 b) {
return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
}
public static Vector3 Substract(Vector3 a, Vector3 b) {
return new Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
}
public static float DotProduct(Vector3 a, Vector3 b) {
float product = a.x * b.x + a.y * b.y + a.z * b.z;
return product;
}
public static Vector3 Scale(Vector3 vec, float scale){
return new Vector3(vec.x * scale, vec.y * scale, vec.z * scale);
}
public void Add(Vector3 vec){
this.x += vec.x;
this.y += vec.y;
this.z += vec.z;
}
public void Substract(Vector3 vec){
this.x -= vec.x;
this.y -= vec.y;
this.z -= vec.z;
}
public void Scale(float scale){
this.x *= scale;
this.y *= scale;
this.z *= scale;
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/FluidSimulatorGeneric.java<|end_filename|>
package com.fluidsimulator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import javolution.util.FastMap;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.QueryCallback;
import com.badlogic.gdx.physics.box2d.RayCastCallback;
import com.badlogic.gdx.physics.box2d.Shape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.joints.MouseJoint;
import com.fluidsimulator.gameobjects.ObjectInfo;
import com.fluidsimulator.gameobjects.Particle;
import com.fluidsimulator.gameobjects.Piece;
import com.fluidsimulator.gameobjects.Portal;
import com.fluidsimulator.gameobjects.Spring;
import com.fluidsimulator.utils.Vector2;
/**
* This class is used as a generic simulation class containing common code.
* Due to the experimental nature of the project, there is still redundant code
* in the subclasses
*/
public class FluidSimulatorGeneric implements Screen, InputProcessor, ContactListener {
public static final boolean IS_DESKTOP = true;
public boolean DEBUG_ENABLED = false;
// FPS Management
private final float FIXED_DELTA_BOX2D = 1.0f / 30.0f;
public int speedCounter;
public float lastDeltaTime;
public float timeStep;
public float timeStep2;
public float interpolation;
public float nextGameTick;
public float nextGameTick2;
public boolean stepped;
public int loops;
public int loops2;
public long time;
// Tune these statics for platform specific behaviors
public final int SIZE = 5460;
public final int ANDROID_SIZE = 600;
public final float EPSILON = 1.1920928955078125E-7f;
public final float LINE_VELOCITY_FACTOR = IS_DESKTOP ? 0.03f : 0.03f;
public final float LINE_DENSITY_FACTOR = IS_DESKTOP ? 0.2f : 0.2f;
public final int WORLD_WIDTH = IS_DESKTOP ? 480 : 240;
public final int WORLD_HEIGHT = IS_DESKTOP ? 320 : 180;
// Box properties can be set by specific simulations like MPM
public int BOX_WIDTH = IS_DESKTOP ? 480 : 240;
public int BOX_HEIGHT = IS_DESKTOP ? 320 : 180;
public int BOX_WIDTH_HALF = BOX_WIDTH / 2;
public int BOX_HEIGHT_HALF = BOX_HEIGHT / 2;
public final int INITIAL_HEIGHT = IS_DESKTOP ? 10 : 10;
public final float TIMESTEP = 0.022f;
public final float COLLISION_FORCE = IS_DESKTOP ? 0.05f : 0.05f;
public final float RIGID_FLUID_COLLISION_FORCE = IS_DESKTOP ? 0.1f : 0.1f;
public final int wpadding = IS_DESKTOP ? 10 : 10;
public final int hpadding = IS_DESKTOP ? 10 : 10;
public int prevHash = 1;
// Particles arrays and spatial table
public Particle[] particleArray = new Particle[IS_DESKTOP ? SIZE : ANDROID_SIZE];
public final ArrayList<Particle> drawParticles = new ArrayList<Particle>();
// Generic Framework objects and flags
public FluidSimulatorStarter game;
public GL20 gl = null;
public boolean firstRender;
public SpriteBatch batch;
public BitmapFont font;
public OrthographicCamera camera;
public ShaderProgram defaultShader;
public ShaderProgram refractionShader;
public ShaderProgram defaultIMShader;
public Texture bgTexture;
public Sprite bgSprite;
public Texture glossMapTexture;
public Texture displacementMap;
public Texture displacementMap2;
public ImmediateModeRenderer20 immediateRenderer;
public ImmediateModeRenderer20 irt2;
public Renderer20 irt;
public ShapeRenderer shapeRenderer;
public boolean touching;
public Random rnd = new Random();
public Object fluidLock = new Object();
public boolean multitouch;
public int touched;
public boolean exitApp;
//3D - only used as an alternative rendering mode for the 2D simulation, because it's cool :)
public PerspectiveCamera camera3D;
public Environment environment;
public ModelBatch modelBatch;
public Model model;
public ModelInstance instance;
public Camera3DController camController;
/** Pieces and portals are a utility developed for The Balance Game project available
* on my Github https://github.com/omgware
* They work perfectly fine with fluids too, might just need few modifications **/
public ArrayList<Piece> pieceTemplates = new ArrayList<Piece>();
public HashMap<Integer, Piece> pieces = new HashMap<Integer, Piece>();
public ArrayList<Portal> portalIn = new ArrayList<Portal>();
public ArrayList<Portal> portalOut = new ArrayList<Portal>();
public final float PORTAL_FORCE_OUT = 200;
// Box2D elements
public Box2DDebugRenderer renderer;
public World world;
public int prevPieceHash = 1;
public BodyDef def = new BodyDef();
public FixtureDef fd = new FixtureDef();
public Fixture tempFixture = null;
public Piece newPiece;
public Piece newPiece2;
public Body logicHitBody = null;
public boolean allowPortalTransferForce = true;
public boolean allowOutOfWorldDestruction;
public Vector2 vec1 = new Vector2();
public Vector2 vec2 = new Vector2();
public Vector2 vec3 = new Vector2();
public Vector2 vec4 = new Vector2();
public Vector2 bodyCollisionImpulse = new Vector2();
public Particle hitParticle;
// Box2D/Fluid collision
public Vector2 collisionPoint = new Vector2();
public Vector2 collisionNormal = new Vector2();
public Piece collisionPiece;
// Box2D Drag
public Body groundBody;
public Body hitBody = null;
public MouseJoint mouseJoint;
public Vector2 target = new Vector2();
public boolean isDragging;
// Simulation management
public final int VELOCITY_CAP = 100;
public ArrayList<Spring> springs;
public FastMap<Integer, ArrayList<Integer>> springPresenceTable;
public Iterator<Spring> springIter;
public ArrayList<Particle> disposableParticles;
public ArrayList<Particle> tempParticles;
public Particle[] tempParticles2;
public float deformation;
public float dropRadius;
public int dropRadiusPixel;
public int dropRadiusPixel2;
// Temp variables mostly for calculations and graphics processing purposes
public int i;
public int j;
public int a;
public int k;
public int z;
public int s;
public int len;
public int len2;
public int w;
public float q;
public float qq;
public float qqqq;
public float p;
public float pnear;
public float pressure;
public float presnear;
public float changex;
public float changey;
public float factor;
public float lastTotalPressure;
public float totalPressure;
public float dX;
public float dY;
public float relvx;
public float relvy;
public float D;
public float distX;
public float distY;
public float vx;
public float vy;
public boolean waitingRehash;
public float u;
public float I;
public Vector2 dx = new Vector2(0.0f, 0.0f);
public Vector2 rij = new Vector2(0.0f, 0.0f);
public Vector2 tempVect = new Vector2(0.0f, 0.0f);
public Vector2 tempVect2 = new Vector2(0.0f, 0.0f);
public Vector2 attract_vect = new Vector2(0.0f, 0.0f);
public Vector2 repulse_vect = new Vector2(0.0f, 0.0f);
public boolean isAttracting;
public boolean isRepulsing;
public float checkTime;
public float checkTime2;
public float checkTime3;
public Texture dropTexture;
public Texture dropTexture2;
public Sprite dropSprite;
public float spriteColor;
public Vector3 dropCoordinate = new Vector3(0.0f, 0.0f, 0.0f);
public Vector3 dropSize = new Vector3(0.0f, 0.0f, 0.0f);
public Vector3 tempVect3 = new Vector3(0.0f, 0.0f, 0.0f);
public Particle tempParticle;
public Particle neighborP;
public Particle mainP;
public int neighborHash;
public float tempFloat = 0;
public long tempLong = 0;
public boolean tempBoolean = false;
public int tempInt = 0;
public Spring tempSpring;
public Mesh lineMesh;
public float[] lineVertices;
public int vertexIndex = 0;
public Vector3 testPoint = new Vector3();
public Vector2 testPoint2D = new Vector2();
public Vector2 oldDragPos = new Vector2();
public Vector2 dragVelocity = new Vector2();
public FluidSimulatorGeneric(FluidSimulatorStarter fluidSimulatorStarter) {
this.game = fluidSimulatorStarter;
// LibGDX single batches cannot have a size more than 5460
batch = new SpriteBatch(IS_DESKTOP ? 5460 : ANDROID_SIZE);
font = new BitmapFont();
camera = new OrthographicCamera(WORLD_WIDTH, WORLD_HEIGHT);
camera.position.set(0, (WORLD_HEIGHT / 2) - 1, 0);
immediateRenderer = new ImmediateModeRenderer20(SIZE*6, false, true, 0);
irt = new Renderer20(SIZE*6, false, true, 1);
irt2 = new ImmediateModeRenderer20(SIZE*11, false, true, 1);
shapeRenderer = new ShapeRenderer(SIZE);
renderer = new Box2DDebugRenderer(true, true, false, true, false, false);
//3D
camera3D = new PerspectiveCamera(67, WORLD_WIDTH, WORLD_HEIGHT);
camera3D.position.set(0, 130f, 250f);
camera3D.lookAt(0,150f,0);
camera3D.near = 0.1f;
camera3D.far = 500f;
camera3D.update();
ModelBuilder modelBuilder = new ModelBuilder();
// model = modelBuilder.createSphere(5f, 5f, 5f, 4, 4, GL10.GL_TRIANGLES,
// new Material(ColorAttribute.createDiffuse(Color.GREEN)),
// Usage.Position | Usage.Normal);
model = modelBuilder.createBox(5f, 5f, 5f,
new Material(ColorAttribute.createDiffuse(Color.GREEN)),
Usage.Position | Usage.Normal);
instance = new ModelInstance(model);
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, 0, -0.8f, -0.2f));
camController = new Camera3DController(camera3D);
camController.setFluidSimulator(this);
world = new World(new Vector2(0, -9.8f), false);
world.setContactListener(this);
}
/** Create and save body templates **/
public void setupPieces() {
// Reallocate arrays
pieceTemplates = new ArrayList<Piece>(60);
portalIn = new ArrayList<Portal>(20);
portalOut = new ArrayList<Portal>(20);
/** Portal In vertical **/
addNewPieceTemplate((new Piece(2.0f, 6.5f, 0, BodyType.StaticBody)).setSensor(true).setPortalIn(true)); // 0
/** Portal Out vertical **/
addNewPieceTemplate((new Piece(2.0f, 6.5f, 0, BodyType.StaticBody)).setSensor(true).setPortalOut(true)); // 1
/** Portal In horizontal **/
addNewPieceTemplate((new Piece(1.5f, 0.5f, 0, BodyType.StaticBody)).setSensor(true).setPortalIn(true)); // 2
/** Portal Out horizontal **/
addNewPieceTemplate((new Piece(1.5f, 0.5f, 0, BodyType.StaticBody)).setSensor(true).setPortalOut(true)); // 3
/** Circle 20.0 DynamicBody **/
addNewPieceTemplate(new Piece(20, BodyType.DynamicBody)); // 4
/** Circle 0.2 DynamicBody **/
addNewPieceTemplate(new Piece(0.5f, BodyType.DynamicBody)); // 5
/** Large MAIN box **/
addNewPieceTemplate(new Piece(15, 15f, 0, BodyType.DynamicBody)); // 6
/** SECONDARY mini box **/
addNewPieceTemplate(new Piece(3, 0.2f, 0, BodyType.KinematicBody)); // 7
/** Mini Box **/
addNewPieceTemplate(new Piece(0.5f, 0.5f, 0, BodyType.DynamicBody)); // 8
/** Basket Piece **/
addNewPieceTemplate(new Piece(5, BodyType.KinematicBody, true)); // 9
/** Large Box **/
addNewPieceTemplate(new Piece(1.2f, 1.2f, 0, BodyType.DynamicBody)); // 10
/** Large Ball **/
addNewPieceTemplate(new Piece(2, BodyType.DynamicBody)); // 11
/** Arrow **/
addNewPieceTemplate(new Piece(2f, 0.2f, 0, BodyType.KinematicBody)); // 12
/** Ultra Large Box **/
addNewPieceTemplate(new Piece(1.5f, 1.5f, 0, BodyType.DynamicBody)); // 13
/** Mega Box **/
addNewPieceTemplate(new Piece(60.0f, 10.0f, 0, BodyType.StaticBody)); // 14
/** Large Planet **/
addNewPieceTemplate(new Piece(30, BodyType.KinematicBody)); // 15
/** Little Planet **/
addNewPieceTemplate(new Piece(5, BodyType.KinematicBody)); // 16
/** Circle 20.0 StaticBody **/
addNewPieceTemplate(new Piece(20, BodyType.StaticBody)); // 17
/** Wall Box **/
addNewPieceTemplate(new Piece(10.0f, 250.0f, 0, BodyType.StaticBody)); // 18
}
public Piece addNewPieceTemplate(Piece piece) {
pieceTemplates.add(piece);
return piece;
}
public Piece getNewPieceInstanceFromTemplate(int templateIndex) {
return (new Piece(pieceTemplates.get(templateIndex))).setIndex(templateIndex).setHash(prevPieceHash++);
}
public void createPortalIn(float x, float y, int bodyAngle, int portalAngle) {
createBodyAndFixture(getNewPieceInstanceFromTemplate(0).setSensor(true).setPortalIn(true).setAngle(bodyAngle), x, y, true);
portalIn.add(new Portal(tempFixture, portalAngle, PORTAL_FORCE_OUT));
}
public void createPortalOut(float x, float y, int bodyAngle, int portalAngle) {
createBodyAndFixture(getNewPieceInstanceFromTemplate(1).setSensor(true).setPortalOut(true).setAngle(bodyAngle), x, y, true);
portalOut.add(new Portal(tempFixture, portalAngle, PORTAL_FORCE_OUT));
}
public Body createBodyAndFixture(Piece piece, float x, float y, boolean addToPiecesList) {
piece.pos.set(x, y);
def.position.set(x, y);
def.type = piece.type;
def.angle = piece.angle;
def.gravityScale = piece.gravityScale;
def.bullet = piece.isBullet;
Body body = world.createBody(def);
if (body.getType() == BodyType.StaticBody) {
if (piece.shapes != null) {
for (Shape shape : piece.shapes) {
fd.shape = shape;
tempFixture = body.createFixture(fd);
}
}
else {
fd.shape = piece.shape;
tempFixture = body.createFixture(fd);
}
}
else {
if (piece.shapes != null) {
for (Shape shape : piece.shapes) {
tempFixture = body.createFixture(shape, piece.density);
}
}
else {
tempFixture = body.createFixture(piece.shape, piece.density);
}
}
tempFixture.setSensor(piece.isSensor);
tempFixture.setFriction(piece.friction);
tempFixture.setRestitution(piece.restitution);
piece.setBody(body);
// if (body.getType() == BodyType.DynamicBody || body.getType() == BodyType.KinematicBody) {
tempFixture.getBody().setUserData(new ObjectInfo(piece));
if (piece.isPortalAllowed) {
((ObjectInfo)tempFixture.getBody().getUserData()).isPortalAllowed = true;
}
// }
if (addToPiecesList)
pieces.put(piece.hash, piece);
return body;
}
public Piece createPiece(int templateId, float x, float y, float angle, float minVelocity, float maxVelocity,
boolean isPortalAllowed, boolean sticky, boolean addToPiecesList) {
return createPiece(templateId, x, y, angle, minVelocity, maxVelocity, 0.1f, 0.2f, isPortalAllowed, sticky, addToPiecesList);
}
public Piece createPiece(int templateId, float x, float y, float angle, float minVelocity, float maxVelocity,
float friction, float restitution, boolean isPortalAllowed, boolean sticky, boolean addToPiecesList) {
newPiece = getNewPieceInstanceFromTemplate(templateId);
newPiece.setPhysics(friction, restitution, 1, false);
newPiece.isPortalAllowed = isPortalAllowed;
newPiece.setSticky(sticky);
createBodyAndFixture(newPiece, x, y, addToPiecesList);
tempFloat = rnd.nextBoolean() ? 1 : -1;
newPiece.body.setLinearVelocity(tempFloat * (minVelocity + rnd.nextFloat() * maxVelocity * 0.8f), 5 + rnd.nextFloat() * maxVelocity);
newPiece.body.setTransform(newPiece.body.getPosition(), (float)Math.toRadians(angle));
return newPiece;
}
public void rigidBodiesLogic(float deltaTime) {
world.step(FIXED_DELTA_BOX2D, 2, 2);
/** PORTALS **/
logicHitBody = null;
if (portalIn.size() > 0 && portalOut.size() > 0 && portalIn.size() == portalOut.size()) {
for (int i=0; i<portalIn.size(); i++) {
world.QueryAABB(portalInCallback, portalIn.get(i).getX() - 2, portalIn.get(i).getY() - 6.5f, portalIn.get(i).getX() + 2, portalIn.get(i).getY() + 6.5f);
world.QueryAABB(portalOutCallback, portalOut.get(i).getX() - 2, portalOut.get(i).getY() - 6.5f, portalOut.get(i).getX() + 2, portalOut.get(i).getY() + 6.5f);
}
}
}
public QueryCallback portalInCallback = new QueryCallback() {
@Override
public boolean reportFixture (Fixture fixture) {
if (fixture.getBody().getType() != BodyType.StaticBody && !fixture.isSensor() && ((ObjectInfo)fixture.getBody().getUserData()).isPortalAllowed) {
// Prevent portal looping
if (!((ObjectInfo)fixture.getBody().getUserData()).hasTimePassed(300))
return true;
for (int i=0; i<portalIn.size(); i++) {
if (portalIn.get(i).fixture.testPoint(fixture.getBody().getPosition().x, fixture.getBody().getPosition().y)) {
logicHitBody = fixture.getBody();
if (logicHitBody != null) {
logicHitBody.setTransform(portalOut.get(i).getBody().getPosition(), 0);
if (portalOut.get(i).normal != null) {
// New velocity angle
//System.out.println("vel: "+logicHitBody.getLinearVelocity().angle()+" norm: " + portalOut.get(i).normal.angle()+" angle: " + portalOut.get(i).angle);
logicHitBody.setLinearVelocity(logicHitBody.getLinearVelocity().rotate(portalOut.get(i).angle - logicHitBody.getLinearVelocity().angle()));
// Apply a little more linear force
if (allowPortalTransferForce)
logicHitBody.applyForceToCenter(portalOut.get(i).transferForce, true);
}
if (fixture.getBody().getUserData() != null)
((ObjectInfo)fixture.getBody().getUserData()).updateTime();
// handlePortalCallbackRendering(portalIn.get(i).getBody().getPosition(), portalOut.get(i).getBody().getPosition());
}
}
}
}
return true;
}
};
public QueryCallback portalOutCallback = new QueryCallback() {
@Override
public boolean reportFixture (Fixture fixture) {
if (fixture.getBody().getType() != BodyType.StaticBody && !fixture.isSensor() && ((ObjectInfo)fixture.getBody().getUserData()).isPortalAllowed) {
// Prevent portal looping
if (!((ObjectInfo)fixture.getBody().getUserData()).hasTimePassed(300))
return true;
for (int i=0; i<portalIn.size(); i++) {
if (portalOut.get(i).fixture.testPoint(fixture.getBody().getPosition().x, fixture.getBody().getPosition().y)) {
logicHitBody = fixture.getBody();
if (logicHitBody != null) {
logicHitBody.setTransform(portalIn.get(i).getBody().getPosition(), 0);
if (portalIn.get(i).normal != null) {
// New velocity angle
logicHitBody.setLinearVelocity(logicHitBody.getLinearVelocity().rotate(portalIn.get(i).normal.angle() - logicHitBody.getLinearVelocity().angle()));
// Apply a little more linear force
if (allowPortalTransferForce)
logicHitBody.applyForceToCenter(portalIn.get(i).transferForce, true);
}
if (fixture.getBody().getUserData() != null)
((ObjectInfo)fixture.getBody().getUserData()).updateTime();
// handlePortalCallbackRendering(portalOut.get(i).getBody().getPosition(), portalIn.get(i).getBody().getPosition());
}
}
}
}
return true;
}
};
public class RayCastCallBack implements RayCastCallback {
@Override
public float reportRayFixture(Fixture fixture, com.badlogic.gdx.math.Vector2 point, com.badlogic.gdx.math.Vector2 normal, float fraction) {
if (fixture.getBody().getUserData() != null) {
collisionPiece = ((ObjectInfo)fixture.getBody().getUserData()).pieceInfo;
collisionPoint.set(point);
collisionNormal.set(normal);
}
return 0;
}
}
public RayCastCallBack rayCastCallback = new RayCastCallBack();
public QueryCallback callback = new QueryCallback() {
@Override
public boolean reportFixture (Fixture fixture) {
logicHitBody = fixture.getBody();
return false;
}
};
public void portalFluidSolver(Particle particle, float deltaTime) {
if (!particle.hasTimePassed(300))
return;
for (int i=0; i<portalIn.size(); i++) {
if (portalIn.get(i).fixture.testPoint(particle.pos.x, particle.pos.y)) {
particle.pos.set(portalOut.get(i).getBody().getPosition());
particle.velocity.rotate(portalOut.get(i).angle - particle.velocity.angle());
particle.velocity.scl(PORTAL_FORCE_OUT * deltaTime);
particle.updateTime();
return;
}
}
for (int i=0; i<portalOut.size(); i++) {
if (portalOut.get(i).fixture.testPoint(particle.pos.x, particle.pos.y)) {
particle.pos.set(portalIn.get(i).getBody().getPosition());
particle.velocity.rotate(portalIn.get(i).angle - particle.velocity.angle());
particle.velocity.scl(PORTAL_FORCE_OUT * deltaTime);
particle.updateTime();
return;
}
}
}
public void box2dFluidSolverTest(Piece piece, Particle particle, float deltaTime) {
logicHitBody = null;
world.QueryAABB(callback, particle.pos.x - 0.01f, particle.pos.y - 0.01f,
particle.pos.x + 0.01f, particle.pos.y + 0.01f);
if (logicHitBody != null) {
}
}
public void capVelocity(Vector2 v) {
if (v.x > VELOCITY_CAP)
v.x = VELOCITY_CAP;
else if (v.x < -VELOCITY_CAP)
v.x = -VELOCITY_CAP;
if (v.y > VELOCITY_CAP)
v.y = VELOCITY_CAP;
else if (v.y < -VELOCITY_CAP)
v.y = -VELOCITY_CAP;
}
public void prepareDeleteOutOfBoundsParticles(Particle pi) {
if ((pi.pos.x < -BOX_WIDTH / 2)
|| (pi.pos.x > BOX_WIDTH / 2) || (pi.pos.y < 0)
|| (pi.pos.y > BOX_HEIGHT)) {
disposableParticles.add(pi);
}
}
public void deleteOutOfBoundsParticles() {
disposableParticles.clear();
}
@Override
public void beginContact(Contact contact) {
}
@Override
public void endContact(Contact contact) {
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
@Override
public boolean keyDown(int keycode) {
if (keycode == Input.Keys.CONTROL_LEFT) {
isDragging = true;
}
return false;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
@Override
public void render(float delta) {
}
@Override
public void resize(int width, int height) {
}
@Override
public void show() {
Gdx.input.setInputProcessor(this);
touching = false;
}
@Override
public void hide() {
if (disposableParticles != null)
disposableParticles.clear();
if (springs != null)
springs.clear();
if (springPresenceTable != null)
springPresenceTable.clear();
pieces.clear();
portalIn.clear();
portalOut.clear();
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
if (disposableParticles != null)
disposableParticles.clear();
if (springs != null)
springs.clear();
if (springPresenceTable != null)
springPresenceTable.clear();
pieceTemplates.clear();
pieces.clear();
portalIn.clear();
portalOut.clear();
lineVertices = null;
if (lineMesh != null)
lineMesh.dispose();
if (dropTexture != null)
dropTexture.dispose();
if (dropTexture2 != null)
dropTexture2.dispose();
if (bgTexture != null)
bgTexture.dispose();
if (defaultShader != null)
defaultShader.dispose();
if (refractionShader != null)
refractionShader.dispose();
lineMesh = null;
renderer.dispose();
world.dispose();
//3D
model.dispose();
modelBatch.dispose();
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/FluidSimulatorStarter.java<|end_filename|>
package com.fluidsimulator;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.badlogic.gdx.Game;
public class FluidSimulatorStarter extends Game {
FluidSimulatorGeneric fluidSimulatorScreen;
private String solverMethod = "LIQUID";
@Override
public void create() {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
prop.load(input);
solverMethod = prop.getProperty("solver");
System.out.println("Solver selected: " + solverMethod);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to read config.properties file, falling back to LIQUID default solver algorithm");
}
}
}
setScreen(switchToFluidSimulator());
}
public FluidSimulatorGeneric switchToFluidSimulator() {
/**
* remove comment from the line corresponding
* to the simulation solver you want to run
*/
if (fluidSimulatorScreen == null) {
if (solverMethod.equals("SPH")) {
//SPH (Viscoelastic Smoothed Particle Hidrodynamics)
fluidSimulatorScreen = new FluidSimulatorSPH(this);
}
else if (solverMethod.equals("LIQUID")) {
// Liquid (Heavily customized and optimized SPH)
// NOTE: Box2D two-way coupling currently works only with this solver
fluidSimulatorScreen = new FluidSimulatorLiquid(this);
}
else if (solverMethod.equals("PBF")) {
// PBF (Position Based Fluid)
fluidSimulatorScreen = new FluidSimulator(this);
}
else if (solverMethod.equals("MPM")) {
// MPM (Material Point Method)
fluidSimulatorScreen = new FluidSimulatorMPM(this);
}
}
return fluidSimulatorScreen;
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/gameobjects/Portal.java<|end_filename|>
package com.fluidsimulator.gameobjects;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Fixture;
public class Portal {
public Fixture fixture;
public Vector2 normal = null;
public Vector2 transferForce = new Vector2(0,0);
public int angle = 0;
public float forceOut = 500.0f;
public Portal(Fixture fixture, int angle, float forceOut) {
this.forceOut = forceOut;
this.angle = angle;
this.fixture = fixture;
this.normal = new Vector2(1, 0);
this.normal.rotate(angle);
this.normal.nor();
this.transferForce.set(this.normal);
this.transferForce.scl(forceOut);
}
public Portal(Fixture fixture) {
this.fixture = fixture;
}
public Body getBody() {
return fixture.getBody();
}
public float getX() {
return fixture.getBody().getPosition().x;
}
public float getY() {
return fixture.getBody().getPosition().y;
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/gameobjects/sph/SpatialTable.java<|end_filename|>
package com.fluidsimulator.gameobjects.sph;
import java.util.ArrayList;
import java.util.Iterator;
abstract public class SpatialTable<V> implements Iterable<V> {
/** default nearby table sizes
*
* These two variables can be tweaked to affect the accuracy
* and performance of PBF and SPH neighbors search
*/
private static final int DEFAULT_NEARBY_SIZE = 50;
// the actual spatial table
private final ArrayList<V> table;
// a void list initialized here for reuse
private ArrayList<V> voidList = new ArrayList<V>(1);
// the nearby elements table
private ArrayList<V>[][] nearby;
// row and column of the spatial table
private int row;
private int column;
// temporary variables for faster iterations and optimized object allocations
private int i;
private int j;
private int tempSize;
private int z;
private int x;
private int y;
private int xPrev;
private int yPrev;
// abstract position variables must be implemented on actual class instantiation
abstract protected int posX(V value);
abstract protected int posY(V value);
abstract protected int prevPosX(V value);
abstract protected int prevPosY(V value);
@SuppressWarnings("unchecked")
public SpatialTable(int column, int row) {
this.row = row;
this.column = column;
table = new ArrayList<V>((row*column)/2);
nearby = new ArrayList[column][row];
}
/**
* Initialize the nearby table to the default size
*/
public void initialize() {
for (i = 0; i < column; ++i) {
for (j = 0; j < row; ++j) {
nearby[i][j] = new ArrayList<V>(DEFAULT_NEARBY_SIZE);
}
}
}
public boolean add(V value) {
addInCell(value);
table.add(value);
return true;
}
public Iterator<V> iterator() {
return table.iterator();
}
public V get(int i) {
return table.get(i);
}
public boolean remove(V value) {
table.remove(value);
return true;
}
public void clear() {
for (i = 0; i < column; ++i) {
for (j = 0; j < row; ++j) {
nearby[i][j].clear();
nearby[i][j] = null;
}
}
table.clear();
}
public int size() {
return table.size();
}
/**
* Returns an array of neighbors for the provided central object
*/
public ArrayList<V> nearby(V value) {
x = posX(value);
y = posY(value);
if (!isInRange(x, y))
return voidList;
return nearby[x][y];
}
/**
* Update position for an item
*/
public void updatePosition(V value) {
x = posX(value);
y = posY(value);
xPrev = prevPosX(value);
yPrev = prevPosY(value);
if (isInRange(xPrev, yPrev))
nearby[xPrev][yPrev].remove(value);
if (isInRange(x, y))
nearby[x][y].add(value);
}
public int sizeNearby(V value) {
return nearby(value).size();
}
/**
* Updates the spatial table based on new values position
*/
public void rehash() {
for (i=0; i<column; i++) {
for (j=0; j<row; j++) {
if (nearby[i][j] != null)
nearby[i][j].clear();
}
}
tempSize = table.size();
for (z=0; z<tempSize; z++) {
addInCell(table.get(z));
}
}
/**
* Add element to its position and neighbor cells.
*/
private void addInCell(V value) {
for (i = -1; i < 2; ++i) {
for (j = -1; j < 2; ++j) {
x = posX(value)+i;
y = posY(value)+j;
if (isInRange(x, y))
nearby[x][y].add(value);
}
}
}
private boolean isInRange(float x, float y) {
return (x > 0 && x < column && y > 0 && y < row);
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/gameobjects/ObjectInfo.java<|end_filename|>
package com.fluidsimulator.gameobjects;
public class ObjectInfo {
// millis
public long timeCheck;
public float lastDistanceCheck;
public boolean isPortalAllowed = false;
public boolean isSphere = false;
public Piece pieceInfo;
public ObjectInfo() {
this(null);
}
public ObjectInfo(Piece pieceInfo) {
this.timeCheck = 0;
this.lastDistanceCheck = 0;
this.pieceInfo = pieceInfo;
}
public void updateTime() {
this.timeCheck = System.currentTimeMillis();
}
public boolean hasTimePassed(long delay) {
return (System.currentTimeMillis() - timeCheck) >= delay;
}
public void updateDistanceCheck(float newDist) {
this.lastDistanceCheck = newDist;
}
public boolean hasDistancePassed(float newDistance, float distanceGap) {
return (newDistance - lastDistanceCheck) >= distanceGap;
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/gameobjects/SpatialTable.java<|end_filename|>
package com.fluidsimulator.gameobjects;
import java.util.ArrayList;
import java.util.Iterator;
abstract public class SpatialTable implements Iterable<Particle> {
/** default nearby table sizes
*
* These two variables can be tweaked to affect the accuracy
* and performance of PBF and SPH neighbors search
*/
public int MAX_NEIGHBORS = 50;
public int MAX_NEIGHBORS2 = 50;
// the actual spatial table
public final ArrayList<Particle> table;
// a void list initialized here for reuse
private Particle[] voidList = new Particle[0];
// the nearby elements table
// private FastMap<Integer, ArrayList<Particle>> nearby;
private Particle[][][] nearby;
private byte[][] nearbySizes;
private byte lastNearbyLength;
// row and column of the spatial table
private int row;
private int column;
// temporary variables for faster iterations and optimized object allocations
private int i;
private int j;
private int tempSize;
private int z;
private int x;
private int y;
private int x2;
private int y2;
private int xPrev;
private int yPrev;
private int xPrev2;
private int yPrev2;
// abstract position variables must be implemented on actual class instantiation
abstract protected int posX(Particle value);
abstract protected int posY(Particle value);
abstract protected int prevPosX(Particle value);
abstract protected int prevPosY(Particle value);
abstract protected void setPrevGridPos(Particle value, int x, int y);
abstract protected int getPrevGridPosX(Particle value);
abstract protected int getPrevGridPosY(Particle value);
abstract protected void savePosX(Particle value, int x);
abstract protected void savePosY(Particle value, int y);
abstract protected int getPosX(Particle value);
abstract protected int getPosY(Particle value);
abstract protected int getHash(Particle value);
@SuppressWarnings("unchecked")
public SpatialTable(int column, int row, int size) {
this.row = row;
this.column = column;
table = new ArrayList<Particle>(size);
nearby = new Particle[column][row][MAX_NEIGHBORS2];
nearbySizes = new byte[column][row];
lastNearbyLength = 0;
}
/**
* Initialize the nearby table to the default size
*/
public void initialize() {
for (i = 0; i < column; ++i) {
for (j = 0; j < row; ++j) {
nearby[i][j] = new Particle[MAX_NEIGHBORS2];
nearbySizes[i][j] = 0;
}
}
lastNearbyLength = 0;
}
public boolean add(Particle value) {
addInCell(value);
table.add(value);
return true;
}
public Iterator<Particle> iterator() {
return table.iterator();
}
public Particle get(int i) {
return table.get(i);
}
public boolean remove(Particle value) {
table.remove(value);
return true;
}
public void clear() {
for (i = 0; i < column; ++i) {
for (j = 0; j < row; ++j) {
nearby[i][j] = null;
nearbySizes[i][j] = 0;
}
}
lastNearbyLength = 0;
table.clear();
}
/**
* Clear only neighbors map
*/
public void clearNeighbors() {
for (i=0; i<column; i++) {
for (j=0; j<row; j++) {
nearbySizes[i][j] = 0;
}
}
lastNearbyLength = 0;
}
public int size() {
return table.size();
}
/**
* Returns an array of neighbors for the provided central object
*/
public Particle[] nearby(Particle value) {
x = getPosX(value);
y = getPosY(value);
lastNearbyLength = 0;
if (!isInRange(x, y))
return null;
lastNearbyLength = nearbySizes[x][y];
return nearby[x][y];
}
public byte lastSizeNearby() {
return lastNearbyLength;
}
/**
* Updates the spatial table based on new values position
*/
public void rehash() {
clearNeighbors();
tempSize = table.size();
// System.out.println(" ");
// System.out.println(" ");
for (z=0; z<tempSize; z++) {
// System.out.print(z + " ");
addInCell(table.get(z));
}
}
/**
* Add element to its position and neighbor cells.
*/
private void addInCell(Particle value) {
x = posX(value);
y = posY(value);
savePosX(value, x);
savePosY(value, y);
// System.out.println(x + " " + y);
for (i = -1; i < 2; ++i) {
for (j = -1; j < 2; ++j) {
x2 = x+i;
y2 = y+j;
// x2 = x;
// y2 = y;
if (isInRange(x2, y2) && nearbySizes[x2][y2] < MAX_NEIGHBORS2) {
if (nearbySizes[x2][y2] < 0)
nearbySizes[x2][y2] = 0;
nearby[x2][y2][nearbySizes[x2][y2]++] = value;
// if (nearby[x2][y2].size() > 50)
// System.out.println(nearby[x2][y2].size());
}
}
}
}
private boolean isInRange(float x, float y) {
return (x >= 0 && x < column && y >= 0 && y < row);
}
}
<|start_filename|>fluid-simulator-android/assets/data/shaders/refract.vert<|end_filename|>
varying vec3 Position;
varying vec3 Normal;
//uniform mat4 u_projModelView;
void main()
{
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_Position = ftransform();
gl_FrontColor = gl_Color;
Position = vec3(gl_ModelViewProjectionMatrix * gl_Vertex);
Normal = normalize(gl_NormalMatrix * gl_Normal);
}
/*uniform vec3 LightPos;
varying vec3 N;
varying vec3 P;
varying vec3 V;
varying vec3 L;
void main()
{
N = normalize(gl_NormalMatrix*gl_Normal);
P = gl_Vertex.xyz;
V = -vec3(gl_ModelViewMatrix*gl_Vertex);
L = vec3(gl_ModelViewMatrix*(vec4(LightPos,1)-gl_Vertex));
gl_Position = ftransform();
}*/
<|start_filename|>fluid-simulator/src/com/fluidsimulator/FluidSimulatorLiquid.java<|end_filename|>
package com.fluidsimulator;
import java.util.ArrayList;
import javolution.util.FastMap;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.joints.MouseJoint;
import com.badlogic.gdx.physics.box2d.joints.MouseJointDef;
import com.fluidsimulator.gameobjects.Particle;
import com.fluidsimulator.gameobjects.Piece;
import com.fluidsimulator.gameobjects.Spring;
import com.fluidsimulator.gameobjects.fluid.SpatialTable;
import com.fluidsimulator.utils.Vector2;
public class FluidSimulatorLiquid extends FluidSimulatorGeneric {
// FPS Management
private float TICKS_PER_SECOND = IS_DESKTOP ? 60 : 50;
private float SKIP_TICKS = 1 / TICKS_PER_SECOND;
private float FIXED_DELTA = 1.0f / 30.0f;
private final int MAX_FRAMESKIP = 1;
private int speedMultiplier = IS_DESKTOP ? 2 : 1;
// Tune these statics for platform specific behaviors
private float GRAVITY_FORCE = IS_DESKTOP ? -3.0f : -3.0f;
private final Vector2 gravityVect = new Vector2(0.0f, GRAVITY_FORCE);
// Particles arrays and spatial table
private SpatialTable<Particle> particles = new SpatialTable<Particle>(40, 40, IS_DESKTOP ? SIZE : ANDROID_SIZE) {
@Override
protected int posX(Particle value) {
return (int) MathUtils.map(value.pos.x, -BOX_WIDTH_HALF, BOX_WIDTH_HALF, 0, 40-.001f);
// return (int) ((value.pos.x + BOX_WIDTH_HALF + 0.3f) / CELL_SIZE);
}
@Override
protected int posY(Particle value) {
// return (int) ((value.pos.y + BOX_HEIGHT_HALF + 0.3f) / CELL_SIZE);
return (int) MathUtils.map(value.pos.y, INITIAL_HEIGHT, BOX_HEIGHT, 0, 40-.001f);
}
@Override
protected int prevPosX(Particle value) {
return (int) ((value.prevPos.x + BOX_WIDTH_HALF + 0.3f) / CELL_SIZE);
}
@Override
protected int prevPosY(Particle value) {
return (int) ((value.prevPos.y + BOX_HEIGHT_HALF + 0.3f) / CELL_SIZE);
}
@Override
protected void setPrevGridPos(Particle value, int x, int y) {
value.prevGridPos.set(x, y);
}
@Override
protected int getPrevGridPosX(Particle value) {
return (int)value.prevGridPos.x;
}
@Override
protected int getPrevGridPosY(Particle value) {
return (int)value.prevGridPos.y;
}
@Override
protected void savePosX(Particle value, int x) {
value.gridPosX = x;
}
@Override
protected void savePosY(Particle value, int y) {
value.gridPosY = y;
}
@Override
protected int getPosX(Particle value) {
return value.gridPosX;
}
@Override
protected int getPosY(Particle value) {
return value.gridPosY;
}
@Override
protected int getHash(Particle value) {
return value.hash;
}
};
// Simulation management
// Most of these can be tuned at runtime with F1-F10 and keys 1-0 (no numpad)
private int CELL_SIZE = 2;
private float H = 50.0f;
private float H2 = H * H;
private float RAD = 17.0f;
private float VISC = 0.001f;
private float MULTIPLIER = 50 / RAD;
private float K = 0.004f;
private float K_ = 1.01f;
private float SIGMA = 2;
private float P0 = 210.0f;
private final float ATTRACT_FORCE = 1.66f;
private float ATTRACT_RANGE = H2 / 2;
private final float REPULSE_FORCE = H / 2;
private float REPULSE_RANGE = H2 / 4;
private float DAMPING = 0.99f;
private float EMITTER_FORCE = 10;
private float EMITTER_SIZE = 5;
private float K_SPRING = 10.0f;
private final float REST_LENGTH = 5.0f;
private final float YELD_RATIO_STRETCH = 0.2f;
private final float YELD_RATIO_COMPRESS = 0.1f;
private final float PLASTICITY = 0.3f;
private final float STICKINESS_DIST = 5.0f;
private final float STICKINESS_DIST2 = STICKINESS_DIST * STICKINESS_DIST;
private float K_STICKINESS = 7.0f;
private final float WET_FRICTION = 0.0f;
private final float WET_RESTITUTION = 1.0f;
private final int PARTICLE_SIZE = 5;
private float dropRadiusK = 1.5f;
// Temp variables mostly for calculations and graphics processing purposes
private float[] qArray = new float[particles.MAX_NEIGHBORS];
private float[] qqArray = new float[particles.MAX_NEIGHBORS];
private float deltaTime2 = FIXED_DELTA * FIXED_DELTA;
// Modes
private int emitType = 2;
private boolean expandMode = false;
private boolean massMode = false;
private boolean slowMotion = false;
private boolean crazyMode = false;
private boolean hudEnabled = IS_DESKTOP ? true : false;
private boolean shapes = IS_DESKTOP ? false : true;
private boolean render3D = false;
private boolean linesMode = false;
private boolean smokeMode = false;
private boolean whiteBackground = false;
private boolean particleRendering = true;
private boolean viscoElasticityEnabled = false;
private boolean plasticityEnabled = false;
private boolean initializePlasticity = false;
private boolean initializeViscoelasticity = false;
private boolean enableBox2DCollisions = false;
private boolean glowMode = false;
private boolean bgMode = false;
public FluidSimulatorLiquid(FluidSimulatorStarter fluidSimulatorStarter) {
super(fluidSimulatorStarter);
setupPieces();
}
private void createWorld() {
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropTexture = new Texture("data/fluid_drop_64.png");
dropTexture2 = new Texture("data/fluid_drop_64.png");
dropSprite = new Sprite(dropTexture);
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
if (IS_DESKTOP) {
disposableParticles = new ArrayList<Particle>(SIZE);
}
defaultShader = new ShaderProgram(Gdx.files.internal("data/shaders/default.vert").readString(),
Gdx.files.internal("data/shaders/default.frag").readString());
if (!defaultShader.isCompiled()) {
Gdx.app.log("SHADER_LOG", "couldn't compile default shader: " + defaultShader.getLog());
}
defaultIMShader = new ShaderProgram(Gdx.files.internal("data/shaders/defaultim.vert").readString(),
Gdx.files.internal("data/shaders/defaultim.frag").readString());
if (!defaultIMShader.isCompiled()) {
Gdx.app.log("SHADER_LOG", "couldn't compile default IM shader: " + defaultIMShader.getLog());
}
ShaderProgram.pedantic = false;
refractionShader = new ShaderProgram(Gdx.files.internal("data/shaders/refract.vert").readString(),
Gdx.files.internal("data/shaders/refract.frag").readString());
if (!refractionShader.isCompiled()) {
Gdx.app.log("SHADER_LOG", "couldn't compile refraction shader: " + refractionShader.getLog());
}
irt.setShader(defaultIMShader);
bgTexture = new Texture("data/bg.png");
glossMapTexture = new Texture("data/gloss_map2.png");
displacementMap = new Texture("data/water1.png");
displacementMap2 = new Texture("data/water2.png");
bgSprite = new Sprite(bgTexture);
bgSprite.setBounds(0, -1, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() + 1);
// On Android populate directly
if (!IS_DESKTOP) {
for (float j = INITIAL_HEIGHT + hpadding + 2; j < BOX_HEIGHT - 2; j += 5.5f) {
for (float i = -BOX_WIDTH / 3; i < BOX_WIDTH / 3; i += 5.5f) {
particles.add(new Particle(i, j, prevHash++));
tempParticle = particles.get(particles.size() - 1);
tempParticle.type = (emitType);
if (particles.size() >= ANDROID_SIZE)
break;
}
if (particles.size() >= ANDROID_SIZE)
break;
}
}
// createPiece(17, 0, 150, 0, 0, 0, false, true, true);
createPiece(17, 100, 240, 0, 0, 0, false, true, true);
// Boxes
createPiece(6, 0, 160, 0, 0, 0, false, false, true);
createPiece(14, -150, 200, 0, 0, 0, false, false, true);
createPiece(14, 0, 140, 0, 0, 0, false, false, true);
createPiece(14, -170, 60, 90, 0, 0, false, false, true);
// Ball
createPiece(4, 100, 100, 0, -20, 0, false, false, true);
// Portals
createPortalIn(-140, 65, 0, 0);
createPortalOut(-140, 240, 0, 0);
// Ground cage
createPiece(18, -BOX_WIDTH/2 + 7, BOX_HEIGHT/2, 0, 0, 0, 0.2f, 0.5f, false, false, true);
createPiece(18, BOX_WIDTH/2 - 10, BOX_HEIGHT/2, 0, 0, 0, 0.2f, 0.5f, false, false, true);
createPiece(18, 0, INITIAL_HEIGHT, 90, 0, 0, 0.2f, 0.5f, false, false, true);
createPiece(18, 0, BOX_HEIGHT - 10, 90, 0, 0, 0.2f, 0.5f, false, false, true);
// Ground body for mousejoint
BodyDef bodyDef = new BodyDef();
// bodyDef.type = BodyType.StaticBody;
groundBody = world.createBody(bodyDef);
}
@Override
public void show() {
super.show();
particles.initialize();
createWorld();
}
// TODO: Query only particles within collision range
public void box2dFluidSolver(Piece piece, Particle particle, float deltaTime) {
if (particle.rigidBodyHit && particle.contactPieceHash == piece.hash
&& (piece.body.getPosition().dst2(particle.contactPoint) > piece.body.getPosition().dst2(particle.pos)
|| particle.pos.dst2(particle.contactPoint) > STICKINESS_DIST2)) {
particle.rigidBodyHit = false;
}
vec2.set(particle.pos.x + (deltaTime * particle.velocity.x) * 1.5f,
particle.pos.y + (deltaTime * particle.velocity.y) * 1.5f);
vec4.set(particle.prevPos);
vec4.sub(piece.body.getPosition());
vec4.nor();
vec4.scl(100);
vec3.set(particle.prevPos);
vec3.add(vec4);
if (/*!particle.rigidBodyHit && */vec3.dst2(vec2) > 0
&& (piece.body.getFixtureList().get(0).testPoint(vec2)
/*|| piece.body.getFixtureList().get(0).testPoint(vec2.x + 0.5f, vec2.y + 0.5f)
|| piece.body.getFixtureList().get(0).testPoint(vec2.x - 0.5f, vec2.y + 0.5f)
|| piece.body.getFixtureList().get(0).testPoint(vec2.x - 0.5f, vec2.y - 0.5f)
|| piece.body.getFixtureList().get(0).testPoint(vec2.x + 0.5f, vec2.y - 0.5f)*/)) {
collisionPiece = null;
world.rayCast(rayCastCallback, vec3, vec2);
// if (piece.body.getUserData() != null) {
// collisionPiece = ((ObjectInfo)piece.body.getUserData()).pieceInfo;
// collisionPoint.set(vec2);
// vec2.set(particle.velocity);
// vec2.rotate(180);
// vec2.nor();
// collisionNormal.set(vec2);
// }
if (collisionPiece != null) {
tempVect.set(particle.velocity);
//
particle.pos.set(particle.lastSafePos);
if (piece.type == BodyType.DynamicBody) {
particle.pos.set(collisionPoint);
particle.pos.add(collisionNormal.x * 0.5f, collisionNormal.y * 0.5f);
}
particle.rigidBodyHit = true;
particle.contactPoint.set(collisionPoint);
particle.contactNormal.set(collisionNormal);
particle.contactPieceHash = piece.hash;
// for (Particle p : particles.nearby(particle)) {
// p.rigidBodyHit = true;
// p.contactPoint.set(collisionPoint);
// p.contactNormal.set(collisionNormal);
// p.contactPieceHash = piece.hash;
// }
particle.relativeVelocity.set(particle.velocity.x - particle.prevVelocity.x,
particle.velocity.y - particle.prevVelocity.y);
// Vnormal = (Vrelative . normal) * normal
vec2.set(collisionNormal);
vec2.scl(particle.velocity.dot(collisionNormal));
// Vtangent = Vrelative - Vnormal
vec3.set(particle.velocity.x - vec2.x, particle.velocity.y - vec2.y);
// Calculate impulse
vec1.set(vec2.x * (WET_RESTITUTION + piece.restitution) - ((WET_FRICTION - piece.friction) * vec3.x),
vec2.y * (WET_RESTITUTION + piece.restitution) - ((WET_FRICTION - piece.friction) * vec3.y));
tempVect.sub(vec1);
// Apply impulse
particle.velocity.set(tempVect);
// Re-update position
particle.prevPos.set(particle.pos);
particle.pos.set(particle.pos.x + (deltaTime * particle.velocity.x),
particle.pos.y + (deltaTime * particle.velocity.y));
if (piece.type == BodyType.DynamicBody) {
vec4.set(collisionNormal);
vec4.rotate(180);
vec4.scl(45000);
// vec1.scl(200);
// vec4.set(vec1);
// System.out.println(vec1.len());
piece.collisionImpulse.add(vec4);
piece.contactPoint.set(collisionPoint);
}
// Particle still inside the body
if (piece.body.getFixtureList().get(0).testPoint(particle.pos)) {
// System.out.println("asd");
particle.pos.set(particle.lastSafePos);
particle.prevPos.set(particle.pos);
}
}
}
else {
// if (!piece.body.getFixtureList().get(0).testPoint(particle.prevPos))
particle.lastSafePos.set(particle.prevPos);
if (particle.rigidBodyHit && particle.contactPieceHash == piece.hash) {
if (piece.isSticky) {
tempVect.set(particle.velocity);
vec2.set(particle.pos);
vec2.sub(particle.contactPoint);
vec2.nor();
// Calculate stickiness
tempFloat = particle.pos.dst(particle.contactPoint);
tempFloat = K_STICKINESS * tempFloat * (1 - (tempFloat / STICKINESS_DIST));
if (tempFloat > 0) {
vec2.scl(-tempFloat);
tempVect.add(vec2);
}
// System.out.println(vec2.len());
particle.velocity.set(tempVect);
// Re-update position
particle.prevPos.set(particle.pos);
particle.pos.set(particle.pos.x + (deltaTime * particle.velocity.x),
particle.pos.y + (deltaTime * particle.velocity.y));
}
}
}
}
public void performLogic(float deltaTime) {
if (!firstRender)
return;
if (IS_DESKTOP && !isDragging)
spawnParticles(deltaTime);
len = particles.size();
time = System.currentTimeMillis();
if (enableBox2DCollisions) {
// for (Piece piece : pieces.values()) {
// if (piece.isSensor || piece.body.getFixtureList().size() <= 0)
// continue;
// piece.collisionImpulse.set(0, 0);
// for (i=0; i<len; i++) {
// box2dFluidSolver(piece, particles.get(i), deltaTime);
//// box2dFluidSolverTest(piece, particles.get(i), deltaTime);
// }
// if (piece.collisionImpulse.x != 0 && piece.collisionImpulse.y != 0)
// piece.body.applyForce(piece.collisionImpulse, piece.contactPoint);
// }
rigidBodiesLogic(deltaTime);
}
if (DEBUG_ENABLED)
System.out.print("\nrigid: " + (System.currentTimeMillis() - time));
if (!expandMode) {
for (i=0; i<len; i++) {
mainP = particles.get(i);
applyGravity(mainP);
mainP.velocity.scl(DAMPING);
mainP.prevPos.set(mainP.pos);
mainP.pos.set(mainP.pos.x + (deltaTime * mainP.velocity.x),
mainP.pos.y + (deltaTime * mainP.velocity.y));
mainP.xs = MULTIPLIER*mainP.pos.x;
mainP.ys = MULTIPLIER*mainP.pos.y;
mainP.vxs = MULTIPLIER*mainP.velocity.x;
mainP.vys = MULTIPLIER*mainP.velocity.y;
mainP.xchange = 0;
mainP.ychange = 0;
}
}
time = System.currentTimeMillis();
if (waitingRehash)
particles.rehash();
waitingRehash = !waitingRehash;
if (DEBUG_ENABLED)
System.out.print("\t rehash: " + (System.currentTimeMillis() - time));
if (viscoElasticityEnabled) {
if (initializeViscoelasticity) {
initializeViscoelasticity();
initializeViscoelasticity = false;
}
calculateViscoelasticity(deltaTime);
} else if (plasticityEnabled) {
if (initializePlasticity) {
initializePlasticity();
initializePlasticity = false;
}
calculatePlasticity(deltaTime);
}
time = System.currentTimeMillis();
relaxation2(deltaTime);
// particleArray = particles.table.toArray(particleArray);
// for (i=0; i<len; i++) {
//// mainP = particles.get(i);
// mainP = particleArray[i];
// mainP.density += i+i;
//
// tempParticles = particles.nearby(mainP);
// len2 = tempParticles.size();
// tempParticles2 = particles.nearby(mainP);
// len2 = particles.lastSizeNearby();
//// len2 = 40;
// for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
// neighborP = tempParticles2[a];
// neighborP.density += mainP.density;
//// mainP.density += a+a;
// }
// for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
// neighborP = tempParticles2[a];
// neighborP.density += mainP.density;
//// mainP.density += a+a;
// }
// }
drawParticles.clear();
drawParticles.addAll(particles.table);
if (DEBUG_ENABLED)
System.out.print("\t fluid: " + (System.currentTimeMillis() - time));
// if (enableBox2DCollisions) {
//// rigidBodiesLogic(deltaTime);
// for (Piece piece : pieces.values()) {
// if (piece.isSensor || piece.body.getFixtureList().size() <= 0)
// continue;
// piece.collisionImpulse.set(0, 0);
// for (i=0; i<len; i++) {
//// if (particles.get(i).pos.dst2(piece.pos) < 1000)
// box2dFluidSolver(piece, particles.get(i), deltaTime);
//// box2dFluidSolverTest(piece, particles.get(i), deltaTime);
// }
// if (piece.collisionImpulse.x != 0 && piece.collisionImpulse.y != 0) {
// piece.body.applyForce(piece.collisionImpulse, piece.contactPoint);
//// if (piece.shape instanceof CircleShape)
// piece.body.setAngularDamping(0.8f);
// }
// }
// }
time = System.currentTimeMillis();
for (i=0; i<len; i++) {
if (enableBox2DCollisions) {
for (Piece piece : pieces.values()) {
if (piece.isSensor || piece.body.getFixtureList().size <= 0)
continue;
piece.collisionImpulse.set(0, 0);
// if (particles.get(i).pos.dst2(piece.pos) < 1000)
box2dFluidSolver(piece, particles.get(i), deltaTime);
// box2dFluidSolverTest(piece, particles.get(i), deltaTime);
if (piece.collisionImpulse.x != 0 && piece.collisionImpulse.y != 0) {
piece.body.applyForce(piece.collisionImpulse, piece.contactPoint, true);
// if (piece.shape instanceof CircleShape)
piece.body.setAngularDamping(0.8f);
}
}
}
mainP = particles.get(i);
mainP.prevVelocity.set(mainP.velocity);
mainP.velocity.set((mainP.pos.x - mainP.prevPos.x) / deltaTime,
(mainP.pos.y - mainP.prevPos.y) / deltaTime);
if (!enableBox2DCollisions)
wallCollision(mainP);
attract(mainP);
repulse(mainP);
// applyGravity(mainP);
if (enableBox2DCollisions) {
portalFluidSolver(mainP, deltaTime);
}
capVelocity(mainP.velocity);
if (IS_DESKTOP)
prepareDeleteOutOfBoundsParticles(mainP);
}
if (DEBUG_ENABLED)
System.out.print("\t fluid/rigid: " + (System.currentTimeMillis() - time));
// Gravity change with mobile accelerometer
// if (Gdx.input.isPeripheralAvailable(Peripheral.Accelerometer) && (Gdx.input.getAccelerometerX() >= 0 || Gdx.input.getAccelerometerY() >= 0)) {
// gravityVect.set(-Gdx.input.getAccelerometerY() * GRAVITY_FORCE * 0.5f,Gdx.input.getAccelerometerX() * GRAVITY_FORCE * 0.5f);
// }
}
private void relaxation2(float deltaT) {
lastTotalPressure = totalPressure;
totalPressure = 0;
// particleArray = particles.table.toArray(particleArray);
for (Particle mainP : particles) {
// for (i=0; i<len; i++) {
// mainP = particleArray[i];
// mainP.velocity.scl(DAMPING);
// mainP.prevPos.set(mainP.pos);
// mainP.pos.set(mainP.pos.x + (deltaT * mainP.velocity.x),
// mainP.pos.y + (deltaT * mainP.velocity.y));
//
// mainP.xs = MULTIPLIER*mainP.pos.x;
// mainP.ys = MULTIPLIER*mainP.pos.y;
// mainP.vxs = MULTIPLIER*mainP.velocity.x;
// mainP.vys = MULTIPLIER*mainP.velocity.y;
// mainP.xchange = 0;
// mainP.ychange = 0;
tempParticles = particles.nearby(mainP);
len2 = tempParticles.size();
// tempParticles2 = particles.nearby(mainP);
// len2 = particles.lastSizeNearby();
// Particle pressure calculated by particle proximity
// Pressures = 0 if all particles within range are H distance away
p = 0.0f;
pnear = 0.0f;
for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
neighborP = tempParticles.get(a);
// neighborP = tempParticles2[a];
vx = neighborP.xs - mainP.xs;
vy = neighborP.ys - mainP.ys;
if(vx > -H && vx < H && vy > -H && vy < H) {
q = (vx * vx + vy * vy);
if(q < H2) {
qArray[a] = (float)Double.longBitsToDouble(((Double.doubleToLongBits(q) >> 32) + 1072632448) << 31);
if (qArray[a] < EPSILON)
qArray[a] = H - 0.01f;
qq = 1.0f - (qArray[a] / H);
qqArray[a] = qq;
qqqq = qq * qq;
p = (p + qqqq);
pnear = (pnear + qqqq*qq);
// qArray[a] = q;
// if (qArray[a] < EPSILON)
// qArray[a] = H2- 0.01f;
// qq = H2 - q;
// p += KPOLY * qq * qq * qq;
// pnear = p;
} else {
qArray[a] = Float.MAX_VALUE;
}
}
}
mainP.density = p;
// Now actually apply the forces
pressure = (p - 5f) / 2.0f; //normal pressure term
presnear = (pnear) / 2.0f; //near particles term
changex = 0.0f;
changey = 0.0f;
for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
neighborP = tempParticles.get(a);
// neighborP = tempParticles2[a];
vx = neighborP.xs - mainP.xs;
vy = neighborP.ys - mainP.ys;
if(vx > -H && vx < H && vy > -H && vy < H) {
if(qArray[a] < H) {
// q = qArray[a] / H;
// qq = 1.0f - q;
qq = qqArray[a];
factor = qq * (pressure + presnear * qq) / (2.0f * qArray[a]);
dX = vx * factor;
dY = vy * factor;
relvx = neighborP.vxs - mainP.vxs;
relvy = neighborP.vys - mainP.vys;
factor = VISC * qq * deltaT;
dX -= relvx * factor;
dY -= relvy * factor;
// neighborP.xchange += dX;
// neighborP.ychange += dY;
changex -= dX;
changey -= dY;
neighborP.pos.x += dX / MULTIPLIER;
neighborP.pos.y += dY / MULTIPLIER;
neighborP.velocity.x += dX / (MULTIPLIER*deltaT);
neighborP.velocity.y += dY / (MULTIPLIER*deltaT);
}
}
}
// mainP.xchange += changex;
// mainP.ychange += changey;
mainP.pos.x += changex / MULTIPLIER;
mainP.pos.y += changey / MULTIPLIER;
mainP.velocity.x += changex / (MULTIPLIER*deltaT);
mainP.velocity.y += changey / (MULTIPLIER*deltaT);
totalPressure += mainP.velocity.len2() / 100000;
mainP.drawPos.set(mainP.pos.x, mainP.pos.y);
}
}
private void spawnParticles(float deltaTime) {
if (touching && (!isAttracting) && (!isRepulsing)
&& (particles.size() < SIZE - 1)) {
if (!((testPoint2D.x < (-BOX_WIDTH / 2 + wpadding) || testPoint2D.x > (BOX_WIDTH / 2 - wpadding))
|| (testPoint2D.y < (INITIAL_HEIGHT + hpadding) || testPoint2D.y > (BOX_HEIGHT - hpadding)))) {
for (float i = -EMITTER_SIZE; i < EMITTER_SIZE; i += 10.0f) {
for (float j = -EMITTER_SIZE; j < EMITTER_SIZE; j += 5.0f) {
if (particles.size() >= SIZE - 1)
// if (particles.size() >= 1)
break;
particles.add(new Particle(testPoint2D.x + i, testPoint2D.y - j, prevHash++));
tempParticle = particles.get(particles.size() - 1);
tempParticle.type = (emitType);
if (!enableBox2DCollisions) {
if (emitType == 2)
tempParticle.mass = 2;
else if (emitType == 3)
tempParticle.mass = 3;
}
if (viscoElasticityEnabled)
springPresenceTable.put(tempParticle.hash,
new ArrayList<Integer>(SIZE));
tempParticle.velocity.set(tempParticle.velocity.x,
tempParticle.velocity.y - EMITTER_FORCE * deltaTime);
}
}
}
}
}
private void initializePlasticity() {
springs.clear();
len = particles.size();
for (i=0; i<len; i++) {
mainP = particles.get(i);
for (j=0; j<len; j++) {
neighborP = particles.get(j);
if (mainP.hash == neighborP.hash)
continue;
q = mainP.pos.dst(neighborP.pos);
rij.set(neighborP.pos);
rij.sub(mainP.pos);
rij.scl(1 / q);
if (q < REST_LENGTH) {
springs.add(new Spring(mainP, neighborP, q));
}
}
mainP.velocity.set(0, 0);
}
}
private void calculatePlasticity(float deltaTime) {
len2 = springs.size();
for (i=0; i<len2; i++) {
springs.get(i).update();
if (springs.get(i).currentDistance == 0)
continue;
rij.set(springs.get(i).pj.pos);
rij.sub(springs.get(i).pi.pos);
rij.scl(1 / springs.get(i).currentDistance);
// D = deltaTime2 * K_SPRING * (1 - (springs.get(i).restLength/REST_LENGTH)) *(springs.get(i).restLength - springs.get(i).currentDistance);
D = deltaTime * K_SPRING * (springs.get(i).restLength - springs.get(i).currentDistance);
rij.scl(D * 0.5f);
springs.get(i).pi.pos.set(springs.get(i).pi.pos.x - rij.x, springs.get(i).pi.pos.y - rij.y);
springs.get(i).pj.pos.set(springs.get(i).pj.pos.x + rij.x, springs.get(i).pj.pos.y + rij.y);
}
}
private void initializeViscoelasticity() {
len = particles.size();
for (i=0; i<len; i++) {
mainP = particles.get(i);
springPresenceTable.put(mainP.hash, new ArrayList<Integer>(SIZE));
mainP.velocity.set(0, 0);
}
}
/** NOTE: still in testing
* tune YELD_RATIO_STRETCH, YELD_RATIO_COMPRESS and K_SPRING
* to test viscoelasticity
**/
private void calculateViscoelasticity(float deltaTime) {
// deltaTime2 = (deltaTime * deltaTime);
len = particles.size();
for (i=0; i<len; i++) {
mainP = particles.get(i);
tempParticles = particles.nearby(mainP);
len2 = tempParticles.size();
// tempParticles2 = particles.nearby(mainP);
// len2 = particles.lastSizeNearby();
// tempParticles2 = mainP.neighbors;
// len2 = mainP.neighborsSize;
if (tempParticles.size() <= 1)
continue;
for (j=0; j<len2 && j<particles.MAX_NEIGHBORS; j++) {
neighborP = tempParticles.get(j);
neighborHash = neighborP.hash;
if (mainP.hash == neighborHash
|| mainP.pos.dst2(neighborP.pos) > REST_LENGTH)
continue;
// q = mainP.pos.dst(neighborP.pos);
if (!springPresenceTable.get(mainP.hash).contains(
neighborHash)) {
springs.add(new Spring(mainP, neighborP, REST_LENGTH));
springPresenceTable.get(mainP.hash).add(neighborHash);
}
}
}
for (springIter = springs.iterator(); springIter.hasNext();) {
tempSpring = springIter.next();
tempSpring.update();
deformation = tempSpring.restLength * YELD_RATIO_STRETCH;
// Stretch
if (tempSpring.currentDistance > (tempSpring.restLength + deformation)) {
tempSpring.restLength += deltaTime * PLASTICITY
* (tempSpring.currentDistance - tempSpring.restLength - (YELD_RATIO_STRETCH * tempSpring.restLength));
}
// Compress
else {
deformation = tempSpring.restLength * YELD_RATIO_COMPRESS;
if (tempSpring.currentDistance < (tempSpring.restLength - deformation)) {
tempSpring.restLength -= deltaTime * PLASTICITY
* (tempSpring.restLength - tempSpring.currentDistance - (YELD_RATIO_COMPRESS * tempSpring.restLength));
}
}
// Remove springs with restLength longer than REST_LENGTH
if (tempSpring.restLength > REST_LENGTH) {
springIter.remove();
springPresenceTable.get(tempSpring.pi.hash).remove(
(Integer) tempSpring.pj.hash);
} else {
if (tempSpring.currentDistance == 0)
continue;
rij.set(tempSpring.pj.pos);
rij.sub(tempSpring.pi.pos);
rij.scl(1 / tempSpring.currentDistance);
// D = deltaTime2 * K_SPRING * (1 - (tempSpring.restLength/REST_LENGTH)) * (tempSpring.restLength - tempSpring.currentDistance);
D = deltaTime * K_SPRING * (tempSpring.restLength - tempSpring.currentDistance);
rij.scl(D * 0.5f);
tempSpring.pi.pos.set(tempSpring.pi.pos.x - rij.x, tempSpring.pi.pos.y - rij.y);
tempSpring.pj.pos.set(tempSpring.pj.pos.x + rij.x, tempSpring.pj.pos.y + rij.y);
}
}
}
private void applyGravity(Particle pi) {
if (massMode)
pi.velocity.set(pi.velocity.x + (gravityVect.x * pi.mass), pi.velocity.y
+ (gravityVect.y * pi.mass));
else
pi.velocity.set(pi.velocity.x + (gravityVect.x), pi.velocity.y
+ (gravityVect.y));
}
private void attract(Particle pi) {
if (isAttracting) {
if (pi.pos.dst2(testPoint2D) > ATTRACT_RANGE)
return;
attract_vect.set(testPoint2D);
attract_vect.sub(pi.pos);
pi.velocity.set(pi.velocity.x
+ (attract_vect.x * ATTRACT_FORCE), pi.velocity.y
+ (attract_vect.y * ATTRACT_FORCE));
}
}
private void repulse(Particle pi) {
if (isRepulsing) {
if (pi.pos.dst2(testPoint2D) > REPULSE_RANGE)
return;
repulse_vect.set(pi.pos);
repulse_vect.sub(testPoint2D);
pi.velocity.set(pi.velocity.x
+ (repulse_vect.x * REPULSE_FORCE), pi.velocity.y
+ (repulse_vect.y * REPULSE_FORCE));
}
}
private void wallCollision(Particle pi) {
tempVect.set(0, 0);
boolean toDump = false;
if (pi.pos.x > (BOX_WIDTH / 2 - wpadding)) {
tempVect.sub((pi.pos.x - (BOX_WIDTH / 2 - wpadding))
/ COLLISION_FORCE, 0);
pi.pos.x = (BOX_WIDTH / 2 - wpadding);
}
else if (pi.pos.x < (-BOX_WIDTH / 2 + wpadding)) {
tempVect.add(((-BOX_WIDTH / 2 + wpadding) - pi.pos.x)
/ COLLISION_FORCE, 0);
pi.pos.x = (-BOX_WIDTH / 2 + wpadding);
}
if (pi.pos.y > (BOX_HEIGHT - hpadding)) {
tempVect.sub(0, (pi.pos.y - (BOX_HEIGHT - hpadding))
/ COLLISION_FORCE);
pi.pos.y = (BOX_HEIGHT - hpadding);
}
else if (pi.pos.y < (INITIAL_HEIGHT + hpadding)) {
tempVect.add(0, ((INITIAL_HEIGHT + hpadding) - pi.pos.y)
/ COLLISION_FORCE);
toDump = true;
pi.pos.y = (INITIAL_HEIGHT + hpadding);
}
pi.velocity.set(pi.velocity.x + tempVect.x, pi.velocity.y
+ tempVect.y);
if (toDump)
pi.velocity.scl(0.98f);
}
private void prepareDeleteOutOfBoundsParticles() {
len = disposableParticles.size();
for (i=0; i<len; i++) {
particles.remove(disposableParticles.get(i));
}
}
@Override
public void render(float deltaTime) {
firstRender = true;
timeStep += deltaTime;
stepped = false;
loops = 0;
while (timeStep > nextGameTick
&& loops < MAX_FRAMESKIP) {
for (speedCounter = 0; speedCounter < speedMultiplier; speedCounter++) {
performLogic(FIXED_DELTA);
if (IS_DESKTOP) {
prepareDeleteOutOfBoundsParticles();
deleteOutOfBoundsParticles();
}
}
stepped = true;
nextGameTick += slowMotion ? SKIP_TICKS * 3 : SKIP_TICKS;
loops++;
}
// interpolation = slowMotion ? (timeStep + (SKIP_TICKS*3) - nextGameTick) / (SKIP_TICKS*3)
// : (timeStep + SKIP_TICKS - nextGameTick) / SKIP_TICKS;
long renderTime = System.currentTimeMillis();
camera.update();
if (gl == null) {
gl = Gdx.gl20;
}
if (whiteBackground)
gl.glClearColor(1, 1, 1, 1);
else
gl.glClearColor(0, 0, 0, 1);
gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
if (bgMode) {
batch.disableBlending();
batch.begin();
bgSprite.draw(batch);
batch.end();
batch.enableBlending();
}
if (enableBox2DCollisions)
renderer.render(world, camera.combined);
gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);
// gl.glEnable(GL10.GL_LINE_SMOOTH);
// gl.glHint(GL10.GL_LINE_SMOOTH_HINT, GL20.GL_NICEST);
// gl.glEnable(GL20.GL_BLEND);
// gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
// gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
// Begin Batch
if (particleRendering && !render3D) {
if (shapes) {
len = drawParticles.size();
batch.setProjectionMatrix(camera.combined);
batch.begin();
// for (i=0; i<len; i++) {
// mainP = particles.get(i);
for (Particle mainP : drawParticles) {
// particleArray = particles.table.toArray(particleArray);
// for (k=0; k<len; k++) {
// mainP = particleArray[k];
if (mainP == null)
break;
dropCoordinate.set(mainP.drawPos.x - dropRadius,
mainP.drawPos.y - dropRadius, 0.0f);
spriteColor = 1.0f/* - (mainP.density * LINE_DENSITY_FACTOR / 255.0f)*/;
// if (spriteColor < 0.2f)
// spriteColor = 0.2f;
if (mainP.type == 1 && k==0)
batch.setColor(spriteColor, 0, 0, 1);
else if (mainP.type == 2 && k==0)
batch.setColor(0, spriteColor, 0, 1);
else if (mainP.type == 3 && k==0)
batch.setColor(0, 0, spriteColor, 1);
// dropSprite.setPosition(dropCoordinate.x, dropCoordinate.y);
// dropSprite.draw(batch);
// batch.setColor(dropSprite.getColor());
batch.draw(dropTexture2, dropCoordinate.x, dropCoordinate.y, dropRadiusPixel, dropRadiusPixel);
}
// }
batch.end();
}
else if (!linesMode) {
len = drawParticles.size();
gl.glEnable(GL20.GL_BLEND);
if (bgMode) {
// if (glowMode)
gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
// else
// gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
gl.glEnable(GL20.GL_TEXTURE_2D);
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE0);
dropTexture.bind();
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE1);
bgTexture.bind();
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE2);
glossMapTexture.bind();
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE3);
displacementMap.bind();
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE4);
displacementMap2.bind();
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE0);
irt.begin(camera.combined, GL20.GL_TRIANGLES);
// for (i=0; i<len; i++) {
// mainP = particles.get(i);
for (Particle mainP : drawParticles) {
// particleArray = particles.table.toArray(particleArray);
// for (k=0; k<len; k++) {
// mainP = particleArray[k];
// if (mainP == null)
// break;
// dropCoordinate.set(mainP.drawPos.x - dropRadius,
// mainP.drawPos.y - dropRadius, 0.0f);
dropCoordinate.set((mainP.drawPos.x + (mainP.velocity.x * interpolation * deltaTime)) - dropRadius,
(mainP.drawPos.y + (mainP.velocity.y * interpolation * deltaTime)) - dropRadius, 0.0f);
spriteColor = 1.0f/* - (mainP.density * LINE_DENSITY_FACTOR / 255.0f)*/;
// if (spriteColor < 0.2f)
// spriteColor = 0.2f;
if (mainP.type == 1 && k==0)
dropSprite.setColor(spriteColor, 0, 0, 1);
else if (mainP.type == 2 && k==0)
dropSprite.setColor(0, spriteColor, 0, 1);
else if (mainP.type == 3 && k==0)
dropSprite.setColor(0.7f, 1, 1, 1);
irt.texCoord(0, 0);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
irt.texCoord(0, 1);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt.texCoord(1, 1);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt.texCoord(0, 0);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
irt.texCoord(1, 1);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt.texCoord(1, 0);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
}
// }
// System.out.println(totalPressure - lastTotalPressure);
if (Math.abs(totalPressure - lastTotalPressure) >= 5)
irt.factor -= 0.0001f;
else
irt.factor += 0.0002f;
irt.end();
gl.glDisable(GL20.GL_TEXTURE_2D);
}
else {
// if (glowMode)
// gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
// else
if (whiteBackground)
gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
else
gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
gl.glEnable(GL20.GL_TEXTURE_2D);
dropTexture.bind();
irt2.begin(camera.combined, GL20.GL_TRIANGLES);
// for (i=0; i<len; i++) {
// mainP = particles.get(i);
for (Particle mainP : drawParticles) {
// particleArray = particles.table.toArray(particleArray);
// for (k=0; k<len; k++) {
// mainP = particleArray[k];
// if (mainP == null)
// break;
// dropCoordinate.set(mainP.drawPos.x - dropRadius,
// mainP.drawPos.y - dropRadius, 0.0f);
dropCoordinate.set((mainP.drawPos.x + (mainP.velocity.x * interpolation * deltaTime)) - dropRadius,
(mainP.drawPos.y + (mainP.velocity.y * interpolation * deltaTime)) - dropRadius, 0.0f);
spriteColor = 1.0f/* - (mainP.density * LINE_DENSITY_FACTOR / 255.0f)*/;
// if (spriteColor < 0.2f)
// spriteColor = 0.2f;
if (mainP.type == 1 && k==0)
dropSprite.setColor(spriteColor, 0, 0, 1);
else if (mainP.type == 2 && k==0)
dropSprite.setColor(0, spriteColor, 0, 1);
else if (mainP.type == 3 && k==0)
dropSprite.setColor(0, 0, spriteColor, 1);
irt2.texCoord(0, 0);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
irt2.texCoord(0, 1);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt2.texCoord(1, 1);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt2.texCoord(0, 0);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
irt2.texCoord(1, 1);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt2.texCoord(1, 0);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
}
// }
irt2.end();
gl.glDisable(GL20.GL_TEXTURE_2D);
// gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);
immediateRenderer.begin(camera.combined, GL20.GL_TRIANGLES);
// if (glowMode)
// gl.glBlendFunc(GL20.GL_DST_COLOR, GL20.GL_DST_COLOR);
// else
gl.glBlendFunc(GL20.GL_ZERO, GL20.GL_DST_COLOR);
for (i=0; i< (glowMode ? 0 : 2); i++) {
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(-BOX_WIDTH/2, 0, 0);
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(-BOX_WIDTH/2, BOX_HEIGHT, 0);
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(BOX_WIDTH/2, BOX_HEIGHT, 0);
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(-BOX_WIDTH/2, 0, 0);
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(BOX_WIDTH/2, BOX_HEIGHT, 0);
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(BOX_WIDTH/2, 0, 0);
}
immediateRenderer.end();
}
} else {
Gdx.gl.glLineWidth(2);
immediateRenderer.begin(camera.combined, GL20.GL_LINES);
vertexIndex = 0;
len = particles.size();
// for (i=0; i<len; i++) {
// mainP = particles.get(i);
for (Particle mainP : drawParticles) {
// particleArray = particles.table.toArray(particleArray);
// for (k=0; k<len; k++) {
// mainP = particleArray[k];
// if (mainP == null)
// break;
spriteColor = mainP.density * LINE_DENSITY_FACTOR / 255.0f;
if (spriteColor > 1.0f)
spriteColor = 1.0f;
if (smokeMode) {
// Red Fire
if (emitType == 1) {
tempInt = 255 - (int) ((System.currentTimeMillis() - mainP
.spawnTime) / 50);
// Start by decreasing B value to 0
mainP.setBGrad(240 - (int) ((System
.currentTimeMillis() - mainP.spawnTime) / (3 * 1)));
// Then decrease G value to 0
if (mainP.bGrad < 150)
mainP.setGGrad(255 - (int) ((System
.currentTimeMillis() - mainP
.spawnTime) / (10 * 1)));
// Then decrease R value to 0
if (mainP.gGrad < 150)
mainP.setRGrad(255 - (int) ((System
.currentTimeMillis() - mainP
.spawnTime) / (25 * 1)));
if (tempInt <= 0 || mainP.rGrad == 0) {
disposableParticles.add(mainP);
continue;
}
}
// Blue Fire
else if (emitType == 2) {
tempInt = 255 - (int) ((System.currentTimeMillis() - mainP
.spawnTime) / 50);
// Start by decreasing R value to 0
mainP.setRGrad(240 - (int) ((System
.currentTimeMillis() - mainP.spawnTime) / (3 * 1)));
// Then decrease G value to 0
if (mainP.rGrad < 150)
mainP.setGGrad(255 - (int) ((System
.currentTimeMillis() - mainP
.spawnTime) / (10 * 1)));
// Then decrease B value to 0
if (mainP.gGrad < 150)
mainP.setBGrad(255 - (int) ((System
.currentTimeMillis() - mainP
.spawnTime) / (25 * 1)));
if (tempInt <= 0 || mainP.bGrad == 0) {
disposableParticles.add(mainP);
continue;
}
}
// Green Fire
else if (emitType == 3) {
tempInt = 255 - (int) ((System.currentTimeMillis() - mainP
.spawnTime) / 50);
// Start by decreasing R and B values to 0
mainP.setRGrad(240 - (int) ((System
.currentTimeMillis() - mainP.spawnTime) / (10 * 1)));
mainP.setBGrad(240 - (int) ((System
.currentTimeMillis() - mainP.spawnTime) / (10 * 1)));
// Then decrease G value to 0
if (mainP.rGrad < 150)
mainP.setGGrad(255 - (int) ((System
.currentTimeMillis() - mainP
.spawnTime) / (25 * 1)));
if (tempInt <= 0 || mainP.gGrad == 0) {
disposableParticles.add(mainP);
continue;
}
}
}
dropCoordinate.set((mainP.drawPos.x + (mainP.velocity.x * interpolation * deltaTime)) - dropRadius,
(mainP.drawPos.y + (mainP.velocity.y * interpolation * deltaTime)) - dropRadius, 0.0f);
// camera.project(dropCoordinate);
// lineVertices[vertexIndex++] = dropCoordinate.x;
// lineVertices[vertexIndex++] = dropCoordinate.y;
if (smokeMode) {
// lineVertices[vertexIndex++] = Color.toFloatBits(
// mainP.rGrad, mainP.gGrad, mainP.bGrad,
// tempInt);
immediateRenderer.color((float)mainP.rGrad / 255.0f,
(float)mainP.gGrad / 255.0f, (float)mainP.bGrad / 255.0f, (float)tempInt / 255.0f);
}
else {
if (mainP.type == 1)
// lineVertices[vertexIndex++] = Color.toFloatBits(
// 255, (int) mainP.density
// * LINE_DENSITY_FACTOR, 0, 255);
immediateRenderer.color(1, spriteColor, 0, 1);
else if (mainP.type == 2)
// lineVertices[vertexIndex++] = Color
// .toFloatBits((int) mainP.density
// * LINE_DENSITY_FACTOR, 0, 255, 255);
immediateRenderer.color(0, 0.79f, spriteColor/2, 1);
else if (mainP.type == 3)
// lineVertices[vertexIndex++] = Color.toFloatBits(0,
// 200, (int) mainP.density
// * LINE_DENSITY_FACTOR, 255);
immediateRenderer.color(spriteColor/4, 0, 1, 1);
}
// lineVertices[vertexIndex++] = dropCoordinate.x
// + mainP.velocity.x * LINE_VELOCITY_FACTOR;
// lineVertices[vertexIndex++] = dropCoordinate.y
// + mainP.velocity.y * LINE_VELOCITY_FACTOR;
immediateRenderer.vertex(dropCoordinate.x, dropCoordinate.y, 0);
if (smokeMode)
// lineVertices[vertexIndex++] = Color.toFloatBits(
// mainP.rGrad, mainP.gGrad, mainP.bGrad,
// tempInt);
immediateRenderer.color((float)mainP.rGrad / 255.0f,
(float)mainP.gGrad / 255.0f, (float)mainP.bGrad / 255.0f, (float)tempInt / 255.0f);
else {
if (mainP.type == 1)
// lineVertices[vertexIndex++] = Color.toFloatBits(
// 255, (int) mainP.density
// * LINE_DENSITY_FACTOR, 0, 255);
immediateRenderer.color(1, spriteColor, 0, 1);
else if (mainP.type == 2)
// lineVertices[vertexIndex++] = Color
// .toFloatBits((int) mainP.density
// * LINE_DENSITY_FACTOR, 0, 255, 255);
immediateRenderer.color(0, 0.79f, spriteColor/2, 1);
else if (mainP.type == 3)
// lineVertices[vertexIndex++] = Color.toFloatBits(0,
// 200, (int) mainP.density
// * LINE_DENSITY_FACTOR, 255);
immediateRenderer.color(spriteColor/4, 0, 1, 1);
}
immediateRenderer.vertex(dropCoordinate.x + mainP.velocity.x * LINE_VELOCITY_FACTOR,
dropCoordinate.y + mainP.velocity.y * LINE_VELOCITY_FACTOR, 0);
}
// }
// lineMesh.setVertices(lineVertices, 0, vertexIndex);
// defaultShader.begin();
// lineMesh.render(defaultShader, GL20.GL_LINES);
// defaultShader.end();
immediateRenderer.end();
}
}
gl.glDisable(GL20.GL_BLEND);
if (hudEnabled) {
if (whiteBackground)
font.setColor(0, 0, 0, 1);
else
font.setColor(1, 1, 1, 1);
batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.begin();
font.draw(batch,
"fps:" + Gdx.graphics.getFramesPerSecond()
+ ", particles: " + (particles.size()), 0, Gdx.graphics.getHeight() - 40);
font.draw(batch, "deltaTime: " + deltaTime, 0, Gdx.graphics.getHeight() - 20);
font.draw(batch, "pressure: " + (totalPressure - lastTotalPressure), 0, Gdx.graphics.getHeight());
font.draw(batch, "(SPACE) Fluid Type: " + emitType
+ " (+/-) Gravity: " + GRAVITY_FORCE
+ " (UP/DOWN) Emitter: " + EMITTER_SIZE
+ " (E) Expand: " + expandMode + " (S) Slow: "
+ slowMotion + " (C) Crazy: " + crazyMode
+ " (L) Lines: " + linesMode + " (Q) Shapes: "
+ shapes, 180.0f, Gdx.graphics.getHeight());
font.draw(batch, "(K) Smoke: " + smokeMode
+ " (P) Plasticity: " + plasticityEnabled
+ " (V) ViscoElasticity: " + viscoElasticityEnabled
+ " (R) Particle Render: " + particleRendering
+ " (M) Mass: " + massMode
+ " (B) Box2DColl: " + enableBox2DCollisions
+ " (G) Glow: " + glowMode, 180, Gdx.graphics.getHeight() - 20);
font.draw(batch,"K: " + K + " Sigma: " + SIGMA
+ " Density: " + P0 + " H: " + H
+ " Cell: " + CELL_SIZE + " K_: " + K_
+ " Rad: " + dropRadiusK
+ " K_SRING: " + K_SPRING
+ " MN: " + particles.MAX_NEIGHBORS
+ " Step: " + FIXED_DELTA
+ " STICK: " + K_STICKINESS
+ " RAD: " + RAD
+ " VISC: " + VISC
+ " DAMP: " + DAMPING, 180, Gdx.graphics.getHeight() - 40);
font.draw(batch,"camera3D: " + camera3D.position, 180, Gdx.graphics.getHeight() - 60);
batch.end();
}
//3D
if (render3D) {
// Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// camera3D.update();
camController.update();
modelBatch.begin(camera3D);
for (Particle p : drawParticles) {
instance.transform.setToTranslation(p.drawPos.x, p.drawPos.y, 0);
modelBatch.render(instance, environment);
}
modelBatch.end();
}
if (DEBUG_ENABLED)
System.out.print("\t render: " + (System.currentTimeMillis() - renderTime));
// Exit the application if ESC has been pressed
if (exitApp) {
Gdx.app.exit();
}
}
@Override
public boolean keyUp(int keycode) {
// K
if (keycode == Input.Keys.F1 && K < 2.0f) {
K += 0.1f;
} else if (keycode == Input.Keys.NUM_1 && K > 0.004f) {
K -= 0.1f;
if (K < 0.004f)
K = 0.004f;
}
// SIGMA
if (keycode == Input.Keys.F2 && SIGMA < 50.0f)
SIGMA += 2;
else if (keycode == Input.Keys.NUM_2 && SIGMA > 0)
SIGMA -= 2;
// DENSITY
else if (keycode == Input.Keys.F3 && P0 < 1000.0f)
P0 += 100.0f;
else if (keycode == Input.Keys.NUM_3 && P0 > 100.0f)
P0 -= 100.0f;
// H
else if (keycode == Input.Keys.F4 && H < 200.0f) {
H += 5.0f;
H2 = H * H;
ATTRACT_RANGE = H2 / 2;
REPULSE_RANGE = H2 / 4;
} else if (keycode == Input.Keys.NUM_4 && H > 5.0f) {
H -= 5.0f;
H2 = H * H;
ATTRACT_RANGE = H2 / 2;
REPULSE_RANGE = H2 / 4;
}
// CELL_SIZE
if (keycode == Input.Keys.F5 && CELL_SIZE < 50) {
CELL_SIZE += 1;
particles.rehash();
} else if (keycode == Input.Keys.NUM_5 && CELL_SIZE > 1) {
CELL_SIZE -= 1;
particles.rehash();
}
// K_
if (keycode == Input.Keys.F6 && K_ < 10.0f) {
K_ += 0.1f;
} else if (keycode == Input.Keys.NUM_6 && K_ > 0.1f) {
K_ -= 0.1f;
}
// MAX_NEIGHBORS
if (keycode == Input.Keys.F7 && particles.MAX_NEIGHBORS < 500) {
particles.MAX_NEIGHBORS += 5;
qArray = new float[particles.MAX_NEIGHBORS];
qqArray = new float[particles.MAX_NEIGHBORS];
} else if (keycode == Input.Keys.NUM_7 && particles.MAX_NEIGHBORS > 0) {
particles.MAX_NEIGHBORS -= 5;
qArray = new float[particles.MAX_NEIGHBORS];
qqArray = new float[particles.MAX_NEIGHBORS];
}
// dropRadiusK
if (keycode == Input.Keys.F8 && dropRadiusK < 3.5f) {
dropRadiusK += 0.2f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
} else if (keycode == Input.Keys.NUM_8 && dropRadiusK >= 0.3f) {
dropRadiusK -= 0.2f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
// K_SPRING
if (keycode == Input.Keys.F9 && K_SPRING < 10.0f)
K_SPRING += 0.2f;
else if (keycode == Input.Keys.NUM_9 && K_SPRING > 0.2f)
K_SPRING -= 0.2f;
// K_STICKINESS
if (keycode == Input.Keys.F10 && K_STICKINESS < 20.0f)
K_STICKINESS += 1;
else if (keycode == Input.Keys.NUM_0 && K_STICKINESS > 0)
K_STICKINESS -= 1;
// RAD
if (keycode == Input.Keys.RIGHT && RAD < 50.0f) {
RAD += 1;
MULTIPLIER = 50 / RAD;
}
else if (keycode == Input.Keys.LEFT && RAD > 0) {
RAD -= 1;
MULTIPLIER = 50 / RAD;
}
// VISC
if (keycode == Input.Keys.F11 && VISC < 1.0f)
VISC += 0.0001f;
else if (keycode == Input.Keys.F12 && VISC > 0)
VISC -= 0.0001f;
if (keycode == Input.Keys.BACKSPACE && isAttracting) {
for (Particle pi : particles) {
if (pi.pos.dst2(testPoint2D) < ATTRACT_RANGE) {
disposableParticles.add(pi);
}
}
} else if (keycode == Input.Keys.BACKSPACE && IS_DESKTOP) {
for (Particle pi : particles)
disposableParticles.add(pi);
}
// Change Particle color
if (keycode == Input.Keys.SPACE) {
emitType += 1;
if (emitType > 3) {
emitType = 1;
}
if (!IS_DESKTOP) {
for (Particle p : particles)
p.type = emitType;
}
}
// Increase/Decrease Gravity
if ((keycode == Input.Keys.PLUS) && (GRAVITY_FORCE > -60.0f)) {
GRAVITY_FORCE -= 1.0f;
gravityVect.set(0.0f, GRAVITY_FORCE);
} else if ((keycode == Input.Keys.MINUS) && (GRAVITY_FORCE < 0.0f)) {
GRAVITY_FORCE += 1.0f;
// if (GRAVITY_FORCE > -0.2f)
// GRAVITY_FORCE = 0.0f;
gravityVect.set(0.0f, GRAVITY_FORCE);
}
// Increase/Decrease Emitter Size
if ((keycode == Input.Keys.DOWN) && (EMITTER_SIZE > 2)) {
EMITTER_SIZE -= 3;
} else if ((keycode == Input.Keys.UP) && (EMITTER_SIZE < 20)) {
EMITTER_SIZE += 3;
}
// Enable/Disable Expand Mode
if (keycode == Input.Keys.E)
expandMode = !expandMode;
// Enable/Disable Stop Motion
if (keycode == Input.Keys.S)
slowMotion = !slowMotion;
// Enable/Disable Crazy Mode
if (keycode == Input.Keys.C) {
// crazyMode = !crazyMode;
Gdx.input.setInputProcessor(camController);
}
// Enable/Disable Box2D Collisions
if (keycode == Input.Keys.B)
enableBox2DCollisions = !enableBox2DCollisions;
// Enable/Disable Render Glow
if (keycode == Input.Keys.G)
glowMode = !glowMode;
// Enable/Disable HUD
if (keycode == Input.Keys.H)
hudEnabled = !hudEnabled;
// Mass Mode
if (keycode == Input.Keys.M) {
massMode = !massMode;
}
// Enable/Disable Plasticity
if (keycode == Input.Keys.P && !viscoElasticityEnabled && IS_DESKTOP) {
plasticityEnabled = !plasticityEnabled;
if (plasticityEnabled) {
initializePlasticity = true;
if (springs == null && springPresenceTable == null) {
springs = new ArrayList<Spring>(SIZE * 230);
springPresenceTable = new FastMap<Integer, ArrayList<Integer>>(
SIZE);
}
} else {
springs.clear();
springPresenceTable.clear();
}
}
// Enable/Disable ViscoElasticity
if (keycode == Input.Keys.V && !plasticityEnabled && IS_DESKTOP) {
viscoElasticityEnabled = !viscoElasticityEnabled;
if (viscoElasticityEnabled) {
initializeViscoelasticity = true;
if (springs == null && springPresenceTable == null) {
springs = new ArrayList<Spring>(SIZE * 230);
springPresenceTable = new FastMap<Integer, ArrayList<Integer>>(
SIZE);
}
springs.clear();
springPresenceTable.clear();
} else {
springs.clear();
springPresenceTable.clear();
System.gc();
}
}
// Enable/Disable Shapes mode
if (keycode == Input.Keys.Q) {
shapes = !shapes;
if (!shapes) {
dropRadiusK = 1.5f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
else {
dropRadiusK = 0.3f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
}
// Enable/Disable Lines mode
if (keycode == Input.Keys.L) {
linesMode = !linesMode;
}
// Enable/Disable Smoke Mode
if (keycode == Input.Keys.K)
smokeMode = !smokeMode;
// Enable/Disable Particle Rendering
if (keycode == Input.Keys.R) {
particleRendering = !particleRendering;
render3D = !render3D;
}
// Enable/Disable White Background
if (keycode == Input.Keys.X)
whiteBackground = !whiteBackground;
if (keycode == Keys.PAGE_UP) {
FIXED_DELTA += 0.004f;
}
if (keycode == Keys.PAGE_DOWN) {
FIXED_DELTA -= 0.004f;
if (FIXED_DELTA <= 0.016f)
FIXED_DELTA = 0.016f;
}
// Exit
if (keycode == Input.Keys.ESCAPE) {
exitApp = true;
}
if (keycode == Input.Keys.CONTROL_LEFT) {
isDragging = false;
}
if (keycode == Input.Keys.CONTROL_RIGHT) {
DAMPING += 0.01f;
}
else if (keycode == Input.Keys.ALT_RIGHT) {
DAMPING -= 0.01f;
}
// Enable/Disable BG Mode
if (keycode == Input.Keys.N) {
if (IS_DESKTOP)
bgMode = !bgMode;
else if (!enableBox2DCollisions) {
shapes = !shapes;
bgMode = !bgMode;
if (shapes)
dropRadiusK = 1.3f;
else
dropRadiusK = 2.5f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
}
return false;
}
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
touching = true;
camera.unproject(testPoint.set(x, y, 0));
testPoint2D.x = testPoint.x;
testPoint2D.y = testPoint.y;
oldDragPos.set(testPoint2D);
if (button == Buttons.LEFT) {
// Drag Mode
if (isDragging) {
for (Piece piece : pieces.values()) {
hitBody = null;
if (piece.body.getFixtureList().get(0).testPoint(testPoint2D)) {
hitBody = piece.body;
if (hitBody.getType() == BodyType.KinematicBody || hitBody.getType() == BodyType.StaticBody)
continue;
MouseJointDef def = new MouseJointDef();
def.bodyA = groundBody;
def.bodyB = hitBody;
def.collideConnected = true;
def.target.set(testPoint2D);
def.maxForce = 10.0f * hitBody.getMass();
mouseJoint = (MouseJoint)world.createJoint(def);
hitBody.setAwake(true);
break;
}
}
if (mouseJoint != null)
return false;
}
if (!IS_DESKTOP) {
isRepulsing = true;
isAttracting = false;
} else {
isAttracting = false;
isRepulsing = false;
}
}
if (button == Buttons.RIGHT) {
isAttracting = true;
}
if (button == Buttons.MIDDLE) {
isRepulsing = true;
}
return false;
}
@Override
public boolean touchDragged(int x, int y, int pointer) {
camera.unproject(testPoint.set(x, y, 0));
testPoint2D.x = testPoint.x;
testPoint2D.y = testPoint.y;
dragVelocity.set(testPoint2D);
dragVelocity.sub(oldDragPos);
oldDragPos.set(testPoint2D);
if (mouseJoint != null) {
mouseJoint.setTarget(target.set(testPoint2D));
mouseJoint.getBodyB().setLinearVelocity(0, 0);
mouseJoint.getBodyB().setTransform(testPoint2D.x, testPoint2D.y, 0);
}
return false;
}
@Override
public boolean touchUp(int x, int y, int pointer, int button) {
touching = false;
if (!IS_DESKTOP) {
isRepulsing = false;
isAttracting = false;
}
if (button == Buttons.RIGHT) {
isAttracting = false;
}
if (button == Buttons.MIDDLE) {
isRepulsing = false;
}
// if a mouse joint exists we simply destroy it
if (mouseJoint != null) {
if (dragVelocity.len() > 1)
mouseJoint.getBodyB().setLinearVelocity(dragVelocity.scl(50000));
world.destroyJoint(mouseJoint);
mouseJoint = null;
}
hitBody = null;
dragVelocity.set(0, 0);
if (pointer == 1 || pointer == 3) {
if (pointer == 3)
enableBox2DCollisions = !enableBox2DCollisions;
if (pointer == 1)
bgMode = !bgMode;
// if (shapes)
// dropRadiusK = 1.3f;
// else
// dropRadiusK = 2.5f;
// dropRadius = 0.1f + dropRadiusK;
// dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
// dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
// dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
else if (pointer == 2) {
emitType ++;
if (emitType > 3)
emitType = 1;
for (Particle p : particles)
p.type = emitType;
}
return false;
}
@Override
public void dispose() {
super.dispose();
particles.clear();
}
@Override
public void hide() {
super.hide();
particles.clear();
}
}
<|start_filename|>fluid-simulator-android/src/com/fluidsimulator/FluidSimulatorActivity.java<|end_filename|>
package com.fluidsimulator;
import com.badlogic.gdx.backends.android.AndroidApplication;
public class FluidSimulatorActivity extends AndroidApplication {
public void onCreate (android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize(new FluidSimulatorStarter(), true);
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/FluidSimulatorMPM.java<|end_filename|>
package com.fluidsimulator;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.joints.MouseJoint;
import com.badlogic.gdx.physics.box2d.joints.MouseJointDef;
import com.fluidsimulator.gameobjects.Particle;
import com.fluidsimulator.gameobjects.Piece;
import com.fluidsimulator.utils.Vector2;
public class FluidSimulatorMPM extends FluidSimulatorGeneric {
// MPM
private MPMSolver mpmSolver;
// FPS Management
private float TICKS_PER_SECOND = IS_DESKTOP ? 60 : 50;
private float SKIP_TICKS = 1 / TICKS_PER_SECOND;
private float FIXED_DELTA = 1.0f / 60.0f;
private final int MAX_FRAMESKIP = 1;
private int speedMultiplier = IS_DESKTOP ? 1 : 1;
// Tune theses for platform specific behaviors
private float GRAVITY_FORCE = IS_DESKTOP ? -50.0f : -50.0f;
private final Vector2 gravityVect = new Vector2(0.0f, GRAVITY_FORCE);
// Simulation management
// Most of these can be tuned at runtime with F1-F10 and keys 1-0 (no numpad)
private float DAMPING = 0.99f;
private float EMITTER_FORCE = 10;
private float EMITTER_SIZE = 5;
private final int PARTICLE_SIZE = 5;
private float dropRadiusK = 0.9f;
// Modes
private int emitType = 2;
private boolean slowMotion = false;
private boolean hudEnabled = IS_DESKTOP ? true : false;
private boolean render3D = false;
private boolean whiteBackground = false;
public FluidSimulatorMPM(FluidSimulatorStarter fluidSimulatorStarter) {
super(fluidSimulatorStarter);
camera.position.set(WORLD_WIDTH/2, WORLD_HEIGHT/2, 0);
camera3D.position.set(240, 130f, 250f);
camera3D.lookAt(240,140f,00);
camera3D.update();
setupPieces();
// MPM
BOX_WIDTH = IS_DESKTOP ? 480 : 240;
BOX_HEIGHT = IS_DESKTOP ? 320 : 180;
BOX_WIDTH_HALF = BOX_WIDTH / 2;
BOX_HEIGHT_HALF = BOX_HEIGHT / 2;
mpmSolver = new MPMSolver(BOX_WIDTH, BOX_HEIGHT, 50, 200);
}
private void createWorld() {
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropTexture = new Texture("data/fluid_drop_64.png");
dropTexture2 = new Texture("data/fluid_drop_64.png");
dropSprite = new Sprite(dropTexture);
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
if (IS_DESKTOP) {
disposableParticles = new ArrayList<Particle>(SIZE);
}
defaultShader = new ShaderProgram(Gdx.files.internal("data/shaders/default.vert").readString(),
Gdx.files.internal("data/shaders/default.frag").readString());
if (!defaultShader.isCompiled()) {
Gdx.app.log("SHADER_LOG", "couldn't compile default shader: " + defaultShader.getLog());
}
defaultIMShader = new ShaderProgram(Gdx.files.internal("data/shaders/defaultim.vert").readString(),
Gdx.files.internal("data/shaders/defaultim.frag").readString());
if (!defaultIMShader.isCompiled()) {
Gdx.app.log("SHADER_LOG", "couldn't compile default IM shader: " + defaultIMShader.getLog());
}
ShaderProgram.pedantic = false;
refractionShader = new ShaderProgram(Gdx.files.internal("data/shaders/refract.vert").readString(),
Gdx.files.internal("data/shaders/refract.frag").readString());
if (!refractionShader.isCompiled()) {
Gdx.app.log("SHADER_LOG", "couldn't compile refraction shader: " + refractionShader.getLog());
}
irt.setShader(defaultIMShader);
bgTexture = new Texture("data/bg.png");
glossMapTexture = new Texture("data/gloss_map2.png");
displacementMap = new Texture("data/water1.png");
displacementMap2 = new Texture("data/water2.png");
bgSprite = new Sprite(bgTexture);
bgSprite.setBounds(0, -1, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() + 1);
// createPiece(17, 0, 150, 0, 0, 0, false, true, true);
createPiece(17, 100, 240, 0, 0, 0, false, true, true);
// createPortalIn(-140, 65, 0, 0, false, true);
// createPortalOut(-140, 220, 0, 0, false, true);
// Boxes
createPiece(6, 0, 160, 0, 0, 0, false, false, true);
createPiece(14, -150, 200, 0, 0, 0, false, false, true);
createPiece(14, 0, 140, 0, 0, 0, false, false, true);
createPiece(14, -170, 60, 90, 0, 0, false, false, true);
// Ball
createPiece(4, 100, 100, 0, -20, 0, false, false, true);
// Ground cage
createPiece(18, -BOX_WIDTH/2 + 7, BOX_HEIGHT/2, 0, 0, 0, 0.2f, 0.5f, false, false, true);
createPiece(18, BOX_WIDTH/2 - 10, BOX_HEIGHT/2, 0, 0, 0, 0.2f, 0.5f, false, false, true);
createPiece(18, 0, INITIAL_HEIGHT, 90, 0, 0, 0.2f, 0.5f, false, false, true);
createPiece(18, 0, BOX_HEIGHT - 10, 90, 0, 0, 0.2f, 0.5f, false, false, true);
// Ground body for mousejoint
BodyDef bodyDef = new BodyDef();
// bodyDef.type = BodyType.StaticBody;
groundBody = world.createBody(bodyDef);
}
@Override
public void show() {
super.show();
createWorld();
}
public void performLogic(float deltaTime) {
if (!firstRender)
return;
if (IS_DESKTOP && !isDragging)
spawnParticles(deltaTime);
time = System.currentTimeMillis();
// mpmSolver.simulate();
mpmSolver.simulateSimple();
if (DEBUG_ENABLED)
System.out.print("\t fluid: " + (System.currentTimeMillis() - time));
// Gravity change with mobile accelerometer
// if (Gdx.input.isPeripheralAvailable(Peripheral.Accelerometer) && (Gdx.input.getAccelerometerX() >= 0 || Gdx.input.getAccelerometerY() >= 0)) {
// gravityVect.set(-Gdx.input.getAccelerometerY() * GRAVITY_FORCE * 0.5f,Gdx.input.getAccelerometerX() * GRAVITY_FORCE * 0.5f);
// }
}
private void spawnParticles(float deltaTime) {
if (touching && !isAttracting && !isRepulsing) {
if (!((testPoint2D.x < (-BOX_WIDTH / 2 + wpadding) || testPoint2D.x > (BOX_WIDTH / 2 - wpadding))
|| (testPoint2D.y < (INITIAL_HEIGHT + hpadding) || testPoint2D.y > (BOX_HEIGHT - hpadding)))) {
for (float i = -EMITTER_SIZE; i < EMITTER_SIZE; i += 10.0f) {
for (float j = -EMITTER_SIZE; j < EMITTER_SIZE; j += 5.0f) {
mpmSolver.addParticle((int)(testPoint2D.x + i), WORLD_HEIGHT - (int)(testPoint2D.y - j), 0);
}
}
}
mpmSolver.particleArray = mpmSolver.particles.toArray(mpmSolver.particleArray);
}
}
@Override
public void render(float deltaTime) {
firstRender = true;
timeStep += deltaTime;
stepped = false;
loops = 0;
while (timeStep > nextGameTick
&& loops < MAX_FRAMESKIP) {
for (speedCounter = 0; speedCounter < speedMultiplier; speedCounter++) {
performLogic(FIXED_DELTA);
if (IS_DESKTOP) {
deleteOutOfBoundsParticles();
}
}
stepped = true;
nextGameTick += slowMotion ? SKIP_TICKS * 3 : SKIP_TICKS;
loops++;
}
// interpolation = slowMotion ? (timeStep + (SKIP_TICKS*3) - nextGameTick) / (SKIP_TICKS*3)
// : (timeStep + SKIP_TICKS - nextGameTick) / SKIP_TICKS;
long renderTime = System.currentTimeMillis();
camera.update();
if (gl == null) {
gl = Gdx.gl20;
}
if (whiteBackground)
gl.glClearColor(1, 1, 1, 1);
else
gl.glClearColor(0, 0, 0, 1);
gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// Begin Batch
gl.glDisable(GL20.GL_BLEND);
if (hudEnabled) {
if (whiteBackground)
font.setColor(0, 0, 0, 1);
else
font.setColor(1, 1, 1, 1);
batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.begin();
font.draw(batch,
"fps:" + Gdx.graphics.getFramesPerSecond()
+ ", particles: " + (mpmSolver.particles.size()), 0, Gdx.graphics.getHeight() - 40);
font.draw(batch, "deltaTime: " + deltaTime, 0, Gdx.graphics.getHeight() - 20);
font.draw(batch, "pressure: " + (totalPressure - lastTotalPressure), 0, Gdx.graphics.getHeight());
font.draw(batch, "(SPACE) Fluid Type: " + emitType
+ " (+/-) Gravity: " + GRAVITY_FORCE
+ " (UP/DOWN) Emitter: " + EMITTER_SIZE
+ " (S) Slow: "
+ slowMotion, 180.0f, Gdx.graphics.getHeight());
font.draw(batch,"Rad: " + dropRadiusK
+ " Step: " + FIXED_DELTA
+ " DAMP: " + DAMPING, 180, Gdx.graphics.getHeight() - 20);
font.draw(batch,"camera3D: " + camera3D.position, 180, Gdx.graphics.getHeight() - 40);
font.draw(batch,"M: " + mpmSolver.materials.get(0).mass
+ " D: " + mpmSolver.materials.get(0).restDensity
+ " Stiff: " + mpmSolver.materials.get(0).stiffness
+ " BVisc: " + mpmSolver.materials.get(0).bulkViscosity
+ " SurfTens: " + mpmSolver.materials.get(0).surfaceTension
+ " Elastic: " + mpmSolver.materials.get(0).kElastic
+ " Deform: " + mpmSolver.materials.get(0).maxDeformation
+ " Melt: " + mpmSolver.materials.get(0).meltRate
+ " Visc: " + mpmSolver.materials.get(0).viscosity
+ " Damping: " + mpmSolver.materials.get(0).damping
+ " Friction: " + mpmSolver.materials.get(0).friction
+ " Smoothing: " + mpmSolver.materials.get(0).smoothing
+ " Grav: " + mpmSolver.materials.get(0).gravity, 180, Gdx.graphics.getHeight() - 60);
batch.end();
}
//3D
if (render3D) {
// Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// camera3D.update();
camController.update();
modelBatch.begin(camera3D);
for (MPMSolver.Particle p : mpmSolver.particles) {
dropCoordinate.set((float)p.x - dropRadius,
WORLD_HEIGHT - (float)p.y - dropRadius, 0.0f);
instance.transform.setToTranslation(dropCoordinate.x, dropCoordinate.y, 0);
modelBatch.render(instance, environment);
}
modelBatch.end();
}
else {
batch.setProjectionMatrix(camera.combined);
batch.setColor(0, 1, 0, 1);
batch.begin();
for (MPMSolver.Particle p : mpmSolver.particles) {
dropCoordinate.set((float)p.x - dropRadius,
WORLD_HEIGHT - (float)p.y - dropRadius, 0.0f);
// if (p.mat.materialIndex == 0)
// batch.setColor(0, 0, 1, 1);
// else if (p.mat.materialIndex == 1)
// batch.setColor(0, 1, 0, 1);
// else if (p.mat.materialIndex == 2)
// batch.setColor(1, 0, 0, 1);
batch.draw(dropTexture2, dropCoordinate.x, dropCoordinate.y, dropRadiusPixel, dropRadiusPixel);
}
batch.end();
}
if (DEBUG_ENABLED)
System.out.print("\t render: " + (System.currentTimeMillis() - renderTime));
// Exit the application if ESC has been pressed
if (exitApp) {
Gdx.app.exit();
}
}
@Override
public boolean keyUp(int keycode) {
// dropRadiusK
if (keycode == Input.Keys.F8 && dropRadiusK < 3.5f) {
dropRadiusK += 0.2f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
} else if (keycode == Input.Keys.NUM_8 && dropRadiusK >= 0.3f) {
dropRadiusK -= 0.2f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
if (keycode == Input.Keys.BACKSPACE && isAttracting) {
mpmSolver.particles.clear();
} else if (keycode == Input.Keys.BACKSPACE && IS_DESKTOP) {
mpmSolver.particles.clear();
}
// Change Particle color
if (keycode == Input.Keys.SPACE) {
emitType += 1;
if (emitType > 3) {
emitType = 1;
}
}
// Increase/Decrease Gravity
if ((keycode == Input.Keys.PLUS) && (GRAVITY_FORCE > -60.0f)) {
GRAVITY_FORCE -= 1.0f;
gravityVect.set(0.0f, GRAVITY_FORCE);
} else if ((keycode == Input.Keys.MINUS) && (GRAVITY_FORCE < 0.0f)) {
GRAVITY_FORCE += 1.0f;
// if (GRAVITY_FORCE > -0.2f)
// GRAVITY_FORCE = 0.0f;
gravityVect.set(0.0f, GRAVITY_FORCE);
}
// Increase/Decrease Emitter Size
if ((keycode == Input.Keys.DOWN) && (EMITTER_SIZE > 2)) {
EMITTER_SIZE -= 3;
} else if ((keycode == Input.Keys.UP) && (EMITTER_SIZE < 20)) {
EMITTER_SIZE += 3;
}
// Enable/Disable Stop Motion
if (keycode == Input.Keys.S)
slowMotion = !slowMotion;
// Enable/Disable HUD
if (keycode == Input.Keys.H)
hudEnabled = !hudEnabled;
// Enable/Disable Particle Rendering
if (keycode == Input.Keys.R) {
render3D = !render3D;
}
// Enable/Disable White Background
if (keycode == Input.Keys.X)
whiteBackground = !whiteBackground;
if (keycode == Keys.PAGE_UP) {
FIXED_DELTA += 0.004f;
}
if (keycode == Keys.PAGE_DOWN) {
FIXED_DELTA -= 0.004f;
if (FIXED_DELTA <= 0.016f)
FIXED_DELTA = 0.016f;
}
// Exit
if (keycode == Input.Keys.ESCAPE) {
exitApp = true;
}
if (keycode == Input.Keys.CONTROL_LEFT) {
isDragging = false;
}
if (keycode == Input.Keys.CONTROL_RIGHT) {
DAMPING += 0.01f;
}
else if (keycode == Input.Keys.ALT_RIGHT) {
DAMPING -= 0.01f;
}
// MPM
// MASS
if (keycode == Input.Keys.F1) {
mpmSolver.materials.get(0).mass += 0.1f;
} else if (keycode == Input.Keys.NUM_1 && mpmSolver.materials.get(0).mass > 0) {
mpmSolver.materials.get(0).mass -= 0.1f;
}
// REST DENSITY
else if (keycode == Input.Keys.F2)
mpmSolver.materials.get(0).restDensity += 0.2f;
else if (keycode == Input.Keys.NUM_2 && mpmSolver.materials.get(0).restDensity > 0)
mpmSolver.materials.get(0).restDensity -= 0.2f;
// STIFFNESS
else if (keycode == Input.Keys.F3)
mpmSolver.materials.get(0).stiffness += 0.1f;
else if (keycode == Input.Keys.NUM_3 && mpmSolver.materials.get(0).stiffness > 0f)
mpmSolver.materials.get(0).stiffness -= 0.1f;
// BULK VISCOSITY
else if (keycode == Input.Keys.F4) {
mpmSolver.materials.get(0).bulkViscosity += 0.1f;
} else if (keycode == Input.Keys.NUM_4 && mpmSolver.materials.get(0).bulkViscosity > 0) {
mpmSolver.materials.get(0).bulkViscosity -= 0.1f;
}
// SURFACE TENSION
else if (keycode == Input.Keys.F5) {
mpmSolver.materials.get(0).surfaceTension += 0.1f;
} else if (keycode == Input.Keys.NUM_5 && mpmSolver.materials.get(0).surfaceTension > 0) {
mpmSolver.materials.get(0).surfaceTension -= 0.1f;
}
// ELASTICITY
if (keycode == Input.Keys.F6) {
mpmSolver.materials.get(0).kElastic += 0.1f;
} else if (keycode == Input.Keys.NUM_6 && mpmSolver.materials.get(0).kElastic > 0) {
mpmSolver.materials.get(0).kElastic -= 0.1f;
}
// MAX DEFORMATION
if (keycode == Input.Keys.F7) {
mpmSolver.materials.get(0).maxDeformation += 0.1f;
} else if (keycode == Input.Keys.NUM_7 && mpmSolver.materials.get(0).maxDeformation > 0) {
mpmSolver.materials.get(0).maxDeformation -= 0.1f;
}
// MELT RATE
if (keycode == Input.Keys.F8) {
mpmSolver.materials.get(0).meltRate += 0.1f;
} else if (keycode == Input.Keys.NUM_8 && mpmSolver.materials.get(0).meltRate > 0) {
mpmSolver.materials.get(0).meltRate -= 0.1f;
}
// VISCOSITY
if (keycode == Input.Keys.F9)
mpmSolver.materials.get(0).viscosity += 0.01f;
else if (keycode == Input.Keys.NUM_9 && mpmSolver.materials.get(0).viscosity > 0)
mpmSolver.materials.get(0).viscosity -= 0.01f;
// DAMPING
if (keycode == Input.Keys.F10)
mpmSolver.materials.get(0).damping += 0.001f;
else if (keycode == Input.Keys.NUM_0 && mpmSolver.materials.get(0).damping > 0)
mpmSolver.materials.get(0).damping -= 0.001f;
// FRICTION
if (keycode == Input.Keys.F11)
mpmSolver.materials.get(0).friction += 0.1f;
else if (keycode == Input.Keys.LEFT && mpmSolver.materials.get(0).friction > 0)
mpmSolver.materials.get(0).friction -= 0.1f;
// SMOOTHING
if (keycode == Input.Keys.F12)
mpmSolver.materials.get(0).smoothing += 0.1f;
else if (keycode == Input.Keys.RIGHT && mpmSolver.materials.get(0).smoothing > 0)
mpmSolver.materials.get(0).smoothing -= 0.1f;
// GRAV
if ((keycode == Input.Keys.PLUS) && (mpmSolver.materials.get(0).gravity < 0.9f)) {
mpmSolver.materials.get(0).gravity += 0.03f;
} else if ((keycode == Input.Keys.MINUS) && (mpmSolver.materials.get(0).gravity > 0.0f)) {
mpmSolver.materials.get(0).gravity -= 0.03f;
if (mpmSolver.materials.get(0).gravity < 0)
mpmSolver.materials.get(0).gravity = 0;
}
return false;
}
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
touching = true;
camera.unproject(testPoint.set(x, y, 0));
testPoint2D.x = testPoint.x;
testPoint2D.y = testPoint.y;
oldDragPos.set(testPoint2D);
if (button == Buttons.LEFT) {
// MPM
mpmSolver.pressed = true;
mpmSolver.mx = (int)testPoint2D.x;
mpmSolver.my = BOX_HEIGHT - (int)testPoint2D.y;
// Drag Mode
if (isDragging) {
for (Piece piece : pieces.values()) {
hitBody = null;
if (piece.body.getFixtureList().get(0).testPoint(testPoint2D)) {
hitBody = piece.body;
if (hitBody.getType() == BodyType.KinematicBody || hitBody.getType() == BodyType.StaticBody)
continue;
MouseJointDef def = new MouseJointDef();
def.bodyA = groundBody;
def.bodyB = hitBody;
def.collideConnected = true;
def.target.set(testPoint2D);
def.maxForce = 10.0f * hitBody.getMass();
mouseJoint = (MouseJoint)world.createJoint(def);
hitBody.setAwake(true);
break;
}
}
if (mouseJoint != null)
return false;
}
if (!IS_DESKTOP) {
isRepulsing = true;
isAttracting = false;
} else {
isAttracting = false;
isRepulsing = false;
}
}
if (button == Buttons.RIGHT) {
isAttracting = true;
}
if (button == Buttons.MIDDLE) {
isRepulsing = true;
}
return false;
}
@Override
public boolean touchDragged(int x, int y, int pointer) {
camera.unproject(testPoint.set(x, y, 0));
testPoint2D.x = testPoint.x;
testPoint2D.y = testPoint.y;
// MPM Fluid interaction
mpmSolver.mx = (int)testPoint2D.x;
mpmSolver.my = BOX_HEIGHT - (int)testPoint2D.y;
dragVelocity.set(testPoint2D);
dragVelocity.sub(oldDragPos);
oldDragPos.set(testPoint2D);
if (mouseJoint != null) {
mouseJoint.setTarget(target.set(testPoint2D));
mouseJoint.getBodyB().setLinearVelocity(0, 0);
mouseJoint.getBodyB().setTransform(testPoint2D.x, testPoint2D.y, 0);
}
return false;
}
@Override
public boolean touchUp(int x, int y, int pointer, int button) {
touching = false;
// MPM Fluid interaction
mpmSolver.pressed = false;
if (!IS_DESKTOP) {
isRepulsing = false;
isAttracting = false;
}
if (button == Buttons.RIGHT) {
isAttracting = false;
}
if (button == Buttons.MIDDLE) {
isRepulsing = false;
}
// if a mouse joint exists we simply destroy it
if (mouseJoint != null) {
if (dragVelocity.len() > 1)
mouseJoint.getBodyB().setLinearVelocity(dragVelocity.scl(50000));
world.destroyJoint(mouseJoint);
mouseJoint = null;
}
hitBody = null;
dragVelocity.set(0, 0);
if (pointer == 2) {
emitType ++;
if (emitType > 3)
emitType = 1;
}
return false;
}
@Override
public void dispose() {
super.dispose();
}
@Override
public void hide() {
super.hide();
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/MathUtils.java<|end_filename|>
package com.fluidsimulator;
public class MathUtils extends com.badlogic.gdx.math.MathUtils {
public final static float map(final float val, final float fromMin, final float fromMax, final float toMin,
final float toMax) {
// final float mult = (val - fromMin) / (fromMax - fromMin);
// final float res = toMin + mult * (toMax - toMin);
// return res;
return toMin + ((val - fromMin) / (fromMax - fromMin)) * (toMax - toMin);
}
}
<|start_filename|>fluid-simulator/bin/data/shaders/defaultim.frag<|end_filename|>
#ifdef GL_ES
precision mediump float;
#endif
varying vec4 v_col;
varying vec3 Position;
varying vec2 v_tex0;
uniform sampler2D u_sampler0;
uniform sampler2D Texture;
uniform sampler2D glossMap;
uniform sampler2D displacementMap;
uniform sampler2D displacementMap2;
uniform float ScreenResX, ScreenResY;
uniform float deltaTime;
uniform float time;
uniform float rippleIntensity;
//uniform float Alpha;
//
// fresnel approximation
// F(a) = F(0) + (1- cos(a))^5 * (1- F(0))
//
// Calculate fresnel term. You can approximate it
// with 1.0-dot(normal, viewpos).
//
float fast_fresnel(vec3 I, vec3 N, vec3 fresnelValues) {
float bias = fresnelValues.x;
float power = fresnelValues.y;
float scale = 1.0 - bias;
return bias + pow(1.0 - dot(I, N), power) * scale;
}
float very_fast_fresnel(vec3 I, vec3 N) {
return 1.0 - dot(N, I);
}
void main() {
const float Alpha = 0.01;
const vec3 Normal = vec3(0, 0, 1);
const vec3 fresnelValues = vec3(0.15, 2.0, 0);
const vec3 IoR_Values = vec3(1.14, 1.12, 1.10);
// Screen to texture coordinate
vec2 PixelTexCoords = vec2(gl_FragCoord.x / ScreenResX, 1.0 - gl_FragCoord.y / ScreenResY);
vec2 PixelTexCoordsDeltaPlus = vec2(fract(PixelTexCoords.x - time*0.01), PixelTexCoords.y);
vec2 PixelTexCoordsDeltaMinus = vec2(fract(PixelTexCoords.x + time*0.03), PixelTexCoords.y);
// ripple deformation texture coordinates
vec2 cPos = -1.0 + 2.0 * PixelTexCoords;
float cLength = length(cPos);
vec2 uv = (cPos/cLength) * cos(cLength * 12.0 - time * 4.0) * rippleIntensity;
//vec3 ripple_color = texture2D(Texture, uv).rgb;
// Base Color
vec3 base_color = v_col.rgb;
// Reflection
vec3 reflVec = normalize(reflect(Position, Normal));
//vec3 reflectColor = texture2D(Texture, PixelTexCoords + reflVec.xy*0.1).rgb;
vec3 reflectColor = texture2D(Texture, PixelTexCoords + uv).rgb;
// Refraction
vec3 Refract = normalize(refract(Position, Normal, 1.20));
/*Refract.x = normalize(refract(Position, Normal, IoR_Values.x)).x;
Refract.y = normalize(refract(Position, Normal, IoR_Values.y)).y;
Refract.z = normalize(refract(Position, Normal, IoR_Values.z)).z;*/
vec3 refractColor;
//refractColor = mix(texture2D(Texture, PixelTexCoords + Refract.xy*0.05), v_col, Alpha).rgb * v_col.rgb;
refractColor = mix(texture2D(Texture, PixelTexCoords + uv), v_col, Alpha).rgb * v_col.rgb;
// Do a gloss map look up and compute the reflectivity.
vec3 gloss_color = texture2D(glossMap, PixelTexCoords + v_tex0 * 0.06).rgb;
float reflectivity = (gloss_color.r + gloss_color.g + gloss_color.b)/3.0;
reflectivity += 0.2;
reflectivity = 0.9;
// Generic Noise displacements
vec3 displacement_color = texture2D(displacementMap, PixelTexCoordsDeltaPlus + v_tex0 * 0.02).rgb;
float displacement = (displacement_color.r + displacement_color.g + displacement_color.b)/3.0;
vec3 displacement_color2 = texture2D(displacementMap2, PixelTexCoords + v_tex0 * 0.03).rgb;
float displacement2 = (displacement_color2.r + displacement_color2.g + displacement_color2.b)/3.0;
displacement += 0.2;
displacement2 += 0.2;
//displacement2 = displacement2 > 1.0 ? 1.0 : displacement2;
// Find the Fresnel term
//float fresnelTerm = fast_fresnel(-Position, Normal, fresnelValues);
float fresnelTerm = very_fast_fresnel(-Position, Normal);
// Apply Fresnel
vec3 color = mix(refractColor, reflectColor, fresnelTerm).rgb;
// Apply Displacements
color = mix(base_color, color, displacement).rgb;
color = mix(base_color, color, displacement2).rgb;
// Apply Gloss Map reflectivity
vec3 final_color = mix(base_color, color, reflectivity);
// Final Color
//final_color = mix(final_color, v_col, Alpha);
gl_FragColor = vec4(final_color, v_col.a * texture2D(u_sampler0, v_tex0).a);
}
<|start_filename|>fluid-simulator/bin/data/shaders/defaultim.vert<|end_filename|>
attribute vec4 a_position;
attribute vec3 a_normal;
attribute vec4 a_color;
attribute vec2 a_texCoord0;
uniform mat4 u_projModelView;
varying vec4 v_col;
varying vec3 Position;
varying vec2 v_tex0;
void main() {
Position = vec3(u_projModelView * a_position);
gl_Position = u_projModelView * a_position;
v_col = a_color;
v_tex0 = a_texCoord0;
gl_PointSize = 1.0;
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/FluidSimulator.java<|end_filename|>
package com.fluidsimulator;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.joints.MouseJoint;
import com.badlogic.gdx.physics.box2d.joints.MouseJointDef;
import com.fluidsimulator.gameobjects.Particle;
import com.fluidsimulator.gameobjects.Piece;
import com.fluidsimulator.gameobjects.SpatialTable;
import com.fluidsimulator.pbf.Box;
import com.fluidsimulator.utils.Vector2;
public class FluidSimulator extends FluidSimulatorGeneric {
// Thread Management
// TODO: Real multithreaded behavior
private Timer timer;
private Thread thread;
private Thread thread2;
private Thread thread3;
private Thread thread4;
private boolean threadRunning = true;
// FPS Management
private float TICKS_PER_SECOND = IS_DESKTOP ? 60 : 50;
private float SKIP_TICKS = 1 / TICKS_PER_SECOND;
private float FIXED_DELTA = 1.0f / 60.0f;
private final int MAX_FRAMESKIP = 1;
private int speedMultiplier = IS_DESKTOP ? 2 : 1;
// Tune theses for platform specific behaviors
private float GRAVITY_FORCE = IS_DESKTOP ? -50.0f : -50.0f;
private final Vector2 gravityVect = new Vector2(0.0f, GRAVITY_FORCE);
// Particles arrays and spatial table
private SpatialTable particles = new SpatialTable(40, 40, IS_DESKTOP ? SIZE : ANDROID_SIZE) {
@Override
protected int posX(Particle value) {
return (int) MathUtils.map(value.pos.x, -BOX_WIDTH_HALF, BOX_WIDTH_HALF, 0, 40-.001f);
// return (int) ((value.pos.x + BOX_WIDTH_HALF + 0.3f) / CELL_SIZE);
}
@Override
protected int posY(Particle value) {
// return (int) ((value.pos.y + BOX_HEIGHT_HALF + 0.3f) / CELL_SIZE);
return (int) MathUtils.map(value.pos.y, INITIAL_HEIGHT, BOX_HEIGHT, 0, 40-.001f);
}
@Override
protected int prevPosX(Particle value) {
return (int) ((value.prevPos.x + BOX_WIDTH_HALF + 0.3f) / CELL_SIZE);
}
@Override
protected int prevPosY(Particle value) {
return (int) ((value.prevPos.y + BOX_HEIGHT_HALF + 0.3f) / CELL_SIZE);
}
@Override
protected void setPrevGridPos(Particle value, int x, int y) {
value.prevGridPos.set(x, y);
}
@Override
protected int getPrevGridPosX(Particle value) {
return (int)value.prevGridPos.x;
}
@Override
protected int getPrevGridPosY(Particle value) {
return (int)value.prevGridPos.y;
}
@Override
protected void savePosX(Particle value, int x) {
value.gridPosX = x;
}
@Override
protected void savePosY(Particle value, int y) {
value.gridPosY = y;
}
@Override
protected int getPosX(Particle value) {
return value.gridPosX;
}
@Override
protected int getPosY(Particle value) {
return value.gridPosY;
}
@Override
protected int getHash(Particle value) {
return value.hash;
}
};
// Simulation management
// Most of these can be tuned at runtime with F1-F10 and keys 1-0 (no numpad)
private int CELL_SIZE = 2;
private float H = 60.0f;
private float H2 = H * H;
private float RAD = 8.0f;
private float VISC = 0.001f;
private float MULTIPLIER = 50 / RAD;
private float K = 0.004f;
private float K_ = 1.01f;
private float SIGMA = 2;
private float P0 = 310.0f;
private final float ATTRACT_FORCE = 1.66f;
private float ATTRACT_RANGE = H2 / 2;
private final float REPULSE_FORCE = H / 2;
private float REPULSE_RANGE = H2 / 4;
private float DAMPING = 0.99f;
private float EMITTER_FORCE = 10;
private float EMITTER_SIZE = 5;
private final float STICKINESS_DIST = 5.0f;
private final float STICKINESS_DIST2 = STICKINESS_DIST * STICKINESS_DIST;
private float K_STICKINESS = 7.0f;
private final float WET_FRICTION = 0.0f;
private final float WET_RESTITUTION = 1.0f;
private final int PARTICLE_SIZE = 5;
private float dropRadiusK = 1.5f;
// Temp variables mostly for calculations and graphics processing purpose
private float[] qArray = new float[particles.MAX_NEIGHBORS];
private float[] qqArray = new float[particles.MAX_NEIGHBORS];
private float deltaTime2 = FIXED_DELTA * FIXED_DELTA;
// Modes
private int emitType = 2;
private boolean expandMode = false;
private boolean massMode = false;
private boolean slowMotion = false;
private boolean crazyMode = false;
private boolean hudEnabled = IS_DESKTOP ? true : false;
private boolean pbfEnabled = true; //Leave this to true
private boolean shapes = IS_DESKTOP ? false : true;
private boolean render3D = false;
private boolean linesMode = false;
private boolean smokeMode = false;
private boolean whiteBackground = false;
private boolean particleRendering = true;
private boolean enableBox2DCollisions = false;
private boolean glowMode = false;
private boolean bgMode = false;
public FluidSimulator(FluidSimulatorStarter fluidSimulatorStarter) {
super(fluidSimulatorStarter);
setupPieces();
}
private void createWorld() {
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropTexture = new Texture("data/fluid_drop_64.png");
dropTexture2 = new Texture("data/fluid_drop_64.png");
dropSprite = new Sprite(dropTexture);
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
if (IS_DESKTOP) {
disposableParticles = new ArrayList<Particle>(SIZE);
}
defaultShader = new ShaderProgram(Gdx.files.internal("data/shaders/default.vert").readString(),
Gdx.files.internal("data/shaders/default.frag").readString());
if (!defaultShader.isCompiled()) {
Gdx.app.log("SHADER_LOG", "couldn't compile default shader: " + defaultShader.getLog());
}
defaultIMShader = new ShaderProgram(Gdx.files.internal("data/shaders/defaultim.vert").readString(),
Gdx.files.internal("data/shaders/defaultim.frag").readString());
if (!defaultIMShader.isCompiled()) {
Gdx.app.log("SHADER_LOG", "couldn't compile default IM shader: " + defaultIMShader.getLog());
}
ShaderProgram.pedantic = false;
refractionShader = new ShaderProgram(Gdx.files.internal("data/shaders/refract.vert").readString(),
Gdx.files.internal("data/shaders/refract.frag").readString());
if (!refractionShader.isCompiled()) {
Gdx.app.log("SHADER_LOG", "couldn't compile refraction shader: " + refractionShader.getLog());
}
irt.setShader(defaultIMShader);
bgTexture = new Texture("data/bg.png");
glossMapTexture = new Texture("data/gloss_map2.png");
displacementMap = new Texture("data/water1.png");
displacementMap2 = new Texture("data/water2.png");
bgSprite = new Sprite(bgTexture);
bgSprite.setBounds(0, -1, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() + 1);
// On Android populate directly
if (!IS_DESKTOP) {
for (float j = INITIAL_HEIGHT + hpadding + 2; j < BOX_HEIGHT - 2; j += 5.5f) {
for (float i = -BOX_WIDTH / 3; i < BOX_WIDTH / 3; i += 5.5f) {
particles.add(new Particle(i, j, prevHash++));
tempParticle = particles.get(particles.size() - 1);
tempParticle.type = (emitType);
if (particles.size() >= ANDROID_SIZE)
break;
}
if (particles.size() >= ANDROID_SIZE)
break;
}
}
// createPiece(17, 0, 150, 0, 0, 0, false, true, true);
createPiece(17, 100, 240, 0, 0, 0, false, true, true);
// createPortalIn(-140, 65, 0, 0, false, true);
// createPortalOut(-140, 220, 0, 0, false, true);
// Boxes
createPiece(6, 0, 160, 0, 0, 0, false, false, true);
createPiece(14, -150, 200, 0, 0, 0, false, false, true);
createPiece(14, 0, 140, 0, 0, 0, false, false, true);
createPiece(14, -170, 60, 90, 0, 0, false, false, true);
// Ball
createPiece(4, 100, 100, 0, -20, 0, false, false, true);
// Ground cage
createPiece(18, -BOX_WIDTH/2 + 7, BOX_HEIGHT/2, 0, 0, 0, 0.2f, 0.5f, false, false, true);
createPiece(18, BOX_WIDTH/2 - 10, BOX_HEIGHT/2, 0, 0, 0, 0.2f, 0.5f, false, false, true);
createPiece(18, 0, INITIAL_HEIGHT, 90, 0, 0, 0.2f, 0.5f, false, false, true);
createPiece(18, 0, BOX_HEIGHT - 10, 90, 0, 0, 0.2f, 0.5f, false, false, true);
// Ground body for mousejoint
BodyDef bodyDef = new BodyDef();
// bodyDef.type = BodyType.StaticBody;
groundBody = world.createBody(bodyDef);
}
@Override
public void show() {
super.show();
// particles.initialize();
createWorld();
// THREAD
thread = new Thread() {
public void run() {
while (threadRunning) {
stepped = false;
loops = 0;
float deltaTime = System.currentTimeMillis() / 1000f;
timeStep += deltaTime;
// System.out.println(timeStep);
while (timeStep > nextGameTick
&& loops < MAX_FRAMESKIP) {
for (speedCounter = 0; speedCounter < speedMultiplier; speedCounter++) {
performLogic(FIXED_DELTA);
if (IS_DESKTOP) {
prepareDeleteOutOfBoundsParticles();
deleteOutOfBoundsParticles();
}
}
stepped = true;
nextGameTick += slowMotion ? SKIP_TICKS * 3 : SKIP_TICKS;
loops++;
}
try {
Thread.sleep(5);
} catch (InterruptedException e) {}
}
}
};
// thread.start();
timer = new Timer(true);
TimerTask task = new TimerTask() {
public void run() {
performLogic(FIXED_DELTA);
if (IS_DESKTOP) {
prepareDeleteOutOfBoundsParticles();
deleteOutOfBoundsParticles();
}
}
};
// timer.schedule(task, 0, 5);
// thread2 = new Thread() {
// public void run() {
// while (threadRunning) {
// loops2 = 0;
// deltaTime2 = Gdx.graphics.getDeltaTime();
// timeStep2 += deltaTime2;
// while (timeStep2 > nextGameTick2
// && loops2 < MAX_FRAMESKIP) {
// rigidBodiesLogic(deltaTime2);
// if (enableBox2DCollisions) {
// for (Piece piece : pieces.values()) {
// if (piece.isSensor || piece.body.getFixtureList().size() <= 0)
// continue;
// piece.collisionImpulse.set(0, 0);
// synchronized (particles) {
// for (i=0; i<len; i++) {
// // if (particles.get(i).pos.dst2(piece.pos) < 1000)
// box2dFluidSolver(piece, particles.get(i), deltaTime2);
// // box2dFluidSolverTest(piece, particles.get(i), deltaTime);
// }
// }
// if (piece.collisionImpulse.x != 0 && piece.collisionImpulse.y != 0) {
// piece.body.applyForce(piece.collisionImpulse, piece.contactPoint);
// // if (piece.shape instanceof CircleShape)
// piece.body.setAngularDamping(0.8f);
// }
// }
// }
// nextGameTick2 += slowMotion ? SKIP_TICKS * 3 : SKIP_TICKS;
// }
// }
// }
// };
// thread2.start();
initializePBF();
}
// TODO: Query only particles within collision range
public void box2dFluidSolver(Piece piece, Particle particle, float deltaTime) {
if (pbfEnabled) {
particle.posStar.x *= MULTIPLIER;
particle.posStar.y *= MULTIPLIER;
particle.velocity.x *= MULTIPLIER;
particle.velocity.y *= MULTIPLIER;
}
else {
particle.posStar.set(particle.pos);
}
if (particle.rigidBodyHit && particle.contactPieceHash == piece.hash
&& (piece.body.getPosition().dst2(particle.contactPoint) > piece.body.getPosition().dst2(particle.posStar)
|| particle.posStar.dst2(particle.contactPoint) > STICKINESS_DIST2)) {
particle.rigidBodyHit = false;
}
vec2.set(particle.posStar.x + (deltaTime * particle.velocity.x) * 1.5f,
particle.posStar.y + (deltaTime * particle.velocity.y) * 1.5f);
vec4.set(particle.prevPos);
vec4.sub(piece.body.getPosition());
vec4.nor();
vec4.scl(100);
vec3.set(particle.prevPos);
vec3.add(vec4);
if (/*!particle.rigidBodyHit && */vec3.dst2(vec2) > 0
&& (piece.body.getFixtureList().get(0).testPoint(vec2)
/*|| piece.body.getFixtureList().get(0).testPoint(vec2.x + 0.5f, vec2.y + 0.5f)
|| piece.body.getFixtureList().get(0).testPoint(vec2.x - 0.5f, vec2.y + 0.5f)
|| piece.body.getFixtureList().get(0).testPoint(vec2.x - 0.5f, vec2.y - 0.5f)
|| piece.body.getFixtureList().get(0).testPoint(vec2.x + 0.5f, vec2.y - 0.5f)*/)) {
collisionPiece = null;
world.rayCast(rayCastCallback, vec3, vec2);
// if (piece.body.getUserData() != null) {
// collisionPiece = ((ObjectInfo)piece.body.getUserData()).pieceInfo;
// collisionPoint.set(vec2);
// vec2.set(particle.velocity);
// vec2.rotate(180);
// vec2.nor();
// collisionNormal.set(vec2);
// }
if (collisionPiece != null) {
tempVect.set(particle.velocity);
//
particle.posStar.set(particle.lastSafePos);
if (piece.type == BodyType.DynamicBody) {
particle.posStar.set(collisionPoint);
particle.posStar.add(collisionNormal.x * 0.5f, collisionNormal.y * 0.5f);
}
particle.rigidBodyHit = true;
particle.contactPoint.set(collisionPoint);
particle.contactNormal.set(collisionNormal);
particle.contactPieceHash = piece.hash;
// for (Particle p : particles.nearby(particle)) {
// p.rigidBodyHit = true;
// p.contactPoint.set(collisionPoint);
// p.contactNormal.set(collisionNormal);
// p.contactPieceHash = piece.hash;
// }
particle.relativeVelocity.set(particle.velocity.x - particle.prevVelocity.x,
particle.velocity.y - particle.prevVelocity.y);
// Vnormal = (Vrelative . normal) * normal
vec2.set(collisionNormal);
vec2.scl(particle.velocity.dot(collisionNormal));
// Vtangent = Vrelative - Vnormal
vec3.set(particle.velocity.x - vec2.x, particle.velocity.y - vec2.y);
// Calculate impulse
vec1.set(vec2.x * (WET_RESTITUTION + piece.restitution) - ((WET_FRICTION - piece.friction) * vec3.x),
vec2.y * (WET_RESTITUTION + piece.restitution) - ((WET_FRICTION - piece.friction) * vec3.y));
tempVect.sub(vec1);
// Apply impulse
particle.velocity.set(tempVect);
// Re-update position
particle.prevPos.set(particle.posStar);
particle.posStar.set(particle.posStar.x + (deltaTime * particle.velocity.x),
particle.posStar.y + (deltaTime * particle.velocity.y));
if (piece.type == BodyType.DynamicBody) {
vec4.set(collisionNormal);
vec4.rotate(180);
vec4.scl(45000);
// vec1.scl(200);
// vec4.set(vec1);
// System.out.println(vec1.len());
piece.collisionImpulse.add(vec4);
piece.contactPoint.set(collisionPoint);
}
// Particle still inside the body
if (piece.body.getFixtureList().get(0).testPoint(particle.posStar)) {
// System.out.println("asd");
particle.posStar.set(particle.lastSafePos);
particle.prevPos.set(particle.posStar);
}
}
}
else {
// if (!piece.body.getFixtureList().get(0).testPoint(particle.prevPos))
particle.lastSafePos.set(particle.prevPos);
if (particle.rigidBodyHit && particle.contactPieceHash == piece.hash) {
if (piece.isSticky) {
tempVect.set(particle.velocity);
vec2.set(particle.posStar);
vec2.sub(particle.contactPoint);
vec2.nor();
// Calculate stickiness
tempFloat = particle.posStar.dst(particle.contactPoint);
tempFloat = K_STICKINESS * tempFloat * (1 - (tempFloat / STICKINESS_DIST));
if (tempFloat > 0) {
vec2.scl(-tempFloat);
tempVect.add(vec2);
}
// System.out.println(vec2.len());
particle.velocity.set(tempVect);
// Re-update position
particle.prevPos.set(particle.posStar);
particle.posStar.set(particle.posStar.x + (deltaTime * particle.velocity.x),
particle.posStar.y + (deltaTime * particle.velocity.y));
}
}
}
if (pbfEnabled) {
particle.posStar.x /= MULTIPLIER;
particle.posStar.y /= MULTIPLIER;
particle.velocity.x /= MULTIPLIER;
particle.velocity.y /= MULTIPLIER;
}
}
public void performLogic(float deltaTime) {
if (!firstRender)
return;
if (IS_DESKTOP && !isDragging)
spawnParticles(deltaTime);
len = particles.size();
time = System.currentTimeMillis();
if (enableBox2DCollisions) {
// for (Piece piece : pieces.values()) {
// if (piece.isSensor || piece.body.getFixtureList().size() <= 0)
// continue;
// piece.collisionImpulse.set(0, 0);
// for (i=0; i<len; i++) {
// box2dFluidSolver(piece, particles.get(i), deltaTime);
//// box2dFluidSolverTest(piece, particles.get(i), deltaTime);
// }
// if (piece.collisionImpulse.x != 0 && piece.collisionImpulse.y != 0)
// piece.body.applyForce(piece.collisionImpulse, piece.contactPoint);
// }
rigidBodiesLogic(deltaTime);
}
if (DEBUG_ENABLED)
System.out.print("\nrigid: " + (System.currentTimeMillis() - time));
if (!expandMode) {
if (!pbfEnabled) {
for (i=0; i<len; i++) {
mainP = particles.get(i);
// applyGravity(mainP);
mainP.velocity.scl(DAMPING);
mainP.prevPos.set(mainP.pos);
mainP.pos.set(mainP.pos.x + (deltaTime * mainP.velocity.x),
mainP.pos.y + (deltaTime * mainP.velocity.y));
mainP.xs = MULTIPLIER*mainP.pos.x;
mainP.ys = MULTIPLIER*mainP.pos.y;
mainP.vxs = MULTIPLIER*mainP.velocity.x;
mainP.vys = MULTIPLIER*mainP.velocity.y;
mainP.xchange = 0;
mainP.ychange = 0;
}
}
}
time = System.currentTimeMillis();
if (!pbfEnabled) {
if (waitingRehash)
particles.rehash();
waitingRehash = !waitingRehash;
}
if (DEBUG_ENABLED)
System.out.print("\t rehash: " + (System.currentTimeMillis() - time));
// hashLocations();
time = System.currentTimeMillis();
if (!pbfEnabled) {
relaxation2(deltaTime);
// particleArray = particles.table.toArray(particleArray);
// for (i=0; i<len; i++) {
//// mainP = particles.get(i);
// mainP = particleArray[i];
// mainP.density += i+i;
//
// tempParticles = particles.nearby(mainP);
// len2 = tempParticles.size();
// tempParticles2 = particles.nearby(mainP);
// len2 = particles.lastSizeNearby();
//// len2 = 40;
// for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
// neighborP = tempParticles2[a];
// neighborP.density += mainP.density;
//// mainP.density += a+a;
// }
// for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
// neighborP = tempParticles2[a];
// neighborP.density += mainP.density;
//// mainP.density += a+a;
// }
// }
}
else
UpdateFluid(deltaTime);
// pbf.UpdateFluid(particles, box);
if (DEBUG_ENABLED)
System.out.print("\t fluid: " + (System.currentTimeMillis() - time));
// if (enableBox2DCollisions) {
//// rigidBodiesLogic(deltaTime);
// for (Piece piece : pieces.values()) {
// if (piece.isSensor || piece.body.getFixtureList().size() <= 0)
// continue;
// piece.collisionImpulse.set(0, 0);
// for (i=0; i<len; i++) {
//// if (particles.get(i).pos.dst2(piece.pos) < 1000)
// box2dFluidSolver(piece, particles.get(i), deltaTime);
//// box2dFluidSolverTest(piece, particles.get(i), deltaTime);
// }
// if (piece.collisionImpulse.x != 0 && piece.collisionImpulse.y != 0) {
// piece.body.applyForce(piece.collisionImpulse, piece.contactPoint);
//// if (piece.shape instanceof CircleShape)
// piece.body.setAngularDamping(0.8f);
// }
// }
// }
time = System.currentTimeMillis();
if (!pbfEnabled) {
for (i=0; i<len; i++) {
mainP = particles.get(i);
mainP.prevVelocity.set(mainP.velocity);
mainP.velocity.set((mainP.pos.x - mainP.prevPos.x) / deltaTime,
(mainP.pos.y - mainP.prevPos.y) / deltaTime);
if (!enableBox2DCollisions)
wallCollision(mainP);
attract(mainP);
repulse(mainP);
applyGravity(mainP);
if (enableBox2DCollisions) {
portalFluidSolver(mainP, deltaTime);
}
capVelocity(mainP.velocity);
if (IS_DESKTOP)
prepareDeleteOutOfBoundsParticles(mainP);
if (enableBox2DCollisions) {
for (Piece piece : pieces.values()) {
if (piece.isSensor || piece.body.getFixtureList().size <= 0)
continue;
piece.collisionImpulse.set(0, 0);
// if (particles.get(i).pos.dst2(piece.pos) < 1000)
box2dFluidSolver(piece, particles.get(i), deltaTime);
// box2dFluidSolverTest(piece, particles.get(i), deltaTime);
if (piece.collisionImpulse.x != 0 && piece.collisionImpulse.y != 0) {
piece.body.applyForce(piece.collisionImpulse, piece.contactPoint, true);
// if (piece.shape instanceof CircleShape)
piece.body.setAngularDamping(0.8f);
}
}
}
}
}
else {
// for (i=0; i<len; i++) {
// mainP = particles.get(i);
// if (enableBox2DCollisions) {
// portalFluidSolver(mainP, deltaTime);
// }
//// capVelocity(mainP.velocity);
// if (IS_DESKTOP)
// prepareDeleteOutOfBoundsParticles(mainP);
// if (enableBox2DCollisions) {
// for (Piece piece : pieces.values()) {
// if (piece.isSensor || piece.body.getFixtureList().size() <= 0)
// continue;
// piece.collisionImpulse.set(0, 0);
// // if (particles.get(i).pos.dst2(piece.pos) < 1000)
// box2dFluidSolver(piece, particles.get(i), deltaTime);
// // box2dFluidSolverTest(piece, particles.get(i), deltaTime);
// if (piece.collisionImpulse.x != 0 && piece.collisionImpulse.y != 0) {
// piece.body.applyForce(piece.collisionImpulse, piece.contactPoint);
// // if (piece.shape instanceof CircleShape)
// piece.body.setAngularDamping(0.8f);
// }
// }
// }
// }
}
if (DEBUG_ENABLED)
System.out.print("\t fluid/rigid: " + (System.currentTimeMillis() - time));
// Gravity change with mobile accelerometer
// if (Gdx.input.isPeripheralAvailable(Peripheral.Accelerometer) && (Gdx.input.getAccelerometerX() >= 0 || Gdx.input.getAccelerometerY() >= 0)) {
// gravityVect.set(-Gdx.input.getAccelerometerY() * GRAVITY_FORCE * 0.5f,Gdx.input.getAccelerometerX() * GRAVITY_FORCE * 0.5f);
// }
}
private void relaxation2(float deltaT) {
lastTotalPressure = totalPressure;
totalPressure = 0;
// particleArray = particles.table.toArray(particleArray);
for (Particle mainP : particles) {
// for (i=0; i<len; i++) {
// mainP = particleArray[i];
// mainP.velocity.scl(DAMPING);
// mainP.prevPos.set(mainP.pos);
// mainP.pos.set(mainP.pos.x + (deltaT * mainP.velocity.x),
// mainP.pos.y + (deltaT * mainP.velocity.y));
//
// mainP.xs = MULTIPLIER*mainP.pos.x;
// mainP.ys = MULTIPLIER*mainP.pos.y;
// mainP.vxs = MULTIPLIER*mainP.velocity.x;
// mainP.vys = MULTIPLIER*mainP.velocity.y;
// mainP.xchange = 0;
// mainP.ychange = 0;
// tempParticles = particles.nearby(mainP);
// len2 = tempParticles.size();
tempParticles2 = particles.nearby(mainP);
len2 = particles.lastSizeNearby();
// Particle pressure calculated by particle proximity
// Pressures = 0 if all particles within range are H distance away
p = 0.0f;
pnear = 0.0f;
for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
// neighborP = tempParticles.get(a);
neighborP = tempParticles2[a];
vx = neighborP.xs - mainP.xs;
vy = neighborP.ys - mainP.ys;
if(vx > -H && vx < H && vy > -H && vy < H) {
q = (vx * vx + vy * vy);
if(q < H2) {
qArray[a] = (float)Double.longBitsToDouble(((Double.doubleToLongBits(q) >> 32) + 1072632448) << 31);
if (qArray[a] < EPSILON)
qArray[a] = H - 0.01f;
qq = 1.0f - (qArray[a] / H);
qqArray[a] = qq;
qqqq = qq * qq;
p = (p + qqqq);
pnear = (pnear + qqqq*qq);
// qArray[a] = q;
// if (qArray[a] < EPSILON)
// qArray[a] = H2- 0.01f;
// qq = H2 - q;
// p += KPOLY * qq * qq * qq;
// pnear = p;
} else {
qArray[a] = Float.MAX_VALUE;
}
}
}
mainP.density = p;
mainP.constraint = (p / REST_DENSITY) - 1f;
// Now actually apply the forces
pressure = (p - 5f) / 2.0f; //normal pressure term
presnear = (pnear) / 2.0f; //near particles term
changex = 0.0f;
changey = 0.0f;
for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
// neighborP = tempParticles.get(a);
neighborP = tempParticles2[a];
vx = neighborP.xs - mainP.xs;
vy = neighborP.ys - mainP.ys;
if(vx > -H && vx < H && vy > -H && vy < H) {
if(qArray[a] < H) {
// q = qArray[a] / H;
// qq = 1.0f - q;
qq = qqArray[a];
factor = qq * (pressure + presnear * qq) / (2.0f * qArray[a]);
dX = vx * factor;
dY = vy * factor;
relvx = neighborP.vxs - mainP.vxs;
relvy = neighborP.vys - mainP.vys;
factor = VISC * qq * deltaT;
dX -= relvx * factor;
dY -= relvy * factor;
// neighborP.xchange += dX;
// neighborP.ychange += dY;
changex -= dX;
changey -= dY;
neighborP.pos.x += dX / MULTIPLIER;
neighborP.pos.y += dY / MULTIPLIER;
neighborP.velocity.x += dX / (MULTIPLIER*deltaT);
neighborP.velocity.y += dY / (MULTIPLIER*deltaT);
}
}
}
// mainP.xchange += changex;
// mainP.ychange += changey;
mainP.pos.x += changex / MULTIPLIER;
mainP.pos.y += changey / MULTIPLIER;
mainP.velocity.x += changex / (MULTIPLIER*deltaT);
mainP.velocity.y += changey / (MULTIPLIER*deltaT);
totalPressure += mainP.velocity.len2() / 100000;
mainP.drawPos.set(mainP.pos.x, mainP.pos.y);
}
}
private void spawnParticles(float deltaTime) {
if (touching && (!isAttracting) && (!isRepulsing)
&& (particles.size() < SIZE - 1)) {
if (!((testPoint2D.x < (-BOX_WIDTH / 2 + wpadding) || testPoint2D.x > (BOX_WIDTH / 2 - wpadding))
|| (testPoint2D.y < (INITIAL_HEIGHT + hpadding) || testPoint2D.y > (BOX_HEIGHT - hpadding)))) {
for (float i = -EMITTER_SIZE; i < EMITTER_SIZE; i += 10.0f) {
for (float j = -EMITTER_SIZE; j < EMITTER_SIZE; j += 5.0f) {
if (particles.size() >= SIZE - 1)
// if (particles.size() >= 1)
break;
particles.add(new Particle(testPoint2D.x + i, testPoint2D.y - j, prevHash++));
tempParticle = particles.get(particles.size() - 1);
tempParticle.type = (emitType);
if (!enableBox2DCollisions) {
if (emitType == 2)
tempParticle.mass = 2;
else if (emitType == 3)
tempParticle.mass = 3;
}
tempParticle.velocity.set(tempParticle.velocity.x,
tempParticle.velocity.y - EMITTER_FORCE * deltaTime);
}
}
}
}
}
private void applyGravity(Particle pi) {
if (massMode)
pi.velocity.set(pi.velocity.x + (gravityVect.x * pi.mass), pi.velocity.y
+ (gravityVect.y * pi.mass));
else
pi.velocity.set(pi.velocity.x + (gravityVect.x), pi.velocity.y
+ (gravityVect.y));
}
private void attract(Particle pi) {
if (isAttracting) {
if (pi.pos.dst2(testPoint2D) > ATTRACT_RANGE)
return;
attract_vect.set(testPoint2D);
attract_vect.sub(pi.pos);
pi.velocity.set(pi.velocity.x
+ (attract_vect.x * ATTRACT_FORCE), pi.velocity.y
+ (attract_vect.y * ATTRACT_FORCE));
}
}
private void repulse(Particle pi) {
if (isRepulsing) {
if (pi.pos.dst2(testPoint2D) > REPULSE_RANGE)
return;
repulse_vect.set(pi.pos);
repulse_vect.sub(testPoint2D);
pi.velocity.set(pi.velocity.x
+ (repulse_vect.x * REPULSE_FORCE), pi.velocity.y
+ (repulse_vect.y * REPULSE_FORCE));
}
}
private void wallCollision(Particle pi) {
tempVect.set(0, 0);
boolean toDump = false;
if (pi.pos.x > (BOX_WIDTH / 2 - wpadding)) {
tempVect.sub((pi.pos.x - (BOX_WIDTH / 2 - wpadding))
/ COLLISION_FORCE, 0);
pi.pos.x = (BOX_WIDTH / 2 - wpadding);
}
else if (pi.pos.x < (-BOX_WIDTH / 2 + wpadding)) {
tempVect.add(((-BOX_WIDTH / 2 + wpadding) - pi.pos.x)
/ COLLISION_FORCE, 0);
pi.pos.x = (-BOX_WIDTH / 2 + wpadding);
}
if (pi.pos.y > (BOX_HEIGHT - hpadding)) {
tempVect.sub(0, (pi.pos.y - (BOX_HEIGHT - hpadding))
/ COLLISION_FORCE);
pi.pos.y = (BOX_HEIGHT - hpadding);
}
else if (pi.pos.y < (INITIAL_HEIGHT + hpadding)) {
tempVect.add(0, ((INITIAL_HEIGHT + hpadding) - pi.pos.y)
/ COLLISION_FORCE);
toDump = true;
pi.pos.y = (INITIAL_HEIGHT + hpadding);
}
pi.velocity.set(pi.velocity.x + tempVect.x, pi.velocity.y
+ tempVect.y);
if (toDump)
pi.velocity.scl(0.98f);
}
private void prepareDeleteOutOfBoundsParticles() {
len = disposableParticles.size();
for (i=0; i<len; i++) {
particles.remove(disposableParticles.get(i));
}
}
@Override
public void render(float deltaTime) {
firstRender = true;
timeStep += deltaTime;
stepped = false;
loops = 0;
while (timeStep > nextGameTick
&& loops < MAX_FRAMESKIP) {
for (speedCounter = 0; speedCounter < speedMultiplier; speedCounter++) {
performLogic(FIXED_DELTA);
if (IS_DESKTOP) {
prepareDeleteOutOfBoundsParticles();
deleteOutOfBoundsParticles();
}
}
stepped = true;
nextGameTick += slowMotion ? SKIP_TICKS * 3 : SKIP_TICKS;
loops++;
}
// interpolation = slowMotion ? (timeStep + (SKIP_TICKS*3) - nextGameTick) / (SKIP_TICKS*3)
// : (timeStep + SKIP_TICKS - nextGameTick) / SKIP_TICKS;
long renderTime = System.currentTimeMillis();
synchronized (drawParticles) {
// synchronized (fluidLock) {
camera.update();
if (gl == null) {
gl = Gdx.gl20;
}
if (whiteBackground)
gl.glClearColor(1, 1, 1, 1);
else
gl.glClearColor(0, 0, 0, 1);
gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
if (bgMode) {
batch.disableBlending();
batch.begin();
bgSprite.draw(batch);
batch.end();
batch.enableBlending();
}
if (enableBox2DCollisions)
renderer.render(world, camera.combined);
gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);
// gl.glEnable(GL10.GL_LINE_SMOOTH);
// gl.glHint(GL10.GL_LINE_SMOOTH_HINT, GL20.GL_NICEST);
// gl.glEnable(GL20.GL_BLEND);
// gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
// gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
// Begin Batch
if (particleRendering && !render3D) {
if (shapes) {
len = drawParticles.size();
// defaultShader.begin();
// shapeRenderer.setProjectionMatrix(camera.combined);
// shapeRenderer.begin(ShapeType.FilledCircle);
// for (i=0; i<len; i++) {
// if (particles.get(i).type == 1)
// shapeRenderer.setColor(1, 0, 0, 1);
// if (particles.get(i).type == 2)
// shapeRenderer.setColor(0, 1, 0, 1);
// if (particles.get(i).type == 3)
// shapeRenderer.setColor(0, 0, 1, 1);
// dropCoordinate.set(particles.get(i).drawPos.x - dropRadius,
// particles.get(i).drawPos.y - dropRadius, 0.0f);
// shapeRenderer.filledCircle(dropCoordinate.x, dropCoordinate.y, dropRadius, 8);
// }
// shapeRenderer.end();
// defaultShader.end();
batch.setProjectionMatrix(camera.combined);
batch.begin();
// for (i=0; i<len; i++) {
// mainP = particles.get(i);
for (Particle mainP : drawParticles) {
// synchronized (particles) {
// particleArray = particles.table.toArray(particleArray);
// for (k=0; k<len; k++) {
// mainP = particleArray[k];
if (mainP == null)
break;
dropCoordinate.set(mainP.drawPos.x - dropRadius,
mainP.drawPos.y - dropRadius, 0.0f);
spriteColor = 1.0f/* - (mainP.density * LINE_DENSITY_FACTOR / 255.0f)*/;
// if (spriteColor < 0.2f)
// spriteColor = 0.2f;
if (mainP.type == 1 && k==0)
batch.setColor(spriteColor, 0, 0, 1);
else if (mainP.type == 2 && k==0)
batch.setColor(0, spriteColor, 0, 1);
else if (mainP.type == 3 && k==0)
batch.setColor(0, 0, spriteColor, 1);
// dropSprite.setPosition(dropCoordinate.x, dropCoordinate.y);
// dropSprite.draw(batch);
// batch.setColor(dropSprite.getColor());
batch.draw(dropTexture2, dropCoordinate.x, dropCoordinate.y, dropRadiusPixel, dropRadiusPixel);
}
// }
batch.end();
}
else if (!linesMode) {
len = drawParticles.size();
gl.glEnable(GL20.GL_BLEND);
if (bgMode) {
// if (glowMode)
gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
// else
// gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
gl.glEnable(GL20.GL_TEXTURE_2D);
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE0);
dropTexture.bind();
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE1);
bgTexture.bind();
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE2);
glossMapTexture.bind();
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE3);
displacementMap.bind();
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE4);
displacementMap2.bind();
Gdx.gl20.glActiveTexture(GL20.GL_TEXTURE0);
irt.begin(camera.combined, GL20.GL_TRIANGLES);
// for (i=0; i<len; i++) {
// mainP = particles.get(i);
// synchronized (particles) {
for (Particle mainP : drawParticles) {
// particleArray = particles.table.toArray(particleArray);
// for (k=0; k<len; k++) {
// mainP = particleArray[k];
// if (mainP == null)
// break;
// dropCoordinate.set(mainP.drawPos.x - dropRadius,
// mainP.drawPos.y - dropRadius, 0.0f);
dropCoordinate.set((mainP.drawPos.x + (mainP.velocity.x * interpolation * deltaTime)) - dropRadius,
(mainP.drawPos.y + (mainP.velocity.y * interpolation * deltaTime)) - dropRadius, 0.0f);
spriteColor = 1.0f/* - (mainP.density * LINE_DENSITY_FACTOR / 255.0f)*/;
// if (spriteColor < 0.2f)
// spriteColor = 0.2f;
if (mainP.type == 1 && k==0)
dropSprite.setColor(spriteColor, 0, 0, 1);
else if (mainP.type == 2 && k==0)
dropSprite.setColor(0, spriteColor, 0, 1);
else if (mainP.type == 3 && k==0)
dropSprite.setColor(0.7f, 1, 1, 1);
irt.texCoord(0, 0);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
irt.texCoord(0, 1);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt.texCoord(1, 1);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt.texCoord(0, 0);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
irt.texCoord(1, 1);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt.texCoord(1, 0);
irt.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
}
// }
// System.out.println(totalPressure - lastTotalPressure);
if (Math.abs(totalPressure - lastTotalPressure) >= 5)
irt.factor -= 0.0001f;
else
irt.factor += 0.0002f;
irt.end();
gl.glDisable(GL20.GL_TEXTURE_2D);
}
else {
// if (glowMode)
// gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
// else
if (whiteBackground)
gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
else
gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
gl.glEnable(GL20.GL_TEXTURE_2D);
dropTexture.bind();
irt2.begin(camera.combined, GL20.GL_TRIANGLES);
// for (i=0; i<len; i++) {
// mainP = particles.get(i);
// synchronized (particles) {
for (Particle mainP : drawParticles) {
// particleArray = particles.table.toArray(particleArray);
// for (k=0; k<len; k++) {
// mainP = particleArray[k];
// if (mainP == null)
// break;
// dropCoordinate.set(mainP.drawPos.x - dropRadius,
// mainP.drawPos.y - dropRadius, 0.0f);
dropCoordinate.set((mainP.drawPos.x + (mainP.velocity.x * interpolation * deltaTime)) - dropRadius,
(mainP.drawPos.y + (mainP.velocity.y * interpolation * deltaTime)) - dropRadius, 0.0f);
spriteColor = 1.0f/* - (mainP.density * LINE_DENSITY_FACTOR / 255.0f)*/;
// if (spriteColor < 0.2f)
// spriteColor = 0.2f;
if (mainP.type == 1 && k==0)
dropSprite.setColor(spriteColor, 0, 0, 1);
else if (mainP.type == 2 && k==0)
dropSprite.setColor(0, spriteColor, 0, 1);
else if (mainP.type == 3 && k==0)
dropSprite.setColor(0, 0, spriteColor, 1);
irt2.texCoord(0, 0);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
irt2.texCoord(0, 1);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt2.texCoord(1, 1);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt2.texCoord(0, 0);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x - dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
irt2.texCoord(1, 1);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y + dropRadiusPixel, 0);
irt2.texCoord(1, 0);
irt2.color(dropSprite.getColor().r, dropSprite.getColor().g, dropSprite.getColor().b, dropSprite.getColor().a);
irt2.vertex(dropCoordinate.x + dropRadiusPixel, dropCoordinate.y - dropRadiusPixel, 0);
}
// }
irt2.end();
gl.glDisable(GL20.GL_TEXTURE_2D);
// gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);
immediateRenderer.begin(camera.combined, GL20.GL_TRIANGLES);
// if (glowMode)
// gl.glBlendFunc(GL20.GL_DST_COLOR, GL20.GL_DST_COLOR);
// else
gl.glBlendFunc(GL20.GL_ZERO, GL20.GL_DST_COLOR);
for (i=0; i< (glowMode ? 0 : 2); i++) {
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(-BOX_WIDTH/2, 0, 0);
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(-BOX_WIDTH/2, BOX_HEIGHT, 0);
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(BOX_WIDTH/2, BOX_HEIGHT, 0);
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(-BOX_WIDTH/2, 0, 0);
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(BOX_WIDTH/2, BOX_HEIGHT, 0);
immediateRenderer.color(1, 1, 1, 1);
immediateRenderer.vertex(BOX_WIDTH/2, 0, 0);
}
immediateRenderer.end();
}
} else {
Gdx.gl.glLineWidth(2);
immediateRenderer.begin(camera.combined, GL20.GL_LINES);
vertexIndex = 0;
len = particles.size();
// for (i=0; i<len; i++) {
// mainP = particles.get(i);
// synchronized (particles) {
for (Particle mainP : drawParticles) {
// particleArray = particles.table.toArray(particleArray);
// for (k=0; k<len; k++) {
// mainP = particleArray[k];
// if (mainP == null)
// break;
spriteColor = mainP.density * LINE_DENSITY_FACTOR / 255.0f;
if (spriteColor > 1.0f)
spriteColor = 1.0f;
if (smokeMode) {
// Red Fire
if (emitType == 1) {
tempInt = 255 - (int) ((System.currentTimeMillis() - mainP
.spawnTime) / 50);
// Start by decreasing B value to 0
mainP.setBGrad(240 - (int) ((System
.currentTimeMillis() - mainP.spawnTime) / (3 * 1)));
// Then decrease G value to 0
if (mainP.bGrad < 150)
mainP.setGGrad(255 - (int) ((System
.currentTimeMillis() - mainP
.spawnTime) / (10 * 1)));
// Then decrease R value to 0
if (mainP.gGrad < 150)
mainP.setRGrad(255 - (int) ((System
.currentTimeMillis() - mainP
.spawnTime) / (25 * 1)));
if (tempInt <= 0 || mainP.rGrad == 0) {
disposableParticles.add(mainP);
continue;
}
}
// Blue Fire
else if (emitType == 2) {
tempInt = 255 - (int) ((System.currentTimeMillis() - mainP
.spawnTime) / 50);
// Start by decreasing R value to 0
mainP.setRGrad(240 - (int) ((System
.currentTimeMillis() - mainP.spawnTime) / (3 * 1)));
// Then decrease G value to 0
if (mainP.rGrad < 150)
mainP.setGGrad(255 - (int) ((System
.currentTimeMillis() - mainP
.spawnTime) / (10 * 1)));
// Then decrease B value to 0
if (mainP.gGrad < 150)
mainP.setBGrad(255 - (int) ((System
.currentTimeMillis() - mainP
.spawnTime) / (25 * 1)));
if (tempInt <= 0 || mainP.bGrad == 0) {
disposableParticles.add(mainP);
continue;
}
}
// Green Fire
else if (emitType == 3) {
tempInt = 255 - (int) ((System.currentTimeMillis() - mainP
.spawnTime) / 50);
// Start by decreasing R and B values to 0
mainP.setRGrad(240 - (int) ((System
.currentTimeMillis() - mainP.spawnTime) / (10 * 1)));
mainP.setBGrad(240 - (int) ((System
.currentTimeMillis() - mainP.spawnTime) / (10 * 1)));
// Then decrease G value to 0
if (mainP.rGrad < 150)
mainP.setGGrad(255 - (int) ((System
.currentTimeMillis() - mainP
.spawnTime) / (25 * 1)));
if (tempInt <= 0 || mainP.gGrad == 0) {
disposableParticles.add(mainP);
continue;
}
}
}
dropCoordinate.set((mainP.drawPos.x + (mainP.velocity.x * interpolation * deltaTime)) - dropRadius,
(mainP.drawPos.y + (mainP.velocity.y * interpolation * deltaTime)) - dropRadius, 0.0f);
// camera.project(dropCoordinate);
// lineVertices[vertexIndex++] = dropCoordinate.x;
// lineVertices[vertexIndex++] = dropCoordinate.y;
if (smokeMode) {
// lineVertices[vertexIndex++] = Color.toFloatBits(
// mainP.rGrad, mainP.gGrad, mainP.bGrad,
// tempInt);
immediateRenderer.color((float)mainP.rGrad / 255.0f,
(float)mainP.gGrad / 255.0f, (float)mainP.bGrad / 255.0f, (float)tempInt / 255.0f);
}
else {
if (mainP.type == 1)
// lineVertices[vertexIndex++] = Color.toFloatBits(
// 255, (int) mainP.density
// * LINE_DENSITY_FACTOR, 0, 255);
immediateRenderer.color(1, spriteColor, 0, 1);
else if (mainP.type == 2)
// lineVertices[vertexIndex++] = Color
// .toFloatBits((int) mainP.density
// * LINE_DENSITY_FACTOR, 0, 255, 255);
immediateRenderer.color(0, 0.79f, spriteColor/2, 1);
else if (mainP.type == 3)
// lineVertices[vertexIndex++] = Color.toFloatBits(0,
// 200, (int) mainP.density
// * LINE_DENSITY_FACTOR, 255);
immediateRenderer.color(spriteColor/4, 0, 1, 1);
}
// lineVertices[vertexIndex++] = dropCoordinate.x
// + mainP.velocity.x * LINE_VELOCITY_FACTOR;
// lineVertices[vertexIndex++] = dropCoordinate.y
// + mainP.velocity.y * LINE_VELOCITY_FACTOR;
immediateRenderer.vertex(dropCoordinate.x, dropCoordinate.y, 0);
if (smokeMode)
// lineVertices[vertexIndex++] = Color.toFloatBits(
// mainP.rGrad, mainP.gGrad, mainP.bGrad,
// tempInt);
immediateRenderer.color((float)mainP.rGrad / 255.0f,
(float)mainP.gGrad / 255.0f, (float)mainP.bGrad / 255.0f, (float)tempInt / 255.0f);
else {
if (mainP.type == 1)
// lineVertices[vertexIndex++] = Color.toFloatBits(
// 255, (int) mainP.density
// * LINE_DENSITY_FACTOR, 0, 255);
immediateRenderer.color(1, spriteColor, 0, 1);
else if (mainP.type == 2)
// lineVertices[vertexIndex++] = Color
// .toFloatBits((int) mainP.density
// * LINE_DENSITY_FACTOR, 0, 255, 255);
immediateRenderer.color(0, 0.79f, spriteColor/2, 1);
else if (mainP.type == 3)
// lineVertices[vertexIndex++] = Color.toFloatBits(0,
// 200, (int) mainP.density
// * LINE_DENSITY_FACTOR, 255);
immediateRenderer.color(spriteColor/4, 0, 1, 1);
}
immediateRenderer.vertex(dropCoordinate.x + mainP.velocity.x * LINE_VELOCITY_FACTOR,
dropCoordinate.y + mainP.velocity.y * LINE_VELOCITY_FACTOR, 0);
}
// }
// lineMesh.setVertices(lineVertices, 0, vertexIndex);
// defaultShader.begin();
// lineMesh.render(defaultShader, GL20.GL_LINES);
// defaultShader.end();
immediateRenderer.end();
}
}
gl.glDisable(GL20.GL_BLEND);
if (hudEnabled) {
if (whiteBackground)
font.setColor(0, 0, 0, 1);
else
font.setColor(1, 1, 1, 1);
batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.begin();
font.draw(batch,
"fps:" + Gdx.graphics.getFramesPerSecond()
+ ", particles: " + (particles.size()), 0, Gdx.graphics.getHeight() - 40);
font.draw(batch, "deltaTime: " + deltaTime, 0, Gdx.graphics.getHeight() - 20);
font.draw(batch, "pressure: " + (totalPressure - lastTotalPressure), 0, Gdx.graphics.getHeight());
// if (IS_DESKTOP) {
font.draw(batch, "(SPACE) Fluid Type: " + emitType
+ " (+/-) Gravity: " + GRAVITY_FORCE
+ " (UP/DOWN) Emitter: " + EMITTER_SIZE
+ " (E) Expand: " + expandMode + " (S) Slow: "
+ slowMotion + " (C) Crazy: " + crazyMode
+ " (L) Lines: " + linesMode + " (Q) Shapes: "
+ shapes, 180.0f, Gdx.graphics.getHeight());
font.draw(batch, "(K) Smoke: " + smokeMode
+ " (R) Particle Render: " + particleRendering
+ " (M) Mass: " + massMode
+ " (B) Box2DColl: " + enableBox2DCollisions
+ " (G) Glow: " + glowMode, 180, Gdx.graphics.getHeight() - 20);
font.draw(batch,"ART: " + ARTI_PRESSURE_DELTA_Q + " Sigma: " + SIGMA
+ " Density: " + P0 + " H: " + H
+ " DensityR: " + REST_DENSITY + " H_H: " + H_H
+ " Cell: " + CELL_SIZE + " K_: " + K_
+ " Rad: " + dropRadiusK
+ " MN: " + particles.MAX_NEIGHBORS
+ " Step: " + FIXED_DELTA
+ " STICK: " + K_STICKINESS
+ " RAD: " + RAD
+ " VISC: " + VISC
+ " DAMP: " + DAMPING
+ " RELAX: " + RELAXATION_EPSILON, 180, Gdx.graphics.getHeight() - 40);
font.draw(batch,"camera3D: " + camera3D.position, 180, Gdx.graphics.getHeight() - 60);
// }
batch.end();
}
// }
}
//3D
if (render3D) {
// Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// camera3D.update();
camController.update();
modelBatch.begin(camera3D);
for (Particle p : drawParticles) {
instance.transform.setToTranslation(p.drawPos.x, p.drawPos.y, 0);
modelBatch.render(instance, environment);
}
modelBatch.end();
}
if (DEBUG_ENABLED)
System.out.print("\t render: " + (System.currentTimeMillis() - renderTime));
// Exit the application if ESC has been pressed
if (exitApp) {
threadRunning = false;
timer.cancel();
Gdx.app.exit();
}
}
@Override
public boolean keyUp(int keycode) {
// K
if (keycode == Input.Keys.F1 && K < 2.0f) {
K += 0.1f;
} else if (keycode == Input.Keys.NUM_1 && K > 0.004f) {
K -= 0.1f;
if (K < 0.004f)
K = 0.004f;
}
if (keycode == Input.Keys.F1) {
ARTI_PRESSURE_DELTA_Q /= H_H;
ARTI_PRESSURE_DELTA_Q += 0.01f;
ARTI_PRESSURE_DELTA_Q *= H_H;
ARTI_PRESSURE = (float) (KPOLY * Math.pow(H_H - ARTI_PRESSURE_DELTA_Q, 3));
ARTI_PRESSURE_K = (float) (-0.05f / Math.pow(ARTI_PRESSURE, 4));
} else if (keycode == Input.Keys.NUM_1) {
ARTI_PRESSURE_DELTA_Q /= H_H;
ARTI_PRESSURE_DELTA_Q -= 0.01f;
if (ARTI_PRESSURE_DELTA_Q < 0)
ARTI_PRESSURE_DELTA_Q = 0.01f;
ARTI_PRESSURE_DELTA_Q *= H_H;
ARTI_PRESSURE = (float) (KPOLY * Math.pow(H_H - ARTI_PRESSURE_DELTA_Q, 3));
ARTI_PRESSURE_K = (float) (-0.05f / Math.pow(ARTI_PRESSURE, 4));
}
// SIGMA
if (keycode == Input.Keys.F2 && SIGMA < 50.0f)
SIGMA += 2;
else if (keycode == Input.Keys.NUM_2 && SIGMA > 0)
SIGMA -= 2;
// DENSITY
else if (keycode == Input.Keys.F3 && P0 < 1000.0f)
P0 += 100.0f;
else if (keycode == Input.Keys.NUM_3 && P0 > 100.0f)
P0 -= 100.0f;
if (keycode == Input.Keys.F3 && REST_DENSITY < 100.0f)
REST_DENSITY += 0.1f;
if (keycode == Input.Keys.NUM_3 && REST_DENSITY > 0.1f)
REST_DENSITY -= 0.1f;
// H
if (keycode == Input.Keys.F4 && H < 200.0f) {
H += 5.0f;
H2 = H * H;
ATTRACT_RANGE = H2 / 2;
REPULSE_RANGE = H2 / 4;
} else if (keycode == Input.Keys.NUM_4 && H > 0.2f) {
H -= 5.0f;
H2 = H * H;
ATTRACT_RANGE = H2 / 2;
REPULSE_RANGE = H2 / 4;
}
if (keycode == Input.Keys.F4 && H_H < 100f) {
H_H += 1.0f;
H1 = (float) Math.sqrt(H_H);
KPOLY = (float) (315f / (64.0f * Math.PI * Math.pow(Math.sqrt(H_H), 9)));
KSPIKY = (float) (45f / (Math.PI * Math.pow(Math.sqrt(H_H), 6)));
ARTI_PRESSURE_DELTA_Q = 0.1f * H_H;
ARTI_PRESSURE = (float) (KPOLY * Math.pow(H_H - ARTI_PRESSURE_DELTA_Q, 3));
ARTI_PRESSURE_K = (float) (-0.05f / Math.pow(ARTI_PRESSURE, 4));
}
if (keycode == Input.Keys.NUM_4 && H_H > 1f) {
H_H -= 1.0f;
if (H_H < 1)
H_H = 1;
H1 = (float) Math.sqrt(H_H);
KPOLY = (float) (315f / (64.0f * Math.PI * Math.pow(Math.sqrt(H_H), 9)));
KSPIKY = (float) (45f / (Math.PI * Math.pow(Math.sqrt(H_H), 6)));
ARTI_PRESSURE_DELTA_Q = 0.1f * H_H;
ARTI_PRESSURE = (float) (KPOLY * Math.pow(H_H - ARTI_PRESSURE_DELTA_Q, 3));
ARTI_PRESSURE_K = (float) (-0.05f / Math.pow(ARTI_PRESSURE, 4));
}
// CELL_SIZE
if (keycode == Input.Keys.F5 && CELL_SIZE < 50) {
CELL_SIZE += 1;
particles.rehash();
} else if (keycode == Input.Keys.NUM_5 && CELL_SIZE > 1) {
CELL_SIZE -= 1;
particles.rehash();
}
// K_
if (keycode == Input.Keys.F6 && K_ < 10.0f) {
K_ += 0.1f;
} else if (keycode == Input.Keys.NUM_6 && K_ > 0.1f) {
K_ -= 0.1f;
}
// MAX_NEIGHBORS
if (keycode == Input.Keys.F7 && particles.MAX_NEIGHBORS < 500) {
particles.MAX_NEIGHBORS += 5;
qArray = new float[particles.MAX_NEIGHBORS];
qqArray = new float[particles.MAX_NEIGHBORS];
} else if (keycode == Input.Keys.NUM_7 && particles.MAX_NEIGHBORS > 0) {
particles.MAX_NEIGHBORS -= 5;
qArray = new float[particles.MAX_NEIGHBORS];
qqArray = new float[particles.MAX_NEIGHBORS];
}
// dropRadiusK
if (keycode == Input.Keys.F8 && dropRadiusK < 3.5f) {
dropRadiusK += 0.2f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
} else if (keycode == Input.Keys.NUM_8 && dropRadiusK >= 0.3f) {
dropRadiusK -= 0.2f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
// K_STICKINESS
if (keycode == Input.Keys.F10 && K_STICKINESS < 20.0f)
K_STICKINESS += 1;
else if (keycode == Input.Keys.NUM_0 && K_STICKINESS > 0)
K_STICKINESS -= 1;
// RAD
if (keycode == Input.Keys.RIGHT && RAD < 50.0f) {
RAD += 1;
MULTIPLIER = 50 / RAD;
}
else if (keycode == Input.Keys.LEFT && RAD > 0) {
RAD -= 1;
MULTIPLIER = 50 / RAD;
}
// VISC
if (keycode == Input.Keys.F11 && VISC < 1.0f)
VISC += 0.0001f;
else if (keycode == Input.Keys.F12 && VISC > 0)
VISC -= 0.0001f;
if (keycode == Input.Keys.BACKSPACE && isAttracting) {
for (Particle pi : particles) {
if (pi.pos.dst2(testPoint2D) < ATTRACT_RANGE) {
disposableParticles.add(pi);
}
}
} else if (keycode == Input.Keys.BACKSPACE && IS_DESKTOP) {
// game.setScreen(game.switchToFluidSimulator());
// synchronized (particles) {
for (Particle pi : particles)
disposableParticles.add(pi);
// }
}
// Change Particle color
if (keycode == Input.Keys.SPACE) {
emitType += 1;
if (emitType > 3) {
emitType = 1;
}
if (!IS_DESKTOP) {
for (Particle p : particles)
p.type = emitType;
}
}
// Increase/Decrease Gravity
if ((keycode == Input.Keys.PLUS) && (GRAVITY_FORCE > -60.0f)) {
GRAVITY_FORCE -= 1.0f;
gravityVect.set(0.0f, GRAVITY_FORCE);
} else if ((keycode == Input.Keys.MINUS) && (GRAVITY_FORCE < 0.0f)) {
GRAVITY_FORCE += 1.0f;
// if (GRAVITY_FORCE > -0.2f)
// GRAVITY_FORCE = 0.0f;
gravityVect.set(0.0f, GRAVITY_FORCE);
}
// Increase/Decrease Emitter Size
if ((keycode == Input.Keys.DOWN) && (EMITTER_SIZE > 2)) {
EMITTER_SIZE -= 3;
} else if ((keycode == Input.Keys.UP) && (EMITTER_SIZE < 20)) {
EMITTER_SIZE += 3;
}
// Enable/Disable Expand Mode
if (keycode == Input.Keys.E)
expandMode = !expandMode;
// Enable/Disable Stop Motion
if (keycode == Input.Keys.S)
slowMotion = !slowMotion;
// Enable/Disable Crazy Mode
if (keycode == Input.Keys.C) {
// crazyMode = !crazyMode;
Gdx.input.setInputProcessor(camController);
}
// Enable/Disable Box2D Collisions
if (keycode == Input.Keys.B)
enableBox2DCollisions = !enableBox2DCollisions;
// Enable/Disable Render Glow
if (keycode == Input.Keys.G)
glowMode = !glowMode;
// Enable/Disable PBF
if (keycode == Input.Keys.J) {
pbfEnabled = !pbfEnabled;
particles.rehash();
}
// Enable/Disable HUD
if (keycode == Input.Keys.H)
hudEnabled = !hudEnabled;
// Mass Mode
if (keycode == Input.Keys.M) {
massMode = !massMode;
}
// Enable/Disable ShapeRenderer mode
if (keycode == Input.Keys.Q) {
shapes = !shapes;
if (!shapes) {
dropRadiusK = 1.5f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
else {
dropRadiusK = 0.3f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
}
// Enable/Disable Lines mode
if (keycode == Input.Keys.L) {
linesMode = !linesMode;
}
// Enable/Disable Smoke Mode
if (keycode == Input.Keys.K)
smokeMode = !smokeMode;
// Enable/Disable Particle Rendering
if (keycode == Input.Keys.R) {
particleRendering = !particleRendering;
render3D = !render3D;
}
// Enable/Disable White Background
if (keycode == Input.Keys.X)
whiteBackground = !whiteBackground;
if (keycode == Keys.PAGE_UP) {
FIXED_DELTA += 0.004f;
}
if (keycode == Keys.PAGE_DOWN) {
FIXED_DELTA -= 0.004f;
if (FIXED_DELTA <= 0.016f)
FIXED_DELTA = 0.016f;
}
// Exit
if (keycode == Input.Keys.ESCAPE) {
exitApp = true;
}
if (keycode == Input.Keys.CONTROL_LEFT) {
isDragging = false;
}
if (keycode == Input.Keys.CONTROL_RIGHT) {
DAMPING += 0.01f;
RELAXATION_EPSILON += 10f;
}
else if (keycode == Input.Keys.ALT_RIGHT) {
DAMPING -= 0.01f;
RELAXATION_EPSILON -= 10f;
if (RELAXATION_EPSILON <= 0)
RELAXATION_EPSILON = 0.1f;
}
// Enable/Disable BG Mode
if (keycode == Input.Keys.N) {
if (IS_DESKTOP)
bgMode = !bgMode;
else if (!enableBox2DCollisions) {
shapes = !shapes;
bgMode = !bgMode;
if (shapes)
dropRadiusK = 1.3f;
else
dropRadiusK = 2.5f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
}
return false;
}
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
touching = true;
camera.unproject(testPoint.set(x, y, 0));
testPoint2D.x = testPoint.x;
testPoint2D.y = testPoint.y;
oldDragPos.set(testPoint2D);
if (button == Buttons.LEFT) {
// Drag Mode
if (isDragging) {
for (Piece piece : pieces.values()) {
hitBody = null;
if (piece.body.getFixtureList().get(0).testPoint(testPoint2D)) {
hitBody = piece.body;
if (hitBody.getType() == BodyType.KinematicBody || hitBody.getType() == BodyType.StaticBody)
continue;
MouseJointDef def = new MouseJointDef();
def.bodyA = groundBody;
def.bodyB = hitBody;
def.collideConnected = true;
def.target.set(testPoint2D);
def.maxForce = 10.0f * hitBody.getMass();
mouseJoint = (MouseJoint)world.createJoint(def);
hitBody.setAwake(true);
break;
}
}
if (mouseJoint != null)
return false;
}
if (!IS_DESKTOP) {
isRepulsing = true;
isAttracting = false;
} else {
isAttracting = false;
isRepulsing = false;
}
}
if (button == Buttons.RIGHT) {
isAttracting = true;
}
if (button == Buttons.MIDDLE) {
isRepulsing = true;
}
return false;
}
@Override
public boolean touchDragged(int x, int y, int pointer) {
camera.unproject(testPoint.set(x, y, 0));
testPoint2D.x = testPoint.x;
testPoint2D.y = testPoint.y;
dragVelocity.set(testPoint2D);
dragVelocity.sub(oldDragPos);
oldDragPos.set(testPoint2D);
if (mouseJoint != null) {
mouseJoint.setTarget(target.set(testPoint2D));
mouseJoint.getBodyB().setLinearVelocity(0, 0);
mouseJoint.getBodyB().setTransform(testPoint2D.x, testPoint2D.y, 0);
}
return false;
}
@Override
public boolean touchUp(int x, int y, int pointer, int button) {
touching = false;
if (!IS_DESKTOP) {
isRepulsing = false;
isAttracting = false;
}
if (button == Buttons.RIGHT) {
isAttracting = false;
}
if (button == Buttons.MIDDLE) {
isRepulsing = false;
}
// if a mouse joint exists we simply destroy it
if (mouseJoint != null) {
if (dragVelocity.len() > 1)
mouseJoint.getBodyB().setLinearVelocity(dragVelocity.scl(50000));
world.destroyJoint(mouseJoint);
mouseJoint = null;
}
hitBody = null;
dragVelocity.set(0, 0);
if (pointer == 1 || pointer == 3) {
if (pointer == 3)
enableBox2DCollisions = !enableBox2DCollisions;
if (pointer == 1)
bgMode = !bgMode;
// if (shapes)
// dropRadiusK = 1.3f;
// else
// dropRadiusK = 2.5f;
// dropRadius = 0.1f + dropRadiusK;
// dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
// dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
// dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
else if (pointer == 2) {
emitType ++;
if (emitType > 3)
emitType = 1;
for (Particle p : particles)
p.type = emitType;
}
return false;
}
@Override
public void dispose() {
super.dispose();
particles.clear();
}
@Override
public void hide() {
super.hide();
particles.clear();
}
/**
*
* POSITION BASED FLUIDS
*/
public final Vector2 ZERO_VEC = new Vector2(0, 0);
public float H_H = 6.00f;
public float H1 = (float) Math.sqrt(H_H);
public float KPOLY = (float) (315f / (64.0f * Math.PI * Math.pow(Math.sqrt(H_H), 9)));
public float KCUSTOM = (float) (945f / (32.0f * Math.PI * Math.pow(Math.sqrt(H_H), 8))) * -3f;
public float KSPIKY = (float) (45f / (Math.PI * Math.pow(Math.sqrt(H_H), 6)));
public float SPIKY_F = (float) Math.pow(1.0f, -12);
public float REST_DENSITY = 0.60f;
public float INVERSE_REST_DENSITY = 1f / REST_DENSITY;
public float ARTI_PRESSURE_DELTA_Q = 0.1f * H_H;
public float ARTI_PRESSURE = (float) (KPOLY * Math.pow(H_H - ARTI_PRESSURE_DELTA_Q, 3));
public float ARTI_PRESSURE_K = (float) (-0.05f / Math.pow(ARTI_PRESSURE, 4));
public float RELAXATION_EPSILON = 10.0f;
public final int PBF_ITERATIONS = 1;
public final Box box = new Box(-35, 35, 3, 50);
private Vector2 tempVec2 = new Vector2();
private Vector2 delta = new Vector2();
private Vector2 dist = new Vector2();
private Vector2 gradient = new Vector2();
private float r_r;
public float r;
private float aFloat;
private float wpipj;
// main function, apply the position-based algorithm
public void UpdateFluid(float deltaTime) {
//find neighbours
long startTime=System.currentTimeMillis();
particles.rehash();
particleArray = particles.table.toArray(particleArray);
long neighbourEndTime=System.currentTimeMillis();
len = particles.size();
if (DEBUG_ENABLED) {
System.out.println("");
System.out.print("neighbour = " + (neighbourEndTime - startTime) );
}
// if (thread == null) {
// TimerTask task = new TimerTask() {
// public void run() {
// updatePBF(0, len/2);
// }
// };
// thread = new Thread() {
// public void run() {
// updatePBF(0, len/4);
// }
// };
// timer.schedule(task, 0, 15);
// }
// if (thread2 == null) {
// TimerTask task = new TimerTask() {
// public void run() {
// updatePBF(len/2, len);
// }
// };
// thread2 = new Thread() {
// public void run() {
// updatePBF(len/4, len/2);
// }
// };
// timer.schedule(task, 0, 15);
// }
// if (thread3 == null) {
// TimerTask task = new TimerTask() {
// public void run() {
// try {
// updatePBF(len/2, 3*len/4);
// } catch(NullPointerException npe) {}
// }
// };
// thread3 = new Thread() {
// public void run() {
// updatePBF(len/2, 3*len/4);
// }
// };
// timer.schedule(task, 0, 30);
// }
// if (thread4 == null) {
// thread4 = new Thread() {
// public void run() {
// try {
// updatePBF(3*len/4, len);
// } catch(NullPointerException npe) {}
// }
// };
// TimerTask task = new TimerTask() {
// public void run() {
// updatePBF(3*len/4, len);
// }
// };
// timer.schedule(task, 0, 30);
// }
// if (!thread.isAlive())
// thread.run();
// if (!thread2.isAlive())
// thread2.run();
// if (!thread3.isAlive())
// thread3.run();
// if (!thread4.isAlive())
// thread4.run();
// synchronized (fluidLock) {
// updatePBF(0, len, deltaTime);
updatePBF(0, len, deltaTime);
// }
// ApplyExternalForce(deltaTime);
// // make it align with constraints
// for(s = 1; s <= PBF_ITERATIONS; s++) {
// long beginDeltaPos=System.currentTimeMillis();
//// for(Particle particle : particles) {
// for (i=0; i<len; i++) {
// mainP = particleArray[i];
// ComputeC(mainP);
// }
// long endCtime=System.currentTimeMillis();
//// for(Particle particle : particles) {
// for (i=0; i<len; i++) {
// mainP = particleArray[i];
// ComputeLamda(mainP);
// }
// long endLamdaTime=System.currentTimeMillis();
//// for(Particle particle : particles) {
// for (i=0; i<len; i++) {
// mainP = particleArray[i];
// ComputeDeltaPos(mainP);
// }
// long endDeltaPos=System.currentTimeMillis();
//// CollisionWithBox();
// long endCollision=System.currentTimeMillis();
//// for(Particle particle : particles) {
// for (i=0; i<len; i++) {
// mainP = particleArray[i];
// if(!box.isInBox(mainP.posStar)) {
// box.ForceInsideBox(mainP.posStar, mainP.velocity);
// }
// mainP.posStar.add(mainP.deltaPos);
// }
//// if (DEBUG_ENABLED)
// System.out.println("neighbour time = " + (neighbourEndTime - startTime) + "\t delta pos = " + (endDeltaPos - beginDeltaPos)
//// + "\t collistion = " + (endCollision - endDeltaPos) + "\t C time = " + (endCtime - beginDeltaPos) + "\tlandatime =" + (endLamdaTime - endCtime));
// }
//
// //v = (posStar-pos) / t
//// for(Particle particle : particles) {
// for (i=0; i<len; i++) {
// mainP = particleArray[i];
// mainP.velocity.set((mainP.posStar.x - mainP.pos.x) / deltaTime, (mainP.posStar.y - mainP.pos.y) / deltaTime);
//// mainP.velocity.scl(DAMPING);
//
// //apply vorticity confinement and XSPH viscosity
// // pos = posStar
// mainP.pos.set(mainP.posStar);
//
// mainP.pos.x *= MULTIPLIER;
// mainP.pos.y *= MULTIPLIER;
// mainP.velocity.x *= MULTIPLIER;
// mainP.velocity.y *= MULTIPLIER;
// }
// try {
// thread.join();
// thread2.join();
// thread3.join();
// thread4.join();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
public void updatePBF(int len1, int len2, float deltaTime) {
//TODO Temp variable for each thread
int i=0;
long applyForcesStartTime=System.currentTimeMillis();
synchronized (fluidLock) {
for (i=len1; i<len2; i++) {
mainP = particleArray[i];
// Precalculate neighbors
mainP.neighbors = particles.nearby(mainP);
mainP.neighborsSize = particles.lastSizeNearby();
//clear force
mainP.force.set(0, 0);
// Gravity
if (massMode)
mainP.force.add(gravityVect.x * mainP.mass, gravityVect.y * mainP.mass);
else
mainP.force.add(gravityVect);
// Attract
if (isAttracting) {
if (mainP.pos.dst2(testPoint2D) <= ATTRACT_RANGE) {
attract_vect.set(testPoint2D);
attract_vect.sub(mainP.pos);
mainP.force.add(attract_vect.x * ATTRACT_FORCE * 3, attract_vect.y * ATTRACT_FORCE * 3);
}
}
// Repulse
if (isRepulsing) {
if (mainP.pos.dst2(testPoint2D) <= REPULSE_RANGE) {
repulse_vect.set(mainP.pos);
repulse_vect.sub(testPoint2D);
mainP.force.add(repulse_vect.x * REPULSE_FORCE / 2f, repulse_vect.y * REPULSE_FORCE / 2f);
}
}
// Scale
mainP.pos.x /= MULTIPLIER;
mainP.pos.y /= MULTIPLIER;
mainP.velocity.x /= MULTIPLIER;
mainP.velocity.y /= MULTIPLIER;
// Apply Forces
mainP.velocity.set(mainP.velocity.x + (mainP.force.x * deltaTime), mainP.velocity.y + (mainP.force.y * deltaTime));
// Predict position
mainP.posStar.set(mainP.pos.x + (mainP.velocity.x * deltaTime), mainP.pos.y + (mainP.velocity.y * deltaTime));
}
}
if (DEBUG_ENABLED)
System.out.print(" forces = " + (System.currentTimeMillis() - applyForcesStartTime) );
long beginC = System.currentTimeMillis();
lastTotalPressure = totalPressure;
totalPressure = 0;
// for(Particle particle : particles) {
for (i=len1; i<len2; i++) {
mainP = particleArray[i];
computeC(mainP);
totalPressure += mainP.constraint;
}
long endCtime = System.currentTimeMillis();
// for(Particle particle : particles) {
for (i=len1; i<len2; i++) {
mainP = particleArray[i];
computeLamda(mainP);
}
long endLamdaTime = System.currentTimeMillis();
synchronized (fluidLock) {
// for(Particle particle : particles) {
for (i=len1; i<len2; i++) {
mainP = particleArray[i];
computeDeltaPos(mainP);
}
}
long endDeltaPos = System.currentTimeMillis();
// CollisionWithBox();
synchronized (fluidLock) {
// for(Particle particle : particles) {
for (i=len1; i<len2; i++) {
mainP = particleArray[i];
if(!box.isInBox(mainP.posStar)) {
box.forceInsideBox(mainP.posStar, mainP.velocity);
}
mainP.posStar.add(mainP.deltaPos);
// preventParticleCohabitation(mainP);
// }
//
// for (i=len1; i<len2; i++) {
// mainP = particleArray[i];
mainP.velocity.set((mainP.posStar.x - mainP.pos.x) / deltaTime, (mainP.posStar.y - mainP.pos.y) / deltaTime);
// mainP.velocity.scl(DAMPING);
//apply vorticity confinement and XSPH viscosity
// pos = posStar
mainP.pos.set(mainP.posStar);
mainP.pos.x *= MULTIPLIER;
mainP.pos.y *= MULTIPLIER;
mainP.velocity.x *= MULTIPLIER;
mainP.velocity.y *= MULTIPLIER;
// capVelocity(mainP.velocity);
mainP.drawPos.set(mainP.pos.x + (mainP.velocity.x * interpolation * Gdx.graphics.getDeltaTime()), mainP.pos.y + (mainP.velocity.y * interpolation * Gdx.graphics.getDeltaTime()));
}
}
synchronized (drawParticles) {
drawParticles.clear();
drawParticles.addAll(particles.table);
}
long endCollision=System.currentTimeMillis();
if (DEBUG_ENABLED)
System.out.println("\t delta pos = " + (endDeltaPos - endLamdaTime)
+ "\t collision = " + (endCollision - endDeltaPos) + "\t C = "
+ (endCtime - beginC) + "\t landatime =" + (endLamdaTime - endCtime));
}
private Vector2 tempVec = new Vector2();
private Vector2 tmpVec2 = new Vector2();
private Vector2 tmpVec3 = new Vector2();
private Vector2 tmpVec4 = new Vector2();
public void ApplyExternalForce(float deltaTime) {
for (Particle mainP : particles) {
//clear force
mainP.force.set(0, 0);
// Gravity
mainP.force.add(0, GRAVITY_FORCE);
// Attract
if (isAttracting) {
if (mainP.pos.dst2(testPoint2D) <= ATTRACT_RANGE) {
attract_vect.set(testPoint2D);
attract_vect.sub(mainP.pos);
mainP.force.add(attract_vect.x * ATTRACT_FORCE, attract_vect.y * ATTRACT_FORCE);
}
}
// Repulse
if (isRepulsing) {
if (mainP.pos.dst2(testPoint2D) <= REPULSE_RANGE) {
repulse_vect.set(mainP.pos);
repulse_vect.sub(testPoint2D);
mainP.force.add(repulse_vect.x * REPULSE_FORCE / 2f, repulse_vect.y * REPULSE_FORCE / 2f);
}
}
// Scale
mainP.pos.x /= MULTIPLIER;
mainP.pos.y /= MULTIPLIER;
mainP.velocity.x /= MULTIPLIER;
mainP.velocity.y /= MULTIPLIER;
// Apply Forces
// wallCollision(mainP);
mainP.velocity.set(mainP.velocity.x + (mainP.force.x * deltaTime), mainP.velocity.y + (mainP.force.y * deltaTime));
// Predict position
mainP.posStar.set(mainP.pos.x + (mainP.velocity.x * deltaTime), mainP.pos.y + (mainP.velocity.y * deltaTime));
}
}
public void CollisionWithBox() {
for(Particle particle:particles) {
if(!box.isInBox(particle.posStar)) {
box.forceInsideBox(particle.posStar, particle.velocity);
}
}
}
public void computeC(Particle particle) {
//density
p = 0;
// tempParticles = particles.nearby(particle);
// len2 = tempParticles.size();
// tempParticles2 = particles.nearby(particle);
// len2 = particles.lastSizeNearby();
tempParticles2 = particle.neighbors;
len2 = particle.neighborsSize;
// System.out.println("neighbors = " + len2);
for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
// neighborP = tempParticles.get(a);
neighborP = tempParticles2[a];
p += Kernel(particle.posStar, neighborP.posStar);
}
particle.density = p;
particle.constraint = (p / REST_DENSITY) - 1f;
// System.out.println("density = " + p);
}
public void computeLamda(Particle particle) {
float sumGradient = 0;
// tempParticles = particles.nearby(particle);
// len2 = tempParticles.size();
// tempParticles2 = particles.nearby(particle);
// len2 = particles.lastSizeNearby();
tempParticles2 = particle.neighbors;
len2 = particle.neighborsSize;
for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
// neighborP = tempParticles.get(a);
neighborP = tempParticles2[a];
Vector2 grad = ComputeGrandientC(particle, neighborP);
sumGradient += grad.len2();
}
// System.out.println("constraint = " + particle.constraint + "\tsumgradient = " + sumGradient);
particle.lamda = -1f * (particle.constraint / (sumGradient + RELAXATION_EPSILON));
// System.out.println(particle.lamda);
}
public Vector2 ComputeGrandientC(Particle particle, Particle neighbour) {
if(particle.hash == neighbour.hash) { // k==i
tmpVec4.set(0, 0);
// tempParticles = particles.nearby(particle);
// len2 = tempParticles.size();
// tempParticles2 = particles.nearby(particle);
// len2 = particles.lastSizeNearby();
tempParticles2 = particle.neighbors;
len2 = particle.neighborsSize;
for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
// neighborP = tempParticles.get(a);
neighborP = tempParticles2[a];
if(neighborP.hash != particle.hash) {
gradient = KernelGradient(particle.posStar, neighborP.posStar);
tmpVec4.add(gradient);
}
}
tmpVec4.scl(INVERSE_REST_DENSITY);
return tmpVec4;
}
else { // k == j
gradient = KernelGradient(particle.posStar, neighbour.posStar);
gradient.scl(-INVERSE_REST_DENSITY);
return gradient;
}
}
public void computeDeltaPos(Particle particle) {
particle.deltaPos.set(0, 0);
// tempParticles = particles.nearby(particle);
// len2 = tempParticles.size();
// tempParticles2 = particles.nearby(particle);
// len2 = particles.lastSizeNearby();
tempParticles2 = particle.neighbors;
len2 = particle.neighborsSize;
for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
// neighborP = tempParticles.get(a);
neighborP = tempParticles2[a];
if(neighborP.hash != particle.hash) {
gradient = KernelGradient(particle.posStar, neighborP.posStar);
gradient.scl(particle.lamda + neighborP.lamda + ComputeArtiPressure(particle, neighborP));
particle.deltaPos.add(gradient);
}
}
particle.deltaPos.scl(INVERSE_REST_DENSITY);
}
public Vector2 KernelGradient(Vector2 pi, Vector2 pj) {
dist.set(pi);
dist.sub(pj);
// Poly6
// r_r = dist.len2();
// if (r_r > H_H)
// return ZERO_VEC;
// aFloat = (float) Math.pow(H_H - r_r, 2);
// tmpVec2.set(-2 * dist.x, -2 * dist.y);
// tmpVec2.scl(KPOLY * 3f * aFloat);
// return tmpVec2;
// WPoly6Grad
// r_r = dist.len2();
// if (r_r > H_H)
// return ZERO_VEC;
// aFloat = (H_H - r_r) * (H_H - r_r);
// tmpVec2.set(dist.x, dist.y);
// tmpVec2.scl(KPOLY * -6f * aFloat);
// return tmpVec2;
// WSpikyGrad
// r_r = dist.len2();
// if (r_r > H_H)
// return ZERO_VEC;
// if (r_r < SPIKY_F)
// r_r = SPIKY_F;
// r = (float) Math.sqrt(r_r);
// dist.nor();
// aFloat = (H1 - r) * (H1 - r) / r;
//// aFloat = (H_H - r_r) * (H_H - r_r);
// dist.scl(KSPIKY * -3f * aFloat);
// return dist;
// Custom
r_r = dist.len2();
if (r_r > H_H)
return ZERO_VEC;
// aFloat = (H_H - r_r) * (H_H - r_r);
// dist.scl(KCUSTOM * -3f * aFloat);
aFloat = KCUSTOM * (H_H - r_r) * (H_H - r_r);
dist.set((pi.x - pj.x) * aFloat, (pi.y - pj.y) * aFloat);
return dist;
}
public float Kernel(Vector2 pi, Vector2 pj) {
// tmpVec3.set(pi);
// tmpVec3.sub(pj);
// r_r = tmpVec3.len2();
r_r = pi.dst2(pj);
if (r_r > H_H)
return 0;
return (KPOLY * (H_H - r_r) * (H_H - r_r) * (H_H - r_r));
}
public float ComputeArtiPressure(Particle pi, Particle pj) {
wpipj = Kernel(pi.posStar, pj.posStar);
// System.out.println("");
// System.out.print(-0.1f * (wpipj / ARTI_PRESSURE) * (wpipj / ARTI_PRESSURE) * (wpipj / ARTI_PRESSURE) * (wpipj / ARTI_PRESSURE));
// System.out.print(" " + (wpipj * wpipj * wpipj * wpipj * ARTI_PRESSURE_K));
// return -0.1f * (wpipj / ARTI_PRESSURE) * (wpipj / ARTI_PRESSURE) * (wpipj / ARTI_PRESSURE) * (wpipj / ARTI_PRESSURE);
return wpipj * wpipj * wpipj * wpipj * ARTI_PRESSURE_K;
}
public void preventParticleCohabitation(Particle particle) {
tempParticles2 = particle.neighbors;
len2 = particle.neighborsSize;
float minDist2 = (0.2f * H1) * (0.2f * H1);
float minDist = (float)Math.sqrt(minDist2);
for (a=0; a<len2 && a<particles.MAX_NEIGHBORS; a++) {
neighborP = tempParticles2[a];
if(neighborP.hash != particle.hash) {
dist.set(particle.posStar);
dist.sub(neighborP.posStar);
if (dist.len2() < minDist2) {
float deltaLen = dist.len();
float diff = 0.1f * 0.5f * (deltaLen - minDist) / deltaLen;
dist.scl(diff);
particle.posStar.Add(dist);
neighborP.posStar.Substract(dist);
}
}
}
}
public void initializePBF() {
H_H = 6.0f;
H1 = (float) Math.sqrt(H_H);
KPOLY = (float) (315f / (64.0f * Math.PI * Math.pow(Math.sqrt(H_H), 9)));
KSPIKY = (float) (45f / (Math.PI * Math.pow(Math.sqrt(H_H), 6)));
KCUSTOM = (float) (945f / (32.0f * Math.PI * Math.pow(Math.sqrt(H_H), 8))) * -3f;
ARTI_PRESSURE_DELTA_Q = 0.1f * H_H;
ARTI_PRESSURE = (float) (KPOLY * Math.pow(H_H - ARTI_PRESSURE_DELTA_Q, 3));
ARTI_PRESSURE_K = (float) (-0.05f / Math.pow(ARTI_PRESSURE, 4));
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/FluidSimulatorSPH.java<|end_filename|>
package com.fluidsimulator;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.Iterator;
import javolution.util.FastMap;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.fluidsimulator.gameobjects.sph.Particle;
import com.fluidsimulator.gameobjects.sph.SpatialTable;
import com.fluidsimulator.gameobjects.sph.Spring;
/**
* This class is the exact copy of the SPH fluid simulation project
* on http://www.github.com/omgware
* No further work has been done on this version so it extends
* FluidSimulatorGeneric just for handling this like the other methods
* in the FluidSimulatorStarter
*/
public class FluidSimulatorSPH extends FluidSimulatorGeneric {
private GL20 gl = null;
// FPS Management
public final float TICKS_PER_SECOND = 60;
public final float SKIP_TICKS = 1 / TICKS_PER_SECOND;
public final float STEPS = 1;
// public final float FIXED_DELTA = SKIP_TICKS / STEPS;
public final float FIXED_DELTA = 0.022f;
public final int MAX_FRAMESKIP = 5;
public int speedMultiplier = 1;
public int speedCounter;
public float timeStep;
public float interpolation;
public float nextGameTick;
public boolean stepped;
public int loops;
public static final boolean USE_FIXED_TIMESTEP = true;
// Tune these statics for platform specific behaviors
public static final boolean IS_DESKTOP = true;
public static final float LINE_VELOCITY_FACTOR = (IS_DESKTOP) ? 0.03f : 0.03f;
public static final int LINE_DENSITY_FACTOR = (IS_DESKTOP) ? 5 : 10;
public static final int WORLD_WIDTH = (IS_DESKTOP) ? 200 : 50;
public static final int WORLD_HEIGHT = (IS_DESKTOP) ? 120 : 30;
public static final int INITIAL_HEIGHT = (IS_DESKTOP) ? 5 : 0;
public static final float TIMESTEP = 0.022f;
public static float GRAVITY_FORCE = -1.0f;
public static final Vector2 gravityVect = new Vector2(0.0f, GRAVITY_FORCE);
public static final int SIZE = 5460;
public static final int ANDROID_SIZE = 200;
public static int MAX_NEIGHBORS = 50;
public static final int wpadding = (IS_DESKTOP) ? 20 : 10;
public static final int hpadding = (IS_DESKTOP) ? 20 : 10;
public static final float collisionForce = (IS_DESKTOP) ? 0.3f : 0.1f;
public static final int SCREEN_WIDTH = (IS_DESKTOP) ? (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth() : 480;
public static final int SCREEN_HEIGHT = (IS_DESKTOP) ? (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight() : 320;
protected SpriteBatch batch;
protected BitmapFont font;
protected OrthographicCamera camera;
public ShaderProgram defaultShader;
public ImmediateModeRenderer20 immediateRenderer;
public boolean touching;
private SpatialTable<Particle> particles = new SpatialTable<Particle>(
WORLD_WIDTH, WORLD_HEIGHT) {
@Override
protected int posX(Particle value) {
return (int) ((value.pos.x + (WORLD_WIDTH / 2) + 0.3f) / CELL_SIZE);
}
@Override
protected int posY(Particle value) {
return (int) ((value.pos.y + 0.3f) / CELL_SIZE);
}
@Override
protected int prevPosX(Particle value) {
return (int) ((value.prevPos.x + (WORLD_WIDTH / 2) + 0.3f) / CELL_SIZE);
}
@Override
protected int prevPosY(Particle value) {
return (int) ((value.prevPos.y + 0.3f) / CELL_SIZE);
}
};
public ArrayList<Spring> springs;
public FastMap<Integer, ArrayList<Integer>> springPresenceTable;
public Iterator<Spring> springIter;
public ArrayList<Particle> disposableParticles;
public ArrayList<Particle> tempParticles;
// Most of these can be tuned at runtime with F1-F9 and keys 1-9 (no numpad)
public static int CELL_SIZE = 1;
public static float H = 5.0f;
public static float H2 = H * H;
public static float K = 0.084f;
public static float K_ = 0.11f;
public static float K_NEAR = K_;
public static float SIGMA = 1.0f;
public static final float BETA = 0.3f;
public static float P0 = 10.0f;
public static final float ATTRACT_FORCE = 0.66f;
public static final float ATTRACT_RANGE = ((float) WORLD_WIDTH) * 2;
public static final float REPULSE_FORCE = 6.6f;
public static final float REPULSE_RANGE = ((float) WORLD_WIDTH) / 2;
public float EMITTER_FORCE = 800;
public float EMITTER_SIZE = 1;
public float K_SPRING = 0.3f;
public static final float REST_LENGTH = 5.0f;
public static final float REST_LENGTH2 = REST_LENGTH * REST_LENGTH;
public static final float YELD_RATIO_STRETCH = 0.5f;
public static final float YELD_RATIO_COMPRESS = 0.5f;
public static final float PLASTICITY = 0.5f;
public static final int VELOCITY_CAP = 150;
public static final int PARTICLE_SIZE = 5;
float deformation;
float dropRadiusK = 0.1f;
float dropRadius;
int dropRadiusPixel;
int dropRadiusPixel2;
final float kNorm = 3.183098862f / 0.09f;
final float kNearNorm = 4.774648293f / 0.09f;
// final float kNorm = 1.0f;
// final float kNearNorm = 1.0f;
final float kSurfaceTension = 0.0004f;
// Temp variables mostly for calculations and graphics processing purpose
int i;
int j;
int k;
int z;
int len;
int len2;
int w;
float q;
float r;
float qq;
float D;
float distX;
float distY;
float u;
float I;
float deltaTime2;
Vector2 dx = new Vector2(0.0f, 0.0f);
Vector2 rij = new Vector2(0.0f, 0.0f);
Vector2 tempVect = new Vector2(0.0f, 0.0f);
Vector2 tempVect2 = new Vector2(0.0f, 0.0f);
Vector2 attract_vect = new Vector2(0.0f, 0.0f);
Vector2 repulse_vect = new Vector2(0.0f, 0.0f);
boolean isAttracting;
boolean isRepulsing;
public float checkTime;
public float checkTime2;
public float checkTime3;
Texture dropTexture;
Sprite dropSprite;
float spriteColor;
Texture dropTexture2;
Vector3 dropCoordinate = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 dropSize = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 tempVect3 = new Vector3(0.0f, 0.0f, 0.0f);
Particle tempParticle;
float tempFloat = 0;
long tempLong = 0;
boolean tempBoolean = false;
int tempInt = 0;
Spring tempSpring;
Mesh lineMesh;
float[] lineVertices;
int vertexIndex = 0;
protected Vector3 testPoint = new Vector3();
protected Vector2 testPoint2D = new Vector2();
// Modes
int emitType = 1;
boolean expandMode = false;
boolean massMode = false;
boolean slowMotion = false;
boolean crazyMode = false;
boolean hudEnabled = true;
boolean linesMode = IS_DESKTOP ? false : true;
boolean smokeMode = false;
boolean whiteBackground = false;
boolean particleRendering = true;
boolean viscoElasticityEnabled = false;
boolean plasticityEnabled = false;
boolean initializePlasticity = false;
boolean initializeViscoelasticity = false;
boolean exitApp;
public FluidSimulatorSPH(FluidSimulatorStarter fluidSimulatorStarter) {
super(fluidSimulatorStarter);
batch = new SpriteBatch(IS_DESKTOP ? 5460 : ANDROID_SIZE);
font = new BitmapFont();
camera = new OrthographicCamera(WORLD_WIDTH, WORLD_HEIGHT);
camera.position.set(0, (WORLD_HEIGHT / 2) - 1, 0);
}
private void createWorld() {
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
if (IS_DESKTOP) {
// dropTexture = new Texture("data/fluid_drop_red_64.png");
dropTexture = new Texture("data/fluid_drop_64.png");
dropTexture2 = new Texture("data/fluid_drop_blue_64.png");
dropSprite = new Sprite(dropTexture);
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
if (IS_DESKTOP) {
disposableParticles = new ArrayList<Particle>(SIZE);
}
defaultShader = new ShaderProgram(Gdx.files.internal("data/shaders/default.vert").readString(),
Gdx.files.internal("data/shaders/default.frag").readString());
if (!defaultShader.isCompiled()) {
Gdx.app.log("SHADER_LOG", "couldn't compile scene shader: " + defaultShader.getLog());
}
immediateRenderer = new ImmediateModeRenderer20(50000, false, true, 0);
// On Android populate directly
if (!IS_DESKTOP) {
for (float j = INITIAL_HEIGHT + hpadding + 2; j < WORLD_HEIGHT - 2; j += 1.0f) {
for (float i = -WORLD_WIDTH / 3; i < WORLD_WIDTH / 3; i += 1.0f) {
particles.add(new Particle(i, j));
tempParticle = particles.get(particles.size() - 1);
tempParticle.type = (emitType);
if (particles.size() >= ANDROID_SIZE)
return;
}
}
}
}
@Override
public void show() {
particles.initialize();
createWorld();
Gdx.input.setInputProcessor(this);
touching = false;
}
protected void performLogic(float deltaTime) {
spawnParticles(deltaTime);
applyViscosity(deltaTime);
if (!expandMode) {
len = particles.size();
for (i=0; i<len; i++) {
particles.get(i).prevPos.set(particles.get(i).pos);
particles.get(i).pos.set(particles.get(i).pos.x + (deltaTime * particles.get(i).velocity.x),
particles.get(i).pos.y + (deltaTime * particles.get(i).velocity.y));
}
}
particles.rehash();
if (viscoElasticityEnabled) {
if (initializeViscoelasticity) {
initializeViscoelasticity();
initializeViscoelasticity = false;
}
calculateViscoelasticity(deltaTime);
} else if (plasticityEnabled) {
if (initializePlasticity) {
initializePlasticity();
initializePlasticity = false;
}
calculatePlasticity(deltaTime);
}
doubleDensityRelaxation(deltaTime);
len = particles.size();
for (i=0; i<len; i++) {
particles.get(i).velocity.set((particles.get(i).pos.x - particles.get(i).prevPos.x) / deltaTime,
(particles.get(i).pos.y - particles.get(i).prevPos.y) / deltaTime);
applyGravity(particles.get(i));
wallCollision(particles.get(i));
attract(particles.get(i));
repulse(particles.get(i));
if (IS_DESKTOP)
capVelocity(particles.get(i).velocity);
if (IS_DESKTOP)
prepareDeleteOutOfBoundsParticles(particles.get(i));
//particles.updatePosition(particles.get(i));
}
}
private void spawnParticles(float deltaTime) {
if (touching && (IS_DESKTOP) && (!isAttracting) && (!isRepulsing)
&& (particles.size() < SIZE - 1)) {
if (!((testPoint2D.x < (-WORLD_WIDTH / 2 + wpadding) || testPoint2D.x > (WORLD_WIDTH / 2 - wpadding))
|| (testPoint2D.y < (INITIAL_HEIGHT + hpadding) || testPoint2D.y > (WORLD_HEIGHT - hpadding)))) {
for (float i = -EMITTER_SIZE; i < EMITTER_SIZE; i += 1.0f) {
for (float j = -EMITTER_SIZE; j < EMITTER_SIZE; j += 1.0f) {
if (particles.size() >= SIZE - 1)
break;
particles.add(new Particle(testPoint2D.x + i, testPoint2D.y - j));
tempParticle = particles.get(particles.size() - 1);
tempParticle.type = (emitType);
if (!linesMode) {
if (emitType == 2)
tempParticle.mass = 3;
else if (emitType == 3)
tempParticle.mass = 5;
}
if (viscoElasticityEnabled)
springPresenceTable.put(tempParticle.hashCode(),
new ArrayList<Integer>(SIZE));
tempParticle.velocity.set(tempParticle.velocity.x,
tempParticle.velocity.y - EMITTER_FORCE * deltaTime);
}
}
}
}
}
private static void capVelocity(Vector2 v) {
if (v.x > VELOCITY_CAP)
v.x = VELOCITY_CAP;
else if (v.x < -VELOCITY_CAP)
v.x = -VELOCITY_CAP;
if (v.y > VELOCITY_CAP)
v.y = VELOCITY_CAP;
else if (v.y < -VELOCITY_CAP)
v.y = -VELOCITY_CAP;
}
private void initializePlasticity() {
springs.clear();
len = particles.size();
for (i=0; i<len; i++) {
for (j=0; j<len; j++) {
if (particles.get(i).hashCode() == particles.get(j).hashCode())
continue;
q = particles.get(i).pos.dst(particles.get(j).pos);
rij.set(particles.get(j).pos);
rij.sub(particles.get(i).pos);
rij.scl(1 / q);
if (q < REST_LENGTH) {
springs.add(new Spring(particles.get(i), particles.get(j), q));
}
}
particles.get(i).velocity.set(0, 0);
}
}
private void calculatePlasticity(float deltaTime) {
len = springs.size();
for (i=0; i<len; i++) {
springs.get(i).update();
if (springs.get(i).currentDistance == 0)
continue;
rij.set(springs.get(i).pj.pos);
rij.sub(springs.get(i).pi.pos);
rij.scl(1 / springs.get(i).currentDistance);
// D = deltaTime2 * K_SPRING * (1 - (springs.get(i).restLength/REST_LENGTH)) *
// (springs.get(i).restLength - springs.get(i).currentDistance);
D = deltaTime * K_SPRING * (springs.get(i).restLength - springs.get(i).currentDistance);
rij.scl(D * 0.5f);
springs.get(i).pi.pos.set(springs.get(i).pi.pos.x - rij.x, springs.get(i).pi.pos.y - rij.y);
springs.get(i).pj.pos.set(springs.get(i).pj.pos.x + rij.x, springs.get(i).pj.pos.y + rij.y);
}
}
private void initializeViscoelasticity() {
len = particles.size();
for (i=0; i<len; i++) {
springPresenceTable.put(particles.get(i).hashCode(), new ArrayList<Integer>(SIZE));
particles.get(i).velocity.set(0, 0);
}
}
/** NOTE: still in testing
* tune YELD_RATIO_STRETCH, YELD_RATIO_COMPRESS and K_SPRING
* to test viscoelasticity
**/
private void calculateViscoelasticity(float deltaTime) {
deltaTime2 = (deltaTime * deltaTime);
len = particles.size();
for (i=0; i<len; i++) {
if (particles.sizeNearby(particles.get(i)) <= 1)
continue;
tempParticles = particles.nearby(particles.get(i));
len2 = tempParticles.size();
if (len2 > MAX_NEIGHBORS)
len2 = MAX_NEIGHBORS;
for (j=0; j<len2; j++) {
if (particles.get(i).hashCode() == particles.get(j).hashCode()
|| particles.get(i).pos.dst2(particles.get(j).pos) > REST_LENGTH2)
continue;
if (!springPresenceTable.get(particles.get(i).hashCode()).contains(
particles.get(j).hashCode())) {
springs.add(new Spring(particles.get(i), particles.get(j), REST_LENGTH));
springPresenceTable.get(particles.get(i).hashCode()).add(particles.get(j).hashCode());
}
}
}
for (springIter = springs.iterator(); springIter.hasNext();) {
tempSpring = springIter.next();
tempSpring.update();
// Stretch
if (tempSpring.currentDistance > (tempSpring.restLength + deformation)) {
tempSpring.restLength += deltaTime
* PLASTICITY
* (tempSpring.currentDistance - tempSpring.restLength - (YELD_RATIO_STRETCH * tempSpring.restLength));
}
// Compress
else if (tempSpring.currentDistance < (tempSpring.restLength - deformation)) {
tempSpring.restLength -= deltaTime
* PLASTICITY
* (tempSpring.restLength
- (YELD_RATIO_COMPRESS * tempSpring.restLength) - tempSpring.currentDistance);
}
// Remove springs with restLength longer than REST_LENGTH
if (tempSpring.restLength > REST_LENGTH) {
springIter.remove();
springPresenceTable.get(tempSpring.pi.hashCode()).remove(
(Integer) tempSpring.pj.hashCode());
} else {
if (tempSpring.currentDistance == 0)
continue;
rij.set(tempSpring.pj.pos);
rij.sub(tempSpring.pi.pos);
rij.scl(1 / tempSpring.currentDistance);
//D = deltaTime2 * K_SPRING * (1 - (tempSpring.restLength/REST_LENGTH)) * (tempSpring.restLength - tempSpring.currentDistance);
D = deltaTime * K_SPRING * (tempSpring.restLength - tempSpring.currentDistance);
rij.scl(D * 0.5f);
tempSpring.pi.pos.set(tempSpring.pi.pos.x - rij.x,
tempSpring.pi.pos.y - rij.y);
tempSpring.pj.pos.set(tempSpring.pj.pos.x + rij.x,
tempSpring.pj.pos.y + rij.y);
}
}
}
private void applyGravity(Particle pi) {
if (massMode)
pi.velocity.set(pi.velocity.x + (gravityVect.x * pi.mass), pi.velocity.y
+ (gravityVect.y * pi.mass));
else
pi.velocity.set(pi.velocity.x + (gravityVect.x), pi.velocity.y
+ (gravityVect.y));
}
private void applyViscosity(float deltaTime) {
len = particles.size();
for (i=0; i<len; i++) {
/*particles.get(i).density = 0;
particles.get(i).nearDensity = 0;*/
tempParticles = particles.nearby(particles.get(i));
len2 = tempParticles.size();
if (len2 > MAX_NEIGHBORS)
len2 = MAX_NEIGHBORS;
for (j=0; j<len2; j++) {
// Distance between p(i) and p(j)
q = particles.get(i).pos.dst2(tempParticles.get(j).pos);
if ((q < H2) && (q != 0)) {
q = (float) Math.sqrt(q);
r = q;
rij.set(tempParticles.get(j).pos);
rij.sub(particles.get(i).pos);
// rij normalized
rij.scl(1 / q);
// q = rij/H
q /= H;
/*qq = ((1 - q) * (1 - q));
particles.get(i).density += qq;
particles.get(i).nearDensity += qq * (1 - q);*/
tempVect.set(particles.get(i).velocity);
tempVect.sub(tempParticles.get(j).velocity);
u = tempVect.dot(rij);
if (u <= 0.0f)
continue;
I = (deltaTime * (1 - q) * (SIGMA * u + BETA * u * u));
rij.scl(I * 0.5f);
// vi -= I/2
tempVect.set(particles.get(i).velocity);
tempVect.sub(rij);
particles.get(i).velocity.set(tempVect);
// vj += I/2
tempVect.set(tempParticles.get(j).velocity);
tempVect.add(rij);
tempParticles.get(j).velocity.set(tempVect);
}
}
}
}
private void doubleDensityRelaxation(float deltaTime) {
if (crazyMode)
deltaTime2 = deltaTime;
else
deltaTime2 = (deltaTime * deltaTime);
len = particles.size();
for (i=0; i<len; i++) {
particles.get(i).density = 0;
particles.get(i).nearDensity = 0;
tempParticles = particles.nearby(particles.get(i));
len2 = tempParticles.size();
if (len2 > MAX_NEIGHBORS)
len2 = MAX_NEIGHBORS;
for (j=0; j<len2; j++) {
q = particles.get(i).pos.dst2(tempParticles.get(j).pos);
if (q < H2 && q != 0) {
q = (float)Math.sqrt(q);
q /= H;
qq = ((1 - q) * (1 - q) * (1 - q));
particles.get(i).density += qq * particles.get(i).mass * kNorm;
particles.get(i).nearDensity += qq * (1 - q) * particles.get(i).mass * kNearNorm;
}
}
particles.get(i).pressure = (K * (particles.get(i).density - P0 * particles.get(i).mass));
particles.get(i).nearPressure = (K_NEAR * particles.get(i).nearDensity);
dx.set(0.0f, 0.0f);
for (j=0; j<len2; j++) {
q = particles.get(i).pos.dst2(tempParticles.get(j).pos);
if ((q < H2) && (q != 0)) {
q = (float) Math.sqrt(q);
rij.set(tempParticles.get(j).pos);
rij.sub(particles.get(i).pos);
rij.scl(1 / (q * particles.get(i).mass));
q /= H;
qq = ((1 - q) * (1 - q));
// D = (deltaTime2 * (particles.get(i).pressure * (1 - q) + particles.get(i).nearPressure * qq));
D = deltaTime2 * ( ((particles.get(i).nearPressure + tempParticles.get(j).nearPressure) * qq * (1 - q))
+ ((particles.get(i).pressure + tempParticles.get(j).pressure) * qq) );
rij.scl(D * 0.5f);
tempParticles.get(j).pos.set(tempParticles.get(j).pos.x + rij.x, tempParticles.get(j).pos.y + rij.y);
dx.sub(rij);
// SURFACE TENSION
if (particles.get(i).mass == tempParticles.get(j).mass) {
distX = tempParticles.get(j).pos.x - particles.get(i).pos.x;
distY = tempParticles.get(j).pos.y - particles.get(i).pos.y;
dx.add((kSurfaceTension/particles.get(i).mass) * tempParticles.get(j).mass * qq * kNorm * distX,
(kSurfaceTension/particles.get(i).mass) * tempParticles.get(j).mass * qq * kNorm * distY);
}
}
}
particles.get(i).pos.set(particles.get(i).pos.add(dx));
}
}
private void attract(Particle pi) {
if (isAttracting) {
if (pi.pos.dst2(testPoint2D) > ATTRACT_RANGE)
return;
attract_vect.set(testPoint2D);
attract_vect.sub(pi.pos);
pi.velocity.set(pi.velocity.x
+ (attract_vect.x * ATTRACT_FORCE), pi.velocity.y
+ (attract_vect.y * ATTRACT_FORCE));
}
}
private void repulse(Particle pi) {
if (isRepulsing) {
if (pi.pos.dst2(testPoint2D) > REPULSE_RANGE)
return;
repulse_vect.set(pi.pos);
repulse_vect.sub(testPoint2D);
pi.velocity.set(pi.velocity.x
+ (repulse_vect.x * REPULSE_FORCE), pi.velocity.y
+ (repulse_vect.y * REPULSE_FORCE));
}
}
private void wallCollision(Particle pi) {
tempVect.set(0, 0);
if (pi.pos.x > (WORLD_WIDTH / 2 - wpadding))
tempVect.sub((pi.pos.x - (WORLD_WIDTH / 2 - wpadding))
/ collisionForce, 0);
else if (pi.pos.x < (-WORLD_WIDTH / 2 + wpadding))
tempVect.add(((-WORLD_WIDTH / 2 + wpadding) - pi.pos.x)
/ collisionForce, 0);
if (pi.pos.y > (WORLD_HEIGHT - hpadding))
tempVect.sub(0, (pi.pos.y - (WORLD_HEIGHT - hpadding))
/ collisionForce);
else if (pi.pos.y < (INITIAL_HEIGHT + hpadding))
tempVect.add(0, ((INITIAL_HEIGHT + hpadding) - pi.pos.y)
/ collisionForce);
pi.velocity.set(pi.velocity.x + tempVect.x, pi.velocity.y
+ tempVect.y);
}
private void prepareDeleteOutOfBoundsParticles(Particle pi) {
if ((pi.pos.x < -WORLD_WIDTH / 2)
|| (pi.pos.x > WORLD_WIDTH / 2) || (pi.pos.y < 0)
|| (pi.pos.y > WORLD_HEIGHT)) {
disposableParticles.add(pi);
}
}
private void prepareDeleteOutOfBoundsParticles() {
len = disposableParticles.size();
for (i=0; i<len; i++) {
particles.remove(disposableParticles.get(i));
}
}
public void deleteOutOfBoundsParticles() {
disposableParticles.clear();
}
public boolean touchDown(int x, int y, int pointer, int button) {
touching = true;
camera.unproject(testPoint.set(x, y, 0));
testPoint2D.x = testPoint.x;
testPoint2D.y = testPoint.y;
if (button == Buttons.LEFT) {
if (!IS_DESKTOP) {
isRepulsing = true;
isAttracting = false;
} else {
isAttracting = false;
isRepulsing = false;
}
}
if (button == Buttons.RIGHT) {
isAttracting = true;
}
if (button == Buttons.MIDDLE) {
isRepulsing = true;
}
return false;
}
public boolean touchDragged(int x, int y, int pointer) {
camera.unproject(testPoint.set(x, y, 0));
testPoint2D.x = testPoint.x;
testPoint2D.y = testPoint.y;
return false;
}
public boolean touchUp(int x, int y, int pointer, int button) {
touching = false;
if (!IS_DESKTOP) {
isRepulsing = false;
isAttracting = false;
}
if (button == Buttons.RIGHT) {
isAttracting = false;
}
if (button == Buttons.MIDDLE) {
isRepulsing = false;
}
return false;
}
public void render(float deltaTime) {
timeStep += deltaTime;
stepped = false;
loops = 0;
while (timeStep > nextGameTick
&& loops < MAX_FRAMESKIP) {
for (speedCounter = 0; speedCounter < speedMultiplier; speedCounter++) {
if (slowMotion)
performLogic(SKIP_TICKS / 4);
else {
// for (k = 0; k < STEPS; k++)
performLogic(FIXED_DELTA);
}
if (IS_DESKTOP) {
prepareDeleteOutOfBoundsParticles();
deleteOutOfBoundsParticles();
}
}
stepped = true;
nextGameTick += SKIP_TICKS;
loops++;
}
interpolation = (timeStep + SKIP_TICKS - nextGameTick) / SKIP_TICKS;
camera.update();
if (gl == null) {
gl = Gdx.gl20;
}
if (whiteBackground)
gl.glClearColor(255, 255, 255, 255);
else
gl.glClearColor(0, 0, 0, 255);
gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
// gl.glEnable(GL10.GL_LINE_SMOOTH);
// gl.glHint(GL10.GL_LINE_SMOOTH_HINT, GL20.GL_NICEST);
gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);
gl.glEnable(GL20.GL_BLEND);
gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
// gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE);
// Begin Batch
if (particleRendering) {
if (!linesMode) {
len = particles.size();
batch.setProjectionMatrix(camera.combined);
batch.begin();
for (i=0; i<len; i++) {
dropCoordinate.set(particles.get(i).pos.x - dropRadius,
particles.get(i).pos.y - dropRadius, 0.0f);
// camera.project(dropCoordinate);
spriteColor = 1.0f/* - (particles.get(i).density * LINE_DENSITY_FACTOR / 255.0f)*/;
if (spriteColor < 0.2f)
spriteColor = 0.2f;
if (particles.get(i).type == 1)
dropSprite.setColor(spriteColor, 0, 0, 1);
else if (particles.get(i).type == 2)
dropSprite.setColor(0, spriteColor, 0, 1);
else if (particles.get(i).type == 3)
dropSprite.setColor(0, 0, spriteColor, 1);
dropSprite.setPosition(dropCoordinate.x, dropCoordinate.y);
// if (particles.get(i).type == 1)
// batch.draw(dropTexture, dropCoordinate.x,
// dropCoordinate.y, dropRadiusPixel,
// dropRadiusPixel);
// else
// batch.draw(dropTexture2, dropCoordinate.x,
// dropCoordinate.y, dropRadiusPixel,
// dropRadiusPixel);
dropSprite.draw(batch);
}
batch.end();
} else {
immediateRenderer.begin(camera.combined, GL20.GL_LINES);
vertexIndex = 0;
len = particles.size();
for (i=0; i<len; i++) {
if (smokeMode) {
// Red Fire
if (emitType == 1) {
tempInt = 255 - (int) ((System.currentTimeMillis() - particles.get(i)
.spawnTime) / 50);
// Start by decreasing B value to 0
particles.get(i).setBGrad(240 - (int) ((System
.currentTimeMillis() - particles.get(i).spawnTime) / (3 * 1)));
// Then decrease G value to 0
if (particles.get(i).bGrad < 150)
particles.get(i).setGGrad(255 - (int) ((System
.currentTimeMillis() - particles.get(i)
.spawnTime) / (10 * 1)));
// Then decrease R value to 0
if (particles.get(i).gGrad < 150)
particles.get(i).setRGrad(255 - (int) ((System
.currentTimeMillis() - particles.get(i)
.spawnTime) / (25 * 1)));
if (tempInt <= 0 || particles.get(i).rGrad == 0) {
disposableParticles.add(particles.get(i));
continue;
}
}
// Blue Fire
else if (emitType == 2) {
tempInt = 255 - (int) ((System.currentTimeMillis() - particles.get(i)
.spawnTime) / 50);
// Start by decreasing R value to 0
particles.get(i).setRGrad(240 - (int) ((System
.currentTimeMillis() - particles.get(i).spawnTime) / (3 * 1)));
// Then decrease G value to 0
if (particles.get(i).rGrad < 150)
particles.get(i).setGGrad(255 - (int) ((System
.currentTimeMillis() - particles.get(i)
.spawnTime) / (10 * 1)));
// Then decrease B value to 0
if (particles.get(i).gGrad < 150)
particles.get(i).setBGrad(255 - (int) ((System
.currentTimeMillis() - particles.get(i)
.spawnTime) / (25 * 1)));
if (tempInt <= 0 || particles.get(i).bGrad == 0) {
disposableParticles.add(particles.get(i));
continue;
}
}
// Green Fire
else if (emitType == 3) {
tempInt = 255 - (int) ((System.currentTimeMillis() - particles.get(i)
.spawnTime) / 50);
// Start by decreasing R and B values to 0
particles.get(i).setRGrad(240 - (int) ((System
.currentTimeMillis() - particles.get(i).spawnTime) / (10 * 1)));
particles.get(i).setBGrad(240 - (int) ((System
.currentTimeMillis() - particles.get(i).spawnTime) / (10 * 1)));
// Then decrease G value to 0
if (particles.get(i).rGrad < 150)
particles.get(i).setGGrad(255 - (int) ((System
.currentTimeMillis() - particles.get(i)
.spawnTime) / (25 * 1)));
if (tempInt <= 0 || particles.get(i).gGrad == 0) {
disposableParticles.add(particles.get(i));
continue;
}
}
}
dropCoordinate.set((particles.get(i).pos.x + (particles.get(i).velocity.x * interpolation * deltaTime)) - dropRadius,
(particles.get(i).pos.y + (particles.get(i).velocity.y * interpolation * deltaTime)) - dropRadius, 0.0f);
// camera.project(dropCoordinate);
// lineVertices[vertexIndex++] = dropCoordinate.x;
// lineVertices[vertexIndex++] = dropCoordinate.y;
if (smokeMode) {
// lineVertices[vertexIndex++] = Color.toFloatBits(
// particles.get(i).rGrad, particles.get(i).gGrad, particles.get(i).bGrad,
// tempInt);
immediateRenderer.color((float)particles.get(i).rGrad / 255.0f,
(float)particles.get(i).gGrad / 255.0f, (float)particles.get(i).bGrad / 255.0f, (float)tempInt / 255.0f);
}
else {
if (particles.get(i).type == 1)
// lineVertices[vertexIndex++] = Color.toFloatBits(
// 255, (int) particles.get(i).density
// * LINE_DENSITY_FACTOR, 0, 255);
immediateRenderer.color(1, particles.get(i).density
* LINE_DENSITY_FACTOR / 255.0f, 0, 1);
else if (particles.get(i).type == 2)
// lineVertices[vertexIndex++] = Color
// .toFloatBits((int) particles.get(i).density
// * LINE_DENSITY_FACTOR, 0, 255, 255);
immediateRenderer.color(particles.get(i).density
* LINE_DENSITY_FACTOR / 255, 0, 1, 1);
else if (particles.get(i).type == 3)
// lineVertices[vertexIndex++] = Color.toFloatBits(0,
// 200, (int) particles.get(i).density
// * LINE_DENSITY_FACTOR, 255);
immediateRenderer.color(0, 0.78f, particles.get(i).density
* LINE_DENSITY_FACTOR / 255, 1);
}
// lineVertices[vertexIndex++] = dropCoordinate.x
// + particles.get(i).velocity.x * LINE_VELOCITY_FACTOR;
// lineVertices[vertexIndex++] = dropCoordinate.y
// + particles.get(i).velocity.y * LINE_VELOCITY_FACTOR;
immediateRenderer.vertex(dropCoordinate.x, dropCoordinate.y, 0);
if (smokeMode)
// lineVertices[vertexIndex++] = Color.toFloatBits(
// particles.get(i).rGrad, particles.get(i).gGrad, particles.get(i).bGrad,
// tempInt);
immediateRenderer.color((float)particles.get(i).rGrad / 255.0f,
(float)particles.get(i).gGrad / 255.0f, (float)particles.get(i).bGrad / 255.0f, (float)tempInt / 255.0f);
else {
if (particles.get(i).type == 1)
// lineVertices[vertexIndex++] = Color.toFloatBits(
// 255, (int) particles.get(i).density
// * LINE_DENSITY_FACTOR, 0, 255);
immediateRenderer.color(1, particles.get(i).density
* LINE_DENSITY_FACTOR / 255, 0, 1);
else if (particles.get(i).type == 2)
// lineVertices[vertexIndex++] = Color
// .toFloatBits((int) particles.get(i).density
// * LINE_DENSITY_FACTOR, 0, 255, 255);
immediateRenderer.color(particles.get(i).density
* LINE_DENSITY_FACTOR / 255, 0, 1, 1);
else if (particles.get(i).type == 3)
// lineVertices[vertexIndex++] = Color.toFloatBits(0,
// 200, (int) particles.get(i).density
// * LINE_DENSITY_FACTOR, 255);
immediateRenderer.color(0, 0.78f, particles.get(i).density
* LINE_DENSITY_FACTOR / 255, 1);
}
immediateRenderer.vertex(dropCoordinate.x + particles.get(i).velocity.x * LINE_VELOCITY_FACTOR,
dropCoordinate.y + particles.get(i).velocity.y * LINE_VELOCITY_FACTOR, 0);
}
// lineMesh.setVertices(lineVertices, 0, vertexIndex);
// defaultShader.begin();
// lineMesh.render(defaultShader, GL20.GL_LINES);
// defaultShader.end();
immediateRenderer.end();
}
}
if (hudEnabled) {
gl.glDisable(GL20.GL_BLEND);
batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.begin();
font.draw(batch,
"FLUID SIMULATION fps:" + Gdx.graphics.getFramesPerSecond()
+ ", particles: " + particles.size(), 0.0f, 20.0f);
if (IS_DESKTOP) {
font.draw(batch, "deltaTime: " + deltaTime, 0.0f, 40.0f);
font.draw(batch, "(SPACE) Fluid Type: " + emitType
+ " (+/-) Gravity: " + GRAVITY_FORCE
+ " (UP/DOWN) Emitter: " + EMITTER_SIZE
+ " (E) Expand: " + expandMode + " (S) Slow: "
+ slowMotion + " (C) Crazy: " + crazyMode
+ " (L) Lines: " + linesMode, 330.0f, 60.0f);
font.draw(batch, "(K) Smoke: " + smokeMode + " (P) Plasticity: "
+ plasticityEnabled + " (V) ViscoElasticity: "
+ viscoElasticityEnabled + " (R) Particle Render: "
+ particleRendering + " (M) Mass: "
+ massMode, 330.0f, 40.0f);
font.draw(
batch,
"K: " + K + " Sigma: " + SIGMA
+ " Density: " + P0 + " H: " + H
+ " Cell: " + CELL_SIZE + " K_: " + K_
+ " Rad: "
+ dropRadiusK + " K_SRING: "
+ K_SPRING + " MN: "
+ MAX_NEIGHBORS, 330.0f, 20.0f);
}
batch.end();
}
// Exit the application if ESC has been pressed
if (exitApp)
Gdx.app.exit();
}
public boolean keyUp(int keycode) {
// K
if (keycode == Input.Keys.F1 && K < 0.5f) {
K += 0.01f;
} else if (keycode == Input.Keys.NUM_1 && K > 0.004f) {
K -= 0.01f;
if (K < 0.004f)
K = 0.004f;
}
// SIGMA
else if (keycode == Input.Keys.F2 && SIGMA < 1.0f)
SIGMA += 0.1f;
else if (keycode == Input.Keys.NUM_2 && SIGMA > 0.0f)
SIGMA -= 0.1f;
// DENSITY
else if (keycode == Input.Keys.F3 && P0 < 1000.0f)
P0 += 100.0f;
else if (keycode == Input.Keys.NUM_3 && P0 > 100.0f)
P0 -= 100.0f;
// H
else if (keycode == Input.Keys.F4 && H < 50.0f) {
H += 5.0f;
H2 = H * H;
} else if (keycode == Input.Keys.NUM_4 && H > 5.0f) {
H -= 5.0f;
H2 = H * H;
}
// CELL_SIZE
else if (keycode == Input.Keys.F5 && CELL_SIZE < 50) {
CELL_SIZE += 1;
particles.rehash();
} else if (keycode == Input.Keys.NUM_5 && CELL_SIZE > 1) {
CELL_SIZE -= 1;
particles.rehash();
}
// K_
if (keycode == Input.Keys.F6 && K_ < 10.0f) {
K_ += 0.1f;
K_NEAR = K_;
} else if (keycode == Input.Keys.NUM_6 && K_ > 0.1f) {
K_ -= 0.1f;
K_NEAR = K_;
}
// MAX_NEIGHBORS
if (keycode == Input.Keys.F7 && MAX_NEIGHBORS < 200) {
MAX_NEIGHBORS += 5;
} else if (keycode == Input.Keys.NUM_7 && MAX_NEIGHBORS > 25) {
MAX_NEIGHBORS -= 5;
}
// dropRadiusK
if (keycode == Input.Keys.F8 && dropRadiusK < 1.5f) {
dropRadiusK += 0.2f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
} else if (keycode == Input.Keys.NUM_8 && dropRadiusK >= 0.3f) {
dropRadiusK -= 0.2f;
dropRadius = 0.1f + dropRadiusK;
dropRadiusPixel = (int) (dropRadius * PARTICLE_SIZE);
dropRadiusPixel2 = dropRadiusPixel * dropRadiusPixel;
dropSprite.setSize(dropRadiusPixel, dropRadiusPixel);
}
// K_SPRING
if (keycode == Input.Keys.F9 && K_SPRING < 5.0f)
K_SPRING += 0.1f;
else if (keycode == Input.Keys.NUM_9 && K_SPRING > 0.2f)
K_SPRING -= 0.1f;
if (keycode == Input.Keys.BACKSPACE && isAttracting) {
for (Particle pi : particles) {
if (pi.pos.dst2(testPoint2D) < ATTRACT_RANGE) {
disposableParticles.add(pi);
}
}
} else if (keycode == Input.Keys.BACKSPACE && IS_DESKTOP) {
for (Particle pi : particles)
disposableParticles.add(pi);
}
// Change Particle color
if (keycode == Input.Keys.SPACE) {
emitType += 1;
if (emitType > 3) {
emitType = 1;
}
}
// Increase/Decrease Gravity
if ((keycode == Input.Keys.PLUS) && (GRAVITY_FORCE > -1.0f)) {
GRAVITY_FORCE -= 0.1f;
gravityVect.set(0.0f, GRAVITY_FORCE);
} else if ((keycode == Input.Keys.MINUS) && (GRAVITY_FORCE < 0.0f)) {
GRAVITY_FORCE += 0.1f;
if (GRAVITY_FORCE > -0.1f)
GRAVITY_FORCE = 0.0f;
gravityVect.set(0.0f, GRAVITY_FORCE);
}
// Increase/Decrease Emitter Size
if ((keycode == Input.Keys.DOWN) && (EMITTER_SIZE > 1)) {
EMITTER_SIZE -= 1;
} else if ((keycode == Input.Keys.UP) && (EMITTER_SIZE < 20)) {
EMITTER_SIZE += 1;
}
// Enable/Disable Expand Mode
if (keycode == Input.Keys.E)
expandMode = !expandMode;
// Enable/Disable Stop Motion
if (keycode == Input.Keys.S)
slowMotion = !slowMotion;
// Enable/Disable Crazy Mode
if (keycode == Input.Keys.C)
crazyMode = !crazyMode;
// Enable/Disable HUD
if (keycode == Input.Keys.H)
hudEnabled = !hudEnabled;
// Mass Mode
if (keycode == Input.Keys.M) {
massMode = !massMode;
}
// Enable/Disable Plasticity
if (keycode == Input.Keys.P && !viscoElasticityEnabled && IS_DESKTOP) {
plasticityEnabled = !plasticityEnabled;
if (plasticityEnabled) {
initializePlasticity = true;
if (springs == null && springPresenceTable == null) {
springs = new ArrayList<Spring>(SIZE * 230);
springPresenceTable = new FastMap<Integer, ArrayList<Integer>>(
SIZE);
}
} else {
springs.clear();
springPresenceTable.clear();
}
}
// Enable/Disable ViscoElasticity
if (keycode == Input.Keys.V && !plasticityEnabled && IS_DESKTOP) {
viscoElasticityEnabled = !viscoElasticityEnabled;
if (viscoElasticityEnabled) {
initializeViscoelasticity = true;
if (springs == null && springPresenceTable == null) {
springs = new ArrayList<Spring>(SIZE * 230);
springPresenceTable = new FastMap<Integer, ArrayList<Integer>>(
SIZE);
}
springs.clear();
springPresenceTable.clear();
} else {
springs.clear();
springPresenceTable.clear();
System.gc();
}
}
// Enable/Disable Lines mode
if (keycode == Input.Keys.L) {
linesMode = !linesMode;
}
// Enable/Disable Smoke Mode
if (keycode == Input.Keys.K)
smokeMode = !smokeMode;
// Enable/Disable Particle Rendering
if (keycode == Input.Keys.R)
particleRendering = !particleRendering;
// Enable/Disable White Background
if (keycode == Input.Keys.X)
whiteBackground = !whiteBackground;
// Exit
if (keycode == Input.Keys.ESCAPE) {
exitApp = true;
}
return false;
}
public void dispose() {
if (IS_DESKTOP)
disposableParticles.clear();
particles.clear();
if (springs != null)
springs.clear();
if (springPresenceTable != null)
springPresenceTable.clear();
lineVertices = null;
if (lineMesh != null)
lineMesh.dispose();
if (IS_DESKTOP) {
dropTexture.dispose();
dropTexture2.dispose();
}
lineMesh = null;
}
@Override
public boolean keyDown(int arg0) {
return false;
}
@Override
public boolean keyTyped(char arg0) {
return false;
}
@Override
public boolean scrolled(int arg0) {
return false;
}
public boolean touchMoved(int arg0, int arg1) {
return false;
}
@Override
public void hide() {
dispose();
}
@Override
public void pause() {
}
@Override
public void resize(int arg0, int arg1) {
}
@Override
public void resume() {
}
@Override
public boolean mouseMoved(int arg0, int arg1) {
return false;
}
}
<|start_filename|>fluid-simulator/bin/data/shaders/refract.frag<|end_filename|>
varying vec3 Position;
varying vec3 Normal;
/*uniform sampler2D Texture;
uniform float ScreenResX, ScreenResY;
uniform float Alpha;*/
void main()
{
/*vec2 PixelTexCoords = vec2(gl_FragCoord.x / ScreenResX, gl_FragCoord.y / ScreenResY);
vec3 Refract = normalize(refract(Position, Normal, 1.20));
gl_FragColor.rgb = mix(texture2D(Texture, PixelTexCoords + Refract.xy*0.1), gl_Color, Alpha).rgb;
gl_FragColor.a = gl_Color.a;*/
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
/*uniform sampler2D Texture;
uniform float RefractionIndex;
uniform vec3 SpecularColour;
uniform float Roughness;
uniform float SpecularIntensity;
varying vec3 V;
varying vec3 N;
varying vec3 L;
void main()
{
vec3 v = normalize(V);
vec3 i = -v;
vec3 n = normalize(N);
vec3 l = normalize(L);
vec3 h = normalize(l+v);
vec3 Refracted = refract(i,n,RefractionIndex);
Refracted = vec3(gl_TextureMatrix[0] * vec4(Refracted,1.0));
vec3 Reflected = reflect(i,n);
Reflected = vec3(gl_TextureMatrix[0] * vec4(Reflected,1.0));
float specular = pow(max(0.0,dot(n,h)),1/Roughness);
vec3 refractColor = SpecularColour*specular*SpecularIntensity +
mix(vec3(texture2D(Texture,Reflected)),
vec3(texture2D(Texture,Refracted)),
dot(n,v));
gl_FragColor = vec4(refractColor,1.0);
}*/
<|start_filename|>fluid-simulator/src/com/fluidsimulator/gameobjects/Particle.java<|end_filename|>
package com.fluidsimulator.gameobjects;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.utils.Pool.Poolable;
import com.fluidsimulator.utils.Vector2;
public class Particle implements Poolable {
public int hash;
public float density;
public float nearDensity;
public float pressure;
public float nearPressure;
public float mass = 1;
public Vector2 prevPos = new Vector2();
public Vector2 pos = new Vector2();
public Vector2 drawPos = new Vector2();
public Vector2 velocity = new Vector2();
public Vector2 prevVelocity = new Vector2();
public Vector2 relativeVelocity = new Vector2();
public Vector2 prevGridPos = new Vector2();
public Vector2 posStar = new Vector2(); // a temp pos before applying constaints
public Vector2 deltaPos = new Vector2();
public Vector2 force = new Vector2();
public Particle[] neighbors;
public int neighborsSize;
public float lamda;
public float constraint;
public int gridPosX;
public int gridPosY;
public int type = 1;
public long spawnTime;
public int rGrad = 255;
public int gGrad = 255;
public int bGrad = 255;
public Body attachedBody;
public float xchange;
public float ychange;
public float xs;
public float ys;
public float vxs;
public float vys;
// Rigid bodies collisions
public boolean rigidBodyHit;
public Vector2 contactPoint = new Vector2();
public Vector2 contactNormal = new Vector2();
public Vector2 lastSafePos = new Vector2();
public int contactPieceHash;
public int collisionPieceHash;
// Portals
public long timeCheck;
public Particle(float posX, float posY, int hash) {
this.pos.set(posX, posY);
this.spawnTime = System.currentTimeMillis();
this.hash = hash;
}
public Particle setPos(float x, float y) {
this.pos.set(x, y);
this.spawnTime = System.currentTimeMillis();
return this;
}
public Particle setPos(Vector2 vec) {
this.pos.set(vec.x, vec.y);
this.spawnTime = System.currentTimeMillis();
return this;
}
public Particle(Vector2 newPos) {
this.pos.set(newPos.x, newPos.y);
}
public void setRGrad(int value) {
if (value < 0)
value = 0;
this.rGrad = value;
}
public void setGGrad(int value) {
if (value < 0)
value = 0;
this.gGrad = value;
}
public void setBGrad(int value) {
if (value < 0)
value = 0;
this.bGrad = value;
}
public void updateTime() {
this.timeCheck = System.currentTimeMillis();
}
public boolean hasTimePassed(long delay) {
return (System.currentTimeMillis() - timeCheck) >= delay;
}
@Override
public void reset() {
this.pos.set(0, 0);
this.prevPos.set(0, 0);
this.velocity.set(0, 0);
this.spawnTime = System.currentTimeMillis();
this.density = 0;
this.nearDensity = 0;
this.pressure = 0;
this.nearPressure = 0;
this.mass = 1;
this.rGrad = 255;
this.gGrad = 255;
this.bGrad = 255;
}
public Vector2 getVelocity() {
return velocity;
}
public void setVelocity(Vector2 value) {
this.velocity = value;
}
public Vector2 getForce() {
return force;
}
public void setForce(Vector2 value) {
this.force = value;
}
public Vector2 getPos() {
return pos;
}
public void setPosStar(Vector2 value) {
this.posStar = value;
}
public Vector2 getPosStar() {
return posStar;
}
public float getLamda() {
return lamda;
}
public void setLamda(float f) {
this.lamda = f;
}
public float getConstraint() {
return constraint;
}
public void setConstraint(float f) {
this.constraint = f;
}
public Vector2 getDeltaPos() {
return deltaPos;
}
public void setDeltaPos(Vector2 delta) {
this.deltaPos = delta;
}
public void setDensity(float value) {
this.density = value;
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/gameobjects/sph/Particle.java<|end_filename|>
package com.fluidsimulator.gameobjects.sph;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Pool.Poolable;
public class Particle implements Poolable {
public float density;
public float nearDensity;
public float pressure;
public float nearPressure;
public float mass = 1;
public Vector2 prevPos = new Vector2(0,0);
public Vector2 pos = new Vector2(0,0);
public Vector2 velocity = new Vector2(0,0);
public int type = 1;
public long spawnTime;
public int rGrad = 255;
public int gGrad = 255;
public int bGrad = 255;
public Particle() {
this(0,0);
}
public Particle(float posX, float posY) {
this.pos.set(posX, posY);
this.spawnTime = System.currentTimeMillis();
}
public Particle setPos(float x, float y) {
this.pos.set(x, y);
this.spawnTime = System.currentTimeMillis();
return this;
}
public Particle setPos(Vector2 vec) {
this.pos.set(vec.x, vec.y);
this.spawnTime = System.currentTimeMillis();
return this;
}
public Particle(Vector2 newPos) {
this.pos.set(newPos);
}
public void setRGrad(int value) {
if (value < 0)
value = 0;
this.rGrad = value;
}
public void setGGrad(int value) {
if (value < 0)
value = 0;
this.gGrad = value;
}
public void setBGrad(int value) {
if (value < 0)
value = 0;
this.bGrad = value;
}
@Override
public void reset() {
this.pos.set(0, 0);
this.prevPos.set(0, 0);
this.velocity.set(0, 0);
this.spawnTime = System.currentTimeMillis();
this.density = 0;
this.nearDensity = 0;
this.pressure = 0;
this.nearPressure = 0;
this.mass = 1;
this.rGrad = 255;
this.gGrad = 255;
this.bGrad = 255;
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/MPMSolver.java<|end_filename|>
package com.fluidsimulator;
import java.util.ArrayList;
public class MPMSolver {
public static final int numMaterials = 2;
public Particle[] particleArray = new Particle[10000];
public ArrayList<Particle> particles = new ArrayList<Particle>();
public Node[] grid;
public ArrayList<Node> active = new ArrayList<Node>();
public boolean pressed = false;
public boolean pressedprev = false;
public int mx = 0;
public int my = 0;
public int mxprev = 0;
public int myprev = 0;
public int gSizeX, gSizeY, gSizeY_3;
public int i, j, k, n, l, len;
public Particle p;
public ArrayList<Material> materials = new ArrayList<Material>(numMaterials);
public MPMSolver(int sizeX, int sizeY, int particlesX, int particlesY) {
this.gSizeX = sizeX;
this.gSizeY = sizeY;
this.gSizeY_3 = sizeY - 3;
// Water
materials.add(new Material());
materials.get(0).materialIndex = 0;
materials.get(0).smoothing = 1;
materials.get(0).restDensity = 0.5f;
// Oil
materials.add(new Material());
materials.get(1).materialIndex = 1;
materials.get(1).mass = 0.9f;
// grid = new ArrayList<Node>(gSizeX*gSizeY);
//
// for (i = 0; i < gSizeX*gSizeY; i++) {
// grid.add(new Node());
// }
grid = new Node[gSizeX * gSizeY];
for (i = 0; i < gSizeX*gSizeY; i++) {
grid[i]= new Node();
}
for (i = 0; i < particlesX; i++) {
for (j = 0; j < particlesY; j++) {
Particle p = new Particle(materials.get(0), i, j);
p.initializeWeights(gSizeY);
particles.add(p);
}
}
particleArray = particles.toArray(particleArray);
}
public void addParticle(int x, int y, int materialId) {
Particle p = new Particle(materials.get(materialId), x, y);
p.initializeWeights(gSizeY);
particles.add(p);
}
public void simulate() {
boolean drag = false;
float mdx = 0, mdy = 0, weight = 0;
if (pressed && pressedprev) {
drag = true;
mdx = (mx - mxprev);
mdy = (my - myprev);
}
pressedprev = pressed;
mxprev = mx;
myprev = my;
for (Particle p : particles) {
Material mat = p.mat;
float gu = 0, gv = 0, dudx = 0, dudy = 0, dvdx = 0, dvdy = 0;
float[] ppx = p.px;
float[] ppy = p.py;
float[] pgx = p.gx;
float[] pgy = p.gy;
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = ppx[i];
float gxi = pgx[i];
for (j = 0; j < 3; j++, k++) {
Node n = grid[p.gi + k];
float pyj = ppy[j];
float gyj = pgy[j];
float phi = pxi * pyj;
gu += phi * n.u2;
gv += phi * n.v2;
float gx = gxi * pyj;
float gy = pxi * gyj;
// Velocity gradient
dudx += n.u2 * gx;
dudy += n.u2 * gy;
dvdx += n.v2 * gx;
dvdy += n.v2 * gy;
}
}
// Update stress tensor
float w1 = dudy - dvdx;
float wT0 = .5f * w1 * (p.T01 + p.T01);
float wT1 = .5f * w1 * (p.T00 - p.T11);
float D00 = dudx;
float D01 = .5f * (dudy + dvdx);
float D11 = dvdy;
float trace = .5f * (D00 + D11);
p.T00 += .5f * (-wT0 + (D00 - trace) - mat.meltRate * p.T00);
p.T01 += .5f * (wT1 + D01 - mat.meltRate * p.T01);
p.T11 += .5f * (wT0 + (D11 - trace) - mat.meltRate * p.T11);
float norm = p.T00 * p.T00 + 2 * p.T01 * p.T01 + p.T11 * p.T11;
if (norm > mat.maxDeformation)
{
p.T00 = p.T01 = p.T11 = 0;
}
p.x += gu;
p.y += gv;
p.gu = gu;
p.gv = gv;
p.u += mat.smoothing*(gu-p.u);
p.v += mat.smoothing*(gv-p.v);
// Hard boundary correction (Random numbers keep it from clustering)
if (p.x < 1) {
p.x = 1 + .01f * (float)Math.random();
} else if (p.x > gSizeX - 2) {
p.x = gSizeX - 2 - .01f * (float)Math.random();
}
if (p.y < 1) {
p.y = 1 + .01f * (float)Math.random();
} else if (p.y > gSizeY - 2) {
p.y = gSizeY - 2 - .01f * (float)Math.random();
}
// Update grid cell index and kernel weights
int cx = p.cx = (int)(p.x - .5f);
int cy = p.cy = (int)(p.y - .5f);
p.gi = cx * gSizeY + cy;
float x = cx - p.x;
float y = cy - p.y;
// Quadratic interpolation kernel weights - Not meant to be changed
ppx[0] = .5f * x * x + 1.5f * x + 1.125f;
pgx[0] = x + 1.5f;
x++;
ppx[1] = -x * x + .75f;
pgx[1] = -2 * x;
x++;
ppx[2] = .5f * x * x - 1.5f * x + 1.125f;
pgx[2] = x - 1.5f;
ppy[0] = .5f * y * y + 1.5f * y + 1.125f;
pgy[0] = y + 1.5f;
y++;
ppy[1] = -y * y + .75f;
pgy[1] = -2 * y;
y++;
ppy[2] = .5f * y * y - 1.5f * y + 1.125f;
pgy[2] = y - 1.5f;
float m = p.mat.mass;
float mu = m * p.u;
float mv = m * p.v;
int mi = p.mat.materialIndex;
float[] px = p.px;
float[] gx = p.gx;
float[] py = p.py;
float[] gy = p.gy;
// n = grid[p.gi);
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = px[i];
float gxi = gx[i];
for (j = 0; j < 3; j++, k++) {
Node n = grid[p.gi + k];
float pyj = py[j];
float gyj = gy[j];
float phi = pxi * pyj;
// Add particle mass, velocity and density gradient to grid
n.mass += phi * m;
n.particleDensity += phi;
n.u += phi * mu;
n.v += phi * mv;
n.cgx[mi] += gxi * pyj;
n.cgy[mi] += pxi * gyj;
n.active = true;
}
}
}
// Add active nodes to list
active.clear();
int gSizeXY = gSizeX * gSizeY;
for (i = 0; i < gSizeXY; i++) {
Node n = grid[i];
if (n.active && n.mass > 0) {
active.add(n);
n.active = false;
n.ax = n.ay = 0;
n.gx = 0;
n.gy = 0;
n.u /= n.mass;
n.v /= n.mass;
for (j = 0; j < numMaterials; j++) {
n.gx += n.cgx[j];
n.gy += n.cgy[j];
}
for (j = 0; j < numMaterials; j++) {
n.cgx[j] -= n.gx - n.cgx[j];
n.cgy[j] -= n.gy - n.cgy[j];
}
}
}
int nActive = active.size();
// Calculate pressure and add forces to grid
for (Particle p : particles) {
Material mat = p.mat;
float fx = 0, fy = 0, dudx = 0, dudy = 0, dvdx = 0, dvdy = 0, sx = 0, sy = 0;
Node n = grid[p.gi];
float[] ppx = p.px;
float[] pgx = p.gx;
float[] ppy = p.py;
float[] pgy = p.gy;
int materialId = mat.materialIndex;
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = ppx[i];
float gxi = pgx[i];
for (j = 0; j < 3; j++, k++) {
n = grid[p.gi + k];
float pyj = ppy[j];
float gyj = pgy[j];
float phi = pxi * pyj;
float gx = gxi * pyj;
float gy = pxi * gyj;
// Velocity gradient
dudx += n.u * gx;
dudy += n.u * gy;
dvdx += n.v * gx;
dvdy += n.v * gy;
// Surface tension
sx += phi * n.cgx[materialId];
sy += phi * n.cgy[materialId];
}
}
int cx = (int)p.x;
int cy = (int)p.y;
int gi = cx * gSizeY + cy;
Node n1 = grid[gi];
Node n2 = grid[gi+1];
Node n3 = grid[gi+gSizeY];
Node n4 = grid[gi+gSizeY+1];
float density = uscip(n1.particleDensity, n1.gx, n1.gy, n2.particleDensity, n2.gx, n2.gy, n3.particleDensity,
n3.gx, n3.gy, n4.particleDensity, n4.gx, n4.gy, p.x - cx, p.y - cy);
float pressure = mat.stiffness / mat.restDensity * (density - mat.restDensity);
if (pressure > 2) {
pressure = 2;
}
// Update stress tensor
float w1 = dudy - dvdx;
float wT0 = .5f * w1 * (p.T01 + p.T01);
float wT1 = .5f * w1 * (p.T00 - p.T11);
float D00 = dudx;
float D01 = .5f * (dudy + dvdx);
float D11 = dvdy;
float trace = .5f * (D00 + D11);
D00 -= trace;
D11 -= trace;
p.T00 += .5f * (-wT0 + D00 - mat.meltRate * p.T00);
p.T01 += .5f * (wT1 + D01 - mat.meltRate * p.T01);
p.T11 += .5f * (wT0 + D11 - mat.meltRate * p.T11);
// Stress tensor fracture
float norm = p.T00 * p.T00 + 2 * p.T01 * p.T01 + p.T11 * p.T11;
if (norm > mat.maxDeformation)
{
p.T00 = p.T01 = p.T11 = 0;
}
float T00 = mat.mass * (mat.kElastic * p.T00 + mat.viscosity * D00 + pressure + trace * mat.bulkViscosity);
float T01 = mat.mass * (mat.kElastic * p.T01 + mat.viscosity * D01);
float T11 = mat.mass * (mat.kElastic * p.T11 + mat.viscosity * D11 + pressure + trace * mat.bulkViscosity);
// Surface tension
float lenSq = sx * sx + sy * sy;
if (lenSq > 0)
{
float len = (float)Math.sqrt(lenSq);
float a = mat.mass * mat.surfaceTension / len;
T00 -= a * (.5f * lenSq - sx * sx);
T01 -= a * (-sx * sy);
T11 -= a * (.5f * lenSq - sy * sy);
}
// Wall force
if (p.x < 4) {
fx += (4 - p.x);
} else if (p.x > gSizeX - 5) {
fx += (gSizeX - 5 - p.x);
}
if (p.y < 4) {
fy += (4 - p.y);
} else if (p.y > gSizeY - 5) {
fy += (gSizeY - 5 - p.y);
}
// Mouse Drag
if (drag) {
float vx = Math.abs(p.x - mx);
float vy = Math.abs(p.y - my);
if ((vx < 10.0f) && (vy < 10.0f)) {
weight = p.mat.mass * (1.0f - vx * 0.10f) * (1.0f - vy * 0.10f);
fx += weight * (mdx - p.u);
fy += weight * (mdy - p.v);
}
}
// Add forces to grid
n = grid[p.gi];
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = ppx[i];
float gxi = pgx[i];
for (j = 0; j < 3; j++, k++) {
n = grid[p.gi + k];
float pyj = ppy[j];
float gyj = pgy[j];
float phi = pxi * pyj;
float gx = gxi * pyj;
float gy = pxi * gyj;
n.ax += -(gx * T00 + gy * T01) + fx * phi;
n.ay += -(gx * T01 + gy * T11) + fy * phi;
}
}
}
// Update acceleration of nodes
for (i = 0; i < nActive; i++) {
Node n = active.get(i);
n.u2 = 0;
n.v2 = 0;
n.ax /= n.mass;
n.ay /= n.mass;
}
for (Particle p : particles) {
Material mat = p.mat;
Node n = grid[p.gi];
// Update particle velocities
float[] px = p.px;
float[] py = p.py;
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = px[i];
for (j = 0; j < 3; j++, k++) {
n = grid[p.gi + k];
float pyj = py[j];
float phi = pxi * pyj;
p.u += phi * n.ax;
p.v += phi * n.ay;
}
}
p.v += mat.gravity;
p.u *= 1-mat.damping;
p.v *= 1-mat.damping;
float m = p.mat.mass;
float mu = m * p.u;
float mv = m * p.v;
// Add particle velocities back to the grid
n = grid[p.gi];
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = px[i];
for (j = 0; j < 3; j++, k++) {
n = grid[p.gi + k];
float pyj = py[j];
float phi = pxi * pyj;
n.u2 += phi * mu;
n.v2 += phi * mv;
}
}
}
// Update node velocities
for (i = 0; i < nActive; i++) {
Node n = active.get(i);
n.u2 /= n.mass;
n.v2 /= n.mass;
n.mass = 0;
n.particleDensity = 0;
n.u = 0;
n.v = 0;
// n.cgx = new float[numMaterials];
// n.cgy = new float[numMaterials];
for (j=0; j<numMaterials; j++) {
n.cgx[j] = 0;
n.cgy[j] = 0;
}
}
}
public void simulateSimple() {
boolean drag = false;
float mdx = 0, mdy = 0, weight = 0;
if (pressed && pressedprev) {
drag = true;
mdx = (mx - mxprev);
mdy = (my - myprev);
}
pressedprev = pressed;
mxprev = mx;
myprev = my;
// Reset grid nodes
int nActive = active.size();
for (int i = 0; i < nActive; i++) {
active.get(i).active = false;
}
active.clear();
// Add particle mass, velocity and density gradient to grid
// for (Particle p : particles) {
len = particles.size();
for (l=0; l<len; l++) {
p = particleArray[l];
float[] px = p.px;
float[] gx = p.gx;
float[] py = p.py;
float[] gy = p.gy;
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = px[i];
float gxi = gx[i];
for (j = 0; j < 3; j++, k++) {
Node n = grid[p.gi + k];
float pyj = py[j];
float gyj = gy[j];
float phi = pxi * pyj;
if (n.active) {
n.mass += phi;
n.gx += gxi * pyj;
n.gy += pxi * gyj;
} else {
n.active = true;
n.mass = phi;
n.gx = gxi * pyj;
n.gy = pxi * gyj;
n.ax = 0;
n.ay = 0;
active.add(n);
}
}
}
}
nActive = active.size();
// Calculate pressure and add forces to grid
// for (Particle p : particles) {
for (l=0; l<len; l++) {
p = particleArray[l];
Material mat = p.mat;
float fx = 0, fy = 0;
Node n = grid[p.gi];
float[] ppx = p.px;
float[] pgx = p.gx;
float[] ppy = p.py;
float[] pgy = p.gy;
int cx = (int)p.x;
int cy = (int)p.y;
int gi = cx * gSizeY + cy;
Node n1 = grid[gi];
Node n2 = grid[gi+1];
Node n3 = grid[gi+gSizeY];
Node n4 = grid[gi+gSizeY+1];
float density = uscip(n1.mass, n1.gx, n1.gy, n2.mass, n2.gx, n2.gy, n3.mass, n3.gx, n3.gy, n4.mass, n4.gx, n4.gy, p.x - cx, p.y - cy);
float pressure = mat.stiffness / mat.restDensity * (density - mat.restDensity);
if (pressure > 2) {
pressure = 2;
}
// Wall force
if (p.x < 4) {
fx += (4 - p.x);
} else if (p.x > gSizeX - 5) {
fx += (gSizeX - 5 - p.x);
}
if (p.y < 4) {
fy += (4 - p.y);
} else if (p.y > gSizeY - 5) {
fy += (gSizeY - 5 - p.y);
}
// Mouse Drag
if (drag) {
float vx = Math.abs(p.x - mx);
float vy = Math.abs(p.y - my);
if ((vx < 10.0f) && (vy < 10.0f)) {
weight = p.mat.mass * (1.0f - vx * 0.10f) * (1.0f - vy * 0.10f);
fx += weight * (mdx - p.u);
fy += weight * (mdy - p.v);
}
}
// Add forces to grid
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = ppx[i];
float gxi = pgx[i];
for (j = 0; j < 3; j++, k++) {
n = grid[p.gi + k];
float pyj = ppy[j];
float gyj = pgy[j];
float phi = pxi * pyj;
float gx = gxi * pyj;
float gy = pxi * gyj;
n.ax += -(gx * pressure) + fx * phi;
n.ay += -(gy * pressure) + fy * phi;
}
}
}
// Update acceleration of nodes
for (int i = 0; i < nActive; i++) {
Node n = active.get(i);
n.u = 0;
n.v = 0;
if (n.mass > 0) {
n.ax /= n.mass;
n.ay /= n.mass;
}
}
// for (Particle p : particles) {
for (l=0; l<len; l++) {
p = particleArray[l];
Material mat = p.mat;
// Update particle velocities
float[] px = p.px;
float[] py = p.py;
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = px[i];
for (j = 0; j < 3; j++, k++) {
Node n = grid[p.gi + k];
float pyj = py[j];
float phi = pxi * pyj;
p.u += phi * n.ax;
p.v += phi * n.ay;
}
}
p.v += mat.gravity;
// Add particle velocities back to the grid
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = px[i];
for (j = 0; j < 3; j++, k++) {
Node n = grid[p.gi + k];
float pyj = py[j];
float phi = pxi * pyj;
n.u += phi * p.u;
n.v += phi * p.v;
}
}
}
// Update node velocities
for (int i = 0; i < nActive; i++) {
Node n = active.get(i);
if (n.mass > 0) {
n.u /= n.mass;
n.v /= n.mass;
}
}
// Advect particles
// for (Particle p : particles) {
for (l=0; l<len; l++) {
p = particleArray[l];
Material mat = p.mat;
float gu = 0, gv = 0;
float[] ppx = p.px;
float[] ppy = p.py;
float[] pgx = p.gx;
float[] pgy = p.gy;
for (i = 0, k = 0; i < 3; i++, k += gSizeY_3) {
float pxi = ppx[i];
for (j = 0; j < 3; j++, k++) {
Node n = grid[p.gi + k];
float pyj = ppy[j];
float phi = pxi * pyj;
gu += phi * n.u;
gv += phi * n.v;
}
}
p.x += gu;
p.y += gv;
p.u += mat.smoothing*(gu-p.u);
p.v += mat.smoothing*(gv-p.v);
// Hard boundary correction (Random numbers keep it from clustering)
if (p.x < 1) {
p.x = 1 + .01f*(float)Math.random();
} else if (p.x > gSizeX - 2) {
p.x = gSizeX - 2 - .01f*(float)Math.random();
}
if (p.y < 1) {
p.y = 1 + .01f*(float)Math.random();
} else if (p.y > gSizeY - 2) {
p.y = gSizeY - 2 - .01f*(float)Math.random();
}
// Update grid cell index and kernel weights
int cx = p.cx = (int)(p.x - .5f);
int cy = p.cy = (int)(p.y - .5f);
p.gi = cx * gSizeY + cy;
float x = cx - p.x;
float y = cy - p.y;
// Quadratic interpolation kernel weights - Not meant to be changed
ppx[0] = .5f * x * x + 1.5f * x + 1.125f;
pgx[0] = x + 1.5f;
x++;
ppx[1] = -x * x + .75f;
pgx[1] = -2 * x;
x++;
ppx[2] = .5f * x * x - 1.5f * x + 1.125f;
pgx[2] = x - 1.5f;
ppy[0] = .5f * y * y + 1.5f * y + 1.125f;
pgy[0] = y + 1.5f;
y++;
ppy[1] = -y * y + .75f;
pgy[1] = -2 * y;
y++;
ppy[2] = .5f * y * y - 1.5f * y + 1.125f;
pgy[2] = y - 1.5f;
}
}
public float uscip(float p00, float x00, float y00, float p01, float x01, float y01, float p10, float x10,
float y10, float p11, float x11, float y11, float u, float v)
{
float dx = x00 - x01;
float dy = y00 - y10;
float a = p01 - p00;
float b = p11 - p10 - a;
float c = p10 - p00;
float d = y11 - y01;
return ((((d - 2 * b - dy) * u - 2 * a + y00 + y01) * v +
((3 * b + 2 * dy - d) * u + 3 * a - 2 * y00 - y01)) * v +
((((2 * c - x00 - x10) * u + (3 * b + 2 * dx + x10 - x11)) * u - b - dy - dx) * u + y00)) * v +
(((x11 - 2 * (p11 - p01 + c) + x10 + x00 + x01) * u +
(3 * c - 2 * x00 - x10)) * u +
x00) * u + p00;
}
public class Particle {
public Material mat;
public float x, y, u, v, gu, gv, T00, T01, T11;
public int cx, cy, gi;
public float[] px;
public float[] py;
public float[] gx;
public float[] gy;
public Particle(Material mat) {
this.mat = mat;
this.x = 0;
this.y = 0;
this.u = 0;
this.v = 0;
this.gu = 0;
this.gv = 0;
this.T00 = 0;
this.T01 = 0;
this.T11 = 0;
this.cx = 0;
this.cy = 0;
this.gi = 0;
this.px = new float[] { 0, 0, 0 };
this.py = new float[] { 0, 0, 0 };
this.gx = new float[] { 0, 0, 0 };
this.gy = new float[] { 0, 0, 0 };
}
public Particle(Material mat, int x, int y) {
this.mat = mat;
this.x = x;
this.y = y;
this.u = 0;
this.v = 0;
this.gu = 0;
this.gv = 0;
this.T00 = 0;
this.T01 = 0;
this.T11 = 0;
this.cx = 0;
this.cy = 0;
this.gi = 0;
this.px = new float[] { 0, 0, 0 };
this.py = new float[] { 0, 0, 0 };
this.gx = new float[] { 0, 0, 0 };
this.gy = new float[] { 0, 0, 0 };
}
public Particle(Material mat, int x, int y, float u, float v) {
this.mat = mat;
this.x = x;
this.y = y;
this.u = u;
this.v = v;
this.gu = 0;
this.gv = 0;
this.T00 = 0;
this.T01 = 0;
this.T11 = 0;
this.cx = 0;
this.cy = 0;
this.gi = 0;
this.px = new float[] { 0, 0, 0 };
this.py = new float[] { 0, 0, 0 };
this.gx = new float[] { 0, 0, 0 };
this.gy = new float[] { 0, 0, 0 };
}
public void initializeWeights(int gSizeY) {
cx = (int)(x - .5f);
cy = (int)(y - .5f);
gi = cx * gSizeY + cy;
float cx_x = cx - x;
float cy_y = cy - y;
// Quadratic interpolation kernel weights - Not meant to be changed
px[0] = .5f * cx_x * cx_x + 1.5f * cx_x + 1.125f;
gx[0] = cx_x + 1.5f;
cx_x++;
px[1] = -cx_x * cx_x + .75f;
gx[1] = -2 * cx_x;
cx_x++;
px[2] = .5f * cx_x * cx_x - 1.5f * cx_x + 1.125f;
gx[2] = cx_x - 1.5f;
py[0] = .5f * cy_y * cy_y + 1.5f * cy_y + 1.125f;
gy[0] = cy_y + 1.5f;
cy_y++;
py[1] = -cy_y * cy_y + .75f;
gy[1] = -2 * cy_y;
cy_y++;
py[2] = .5f * cy_y * cy_y - 1.5f * cy_y + 1.125f;
gy[2] = cy_y - 1.5f;
}
}
public class Material {
public float mass;
public float restDensity;
public float stiffness;
public float bulkViscosity;
public float surfaceTension;
public float kElastic;
public float maxDeformation;
public float meltRate;
public float viscosity;
public float damping;
public float friction;
public float stickiness;
public float smoothing;
public float gravity;
public int materialIndex;
public Material() {
this.mass = 1;
this.restDensity = 2;
this.stiffness = 1;
this.bulkViscosity = 1;
this.surfaceTension = 0;
this.kElastic = 0;
this.maxDeformation = 0;
this.meltRate = 0;
this.viscosity = 0.02f;
this.damping = 0.001f;
this.friction = 0;
this.stickiness = 0;
this.smoothing = 0.02f;
this.gravity = 0.09f;
}
public Material(float mass, float restDensity, float stiffness, float bulkViscosity, float surfaceTension,
float kElastic, float maxDeformation, float meltRate, float viscosity, float damping, float friction,
float stickiness, float smoothing, float gravity) {
this.mass = mass;
this.restDensity = restDensity;
this.stiffness = stiffness;
this.bulkViscosity = bulkViscosity;
this.surfaceTension = surfaceTension;
this.kElastic = kElastic;
this.maxDeformation = maxDeformation;
this.meltRate = meltRate;
this.viscosity = viscosity;
this.damping = damping;
this.friction = friction;
this.stickiness = stickiness;
this.smoothing = smoothing;
this.gravity = gravity;
}
}
public class Node {
public float mass, particleDensity, gx, gy, u, v, u2, v2, ax, ay;
public float[] cgx;
public float[] cgy;
public boolean active;
public Node() {
mass = 0;
particleDensity = 0;
gx = 0;
gy = 0;
u = 0;
v = 0;
u2 = 0;
v2 = 0;
ax = 0;
ay = 0;
active = false;
cgx = new float[numMaterials];
cgy = new float[numMaterials];
}
public void clear() {
mass = 0;
particleDensity = 0;
gx = 0;
gy = 0;
u = 0;
v = 0;
u2 = 0;
v2 = 0;
ax = 0;
ay = 0;
active = false;
for (i=0; i<numMaterials; i++) {
cgx[i] = 0;
cgy[i] = 0;
}
}
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/DesktopStarter.java<|end_filename|>
package com.fluidsimulator;
import java.awt.Toolkit;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
public class DesktopStarter {
public static void main(String[] args) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.fullscreen = true;
config.resizable = false;
config.title = "Fluid Simulator v2.1";
config.vSyncEnabled = true;
config.width = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
config.height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
// config.width = 800;
// config.height = 480;
config.useGL20 = true;
new LwjglApplication(new FluidSimulatorStarter(), config);
}
}
<|start_filename|>fluid-simulator/src/com/fluidsimulator/gameobjects/Piece.java<|end_filename|>
package com.fluidsimulator.gameobjects;
import java.util.ArrayList;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.Shape;
import com.badlogic.gdx.utils.ArrayMap;
public class Piece {
public int hash;
public Shape shape;
public ArrayList<Shape> shapes;
public Vector2 pos;
public BodyType type;
public Body body;
public float angle = 0;
public float friction = 0.5f;
public float restitution = 0.5f;
public float gravityScale = 1.0f;
public float density = 5.0f;
public float radius;
public int index;
public boolean isBullet = false;
public boolean isPortalAllowed = false;
public boolean isSensor = false;
public boolean isPortalIn = false;
public boolean isPortalOut = false;
public boolean isCreated = false;
public boolean isEnemy = false;
public boolean isSticky = false;
public static final Vector2 ZERO_VEC = new Vector2();
public ArrayMap<Integer, Particle> rayCastArray = new ArrayMap<Integer, Particle>();
public Vector2 collisionImpulse = new Vector2();
public Vector2 contactPoint = new Vector2();
public Piece(Piece anotherPiece) {
this.shape = anotherPiece.shape;
if (anotherPiece.pos != null)
this.pos = new Vector2(anotherPiece.pos);
this.type = anotherPiece.type;
this.body = anotherPiece.body;
this.angle = anotherPiece.angle;
this.friction = anotherPiece.friction;
this.restitution = anotherPiece.restitution;
this.gravityScale = anotherPiece.gravityScale;
this.isPortalAllowed = anotherPiece.isPortalAllowed;
this.isSensor = anotherPiece.isSensor;
this.isPortalIn = anotherPiece.isPortalIn;
this.isPortalOut = anotherPiece.isPortalOut;
this.isCreated = anotherPiece.isCreated;
this.isEnemy = anotherPiece.isEnemy;
this.radius = anotherPiece.radius;
}
/** Void Shape */
public Piece (BodyType type) {
this.shape = null;
this.pos = new Vector2();
this.type = type;
}
public Piece (float radius, BodyType type, boolean isComposite) {
ChainShape shape = new ChainShape();
// ArrayList<Vector2> vectors = createArc(0, 0, radius, 180, 360, 0.07f, false);
// vectors.add(new Vector2(vectors.get(vectors.size() - 1).x - 1, vectors.get(vectors.size() - 1).y));
// vectors.add(0, new Vector2(vectors.get(0).x+1, vectors.get(0).y));
// vectors.addAll(createArc(0, 0, radius-1, 0, -180, 0.07f, true));
// Vector2[] finalVectors = new Vector2[vectors.size()];
// ((ChainShape)shape).createLoop(vectors.toArray(finalVectors));
// vectors.clear();
// finalVectors = null;
this.shape = shape;
this.pos = new Vector2();
this.type = type;
}
/** Circle Shape */
public Piece (float radius, BodyType type) {
this.shape = new CircleShape();
((CircleShape)this.shape).setRadius(radius);
this.pos = new Vector2();
this.type = type;
this.radius = radius;
}
/** Box Shape */
public Piece (float halfWidth, float halfHeight, float angle, BodyType type) {
this.shape = new PolygonShape();
((PolygonShape)this.shape).setAsBox(halfWidth, halfHeight, ZERO_VEC, 0);
this.pos = new Vector2();
this.type = type;
this.angle = (float)Math.toRadians(angle);
}
/** Polygon Shape **/
public Piece (BodyType type, boolean flag, Vector2... pos) {
this.shape = new PolygonShape();
((PolygonShape)this.shape).set(pos);
this.pos = new Vector2();
this.type = type;
}
/** Chain Shape */
public Piece (BodyType type, Vector2... pos) {
this.shape = new ChainShape();
((ChainShape)this.shape).createLoop(pos);
this.pos = null;
this.type = type;
}
public ArrayList<Vector2> createArc(float centerX, float centerY, float radius, float angleFrom, float angleTo, float precision, boolean revert) {
ArrayList<Vector2> vectors = new ArrayList<Vector2>();
float angleDiff = Math.abs(angleTo - angleFrom);
int steps = Math.round(angleDiff * precision);
float angle = angleFrom;
float px = (float) (centerX + radius * Math.cos(Math.toRadians(angle)));
float py = (float) (centerY + radius * Math.sin(Math.toRadians(angle)));
vectors.add(new Vector2(px, py));
for (int i=1; i<=steps; i++) {
if (revert)
angle = angleFrom - angleDiff / steps * i;
else
angle = angleFrom + angleDiff / steps * i;
vectors.add(new Vector2(centerX + radius * (float)Math.cos(Math.toRadians(angle)), centerY + radius * (float)Math.sin(Math.toRadians(angle))));
}
return vectors;
}
public Piece setPhysics(float friction, float restitution, float gravityScale, boolean isSensor) {
this.friction = friction;
this.restitution = restitution;
this.gravityScale = gravityScale;
this.isSensor = isSensor;
return this;
}
public Piece setSensor(boolean value) {
this.isSensor = value;
return this;
}
public Piece setBody(Body body) {
this.body = body;
isCreated = true;
return this;
}
public Piece setPortalIn(boolean value) {
this.isPortalIn = value;
return this;
}
public Piece setPortalOut(boolean value) {
this.isPortalOut = value;
return this;
}
public Piece setPortalAllowed(boolean value) {
this.isPortalAllowed = value;
return this;
}
public Piece setEnemy(boolean value) {
this.isEnemy = value;
return this;
}
public Piece setAngle(float angle) {
this.angle = (float)Math.toRadians(angle);
return this;
}
public void addShape(Shape newShape) {
if (shapes == null)
shapes = new ArrayList<Shape>();
shapes.add(newShape);
}
public Piece setIndex(int value) {
this.index = value;
return this;
}
public Piece setHash(int value) {
this.hash = value;
return this;
}
public Piece setSticky(boolean value) {
this.isSticky = value;
return this;
}
} | omgware/fluid-simulator-v2 |
<|start_filename|>ui/src/service/bookService.js<|end_filename|>
import axios from "axios";
let baseUrl = "http://localhost:5000/api";
if (process.env.REACT_APP_USING_DOCKER === '1') {
/*
When running inside docker the API is requested as a local web path.
NGINX will then proxy the request to the right docker container service url.
*/
baseUrl = "/api";
}
export const SearchBooks = async(query, page, perPage, newEndpoint) => {
if (newEndpoint) {
const response = await axios.get(baseUrl + newEndpoint);
return response.data;
}
const response = await axios.get(
`${baseUrl}/books/search`, {params: {q: query, page, per_page: perPage}});
return response.data;
};
export const SearchBookParagraphs =
async(bookTitle, start, offset, newEndpoint) => {
if (newEndpoint) {
const response = await axios.get(baseUrl + newEndpoint);
return response.data;
}
const response =
await axios.get(`${baseUrl}/books/paragraphs`,
{params: {book_title: bookTitle, start, offset}});
return response.data;
};
<|start_filename|>ui/src/store/index.js<|end_filename|>
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import { createLogger } from "redux-logger";
import rootReducer from "./ducks";
import * as bookService from "../service/bookService";
// redux-logger constantly logs the state and actions changes.
// so its much easier to follow what's happening.
const loggerMiddleware = createLogger();
const middleware = [thunk.withExtraArgument(bookService)];
const enhancers = [];
if (process.env.NODE_ENV === "development") {
const { devToolsExtension } = window;
if (typeof devToolsExtension === "function") {
enhancers.push(devToolsExtension());
}
middleware.push(loggerMiddleware);
}
const composedEnhancers = compose(
applyMiddleware(...middleware),
...enhancers
);
const store = createStore(rootReducer, composedEnhancers);
export default store;
<|start_filename|>ui/src/store/ducks/bookParagraphs.js<|end_filename|>
export const Types = {
FETCH_BOOK_PARAGRAPHS_START: "books/FETCH_BOOK_PARAGRAPHS_START",
FETCH_BOOK_PARAGRAPHS_END: "books/FETCH_BOOK_PARAGRAPHS_END",
FETCH_BOOK_PARAGRAPHS_ERROR: "books/FETCH_BOOK_PARAGRAPHS_ERROR"
};
const INITIAL_STATE = {
fetching: false,
fetched: false,
paragraphs: null,
error: null
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case Types.FETCH_BOOK_PARAGRAPHS_START:
return { ...state, fetching: true };
case Types.FETCH_BOOK_PARAGRAPHS_END:
return {
...state,
fetching: false,
fetched: true,
paragraphs: action.payload,
error: null
};
case Types.FETCH_BOOK_PARAGRAPHS_ERROR:
return {
...state,
fetching: false,
fetched: true,
paragraphs: null,
error: action.payload
};
default:
return {
...state,
fetching: false,
paragraphs: null
};
}
};
export const Creators = {
fetchBookParagraphsStart: () => ({
type: Types.FETCH_BOOK_PARAGRAPHS_START
}),
fetchBookParagraphsEnd: paragraphs => ({
type: Types.FETCH_BOOK_PARAGRAPHS_END,
payload: paragraphs
}),
fetchBookParagraphsError: error => ({
type: Types.FETCH_BOOK_PARAGRAPHS_ERROR,
payload: error
}),
SearchBookParagraphs: (bookTitle, start, offset, newEndpoint) => async (
dispatch,
getState,
bookService
) => {
dispatch(Creators.fetchBookParagraphsStart());
const { SearchBookParagraphs } = bookService;
const bookParagraphs = await SearchBookParagraphs(
bookTitle,
start,
offset,
newEndpoint
);
return bookParagraphs;
}
};
<|start_filename|>ui/Dockerfile<|end_filename|>
FROM node:12.2.0-alpine as build
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
ENV REACT_APP_USING_DOCKER=1
COPY package.json /app/package.json
RUN npm install --silent
RUN npm install react-scripts@3.0.1 -g --silent
COPY . /app
RUN npm run build
# production environment
FROM nginx:1.16.0-alpine
RUN rm -v /etc/nginx/nginx.conf
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
<|start_filename|>ui/src/store/ducks/index.js<|end_filename|>
import { combineReducers } from "redux";
import books from "./books";
import bookParagraphs from "./bookParagraphs";
export default combineReducers({
books,
bookParagraphs
});
<|start_filename|>ui/src/BookParagraph.js<|end_filename|>
import PropTypes from "prop-types";
import React, { Component } from "react";
import { withStyles } from "@material-ui/core/styles";
import { Button, Divider, Typography } from "@material-ui/core";
import Icon from "@material-ui/core/Icon";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { Creators as BookParagraphActions } from "./store/ducks/bookParagraphs";
const styles = theme => ({
allCaps: {
textTransform: "uppercase"
},
bookModal: {
width: "100%",
height: "100%",
padding: "40px 10%",
margin: "0 auto",
backgroundColor: "white",
overflowY: "scroll",
position: "fixed",
top: 0,
left: 0
},
error: {
color: "#C0C0C0",
display: "flex",
flexDirection: "column",
alignItems: "center"
},
locationsLabel: {
textAlign: "center",
margin: theme.spacing()
},
modalFooter: {
position: "fixed",
bottom: 0,
left: 0,
width: "100%",
display: "flex",
justifyContent: "space-around",
background: "white"
},
paragraphsContainer: {
maxWidth: 800,
margin: "0 auto",
marginBottom: 48
},
titleRow: {
display: "flex",
justifyContent: "space-between",
alignItems: "flex-end"
}
});
class BookParagraph extends Component {
constructor(props) {
super(props);
this.start = 0;
this.offsetFromParagraph = 5;
this.offset = 10;
this.prevPageUrl = "";
this.nextPageUrl = "";
}
componentDidMount() {
const { selectedParagraph } = this.props;
this.start =
selectedParagraph._source.location - this.offsetFromParagraph >= 0
? selectedParagraph._source.location - this.offsetFromParagraph
: 0;
this.doSearch("");
}
doSearch = newEndpoint => {
(async () => {
const { SearchBookParagraphs, selectedParagraph } = this.props;
const { fetchBookParagraphsEnd, fetchBookParagraphsError } = this.props;
try {
const bookParagraphs = await SearchBookParagraphs(
selectedParagraph._source.title,
this.start,
this.offset,
newEndpoint
);
fetchBookParagraphsEnd(bookParagraphs);
} catch (e) {
if (e.response !== undefined) {
fetchBookParagraphsError(e.response.data);
} else {
fetchBookParagraphsError({
message: "Search service is unavailable. Please try again."
});
}
}
})();
};
closeBookParagraphModal = () => {
const { onCloseBookParagraphModal } = this.props;
onCloseBookParagraphModal();
};
prevResultsPage = () => {
this.doSearch(this.prevPageUrl);
this.start = parseInt(
this.prevPageUrl
.match(/start=.*&/)[0]
.split("=")[1]
.replace("&", "")
);
};
nextResultsPage = () => {
this.doSearch(this.nextPageUrl);
this.start = parseInt(
this.nextPageUrl
.match(/start=.*&/)[0]
.split("=")[1]
.replace("&", "")
);
};
render() {
const { classes, selectedParagraph } = this.props;
const { bookParagraphs } = this.props;
const { error } = bookParagraphs;
const paragraphs =
bookParagraphs.paragraphs === null ? [] : bookParagraphs.paragraphs.items;
const links =
bookParagraphs.paragraphs === null
? []
: bookParagraphs.paragraphs._links;
this.prevPageUrl = links.prev === null ? "" : links.prev;
this.nextPageUrl = links.next === null ? "" : links.next;
return (
<div className={classes.bookModal}>
<div className={classes.paragraphsContainer}>
<div className={classes.titleRow}>
<Typography variant="h4" className={classes.allCaps}>
{selectedParagraph._source.title}
</Typography>
<Typography variant="h5">
{selectedParagraph._source.author}
</Typography>
</div>
<br />
<Divider />
<Typography variant="subtitle1" className={classes.locationsLabel}>
Locations {this.start} - {this.start + this.offset}
</Typography>
<Divider />
<br />
{error !== null ? (
<div className={classes.error}>
<div>
<Icon>error_outline</Icon>
</div>
<div>
<Typography variant="subtitle1">{error.message}</Typography>
</div>
</div>
) : (
paragraphs.map(paragraph => (
<div>
{paragraph._source.location ===
selectedParagraph._source.location ? (
<Typography variant="body1">
<strong>{paragraph._source.text}</strong>
</Typography>
) : (
<Typography variant="body1">
{paragraph._source.text}
</Typography>
)}
<br />
</div>
))
)}
</div>
<div className={classes.modalFooter}>
{this.prevPageUrl ? (
<Button
className={classes.buttonDefault}
onClick={this.prevResultsPage}
>
Prev Page
</Button>
) : (
<Button
disabled
className={classes.buttonDefault}
onClick={this.prevResultsPage}
>
Prev Page
</Button>
)}
<Button
className={classes.buttonDefault}
onClick={this.closeBookParagraphModal}
>
Close
</Button>
{this.nextPageUrl ? (
<Button
className={classes.buttonDefault}
onClick={this.nextResultsPage}
>
Next Page
</Button>
) : (
<Button
disabled
className={classes.buttonDefault}
onClick={this.nextResultsPage}
>
Next Page
</Button>
)}
</div>
</div>
);
}
}
BookParagraph.propTypes = {
bookParagraphs: PropTypes.objectOf(PropTypes.any),
classes: PropTypes.objectOf(PropTypes.string),
selectedParagraph: PropTypes.objectOf(PropTypes.object),
SearchBookParagraphs: PropTypes.func,
fetchBookParagraphsEnd: PropTypes.func,
fetchBookParagraphsError: PropTypes.func,
onCloseBookParagraphModal: PropTypes.func
};
const mapStateToProps = ({ bookParagraphs }) => ({
bookParagraphs
});
const mapDispatchToProps = dispatch =>
bindActionCreators(BookParagraphActions, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(BookParagraph));
<|start_filename|>ui/src/Book.js<|end_filename|>
import PropTypes from "prop-types";
import React, { Component } from "react";
import ReactHtmlParser from "react-html-parser";
import { withStyles } from "@material-ui/core/styles";
import {
Button,
Card,
CardContent,
Divider,
Grid,
Paper,
TextField,
Typography
} from "@material-ui/core";
import Icon from "@material-ui/core/Icon";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { Creators as BookActions } from "./store/ducks/books";
import BookParagraph from "./BookParagraph";
const styles = theme => ({
buttonDefault: {
marginLeft: theme.spacing(5),
marginRight: theme.spacing(5)
},
gridCard: {
margin: theme.spacing(2),
cursor: "pointer"
},
paginationPanel: {
display: "flex",
justifyContent: "center"
},
paper: {
padding: theme.spacing(3),
margin: theme.spacing(2)
},
paperError: {
padding: theme.spacing(3),
margin: theme.spacing(2),
color: "#C0C0C0",
display: "flex",
flexDirection: "column",
alignItems: "center"
},
textField: {
marginTop: 0,
width: "100%"
},
textParagraph: {
marginBottom: theme.spacing(1),
fontWeight: "normal",
"& em": {
fontWeight: "bold"
}
},
textTitle: {
marginTop: theme.spacing(1)
}
});
class Book extends Component {
constructor(props) {
super(props);
this.searchDebounceTimeout = null;
this.page = 1;
this.perPage = 10;
this.prevPageUrl = "";
this.nextPageUrl = "";
}
doSearch = async (query, newEndpoint) => {
const { SearchBooks } = this.props;
const { fetchBooksEnd, fetchBooksError } = this.props;
try {
const books = await SearchBooks(
query,
this.page,
this.perPage,
newEndpoint
);
fetchBooksEnd(books);
} catch (e) {
if (e.response !== undefined) {
fetchBooksError(e.response.data);
} else {
fetchBooksError({
message: "Search service is unavailable. Please try again."
});
}
}
};
onSearchInputKeyUp = e => {
const iptValue = e.target.value;
clearTimeout(this.searchDebounceTimeout);
this.searchDebounceTimeout = setTimeout(async () => {
this.doSearch(iptValue, "");
}, 100);
};
prevResultsPage = () => {
this.doSearch("", this.prevPageUrl);
this.page = this.prevPageUrl
.match(/page=.*&/)[0]
.split("=")[1]
.replace("&", "");
document.documentElement.scrollTop = 0;
};
nextResultsPage = () => {
this.doSearch("", this.nextPageUrl);
this.page = this.nextPageUrl
.match(/page=.*&/)[0]
.split("=")[1]
.replace("&", "");
document.documentElement.scrollTop = 0;
};
showBookParagraphModal = bookParagraph => {
document.body.style.overflow = "hidden";
const { selectParagraph } = this.props;
selectParagraph(bookParagraph);
};
onCloseBookParagraphModal = () => {
document.body.style.overflow = "auto";
const { unselectParagraph } = this.props;
unselectParagraph();
};
render() {
const { classes } = this.props;
const { books } = this.props;
const items = books.books === null ? [] : books.books.items;
const { error } = books;
const numItems = books.books === null ? 0 : books.books._meta.total_items;
const links = books.books === null ? [] : books.books._links;
this.prevPageUrl = links.prev === null ? "" : links.prev;
this.nextPageUrl = links.next === null ? "" : links.next;
const { selectedParagraph } = books;
return (
<div>
<Grid container>
<Grid item xs={12}>
<Paper className={classes.paper}>
<div>
<TextField
id="iptSearch"
label="Search"
onKeyUp={this.onSearchInputKeyUp}
className={classes.textField}
/>
</div>
</Paper>
</Grid>
<Grid item xs={12}>
<Paper className={classes.paper}>
<div>
<Typography variant="h5">
Total Found: {numItems} Items
</Typography>
</div>
<div>
{numItems > 0 ? (
<Typography variant="subtitle1">
Displaying Results {1 + (this.page - 1) * this.perPage} -{" "}
{this.page * this.perPage}
</Typography>
) : (
<Typography variant="subtitle1">
Displaying 0 Results
</Typography>
)}
</div>
</Paper>
</Grid>
<Grid item xs={12}>
{error !== null ? (
<Paper className={classes.paperError}>
<div>
<Icon>error_outline</Icon>
</div>
<div>
<Typography variant="subtitle1">{error.message}</Typography>
</div>
</Paper>
) : (
<Grid container>
{items.map(item => (
<Grid item xs={6} key={item._source._id}>
<Card
className={classes.gridCard}
onClick={() => this.showBookParagraphModal(item)}
>
<CardContent>
<Typography
variant="h6"
className={classes.textParagraph}
>
{ReactHtmlParser(item.highlight.text[0])}
</Typography>
<Divider variant="middle" />
<Typography
variant="subtitle1"
className={classes.textTitle}
>
{item._source.title} - {item._source.author}
</Typography>
<Typography variant="body2">
Location {item._source.location}
</Typography>
</CardContent>
</Card>
</Grid>
))}
</Grid>
)}
</Grid>
<Grid item xs={12}>
<Paper
className={[classes.paper, classes.paginationPanel].join(" ")}
>
{this.prevPageUrl ? (
<Button
className={classes.buttonDefault}
onClick={this.prevResultsPage}
>
Prev Page
</Button>
) : (
<Button
disabled
className={classes.buttonDefault}
onClick={this.prevResultsPage}
>
Prev Page
</Button>
)}
{this.nextPageUrl ? (
<Button
className={classes.buttonDefault}
onClick={this.nextResultsPage}
>
Next Page
</Button>
) : (
<Button
disabled
className={classes.buttonDefault}
onClick={this.nextResultsPage}
>
Next Page
</Button>
)}
</Paper>
</Grid>
</Grid>
{selectedParagraph && (
<BookParagraph
selectedParagraph={selectedParagraph}
onCloseBookParagraphModal={this.onCloseBookParagraphModal}
/>
)}
</div>
);
}
}
Book.propTypes = {
books: PropTypes.objectOf(PropTypes.any),
classes: PropTypes.objectOf(PropTypes.string),
SearchBooks: PropTypes.func,
fetchBooksEnd: PropTypes.func,
fetchBooksError: PropTypes.func,
selectParagraph: PropTypes.func,
unselectParagraph: PropTypes.func
};
const mapStateToProps = ({ books }) => ({
books
});
const mapDispatchToProps = dispatch =>
bindActionCreators(BookActions, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(Book));
<|start_filename|>api/Dockerfile<|end_filename|>
FROM python:3.7-alpine
RUN adduser -D gs
WORKDIR /home/gs
COPY requirements.txt requirements.txt
RUN python -m venv venv
RUN venv/bin/pip install -r requirements.txt
RUN venv/bin/pip install gunicorn
RUN apk --no-cache add curl
COPY app app
COPY server.py config.py boot.sh wait-for.sh ./
RUN chmod +x boot.sh
RUN chmod +x wait-for.sh
ENV FLASK_APP server.py
RUN chown -R gs:gs ./
USER gs
EXPOSE 5000
ENTRYPOINT ["./boot.sh"]
<|start_filename|>ui/src/store/ducks/books.js<|end_filename|>
export const Types = {
FETCH_BOOKS_START: "books/FETCH_BOOKS_START",
FETCH_BOOKS_END: "books/FETCH_BOOKS_END",
FETCH_BOOKS_ERROR: "books/FETCH_BOOKS_ERROR",
SELECT_PARAGRAPH: "books/SELECT_PARAGRAPH",
UNSELECT_PARAGRAPH: "books/UNSELECT_PARAGRAPH"
};
const INITIAL_STATE = {
fetching: false,
fetched: false,
books: null,
selectedParagraph: null,
error: null
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case Types.FETCH_BOOKS_START:
return { ...state, fetching: true };
case Types.FETCH_BOOKS_END:
return {
...state,
fetching: false,
fetched: true,
books: action.payload,
error: null
};
case Types.FETCH_BOOKS_ERROR:
return {
...state,
fetching: false,
fetched: true,
books: null,
error: action.payload
};
case Types.SELECT_PARAGRAPH:
return {
...state,
selectedParagraph: action.payload
};
case Types.UNSELECT_PARAGRAPH:
return {
...state,
selectedParagraph: null
};
default:
return {
...state,
fetching: false
};
}
};
export const Creators = {
// With parenthesis there is no need to do a explicit return of the object inside the arrow func.
// The object is returned automatically.
fetchBooksStart: () => ({
type: Types.FETCH_BOOKS_START
}),
fetchBooksEnd: books => ({
type: Types.FETCH_BOOKS_END,
payload: books
}),
fetchBooksError: error => ({
type: Types.FETCH_BOOKS_ERROR,
payload: error
}),
SearchBooks: (query, page, perPage, newEndpoint) => async (
dispatch,
getState,
bookService
) => {
dispatch(Creators.fetchBooksStart());
const { SearchBooks } = bookService;
const books = await SearchBooks(query, page, perPage, newEndpoint);
return books;
},
selectParagraph: bookParagraph => ({
type: Types.SELECT_PARAGRAPH,
payload: bookParagraph
}),
unselectParagraph: () => ({
type: Types.UNSELECT_PARAGRAPH
})
};
| GlenioSP/Gutenberg-Search |
<|start_filename|>models/group.principal.js<|end_filename|>
import { MANAGEMENT, NORMAN } from '@/config/types';
import { clone } from '@/utils/object';
import principal from './principal';
export default {
...principal,
canViewInApi() {
return false;
},
nameDisplay() {
return this.principalNameDisplay;
},
principalNameDisplay() {
const principal = this.$rootGetters['rancher/byId'](NORMAN.PRINCIPAL, this.id);
return `${ principal.name } (${ principal.displayType })`;
},
detailLocation() {
const detailLocation = clone(this._detailLocation);
detailLocation.params.id = this.id; // Base fn removes part of the id (`github_team://3375666` --> `3375666`)
return detailLocation;
},
globalRoleBindings() {
return this.$rootGetters['management/all'](MANAGEMENT.GLOBAL_ROLE_BINDING)
.filter(globalRoleBinding => this.id === globalRoleBinding.groupPrincipalName);
},
_availableActions() {
return [
{
action: 'goToEdit',
label: this.t('action.edit'),
icon: 'icon icon-edit',
enabled: true,
},
{
action: 'unassignGroupRoles',
label: this.t('action.unassign'),
icon: 'icon icon-trash',
bulkable: true,
enabled: !!this.globalRoleBindings.length,
bulkAction: 'unassignGroupRoles',
},
];
},
unassignGroupRoles() {
return (resources = this) => {
const principals = Array.isArray(resources) ? resources : [resources];
const globalRoleBindings = this.$rootGetters['management/all'](MANAGEMENT.GLOBAL_ROLE_BINDING)
.filter(globalRoleBinding => principals.find(principal => principal.id === globalRoleBinding.groupPrincipalName));
this.$dispatch('promptRemove', globalRoleBindings);
};
},
};
<|start_filename|>models/management.cattle.io.nodetemplate.js<|end_filename|>
export default {
provider() {
const allKeys = Object.keys(this);
const configKey = allKeys.find( k => k.endsWith('Config'));
if ( configKey ) {
return configKey.replace(/config$/i, '');
}
},
providerDisplay() {
const provider = (this.provider || '').toLowerCase();
return this.$rootGetters['i18n/withFallback'](`cluster.provider."${ provider }"`, null, 'generic.unknown', true);
},
};
<|start_filename|>models/management.cattle.io.setting.js<|end_filename|>
import { ALLOWED_SETTINGS } from '@/config/settings';
export default {
_availableActions() {
const toFilter = ['cloneYaml', 'download', 'goToEditYaml', 'goToViewYaml', 'goToViewConfig'];
const settingMetadata = ALLOWED_SETTINGS[this.id];
let out = this._standardActions;
// Some settings are not editable
if (settingMetadata && settingMetadata.readOnly) {
toFilter.push('goToEdit');
}
out = out.filter((action) => {
return (!toFilter.includes(action.action));
});
// Change the label on the first action (edit)
const editAction = out.find(action => action.action === 'goToEdit');
if (editAction) {
editAction.label = this.t('advancedSettings.edit.label');
}
return out;
}
};
<|start_filename|>store/kubevirt.io.virtualmachine.js<|end_filename|>
export const state = function() {
return {
actionResources: null,
isShowBackUp: false,
isShowRestore: false,
isShowMigration: false,
isShowCloneTemplate: false
};
};
export const mutations = {
toggleBackupModal(state, resources = []) {
state.isShowBackUp = !state.isShowBackUp;
state.actionResources = resources;
},
toggleRestoreModal(state, resources = []) {
state.isShowRestore = !state.isShowRestore;
state.actionResources = resources;
},
toggleMigrationModal(state, resources = []) {
state.isShowMigration = !state.isShowMigration;
state.actionResources = resources;
},
toggleCloneTemplateModal(state, resources = []) {
state.isShowCloneTemplate = !state.isShowCloneTemplate;
state.actionResources = resources;
},
};
export const actions = {};
<|start_filename|>models/management.cattle.io.nodepool.js<|end_filename|>
import { MANAGEMENT } from '@/config/types';
export default {
nodeTemplate() {
const id = (this.spec?.nodeTemplateName || '').replace(/:/, '/');
const template = this.$getters['byId'](MANAGEMENT.NODE_TEMPLATE, id);
return template;
},
provider() {
return this.nodeTemplate?.provider;
},
providerDisplay() {
return this.nodeTemplate?.providerDisplay;
},
};
<|start_filename|>config/product/istio.js<|end_filename|>
import { DSL } from '@/store/type-map';
import { ISTIO } from '@/config/types';
import { STATE, NAME as NAME_HEADER, AGE } from '@/config/table-headers';
export const NAME = 'istio';
export const CHART_NAME = 'rancher-istio';
export function init(store) {
const {
product,
basicType,
virtualType,
headers
} = DSL(store, NAME);
product({
ifHaveGroup: /^(.*\.)*istio\.io$/,
icon: 'istio',
});
virtualType({
label: 'Overview',
group: 'Root',
namespaced: false,
name: 'istio-overview',
weight: 100,
route: { name: 'c-cluster-istio' },
exact: true,
overview: true,
});
basicType('istio-overview');
basicType([
'networking.istio.io.virtualservice',
'networking.istio.io.gateway',
'networking.istio.io.destinationrule',
]);
basicType([
'networking.istio.io.envoyfilter',
'networking.istio.io.serviceentrie',
'networking.istio.io.sidecar',
'networking.istio.io.workloadentrie',
], 'Networking');
basicType([
'rbac.istio.io.clusterrbacconfig',
'rbac.istio.io.rbacconfig',
'rbac.istio.io.servicerolebinding',
'rbac.istio.io.servicerole',
], 'RBAC');
basicType([
'security.istio.io.authorizationpolicie',
'security.istio.io.peerauthentication',
'security.istio.io.requestauthentication',
], 'Security');
headers(ISTIO.VIRTUAL_SERVICE, [
STATE,
NAME_HEADER,
{
name: 'gateways',
label: 'Gateways',
value: 'spec',
formatter: 'VirtualServiceGateways'
},
{
name: 'hosts',
label: 'Hosts',
value: 'spec.hosts',
sort: ['spec.hosts'],
formatter: 'List'
},
AGE
]);
}
<|start_filename|>models/catalog.cattle.io.app.js<|end_filename|>
import Vue from 'vue';
import {
NAMESPACE, NAME, REPO, REPO_TYPE, CHART, VERSION, _VIEW, FROM_TOOLS, _FLAGGED
} from '@/config/query-params';
import { CATALOG as CATALOG_ANNOTATIONS, FLEET } from '@/config/labels-annotations';
import { compare, isPrerelease, sortable } from '@/utils/version';
import { filterBy } from '@/utils/array';
import { CATALOG } from '@/config/types';
import { SHOW_PRE_RELEASE } from '@/store/prefs';
export default {
showMasthead() {
return (mode) => {
return mode === _VIEW;
};
},
applyDefaults() {
return () => {
Vue.set(this, 'disableOpenApiValidation', false);
Vue.set(this, 'noHooks', false);
Vue.set(this, 'skipCRDs', false);
Vue.set(this, 'timeout', 300);
Vue.set(this, 'wait', true);
};
},
_availableActions() {
const out = this._standardActions;
const upgrade = {
action: 'goToUpgrade',
enabled: true,
icon: 'icon icon-fw icon-edit',
label: this.t('catalog.install.action.goToUpgrade'),
};
out.unshift(upgrade);
return out;
},
matchingChart() {
return (includeHidden) => {
const chart = this.spec?.chart;
if ( !chart ) {
return;
}
const chartName = chart.metadata?.name;
const preferRepoType = chart.metadata?.annotations?.[CATALOG_ANNOTATIONS.SOURCE_REPO_TYPE];
const preferRepoName = chart.metadata?.annotations?.[CATALOG_ANNOTATIONS.SOURCE_REPO_NAME];
const match = this.$rootGetters['catalog/chart']({
chartName,
preferRepoType,
preferRepoName,
includeHidden
});
return match;
};
},
currentVersion() {
return this.spec?.chart?.metadata?.version;
},
upgradeAvailable() {
// false = does not apply (managed by fleet)
// null = no upgrade found
// object = version available to upgrade to
if ( this.spec?.chart?.metadata?.annotations?.[FLEET.BUNDLE_ID] ) {
// Things managed by fleet shouldn't show ugrade available even if there might be.
return false;
}
const chart = this.matchingChart(false);
if ( !chart ) {
return null;
}
const isWindows = this.$rootGetters['currentCluster'].providerOs === 'windows';
const showPreRelease = this.$rootGetters['prefs/get'](SHOW_PRE_RELEASE);
const thisVersion = this.spec?.chart?.metadata?.version;
let versions = chart.versions;
if (!showPreRelease) {
versions = chart.versions.filter(v => !isPrerelease(v.version));
}
const newestChart = versions?.[0];
const newestVersion = newestChart?.version;
if ( !thisVersion || !newestVersion ) {
return null;
}
if (isWindows && newestChart?.annotations?.['catalog.cattle.io/os'] === 'linux') {
return null;
} else if (!isWindows && newestChart?.annotations?.['catalog.cattle.io/os'] === 'windows') {
return null;
}
if ( compare(thisVersion, newestVersion) < 0 ) {
return cleanupVersion(newestVersion);
}
return null;
},
upgradeAvailableSort() {
const version = this.upgradeAvailable;
if ( !version ) {
return '~'; // Tilde sorts after all numbers and letters
}
return sortable(version);
},
goToUpgrade() {
return (forceVersion, fromTools) => {
const match = this.matchingChart(true);
const versionName = this.spec?.chart?.metadata?.version;
const query = {
[NAMESPACE]: this.metadata.namespace,
[NAME]: this.metadata.name,
[VERSION]: forceVersion || versionName,
};
if ( match ) {
query[REPO] = match.repoName;
query[REPO_TYPE] = match.repoType;
query[CHART] = match.chartName;
}
if ( fromTools ) {
query[FROM_TOOLS] = _FLAGGED;
}
this.currentRouter().push({
name: 'c-cluster-apps-install',
params: {
product: this.$rootGetters['productId'],
cluster: this.$rootGetters['clusterId'],
},
query,
});
};
},
details() {
const t = this.$rootGetters['i18n/t'];
const first = this.spec?.info?.firstDeployed;
const last = this.spec?.info?.lastDeployed;
if ( first && last && first !== last ) {
return [
{
label: t('model."catalog.cattle.io.app".lastDeployed'),
formatter: 'LiveDate',
content: last,
},
];
}
return [];
},
nameDisplay() {
const out = this.spec?.name || this.metadata?.name || this.id || '';
return out;
},
chartDisplay() {
const name = this.spec?.chart?.metadata?.name || '?';
return `${ name }:${ this.versionDisplay }`;
},
versionDisplay() {
return cleanupVersion(this.spec?.chart?.metadata?.version);
},
versionSort() {
return sortable(this.versionDisplay);
},
remove() {
return async(opt = {}) => {
const res = await this.doAction('uninstall', opt);
const operation = await this.$dispatch('find', {
type: CATALOG.OPERATION,
id: `${ res.operationNamespace }/${ res.operationName }`
});
try {
await operation.waitForLink('logs');
operation.openLogs();
} catch (e) {
// The wait times out eventually, move on...
}
};
},
canDelete() {
return this.hasAction('uninstall');
},
deployedResources() {
return filterBy(this.metadata?.relationships || [], 'rel', 'helmresource');
},
};
function cleanupVersion(version) {
if ( !version ) {
return '?';
}
if ( version.match(/^v/i) ) {
version = version.substr(1);
}
const hash = version.match(/[0-9a-f]{32,}/);
if ( hash ) {
version = version.replace(hash[0], hash[0].substr(0, 7));
}
return version;
}
<|start_filename|>models/harvesterhci.io.upgrade.js<|end_filename|>
import { NODE } from '@/config/types';
const LATEST_UPGRADE_RESOURCE = 'harvesterhci.io/latestUpgrade';
export default {
isCurrentUpgrade() {
return this?.metadata?.labels?.[LATEST_UPGRADE_RESOURCE] === 'true';
},
nodes() {
return this.$rootGetters['cluster/all'](NODE);
},
upgradeMessage() {
const upgradeMessage = [];
const nodeStatuses = this?.status?.nodeStatuses || {};
const conditions = this?.status?.conditions || [];
for (const key in nodeStatuses) {
const state = nodeStatuses[key]?.state;
if (nodeStatuses[key] && state !== 'Succeeded' && state !== 'succeeded') {
upgradeMessage.push({
id: key,
message: `The node ${ key } is ${ nodeStatuses[key]?.state }`
});
}
}
for (let i = 0; i < conditions.length; i++) {
const type = conditions[i].type;
if (type === 'systemServiceUpgraded' && conditions[i]?.status !== 'True') {
upgradeMessage.push({
id: 'systemService',
message: `The systemService is upgrading`
});
}
}
if (this.metadata?.state?.message && this.metadata?.state?.error) {
upgradeMessage.push({
id: 'message',
message: `${ this.metadata.state.message }`
});
}
return upgradeMessage;
},
nodeUpgradeMessage() {
const message = [];
const nodeStatuses = this?.status?.nodeStatuses || {};
for (const key in nodeStatuses) {
const state = nodeStatuses[key]?.state;
const _message = nodeStatuses[key]?.message;
let percent = 0;
if (state === 'Upgrading') {
percent = 50;
} else if (state === 'Succeeded' || state === 'succeeded') {
percent = 100;
}
message.push({
name: key,
state,
percent,
message: _message
});
}
for (const node of this.nodes) {
const hasNode = message.find( O => O.name === node.id);
if (!hasNode) {
message.push({
name: node.id,
state: 'Pending',
percent: 0,
});
}
}
return message;
},
nodeTotalPercent() {
let out = 0;
for (let i = 0; i < this.nodeUpgradeMessage.length; i++) {
out += this.nodeUpgradeMessage[i].percent;
}
out = Math.floor(out / this.nodeUpgradeMessage.length);
const nodeUpgradedCondition = this.getConditionStatus('nodesUpgraded');
if (out === 100 && !nodeUpgradedCondition) {
out = 99;
}
return out;
},
sysServiceUpgradeMessage() {
let percent = 0;
let state = 'Pending';
const message = [];
const conditions = this?.status?.conditions || [];
for (let i = 0; i < conditions.length; i++) {
const type = conditions[i].type;
if (type === 'systemServicesUpgraded') {
if (conditions[i].status === 'True') {
percent = 100;
state = 'Succeeded';
} else {
percent = 50;
}
message.push({
name: 'system services',
state,
percent,
message: conditions[i]?.message
});
}
}
if (message.length === 0) {
message.push({
name: 'system services',
state,
percent,
});
}
return message;
},
totalPercent() {
const nodePercent = this.nodeTotalPercent * this.nodeUpgradeMessage.length;
const servicePercent = this.sysServiceUpgradeMessage?.[0].percent;
return Math.floor((nodePercent + servicePercent) / (this.nodeUpgradeMessage.length + 1));
}
};
<|start_filename|>models/cluster.x-k8s.io.machine.js<|end_filename|>
import { CAPI } from '@/config/types';
import { CAPI as CAPI_LABELS } from '@/config/labels-annotations';
import { escapeHtml } from '@/utils/string';
import { insertAt } from '@/utils/array';
import { downloadUrl } from '@/utils/download';
export default {
_availableActions() {
const out = this._standardActions;
const openSsh = {
action: 'openSsh',
enabled: !!this.links.shell,
icon: 'icon icon-fw icon-chevron-right',
label: 'SSH Shell',
};
const downloadKeys = {
action: 'downloadKeys',
enabled: !!this.links.sshkeys,
icon: 'icon icon-fw icon-download',
label: 'Download SSH Key',
};
insertAt(out, 0, { divider: true });
insertAt(out, 0, downloadKeys);
insertAt(out, 0, openSsh);
return out;
},
openSsh() {
return () => {
this.$dispatch('wm/open', {
id: `${ this.id }-ssh`,
label: this.nameDisplay,
icon: 'terminal',
component: 'MachineSsh',
attrs: { machine: this, pod: {} }
}, { root: true });
};
},
downloadKeys() {
return () => {
downloadUrl(this.links.sshkeys);
};
},
cluster() {
if ( !this.spec.clusterName ) {
return null;
}
const clusterId = `${ this.metadata.namespace }/${ this.spec.clusterName }`;
const cluster = this.$rootGetters['management/byId'](CAPI.RANCHER_CLUSTER, clusterId);
return cluster;
},
poolName() {
return this.metadata?.labels?.[ CAPI_LABELS.DEPLOYMENT_NAME ] || '';
},
poolId() {
const poolId = `${ this.metadata.namespace }/${ this.poolName }`;
return poolId;
},
pool() {
return this.$rootGetters['management/byId'](CAPI.MACHINE_DEPLOYMENT, this.poolId);
},
groupByLabel() {
const name = this.cluster?.nameDisplay || this.spec.clusterName;
return this.$rootGetters['i18n/t']('resourceTable.groupLabel.cluster', { name: escapeHtml(name) });
},
};
<|start_filename|>models/persistentvolume.js<|end_filename|>
import { PVC } from '@/config/types';
export const VOLUME_PLUGINS = [
{
labelKey: 'persistentVolume.awsElasticBlockStore.label',
value: 'awsElasticBlockStore',
supported: true
},
{
labelKey: 'persistentVolume.azureDisk.label',
value: 'azureDisk',
supported: true
},
{
labelKey: 'persistentVolume.azureFile.label',
value: 'azureFile',
supported: true
},
{
labelKey: 'persistentVolume.cephfs.label',
value: 'cephfs',
},
{
labelKey: 'persistentVolume.rbd.label',
value: 'rbd',
},
{
labelKey: 'persistentVolume.csi.label',
value: 'csi',
},
{
labelKey: 'persistentVolume.fc.label',
value: 'fc',
},
{
labelKey: 'persistentVolume.flexVolume.label',
value: 'flexVolume',
},
{
labelKey: 'persistentVolume.flocker.label',
value: 'flocker',
},
{
labelKey: 'persistentVolume.glusterfs.label',
value: 'glusterfs',
},
{
labelKey: 'persistentVolume.gcePersistentDisk.label',
value: 'gcePersistentDisk',
supported: true
},
{
labelKey: 'persistentVolume.hostPath.label',
value: 'hostPath',
supported: true
},
{
labelKey: 'persistentVolume.iscsi.label',
value: 'iscsi',
},
{
labelKey: 'persistentVolume.local.label',
value: 'local',
supported: true
},
{
labelKey: 'persistentVolume.longhorn.label',
value: 'longhorn',
supported: true
},
{
labelKey: 'persistentVolume.nfs.label',
value: 'nfs',
supported: true
},
{
labelKey: 'persistentVolume.cinder.label',
value: 'cinder',
},
{
labelKey: 'persistentVolume.photonPersistentDisk.label',
value: 'photonPersistentDisk',
},
{
labelKey: 'persistentVolume.portworxVolume.label',
value: 'portworxVolume',
},
{
labelKey: 'persistentVolume.quobyte.label',
value: 'quobyte',
},
{
labelKey: 'persistentVolume.scaleIO.label',
value: 'scaleIO',
},
{
labelKey: 'persistentVolume.storageos.label',
value: 'storageos',
},
{
labelKey: 'persistentVolume.vsphereVolume.label',
value: 'vsphereVolume',
supported: true
},
];
export const LONGHORN_DRIVER = 'driver.longhorn.io';
export const LONGHORN_PLUGIN = VOLUME_PLUGINS.find(plugin => plugin.value === 'longhorn');
export default {
source() {
const plugin = this.isLonghorn ? LONGHORN_PLUGIN : VOLUME_PLUGINS.find(plugin => this.spec[plugin.value]);
return this.t(plugin.labelKey);
},
isLonghorn() {
return this.spec.csi && this.spec.csi.driver === LONGHORN_DRIVER;
},
claim() {
if (!this.name) {
return null;
}
const allClaims = this.$rootGetters['cluster/all'](PVC);
return allClaims.find(claim => claim.spec.volumeName === this.name);
},
canDelete() {
return this.state !== 'bound';
},
};
<|start_filename|>config/cookies.js<|end_filename|>
export const CSRF = 'CSRF';
export const USERNAME = 'R_USERNAME';
export const LOCALE = 'R_LOCALE';
<|start_filename|>utils/time.js<|end_filename|>
import day from 'dayjs';
const FACTORS = [60, 60, 24];
const LABELS = ['sec', 'min', 'hour', 'day'];
// Diff two dates and return an object with values for presentation
// If 't' is also passed, 'string' property is set on the return object with the diff formated as a string
// e.g. formats a date difference to return '1 day', '20 hours' etc
export function diffFrom(value, from, t) {
const now = day();
from = from || now;
const diff = value.diff(now, 'seconds');
let absDiff = Math.abs(diff);
let next = 1;
let label = '?';
let i = 0;
while ( absDiff >= FACTORS[i] && i < FACTORS.length ) {
absDiff /= FACTORS[i];
next *= Math.floor(FACTORS[i] / 10);
i++;
}
if ( absDiff < 5 ) {
label = Math.floor(absDiff * 10) / 10;
} else {
label = Math.floor(absDiff);
}
const ret = {
diff,
absDiff,
label,
unitsKey: `unit.${ LABELS[i] }`,
units: LABELS[i],
next,
};
if (!!t) {
ret.string = `${ ret.label } ${ t(ret.unitsKey, { count: ret.label }) }`;
}
return ret;
}
export function safeSetTimeout(timeout, callback, that) {
if (timeout <= 2147483647) {
// Max value setTimeout can take is max 32 bit int (about 24.9 days)
return setTimeout(() => {
callback.apply(that);
}, timeout);
}
}
<|start_filename|>models/network.harvesterhci.io.nodenetwork.js<|end_filename|>
export default {
message() {
return this.getStatusConditionOfType('Ready')?.message;
},
isReady() {
return this.getStatusConditionOfType('Ready')?.status === 'True';
},
physicalNics() {
return this?.status?.physicalNICs || [];
},
attachNodeName() {
return this.getLabelValue('network.harvesterhci.io/nodename');
},
linkMessage() {
return {
name: this.attachNodeName,
message: this.message,
to: `node/${ this.attachNodeName }?mode=edit`
};
}
};
<|start_filename|>utils/download.js<|end_filename|>
import JSZip from 'jszip';
export async function downloadFile(fileName, content, contentType = 'text/plain;charset=utf-8') {
const blob = new Blob([content], { type: contentType });
const { saveAs } = await import('file-saver');
return saveAs(blob, fileName);
}
// {[fileName1]:data1, [fileName2]:data2}
export function generateZip(files) {
// Moving this to a dynamic const JSZip = import('jszip') didn't work... figure out later
const zip = new JSZip();
for ( const fileName in files) {
if (files[fileName]) {
zip.file(fileName, files[fileName]);
}
}
return zip.generateAsync({ type: 'blob' });
}
export function downloadUrl(url, id = '__downloadIframe') {
let iframe = document.getElementById(id);
if ( !iframe ) {
iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.id = id;
document.body.appendChild(iframe);
}
iframe.src = url;
}
<|start_filename|>models/management.cattle.io.clusterroletemplatebinding.js<|end_filename|>
import { MANAGEMENT } from '@/config/types';
export default {
roleTemplate() {
return this.$rootGetters['management/byId'](MANAGEMENT.ROLE_TEMPLATE, this.roleTemplateName);
},
cluster() {
return this.$rootGetters['management/byId'](MANAGEMENT.CLUSTER, this.clusterName);
},
clusterDisplayName() {
return this.cluster ? this.cluster.nameDisplay : this.clusterName;
},
clusterDetailLocation() {
if (this.cluster) {
return this.cluster.detailLocation;
}
const name = `c-cluster-product-resource-id`;
const params = {
resource: MANAGEMENT.CLUSTER_ROLE_TEMPLATE_BINDING,
id: this.clusterName,
product: 'explorer',
};
return { name, params };
},
};
<|start_filename|>models/management.cattle.io.projectroletemplatebinding.js<|end_filename|>
import { MANAGEMENT } from '@/config/types';
export default {
projectId() {
// projectName is in format `local:p-v679w`. project id's are in format `local/p-v679w`,
return this.projectName.replace(':', '/');
},
clusterId() {
// projectName is in format `local:p-v679w`,
return this.projectName.substring(0, this.projectName.lastIndexOf(':'));
},
project() {
return this.$rootGetters['management/byId'](MANAGEMENT.PROJECT, this.projectId);
},
cluster() {
return this.$rootGetters['management/byId'](MANAGEMENT.CLUSTER, this.clusterId);
},
projectDisplayName() {
return this.project ? this.project.nameDisplay : this.projectName;
},
clusterDisplayName() {
return this.cluster ? this.cluster.nameDisplay : this.clusterId;
},
projectDetailLocation() {
if (this.project) {
return this.project.detailLocation;
}
const name = `c-cluster-product-resource-id`;
const params = {
resource: MANAGEMENT.PROJECT,
id: this.projectId,
product: 'explorer',
};
return { name, params };
},
clusterDetailLocation() {
if (this.cluster) {
return this.cluster.detailLocation;
}
const name = `c-cluster-product-resource-id`;
const params = {
resource: MANAGEMENT.CLUSTER_ROLE_TEMPLATE_BINDING,
id: this.clusterName,
product: 'explorer',
};
return { name, params };
},
roleTemplate() {
return this.$rootGetters['management/byId'](MANAGEMENT.ROLE_TEMPLATE, this.roleTemplateName);
}
};
| lucidd/harvester-ui |
<|start_filename|>menus/command-palette.cson<|end_filename|>
'menu': [
{
'label': 'View'
'submenu': [
{
'label': 'Toggle Command Palette'
'command': 'command-palette:toggle'
}
]
}
{
'label': 'Packages'
'submenu': [
{
'label': 'Command Palette',
'submenu': [
{
'label': 'Toggle'
'command': 'command-palette:toggle'
}
]
}
]
}
]
<|start_filename|>keymaps/command-palette.cson<|end_filename|>
'.platform-darwin, .platform-darwin .command-palette atom-text-editor':
'cmd-shift-p': 'command-palette:toggle'
'.platform-win32, .platform-win32 .command-palette atom-text-editor':
'ctrl-shift-p': 'command-palette:toggle'
'.platform-linux, .platform-linux .command-palette atom-text-editor':
'ctrl-shift-p': 'command-palette:toggle'
<|start_filename|>lib/command-palette-package.js<|end_filename|>
/** @babel */
import {CompositeDisposable} from 'atom'
import CommandPaletteView from './command-palette-view'
class CommandPalettePackage {
activate () {
this.commandPaletteView = new CommandPaletteView()
this.disposables = new CompositeDisposable()
this.disposables.add(atom.commands.add('atom-workspace', {
'command-palette:toggle': () => {
this.commandPaletteView.toggle()
},
'command-palette:show-hidden-commands': () => {
this.commandPaletteView.show(true)
}
}))
this.disposables.add(atom.config.observe('command-palette.useAlternateScoring', (newValue) => {
this.commandPaletteView.update({useAlternateScoring: newValue})
}))
this.disposables.add(atom.config.observe('command-palette.preserveLastSearch', (newValue) => {
this.commandPaletteView.update({preserveLastSearch: newValue})
}))
return this.commandPaletteView.show()
}
async deactivate () {
this.disposables.dispose()
await this.commandPaletteView.destroy()
}
}
const pack = new CommandPalettePackage()
export default pack
<|start_filename|>test/command-palette-view.test.js<|end_filename|>
/** @babel */
import _ from 'underscore-plus'
import assert from 'assert'
import semver from 'semver'
import sinon from 'sinon'
import CommandPaletteView from '../lib/command-palette-view'
import {CompositeDisposable} from 'event-kit'
describe('CommandPaletteView', () => {
let sandbox
let workspaceElement
beforeEach(() => {
workspaceElement = atom.views.getView(atom.workspace)
document.body.appendChild(workspaceElement)
document.body.focus()
sandbox = sinon.sandbox.create()
})
afterEach(() => {
sandbox.restore()
workspaceElement.remove()
})
describe('toggle', () => {
describe('when an element is focused', () => {
it('shows a list of all valid command descriptions, names, and keybindings for the previously focused element', async () => {
const editor = await atom.workspace.open()
editor.element.focus()
// To assert pure item rendering logic, disable render-on-visible behavior by passing Infinity to constructor.
const commandPalette = new CommandPaletteView(Infinity)
await commandPalette.toggle()
const keyBindings = atom.keymaps.findKeyBindings({target: editor.element})
for (const item of atom.commands.findCommands({target: editor.element})) {
const {name, description, displayName, tags} = item
const eventLi = workspaceElement.querySelector(`[data-event-name='${name}']`)
const displayNameLine = eventLi.querySelector('.primary-line')
assert.equal(displayNameLine.textContent, displayName)
assert.equal(displayNameLine.title, name)
if (description) {
// just in case it's not the first, need to select the item in order
// for its description to show
await commandPalette.selectListView.selectItem(item)
const descriptionEl = eventLi.querySelector('.secondary-line div')
assert(descriptionEl)
assert.equal(descriptionEl.textContent, description)
assert.equal(descriptionEl.title, description)
}
for (const binding of keyBindings) {
if (binding.command === name) {
assert(eventLi.textContent.includes(_.humanizeKeystroke(binding.keystrokes)))
}
}
}
})
})
describe('when no element has focus', () => {
it('uses the root view as the element to display and dispatch events to', async () => {
const findCommandsSpy = sandbox.spy(atom.commands, 'findCommands')
const findKeyBindingsSpy = sandbox.spy(atom.keymaps, 'findKeyBindings')
document.activeElement.blur()
const commandPalette = new CommandPaletteView()
await commandPalette.toggle()
assert(findCommandsSpy.calledWith({target: workspaceElement}))
assert(findKeyBindingsSpy.calledWith({target: workspaceElement}))
})
})
describe('when document.body has focus', () => {
it('uses the root view as the element to display and dispatch events to', async () => {
const findCommandsSpy = sandbox.spy(atom.commands, 'findCommands')
const findKeyBindingsSpy = sandbox.spy(atom.keymaps, 'findKeyBindings')
document.body.focus()
const commandPalette = new CommandPaletteView()
await commandPalette.toggle()
assert(findCommandsSpy.calledWith({target: workspaceElement}))
assert(findKeyBindingsSpy.calledWith({target: workspaceElement}))
})
})
it('focuses the mini-editor and selects the first command', async () => {
const commandPalette = new CommandPaletteView()
await commandPalette.toggle()
assert(commandPalette.selectListView.element.contains(document.activeElement))
assert(commandPalette.selectListView.element.querySelectorAll('.event')[0].classList.contains('selected'))
})
it('clears the previous mini editor text when `preserveLastSearch` is off', async () => {
const commandPalette = new CommandPaletteView()
await commandPalette.update({preserveLastSearch: false})
await commandPalette.toggle()
commandPalette.selectListView.refs.queryEditor.setText('abc')
await commandPalette.toggle()
assert.equal(commandPalette.selectListView.refs.queryEditor.getText(), 'abc')
await commandPalette.toggle()
assert.equal(commandPalette.selectListView.refs.queryEditor.getText(), '')
})
it('preserves the previous mini editor text when `preserveLastSearch` is on', async () => {
const commandPalette = new CommandPaletteView()
await commandPalette.update({preserveLastSearch: true})
await commandPalette.toggle()
commandPalette.selectListView.refs.queryEditor.setText('abc')
await commandPalette.toggle()
assert.equal(commandPalette.selectListView.refs.queryEditor.getText(), 'abc')
await commandPalette.toggle()
assert.equal(commandPalette.selectListView.refs.queryEditor.getText(), 'abc')
})
it('hides the command palette and focuses the previously active element if the palette was already open', async () => {
const editor = await atom.workspace.open()
const commandPalette = new CommandPaletteView()
assert.equal(document.activeElement.closest('atom-text-editor'), editor.element)
assert.equal(commandPalette.selectListView.element.offsetHeight, 0)
await commandPalette.toggle()
assert.notEqual(document.activeElement.closest('atom-text-editor'), editor.element)
assert.notEqual(commandPalette.selectListView.element.offsetHeight, 0)
await commandPalette.toggle()
assert.equal(commandPalette.selectListView.element.offsetHeight, 0)
assert.equal(document.activeElement.closest('atom-text-editor'), editor.element)
await commandPalette.toggle()
assert.notEqual(document.activeElement.closest('atom-text-editor'), editor.element)
assert.notEqual(commandPalette.selectListView.element.offsetHeight, 0)
commandPalette.selectListView.cancelSelection()
assert.equal(document.activeElement.closest('atom-text-editor'), editor.element)
assert.equal(commandPalette.selectListView.element.offsetHeight, 0)
})
})
describe('hidden commands', () => {
it('does not show commands that are marked as `hiddenInCommandPalette` by default, then *only* shows those commands when showHiddenCommands is invoked', async () => {
const commandsDisposable = atom.commands.add('*', 'foo:hidden-in-command-palette', {
hiddenInCommandPalette: true,
didDispatch () {}
})
const commandPalette = new CommandPaletteView()
await commandPalette.toggle()
assert(!commandPalette.selectListView.props.items.find(item => item.name === 'foo:hidden-in-command-palette'))
await commandPalette.show(true)
assert.equal(commandPalette.selectListView.props.items.length, 1)
assert.equal(commandPalette.selectListView.props.items[0].name, 'foo:hidden-in-command-palette')
})
})
describe('when selecting a command', () => {
it('hides the palette, then focuses the previously focused element and dispatches the selected command on it', async () => {
const editor = await atom.workspace.open()
editor.element.focus()
const commandPalette = new CommandPaletteView()
await commandPalette.toggle()
await commandPalette.selectListView.selectNext()
await commandPalette.selectListView.selectNext()
await commandPalette.selectListView.selectNext()
let hasDispatchedCommand = false
atom.commands.add(
editor.element,
commandPalette.selectListView.getSelectedItem().name,
() => { hasDispatchedCommand = true }
)
commandPalette.selectListView.confirmSelection()
assert(hasDispatchedCommand)
assert.equal(document.activeElement.closest('atom-text-editor'), editor.element)
assert.equal(commandPalette.selectListView.element.offsetHeight, 0)
})
})
describe('match highlighting', () => {
it('highlights exact matches', async () => {
const commandPalette = new CommandPaletteView()
await commandPalette.toggle()
commandPalette.selectListView.refs.queryEditor.setText('Application: About')
await commandPalette.selectListView.update()
const matches = commandPalette.selectListView.element.querySelectorAll('.character-match')
assert.equal(matches.length, 1)
assert.equal(matches[0].textContent, 'Application: About')
})
it('highlights partial matches in the displayName', async () => {
const commandPalette = new CommandPaletteView()
await commandPalette.toggle()
commandPalette.selectListView.refs.queryEditor.setText('Application')
await commandPalette.selectListView.update()
const matches = commandPalette.selectListView.element.querySelectorAll('.character-match')
assert(matches.length > 1)
for (const match of matches) {
assert.equal(match.textContent, 'Application')
}
})
it('highlights multiple matches in the command name', async () => {
const commandPalette = new CommandPaletteView()
await commandPalette.toggle()
commandPalette.selectListView.refs.queryEditor.setText('ApplicationAbout')
await commandPalette.selectListView.update()
const matches = commandPalette.selectListView.element.querySelectorAll('.character-match')
assert.equal(matches.length, 2)
assert.equal(matches[0].textContent, 'Application')
assert.equal(matches[1].textContent, 'About')
})
describe('in atom >= 1.21, where object command listeners are supported', () => {
if (semver.lt(atom.getVersion(), '1.21.0')) {
// only function listeners are supported, so the `add` method below will fail
return
}
let disposable
beforeEach(() => {
disposable = new CompositeDisposable()
})
afterEach(() => {
disposable.dispose()
})
it('highlights partial matches in the description', async () => {
disposable.add(atom.commands.add('*', 'foo:with-description', {
displayName: 'A Custom Display Name',
description: 'Awesome description here',
didDispatch () {}
}))
const commandPalette = new CommandPaletteView()
await commandPalette.toggle()
commandPalette.selectListView.refs.queryEditor.setText('Awesome')
await commandPalette.selectListView.update()
const {element} = commandPalette.selectListView
const withDescriptionLi = element.querySelector(`[data-event-name='foo:with-description']`)
const matches = withDescriptionLi.querySelectorAll('.character-match')
assert(matches.length > 0)
assert.equal(matches[0].textContent, 'Awesome')
})
it('highlights partial matches in the tags', async () => {
disposable.add(atom.commands.add('*', 'foo:with-tags', {
displayName: 'A Custom Display Name',
tags: ['bar', 'baz'],
didDispatch () {}
}))
const commandPalette = new CommandPaletteView()
await commandPalette.toggle()
commandPalette.selectListView.refs.queryEditor.setText('bar')
await commandPalette.selectListView.update()
const {element} = commandPalette.selectListView
const withTagsLi = element.querySelector(`[data-event-name='foo:with-tags']`)
const matches = withTagsLi.querySelectorAll('.character-match')
assert(matches.length > 0)
assert.equal(matches[0].textContent, 'bar')
})
})
})
describe('return placeholder element for invisible item for better performance', () => {
it('return placeholder element for first 10 items on initial toggle', async () => {
const commandPalette = new CommandPaletteView()
const spy = sinon.spy(commandPalette.selectListView.props, 'elementForItem')
await commandPalette.toggle()
const initiallyVisibleItemCount = 10
assert.equal(spy.args.length, commandPalette.selectListView.items.length)
spy.args.forEach((arg, index) => {
const innerText = spy.returnValues[index].innerText
if (index < initiallyVisibleItemCount) {
assert.notEqual(innerText, "")
} else {
assert.equal(innerText, "")
}
})
})
})
})
| laohubuzaijia/command-palette |
<|start_filename|>client/profile.js<|end_filename|>
var formatDate, weekDays;
var numStoriesToDisplay = 12;
weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
formatDate = function(date) {
var hms;
hms = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
return weekDays[date.getDay()] + " " + (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + hms;
};
Template.profile.onCreated(function(){
this.sectionToShow = new ReactiveVar('latest');
this.autorun(() => {
if(adminMode()){
this.subscribe('adminOtherUserPub', this.data.user._id);
}
});
});
Template.profile.events({
"click .show-latest" (e, t) {
t.sectionToShow.set('latest');
},
"click .show-favorites" (e, t) {
t.sectionToShow.set('favorites');
},
"click .show-following" (e, t) {
t.sectionToShow.set('following');
},
"click .show-followers" (e, t) {
t.sectionToShow.set('followers');
},
"click .followers-total" (e, t) {
t.sectionToShow.set('followers');
},
"click .following-total" (e, t) {
t.sectionToShow.set('following');
}
});
Template.profile.helpers({
"showLatest" (){
return Template.instance().sectionToShow.get() === 'latest';
},
"showFavorites" (){
return Template.instance().sectionToShow.get() === 'favorites';
},
"showFollowing" (){
return Template.instance().sectionToShow.get() === 'following';
},
"showFollowers" (){
return Template.instance().sectionToShow.get() === 'followers';
}
});
Template.my_stories.events({
'click .unpublish' (){
if (confirm('Are you sure you want to unpublish this story?')){
$('.story[data-story-id=' + this._id + ']').fadeOut(500, () => {
Meteor.call('unpublishStory', this._id, (err, result) => {
if(err || !result){
notifyError('Unpublish failed.');
}
});
})
}
},
'click .delete' (){
if (confirm('Are you sure you want to delete this story? This cannot be undone.')){
$('.story[data-story-id=' + this._id + ']').fadeOut(500, () => {
Meteor.call('deleteStory', this._id, (err, result) => {
if(err || !result){
notifyError('Delete failed.');
}
});
})
}
}
});
Template.my_stories.helpers({
publishedStories () {
if (Meteor.user()) {
return Stories.find({
authorId: Meteor.userId(),
published : true
});
}
},
unpublishedStories () {
if (Meteor.user()) {
return Stories.find({
authorId: Meteor.userId(),
published : false
});
}
},
lastEditDate () {
return prettyDateInPast(this.savedAt);
},
lastPublishDate () {
return prettyDateInPast(this.publishedAt);
}
});
Template.my_stories.events({
"click div#delete" (d) {
var srcE, storyId;
srcE = d.srcElement ? d.srcElement : d.target;
storyId = $(srcE).closest('div.story').data('story-id');
return Stories.remove({
_id: storyId
});
}
});
Template.user_profile.onCreated(function(){
this.autorun(() => { // TODO this sometimes runs twice unnecessarily if coming from home (first one does not have full profile user loaded with favorites)
var user = Meteor.users.findOne(this.data.user._id);
var usersFromStories = Stories.find({ published: true, _id: {$in: user.profile.favorites || []}}, {fields: {authorId:1}, reactive: false}).map(function(story){return story.authorId});
var usersToSubscribeTo = _.compact(_.union(usersFromStories, user.profile.following, user.followers));
this.subscribe('minimalUsersPub', _.sortBy(usersToSubscribeTo, _.identity));
});
this.editing = new ReactiveVar(false);
this.uploadPreview = new ReactiveVar();
this.uploadingPicture = new ReactiveVar();
this.pictureId = new ReactiveVar();
});
Template.user_profile.onRendered(function(){
this.$('.bio').linkify({linkAttributes: {rel : 'nofollow'}});
});
var ownProfile = function() {
var user = Meteor.user();
return (user && (user.username == this.user.username)) ? true : false
};
Template.user_profile.helpers({
editing () {
return Template.instance().editing.get()
},
ownProfile: ownProfile,
name () {
return this.user.profile.name
},
uploadPreview (){
return Template.instance().uploadPreview.get();
},
uploadingPicture (){
return Template.instance().uploadingPicture.get();
},
"email" (){
return this.user.emails ? this.user.emails[0].address : null;
},
bioHtml (){
return _.escape(this.user.profile.bio).replace(/(@\w+)/g, "<a href='https://twitter.com/$1' target='_blank'>$1</a>");
}
});
Template.user_profile.events({
"click .edit-profile" (d, template) {
template.editing.set(true);
},
"click .save-profile-button" (d, template) {
template.editing.set(false);
if (template.pictureId.get()) {
Meteor.call('saveProfilePicture', this.user._id, template.pictureId.get());
}
},
"change input[type=file]" (e, template){
var file = _.first(e.target.files);
if (file) {
if(file.size > CLOUDINARY_FILE_SIZE){
return notifyImageSizeError();
}
template.uploadingPicture.set(true);
// actual upload
Cloudinary.upload([file], {}, function(err, doc) {
template.uploadingPicture.set(false);
if(err){
var input = template.$('input[type=file]');
input.val(null);
input.change();
notifyError('Image upload failed');
} else {
template.uploadPreview.set('//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/w_150,h_150,c_fill,g_face/' + doc.public_id);
template.pictureId.set(doc.public_id);
}
})
} else {
template.uploadPreview.set(null);
}
}
});
Template.user_stories.onCreated(function(){
this.seeAllPublished = new ReactiveVar(false);
});
Template.user_stories.events({
"click .toggle-published" (d, template) {
return template.seeAllPublished.set(!template.seeAllPublished.get())
}
});
Template.user_stories.helpers({
seeAllPublished () {
return Template.instance().seeAllPublished.get()
},
publishedStories () {
var limit = 0; // = Template.instance().seeAllPublished.get() ? 0 : numStoriesToDisplay; //when limit=0 -> no limit on stories
return Stories.find({authorId : this.user._id, published : true}, {
sort: {
publishedAt: -1
},
limit: limit
})
},
showAllPublishedButton () {
return Stories.find({authorId : this.user._id, published : true}).count() > numStoriesToDisplay
},
hasPublished () {
return Stories.findOne({authorId : this.user._id, published : true})
},
hasDrafts (){
return Stories.findOne({authorId : this.user._id}, {published: false})
},
ownProfile: ownProfile
});
Template.user_favorite_stories.onCreated(function(){
this.seeAllFavorites = new ReactiveVar(false);
});
Template.user_favorite_stories.events({
"click .toggle-favorites" (d, template) {
return template.seeAllFavorites.set(!template.seeAllFavorites.get())
}
});
Template.user_favorite_stories.helpers({
seeAllFavorites () {
return Template.instance().seeAllFavorites.get()
},
favoriteStories () {
var limit = 0; // Template.instance().seeAllFavorites.get() ? 0 : numStoriesToDisplay;
var favorites = this.user.profile.favorites;
if (favorites && favorites.length) {
return Stories.find({
_id: {
$in: this.user.profile.favorites
}}, {
sort: {
publishedAt: -1
},
limit: limit
})
} else {
return [];
}
},
showAllFavoritesButton () {
var favorites = this.user.profile.favorites;
if (favorites && favorites.length) {
return favorites.length > numStoriesToDisplay
}
},
hasFavorites () {
return !_.isEmpty(this.user.profile.favorites);
},
ownProfile: ownProfile
});
Template.user_following.helpers({
usersFollowing () {
var following = this.user.profile.following;
if (following && following.length) {
return Meteor.users.find({
_id: {
$in: following
}})
} else {
return [];
}
},
ownProfile: ownProfile
});
Template.user_followers.helpers({
followers () {
var followers = this.user.followers;
if (followers && followers.length) {
return Meteor.users.find({
_id: {
$in: followers
}})
} else {
return [];
}
},
ownProfile: ownProfile
});
Template.person_card.helpers({
profileUrl (){
return '/profile/' + (Template.instance().data.person.displayUsername);
},
});
<|start_filename|>client/create.js<|end_filename|>
window.enclosingAnchorTag = null;
window.selectedNode = null;
var saveUpdatedSelection = function () {
$(window.selectedNode).closest('.content').blur();
};
window.removeAnchorTag = function(tag){
parentDiv = $(tag).closest('.content');
$(tag).contents().unwrap();
parentDiv.blur();
};
var saveNarrativeSectionContent = function (verticalIndex) {
$('.vertical-narrative-section[data-vertical-index="' + verticalIndex + '"]').find('.content').blur();
};
window.updateUIBasedOnSelection = function(e){
var selection = window.getSelection();
// Based off of code from https://github.com/daviferreira/medium-editor
return setTimeout((function(_this) {
return function() {
var boundary, boundaryMiddle, pageYOffset, range;
window.enclosingAnchorTag = null;
window.selectedNode = null;
var selectionType = window.getSelection().type;
var selectionLength = window.getSelection().toString().length;
if (selectionType !== 'None'){//(selectionType === 'Range' || selectionType === 'Caret' ) {
range = selection.getRangeAt(0);
// Get containing tag
if (rangeSelectsSingleNode(range)) {
selectedParentElement = range.startContainer.childNodes[range.startOffset];
} else if (range.startContainer.nodeType === 3) {
selectedParentElement = range.startContainer.parentNode;
} else {
selectedParentElement = range.startContainer;
}
var parentNode = selectedParentElement;
window.selectedNode = selectedParentElement;
var selectedTags = [];
var tagName;
// only do if selection is inside a fold-editable block
if($(parentNode).hasClass('fold-editable') || $(parentNode).parents('.fold-editable').length) {
while (parentNode.tagName !== undefined && parentNode.tagName.toLowerCase() !== 'div') {
tagName = parentNode.tagName.toLowerCase();
selectedTags.push(tagName);
if (selectionType !== 'Range' && tagName === 'a') { // we want type === 'Caret', but firefox doesn't do that, so just avoid range
window.enclosingAnchorTag = parentNode;
break;
}
parentNode = parentNode.parentNode;
}
Session.set('selectedTags', selectedTags);
// TO-DO actually get this from selection
if (e) {
if (selectionType === 'Range' || selectionLength) { // need to check selection length for firefox
showFoldEditor();
boundary = range.getBoundingClientRect();
boundaryMiddle = (boundary.left + boundary.right) / 2;
$('#fold-editor').css('left', boundaryMiddle - 205/2 + $(window).scrollLeft());
return $('#fold-editor').css('top', boundary.top - 70 + $(window).scrollTop());
} else if (window.enclosingAnchorTag) {
showFoldLinkRemover();
var offset = $(window.selectedNode).offset();
var posY = offset.top;
var posX = offset.left + $(window.selectedNode).width();
$('#fold-link-remover').css('left', posX - 8);
return $('#fold-link-remover').css('top', posY - 35);
} else {
return hideFoldAll();
}
}
} else {
return hideFoldAll();
}
} else {
return hideFoldAll();
}
};
})(this));
};
window.plainTextPaste = function(e) {
var clipboardData = (e.originalEvent || e).clipboardData;
e.preventDefault();
return document.execCommand('insertText', false, clipboardData.getData('text/plain'));
};
Template.create.onCreated(function() {
this.publishing = new ReactiveVar();
this.headerImageLoading = new ReactiveVar();
this.autorun(() => {
if (adminMode) {
this.subscribe('adminOtherUserPub', this.data.authorId); // for admins to see author info when read draft
}
})
});
Template.create.onRendered(function() {
window.showAnchorMenu = function() {
Session.set("anchorMenuOpen", true);
return $(".anchor-menu").show();
};
window.hideAnchorMenu = function() {
Session.set("anchorMenuOpen", false);
return $(".anchor-menu").hide();
};
window.toggleAnchorMenu = function() {
var anchorMenu, contextAnchorMenu, shiftAmt;
anchorMenu = $(".anchor-menu");
contextAnchorMenu = $(".context-anchor-menu");
shiftAmt = 120;
if (anchorMenu.is(':visible') || contextAnchorMenu.is(':visible')) {
$('#fold-editor').css('top', parseInt($('#fold-editor').css('top')) + shiftAmt);
window.hideAnchorMenu();
return window.hideContextAnchorMenu();
} else {
$('#fold-editor').css('top', parseInt($('#fold-editor').css('top')) - shiftAmt);
return window.showAnchorMenu();
}
};
window.showContextAnchorMenu = function() {
var contextAnchorForm;
contextAnchorForm = $(".context-anchor-menu");
contextAnchorForm.show();
Session.set("contextAnchorMenuOpen", true);
return contextAnchorForm.insertAfter('#fold-editor-button-group');
};
window.hideContextAnchorMenu = function() {
Session.set("contextAnchorMenuOpen", false);
return $(".context-anchor-menu").hide();
};
window.showFoldEditor = function() {
$('#fold-editor').show();
hideFoldLinkRemover();
};
window.hideFoldEditor = function() {
$('#fold-editor').hide();
hideContextAnchorMenu();
return hideAnchorMenu();
};
window.showFoldLinkRemover = function() {
$('#fold-link-remover').show();
hideFoldEditor();
};
window.hideFoldLinkRemover = function() {
$('#fold-link-remover').hide();
};
window.hideFoldAll = function() {
hideFoldEditor();
hideFoldLinkRemover();
};
this.autorun(function(){
switch(Session.get('saveState')) {
case 'saving':
Session.set('saving', true);
break;
case 'failed':
notifyError('Saving failed. Please refresh and try again.');
alert('Saving failed. Please refresh and try again.');
break;
case 'saved':
Session.set('saving', false);
break;
}
});
this.autorun(function(){
if (Session.get('read') || Session.get('currentYId')){
return window.hideFoldAll();
}
});
this.autorun(function() { // Hide add card menu when scroll
var y = Session.get('currentY'); // so reacts to changes in currentY
if(y !== Session.get('previousY')){
Session.set("addingContext", null);
}
Session.set('previousY', y)
});
this.autorun(function() { // update UI when start and stop adding/editing context
var currentContextBlocks, currentY, horizontalContextDiv, story, _ref;
if (Session.get('currentYId')) {
horizontalContextDiv = $(".horizontal-context");
horizontalContextDiv.removeClass('editing');
if (Session.get("addingContext")) { // editing individual cards isn't currently a thing // || (_ref = Session.get("editingContext"), __indexOf.call(currentContextBlocks, _ref) >= 0)) {
Session.set("showMinimap", false);
return horizontalContextDiv.addClass('editing');
} else {
Session.set("showMinimap", true);
if (document.body){
if(!Session.get('read') && !Session.get('metaview')){
document.body.style.overflow = 'auto'; // return scroll to document in case it lost it
removePlaceholderLinks();
}
}
}
}
});
if (!(Session.equals("currentY", void 0) && Session.equals("currentX", void 0))) {
$('.attribution, #to-story').fadeOut(1);
goToY(Session.get("currentY"));
goToX(Session.get("currentX"));
}
$(window).scrollTop(Session.get('scrollTop'));
window.updateCurrentY(); // needs to be manually triggered for better hot code reload behavior (perhaps due to throttle)
});
Template.fold_editor.helpers({
boldActive () {
return _.intersection(['b', 'strong'], Session.get('selectedTags')).length;
},
italicActive () {
return _.intersection(['i', 'em'], Session.get('selectedTags')).length;
},
underlineActive () {
return _.intersection(['u'], Session.get('selectedTags')).length;
},
anchorActive () {
return _.intersection(['a'], Session.get('selectedTags')).length || Session.get('contextAnchorMenuOpen') || Session.get('anchorMenuOpen');
}
});
Template.fold_editor.events({
'mouseup' () {
window.updateUIBasedOnSelection()
},
'mouseup .bold-button' (e) {
e.preventDefault();
document.execCommand('bold', false, null);
saveUpdatedSelection();
},
'mouseup .italic-button' (e) {
e.preventDefault();
document.execCommand('italic', false, null);
saveUpdatedSelection();
},
'mouseup .underline-button' (e) {
e.preventDefault();
document.execCommand('underline', false, null);
saveUpdatedSelection();
},
'mouseup .anchor-button' (e) {
e.preventDefault();
return toggleAnchorMenu();
}
});
Template.context_anchor_menu_contents.events({
'mouseenter .context-anchor-menu-contents' () {
document.body.style.overflow = 'hidden';
},
'mouseleave .context-anchor-menu-contents' (){
document.body.style.overflow='auto';
}
});
Template.context_anchor_go_back.events({
'mouseup' (e) {
e.preventDefault();
hideContextAnchorMenu();
return showAnchorMenu();
}
});
Template.anchor_menu.events({
'mouseup .link-to-card' (e) {
e.preventDefault();
hideAnchorMenu();
return showContextAnchorMenu();
},
'mouseup .link-out-of-story' (e) {
return e.preventDefault();
}
});
Template.fold_link_remover.events({
'mouseup button' (e) {
e.preventDefault();
removeAnchorTag(window.enclosingAnchorTag);
hideFoldAll();
}
});
// http://stackoverflow.com/questions/15867542/range-object-get-selection-parent-node-chrome-vs-firefox
var rangeSelectsSingleNode = function (range) {
var startNode = range.startContainer;
return startNode === range.endContainer &&
startNode.hasChildNodes() &&
range.endOffset === range.startOffset + 1;
};
window.saveCallback = function(err, success, cb) {
var saveUIUpdateDelay = 300;
setTimeout(function(){
if (err) {
return Session.set('saveState', 'failed');
}
if (!success) {
return Session.set('saveState', 'failed');
}
Session.set('saveState', 'saved');
}, saveUIUpdateDelay);
if(cb){
cb(err, success);
}
if (err){
throw(err);
}
};
var saveVerticalSectionContent = function(e, template) {
Session.set('saveState', 'saving');
Meteor.call('updateVerticalSectionContent',
Session.get('storyId'),
template.data.index,
cleanVerticalSectionContent($.trim(template.$('div.content').html())),
saveCallback);
return true;
};
var throttledSaveVerticalSectionContent = _.throttle(saveVerticalSectionContent, 4000, {trailing: false});
Template.vertical_section_block.events({
'blur [contenteditable]': window.updateUIBasedOnSelection,
'keyup [contenteditable]': window.updateUIBasedOnSelection,
'blur .title[contenteditable]' (e, template){
Session.set('saveState', 'saving');
Meteor.call('updateVerticalSectionTitle', Session.get('storyId'), template.data.index, $.trim(template.$('div.title').text()), saveCallback);
return true;
},
'keydown .title[contenteditable]' (e, template){
if (e.keyCode === 13){ // enter
e.preventDefault();
template.$('.content').focus();
}
return true;
},
'blur .content[contenteditable]' : saveVerticalSectionContent,
'keyup .content[contenteditable]' : throttledSaveVerticalSectionContent,
'paste .fold-editable' (e, t) {
var clipboardData, html;
e.preventDefault();
clipboardData = (e.originalEvent || e).clipboardData;
if (!clipboardData){return}
html = clipboardData.getData('text/html') || clipboardData.getData('text/plain');
var cleanedHtml = window.cleanVerticalSectionContent(html);
jqHtml = $('<div>' + cleanedHtml + '</div>');
jqHtml.find('a').each(function(){
let contextId = $(this).data('contextId');
if(!_.contains(t.data.contextBlocks, contextId)){ // if this link isn't to a context card in this row
$(this).contents().unwrap();
}
});
var htmlToPaste = jqHtml.html();
document.execCommand('insertHTML', false, htmlToPaste);
trackEvent('Paste into fold-editable area');
},
'drop' (e){
e.preventDefault();
trackEvent('Drop (attempt) into fold-editable area');
return false;
},
'paste .title.editable': window.plainTextPaste, // only allow plaintext in title
'mouseenter .narrative-babyburger-and-menu' (e, template){
template.babyburgerOpen.set(true);
},
'mouseleave .narrative-babyburger-and-menu' (e, template){
template.babyburgerOpen.set(false);
}
});
window.refreshContentDep = new Tracker.Dependency();
Template.vertical_section_block.onCreated(function() {
this.semiReactiveContent = new ReactiveVar(); // used in edit mode so that browser undo functionality doesn't break when autosave
this.babyburgerOpen = new ReactiveVar(false);
this.autorun(() => {
window.refreshContentDep.depend();
this.semiReactiveContent.set(this.data.content)
});
});
Template.vertical_section_block.onRendered(function () {
this.autorun(() => {
if (!hiddenContextMode()) {
Session.get('read') // make reactive to switching between preview and edit
var currentXId = Session.get('currentXId');
var pastHeader = Session.get("pastHeader");
if (Session.equals("currentYId", this.data._id) && pastHeader) { // if block is selected
if (currentXId) { // if there is a current context card
Meteor.setTimeout(() => {
this.$('a[data-context-id="' + currentXId + '"]').addClass('active');
this.$('a[data-context-id!="' + currentXId + '"]').removeClass('active');
}, 0)
}
} else {
Meteor.setTimeout(() => {
this.$('a').removeClass('active');
}, 0)
}
} else {
this.$('a').removeClass('active');
}
});
});
Template.vertical_section_block.helpers({
babyburgerOpen (){
return Template.instance().babyburgerOpen.get();
}
});
var resizeStoryTitleFont = function(){
var titleDiv = $('.story-title');
var fontSize = 24;
titleDiv.css({'font-size': (fontSize + 'px')});
while((titleDiv.width() < titleDiv[0].scrollWidth) && fontSize > 12){
fontSize -= 1;
titleDiv.css({'font-size': (fontSize + 'px')});
}
};
var resetStoryTitleFont = function(){
var titleDiv = $('.story-title');
var fontSize = 24;
titleDiv.css({'font-size': (fontSize + 'px')});
};
Template.story_title.onRendered(function(){
if(Session.get('read') && !window.hiddenContextMode()){
Meteor.setTimeout(resizeStoryTitleFont, 100);
} else {
resetStoryTitleFont();
}
this.autorun(()=> {
if(Session.get('read') && !window.hiddenContextMode()){
windowSizeDep.depend();
resizeStoryTitleFont();
} else {
resetStoryTitleFont();
}
})
});
Template.story_title.events({
'paste [contenteditable]': window.plainTextPaste,
'drop' (e){
e.preventDefault();
return false;
},
'blur .story-title[contenteditable]' (e,template) {
storyId = Session.get('storyId');
storyTitle = $.trim(template.$('div.story-title').text());
Session.set('saveState', 'saving');
return Meteor.call('updateStoryTitle', storyId, storyTitle, saveCallback)
}
});
Template.create.helpers({
publishing () {
return Template.instance().publishing.get();
},
headerImageLoading () {
return Template.instance().headerImageLoading.get();
}
});
Template.create.events({
'mouseup': window.updateUIBasedOnSelection, // this is here so that it fires when mouse goes off to the side of vertical section
"click .publish-story" (e, template) {
var accessPriority = Meteor.user().accessPriority;
if (!accessPriority || accessPriority > window.publishAccessLevel) {
notifyInfo("Due to high demand, we had to turn off publish functionality for a moment. Stay tuned for updates!");
} else {
template.publishing.set(true);
trackEvent('Click publish button');
}
},
"click .cancel-publish" (e, template) {
template.publishing.set(false);
trackEvent('Click cancel publish button');
},
"click .confirm-publish" (e, template) {
var title = template.$('input[name=confirm-title]').val();
var keywords = _.compact(template.$('input[name=keywords]').val().split(','));
var narrativeRightsReserved = template.$('input[name=reserve-rights]').is(':checked');
return Meteor.call('publishStory', this._id, title, keywords, narrativeRightsReserved, (err, numDocs) => {
template.publishing.set(false);
if (err) {
setTimeout(() => {
throw(err);
});
}
if (err || !numDocs) {
notifyError('Publication failed');
} else {
Router.go('/profile/' + Meteor.user().username);
notifySuccess('You story has been published!');
trackEvent('Publish story', window.trackingInfoFromStory(Stories.findOne(this._id))); // TODO add info about author
}
});
},
"change input.header-upload" (e, template){
var file = _.first(e.target.files);
if (file) {
if (file.size > CLOUDINARY_FILE_SIZE) {
return notifyImageSizeError();
}
template.headerImageLoading.set(true);
Session.set('saveState', 'saving');
console.log('bbbbb')
Cloudinary.upload([file], {}, (err, doc) => {
console.log('lalalalal')
if (err) {
template.headerImageLoading.set(false);
return saveCallback(err)
}
return Meteor.call('updateHeaderImage', this._id, doc.public_id, doc.format, (err, success) => {
template.headerImageLoading.set(false);
saveCallback(err, success)
});
});
trackEvent('Change upload header on header');
}
}
});
Template.add_vertical.events({
"click" () {
var indexToInsert, storyId, verticalSections;
storyId = Session.get('storyId');
verticalSections = Session.get('story').verticalSections;
indexToInsert = this.index != null ? this.index : verticalSections.length;
return Meteor.call('insertVerticalSection', storyId, indexToInsert, Random.id(9), function(err, numDocs) {
if (err) {
notifyError(err);
throw(err);
}
if (numDocs) {
trackEvent('Add vertical section', {
label: indexToInsert,
verticalSectionIndex: indexToInsert
});
} else {
notifyError('Inserting section failed');
}
});
}
});
Template.vertical_edit_menu.helpers({
canMoveUp () {
return this.index;
},
canMoveDown () {
return this.index < Session.get('story').verticalSections.length - 1;
}
});
Template.vertical_edit_menu.events({
"click .add-title" () {
var storyId = Session.get('storyId');
var index = this.index;
Session.set('saveState', 'saving');
Meteor.call('addTitle', storyId, index, saveCallback);
trackEvent('Click add section title');
},
"click .remove-title" () {
var storyId = Session.get('storyId');
var index = this.index;
Session.set('saveState', 'saving');
Meteor.call('removeTitle', storyId, index, saveCallback);
trackEvent('Click remove section title');
},
"click .move-card-up" () {
var storyId = Session.get('storyId');
var index = this.index;
Session.set('saveState', 'saving');
Meteor.call('moveVerticalSectionUpOne', storyId, index, saveCallback);
trackEvent('Click move card up');
},
"click .move-card-down" () {
var storyId = Session.get('storyId');
var index = this.index;
Session.set('saveState', 'saving');
Meteor.call('moveVerticalSectionDownOne', storyId, index, saveCallback);
trackEvent('Click move card down');
},
"click .delete-card" () {
if(confirm("Permanently delete this card and all associated context cards?")) {
var storyId = Session.get('storyId');
var index = this.index;
Session.set('saveState', 'saving');
Meteor.call('deleteVerticalSection', storyId, index, saveCallback);
trackEvent('Click delete card');
}
}
});
Template.add_horizontal.helpers({
left () {
return getVerticalLeft() + Session.get("cardWidth") + Session.get("separation");
}
});
var showNewHorizontalUI = function() {
slideCurrentYIntoPlace();
Session.set("addingContext", Session.get('currentYId'));
return Session.set("editingContext", null);
};
window.hideNewHorizontalUI = function() {
slideCurrentYIntoPlace();
return Session.set("addingContext", null);
};
var defaultContextType = 'video';
var toggleHorizontalUI = function(forceBool) {
if (!Session.get("addingContext")) {
Session.set('newHorizontalDataType', defaultContextType);
showNewHorizontalUI()
} else {
hideNewHorizontalUI()
}
};
Template.add_horizontal.events({
"click" (d) {
toggleHorizontalUI();
trackEvent('Click toggle horizontal editor');
}
});
Template.create_horizontal_section_block.onCreated(function() {
Session.setDefault('newHorizontalDataType', defaultContextType);
});
Template.create_horizontal_section_block.helpers({
type () {
return Session.get('newHorizontalDataType');
},
text () {
return Session.get('newHorizontalDataType') === "text";
},
image () {
return Session.get('newHorizontalDataType') === "image";
},
gif () {
return Session.get('newHorizontalDataType') === "gif";
},
map () {
return Session.get('newHorizontalDataType') === "map";
},
video () {
return Session.get('newHorizontalDataType') === "video";
},
twitter () {
return Session.get('newHorizontalDataType') === "twitter";
},
viz () {
return Session.get('newHorizontalDataType') === "viz";
},
audio () {
return Session.get('newHorizontalDataType') === "audio";
},
link () {
return Session.get('newHorizontalDataType') === "link";
},
remix () {
return Session.get('newHorizontalDataType') === "remix";
}
});
Template.create_horizontal_section_block.helpers({
left () {
var addBlockWidth = 75;
return addBlockWidth + getVerticalLeft() + Session.get("cardWidth") + 2 * Session.get("separation");
},
actionCardPrivileges (){
var user = Meteor.user();
return (user && user.privileges && user.privileges.actionCard)
}
});
Template.create_horizontal_section_block.events({
'click .text-button' (d, t) {
return Session.set('newHorizontalDataType', 'text');
},
'click .map-button' (d, t) {
return Session.set('newHorizontalDataType', 'map');
},
'click .video-button' (d, t) {
return Session.set('newHorizontalDataType', 'video');
},
'click .image-button' (d, t) {
return Session.set('newHorizontalDataType', 'image');
},
'click .gif-button' (d, t) {
return Session.set('newHorizontalDataType', 'gif');
},
'click .twitter-button' (d, t) {
return Session.set('newHorizontalDataType', 'twitter');
},
'click .viz-button' (d, t) {
return Session.set('newHorizontalDataType', 'viz');
},
'click .audio-button' (d, t) {
return Session.set('newHorizontalDataType', 'audio');
},
'click .link-button' (d, t) {
return Session.set('newHorizontalDataType', 'link');
},
'click .remix-button' (d, t) {
return Session.set('newHorizontalDataType', 'remix');
},
'click .add-action-button' (d, t) {
addContext({type: 'action'});
hideNewHorizontalUI();
},
'mouseenter .horizontal-narrative-section' () {
document.body.style.overflow = 'hidden';
},
'mouseleave .horizontal-narrative-section' (){
document.body.style.overflow='auto';
}
});
Template.horizontal_context.helpers({
lastUpdate () {
Session.get('lastUpdate');
}
});
window.findPlaceholderLink = function(verticalSectionIndex){
return $('.vertical-narrative-section[data-vertical-index="' + verticalSectionIndex + '"]').find('a.placeholder');
};
var removePlaceholderLinks = function(){
return $('.vertical-narrative-section').find('a.placeholder').contents().unwrap();
};
Template.context_anchor_new_card_option.events = {
"mousedown" (e) {
e.preventDefault();
hideFoldEditor();
removePlaceholderLinks();
var placeholderHrefToken = '#LinkToNextCard';
document.execCommand('createLink', false, placeholderHrefToken);
var placeholderAnchorElement = $('a[href="' + placeholderHrefToken +'"]'); // find temporary anchor
placeholderAnchorElement.attr('href', 'javascript:void(0);'); // get rid of temporary href
placeholderAnchorElement.addClass('placeholder');
showNewHorizontalUI();
trackEvent('Click add new card inside fold editor');
}
};
Template.context_anchor_option.events = {
"mousedown" (e) {
var contextId, link;
e.preventDefault();
hideFoldEditor();
contextId = this._id;
// need to create temporary link because want to take advantage of createLink browser functionality
// but the link really gets interacted with via the 'data-context-id' attribute
var temporaryHrefToken = '#<PASSWORD>';
document.execCommand('createLink', false, temporaryHrefToken);
var temporaryAnchorElement = $('a[href="' + temporaryHrefToken +'"]'); // find temporary anchor
temporaryAnchorElement.attr('href', 'javascript:void(0);'); // get rid of temporary href
temporaryAnchorElement.attr('data-context-id', contextId); // set data attributes correctly
temporaryAnchorElement.attr('data-context-type', this.type);
temporaryAnchorElement.attr('data-context-source', this.source);
temporaryAnchorElement.attr('data-anchor-id', Random.id(8));
temporaryAnchorElement.addClass('active'); // add active class because we go to this context and if we're already there it won't get the class
//temporaryAnchorElement.data({contextId: contextId});
saveUpdatedSelection();
goToContext(contextId);
trackEvent('Click add link to context option inside fold editor');
return false;
}
};
window.addContext = function(contextBlock) {
var storyId = Session.get("storyId");
var verticalIndex = Session.get("currentY");
Session.set('query', null); // clear query so it doesn't seem like you're editing this card next time open the new card menu
Session.set('saveState', 'saving');
Meteor.call('addContextToStory', storyId, Session.get("storyShortId"), contextBlock, verticalIndex, function(err, contextId){
if (contextId){
saveNarrativeSectionContent(verticalIndex);
}
saveCallback(err, contextId);
});
};
Template.horizontal_section_edit_delete.helpers({
canMoveLeft () {
return this.index;
},
canMoveRight () {
return this.index < Session.get('story').verticalSections[this.verticalIndex].contextBlocks.length - 1;
}
});
Template.horizontal_section_block.events({
"click .delete" (d) {
trackEvent('Click delete horizontal');
if(confirm("Permanently delete this card?")){
var currentY = Session.get("currentY");
Session.set('saveState', 'saving');
id = this._id;
removeAnchorTag($('.vertical-narrative-section[data-vertical-index="'+ currentY +'"] .content a[data-context-id="' + id + '"]'));
Meteor.call('removeContextFromStory', Session.get("storyId"), id, currentY, saveCallback);
trackEvent('Confirm delete horizontal');
}
},
"click .edit" (e, t) {
Session.set('editingContext', this._id);
Session.set('addingContext', false);
trackEvent('Click edit horizontal');
}
});
Template.create_options.events({
"click .toggle-preview" () {
if (Session.get('read')) {
window.refreshContentDep.changed();
Session.set('read', false);
trackEvent('Click toggle preview off');
} else {
Session.set('read', true);
trackEvent('Click toggle preview on');
}
},
"click .how-to-button" (){
openHowToOverlay();
}
});
Template.link_twitter.events({
"click button" () {
Meteor.linkWithTwitter({
requestPermissions: ['user']
}, function (err) {
if (err) {
notifyError("Twitter login failed");
throw(err);
} else if (!Meteor.user().profile.bio){
Meteor.call('setBioFromTwitter')
}
});
trackEvent('Click Link Twitter');
}
});
Template.publish_overlay.onRendered(function(){
this.$('#story-tags-input').tagsInput({
minInputWidth: '80px',
width: '100%',
height: '83px'
});
});
Template.publish_overlay.helpers({
'keywordsString' (){
return (this.keywords || []).toString();
}
});
Template.publish_overlay.events({
'click .header-upload' (e, t) {
Meteor.setTimeout(function(){
$('body,html').animate({
scrollTop: 0
}, 500, 'easeInExpo')}
, 1500)
trackEvent('Click upload header inside publish dialog');
}
});
<|start_filename|>server/methods.js<|end_filename|>
var countStat = function(storyId, stat, details) {
var connectionId = this.connection.id;
var clientIP = this.connection.httpHeaders['x-forwarded-for'] || this.connection.clientAddress;
var story = Stories.findOne({_id: storyId, published: true});
if (!story){
throw new Meteor.error('Story not found for count ' + stat + ': ' + storyId); // this mostly confirms the story has been published
}
var stats = StoryStats.findOne({storyId: storyId}, {fields: {all: 0}});
if(!stats){
stats = {};
}
if (!stats.deepAnalytics){
stats.deepAnalytics= {};
}
if (!stats.deepAnalytics[stat]){
stats.deepAnalytics[stat] = {};
}
var addToSet = {};
var inc = {};
inc['analytics.' + stat + '.total'] = 1;
if(!_.contains(stats.deepAnalytics[stat].uniqueViewersByConnection, connectionId)){
addToSet['deepAnalytics.' + stat + '.uniqueViewersByConnection'] = connectionId ;
inc['analytics.' + stat + '.byConnection'] = 1;
if(stat === 'shares'){
generateShareActivity(story._id, details.service);
}
}
if(!_.contains(stats.deepAnalytics[stat].uniqueViewersByIP, clientIP)){
addToSet['deepAnalytics.' + stat + '.uniqueViewersByIP'] = clientIP ;
inc['analytics.' + stat + '.byIP'] = 1;
if((stat === 'views') && stats.analytics && stats.analytics.views){
var uniqueViews = stats.analytics.views.byIP + 1;
if(_.contains(VIEW_THRESHOLDS, uniqueViews)){
generateViewThresholdActivity(story._id, uniqueViews);
}
}
}
if (this.userId && !_.contains(stats.deepAnalytics[stat].uniqueViewersByUserId, this.userId)){
addToSet['deepAnalytics.' + stat + '.uniqueViewersByUserId'] = this.userId ;
inc['analytics.' + stat + '.byId'] = 1;
}
var push = {};
var fullData = _.extend({}, _.omit(this.connection, ['close', 'onClose']), {date: new Date});
if (this.userId){
_.extend(fullData, {
userId: this.userId,
username: Meteor.user().username
});
};
if (details){
_.extend(fullData, details);
};
push['deepAnalytics.' + stat + '.all'] = fullData;
Stories.update( {_id: storyId}, {$inc: inc });
StoryStats.upsert( {storyId: storyId} , {$inc: inc, $addToSet: addToSet, $push: push} );
};
var checkCountMap = function(countMap){
check(countMap, Object);
_.keys(countMap, function (e) {
check(e, String); // these should be ids
check(e, Match.Where(function (str) {
return (/^[^.]*$/).test(str); // check has no periods
}))
});
_.values(countMap, function (e) {
check(e, Number);
check(e, Match.Where(function (num) {
return num > 0; // check only positive numbers
}));
});
};
Meteor.methods({
countStoryView: function(storyId) {
this.unblock();
check(storyId, String);
countStat.call(this, storyId, 'views');
},
countStoryShare: function(storyId, service) {
this.unblock();
check(storyId, String);
countStat.call(this, storyId, 'shares', {service: service});
},
countStoryRead: function(storyId, service) {
this.unblock();
check(storyId, String);
countStat.call(this, storyId, 'reads', {service: service});
},
countStoryAnalytics: function(storyId, analytics) {
this.unblock();
check(storyId, String);
var activeHeartbeatCountMap = analytics.activeHeartbeats;
checkCountMap(activeHeartbeatCountMap);
var anchorClickCountMap = analytics.anchorClicks;
checkCountMap(anchorClickCountMap);
var maxClicks = Math.ceil(activeHeartbeatCountMap.story / 5);
_.keys(anchorClickCountMap, (k) => {
anchorClickCountMap[k] = Math.min(anchorClickCountMap[k], maxClicks)
});
var contextInteractionCountMap = analytics.contextInteractions;
checkCountMap(contextInteractionCountMap);
var maxInteractions = Math.ceil(activeHeartbeatCountMap.story / 10);
_.keys(contextInteractionCountMap, (k) => {
contextInteractionCountMap[k] = Math.min(contextInteractionCountMap[k], maxInteractions)
});
var incMap = {};
_.each(_.keys(activeHeartbeatCountMap), function (k) {
incMap['analytics.heartbeats.active.' + k] = activeHeartbeatCountMap[k];
});
if(!_.isEmpty(anchorClickCountMap)){
_.each(_.keys(anchorClickCountMap), function (k) {
incMap['analytics.anchorClicks.' + k] = anchorClickCountMap[k];
});
}
if(!_.isEmpty(contextInteractionCountMap)){
_.each(_.keys(contextInteractionCountMap), function (k) {
incMap['analytics.contextInteractions.' + k] = contextInteractionCountMap[k];
});
}
StoryStats.upsert({storyId: storyId}, {$inc: incMap});
return Stories.update({_id: storyId}, {$inc: incMap});
},
impersonate: function(username) {
check(username, String);
var user = Meteor.user();
if (!user || !user.admin || !user.privileges || !user.privileges.impersonation){
throw new Meteor.Error(403, 'Permission denied');
}
var otherUser;
if (!(otherUser = Meteor.users.findOne({username: username}))){
throw new Meteor.Error(404, 'User not found');
}
this.setUserId(otherUser._id);
return otherUser._id
},
getActivityFeed: function(aId){
check(aId, Match.Optional(String));
if(!this.userId){
throw new Meteor.Error("Only users may get their activity feed");
}
var query = aId ? {uId: this.userId, aId: aId} : {uId: this.userId};
var activityIds = ActivityFeedItems.find(query, {sort:{r: -1}, limit: 50, fields: {'aId' : 1}}).map(function(i){return i.aId});
return Activities.find({_id: {$in: activityIds}}).fetch();
}
});
<|start_filename|>collections/collections.js<|end_filename|>
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
SimpleSchema.debug = true; // TODO Remove after launch
if(!this.Schema){
Schema = {};
};
Story = (function() {
function Story(doc) {
_.extend(this, doc);
if (this.draftStory){
_.extend(this.draftStory, {
unpublishedChanges: (!this.published || !this.publishedAt || this.savedAt > this.publishedAt),
savedAt: this.savedAt,
userPathSegment: this.userPathSegment,
authorUsername: this.authorUsername,
authorDisplayUsername: this.authorDisplayUsername,
authorId: this.authorId,
authorName: this.authorName,
contextCountOfType (){}, // stub out for now
narrativeCount (){}, // stub out for now
countContextTypes (){}, // stub out for now
headerImageUrl: this.headerImageUrl.bind(this.draftStory),
headerImageVideoObject: this.headerImageVideoObject.bind(this.draftStory),
_id: this._id
});
}
}
Story.prototype.readPath = function(){
return '/read/' + this.userPathSegment + '/' + this.storyPathSegment;
};
Story.prototype.contentPreview = function() {
var content;
if (content = this.verticalSections[0].content) {
if(Meteor.isClient){
return $($.parseHTML(content)).text();
} else {
return cheerio.load('<body>' + content + '</body>')('body').text();
}
}
};
Story.prototype.updateAuthor = function(user) {
if (user == null) {
user = Meteor.user();
}
this.authorId = user._id;
this.authorName = user.profile.name;
return this.title = "";
};
Story.prototype.narrativeCount = function() {
return this.verticalSections ? this.verticalSections.length : null;
};
Story.prototype.contextCount = function() {
return this.contextBlocks.length;
};
Story.prototype.contextCountOfType = function(type) {
return this.contextBlocks.reduce(function(count, contextBlock){
if(contextBlock.type === type){
count++;
}
return count;
}, 0)
};
Story.prototype.countContextTypes = function(){
return _.chain(this.contextBlocks).pluck('type').countBy(_.identity).value()
};
Story.prototype.headerImageUrl = function(size){
return Story.getHeaderImageUrl(this.headerImage, size);
};
Story.prototype.headerImageVideoObject = function(size){
return // looping video has chops occasionally, don't show it for now
if (this.headerImageFormat ==='gif' && !Meteor.Device.isPhone()){
var headerImageUrl = this.headerImageUrl(size);
return {
previewUrl: headerImageUrl + '.jpg',
mp4Url: headerImageUrl + '.mp4',
webMUrl: headerImageUrl + '.webm'
}
}
};
Story.prototype.maxActiveHeartbeats = function(){
if(!this.analytics.heartbeats){
return 0;
}
return _.chain(this.analytics.heartbeats.active)
.omit(['story', 'header', 'footer'])
.values()
.max()
.value()
};
Story.prototype.maxActiveNarrativeHeartbeats = function(){
if(!this.analytics.heartbeats){
return 0;
}
return _.chain(this.analytics.heartbeats.active)
.pick(_.pluck(this.verticalSections, '_id'))
.values()
.max()
.value()
};
Story.prototype.maxActiveContextHeartbeats = function(){
if(!this.analytics.heartbeats){
return 0;
}
return _.chain(this.analytics.heartbeats.active)
.pick(this.contextBlockIds)
.values()
.max()
.value()
};
Story.prototype.maxAnchorClicks = function(){
if(!this.analytics.anchorClicks){
return 0
}
return _.chain(this.analytics.anchorClicks)
.values()
.max()
.value()
};
Story.getHeaderImageUrl = function(headerImageId, size){
var image, imageFormat, url;
image = headerImageId;
var maxWidth = (size === 'small') ? 800 : 2048;
var maxHeight = (size === 'small') ? 230 : 350;
if (image) {
if (image <= 13){ // if it's a placeholder image
var headerAtmosphereMap = {
1: "SAUCERS",
2: "OCEAN",
3: "FLOWERS",
4: "BUILDING",
5: "LIGHTNING",
6: "DANCER",
7: "CUBES",
8: "COMPUTER",
9: "MARSH",
10: "RINGS",
11: "MOTH",
12: "MOUNTAINS",
13: "AERIAL"
};
var headerAtmosphereName = headerAtmosphereMap[image];
if (!headerAtmosphereName){
Meteor.defer(function(){
throw new Meteor.Error('Header atmosphere not found');
})
}
url = '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_lfill,g_north,h_' + maxHeight + ',w_' + maxWidth + '/static/header_atmosphere_' + headerAtmosphereName
} else {
url = '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_lfill,g_north,h_' + maxHeight + ',w_' + maxWidth + '/' + image
}
}
if(this.headerImageFormat === 'gif'){ // animated header image is static jpg on phone for now //if(Meteor.Device.isPhone() && this.headerImageFormat ==='gif'){
url += '.jpg'; // TODO, this could conflict with headerImageVideoObject if conditional changes
}
return url
};
Story.prototype.embedCode = function(){
return '<iframe width="100%" height="600" src="' + Meteor.absoluteUrl('embed/' + this.userPathSegment + '/' + this.storyPathSegment) + '" frameborder="0" allowfullscreen></iframe>' +
'<script async src="' + Meteor.absoluteUrl('js/responsive-embed.js') + '"></script>'
};
return Story;
})();
// TO-DO consider replacing htmlclean with https://github.com/cristo-rabani/meteor-universe-html-purifier/
var cleanHtmlOptions = {
allowedTags: ['strong', 'em', 'u', 'b', 'a', 'br'], // only allow tags used in fold-editor and
format: false,
removeTags: [], // allow u tag
removeAttrs: ['class', 'id', 'href'], // strip away hrefs and other undesired attributes that might slip into a paste
allowedAttributes: [["data-context-id"],["data-context-type"],["data-context-source"], ["data-anchor-id"]] // data-context-id is used to direct links to context cards
};
var matchAnchors = /<a( data-[a-z-]*?=["|'].*?["|'])?( data-[a-z-]*?=["|'].*?["|'])?( data-[a-z-]*?=["|'].*?["|'])?( data-[a-z-]*?=["|'].*?["|'])?.*?>/gm; // match anchors, capture data-context-id and other attributes so it can be kept in string
var matchBlankAnchors = /<a href="javascript:void\(0\);">(.*?)<\/a>/gm; // match anchors that are left over from above if copied from somewhere else, capture contents so can be kept
cleanVerticalSectionContent = function(html) {
var preClean = html // this fixes issues with line-breaks at the edge of other tags
.replace(new RegExp('<br />', 'g'), '<br>') // just in case
.replace(new RegExp('<br></strong>', 'g'), '</strong><br>')
.replace(new RegExp('<br></em>', 'g'), '</em><br>')
.replace(new RegExp('<br></u>', 'g'), '</u><br>')
.replace(new RegExp('<br></b>', 'g'), '</b><br>')
.replace(new RegExp('<br></i>', 'g'), '</i><br>');
var initialClean = $.htmlClean(preClean, _.extend({}, _.omit(cleanHtmlOptions, 'allowedTags'), {allowEmpty: ['div']})); // do all cleaning except tag removal. allowEmpty means <div><br></div> turns into <div></div> instead of being deleted entirely
var linebreakClean = initialClean
.replace(new RegExp('<br />', 'g'), '<br>')
.replace(new RegExp('<div><br></div>', 'g'), '<br>')
.replace(new RegExp('<div>', 'g'), '<br>')
.replace(new RegExp('</div>', 'g'), '');
return $.htmlClean(linebreakClean, cleanHtmlOptions)
.replace(matchAnchors, '<a href="javascript:void(0);"$1$2$3$4>') // add js void to all anchors and keep all data-context-ids and other data attributes
.replace(matchBlankAnchors, '$1') // remove anchors without data-context-ids
.replace(new RegExp('<br />', 'g'), '<br>');
};
if (Meteor.isClient) {
window.Story = Story;
window.cleanVerticalSectionContent = cleanVerticalSectionContent;
}
this.Stories = new Mongo.Collection("stories", {
transform (doc) {
return new Story(doc);
}
});
this.Stories.deny({
insert () {
return true;
},
update () {
return true
},
remove () {
return true;
}
});
ContextBlocks = new Mongo.Collection("context_blocks", {
transform: newTypeSpecificContextBlock
});
this.ContextBlocks.deny({
insert () {
return true;
},
update () {
return true
},
remove () {
return true
}
});
var __hasProp = {}.hasOwnProperty,
__extends = function (child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
};
var getIdFromUrl = function(url){
return _.chain(url.split('/')).compact().last().value().match(/[\d]*/)[0]
};
var parseDate = function(date) {
return date.substring(0,10).replace( /(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
};
ContextBlock = (function () {
function ContextBlock(doc) {
_.extend(this, doc);
}
return ContextBlock;
})();
youtubeMapFn = function (e) {
return {
reference: {
title: e.title,
description: e.description,
id: e.videoId,
username: e.channelTitle,
userId: e.channelId,
creationDate: parseDate(e.publishedAt)
},
source: 'youtube'
}
};
ustreamMapFn = function (e) { // this is post-insert from pre-loading ustream results
return {
reference: {
title: e.title,
description: $($.parseHTML(e.description)).text(),
id: e.id,
username: e.username,
currentViewers: e.currentViewers,
thumbnailUrl: e.imageUrl.small,
previewUrl: e.imageUrl.medium,
totalViews: e.totalViews,
userId: e.userId,
creationDate: parseDate(e.createdAt) // TODO: is this a correct way to parse these dates... at all...
},
source: 'ustream'
}
};
bambuserMapFn = function (e) {
return {
reference: {
title: e.title,
id: e.vid,
username: e.username,
currentViewers: e.currentViewers,
totalViews: e.totalViews,
userId: e.owner.uid,
creationDate: new Date(e.created)
},
source: 'bambuser'
}
};
ContextBlock.searchMappings = {
all_streaming_services: {
methodName: 'streamSearchList',
mapFn (e) {
switch (e._source) {
case 'youtube':
return youtubeMapFn(e);
case 'bambuser':
return bambuserMapFn(e);
case 'ustream':
return ustreamMapFn(e);
default:
throw new Meteor.Error('Unknown stream source')
}
}
},
youtube: {
methodName: 'youtubeVideoSearchList',
mapFn: youtubeMapFn
},
bambuser: {
methodName: 'bambuserVideoSearchList',
mapFn: bambuserMapFn
},
ustream: {
methodName: 'ustreamVideoSearchList',
mapFn: ustreamMapFn
},
vimeo: {
methodName: 'vimeoVideoSearchList',
mapFn (e) {
return {
reference: {
title: e.name,
description: e.description,
id: getIdFromUrl(e.uri),
username: e.user.name,
creationDate: parseDate(e.created_time),
previewImage: getIdFromUrl(e.pictures.uri)
}
}
}
},
soundcloud: {
methodName: 'soundcloudAudioSearchList',
mapFn (e) {
return {
reference: {
title: e.title,
description: e.description,
id: e.id,
username: e.channelTitle,
userId: e.user_id,
creationDate: parseDate(e.created_at),
artworkUrl: e.artwork_url
}
}
}
},
twitter: {
methodName: 'twitterSearchList',
mapFn (e) {
var item = {
reference: {
text: e.text,
extendedEntities: e.extended_entities,
retweetedStatus: e.retweeted_status,
entities: e.entities,
id: e.id_str,
username: e.user.name,
screenname: e.user.screen_name,
userPic: e.user.profile_image_url_https,
creationDate: e.created_at.substring(0, 19)
}
};
return item;
}
},
imgur: {
methodName: 'imgurImageSearchList',
mapFn (e) {
return {
reference: {
id: e.id,
username: e.account_url,
userId: e.account_id,
fileExtension: e.link.substring(e.link.lastIndexOf('.') + 1),
title: e.title,
hasMP4: e.mp4 ? true : false,
hasWebM: e.webm ? true : false
}
}
}
},
flickr: {
methodName: 'flickrImageSearchList',
mapFn (e) {
var username, uploadDate, title, lgUrl, lgHeight, lgWidth, flickrSecretOrig, formatOrig;
if (e.media) {
//if single image result
ownername = e.owner.username;
flickrOwnerId = e.owner.nsid;
uploadDate = e.dateuploaded;
title = e.title._content;
} else {
//if search result
ownername = e.ownername;
flickrOwnerId = e.owner;
uploadDate = e.dateupload;
title = e.title;
}
var info = {
reference: {
ownerName: ownername,
flickrOwnerId: flickrOwnerId,
uploadDate: new Date(parseInt(uploadDate) * 1000),
flickrFarm: e.farm,
flickrSecret: e.secret,
id: e.id,
flickrServer: e.server,
title: title
}
};
if(e.originalsecret && e.originalformat){ // check if original is available
_.extend(info.reference, {
flickrSecretOrig: e.originalsecret,
flickrFormatOrig: e.originalformat
})
} else {
// find the largest version of image available
_.each(['z', 'c', 'l', 'h', 'k', 'o'], function(sizeSuffix){
if(e['url_'+ sizeSuffix]){
lgUrl = e['url_'+ sizeSuffix];
lgHeight = e['height_'+ sizeSuffix];
lgWidth = e['width_'+ sizeSuffix];
}
});
if(lgUrl){
_.extend(info.reference, {
lgUrl: lgUrl,
lgHeight: lgHeight,
lgWidth: lgWidth
})
}
}
return info
}
},
cloudinary: {
notSearch: true
},
giphy: {
methodName: 'giphyGifSearchList',
mapFn (e) {
return {
reference: {
id: e.id,
username: e.username,
source: e.source
}
}
}
}
};
Stream = (function (_super) {
__extends(Stream, _super);
function Stream(doc) {
Stream.__super__.constructor.call(this, doc);
this.type = 'stream';
}
Stream.prototype.videoId = function () {
//if (this.source === 'youtube') {
return this.reference.id;
//}
};
Stream.prototype.title = function () {
//if (this.source === 'youtube') {
return this.reference.title;
//}
};
Stream.prototype.createdAtString = function () {
return this.reference.creationDate;
};
Stream.prototype.caption = function () {
//if (this.source === 'youtube') {
return this.reference.description;
//}
};
Stream.prototype.username = function () {
//if (this.source === 'youtube') {
return this.reference.username;
//}
};
Stream.prototype.currentViewers = function () {
if(this.source ==='youtube'){ // TODO get this for each video
return 431;
}
return this.reference.currentViewers;
};
Stream.prototype.totalViews = function () {
if(this.source ==='youtube'){ // TODO get this for each video
return 59274;
}
return this.reference.totalViews;
};
Stream.prototype.creationDate = function () {
if (this.source === 'youtube') {
return this.reference.creationDate
}
};
Stream.prototype.autoplayUrl = function(){
if (this.source === 'bambuser') {
return this.url() + "&autoplay=1";
} else {
return this.url() + "&autoplay=true";
}
};
Stream.prototype.url = function () {
if (this.source === 'youtube') {
return '//www.youtube.com/embed/' + this.reference.id + '?enablejsapi=1&modestbranding=1&rel=0&iv_load_policy=3&autohide=1';
} else if (this.source === 'ustream') {
return 'https://www.ustream.tv/embed/' + this.reference.id + '?v=3&wmode=direct';
} else if (this.source === 'bambuser') {
return '//embed.bambuser.com/broadcast/' + this.reference.id + '?chat=0';
}
};
Stream.prototype.previewUrl = function () {
if (this.source === 'youtube') {
return '//img.youtube.com/vi/' + this.reference.id + '/0.jpg';
} else {
return this.reference.previewUrl;
}
};
Stream.prototype.thumbnailUrl = function () {
if (this.source === 'youtube') {
return '//i.ytimg.com/vi/' + this.reference.id + '/default.jpg';
} else {
return this.reference.thumbnailUrl;
}
};
Stream.prototype.sourceUrl = function () {
if (this.source === 'youtube') {
return 'https://www.youtube.com/watch?v=' + this.reference.id;
} else if (this.source === 'ustream') {
return 'https://www.ustream.tv/channel/' + this.reference.id;
}
};
return Stream;
})(ContextBlock);
VideoBlock = (function (_super) {
__extends(VideoBlock, _super);
function VideoBlock(doc) {
VideoBlock.__super__.constructor.call(this, doc);
this.type = 'video';
if (this.source == null) {
this.source = 'youtube';
}
}
VideoBlock.prototype.title = function () {
if (this.source === 'youtube' || this.source === 'vimeo') {
return this.reference.title
}
};
VideoBlock.prototype.caption = function () {
if (this.source === 'youtube' || this.source === 'vimeo') {
return this.reference.description
}
};
VideoBlock.prototype.username = function () {
if (this.source === 'youtube' || this.source === 'vimeo') {
return this.reference.username
}
};
VideoBlock.prototype.creationDate = function () {
if (this.source === 'youtube' || this.source === 'vimeo') {
return this.reference.creationDate
}
};
VideoBlock.prototype.url = function () {
if (this.source === 'youtube') {
return '//www.youtube.com/embed/' + this.reference.id + '?fs=0&enablejsapi=1';
} else if (this.source === 'vimeo') {
return '//player.vimeo.com/video/' + this.reference.id + '?api=1';
}
};
VideoBlock.prototype.autoplayUrl= function () {
return this.url() + '?autoplay=true'
};
VideoBlock.prototype.previewUrl = function () {
if (this.source === 'youtube') {
return '//img.youtube.com/vi/' + this.reference.id + '/0.jpg';
} else if (this.source === 'vimeo') {
return '//i.vimeocdn.com/video/' + this.reference.previewImage + '_640x359.jpg'
}
};
VideoBlock.prototype.thumbnailUrl = function () {
if (this.source === 'youtube') {
return '//i.ytimg.com/vi/' + this.reference.id + '/default.jpg';
} else if (this.source === 'vimeo') {
return '//i.vimeocdn.com/video/' + this.reference.previewImage + '_100x75.jpg'
}
};
VideoBlock.prototype.anchorMenuSnippet = function () {
return this.reference.title;
};
return VideoBlock;
})(ContextBlock);
AudioBlock = (function (_super) {
__extends(AudioBlock, _super);
function AudioBlock(doc) {
AudioBlock.__super__.constructor.call(this, doc);
this.type = 'audio';
if (this.source == null) {
this.source = 'soundcloud';
}
}
AudioBlock.prototype.title = function () {
return this.reference.title;
};
AudioBlock.prototype.url = function () {
if (this.source === 'soundcloud') {
return '//w.soundcloud.com/player/?url=https://api.soundcloud.com/tracks/' + this.reference.id + '&auto_play=false&buying=false&liking=false&download=false&sharing=false&show_artwork=true&show_comments=false&show_playcount=false&show_user=true&hide_related=true&visual=true'
}
};
AudioBlock.prototype.artworkUrl = function () {
if (this.source === 'soundcloud') {
return this.reference.artworkUrl;
}
};
AudioBlock.prototype.previewUrl = function () {
if (this.source === 'soundcloud') {
if(this.reference.artworkUrl){
return this.reference.artworkUrl.replace(/large\.jpg/, "t500x500.jpg");
} else {
return "https://w1.sndcdn.com/AKjJbbNw4Pz6_m.png"; // TODO something else
}
}
};
AudioBlock.prototype.anchorMenuSnippet = function () {
return this.reference.title;
};
return AudioBlock;
})(ContextBlock);
TwitterBlock = (function (_super) {
__extends(TwitterBlock, _super);
function TwitterBlock(doc) {
TwitterBlock.__super__.constructor.call(this, doc);
this.type = 'twitter';
if (this.source == null) {
this.source = 'twitter';
}
}
TwitterBlock.prototype.userpic = function () {
return this.reference.userPic
};
TwitterBlock.prototype.username = function () {
return this.reference.username
};
TwitterBlock.prototype.screenname = function () {
return this.reference.screenname
};
TwitterBlock.prototype.text = function () {
return this.reference.userPic
};
TwitterBlock.prototype.date = function () {
return this.reference.creationDate
};
TwitterBlock.prototype.tweet_url = function () {
return '//twitter.com/' + this.reference.screenname + '/status/' + this.reference.id
};
TwitterBlock.prototype.user_url = function () {
return '//twitter.com/' + this.reference.screenname
};
TwitterBlock.prototype.twitter_url = function () {
return '//twitter.com/'
};
TwitterBlock.prototype.retweet_action = function () {
return '//twitter.com/intent/retweet?tweet_id=' + this.reference.id
};
TwitterBlock.prototype.reply_action = function () {
return '//twitter.com/intent/tweet?in_reply_to=' + this.reference.id
};
TwitterBlock.prototype.favorite_action = function () {
return '//twitter.com/intent/favorite?tweet_id=' + this.reference.id
};
TwitterBlock.prototype.imgUrl = function () {
var imgUrl;
if (this.extendedEntities) {
imgUrl = this.extendedEntities.media[0].media_url_https;
}
if (this.reference.retweetedStatus) {
if (this.reference.retweetedStatus.entities.media) {
imgUrl = this.reference.retweetedStatus.entities.media[0].media_url
}
} else {
if (this.reference.entities.media) {
imgUrl = this.reference.entities.media[0].media_url
}
}
return imgUrl
};
TwitterBlock.prototype.retweet_url = function () {
return '//twitter.com/' + this.reference.retweetedStatus.user.screen_name
};
TwitterBlock.prototype.retweetUser = function () {
if (this.reference.retweetedStatus) {
return this.reference.retweetedStatus.user.screen_name;
}
};
TwitterBlock.prototype.anchorMenuSnippet = function () {
return this.reference.text;
};
TwitterBlock.prototype.links = function () {
if (this.reference.retweetedStatus) {
var urls = this.reference.retweetedStatus.entities.urls;
} else {
var urls = this.reference.entities.urls;
}
return urls
};
TwitterBlock.prototype.formattedTweet = function () {
var text = this.reference.text; // twttr seems to be escaping appropriately itself
if (this.imgUrl()) {
var imgIndex = text.lastIndexOf("https://") || text.lastIndexOf("http://");
text = text.substring(0, imgIndex);
}
return twttr.txt.autoLink(text, {
urlEntities: this.links(),
targetBlank: true
});
};
return TwitterBlock;
})(ContextBlock);
ImageBlock = (function (_super) {
__extends(ImageBlock, _super);
function ImageBlock(doc) {
ImageBlock.__super__.constructor.call(this, doc);
this.type = 'image';
if (!this.source) { // TO-DO Remove
this.source = 'imgur';
}
};
ImageBlock.prototype.showVideo = function () {
return this.webMUrl() || this.mp4Url();
};
ImageBlock.prototype.webMUrl = function () {
if (this.source === 'imgur' && this.reference.hasWebM) {
return '//i.imgur.com/' + this.reference.id + '.webm';
}
};
ImageBlock.prototype.mp4Url = function () {
if (this.source === 'imgur' && this.reference.hasMP4) {
return '//i.imgur.com/' + this.reference.id + '.mp4';
}
};
ImageBlock.prototype.url = function () {
switch (this.source) {
case 'local':
return '/' + this.reference.id;
case 'link':
return this.reference.url;
case 'imgur':
return '//i.imgur.com/' + this.reference.id + '.' + this.reference.fileExtension;
case 'flickr':
return '//farm' + this.reference.flickrFarm + '.staticflickr.com/' + this.reference.flickrServer + '/' + this.reference.id + '_' + this.reference.flickrSecret + '.jpg'
case 'embedly':
return this.reference.url;
case 'cloudinary':
// TO-DO maybe use jpeg instead of png in certain situations
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_limit,h_300,w_520/' + this.reference.id;
}
};
ImageBlock.prototype.isFlickr = function () {
return (this.source === 'flickr');
};
ImageBlock.prototype.webUrl = function () {
switch (this.source) {
case 'flickr':
if (this.reference.flickrOwnerId) {
return '//www.flickr.com/photos/' + this.reference.flickrOwnerId + '/' + this.reference.id;
} else {
return encodeFlickrUrl(this.reference.id)
}
}
};
ImageBlock.prototype.ownerUrl = function () {
switch (this.source) {
case 'flickr':
if (this.reference.flickrOwnerId) {
return '//www.flickr.com/photos/' + this.reference.flickrOwnerId;
} else {
return this.reference.authorUrl; // from embedly
}
}
};
ImageBlock.prototype.ownerName = function () {
switch (this.source) {
case 'flickr':
return this.reference.ownerName || this.reference.authorName; // author name is from embedly
}
};
ImageBlock.prototype.uploadDate = function () {
switch (this.source) {
case 'flickr':
if (this.reference.uploadDate) {
return this.reference.uploadDate.toDateString();
}
}
};
ImageBlock.prototype.largeUrl = function () {
switch (this.source) {
case 'flickr':
if (this.reference.flickrSecretOrig){ // check for original
return '//farm' + this.reference.flickrFarm + '.staticflickr.com/' + this.reference.flickrServer + '/' + this.reference.id + '_' + this.reference.flickrSecretOrig + '_o.' + this.reference.flickrFormatOrig;
} else if (this.reference.lgUrl){ // check for largest url available
return this.reference.lgUrl
} else { // fallback to size "z"
return '//farm' + this.reference.flickrFarm + '.staticflickr.com/' + this.reference.flickrServer + '/' + this.reference.id + '_' + this.reference.flickrSecret + '_z.jpg';
}
case 'cloudinary':
// TO-DO maybe use jpeg instead of png in certain situations
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/' + this.reference.id;
default:
return this.url();
}
};
ImageBlock.prototype.previewUrl = function () {
switch (this.source) {
case 'local':
return '/' + this.reference.id;
case 'link':
return this.reference.url;
case 'imgur':
if (this.reference.fileExtension === 'gif') {
return '//i.imgur.com/' + this.reference.id + 'l' + '.' + this.reference.fileExtension;
} else {
return '//i.imgur.com/' + this.reference.id + '.' + this.reference.fileExtension;
}
case 'flickr':
return '//farm' + this.reference.flickrFarm + '.staticflickr.com/' + this.reference.flickrServer + '/' + this.reference.id + '_' + this.reference.flickrSecret + '.jpg'
case 'embedly':
return this.reference.url;
case 'cloudinary':
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_limit,h_300,w_520/' + this.reference.id;
}
};
ImageBlock.prototype.thumbnailUrl = function () {
switch (this.source) {
case 'local':
return '/' + this.reference.id;
case 'imgur':
return '//i.imgur.com/' + this.reference.id + 't' + '.' + this.reference.fileExtension;
case 'flickr':
return '//farm' + this.reference.flickrFarm + '.staticflickr.com/' + this.reference.flickrServer + '/' + this.reference.id + '_' + this.reference.flickrSecret + '_t' + '.jpg';
case 'embedly':
return this.reference.thumbnailUrl;
case 'cloudinary':
// f_auto is slightly worse quality but less bandwidth
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/f_auto,c_limit,h_150,w_260/' + this.reference.id;
}
};
ImageBlock.prototype.anchorMenuSnippet = function () {
return this.description || this.reference.title || this.reference.description || this.reference.id;
};
return ImageBlock;
})(ContextBlock);
GifBlock = (function (_super) {
__extends(GifBlock, _super);
function GifBlock(doc) {
GifBlock.__super__.constructor.call(this, doc);
this.type = 'gif';
};
GifBlock.prototype.isGiphy = function () {
return (this.source === 'giphy');
};
GifBlock.prototype.showVideo = function () {
return this.webMUrl() || this.mp4Url();
};
GifBlock.prototype.webMUrl = function () {
if (this.source === 'cloudinary') {
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_limit,h_300,w_520/' + this.reference.id + '.webm';
}
};
GifBlock.prototype.mp4Url = function () {
if (this.source === 'cloudinary') {
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_limit,h_300,w_520/' + this.reference.id + '.mp4';
}
};
GifBlock.prototype.largeUrl = function () {
return this.url(); // don't let gifs get large to preserve bandwidth
};
GifBlock.prototype.url = function () {
switch (this.source) {
case 'giphy':
return '//media4.giphy.com/media/' + this.reference.id + '/giphy.gif';
case 'cloudinary':
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_limit,h_300,w_520/' + this.reference.id;
}
};
GifBlock.prototype.previewUrl = function () {
switch (this.source) {
case 'giphy':
return '//media4.giphy.com/media/' + this.reference.id + '/giphy.gif';
case 'cloudinary':
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_limit,h_300,w_520/' + this.reference.id + '.jpg';
}
};
GifBlock.prototype.thumbnailUrl = function () {
switch (this.source) {
case 'giphy':
return '//media4.giphy.com/media/' + this.reference.id + '/200_d.gif';
case 'cloudinary':
// f_auto is slightly worse quality but less bandwidth
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/f_auto,c_limit,h_150,w_260/' + this.reference.id;
}
};
GifBlock.prototype.anchorMenuSnippet = function () {
return this.description || this.reference.title || this.reference.description || this.reference.id;
};
return GifBlock;
})(ContextBlock);
VizBlock = (function (_super) {
__extends(VizBlock, _super);
function VizBlock(doc) {
VizBlock.__super__.constructor.call(this, doc);
this.type = 'viz';
}
VizBlock.prototype.url = function () {
switch (this.source) {
case 'oec':
return '//atlas.media.mit.edu/en/explore/embed/tree_map/hs/' + this.reference.oecDirection + '/' + this.reference.oecCountry + '/all/show/' + this.reference.oecYear + '/?controls=false&lang=en'
}
};
VizBlock.prototype.linkUrl = function () {
switch (this.source) {
case 'oec':
return '//atlas.media.mit.edu/en/visualize/tree_map/hs/' + this.reference.oecDirection + '/' + this.reference.oecCountry + '/all/show/' + this.reference.oecYear
}
};
VizBlock.countries = [{"id": "ago", "name": "Angola"}, {"id": "bdi", "name": "Burundi"}, {
"id": "ben",
"name": "Benin"
}, {"id": "bfa", "name": "Burkina Faso"}, {"id": "bwa", "name": "Botswana"}, {
"id": "caf",
"name": "Central African Republic"
}, {"id": "civ", "name": "Cote d'Ivoire"}, {"id": "cmr", "name": "Cameroon"}, {
"id": "cod",
"name": "Democratic Republic of the Congo"
}, {"id": "cog", "name": "Republic of the Congo"}, {"id": "com", "name": "Comoros"}, {
"id": "cpv",
"name": "Cape Verde"
}, {"id": "dji", "name": "Djibouti"}, {"id": "dza", "name": "Algeria"}, {"id": "egy", "name": "Egypt"}, {
"id": "eri",
"name": "Eritrea"
}, {"id": "esh", "name": "Western Sahara"}, {"id": "eth", "name": "Ethiopia"}, {
"id": "gab",
"name": "Gabon"
}, {"id": "gha", "name": "Ghana"}, {"id": "gin", "name": "Guinea"}, {"id": "gmb", "name": "Gambia"}, {
"id": "gnb",
"name": "Guinea-Bissau"
}, {"id": "gnq", "name": "Equatorial Guinea"}, {"id": "ken", "name": "Kenya"}, {
"id": "lbr",
"name": "Liberia"
}, {"id": "lby", "name": "Libya"}, {"id": "lso", "name": "Lesotho"}, {"id": "mar", "name": "Morocco"}, {
"id": "mdg",
"name": "Madagascar"
}, {"id": "mli", "name": "Mali"}, {"id": "moz", "name": "Mozambique"}, {
"id": "mrt",
"name": "Mauritania"
}, {"id": "mus", "name": "Mauritius"}, {"id": "mwi", "name": "Malawi"}, {
"id": "myt",
"name": "Mayotte"
}, {"id": "nam", "name": "Namibia"}, {"id": "ner", "name": "Niger"}, {"id": "nga", "name": "Nigeria"}, {
"id": "reu",
"name": "Reunion"
}, {"id": "rwa", "name": "Rwanda"}, {"id": "sdn", "name": "Sudan"}, {"id": "sen", "name": "Senegal"}, {
"id": "shn",
"name": "<NAME>"
}, {"id": "sle", "name": "Sierra Leone"}, {"id": "som", "name": "Somalia"}, {
"id": "ssd",
"name": "South Sudan"
}, {"id": "stp", "name": "Sao Tome and Principe"}, {"id": "swz", "name": "Swaziland"}, {
"id": "syc",
"name": "Seychelles"
}, {"id": "tcd", "name": "Chad"}, {"id": "tgo", "name": "Togo"}, {"id": "tun", "name": "Tunisia"}, {
"id": "tza",
"name": "Tanzania"
}, {"id": "uga", "name": "Uganda"}, {"id": "zaf", "name": "South Africa"}, {
"id": "zmb",
"name": "Zambia"
}, {"id": "zwe", "name": "Zimbabwe"}, {"id": "ata", "name": "Antarctica"}, {
"id": "atf",
"name": "French South Antarctic Territory"
}, {"id": "bvt", "name": "Bouvet Island"}, {"id": "hmd", "name": "Heard Island and McDonald Islands"}, {
"id": "sgs",
"name": "South Georgia South Sandwich Islands"
}, {"id": "afg", "name": "Afghanistan"}, {"id": "are", "name": "United Arab Emirates"}, {
"id": "arm",
"name": "Armenia"
}, {"id": "aze", "name": "Azerbaijan"}, {"id": "bgd", "name": "Bangladesh"}, {
"id": "bhr",
"name": "Bahrain"
}, {"id": "brn", "name": "Brunei"}, {"id": "btn", "name": "Bhutan"}, {
"id": "cck",
"name": "Cocos (Keeling) Islands"
}, {"id": "chn", "name": "China"}, {"id": "cxr", "name": "Christmas Island"}, {
"id": "cyp",
"name": "Cyprus"
}, {"id": "geo", "name": "Georgia"}, {"id": "hkg", "name": "Hong Kong"}, {
"id": "idn",
"name": "Indonesia"
}, {"id": "ind", "name": "India"}, {"id": "iot", "name": "British Indian Ocean Territory"}, {
"id": "irn",
"name": "Iran"
}, {"id": "irq", "name": "Iraq"}, {"id": "isr", "name": "Israel"}, {"id": "jor", "name": "Jordan"}, {
"id": "jpn",
"name": "Japan"
}, {"id": "kaz", "name": "Kazakhstan"}, {"id": "kgz", "name": "Kyrgyzstan"}, {
"id": "khm",
"name": "Cambodia"
}, {"id": "kor", "name": "South Korea"}, {"id": "kwt", "name": "Kuwait"}, {"id": "lao", "name": "Laos"}, {
"id": "lbn",
"name": "Lebanon"
}, {"id": "lka", "name": "<NAME>a"}, {"id": "mac", "name": "Macau"}, {
"id": "mdv",
"name": "Maldives"
}, {"id": "mid", "name": "Midway"}, {"id": "mmr", "name": "Burma"}, {"id": "mng", "name": "Mongolia"}, {
"id": "mys",
"name": "Malaysia"
}, {"id": "npl", "name": "Nepal"}, {"id": "omn", "name": "Oman"}, {"id": "pak", "name": "Pakistan"}, {
"id": "phl",
"name": "Philippines"
}, {"id": "prk", "name": "North Korea"}, {"id": "pse", "name": "Palestine"}, {
"id": "qat",
"name": "Qatar"
}, {"id": "sau", "name": "Saudi Arabia"}, {"id": "sgp", "name": "Singapore"}, {
"id": "syr",
"name": "Syria"
}, {"id": "tha", "name": "Thailand"}, {"id": "tjk", "name": "Tajikistan"}, {
"id": "tkm",
"name": "Turkmenistan"
}, {"id": "tls", "name": "Timor-Leste"}, {"id": "tur", "name": "Turkey"}, {
"id": "twn",
"name": "Taiwan"
}, {"id": "uzb", "name": "Uzbekistan"}, {"id": "vnm", "name": "Vietnam"}, {
"id": "yar",
"name": "Yemen Arab Republic"
}, {"id": "yem", "name": "Yemen"}, {"id": "ymd", "name": "Democratic Yemen"}, {
"id": "alb",
"name": "Albania"
}, {"id": "and", "name": "Andorra"}, {"id": "aut", "name": "Austria"}, {"id": "bel", "name": "Belgium"}, {
"id": "bgr",
"name": "Bulgaria"
}, {"id": "bih", "name": "Bosnia and Herzegovina"}, {"id": "blr", "name": "Belarus"}, {
"id": "blx",
"name": "Belgium-Luxembourg"
}, {"id": "che", "name": "Switzerland"}, {"id": "chi", "name": "Channel Islands"}, {
"id": "csk",
"name": "Czechoslovakia"
}, {"id": "cze", "name": "Czech Republic"}, {"id": "ddr", "name": "Democratic Republic of Germany"}, {
"id": "deu",
"name": "Germany"
}, {"id": "dnk", "name": "Denmark"}, {"id": "esp", "name": "Spain"}, {"id": "est", "name": "Estonia"}, {
"id": "fdr",
"name": "Federal Republic of Germany"
}, {"id": "fin", "name": "Finland"}, {"id": "fra", "name": "France"}, {
"id": "fro",
"name": "Faroe Islands"
}, {"id": "gbr", "name": "United Kingdom"}, {"id": "gib", "name": "Gibraltar"}, {
"id": "grc",
"name": "Greece"
}, {"id": "hrv", "name": "Croatia"}, {"id": "hun", "name": "Hungary"}, {
"id": "imn",
"name": "Isle of Man"
}, {"id": "irl", "name": "Ireland"}, {"id": "isl", "name": "Iceland"}, {"id": "ita", "name": "Italy"}, {
"id": "ksv",
"name": "Kosovo"
}, {"id": "lie", "name": "Liechtenstein"}, {"id": "ltu", "name": "Lithuania"}, {
"id": "lux",
"name": "Luxembourg"
}, {"id": "lva", "name": "Latvia"}, {"id": "mco", "name": "Monaco"}, {"id": "mda", "name": "Moldova"}, {
"id": "mkd",
"name": "Macedonia"
}, {"id": "mlt", "name": "Malta"}, {"id": "mne", "name": "Montenegro"}, {
"id": "nld",
"name": "Netherlands"
}, {"id": "nor", "name": "Norway"}, {"id": "pol", "name": "Poland"}, {"id": "prt", "name": "Portugal"}, {
"id": "rou",
"name": "Romania"
}, {"id": "rus", "name": "Russia"}, {"id": "scg", "name": "Serbia and Montenegro"}, {
"id": "sjm",
"name": "Svalbard"
}, {"id": "smr", "name": "San Marino"}, {"id": "srb", "name": "Serbia"}, {"id": "sun", "name": "USSR"}, {
"id": "svk",
"name": "Slovakia"
}, {"id": "svn", "name": "Slovenia"}, {"id": "swe", "name": "Sweden"}, {"id": "ukr", "name": "Ukraine"}, {
"id": "vat",
"name": "Holy See (Vatican City)"
}, {"id": "yug", "name": "Yugoslavia"}, {"id": "abw", "name": "Aruba"}, {
"id": "aia",
"name": "Anguilla"
}, {"id": "ant", "name": "Netherlands Antilles"}, {"id": "atg", "name": "Antigua and Barbuda"}, {
"id": "bes",
"name": "Bonaire"
}, {"id": "bhs", "name": "Bahamas"}, {"id": "blz", "name": "Belize"}, {"id": "bmu", "name": "Bermuda"}, {
"id": "brb",
"name": "Barbados"
}, {"id": "can", "name": "Canada"}, {"id": "cri", "name": "Costa Rica"}, {"id": "cub", "name": "Cuba"}, {
"id": "cuw",
"name": "Cura\u00e7ao"
}, {"id": "cym", "name": "Cayman Islands"}, {"id": "dma", "name": "Dominica"}, {
"id": "dom",
"name": "Dominican Republic"
}, {"id": "grd", "name": "Grenada"}, {"id": "grl", "name": "Greenland"}, {
"id": "gtm",
"name": "Guatemala"
}, {"id": "hnd", "name": "Honduras"}, {"id": "hti", "name": "Haiti"}, {"id": "jam", "name": "Jamaica"}, {
"id": "kna",
"name": "Saint Kitts and Nevis"
}, {"id": "lca", "name": "<NAME>"}, {"id": "maf", "name": "<NAME>"}, {
"id": "mex",
"name": "Mexico"
}, {"id": "msr", "name": "Montserrat"}, {"id": "mtq", "name": "Martinique"}, {
"id": "naa",
"name": "Netherland Antilles and Aruba"
}, {"id": "nic", "name": "Nicaragua"}, {"id": "pan", "name": "Panama"}, {
"id": "pci",
"name": "Pacific Island (US)"
}, {"id": "pcz", "name": "Panama Canal Zone"}, {"id": "pri", "name": "Puerto Rico"}, {
"id": "slv",
"name": "El Salvador"
}, {"id": "spm", "name": "Saint Pierre and Miquelon"}, {
"id": "tca",
"name": "Turks and Caicos Islands"
}, {"id": "tto", "name": "Trinidad and Tobago"}, {
"id": "umi",
"name": "United States Minor Outlying Islands"
}, {"id": "usa", "name": "United States"}, {"id": "vct", "name": "Saint Vincent and the Grenadines"}, {
"id": "vgb",
"name": "British Virgin Islands"
}, {"id": "vir", "name": "Virgin Islands"}, {"id": "asm", "name": "American Samoa"}, {
"id": "aus",
"name": "Australia"
}, {"id": "cok", "name": "Cook Islands"}, {"id": "fji", "name": "Fiji"}, {
"id": "fsm",
"name": "Micronesia"
}, {"id": "glp", "name": "Guadeloupe"}, {"id": "gum", "name": "Guam"}, {
"id": "kir",
"name": "Kiribati"
}, {"id": "mhl", "name": "Marshall Islands"}, {"id": "mnp", "name": "Northern Mariana Islands"}, {
"id": "ncl",
"name": "New Caledonia"
}, {"id": "nfk", "name": "Norfolk Island"}, {"id": "niu", "name": "Niue"}, {
"id": "nru",
"name": "Nauru"
}, {"id": "nzl", "name": "New Zealand"}, {"id": "pcn", "name": "Pitcairn Islands"}, {
"id": "plw",
"name": "Palau"
}, {"id": "png", "name": "Papua New Guinea"}, {"id": "pyf", "name": "French Polynesia"}, {
"id": "slb",
"name": "Solomon Islands"
}, {"id": "tkl", "name": "Tokelau"}, {"id": "ton", "name": "Tonga"}, {"id": "tuv", "name": "Tuvalu"}, {
"id": "vut",
"name": "Vanuatu"
}, {"id": "wlf", "name": "Wallis and Futuna"}, {"id": "wsm", "name": "Samoa"}, {
"id": "arg",
"name": "Argentina"
}, {"id": "bol", "name": "Bolivia"}, {"id": "bra", "name": "Brazil"}, {"id": "chl", "name": "Chile"}, {
"id": "col",
"name": "Colombia"
}, {"id": "ecu", "name": "Ecuador"}, {"id": "flk", "name": "Falkland Islands"}, {
"id": "guf",
"name": "French Guiana"
}, {"id": "guy", "name": "Guyana"}, {"id": "per", "name": "Peru"}, {"id": "pry", "name": "Paraguay"}, {
"id": "sur",
"name": "Suriname"
}, {"id": "ury", "name": "Uruguay"}, {"id": "ven", "name": "Venezuela"}, {"id": "wld", "name": "World"}, {
"id": "xxa",
"name": "Areas"
}];
VizBlock.prototype.oecCountryName = function () {
switch (this.source) {
case 'oec':
if (this.reference.oecCountry) {
return _.findWhere(VizBlock.countries, {id: this.reference.oecCountry})['name'];
}
}
};
VizBlock.prototype.longSnippet = function () {
switch (this.source) {
case 'oec':
return this.oecCountryName() + " " + this.reference.oecDirection + "s in " + this.reference.oecYear;
}
};
VizBlock.prototype.anchorMenuSnippet = function () {
switch (this.source) {
case 'oec':
return this.oecCountryName() + " (" + this.reference.oecYear + ")";
}
};
return VizBlock;
})(ContextBlock);
MapBlock = (function (_super) {
__extends(MapBlock, _super);
function MapBlock(doc) {
MapBlock.__super__.constructor.call(this, doc);
this.type = 'map';
if (this.source == null) {
this.source = 'google_maps';
}
}
MapBlock.prototype.longSnippet = function () {
return this.reference.mapQuery;
};
MapBlock.prototype.anchorMenuSnippet = function () {
return this.reference.mapQuery;
};
MapBlock.prototype.escape = function (value) {
return encodeURIComponent(value).replace(/%20/g, "+");
};
MapBlock.prototype.url = function () {
if (this.source === 'google_maps') {
return 'https://www.google.com/maps/embed/v1/place?' + 'key=' + GOOGLE_API_CLIENT_KEY + '&q=' + this.escape(this.reference.mapQuery) + '&maptype=' + this.escape(this.reference.mapType);
}
};
MapBlock.prototype.previewUrl = function (height, width) {
height = height || 300;
width = width || 520;
if (this.source === 'google_maps') {
return 'https://maps.googleapis.com/maps/api/staticmap?' + 'key=' + GOOGLE_API_CLIENT_KEY + '¢er=' + this.escape(this.reference.mapQuery) + '&maptype=' + this.escape(this.reference.mapType) + '&size=' + width + 'x' + height + '&markers=color:red|' + this.escape(this.reference.mapQuery);
}
};
return MapBlock;
})(ContextBlock);
TextBlock = (function (_super) {
__extends(TextBlock, _super);
function TextBlock(doc) {
TextBlock.__super__.constructor.call(this, doc);
this.type = 'text';
if (!this.source) {
this.source = 'plaintext';
}
}
TextBlock.prototype.longSnippet = function () {
var maxLength;
maxLength = 40;
if (this.content.length <= maxLength) {
return this.content;
} else {
return this.content.slice(0, maxLength) + '...';
}
};
TextBlock.prototype.anchorMenuSnippet = function () {
return this.content;
};
return TextBlock;
})(ContextBlock);
LinkBlock = (function (_super) {
__extends(LinkBlock, _super);
function LinkBlock(doc) {
LinkBlock.__super__.constructor.call(this, doc);
this.type = 'link';
if(!this.override){
this.override = {}; // if needed in more type, probably put this in ContextBlock, or the schema and migrate
}
}
LinkBlock.prototype.title = function () {
return this.override.title ||this.reference.title || this.reference.originalUrl;
};
LinkBlock.prototype.linkDescription = function () {
return this.override.description || this.reference.description || '';
};
LinkBlock.prototype.thumbnailOverride = function () {
return this.override.thumbnailId ? true : false;
};
LinkBlock.prototype.thumbnailOverrideUrl = function () {
if(this.thumbnailOverride()){
var url;
if(this.imageOnLeft()){
url = '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_lfill,g_center,h_130,w_130/' + this.override.thumbnailId;
} else {
url = '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_lfill,g_center,h_130,w_520/' + this.override.thumbnailId;
}
if(this.override.thumbnailFileExtension === 'gif'){
url += '.jpg'
}
return url
}
};
LinkBlock.prototype.thumbnailUrl = function () {
return this.thumbnailOverrideUrl() || this.reference.thumbnailUrl || this.thumbnailFallback() || '//res.cloudinary.com/fold/image/upload/v1/static/LINK_SQUARE.svg';
};
LinkBlock.prototype.thumbnailFallback = function () {
if(!this.reference.thumbnailFallback){
return
}
var maxWidth = 2048; // make it like the header images
var maxHeight = 350; // make it like the header images
var atmosphereMap = {
1: "SAUCERS",
2: "OCEAN",
3: "FLOWERS",
4: "BUILDING",
5: "LIGHTNING",
6: "DANCER",
7: "CUBES",
8: "COMPUTER",
9: "MARSH",
10: "RINGS",
11: "MOTH",
12: "MOUNTAINS",
13: "AERIAL"
};
var atmosphereName = atmosphereMap[this.reference.thumbnailFallback];
if (!atmosphereName){
Meteor.defer(function(){
throw new Meteor.Error('Header atmosphere not found');
})
}
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_lfill,g_north,h_' + maxHeight + ',w_' + maxWidth + '/static/header_atmosphere_' + atmosphereName
};
LinkBlock.prototype.imageOnLeft = function () {
if (this.thumbnailOverride()) {
return (this.override.thumbnailWidth / this.override.thumbnailHeight) <= 1.25;
} else if (this.reference.thumbnailUrl) {
return (this.reference.thumbnailWidth / this.reference.thumbnailHeight) <= 1.25;
} else {
return true
}
};
LinkBlock.prototype.url = function () {
return this.reference.url || this.reference.originalUrl;
};
LinkBlock.prototype.providerUrl = function () {
return this.reference.providerUrl;
};
LinkBlock.prototype.providerTruncatedUrl = function () {
return this.reference.providerUrl.replace(/(https?:\/\/)?(www\.)?/, "");
};
LinkBlock.prototype.anchorMenuSnippet = function () {
return this.title();
};
return LinkBlock;
})(ContextBlock);
NewsBlock = (function (_super) {
__extends(NewsBlock, _super);
function NewsBlock(doc) {
NewsBlock.__super__.constructor.call(this, doc);
this.type = 'news';
}
NewsBlock.prototype.title = function () {
return this.reference.title || this.reference.originalUrl;
};
NewsBlock.prototype.introduction = function () {
return this.reference.description || '';
};
NewsBlock.prototype.html = function () {
return this.reference.content;
};
NewsBlock.prototype.headerImageUrl = function () {
return this.reference.topImage ? this.reference.topImage.url : null;
};
NewsBlock.prototype.providerName = function () {
return this.reference.providerName;
};
NewsBlock.prototype.providerIconUrl= function () {
return this.reference.providerIconUrl;
};
//
//NewsBlock.prototype.imageOnLeft = function () {
// return !this.reference.thumbnailUrl || (this.reference.thumbnailWidth / this.reference.thumbnailHeight) <= 1.25;
//};
NewsBlock.prototype.url = function () {
return this.reference.url || this.reference.originalUrl;
};
NewsBlock.prototype.providerUrl = function () {
return this.reference.providerUrl;
};
NewsBlock.prototype.providerTruncatedUrl = function () {
return this.reference.providerUrl.replace(/(https?:\/\/)?(www\.)?/, "");
};
NewsBlock.prototype.anchorMenuSnippet = function () {
return this.title();
};
return NewsBlock;
})(ContextBlock);
ActionBlock = (function (_super) {
__extends(ActionBlock, _super);
function ActionBlock(doc) {
ActionBlock.__super__.constructor.call(this, doc);
this.type = 'action';
}
ActionBlock.prototype.title = function () {
return this.reference.title;
};
ActionBlock.prototype.actionDescription = function () {
return this.reference.description || '';
};
ActionBlock.prototype.thumbnailUrl = function () {
if(!this.override.thumbnailId){
return
}
var url;
url = '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/c_lfill,g_center,h_130,w_520/' + this.override.thumbnailId;
if(this.override.thumbnailFileExtension === 'gif'){
url += '.jpg'
}
return url
};
ActionBlock.prototype.actionButtonText = function () {
return this.reference.buttonText;
};
ActionBlock.prototype.actionButtonUrl = function () {
return this.reference.buttonUrl;
};
ActionBlock.prototype.anchorMenuSnippet = function () {
return this.title();
};
return ActionBlock;
})(ContextBlock);
Schema.ContextReferenceProfile = new SimpleSchema({
id: {
type: String,
optional: true
},
creationDate: {
type: String,
optional: true
},
username: {
type: String,
optional: true
},
userId: {
type: String,
optional: true
},
source: {
type: String,
optional: true
},
artworkUrl: {
type: String,
optional: true
},
previewImage: {
type: String,
optional: true
},
title: {
type: String,
optional: true,
defaultValue: ''
},
description: {
type: String,
optional: true,
defaultValue: ''
},
fileExtension: {
type: String,
optional: true
},
// Image
flickrOwnerId: {
type: String,
optional: true
},
flickrFarm: {
type: String,
optional: true
},
flickrSecret: {
type: String,
optional: true
},
flickrServer: {
type: String,
optional: true
},
flickrSecretOrig: {
type: String,
optional: true
},
flickrFormatOrig: {
type: String,
optional: true
},
lgUrl: {
type: String,
optional: true
},
lgHeight: {
type: String,
optional: true
},
lgWidth: {
type: String,
optional: true
},
uploadDate: {
type: Date,
optional: true
},
ownerName: {
type: String,
optional: true
},
hasWebM: {
type: Boolean,
optional: true
},
hasMP4: {
type: Boolean,
optional: true
},
// Image upload
width: {
type: Number,
optional: true
},
height: {
type: Number,
optional: true
},
// twitter
retweet: {
type: String,
optional: true
},
creationDate: {
type: String,
optional: true
},
username: {
type: String,
optional: true
},
screenname: {
type: String,
optional: true
},
userId: {
type: String,
optional: true
},
userPic: {
type: String,
optional: true
},
text: {
type: String,
optional: true
},
entities: {
type: Object,
optional: true,
blackbox: true
},
extendedEntities: {
type: Object,
optional: true,
blackbox: true
},
retweetedStatus: {
type: Object,
optional: true,
blackbox: true
},
// Link
title: { type: String, optional: true },
thumbnailUrl: { type: String, optional: true },
thumbnailFallback: { type: String, optional: true },
url: { type: String, optional: true },
originalUrl: { type: String, optional: true },
providerName: { type: String, optional: true },
providerUrl: { type: String, optional: true },
authorUrl: { type: String, optional: true },
authorName: { type: String, optional: true },
thumbnailHeight: { type: Number, optional: true },
thumbnailWidth: { type: Number, optional: true },
embedlyType: { type: String, optional: true },
imageOnLeft: { type: Boolean, optional: true },
// Rich or Extract
html: { type: String, optional: true },
// OEC
oecYear: {
type: String,
optional: true
},
oecCountry: {
type: String,
optional: true
},
oecDirection: {
type: String,
optional: true
},
mapQuery: {
type: String,
optional: true
},
mapType: {
type: String,
allowedValues: ['roadmap', 'satellite'],
optional: true,
autoform: {
afFieldInput: {
firstOption: false,
options: 'allowed'
}
}
},
// link override
thumbnailId: {
type: String,
optional: true
},
thumbnailFileExtension: {
type: String,
optional: true
},
// Action
buttonText: { type: String, optional: true },
buttonUrl: { type: String, optional: true },
});
Schema.ContextBlocks = new SimpleSchema({
storyId: {
type: String
},
storyShortId: {
type: String
},
authorId: {
type: String
},
type: {
type: String
},
source: {
type: String,
optional: true
},
fromEmbedly: {
type: Boolean,
optional: true
},
version: {
type: String,
optional: true
},
savedAt: {
type: Date,
optional: true
},
publishedAt: {
type: Date,
optional: true
},
createdAt: {
type: Date,
autoValue () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {$setOnInsert: new Date};
} else {
this.unset();
}
},
optional: true // optional because only added this fieldjust before launch
},
fullDetails: {
type: Object,
optional: true,
blackbox: true
},
description: {
type: String,
optional: true
},
content: {
type: String,
trim: false,
label: " ",
optional: true,
autoform: {
afFieldInput: {
type: "textarea",
rows: 10,
"class": "text-input"
}
}
},
published: {
type: Boolean,
defaultValue: false
},
everPublished: {
type: Boolean,
defaultValue: false
},
reference: {
type: Schema.ContextReferenceProfile,
optional: true
},
override: {
type: Schema.ContextReferenceProfile,
optional: true
},
searchQuery: {
type:String,
optional:true
},
searchOption: {
type: String,
optional:true
}
});
ContextBlocks.attachSchema(Schema.ContextBlocks);
var verticalSectionSchema = new SimpleSchema({
'_id': {
type: String
},
'title': {
type: String,
optional: true
},
'hasTitle': {
type: Boolean,
optional: true,
defaultValue: false
},
'content': {
type: String,
trim: false
},
'contextBlocks': {
type: [String],
defaultValue: []
}
});
var sharedStorySchema = function(options) {
options = options || {};
return {
headerImageFormat: {
type: String,
optional: true
},
headerImageAttribution: {
type: String,
optional: true
},
headerImage: {
type: String,
optional: true,
autoValue () {
if(options.draft){
if (this.isSet) {
return this.value;
} else {
return this.unset();
}
}
var placeholderNumber = _.random(1,13).toString();
if (this.isSet) {
return this.value;
} else if (this.isInsert) {
return placeholderNumber;
} else if (this.isUpsert) {
return {$setOnInsert: placeholderNumber};
} else {
this.unset();
}
}
},
storyPathSegment: {
type: String
},
title: {
type: String,
defaultValue: ''
},
keywords:{
type: [String],
defaultValue: []
},
narrativeRightsReserved: {
type: Boolean,
optional: true
},
verticalSections: {
type: [verticalSectionSchema],
minCount: 1,
maxCount: 1000
}
}
};
var draftStorySchema = new SimpleSchema(sharedStorySchema({draft: true}));
var analyticsSchema = new SimpleSchema({
byConnection: {
type: Number,
defaultValue: 0
},
byIP: {
type: Number,
defaultValue: 0
},
byId: {
type: Number,
defaultValue: 0
},
total: {
type: Number,
defaultValue: 0
}
});
Schema.Stories = new SimpleSchema(_.extend({}, sharedStorySchema(), {
shortId: {
type: String
},
savedAt: {
type: Date
},
createdAt: {
type: Date,
autoValue () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {$setOnInsert: new Date};
} else {
this.unset();
}
}
},
'r': { // relevancy for published stories. determines order of results on homepage
type: Date,
optional: true
},
publishedAt: {
type: Date,
optional: true
},
firstPublishedAt: {
type: Date,
optional: true
},
published: {
type: Boolean,
defaultValue: false
},
everPublished: {
type: Boolean,
defaultValue: false
},
userPathSegment: {
type: String
},
authorId: {
type: String
},
authorName: {
type: String
},
authorUsername: {
type: String
},
authorDisplayUsername: {
type: String,
optional: true
},
deleted: {
type: Boolean,
defaultValue: false
},
deletedAt: {
type: Date,
optional: true
},
favorited: {
type: [String],
defaultValue: []
},
favoritedTotal: {
type: Number,
defaultValue: 0
},
editorsPick: {
type: Boolean,
optional: true
},
editorsPickAt: {
type: Date,
optional: true
},
analytics: {
type: Object
},
'analytics.views': {
type: analyticsSchema
},
'analytics.shares': {
type: analyticsSchema
},
'analytics.reads': {
type: analyticsSchema
},
'analytics.heartbeats': {
type: Object,
optional: true
},
'analytics.heartbeats.active': {
type: Object,
optional: true,
blackbox: true
},
'analytics.contextInteractions': {
type: Object,
optional: true,
blackbox: true
},
'analytics.anchorClicks': {
type: Object,
optional: true,
blackbox: true
},
contextBlocks: {
type: [ContextBlock], // TODO this should really be Schema.ContextBlocks, but would need to be converted to a regular object, otherwise simple-schema complains
minCount: 0,
maxCount: 1000,
defaultValue: []
},
contextBlockIds: {
type: [String],
minCount: 0,
maxCount: 1000,
defaultValue: []
},
contextBlockTypeCount:{
type: Object,
optional: true,
blackbox: true
},
narrativeBlockCount:{
type: Number,
optional: true
},
draftStory: {
type: draftStorySchema
},
'version': {
type: String,
optional: true
}
})
);
this.Stories.attachSchema(Schema.Stories);
this.StoryStats = new Mongo.Collection("story_stats");
this.StoryStats.deny({
insert () {
return true;
},
update () {
return true
},
remove () {
return true
}
});
var deepAnalyticsSchema = new SimpleSchema({
uniqueViewersByConnection: {
type: [String],
defaultValue: []
},
uniqueViewersByIP: {
type: [String],
defaultValue: []
},
uniqueViewersByUserId: {
type: [String],
defaultValue: []
},
all: {
type: [Object],
blackbox: true
}
});
Schema.StoryStats = new SimpleSchema({
storyId: {
type: String
},
deepAnalytics: {
type: Object,
optional: true
},
'deepAnalytics.views': {
type: deepAnalyticsSchema
},
'deepAnalytics.shares': {
type: deepAnalyticsSchema
},
'deepAnalytics.reads': {
type: deepAnalyticsSchema
},
analytics: {
type: analyticsSchema,
optional: true
},
'analytics.views': {
type: analyticsSchema
},
'analytics.shares': {
type: analyticsSchema
},
'analytics.reads': {
type: analyticsSchema
},
'analytics.heartbeats': {
type: Object,
optional: true
},
'analytics.heartbeats.active': {
type: Object,
optional: true,
blackbox: true
},
'analytics.contextInteractions': {
type: Object,
optional: true,
blackbox: true
},
'analytics.anchorClicks': {
type: Object,
optional: true,
blackbox: true
},
});
this.StoryStats.attachSchema(Schema.StoryStats);
this.StoryHistories = new Mongo.Collection("story_histories");
this.Activities = new Mongo.Collection("activities");
var basicObjectSchema = {
type: {
type: String,
allowedValues: ['Person', 'Story', 'ContextCard']
},
id: {
type: String
},
name: {
type: String
},
urlPath: {
type: String
},
imageId: {
type: String,
optional: true
},
twitterId: {
type: String,
optional: true
}
};
var objectSchema = new SimpleSchema(_.extend( basicObjectSchema, {
attributedTo: {
type: new SimpleSchema(basicObjectSchema),
optional: true
}
})
);
Schema.Activities = new SimpleSchema({
type: { // follow, favorite etc...
type: String,
allowedValues: ['Favorite', 'Follow', 'FollowBack', 'Publish', 'Share', 'ViewThreshold']
},
content: { // for ex., message contents
type: String,
optional: true
},
published: { // when this happened
type: Date,
autoValue () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {$setOnInsert: new Date};
} else {
this.unset();
}
}
},
fanout: { // fanout status
type: String,
defaultValue: 'pending',
allowedValues: ['pending', 'in_progress', 'done']
},
actor: {
type: objectSchema,
optional: true
},
object: {
type: objectSchema,
optional: true
},
//target: {
// type: objectSchema,
// optional: true
//}
});
this.Activities.attachSchema(Schema.Activities);
this.ActivityFeedItems = new Mongo.Collection("activity_feed_items");
Schema.ActivityFeedItems = new SimpleSchema({
uId: { // userId
type: String
},
aId: { // actionId
type: String
},
r: { // relevancy
type: Date
}
});
this.ActivityFeedItems.attachSchema(Schema.ActivityFeedItems);
<|start_filename|>client/activity-feed.js<|end_filename|>
ActivityItems = new Mongo.Collection(null);
var activityFeedItemsSub;
var activityFeedSubs = new SubsManager({
cacheLimit: 1,
expireIn: 99999
});
var subscribeToActivityFeedItems = function(cb){
if(!activityFeedItemsSub){
activityFeedItemsSub = activityFeedSubs.subscribe("activityFeedItemsPub", function(){
if(cb){
cb();
}
})
} else {
if(cb){
cb();
}
}
};
var loadedActivities;
var loadedActivitiesDep = new Tracker.Dependency();
var loadInitialActivities = function(cb) {
if (!loadedActivities) { // only load if haven't loaded
Meteor.call('getActivityFeed', function (err, feedItems) {
if (err) {
throw err
}
loadedActivities = _.pluck(feedItems, '_id');
loadedActivitiesDep.changed();
_.each(feedItems, function (feedItem) {
ActivityItems.insert(feedItem);
});
cb(null, loadedActivities);
});
} else {
loadedActivities = ActivityItems.find({}).map(function (a) {
return a._id
});
loadedActivitiesDep.changed();
cb(null, loadedActivities)
}
};
Template.activity_feed.onCreated(function(){
this.activityFeedLoading = new ReactiveVar(true);
loadInitialActivities((err, loadedActivities) => {
this.activityFeedLoading.set(false);
subscribeToActivityFeedItems(() => {
var query = ActivityFeedItems.find({uId: Meteor.userId()}, {sort:{r: -1}, fields: {'aId' : 1}});
if(this.activityFeedObserver){
this.activityFeedObserver.stop();
}
this.activityFeedObserver = query.observeChanges({
added (id, aFI) {
if (!_.contains(loadedActivities, aFI.aId)) {
Meteor.call('getActivityFeed', aFI.aId, (err, feedItems) => {
if (err) {
throw err
}
loadedActivities.push(aFI.aId);
_.each(feedItems, function (feedItem) {
ActivityItems.insert(feedItem);
})
});
}
}
})
})
})
});
Template.activity_feed.onDestroyed(function(){
unfreezePageScroll();
if(this.activityFeedObserver){
this.activityFeedObserver.stop();
}
});
Template.activity_feed.events({
'mouseenter .activity-feed' () {
freezePageScroll();
},
'mouseleave .activity-feed' (){
unfreezePageScroll();
}
});
var feedLimit = Meteor.Device.isPhone() ? 5 : 50;
Template.activity_feed.helpers({
populatedFeedItems (){
return ActivityItems.find({}, {sort: {published: -1}, limit: feedLimit});
},
loading (){
return Template.instance().activityFeedLoading.get();
},
hideContent (){
loadedActivitiesDep.depend();
return loadedActivities ? false : true;
}
});
Template._activity_feed_content.helpers({
image (){
if(this.type === 'Person'){
return getProfileImage(this.imageId, this.twitterId, 'small');
} else if (this.type === 'Story'){
return Story.getHeaderImageUrl(this.imageId, 'small');
}
},
imageClass (){
return this.type.toLowerCase() + '-preview-image';
},
objectIsYou (){
return this.object.id === Meteor.userId();
},
includeBaselineActivityFeedContent (){
return Template.instance().data.activities.count() <= (feedLimit - 3);
},
activityPlaceholders (){
if(Meteor.Device.isPhone()){
return 0;
}
var numPlaceholders;
var numActivities = Template.instance().data.activities.count();
if (numActivities <= 3 ) {
numPlaceholders = 5 - numActivities;
} else {
numPlaceholders = 0;
}
return _.range(numPlaceholders);
},
hasButton (){
return _.contains(['Follow', 'FollowBack'], this.type);
},
noRightImage (){
return _.contains(['Share'], this.type);
}
});
<|start_filename|>client/lib/devices.js<|end_filename|>
Meteor.Device.emptyUserAgentDeviceName = 'bot';
Meteor.Device.botUserAgentDeviceName = 'bot';
Meteor.Device.unknownUserAgentDeviceType = 'bot';
// Don't forget to re-detect the device!
Meteor.Device.detectDevice();
<|start_filename|>lib/helpers.js<|end_filename|>
newTypeSpecificContextBlock = function (doc) {
switch (doc.type) {
case 'stream':
return new Stream(doc);
case 'video':
return new VideoBlock(doc);
case 'text':
return new TextBlock(doc);
case 'map':
return new MapBlock(doc);
case 'image':
return new ImageBlock(doc);
case 'gif':
return new GifBlock(doc);
case 'audio':
return new AudioBlock(doc);
case 'viz':
return new VizBlock(doc);
case 'twitter':
return new TwitterBlock(doc);
case 'link':
return new LinkBlock(doc);
case 'news':
return new NewsBlock(doc);
case 'action':
return new ActionBlock(doc);
default:
return new ContextBlock(doc);
}
};
idFromPathSegment = function(pathSegment) { // everything after last dash
return pathSegment.substring(pathSegment.lastIndexOf('-') + 1);
};
sum = function(a,b){ return a+b; };
if(Meteor.isServer){
import cheerio from 'cheerio';
}
getProfileImage = function(profilePicture, twitterId, size, forEmail){
var diameter;
if (size === 'large'){
diameter = 150;
} else {
diameter = 60;
}
var defaultProfilePic = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; // transparent gif
var dprSetting = ((typeof window == 'undefined') || window.isHighDensity) ? ',dpr_2.0' : '';
var twitterPic;
if (twitterId) {
twitterPic = '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/twitter/w_' + diameter + ',h_' + diameter + ',c_fill,g_face' + dprSetting + '/' + twitterId
}
if (profilePicture || twitterId) {
if ( profilePicture) {
if ( profilePicture < 20) { // it's a monster
if (twitterPic){
return twitterPic
} else { // show monster
if(forEmail){
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/w_' + diameter + ',h_' + diameter + dprSetting + '/static/profile_monster_' + profilePicture + '.png';
} else {
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/static/profile_monster_' + profilePicture + '.svg';
}
}
} else {
return '//res.cloudinary.com/' + Meteor.settings['public'].CLOUDINARY_CLOUD_NAME + '/image/upload/w_' + diameter + ',h_' + diameter + ',c_fill,g_face' + dprSetting + '/' + profilePicture
}
} else if (twitterPic) {
return twitterPic
}
}
// if nothing else served up
return defaultProfilePic
}
<|start_filename|>client/lib/reload.js<|end_filename|>
window.readyToMigrate = new ReactiveVar(false);
var reloadDelay = Meteor.settings['public'].NODE_ENV === 'development' ? 0 : 2000;
Reload._onMigrate('fold', function (retry) {
if (readyToMigrate.get()) {
return [true, {codeReloaded: true}];
} else {
//if (Router.current().route.getName() === 'edit') {
if (Meteor.settings['public'].NODE_ENV !== 'development') {
notifyDeploy("We've just made an improvement! Click here to sync up the latest code.", true);
trackEvent('Reload notification happened', {label: 'Reload on click'});
$('.migration-notification').click(function () {
saveCallback(null, true);
setTimeout(function () {
readyToMigrate.set(true);
retry();
}, 300);
});
Router.onRun(function () {
readyToMigrate.set(true);
retry();
});
return [false];
} else {
notifyDeploy("We've made an improvement! Wait just a moment while we sync up the latest code.", false);
trackEvent('Reload notification happened', {label: 'Immediate reload', nonInteraction: 1});
setTimeout(function () {
readyToMigrate.set(true);
retry();
}, reloadDelay);
return [false]
}
}
});
var migrationData = Reload._migrationData('fold');
if (migrationData){
window.codeReloaded = migrationData.codeReloaded;
}
<|start_filename|>server/settings.js<|end_filename|>
// get segment key to the client, while allowing it to be set from environment variable
// NOTE: this hack may not be 100% reliable (for ex when initially deploy won't update clients)
if (process.env.GA_TRACKING_KEY){
Meteor.settings['public'].GA_TRACKING_KEY = process.env.GA_TRACKING_KEY;
}
if (process.env.NODE_ENV){
Meteor.settings['public'].NODE_ENV = process.env.NODE_ENV;
}
// SMTP Config
smtp = {
username: Meteor.settings.SMTP_USERNAME,
password: Meteor.settings.SMTP_API_KEY,
server: Meteor.settings.SMTP_SERVER,
port: Meteor.settings.SMTP_PORT
};
process.env.MAIL_URL = 'smtp://' + encodeURIComponent(smtp.username) + ':' + encodeURIComponent(smtp.password) + '@' + encodeURIComponent(smtp.server) + ':' + smtp.port;
Mandrill.config({
key: Meteor.settings.MANDRILL_API_KEY // get your Mandrill key from https://mandrillapp.com/settings/index
});
if (Meteor.settings.CLOUDINARY_API_SECRET){
Cloudinary.config({
cloud_name: Meteor.settings['public'].CLOUDINARY_CLOUD_NAME,
api_key: Meteor.settings.CLOUDINARY_API_KEY,
api_secret: Meteor.settings.CLOUDINARY_API_SECRET
});
};
<|start_filename|>server/search.js<|end_filename|>
SearchSource.defineSource('stories', function(searchText, options) {
options = options || {};
_.defaults(options, {
page: 0
});
var findOptions = {
sort: [
["editorsPickAt", "desc"],
["favoritedTotal", "desc"],
["savedAt", "desc"]
],
limit: PUB_SIZE * (options.page + 1),
fields: previewStoryFields
};
if(searchText) {
var regExp = buildRegExp(searchText);
var selector = {$or: [{title: regExp},{ keywords: regExp},{ authorName: regExp},{ authorDisplayUsername: regExp}],
published: true
};
return Stories.find(selector, findOptions).fetch();
} else {
return []
}
});
SearchSource.defineSource('people', function(searchText, options) {
options = options || {};
_.defaults(options, {
page: 0
});
var findOptions = {
sort: [
["followersTotal", "desc"],
["followingTotal", "desc"],
["favoritesTotal", "desc"],
["createdAt", "desc"]
],
limit: 3 * (options.page + 1),
fields: minimalUserFields
};
if(searchText) {
var regExp = buildRegExp(searchText);
var selector = {
username: {$exists: true},
$or: [{username: regExp},{ 'profile.name': regExp}]
};
return Meteor.users.find(selector, findOptions).fetch();
} else {
return []
}
});
function buildRegExp(searchText) {
var words = searchText.trim().split(/[ \-\:]+/);
var exps = _.map(words, function(word) {
return "(?=.*" + word + ")";
});
var fullExp = exps.join('') + ".+";
return new RegExp(fullExp, "i");
}
<|start_filename|>client/home.js<|end_filename|>
var formatDate, weekDays, formatDateNice, monthNames;
weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
// Friday 2/20/2015 20:29:22
formatDate = function(date) {
var hms;
hms = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
return weekDays[date.getDay()] + " " + date.getMonth() + "/" + date.getDate() + "/" + date.getFullYear() + " " + hms;
};
// February 7th, 2015
formatDateNice = function(date) {
var hms;
hms = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
return monthNames[(date.getMonth())] + " " + date.getDate() + ", " + date.getFullYear();
};
var filters = ['mixed', 'curated', 'trending', 'starred', 'newest'];
Session.setDefault('filterValue', filters[0]); // this must correspond to the first thing in the dropdown
Template.home.helpers({
user () {
return Meteor.user();
},
filter () {
return Session.get("filter");
}
});
Template.home.events({
"click .logo-title a" (e, t) {
// reset search query
Session.set('storySearchQuery', null);
// reset filter
Session.set('filterValue', filters[0]);
t.$("select.filters-select").val(filters[0]);
t.$("select.filters-select").selectOrDie("update");
}
});
Template.top_banner.helpers({
showingFeed () {
return Session.equals('filterValue', 'mixed') && !Session.get('storySearchQuery');
},
showingLatest () {
return Session.equals('filterValue', 'newest') && !Session.get('storySearchQuery');
},
altSlim (){
return Template.instance().data && (Template.instance().data.slim || Meteor.Device.isPhone()) && hiddenContextMode()
}
});
Template.top_banner.events({
"click .show-newest" (e, t) {
Meteor.defer(() => {
Session.set('filterValue', 'newest');
Session.set('storySearchQuery', null);
});
// do this so the ui is snappy
t.$('.newest-toggle button').prop("disabled", "");
t.$("input").val(null);
t.$(".clear-search").hide();
$(e.target).prop("disabled", "disabled");
},
"click .show-feed" (e, t) {
Meteor.defer(() => {
Session.set('filterValue', 'mixed');
Session.set('storySearchQuery', null);
});
// do this so the ui is snappy
t.$('.newest-toggle button').prop("disabled", "");
t.$("input").val(null);
t.$(".clear-search").hide();
$(e.target).prop("disabled", "disabled");
},
"click .alt-signup-button" (d) {
openSignInOverlay();
},
"click .alt-search-button" () {
openSearchOverlay();
},
"click .alt-menu-button" () {
openMenuOverlay();
}
});
Template.search.onCreated(function() {
this.autorun(function(){
if(!Session.get('storySearchQuery')){
$("input").val(null);
}
})
});
Template.search.onRendered(function() {
if(this.data && this.data.slim){
this.$("button").hide(); // hack to hide button
} else {
var storySearchQuery;
if(storySearchQuery = Session.get('storySearchQuery')){
this.$("input").val(storySearchQuery);
}
}
});
Template.search.helpers({
showClearSearch (){
return Session.get('storySearchQuery');
}
});
Template.search.events({
'click .clear-search' (e, t){
// this is the business logic
Meteor.defer(function(){
return Session.set('storySearchQuery', null);
});
// do this so the ui is snappy
t.$("input").val(null);
t.$("button").hide();
},
'keydown' (e, t){
if(t.data.slim){
t.$("button").show(); // compensate for hack from above
}
}
});
Template.filters.onRendered(function() {
var options = {};
if(this.data.slim){
options.placeholder = "Explore";
} else {
var filterValue;
if(filterValue = Session.get('filterValue')){
$("select").val(filterValue);
}
}
$("select").selectOrDie(options);
});
Template.filters.helpers({
filters () {
return _.map(filters, function(filter){
return {
value: filter,
label: filter === 'curated' ? 'FOLD Picks' : _s.capitalize(filter)
}
})
},
conditionallySelected (){
return Session.equals('filterValue', this.toString()) ? 'selected' : '';
}
});
Template.filters.events({
"change select" (e, t) {
var filterValue = $(e.target).val();
Session.set('filterValue', filterValue);
Session.set('storySearchQuery', null);
if(t.data.slim){
Router.go('/');
}
trackEvent('Select filter', {
label: filterValue
});
}
});
Template.search.events({
"submit" (e, t){
e.preventDefault();
},
"keyup input": _.throttle(function(e, t) {
var text = $(e.target).val().trim();
if(enterPress(e)){
$(e.target).blur();
closeSearchOverlay();
if(t.data.slim){
Router.go('/');
}
}
if(!Session.get('searchOverlayShown')){
Session.set('storySearchQuery', text);
}
if(!t.data.slim){
$('html, body').scrollTop(0);
}
}, 200, {leading: false})
});
var curatedStoriesSub,
trendingStoriesSub,
newestStoriesSub,
starredStoriesSub;
var getSubscriptionPage = function(filterValue){
return subscriptionsPage.get(filterValue + 'Stories')
};
var setSubscriptionPage = function(filterValue, val){
return subscriptionsPage.set(filterValue + 'Stories', val);
};
var getCurrentSubscriptionPage = function(){
var storySearchQuery = Session.get('storySearchQuery');
return getSubscriptionPage(storySearchQuery ? ('search:' + storySearchQuery) : Session.get('filterValue'));
};
var setCurrentSubscriptionPage = function(val){
var storySearchQuery = Session.get('storySearchQuery');
return setSubscriptionPage(storySearchQuery ? ('search:' + storySearchQuery) : Session.get('filterValue'), val);
};
var incrementSubscriptionPage = function(filterValue){
setSubscriptionPage(filterValue, getSubscriptionPage(filterValue) + 1);
};
var incrementCurrentSubscriptionPage = function(){
setCurrentSubscriptionPage(getCurrentSubscriptionPage() + 1);
};
var subscriptionsReady = new ReactiveDict();
var subscriptionsPage = new ReactiveDict();
_.each(filters, function(filter){
setSubscriptionPage(filter, -1);
});
setSubscriptionPage('mixed', 0); // curated stories are preloaded
setSubscriptionPage('curated', 0); // curated stories are preloaded
var homeSubs = new SubsManager({
cacheLimit: 9999,
expireIn: 99999999
});
var followingHomeSubs = new SubsManager({
cacheLimit: 99,
expireIn: 99999999
});
var storySearchUserSubs = new SubsManager({
cacheLimit: 1,
expireIn: 60
});
var peopleSearchUserSubs = new SubsManager({
cacheLimit: 1,
expireIn: 60
});
// these methods all keep the subscription open for the lifetime of the window, but can be called again safely
var subscribeToCuratedStories = function(cb){
if(!curatedStoriesSub){
curatedStoriesSub = homeSubs.subscribe("curatedStoriesPub", function(){
subscriptionsReady.set('curatedStories', true);
if(cb){
cb();
}
})
} else {
if(cb){
cb();
}
}
};
var subscribeToTrendingStories = function(cb){
if(!trendingStoriesSub){
trendingStoriesSub = homeSubs.subscribe("trendingStoriesPub", {preview: true}, function(){
incrementSubscriptionPage('trending');
subscriptionsReady.set('trendingStories', true);
if(cb){
cb();
}
})
} else {
if(cb){
cb();
}
}
};
var subscribeToNewestStories = function(cb){
if(!newestStoriesSub){
newestStoriesSub = homeSubs.subscribe("newestStoriesPub", {preview: true}, function(){
incrementSubscriptionPage('newest');
subscriptionsReady.set('newestStories', true);
if(cb){
cb();
}
})
} else {
if(cb){
cb();
}
}
};
var subscribeToStarredStories = function(cb){
if(!starredStoriesSub){
starredStoriesSub = homeSubs.subscribe("starredStoriesPub", {preview: true}, function(){
incrementSubscriptionPage('starred');
subscriptionsReady.set('starredStories', true);
if(cb){
cb();
}
})
} else {
if(cb){
cb();
}
}
};
var createHomePageDate;
var whichUserPics = new Tracker.Dependency();
var additionalMixedPages = new Tracker.Dependency();
Template.all_stories.onCreated(function(){
createHomePageDate = Date.now();
this.autorun(() => {
whichUserPics.depend();
this.subscribe('minimalUsersPub', _.sortBy(Stories.find({published: true}, { fields: {authorId: 1}, reactive: false }).map(function (story) {
return story.authorId
}), _.identity));
});
subscriptionsReady.set('curatedStories', true); // we loaded a preview of these up front
subscriptionsReady.set('mixedStories', true); // we loaded a preview of these up front
Meteor.setTimeout(() =>{
if (!this.view.isDestroyed) { // because this happens asynchronously, the user may have already navigated away
subscribeToCuratedStories(() => { // might as well load the full versions of curated stories for a faster experience
// do nothing for now
});
}
}, 4500); // wait a few seconds to let the user orient before potentially slowing down the page for another couple seconds
var notFirstRunA = false;
this.autorun(function(){
var user = Meteor.users.find(Meteor.userId(), {fields: {'profile.following': 1}}).fetch()[0];
if(!user){
return;
}
if(notFirstRunA){
var following = user.profile.following;
followingHomeSubs.clear();
additionalMixedPages.changed();
followingHomeSubs.subscribe("mixedStoriesPub", {authors: _.sortBy(following, _.identity), preview: true}, function(){ // preview for memory savings on server. can remove preview to make it faster to visit stories you're following
subscriptionsReady.set('mixedStories', true);
whichUserPics.changed();
})
}
notFirstRunA = true;
});
var notFirstRunB = false;
this.autorun(function(){
Session.get('filterValue'); // re-run whenever filter value changes
if (notFirstRunB){
$(window).scrollTop(0)
}
notFirstRunB = true;
});
this.autorun(function () {
if (adminMode()) {
subscribeToCuratedStories(function () {
subscribeToNewestStories(function () {
subscribeToTrendingStories(function () {
subscribeToStarredStories(function () {
whichUserPics.changed();
});
});
});
});
}
});
this.autorun(function () {
if (Session.equals('filterValue', 'newest')) {
subscriptionsReady.set('newestStories', false);
subscribeToNewestStories(function () {
subscriptionsReady.set('newestStories', true);
whichUserPics.changed();
});
}
});
// first page of search results, or when flip back to query
this.autorun(function(){
var storySearchQuery = Session.get('storySearchQuery');
if(storySearchQuery){
Tracker.nonreactive(function(){
var currentPage = getCurrentSubscriptionPage();
if(typeof currentPage !== 'number'){
currentPage = 0;
setCurrentSubscriptionPage(currentPage);
}
StorySearch.search(storySearchQuery, {page: currentPage});
PersonSearch.search(storySearchQuery, {page: 0});
})
}
});
// further pages of search results
this.autorun(function(){
var currentPage = getCurrentSubscriptionPage();
Tracker.nonreactive(function(){
var storySearchQuery = Session.get('storySearchQuery');
if(storySearchQuery && currentPage){
StorySearch.search(storySearchQuery, {page: currentPage});
}
});
});
subscribeToStorySearchedMinimalUsers = _.debounce(function(){
return storySearchUserSubs.subscribe('minimalUsersPub', _.sortBy(StorySearch.getData({}, true).map(function(story){return story.authorId}), _.identity));
}, 1000);
// TO-DO, we just loaded this data with the search....
subscribeToPeopleSearchedMinimalUsers = _.debounce(function(){
return peopleSearchUserSubs.subscribe('minimalUsersPub', _.sortBy(PersonSearch.getData({}, true).map(function(person){return person._id}), _.identity));
}, 1000);
this.autorun(function(){
if(StorySearch.getStatus().loaded){
subscribeToStorySearchedMinimalUsers();
}
if(PersonSearch.getStatus().loaded){
subscribeToPeopleSearchedMinimalUsers();
}
});
});
search = null;
var currentHomeStories = function(){
var limit = (getCurrentSubscriptionPage() + 1) * PUB_SIZE;
if (limit <= 0){
return
}
if(Session.get('storySearchQuery')){
var storyResults = StorySearch.getData({
sort:[
["editorsPickAt", "desc"],
["favoritedTotal", "desc"],
["savedAt", "desc"]
],
docTransform (doc){
return new Story(doc);
}
});
var personResults = PersonSearch.getData({
sort:[
["followersTotal", "desc"],
["followingTotal", "desc"],
["favoritesTotal", "desc"],
["createdAt", "desc"]
]
});
var searchResults = _.union(personResults, storyResults)
searchResults.count = function(){
return storyResults.length
}
return searchResults;
}
switch (Session.get('filterValue')) {
case 'mixed':
if(!Meteor.userId()){
return Stories.find({ published: true, editorsPick: true}, {sort: {'editorsPickAt': -1}, limit: limit, reactive: true});
} else {
return Stories.find({ published: true, $or: [{editorsPick: true}, {authorId: {$in: Meteor.user().profile.following || []}}]}, {sort: {'r': -1}, limit: limit, reactive: true});
}
break;
case 'curated':
return Stories.find({ published: true, editorsPick: true}, {sort: {'editorsPickAt': -1}, limit: limit, reactive: true});
break;
case 'newest':
return Stories.find({published: true}, {sort: {'publishedAt': -1}, limit: limit, reactive: true});
break;
case 'trending':
return Stories.find({published: true}, {sort: {'analytics.views.total': -1}, limit: limit, reactive: true});
break;
case 'starred':
return Stories.find({published: true}, {sort: {'favoritedTotal': -1}, limit: limit, reactive: true});
break;
}
};
Template.all_stories.events({
'click .show-more' (e,t){
var storySearchQuery = Session.get('storySearchQuery');
if(storySearchQuery){
incrementCurrentSubscriptionPage();
} else if (adminMode() || (Session.get('filterValue') === 'newest')) { // legacy behavior + newest
var filterValue = Session.get('filterValue');
subscriptionsReady.set(filterValue + 'Stories', false);
homeSubs.subscribe(filterValue + 'StoriesPub', {page: getCurrentSubscriptionPage() + 1}, function(){
incrementCurrentSubscriptionPage();
whichUserPics.changed();
subscriptionsReady.set(filterValue + 'Stories', true);
})
} else if (Meteor.userId()) {
var nextPage = getCurrentSubscriptionPage() + 1;
t.autorun(() =>{ // autorun and depend is so that subs update when list of following users does
additionalMixedPages.depend();
var user;
var currentPage;
Tracker.nonreactive(function(){
user = Meteor.user();
currentPage = getCurrentSubscriptionPage();
});
var following = user.profile.following;
subscriptionsReady.set('mixedStories', false);
followingHomeSubs.subscribe("mixedStoriesPub", {authors: _.sortBy(following, _.identity), preview: true, page: nextPage}, function(){
subscriptionsReady.set('mixedStories', true);
if(nextPage === currentPage + 1){
incrementCurrentSubscriptionPage();
}
whichUserPics.changed(); // TO-DO this gets run more often than it needs to when authors user is following changes
})
});
} else {
subscriptionsReady.set('curatedStories', false);
homeSubs.subscribe('curatedStoriesPub', {page: getCurrentSubscriptionPage() + 1, preview: true}, function(){
incrementCurrentSubscriptionPage();
subscriptionsReady.set('curatedStories', true);
whichUserPics.changed();
});
}
},
'click .dismiss-box' (e,t) {
Session.set('boxDismissed', true);
},
'click .clear-search' (e,t) {
Session.set('storySearchQuery', null);
}
});
Template.all_stories.helpers({ // most of these are reactive false, but they will react when switch back and forth due to nesting inside ifs (so they rerun when switching between filters)
stories: currentHomeStories,
storiesLoading (){
return(!(subscriptionsReady.get(Session.get('filterValue') + 'Stories')) || PersonSearch.getStatus().loading
|| StorySearch.getStatus().loading)
},
moreToShow (){
var stories = currentHomeStories();
if (!stories){
return false
}
return currentHomeStories().count() >= (getCurrentSubscriptionPage() + 1) * PUB_SIZE
},
boxDismissed (){
return Session.get('boxDismissed') || Session.get('storySearchQuery')
},
hideActivityFeed (){ // we'll hide it so it doesn't need to reload all activities
return !Session.equals('filterValue', 'mixed') || Session.get('storySearchQuery');
},
currentSearch (){
return Session.get('storySearchQuery')
}
});
Template.story_preview.helpers({
story (){
return Template.instance().data.story || Stories.findOne(this._id);
}
});
Template._story_preview_content.helpers({
lastPublishDate () {
if(this.publishedAt) {
return prettyDateInPast(this.publishedAt);
}
},
story (){
if (Template.instance().data.useDraftStory){
return this.draftStory;
} else {
return this;
}
},
linkRoute (){
return Template.instance().data.useDraftStory ? 'edit' : 'read';
},
author (){
return Meteor.users.findOne(this.authorId)
},
profileUrl (){
return '/profile/' + (this.authorDisplayUsername || this.authorUsername); // TODO migrate drafts and only use authorDisplayUsername
},
narrativeCount (){
return this.narrativeBlockCount ? this.narrativeBlockCount : this.narrativeCount();
},
contextCountOfType (type){
return this.contextBlockTypeCount ? this.contextBlockTypeCount[type] : this.contextCountOfType(type);
}
});
Template.login_buttons.helpers({
showUserInfo () {
return Template.instance().showUserInfo.get();
}
});
Template.login_buttons.onCreated(function() {
return this.showUserInfo = new ReactiveVar(false);
});
Template.login_buttons.events({
"mouseenter .user-action" (d) {
Template.instance().showUserInfo.set(true);
},
"mouseleave .user-action" (d) {
Template.instance().showUserInfo.set(false);
},
"click .signin" (d) {
openSignInOverlay();
},
"click .logout" (e) {
e.preventDefault();
Template.instance().showUserInfo.set(false);
Meteor.logout();
}
});
Template.search_overlay.events({
'click .close' (){
return closeSearchOverlay();
}
});
Template.search.onRendered(function(){
if(Session.get('searchOverlayShown')){
this.$('input').focus();
}
});
Template.menu_overlay.events({
'click .close' (){
return closeMenuOverlay();
},
'click a, click button' (){
return closeMenuOverlay();
},
'click .search' (){
return openSearchOverlay();
},
'click .sign-up' (){
return openSignInOverlay();
},
'click .log-in' (){
return openSignInOverlay('login');
}
});
Template.embed_overlay.onRendered(function(){
this.$('.embed-code').select();
});
Template.embed_overlay.events({
'click .close' (){
return closeEmbedOverlay();
},
'click' (e, t){
return t.$('.embed-code').select();
}
});
Template.how_to_overlay.onCreated(function(){
this.totalSlides = 5;
this.currentSlide = new ReactiveVar(0);
});
Template.how_to_overlay.events({
'click .close' (){
return closeHowToOverlay();
},
'click .right' (e, t){
return t.currentSlide.set((t.currentSlide.get() + 1) % t.totalSlides);
},
'click .left' (e, t){
var currentSlide = t.currentSlide.get();
if (currentSlide === 0){
return t.currentSlide.set(t.totalSlides - 1);
} else {
return t.currentSlide.set( (currentSlide - 1) % t.totalSlides);
}
},
'click .bullet' (e, t){
t.currentSlide.set($(e.currentTarget).data('slide'));
}
});
Template.how_to_overlay.helpers({
'currentSlide' (){
return Template.instance().currentSlide.get();
}
});
<|start_filename|>client/styles/MyFontsWebfontsKit.css<|end_filename|>
/**
* @license
* MyFonts Webfont Build ID 3109905, 2015-10-18T16:18:30-0400
*
* The fonts listed in this notice are subject to the End User License
* Agreement(s) entered into by the website owner. All other parties are
* explicitly restricted from using the Licensed Webfonts(s).
*
* You may obtain a valid license at the URLs below.
*
* Webfont: FF Mark Web Italic by FontFont
* URL: http://www.myfonts.com/fonts/fontfont/mark/ot-italic/
*
* Webfont: FF Mark Web Bold Italic by FontFont
* URL: http://www.myfonts.com/fonts/fontfont/mark/ot-bold-italic/
*
* Webfont: FF Mark Web Bold by FontFont
* URL: http://www.myfonts.com/fonts/fontfont/mark/ot-bold/
*
* Webfont: FF Mark Web Light Italic by FontFont
* URL: http://www.myfonts.com/fonts/fontfont/mark/ot-light-italic/
*
* Webfont: FF Mark Web Light by FontFont
* URL: http://www.myfonts.com/fonts/fontfont/mark/ot-light/
*
* Webfont: FF Mark Web Medium Italic by FontFont
* URL: http://www.myfonts.com/fonts/fontfont/mark/ot-medium-italic/
*
* Webfont: FF Mark Web Medium by FontFont
* URL: http://www.myfonts.com/fonts/fontfont/mark/ot-medium/
*
* Webfont: FF Mark Web by FontFont
* URL: http://www.myfonts.com/fonts/fontfont/mark/ot-regular/
*
*
* License: http://www.myfonts.com/viewlicense?type=web&buildid=3109905
* Licensed pageviews: 50,000
* Webfonts copyright: 2013 published by FontShop International GmbH
*
* © 2015 MyFonts Inc
*/
/*
* @license
* MyFonts Webfont Build ID 3109936, 2015-10-18T18:52:23-0400
*
* The fonts listed in this notice are subject to the End User License
* Agreement(s) entered into by the website owner. All other parties are
* explicitly restricted from using the Licensed Webfonts(s).
*
* You may obtain a valid license at the URLs below.
*
* Webfont: FF Magda Clean Mono Web Pro Regular by FontFont
* URL: http://www.myfonts.com/fonts/fontfont/ff-magda-clean-mono/pro-regular/
* Copyright: 2011 Critzla, <NAME>, <NAME> published by FSI FontShop International GmbH
* Licensed pageviews: 50,000
*
*
* License: http://www.myfonts.com/viewlicense?type=web&buildid=3109936
*
* © 2015 MyFonts Inc
*/
@font-face {font-family: 'FFMagdaCleanMonoWebProRegular';src: url('webfonts/2F7430_0_0.eot');src: url('webfonts/2F7430_0_0.eot?#iefix') format('embedded-opentype'),url('webfonts/2F7430_0_0.woff2') format('woff2'),url('webfonts/2F7430_0_0.woff') format('woff'),url('webfonts/2F7430_0_0.ttf') format('truetype');}
@font-face {font-family: 'FFMarkWebItalic';src: url('webfonts/2F7411_0_0.eot');src: url('webfonts/2F7411_0_0.eot?#iefix') format('embedded-opentype'),url('webfonts/2F7411_0_0.woff2') format('woff2'),url('webfonts/2F7411_0_0.woff') format('woff'),url('webfonts/2F7411_0_0.ttf') format('truetype');}
@font-face {font-family: 'FFMarkWebBoldItalic';src: url('webfonts/2F7411_1_0.eot');src: url('webfonts/2F7411_1_0.eot?#iefix') format('embedded-opentype'),url('webfonts/2F7411_1_0.woff2') format('woff2'),url('webfonts/2F7411_1_0.woff') format('woff'),url('webfonts/2F7411_1_0.ttf') format('truetype');}
@font-face {font-family: 'FFMarkWebBold';src: url('webfonts/2F7411_2_0.eot');src: url('webfonts/2F7411_2_0.eot?#iefix') format('embedded-opentype'),url('webfonts/2F7411_2_0.woff2') format('woff2'),url('webfonts/2F7411_2_0.woff') format('woff'),url('webfonts/2F7411_2_0.ttf') format('truetype');}
@font-face {font-family: 'FFMarkWebLightItalic';src: url('webfonts/2F7411_3_0.eot');src: url('webfonts/2F7411_3_0.eot?#iefix') format('embedded-opentype'),url('webfonts/2F7411_3_0.woff2') format('woff2'),url('webfonts/2F7411_3_0.woff') format('woff'),url('webfonts/2F7411_3_0.ttf') format('truetype');}
@font-face {font-family: 'FFMarkWebLight';src: url('webfonts/2F7411_4_0.eot');src: url('webfonts/2F7411_4_0.eot?#iefix') format('embedded-opentype'),url('webfonts/2F7411_4_0.woff2') format('woff2'),url('webfonts/2F7411_4_0.woff') format('woff'),url('webfonts/2F7411_4_0.ttf') format('truetype');}
@font-face {font-family: 'FFMarkWebMediumItalic';src: url('webfonts/2F7411_5_0.eot');src: url('webfonts/2F7411_5_0.eot?#iefix') format('embedded-opentype'),url('webfonts/2F7411_5_0.woff2') format('woff2'),url('webfonts/2F7411_5_0.woff') format('woff'),url('webfonts/2F7411_5_0.ttf') format('truetype');}
@font-face {font-family: 'FFMarkWebMedium';src: url('webfonts/2F7411_6_0.eot');src: url('webfonts/2F7411_6_0.eot?#iefix') format('embedded-opentype'),url('webfonts/2F7411_6_0.woff2') format('woff2'),url('webfonts/2F7411_6_0.woff') format('woff'),url('webfonts/2F7411_6_0.ttf') format('truetype');}
@font-face {font-family: 'FFMarkWeb';src: url('webfonts/2F7411_7_0.eot');src: url('webfonts/2F7411_7_0.eot?#iefix') format('embedded-opentype'),url('webfonts/2F7411_7_0.woff2') format('woff2'),url('webfonts/2F7411_7_0.woff') format('woff'),url('webfonts/2F7411_7_0.ttf') format('truetype');}
/* FOLD Edit: Set bold weight of markweb to the bold version of the font*/
@font-face {font-family: 'FFMarkWeb';src: url('webfonts/2F7411_2_0.eot');src: url('webfonts/2F7411_2_0.eot?#iefix') format('embedded-opentype'),url('webfonts/2F7411_2_0.woff2') format('woff2'),url('webfonts/2F7411_2_0.woff') format('woff'),url('webfonts/2F7411_2_0.ttf') format('truetype');
font-weight: bold;}
<|start_filename|>client/create-context-blocks.js<|end_filename|>
var searchDep = new Tracker.Dependency();
var i = 0;
var count = function(){
return i++;
};
var createBlockHelpers = {
showAddButton (){
return Template.instance().focusResult.get() ? true : false;
},
isFocused () {
var focusResult = Template.instance().focusResult.get();
if (_.isObject(focusResult)) {
if (this._id === focusResult._id) {
return true;
}
}
},
isActive () {
var focusResult = Template.instance().focusResult.get();
if (_.isObject(focusResult)) {
return true;
}
},
selected () {
return (this.source === Session.get('newHorizontalDataSource'));
},
loading () {
if (Template.instance().loadingResults)
return Template.instance().loadingResults.get()
},
noMoreResults () {
if (Template.instance().noMoreResults)
return Template.instance().noMoreResults.get()
},
results () {
searchDep.depend();
return Template.instance().existingSearchResults()
},
addingDescription () {
return Template.instance().addingDescription.get();
},
focusResult () {
var focusResult = Template.instance().focusResult.get();
if (focusResult) { return focusResult; }
}
};
searchScrollFn = function(d, template) {
var searchContainer = $("ol.search-results-container");
if ((searchContainer.scrollTop() + searchContainer.height()) === searchContainer[0].scrollHeight && !template.loadingResults.get()) {
if (template.existingSearchResults({reactive: false}).count()){ // confirm there are already results and we're scrolling down{
template.search();
}
}
};
throttledSearchScrollFn = _.throttle(searchScrollFn, 20);
var addFocusResult = function(d, template) {
var focusResult = template.focusResult.get();
if (focusResult) {
var textAreaContent = template.$('textarea[name=content]').val();
focusResult.description = textAreaContent;
template.focusResult.set(focusResult);
addContext(focusResult);
}
};
var createBlockEvents = {
"click .data-source" (d, template) {
Session.set('newHorizontalDataSource', this.source);
},
"submit form" (d, template) {
d.preventDefault();
if(!template.loadingResults.get()){
if (!template.existingSearchResults || !template.existingSearchResults({reactive: false}).count()) { // confirm there are no results yet
template.search();
}
}
},
"scroll ol.search-results-container": throttledSearchScrollFn,
"click .search-results-container li:not(.loading-icon)" (d, template) {
template.focusResult.set(this);
},
"click .add-desc-button" (d, template) {
template.addingDescription.set(true);
},
"click .back-button" (d, template) {
template.addingDescription.set(false);
},
"click .add-button": addFocusResult,
"keydown .text-content.editable" (e, t) {
if (e.which === 13){
addFocusResult.apply(this,arguments);
}
},
"click .cancel" () {
Session.set('addingContext', false);
return Session.set('editingContext', null);
}
};
var getSearchInput = function(){
try { // wrap in try in case dom isn't ready
return {
query: this.$('input[type="search"]').val(),
option: this.$('input[name=option]:checked').val()
}
} catch (e) {
return {};
}
};
var setSearchInput = function(query){
try { // wrap in try in case dom isn't ready
this.$('input[type="search"]').val(query);
} catch (e) {
return {};
}
};
var existingSearchResults = function(options){
inputs = getSearchInput.call(this);
return SearchResults.find({
searchQuery: inputs.query,
searchOption: inputs.option,
type: this.type,
source: Session.get('newHorizontalDataSource')
}, _.extend({}, options, {sort: {ordinalId: 1} }))
};
var searchAPI = function(query) {
var source = Session.get('newHorizontalDataSource');
var type = this.type;
var page;
var inputs = getSearchInput.call(this);
var query = inputs.query;
if (!query){
return this.noMoreResults.set('Please enter a search query');
}
var option = inputs.option;
var mostRecentResult = this.existingSearchResults({reactive:false}).fetch().slice(-1)[0];
if (mostRecentResult) {
page = mostRecentResult.nextPage;
}
if (page === 'end') { // return if at end of possible results
this.noMoreResults.set('No more results');
this.loadingResults.set(false);
return;
}
this.noMoreResults.set(false);
this.loadingResults.set(true);
searchDep.changed();
integrationDetails = ContextBlock.searchMappings[source];
if (integrationDetails.notSearch){ // don't search if it's not a search integration
return
}
Meteor.call(integrationDetails.methodName, query, option, page, (err, results) => {
this.loadingResults.set(false);
if (err) {
this.noMoreResults.set('No more results'); // TO-DO - surface error to user?
throw(err);
return;
}
var items = results.items;
var nextPage = results.nextPage;
if (!items || !items.length) {
this.noMoreResults.set('No results found');
return;
}
_.chain(items)
.map(integrationDetails.mapFn || _.identity)
.each(function(item, i) {
_.extend(item, {
type : type,
source: source,
authorId : Meteor.userId(),
searchQuery : query,
searchOption : option,
nextPage: nextPage,
ordinalId: count(),
fullDetails: items[i] // include all original details from the api
});
SearchResults.insert(item);
});
});
};
var createTemplateNames = [
'create_image_section',
'create_gif_section',
'create_video_section',
'create_twitter_section',
'create_map_section',
'create_audio_section',
'create_link_section'
];
_.each(createTemplateNames, function(templateName){
Template[templateName].helpers(createBlockHelpers);
Template[templateName].events(createBlockEvents);
});
Template.create_audio_section.events({
"dblclick .search-results-container li:not(.loading-icon)" (d, template) {
addContext(this);
}
});
Template.create_video_section.events({
"dblclick .search-results-container li:not(.loading-icon)" (d, template) {
addContext(this);
}
});
Template.create_twitter_section.events({
"dblclick .search-results-container li:not(.loading-icon)" (d, template) {
addContext(this);
}
});
Template.create_image_section.events({
"dblclick .search-results-container li:not(.loading-icon)" (d, template) {
template.addingDescription.set(true);
}
});
Template.create_gif_section.events({
"dblclick .search-results-container li:not(.loading-icon)" (d, template) {
template.addingDescription.set(true);
}
});
searchTemplateCreatedBoilerplate = function(type, defaultSource) {
return function() {
this.type = type;
var previousSource = Session.get('newHorizontalDataSource');
if (!_.contains(_.pluck(dataSourcesByType[type], 'source'), previousSource)){
Session.set('newHorizontalDataSource', defaultSource)
}
this.loadingResults = new ReactiveVar();
this.focusResult = new ReactiveVar();
this.noMoreResults = new ReactiveVar();
this.addingDescription = new ReactiveVar(false);
this.autorun(() =>{
if(this.addingDescription.get()){
Meteor.setTimeout(function(){
this.$('textarea').focus();
});
}
});
this.search = _.bind(searchAPI, this);
this.existingSearchResults = _.bind(existingSearchResults, this);
this.getSearchInput = _.bind(getSearchInput, this);
this.setSearchInput = _.bind(setSearchInput, this);
this.autorun(() => {
searchDep.depend();
this.noMoreResults.set(false);
});
};
};
searchTemplateRenderedBoilerplate = function() {
return function() {
// set initial search query to session query
this.setSearchInput(Session.get('query'));
searchDep.changed();
// focus search box
this.$('input[type="search"]').focus();
// update session query whenever search input changes
this.autorun(() => {
searchDep.depend();
Session.set('query', this.getSearchInput().query);
});
// search when initially arrive and when source changes (if there aren't already results)
this.autorun(() => {
Session.get('newHorizontalDataSource');
if (Session.get('addingContext') && this.getSearchInput().query && !this.existingSearchResults({reactive: false}).count()) {
this.search();
}
});
};
};
Template.create_video_section.onCreated(searchTemplateCreatedBoilerplate('video', 'youtube'));
Template.create_video_section.onRendered(searchTemplateRenderedBoilerplate());
Template.create_twitter_section.onCreated(searchTemplateCreatedBoilerplate('twitter', 'twitter'));
Template.create_twitter_section.onRendered(searchTemplateRenderedBoilerplate());
Template.create_image_section.onCreated(function(){
this.uploadPreview = new ReactiveVar();
this.uploadStatus = new ReactiveVar();
});
Template.create_image_section.helpers({
uploadMode (){
return Session.get('newHorizontalDataSource') === 'cloudinary';
},
uploadStatus (){
return Template.instance().uploadStatus.get();
},
uploadPreview (){
return Template.instance().uploadPreview.get();
}
});
Template.create_image_section.events({
'change input[type=file]' (e, t){
var file = _.first(e.target.files);
if (file){
if(file.size > CLOUDINARY_FILE_SIZE){
return notifyImageSizeError();
}
t.uploadStatus.set('Uploading...');
// immediate preview
var reader = new FileReader;
reader.onload = function(upload){
t.uploadPreview.set(upload.target.result);
};
reader.readAsDataURL(file);
// actual upload
Cloudinary.upload([file], {}, function(err, doc) {
if(err){
var input = t.$('input[type=file]');
t.uploadStatus.set('Upload failed');
input.val(null);
input.change(); // trigger change event
} else {
var cardModel = doc.format === 'gif' ? GifBlock : ImageBlock;
// TO-DO consider how to do attribution
t.uploadStatus.set('Upload successful');
t.focusResult.set(new cardModel({
reference: {
id: doc.public_id,
fileExtension: doc.format,
width: doc.width,
height: doc.height
},
source: Session.get('newHorizontalDataSource'),
authorId : Meteor.userId(),
fullDetails: doc
}));
t.addingDescription.set(true);
}
})
} else {
t.uploadPreview.set(null);
}
}
});
Template.create_image_section.onCreated(searchTemplateCreatedBoilerplate('image', 'flickr'));
Template.create_image_section.onRendered(searchTemplateRenderedBoilerplate());
Template.create_gif_section.onCreated(searchTemplateCreatedBoilerplate('gif', 'giphy'));
Template.create_gif_section.onRendered(searchTemplateRenderedBoilerplate());
Template.create_audio_section.onCreated(searchTemplateCreatedBoilerplate('audio', 'soundcloud'));
Template.create_audio_section.onRendered(searchTemplateRenderedBoilerplate());
var dataSourcesByType = {
'image': [{source: 'flickr', 'display': 'Flickr'}, {source: 'imgur', display: 'Imgur'}, {source: 'cloudinary', display: 'Upload Your Own'}],
'gif': [{source: 'giphy', display: 'Giphy'}],
'video': [{source: 'youtube', display: 'Youtube'}, {source: 'vimeo', display: 'Vimeo'}],
'audio': [{source: 'soundcloud', display: 'SoundCloud'}],
'twitter': [{source: 'twitter', display: 'Twitter'}],
'map': [{source: 'google_maps', display: 'Google Maps'}],
'text': [{source: 'free_text', display: 'Free Text'}],
'link': [{source: 'link', display: 'Link'}]
};
_.each(dataSourcesByType, function(dataSources, type){
var templateName = 'create_' + type + '_section';
Template[templateName].helpers({dataSources: dataSources});
});
Template.create_link_section.onCreated(function() {
this.type = 'link';
Session.set('newHorizontalDataSource', 'link');
this.loadingResults = new ReactiveVar();
this.noMoreResults = new ReactiveVar();
this.focusResult = new ReactiveVar();
var that = this;
this.search = function(){
var url = this.$('input[type="search"]').val();
that.loadingResults.set(true);
Meteor.call('embedlyEmbedResult', url, function(error, result) {
that.loadingResults.set(false);
if(error){
that.noMoreResults.set('No results found');
return
}
that.noMoreResults.set(false);
addPropertiesToBaseline = function(obj){
var newObj = _.extend({}, obj, {
fullDetails: result,
authorId : Meteor.userId(),
searchQuery: url,
fromEmbedly: true,
version: 'em1'
});
if (!newObj.reference){
newObj.reference = {};
}
_.extend(newObj.reference, {
title: result.title,
description: result.description,
providerName: result.provider_name,
providerUrl: result.provider_url,
url: result.url,
originalUrl: url,
authorUrl: result.author_url,
authorName: result.author_name,
thumbnailUrl: result.thumbnail_url,
thumbnailWidth: result.thumbnail_width,
thumbnailHeight: result.thumbnail_height,
embedlyType: result.type
});
if(!newObj.reference.thumbnailUrl){
newObj.reference.thumbnailFallback = _.random(1,13).toString();
}
return newObj
};
switch(result.type) {
case 'rich':
// fall through to the link
case 'link':
that.focusResult.set(new LinkBlock(addPropertiesToBaseline({
type: 'link',
source: 'embedly'
})));
break;
case 'photo':
var source, reference;
switch(result.provider_name) {
case 'Imgur':
source = 'imgur';
var info = _.chain(result.url.split('/')).compact().last().value().split('.');
reference = {
id: info[0],
fileExtension: info[1]
};
break;
case 'Giphy':
source = 'giphy';
var info = result.url.match(/\/media\/(.*)?\/giphy/);
reference = {
id: info[1]
};
break;
case 'Flickr':
source = 'flickr';
var info = result.url.match(/\/\/farm(.*)?\.staticflickr\.com\/(.*)?\/(.*)?_(.*)?_/);
reference = {
flickrFarm: info[1],
flickrServer: info[2],
id: info[3],
flickrSecret: info[4]
};
break;
default:
source = 'embedly';
reference = {};
}
cardModel = source === 'giphy' ? GifBlock : ImageBlock;
that.focusResult.set(new cardModel(addPropertiesToBaseline({
reference: reference,
type: 'image',
source: source
})));
break;
case 'video':
switch (result.provider_name){
case "YouTube":
var id = result.url.split("v=")[1];
that.focusResult.set(new VideoBlock(addPropertiesToBaseline({
reference: {
id: id,
username: result.author_name
},
source: 'youtube'
})));
break;
case "Vimeo":
var id = result.html.match(/%2Fvideo%2F(\d*)/)[1];
var previewImage = result.thumbnail_url.match(/\/video\/(.*)?_/)[1];
that.focusResult.set(new VideoBlock(addPropertiesToBaseline({
reference: {
id: id,
previewImage: previewImage,
username: result.author_name
},
source: 'vimeo'
})));
break;
case 'Giphy':
source = 'giphy';
var info = result.url.match(/\/media\/(.*)?\/giphy/);
that.focusResult.set(new GifBlock(addPropertiesToBaseline({
reference: {
id: info[1]
},
source: source
})));
break;
default:
that.focusResult.set(new LinkBlock(addPropertiesToBaseline({
reference: reference,
source: 'embedly'
})));
break;
}
break;
}
});
};
});
Template.create_link_section.onRendered(function() {
this.$('input[type="search"]').focus();
});
Template.create_link_section.helpers({
preview (){
return Template.instance().focusResult.get();
},
link () {
var preview = Template.instance().focusResult.get();
if (preview) {
return (preview.type === 'link');
}
},
image () {
var preview = Template.instance().focusResult.get();
if (preview) {
return (preview.type === 'image' || preview.type === 'gif');
}
},
video () {
var preview = Template.instance().focusResult.get();
if (preview) {
return (preview.type === 'video');
}
}
});
Template.create_map_section.onCreated(function() {
this.type = 'map';
Session.set('newHorizontalDataSource', 'google_maps');
this.loadingResults = new ReactiveVar();
this.focusResult = new ReactiveVar();
var that = this;
this.search = function(){
var inputs = getSearchInput.call(that);
if (!inputs.query){
return
}
that.focusResult.set(new MapBlock({
reference: {
mapQuery: inputs.query,
mapType: inputs.option
},
authorId : Meteor.userId()
}))
};
});
Template.create_map_section.onRendered(function() {
this.$('input[type="search"]').focus();
});
Template.create_map_section.events({
'change input[type="radio"]' (e, template) {
template.search();
}
});
Template.create_map_section.helpers({
url () {
var preview = Template.instance().focusResult.get();
if (preview) {
return preview.url()
}
},
previewUrl () {
var preview = Template.instance().focusResult.get();
if (preview) {
return preview.previewUrl()
}
}
});
Template.create_text_section.onCreated(function() {
this.type = 'text';
Session.set('newHorizontalDataSource', 'free_text');
});
Template.create_text_section.onRendered(function() {
this.$('textarea').focus();
});
Template.create_text_section.events({
'click .add-button' (e, template){
e.preventDefault()
addContext(new TextBlock({
content: template.$('textarea[name=content]').val(),
authorId: Meteor.userId(),
source: 'plaintext'
}));
}
});
Template.create_action_section.onCreated(function(){
this.editingThumbnail = new ReactiveVar();
this.uploadingThumbnail = new ReactiveVar();
});
Template.create_action_section.helpers({
uploadingThumbnail (){
return Template.instance().uploadingThumbnail.get();
}
});
Template.create_action_section.events({
'blur textarea.title' (e,t){
Session.set('saveState', 'saving');
Meteor.call('editActionTitle', this._id, t.$('textarea.title').val(), (err, result) => {
saveCallback(err, result)
});
},
'blur textarea.description' (e,t){
Session.set('saveState', 'saving');
Meteor.call('editActionDescription', this._id, t.$('textarea.description').val(), (err, result) => {
saveCallback(err, result)
});
},
'blur textarea.button-text' (e,t){
Session.set('saveState', 'saving');
Meteor.call('editActionButtonText', this._id, t.$('textarea.button-text').val(), (err, result) => {
saveCallback(err, result)
});
},
'blur textarea.button-url' (e,t){
Session.set('saveState', 'saving');
Meteor.call('editActionButtonUrl', this._id, t.$('textarea.button-url').val(), (err, result) => {
saveCallback(err, result)
});
},
"click input[type=file]" (d, template) {
return template.editingThumbnail.set(true);
},
"change input[type=file]" (e, template){
var finish = function(){
template.uploadingThumbnail.set(false);
return template.editingThumbnail.set(false);
};
var file = _.first(e.target.files);
if (file) {
if(file.size > CLOUDINARY_FILE_SIZE){
notifyImageSizeError();
return finish()
}
template.uploadingThumbnail.set(true);
Cloudinary.upload([file], {}, (err, doc) => {
if(err){
var input = template.$('input[type=file]');
input.val(null);
input.change();
saveCallback(err);
return finish();
} else {
var cloudinaryImageInfo = {
id: doc.public_id,
fileExtension: doc.format,
width: doc.width,
height: doc.height
};
Meteor.call('editLinkThumbnail', this._id, cloudinaryImageInfo, (err, result) => {
saveCallback(err, result);
return finish()
});
}
})
} else {
return finish()
}
}
});
Template.search_form.events({
'change, keydown' (){
searchDep.changed();
},
'change input[type="radio"]' (e,t){
t.$('form').submit();
}
});
Template.search_form.helpers({
placeholder () {
switch(Template.instance().data.placeholderType){
case 'links':
return 'e.g. ' +
_.sample([
'https://twitter.com/readFOLD',
'http://nytimes.com',
'http://flickr.com'
]);
break;
case 'locations':
return 'e.g. ' +
_.sample([
'waffle tower',
'aoshima island',
'area 51',
'the south pole',
'twin peaks',
'neutral zone',
'cal anderson park'
]);
break;
default:
return 'e.g. ' +
_.sample([
'radar',
'competitive fly fishing',
'net neutrality',
'synthetic biology',
'beekeeping',
'quantum mechanics',
'bitcoin mining',
'glass blowing',
'falconry',
'origami',
'table tennis',
'llama training',
]);
}
}
});
<|start_filename|>client/unsubscribe.js<|end_filename|>
Template.unsubscribe.onCreated(function(){
this.unsubscribed = new ReactiveVar(false);
this.resubscribed = new ReactiveVar(false);
this.autorun(() => {
if(Meteor.userId()){
Meteor.call('unsubscribe', Router.current().params.query.email_type, (err, success) => {
if(err || !success){
notifyError('Unsubscribe failed. Please email us at <EMAIL>')
} else {
this.unsubscribed.set(true);
}
})
} else {
openSignInOverlay('Please sign in to unsubscribe from emails');
}
})
});
Template.unsubscribe.events({
'click .resubscribe' (e, t){
Meteor.call('resubscribe', Router.current().params.query.email_type, (err, success) => {
if (err) {
notifyError('Resubscribe failed. Please email us at <EMAIL>')
} else {
t.resubscribed.set(true);
}
})
}
});
Template.unsubscribe.helpers({
'unsubscribed' (){
return Template.instance().unsubscribed.get();
},
'resubscribed' (){
return Template.instance().resubscribed.get();
},
'humanReadableEmailType' (){
switch (Router.current().params.query.email_type){
case 'followed-you':
return 'Follower Notifications';
break;
case 'following-published':
return 'Notifications When Someone You Follow Publishes a Story';
break;
default:
return Router.current().params.query.email_type;
}
}
});
<|start_filename|>collections/user-collections.js<|end_filename|>
if(!this.Schema){
Schema = {};
}
Schema.UserProfile = new SimpleSchema({
name: {
type: String,
optional: true,
min: 2,
max: 127,
autoValue () { // trim off whitespace
if (this.isSet && typeof this.value === "string") {
return this.value.trim();
} else {
this.unset()
}
}
},
bio: {
type: String,
optional: true,
max: 160,
autoValue () { // trim off whitespace
if (this.isSet && typeof this.value === "string") {
return this.value.trim();
} else {
this.unset()
}
},
autoform: {
rows: 7
}
},
favorites: {
type: [String],
optional: true,
defaultValue: []
},
following: {
type: [String],
optional: true,
defaultValue: []
},
profilePicture: {
type: String,
autoValue () {
var monster = _.random(1,10).toString();
if (this.isSet) {
return this.value;
} else if (this.isInsert) {
return this.value || monster;
} else if (this.isUpsert) {
return {$setOnInsert: this.value || monster};
} else {
this.unset();
}
}
}
});
Schema.User = new SimpleSchema({
username: {
type: String,
regEx: /^[a-z0-9_]*$/,
min: 3,
max: 15,
optional: true,
autoValue () {
if (this.isSet && typeof this.value === "string") {
return this.value.toLowerCase().trim();
} else {
this.unset()
}
}
},
displayUsername: { // allows for caps
type: String,
optional: true,
autoValue () { // TODO ensure this matches username except for capitalization
if (this.isSet && typeof this.value === "string") {
return this.value.trim();
} else {
this.unset()
}
}
},
tempUsername: {
type: String,
optional: true
},
emails: {
type: [Object],
optional: true
},
"emails.$.address": {
type: String,
regEx: SimpleSchema.RegEx.Email,
label: "Email address",
autoValue () {
if (this.isSet && typeof this.value === "string") {
return this.value.toLowerCase();
} else {
this.unset();
}
},
autoform: {
afFieldInput: {
readOnly: true,
disabled: true
}
}
},
"emails.$.verified": {
type: Boolean
},
createdAt: {
type: Date,
autoValue () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {$setOnInsert: new Date};
} else {
this.unset();
}
}
},
admin: {
type: Boolean,
optional: true,
autoValue (){
this.unset(); // don't allow to be set from anywhere within the code
}
},
accessPriority: {
type: Number,
optional: true
},
profile: {
type: Schema.UserProfile,
optional: true,
defaultValue: {}
},
followers: {
type: [String],
optional: true,
defaultValue: []
},
followersTotal: {
type: Number,
optional: true,
defaultValue: 0
},
followingTotal: {
type: Number,
optional: true,
defaultValue: 0
},
services: {
type: Object,
optional: true,
blackbox: true
},
unsubscribes: {
type: [String],
allowedValues: ['followed-you', 'following-published'],
optional: true
}
});
Meteor.users.attachSchema(Schema.User);
SimpleSchema.messages({
"regEx username": "Username may only contain letters, numbers, and underscores"
});
<|start_filename|>client/positioning.js<|end_filename|>
window.constants = {
verticalSpacing: 20, // there is css that needs to match this
readModeOffset: 246,
minPageWidth: 1024,
selectOffset: - 210,
baselineCardHeight: 300
};
if(Meteor.Device.isPhone()){
window.constants.readModeOffset = 0;
window.constants.verticalSpacing = 15;
}
window.getVerticalLeft = function() {
var windowWidth = Session.get('windowWidth');
return (windowWidth - 2 * getCardWidth(windowWidth) - constants.verticalSpacing) / 2;
};
Tracker.autorun(function(){
var inEmbedMode = embedMode();
if(inEmbedMode){
var inSandwichMode = sandwichMode();
if(!inSandwichMode){
window.constants.selectOffset = 0;
return
}
}
window.constants.selectOffset = -210; // original
});
window.getHorizontalLeft = function() {
var currentPos, currentHorizontal, cardWidth, numCards, left, offset, pageWidth, verticalRight, addContextBlockWidth, cardSeparation;
// Variable definitions (width of page, width of card, offset of cards)
cardWidth = Session.get("cardWidth");
cardSeparation = Session.get("separation");
addContextBlockWidth = 75;
verticalLeft = getVerticalLeft();
verticalRight = verticalLeft + cardWidth;
var currentY = Session.get("currentY");
var currentX = Session.get("currentX");
var wrap = Session.get("wrap");
var horizontalSectionsMap = Session.get("horizontalSectionsMap");
var inHiddenContextMode = hiddenContextMode();
// Offset of first card, different on create page because of (+) button
if (Session.get("read")) {
offset = 0;
} else {
offset = addContextBlockWidth + cardSeparation;
}
if (Session.get("addingContext")) {
offset += cardWidth + cardSeparation;
}
if(this.verticalIndex === currentY){
currentHorizontal = horizontalSectionsMap[currentY];
if (!currentHorizontal) {
return
}
currentPos = this.index - currentX;
numCards = currentHorizontal.horizontal.length;
} else { // card is from another row
currentPos = this.index - getXByYId(this.verticalId);
numCards = horizontalSectionsMap[this.verticalIndex].horizontal.length;
}
if(inHiddenContextMode){
// we do something different
var focusCardLeft = (Session.get('windowWidth') - cardWidth) / 2;
if(currentPos === 0){
return focusCardLeft
}
var positiveWrapPoint;
var negativeWrapPoint;
if(numCards <= 3){
positiveWrapPoint = 1;
negativeWrapPoint = -1;
} else if(numCards <= 4) {
positiveWrapPoint = 1;
negativeWrapPoint = -2;
} else if(numCards <= 5) {
positiveWrapPoint = 2;
negativeWrapPoint = -2;
} else if(numCards <= 6) {
positiveWrapPoint = 2;
negativeWrapPoint = -3;
} else {
positiveWrapPoint = 3;
negativeWrapPoint = -3;
}
if(currentPos > positiveWrapPoint){
currentPos -= numCards;
} else if (currentPos < negativeWrapPoint){
currentPos += numCards;
}
return (Session.get('windowWidth') - cardWidth) / 2 + currentPos * (cardWidth + cardSeparation)
}
if (numCards === 1){
return verticalRight + offset + cardSeparation;
}
if (wrap[this.verticalId] || numCards === 2) { // wrapping (and always position as if wrapping when two cards)
if (currentPos < 0) { // makes the first card appear at the end of the last card
currentPos = numCards + currentPos;
}
// Default context positioning (all to the right of vertical narrative)
left = (currentPos * (cardWidth + cardSeparation)) + (verticalRight + cardSeparation + offset);
// Last card positioning if number of cards is greater than 3
if (numCards >= 3) {
if (currentPos === numCards - 1) {
left = verticalLeft - cardWidth - cardSeparation;
}
}
return left;
} else { // not wrapping
if (currentPos === numCards - 1 || currentPos < -1) { // this makes cards appear on the right when they run off the left
currentPos = numCards + currentPos;
}
if (currentPos >= 0) {
left = (currentPos * (cardWidth + cardSeparation)) + (verticalRight + cardSeparation + offset);
} else {
left = ((currentPos + 1) * (cardWidth + cardSeparation)) + (verticalLeft - cardWidth - cardSeparation);
}
return left;
}
};
window.getVerticalHeights = function() {
var sum, verticalHeights;
var offset;
if(Meteor.Device.isPhone()){
offset = constants.readModeOffset + $('.title-overlay').height();
} else {
offset = constants.readModeOffset;
}
verticalHeights = [offset];
sum = offset;
$('.vertical-narrative-section').each(function() {
sum += $(this).outerHeight() + constants.verticalSpacing;
return verticalHeights.push(sum);
});
return verticalHeights;
};
window.slideCurrentYIntoPlace = function(){
goToY(Session.get('currentY'), {force: true})
};
window.goToXY = function(x, y) {
if (y !== Session.get("currentY")) {
goToY(y, {complete: goToX.bind(this, x)})
} else {
goToX(x);
}
};
window.goToY = function(y, options) {
options = options || {};
options.complete = options.complete || function(){};
if(hiddenContextMode()){ // don't actually scroll in hidden context mode
Session.set('currentY', y);
return Meteor.defer(options.complete);
}
if ((options.force) || Session.get("currentY") !== y){
var verticalHeights;
verticalHeights = window.getVerticalHeights();
$('body,html').animate({
scrollTop: verticalHeights[y]
}, 500, 'easeInExpo', function() {
Session.set("currentY", y);
Meteor.setTimeout(function(){
options.complete();
});
});
} else {
options.complete();
}
};
window.goToX = function(x) {
currentXByYId = Session.get("currentXByYId");
currentXByYId[Session.get("currentYId")] = x;
Session.set("currentXByYId", currentXByYId);
};
window.goToContext = function(id) {
var contextIndex, currentVertical, currentY, story;
if (id) {
currentY = Session.get('currentY');
contextIndex = _.indexOf(_.pluck(Session.get('horizontalSectionsMap')[currentY].horizontal, '_id'), id.toString());
if (contextIndex >= 0) {
if (hiddenContextMode()){
Session.set('hiddenContextShown', true);
}
return goToX(contextIndex);
}
}
};
window.goDownOneCard = function() {
var currentY, newY;
currentY = Session.get("currentY");
if (typeof currentY !== 'number'){
return goToXY(0, 0);
}
newY = currentY + 1;
if (newY < Session.get("story").verticalSections.length){
return goToY(newY);
}
};
window.goUpOneCard = function() {
var currentY, newY;
currentY = Session.get("currentY");
newY = currentY - 1;
if (newY >= 0)
return goToY(newY);
};
window.goRightOneCard = function() {
var currentX, horizontalSection, newX;
var currentY = Session.get("currentY");
var h = Session.get("horizontalSectionsMap")[currentY];
if(!h){
return
}
horizontalSection = h.horizontal;
currentX = Session.get("currentX");
currentYId = Session.get("currentYId");
if (currentX === (horizontalSection.length - 1)) { // end of our rope
newX = 0;
wrap = Session.get("wrap");
wrap[currentYId] = true;
Session.set("wrap", wrap);
} else {
newX = currentX + 1;
}
goToX(newX);
};
window.goLeftOneCard = function() {
var currentX, horizontalSection, newX;
var h = Session.get("horizontalSectionsMap")[Session.get("currentY")];
if(!h){
return
}
horizontalSection = h.horizontal;
currentX = Session.get("currentX");
newX = currentX ? currentX - 1 : horizontalSection.length - 1;
goToX(newX);
};
window.moveOneCard = function(d) {
if (d < 0) {
return goDownOneCard();
} else if (d > 0) {
return goUpOneCard();
}
};
window.horizontalExists = function(){
var currentY = Session.get('currentY');
return ((_ref = Session.get('horizontalSectionsMap')[currentY]) != null ? _ref.horizontal.length : void 0) > 1
};
Meteor.startup(function(){
$(document).keydown(function(e) {
var currentRoute = Router.current();
var routeName = currentRoute ? currentRoute.route.getName() : '';
if($(e.target).is('input, textarea')){
return
}
if ((routeName === 'read' || routeName === 'embed' || (routeName === 'edit' && Session.get('read'))) && !signingIn()){
var letter = String.fromCharCode(e.keyCode);
switch(letter){
case 'J':
goDownOneCard();
break;
case 'K':
goUpOneCard();
break;
case 'H':
if(Session.get('pastHeader')){
goLeftOneCard();
}
break;
case 'L':
if(Session.get('pastHeader')) {
goRightOneCard();
}
break;
case '%': // left arrow
if(Session.get('pastHeader')){
goLeftOneCard();
}
break;
case '\'': // right arrow
if(Session.get('pastHeader')) {
goRightOneCard();
}
break;
case ' ': // spacebar
break;
}
} else if (signingIn() && Session.equals('signinStage', 'signup')){
if(e.keyCode === 27){ // esc
closeSignInOverlay();
}
}
});
});
window.resetXPositionMemory = function () {
Session.set("wrap", {});
Session.set("currentXByYId", {});
};
window.getXByYId = function(yId) {
if(yId){
var currentXByYId = Session.get('currentXByYId');
if(currentXByYId){
return currentXByYId[yId] || 0;
}
}
};
<|start_filename|>server/user-methods.js<|end_filename|>
var TWITTER_API_KEY = process.env.TWITTER_API_KEY || Meteor.settings.TWITTER_API_KEY;
var TWITTER_API_SECRET = process.env.TWITTER_API_SECRET || Meteor.settings.TWITTER_API_SECRET;
import Twit from 'twit';
var makeTwitterCall = function (apiCall, params) {
var res;
var user = Meteor.user();
var client = new Twit({
consumer_key: TWITTER_API_KEY,
consumer_secret: TWITTER_API_SECRET,
access_token: user.services.twitter.accessToken,
access_token_secret: user.services.twitter.accessTokenSecret
});
var twitterResultsSync = Meteor.wrapAsync(client.get, client);
try {
res = twitterResultsSync(apiCall, params);
}
catch (err) {
if (err.statusCode !== 404) {
throw err;
}
res = {};
}
return res;
};
Meteor.methods({
updateInitialTwitterUserInfo: function (userInfo) {
check(userInfo, Object);
var user = Meteor.user();
if (!user.tempUsername) {
return
}
var username = userInfo.username,
email = userInfo.email;
if (!email) {
throw new Meteor.Error('Please enter your email');
}
check(username, String);
check(email, String);
checkUserSignup(username, email);
//get twitter info
var res;
if (user.services.twitter) {
var twitterParams = {
user_id: user.services.twitter.id
};
try {
res = makeTwitterCall("users/show", twitterParams);
}
catch (err) {
res = {};
}
}
var bio = (res && res.description) ? res.description : "";
var success = Meteor.users.update({
_id: this.userId
}, {
$set: {
"profile.name": userInfo.name || username,
"displayUsername": username,
"username": username,
"profile.bio": bio
},
$unset: {"tempUsername": ""},
$push: {
"emails": {"address": userInfo.email, "verified": false}
}
});
if(success){
Meteor.defer(() => {
sendWelcomeEmail(Meteor.users.findOne(this.userId));
});
}
return success
},
setBioFromTwitter: function () {
var user = Meteor.user();
if (user && user.profile && user.services.twitter) {
var res;
var twitterParams = {
user_id: user.services.twitter.id
};
res = makeTwitterCall("users/show", twitterParams);
var bio = res.description;
if (bio) {
return Meteor.users.update({
_id: this.userId
}, {
$set: {
"profile.bio": bio
}
});
}
}
},
validateUserInfo: function(userInfo){
check(userInfo.email, String);
userInfo.emails = [{address: userInfo.email}];
return validateNewUser(userInfo);
},
unsubscribe (emailType){
check(emailType, String);
return Meteor.users.update({
_id: this.userId
}, {
$addToSet: {
"unsubscribes": emailType
}
});
},
resubscribe (emailType){
check(emailType, String);
return Meteor.users.update({
_id: this.userId
}, {
$pull: {
"unsubscribes": emailType
}
});
}
});
<|start_filename|>lib/constants.js<|end_filename|>
PUB_SIZE = 30;
if (Meteor.isClient){
window.PUB_SIZE = PUB_SIZE;
}
CLOUDINARY_FILE_SIZE = 20000000; // bytes
VIEW_THRESHOLDS = [
25,
50,
75,
100,
150,
200,
250,
300,
350,
400,
450,
500,
600,
700,
800,
900,
1000,
1250,
1500,
1750,
2000,
2250,
2500,
2750,
3000,
3250,
3500,
3750,
4000,
4250,
4500,
4750,
5000,
5500,
6000,
6500,
7000,
7500,
8000,
8500,
9000,
9500,
10000,
11000,
12000,
13000,
14000,
15000,
20000,
30000,
40000,
50000,
60000,
70000,
80000,
90000,
100000,
200000,
500000,
1000000
];
<|start_filename|>server/context-methods.js<|end_filename|>
var BAMBUSER_API_KEY = Meteor.settings.BAMBUSER_API_KEY;
var USTREAM_DATA_API_KEY = Meteor.settings.USTREAM_DATA_API_KEY;
var GOOGLE_API_SERVER_KEY = Meteor.settings.GOOGLE_API_SERVER_KEY;
var SOUNDCLOUD_CLIENT_ID = Meteor.settings.SOUNDCLOUD_CLIENT_ID;
var IMGUR_CLIENT_ID = Meteor.settings.IMGUR_CLIENT_ID;
var FLICKR_API_KEY = Meteor.settings.FLICKR_API_KEY;
var GIPHY_API_KEY = Meteor.settings.GIPHY_API_KEY;
var TWITTER_API_KEY = process.env.TWITTER_API_KEY || Meteor.settings.TWITTER_API_KEY;
var TWITTER_API_SECRET = process.env.TWITTER_API_SECRET || Meteor.settings.TWITTER_API_SECRET;
var EMBEDLY_KEY = Meteor.settings.EMBEDLY_KEY;
var VIMEO_API_KEY = Meteor.settings.VIMEO_API_KEY;
var VIMEO_API_SECRET = Meteor.settings.VIMEO_API_SECRET;
var VIMEO_ACCESS_TOKEN = Meteor.settings.VIMEO_ACCESS_TOKEN;
import Twit from 'twit';
import { Vimeo } from 'vimeo-api';
if (!GOOGLE_API_SERVER_KEY) {
console.error('Settings must be loaded for apis to work');
throw new Meteor.Error('Settings must be loaded for apis to work');
}
var decrementByOne = function(bigInt) {
var intArr = bigInt.split("");
if (intArr.length === 1) {
return (intArr[0] -1).toString()
}
var result = [],
borrow = 0;
for (var i=intArr.length ; i--;) {
var temp = intArr[i] - borrow - (i === intArr.length -1 ? 1 :0) ;
borrow = temp < 0 ? 1 : 0;
result.unshift(((borrow * 10) + temp).toString());
}
return result.join("")
};
var makeTwitterCall = function(apiCall, params) {
var res;
var user = Meteor.user();
var client = new Twit({
consumer_key: TWITTER_API_KEY,
consumer_secret: TWITTER_API_SECRET,
access_token: user.services.twitter.accessToken,
access_token_secret: user.services.twitter.accessTokenSecret
});
var twitterResultsSync = Meteor.wrapAsync(client.get, client);
try {
res = twitterResultsSync(apiCall, params);
}
catch (err) {
if (err.statusCode !== 404) {
throw err;
}
res = {};
}
return res;
};
var searchYouTube = function (query, option, page) {
var res;
var nextPageToken;
check(query, String);
this.unblock();
requestParams = {
part: 'snippet',
q: query,
type: 'video',
videoEmbeddable: 'true',
maxResults: 50,
key: GOOGLE_API_SERVER_KEY
};
if (option === 'live'){
requestParams['eventType'] = 'live';
requestParams['safeSearch'] = 'none';
}
if (page) {
requestParams['pageToken'] = page;
}
res = HTTP.get('https://www.googleapis.com/youtube/v3/search', {
params: requestParams
});
items = _.chain(res.data.items)
.filter(function (element) {
return element.id.videoId;
})
.map(function (element) {
element.snippet.videoId = element.id.videoId;
return element.snippet;
})
.value();
if (items.length) {
nextPageToken = res.data.nextPageToken || 'end';
} else {
nextPageToken = 'end';
}
return {
'nextPage': nextPageToken,
'items': items
}
};
Meteor.methods({
///////////////////////////////////
/////// SEARCH API METHODS ///////
//////////////////////////////////
/*
input: (query, option, page (optional))
output: {items: [..], nextPage: any constant value})
*/
flickrImageSearchList: function (query, option, page) {
var items, nextPage, linkSearch, path, requestParams;
check(query, String);
if ((query.indexOf('flickr.com') !== -1) && (query.indexOf('/photos/') !== -1)) {
//search photo: flickr.com/photos/{user-id}/{photo-id}/in/photolist-{search-info}
//individual photo: flickr.com/photos/{user-id}/{photo-id}
var split = _.compact(query.split('/'));
var offset = split.indexOf('photos');
if (split[offset + 2]) {
var photo_id = (split[offset + 2]).match(/[\d]*/)[0];
linkSearch = true;
} else {
linkSearch = false;
}
} else if ((query.indexOf('flic.kr') !== -1) && (query.indexOf('/p/') !== -1)) {
//short url: https://flic.kr/p/{base58-photo-id}
var photo_id = _.chain(query.split('/')).compact().last().value().match(/[\d\w]*/)[0];
linkSearch = true;
} else {
linkSearch = false;
}
page = page || 1; // flickr starts from 1
this.unblock();
if (linkSearch) {
path = 'flickr.photos.getInfo';
requestParams = {
photo_id: photo_id,
api_key: FLICKR_API_KEY,
format: 'json',
nojsoncallback: 1
};
} else {
path = 'flickr.photos.search';
requestParams = {
tags: query.replace(' ', ','),
text: query,
api_key: FLICKR_API_KEY,
format: 'json',
privacy_filter: 1,
media: 'photos',
nojsoncallback: 1,
sort: 'relevance',
license: '1,2,3,4,5,6,7,8',
per_page: 200,
extras: ['date_upload', 'owner_name', 'description','tags', 'url_z', 'url_c', 'url_l', 'url_h', 'url_k', 'url_o'],
page: page
};
}
var url = "https://api.flickr.com/services/rest/?&method=" + path;
var res = HTTP.get(url, {
params: requestParams
});
if (res.data) {
var results = res.data;
}
if (results && (results.photos)) {
items = results.photos.photo;
} else if (results && results.photo) {
items = [results.photo];
} else {
items = []
}
if (items.length) {
nextPage = page + 1;
} else {
nextPage = 'end';
}
return {
'items': items,
'nextPage': nextPage
};
},
imgurImageSearchList: function (query, option, page) {
var res;
var fullSearchItems;
check(query, String);
this.unblock();
var nextPage;
page = page || 0;
var authorizationStr = "Client-ID " + IMGUR_CLIENT_ID;
var urlItems = [];
if (query.indexOf('imgur.com') !== -1) { // if paste in an image link, just grab it
var id = _.chain(query.split('/')).compact().last().value().split('.')[0]; // if it's a url just send the final path segment without any extension;
try {
res = HTTP.get("https://api.imgur.com/3/image/" + id, {
headers: {"Content-Type": "text", "Authorization": authorizationStr}
});
} catch (err) {
if (!err.response || err.response.statusCode !== 404) { // swallow 404's, rethrow others
throw err;
}
}
if (res.data && res.data.data) {
urlItems[0] = res.data.data;
}
}
requestParams = {
q: query
};
var url = 'https://api.imgur.com/3/gallery/search/top/' + page;
// https://api.imgur.com/endpoints/gallery
var res = HTTP.get(url, {
params: requestParams,
headers: {"Content-Type": "text", "Authorization": authorizationStr}
});
if (res.data && res.data.data) {
fullSearchItems = _.filter(res.data.data, function (e) {
return (e.type && e.type.indexOf('image') === 0)
});
if (fullSearchItems.length) {
nextPage = page + 1;
} else {
nextPage = 'end'
}
} else {
fullSearchItems = []
}
if (!fullSearchItems.length) {
nextPage = 'end'
}
return {
nextPage: nextPage,
items: urlItems.concat(fullSearchItems)
}
},
giphyGifSearchList: function (query, option, page) {
var res;
var items;
var nextPage;
check(query, String);
this.unblock();
page = page || 0;
requestParams = {
q: query,
api_key: GIPHY_API_KEY,
offset: page,
limit: 50
};
var urlItems = [];
if (query.indexOf('giphy.com') !== -1) { // if paste in an gif link, query for the id from the url
var pathSegment = _.chain(query.split('/')).compact().last().value();
var id = _.last(pathSegment.split('-')).match(/[\w]*/)[0]; // if it's a url just send the id at the end of the path segment without any extension;
var res;
try {
res = HTTP.get('http://api.giphy.com/v1/gifs/' + id, {
params: {
api_key: GIPHY_API_KEY
}
});
} catch (err) {
if (!err.response || err.response.statusCode !== 404) { // swallow 404's, rethrow others
throw err;
}
}
if (res.data && res.data.data) {
urlItems[0] = res.data.data;
}
}
var res = HTTP.get('http://api.giphy.com/v1/gifs/search', {
params: requestParams
});
var data = res.data;
if (data.data) {
items = data.data;
} else {
items = [];
}
if (items.length && data.pagination) {
var totalCount = data.pagination.total_count;
nextPage = data.pagination.count + data.pagination.offset;
if (nextPage >= totalCount) {
nextPage = 'end';
}
} else {
nextPage = 'end';
}
return {
nextPage: nextPage,
items: urlItems.concat(items)
}
},
soundcloudAudioSearchList: function (query, option, page) {
var res;
var items, nextPage, linkSearch, path, requestParams;
check(query, String);
if (query.indexOf('soundcloud.com') !== -1) {
linkSearch = true;
} else {
linkSearch = false;
}
var offset = page || 0;
var limit = 50;
if (linkSearch) {
path = 'resolve';
requestParams = {
url: query,
client_id: SOUNDCLOUD_CLIENT_ID
};
} else {
path = 'tracks';
requestParams = {
q: query,
limit: limit,
offset: offset,
client_id: SOUNDCLOUD_CLIENT_ID
};
}
this.unblock();
var res = HTTP.get('http://api.soundcloud.com/' + path + '.json', {
params: requestParams
});
var results;
if (res && res.data) {
results = res.data.length ? res.data : [res.data];
if (results && (results[0].kind === 'track')) {
items = results;
} else {
items = [];
}
} else {
items = [];
}
if (items.length) {
nextPage = offset + limit;
} else {
nextPage = 'end';
}
return {
'nextPage': nextPage,
'items': items
}
},
twitterSearchList: function (query, option, page) {
var res;
var items = [];
var isId = false;
check(query, String);
if (query.indexOf('twitter.com') !== -1) {
var newQuery = _.chain(query.split('/')).compact().last().value().match(/[\d\w_]*/)[0];
query = newQuery || query;
isId = (/^\d+$/).test(query);
}
this.unblock();
count = 30;
var api = {
'all': 'search/tweets',
'all_url': 'statuses/show',
'user': 'statuses/user_timeline',
'favorites': 'favorites/list'
};
params = {count: count};
if (page) {
params['max_id'] = page;
}
if (option === 'all' && isId) {
option = 'all_url';
params['id'] = query;
} else if (option === 'all') {
params['q'] = query;
} else {
params['screen_name'] = query;
}
res = makeTwitterCall(api[option], params);
if (option === 'all_url') {
items[0] = res;
page = "end";
} else if (option === 'all') {
items = res.statuses;
page = res.search_metadata.next_results ? res.search_metadata.next_results.match(/\d+/)[0] : "end";
} else if (res.length) {
items = res;
page = decrementByOne(items[items.length - 1].id_str);
}
searchResults = {
nextPage: page,
items: items
};
return searchResults;
},
embedlyEmbedResult: function (url) {
var res, requestParams;
check(url, String);
this.unblock();
requestParams = {
url: url.trim(),
key: EMBEDLY_KEY,
maxheight: 300,
maxwidth: 474
};
res = HTTP.get('http://api.embed.ly/1/oembed', {
params: requestParams
});
return res.data;
},
embedlyExtractResult: function (url) {
var res, requestParams;
check(url, String);
this.unblock();
requestParams = {
url: url.trim(),
key: EMBEDLY_KEY,
maxheight: 300,
maxwidth: 474 // TODO update for deepstream
};
res = HTTP.get('http://api.embed.ly/1/extract', {
params: requestParams
});
return res.data;
},
vimeoVideoSearchList: function (query, option, page) {
var items;
var nextPage;
var path = '/videos';
check(query, String);
if (query.indexOf('vimeo.com') !== -1) {
var newQuery = _.chain(query.split('/')).compact().last().value().match(/[\d]*/)[0];
path = path + '/' + newQuery;
}
this.unblock();
page = page || 1;
var client = new Vimeo(
VIMEO_API_KEY,
VIMEO_API_SECRET,
VIMEO_ACCESS_TOKEN
);
var vimeoResultsSync = Meteor.wrapAsync(client.request, client);
var params = {
path: path,
query: {
query: query,
sort: 'relevant',
page: page,
per_page: 40
}
};
try {
res = vimeoResultsSync(params);
items = res.data || [res];
}
catch (err) {
if (err.statusCode !== 404) {
throw err;
}
items = [];
}
if (items.length) {
nextPage = page + 1;
} else {
nextPage = 'end';
}
return {
'items': items,
'nextPage': nextPage
};
},
streamSearchList: function(query, option, page){
var youtubeResults;
if (!page) {
page = {
ustream: 0
}
}
if (page.youtube !== 'end'){
youtubeResults = searchYouTube.call(this, query, 'live', page.youtube || null);
_.each(youtubeResults.items, function(item){
_.extend(item, { _source: 'youtube'})
});
} else { // youtube results are over
youtubeResults = {
items: [],
nextPage: 'end'
}
}
var ustreams;
if(page.ustream !== 'end'){
// ustream
var limit = 50;
var options = {
limit: limit,
sort: {
currentViewers: -1
},
skip: page.ustream * limit
};
function buildRegExp(query) {
// this is a dumb implementation
var parts = query.trim().split(/[ \-\:]+/);
return new RegExp("(" + parts.join('|') + ")", "ig");
}
var regExp = buildRegExp(query);
var selector = {$or: [
{title: regExp},
{description: regExp},
{username: regExp}
//{ $text: { $search: query, $language: 'en' } }
]};
ustreams = Streams.find(selector, options).fetch();
} else {
ustreams = [];
}
// compile nextPage for each source
var nextPage = {
youtube: youtubeResults.nextPage
};
if(ustreams.length){
nextPage.ustream = page.ustream + 1;
} else {
nextPage.ustream = 'end';
}
var allSourcesExhausted = _.chain(nextPage)
.values()
.uniq()
.every(function(v){
return v == 'end'
})
.value();
if(allSourcesExhausted){
nextPage = 'end';
}
// mix streams from various sources
var items = _.chain(youtubeResults.items)
.zip(ustreams)
.flatten()
.compact()
.value();
return {
items: items,
nextPage: nextPage
}
},
youtubeVideoSearchList: searchYouTube,
bambuserVideoSearchList: function (query, option, page) {
var res;
var nextPageToken;
check(query, String);
this.unblock();
requestParams = {
tag: query.replace(' ', ','),
type: 'live', // or archived. default is both
limit: 10,
api_key: BAMBUSER_API_KEY
// username,
// max_age,
// geo_distace/lat/lon
};
page = page || 0;
if (page) {
requestParams['page'] = page;
}
res = HTTP.get('http://api.bambuser.com/broadcast.json', {
params: requestParams
});
items = res.data.result;
if (items && items.length) {
nextPageToken = page + 1;
} else {
nextPageToken = 'end';
}
return {
'nextPage': nextPageToken,
'items': items
}
},
ustreamVideoSearchList: function (query, option, page) {
var res;
var nextPageToken;
check(query, Match.Optional(String));
this.unblock();
requestParams = {
limit: 100,
key: USTREAM_DATA_API_KEY
};
var kindOfThingToSearch = 'channel'; // channel, user
var sortBy = 'popular'; // live, recent
var searchString = 'all'; //'title:like:' + query; // targetProperty:comparison:targetValue or all
page = page || 1;
requestParams['page'] = page;
res = HTTP.get('http://api.ustream.tv/json/' + kindOfThingToSearch + '/' + sortBy + '/search/' + searchString, {
params: requestParams
});
//console.log('aaaaaaaaaaa')
//console.log(res)
items = res.data.results;
if (items && items.length) {
nextPageToken = page + 1;
} else {
nextPageToken = 'end';
}
return {
'nextPage': nextPageToken,
'items': items
}
}
});
<|start_filename|>lib/router.js<|end_filename|>
var setTitle = function(pageName){
if (Meteor.isClient){
var title;
if(pageName) {
title = pageName + ' - FOLD';
} else {
title = 'FOLD';
}
document.title = title;
$('meta[property="og:title"]').attr('content', pageName);
$('meta[name="twitter:title"]').attr('content', pageName);
}
};
var setMetaImage = function(imageUrl){
if (Meteor.isClient){
if (imageUrl){
$('meta[property="og:image"]').attr('content', imageUrl.replace(/^\/\//, "https://")); // replace protocol-less url with https
$('meta[property="og:image:secure_url"]').attr('content', imageUrl.replace(/^\/\//, "https://")); // replace protocol-less url with https
$('meta[name="twitter:image"]').attr('content', imageUrl.replace(/^\/\//, "https://")); // replace protocol-less url with https
} else {
$('meta[property="og:image"]').attr('content', "http://res.cloudinary.com/fold/image/upload/v1/static/FOLD_fb_image.png");
$('meta[property="og:image:secure_url"]').attr('content', "https://res.cloudinary.com/fold/image/upload/v1/static/FOLD_fb_image.png");
$('meta[name="twitter:image"]').attr('content', "https://res.cloudinary.com/fold/image/upload/v1/static/FOLD_twitter_image.png");
}
}
};
var setMetaDescription = function(desc){
if (Meteor.isClient){
if (desc){
$('meta[name="description"]').attr('content', desc);
$('meta[property="og:description"]').attr('content', desc);
$('meta[name="twitter:description"]').attr('content', desc);
} else {
$('meta[name="description"]').attr('content', 'Reading, authoring, and publishing platform allowing storytellers to structure and contextualize stories.');
$('meta[property="og:description"]').attr('content', 'Reading, authoring, and publishing platform allowing storytellers to structure and contextualize stories.');
$('meta[name="twitter:description"]').attr('content', 'Reading, authoring, and publishing platform allowing storytellers to structure and contextualize stories.');
}
}
};
var setStatusCode = function(statusCode){
if (Meteor.isClient){
if(!statusCode){
statusCode = '200';
}
$('meta[name=prerender-status-code]').remove();
$('head').append('<meta name="prerender-status-code" content="' + statusCode + '">');
}
};
var longTermSubs = new SubsManager({
cacheLimit: 9999,
expireIn: 9999
});
var shortTermSubs = new SubsManager({
cacheLimit: 1,
expireIn: 1
});
Router.route("home", {
path: "/",
template: "home",
action () {
if (this.ready()) {
setTitle();
setMetaImage();
setMetaDescription();
setStatusCode();
return this.render();
}
},
waitOn (){
return [shortTermSubs.subscribe('curatedAndUserFollowingStoriesPub', {preview: true})];
},
fastRender: true,
data () {},
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
}
});
Router.route("about", {
path: "/about",
onBeforeAction (){
this.redirect("/read/FOLD/what-is-fold-TiyWEK6C", {}, {
replaceState: true
});
},
action () {
if (this.ready()) {
setTitle('About');
setMetaImage();
setMetaDescription();
setStatusCode();
return this.render();
}
},
data () {},
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
}
});
Router.route("terms", {
path: "/terms",
template: "terms",
action () {
if (this.ready()) {
setTitle('Terms');
setMetaImage();
setMetaDescription();
setStatusCode();
return this.render();
}
},
data () {},
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
}
});
Router.route("privacy", {
path: "/privacy",
template: "privacy",
action () {
if (this.ready()) {
setTitle('Privacy Policy');
setMetaImage();
setMetaDescription();
setStatusCode();
return this.render();
}
},
data () {},
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
}
});
Router.route("profile", {
path: "/profile/:username", // can put in display username
template: "profile",
action () {
if (this.ready()) {
setTitle(this.params.username + "'s Profile");
setMetaImage();
setMetaDescription();
return this.render();
}
},
waitOn () {
var username = this.params.username.toLowerCase();
var subs = [Meteor.subscribe('userProfilePub', username),
Meteor.subscribe('userStoriesPub', username)];
var user = Meteor.user();
if(user && Meteor.user().username === username){ // if users own profile
subs.push(Meteor.subscribe('myStoriesPub'));
}
return subs;
},
data () {
var username = this.params.username.toLowerCase();
var user;
if (this.ready()) {
user = Meteor.users.findOne({username : username});
if (user) {
setStatusCode();
return {
user : user
}
} else {
setStatusCode("404");
this.render("user_not_found");
// TODO add 404 tags for seo etc...
}
}
},
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
}
});
Router.route("reset_password", {
path: "/reset-password/:resetPasswordToken",
template: "reset_password",
data () {
Session.set("resetPasswordToken", this.params.resetPasswordToken);
},
action () {
if (this.ready()) {
setTitle('Reset Password');
setMetaImage();
setMetaDescription();
setStatusCode();
return this.render();
}
},
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
}
});
Router.route("my_story_profile", {
path: "/my-stories",
template: "my_story_profile",
waitOn () {
return [Meteor.subscribe('myStoriesPub')];
},
action () {
if (this.ready()) {
setTitle('My Stories');
setMetaImage();
setMetaDescription();
setStatusCode();
return this.render();
}
},
onBeforeAction () {
var user;
if ((user = Meteor.user()) || Meteor.loggingIn()) {
return this.next();
} else {
this.redirect("home", {}, {
replaceState: true
});
return notifyInfo("You must be logged in to view your stories");
}
},
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
}
});
var readSubs = new SubsManager({
cacheLimit: 1,
expireIn: 1
});
var readRouteDetails = {
template: "read",
waitOn () { // subscribe and wait for story if don't have it yet
var shortId = idFromPathSegment(this.params.storyPathSegment);
if (Meteor.isClient) { // if full ready story is already loaded due to visiting homepage, don't wait for it
var story = Stories.findOne({shortId: shortId}, {reactive: false, fields: {verticalSections: 1}});
if (story && story.verticalSections) { // confirm that full "read story" is loaded
return [];
}
}
return [readSubs.subscribe('readStoryPub', this.params.userPathSegment, shortId)];
},
action () {
if (this.ready()) {
return this.render();
}
},
fastRender: true,
data () {
var story;
if (this.ready()){
var shortId = idFromPathSegment(this.params.storyPathSegment);
story = Stories.findOne({shortId: shortId}, {reactive: false});
if (story) {
Session.set("story", story);
Session.set("storyId", story._id);
Session.set("storyShortId", shortId);
Session.set("headerImage", story.headerImage);
Session.set("horizontalSectionsMap", _.map(_.pluck(story.verticalSections, "contextBlocks"), function (cBlockIds, i) {
var id = story.verticalSections[i]._id;
return {
verticalIndex: i,
activeHeartbeats: story.analytics.heartbeats ? story.analytics.heartbeats.active[id] : 0,
horizontal: _.map(cBlockIds, function (id, j) {
return {
_id: id,
verticalIndex: i,
horizontalIndex: j,
activeHeartbeats: story.analytics.heartbeats ? story.analytics.heartbeats.active[id] : 0
}
})
};
}));
setTitle(story.title);
setMetaImage(story.headerImageUrl());
setMetaDescription(story.contentPreview());
setStatusCode();
return story;
} else {
setTitle("Story not found");
setMetaImage();
setMetaDescription();
setStatusCode("404");
this.render("story_not_found");
// TODO add 404 tags for seo etc...
}
}
},
onRun (){
resetXPositionMemory();
Session.set("showMinimap", true);
Session.set("hiddenContextShown", false);
Session.set("currentY", null);
Session.set("previousY", null);
Session.set("previousXId", null);
Session.set("contextOverlayId", null);
Session.set("scrollTop", 0);
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
},
onAfterAction (){
Session.set("showDraft", false);
}
};
Router.route("read", _.extend({
path: "/read/:userPathSegment/:storyPathSegment",
onBeforeAction () {
if(embedMode()){
this.redirect('embed', this.params, {replaceState: true})
return this.next();
}
Session.set("newStory", false);
Session.set("read", true);
return this.next();
}
}, readRouteDetails));
Router.route("embed", _.extend({
path: "/embed/:userPathSegment/:storyPathSegment",
onBeforeAction () {
Session.set("newStory", false);
Session.set("read", true);
activateEmbedMode();
return this.next();
}
}, readRouteDetails));
var draftStoryRouteObject = {
data () {
var story;
if (this.ready()) {
var shortId = idFromPathSegment(this.params.storyPathSegment);
story = Stories.findOne({shortId: shortId});
if (story && story.draftStory) {
Session.set("story", story.draftStory);
Session.set("storyId", story._id);
Session.set("storyShortId", shortId);
Session.set("storyPublished", story.published);
Session.set("headerImage", story.draftStory.headerImage);
Session.set("userPathSegment", this.params.userPathSegment);
Session.set("horizontalSectionsMap", _.map(_.pluck(story.draftStory.verticalSections, "contextBlocks"), function (cBlockIds, i) {
return {
verticalIndex: i,
horizontal: _.map(cBlockIds, function (id, i) {
return {
_id: id,
horizontalIndex: i
}
})
};
}));
setTitle('Editing: ' + story.draftStory.title || 'a new story');
setStatusCode();
return story;
} else {
setTitle('Story not found');
setStatusCode('404');
this.render("story_not_found");
// TODO add 404 tags for seo etc...
}
}
},
onRun (){
resetXPositionMemory();
Session.set("currentY", null);
Session.set("previousY", null);
Session.set("previousXId", null);
Session.set("contextOverlayId", null);
Session.set("read", false);
Session.set("newStory", false);
Session.set("showDraft", true);
Session.set("showMinimap", true);
Session.set('saveState', 'saved');
Session.set('scrollTop', 0);
Meteor.defer(function(){
$(window).scrollTop(0);
});
if(!window.isChrome){
notifyBrowser();
}
if (Meteor.isClient){
window.readyToMigrate.set(false);
}
this.next();
},
action () {
if (this.ready()) {
setMetaImage();
setMetaDescription();
setStatusCode();
return this.render();
}
}
};
Router.route("edit", _.extend({}, draftStoryRouteObject, {
path: "/create/:userPathSegment/:storyPathSegment",
template: "create",
waitOn () {
shortId = idFromPathSegment(this.params.storyPathSegment);
return [Meteor.subscribe('createStoryPub', this.params.userPathSegment, shortId), Meteor.subscribe('contextBlocksPub', shortId)];
},
onBeforeAction () {
if(embedMode()){
this.redirect('embed', this.params, {replaceState: true});
return this.next();
}
var user, data;
if ((user = Meteor.user()) || Meteor.loggingIn()) { // if there is a user
data = this.data();
if (user && data && user._id !== data.authorId) { // if they don't own the story take them to story not found
return this.render("story_not_found");
}
var accessPriority = Meteor.user().accessPriority;
if (!accessPriority || accessPriority > window.createAccessLevel){
this.redirect("home", {}, {
replaceState: true
});
notifyInfo("Creating and editing stories is temporarily disabled, possibly because things blew up (in a good way). Sorry about that! We'll have everything back up as soon as we can. Until then, why not check out some of the other great content authors in the community have written?")
}
return this.next(); // if they do own the story, let them through to create
} else {
openSignInOverlay(); // if there is no user, take them to the signin page
this.redirect("home", {}, { // TO-DO, after they sign in, they should get back to the create page
replaceState: true
});
return this.next();
}
}
}));
Router.route("admin-read-draft", _.extend({}, draftStoryRouteObject, {
path: "/admin/read-draft/:storyPathSegment",
template: "create",
waitOn () {
shortId = idFromPathSegment(this.params.storyPathSegment);
return [Meteor.subscribe('adminReadDraftPub', shortId), Meteor.subscribe('adminContextBlocksPub', shortId)];
},
onBeforeAction () {
var user, data;
if ((user = Meteor.user()) || Meteor.loggingIn()) { // if there is a user
if(user.admin){
return this.next(); // if they are an admin, let them through
}
}
}
}));
Router.route("/unsubscribe", {
path: "/unsubscribe",
template: "unsubscribe",
triggersEnter: [function(){
$('html, body').scrollTop(0);
}]
});
// handle user bailing in middle of twitter signup, before a username is chosen. this probably only happens on page load or reload.
Router.onBeforeAction(function() {
setTimeout(() => {
var user = Meteor.user();
var currentRoute = this.route.getName();
if (user && currentRoute){
if(!user.username && currentRoute !== 'twitter-signup'){ // if user has no username, confirm they are on the page where they can fill that out
Meteor.logout(); // otherwise log them out
setTimeout(() => {
throw new Meteor.Error('Forcibly logged out user, presumably because they did not finish twitter signup (setting username etc...)');
}, 0);
}
}
}, 100); // this might even be ok when set to 0
this.next()
});
Router.route("admin", {
path: "admin",
template: "admin",
waitOn () {
if (Meteor.user() && Meteor.user().admin) {
return [Meteor.subscribe('adminMostFavoritesUsersPub')];
}
},
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
},
onBeforeAction () {
var user, data;
if ((user = Meteor.user()) || Meteor.loggingIn()) { // if there is a user
if(user.admin){
return this.next(); // if they are an admin, let them through
}
}
}
});
Router.route("admin-recent-drafts", {
path: "/admin/recent-drafts",
template: "admin_recent_drafts",
action () {
if (this.ready()) {
setTitle('Most recent drafts');
setMetaImage();
setMetaDescription();
setStatusCode();
return this.render();
}
},
onBeforeAction () {
var user, data;
if ((user = Meteor.user()) || Meteor.loggingIn()) { // if there is a user
if(user.admin){
return this.next(); // if they are an admin, let them through
}
}
},
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
}
});
Router.route("admin-recent-activities", {
path: "/admin/recent-activities",
template: "admin_recent_activities",
action () {
if (this.ready()) {
setTitle('Most recent activities');
setMetaImage();
setMetaDescription();
setStatusCode();
return this.render();
}
},
onBeforeAction () {
var user, data;
if ((user = Meteor.user()) || Meteor.loggingIn()) { // if there is a user
if(user.admin){
return this.next(); // if they are an admin, let them through
}
}
},
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
}
});
Router.route("stats", {
path: "stats",
template: "stats",
onRun (){
Meteor.defer(function(){
$(window).scrollTop(0);
});
this.next();
}
});
//Router.route("loading", {
// path: "loading",
// template: "loading_page"
//});
Router.configure({
waitOn () {
return [
Meteor.subscribe('userData')
]
},
loadingTemplate: 'loading_page',
notFoundTemplate: "not_found"
});
// if embed but not a story, just take 'em to the about story
Router.onBeforeAction(function(){
if (embedMode()) {
var routeName = Router.current().route.getName();
if (!_.contains(['edit', 'read', 'embed'], routeName)){
this.redirect("about", {}, {replaceState: true});
}
}
this.next();
});
<|start_filename|>client/admin.js<|end_filename|>
Template.admin.helpers({
usersWhoLoveStories (){
return _.sortBy(Meteor.users.find().fetch(), function(e){ return -1 * e.profile.favorites.length })
},
emailAddress () {
if (this.emails) {
return this.emails[0].address;
}
},
twitterHandle () {
if (this.services && this.services.twitter && this.services.twitter.screenName) {
return '@' + this.services.twitter.screenName;
}
}
});
Template.admin.events({
'keypress .impersonate' (e,t) {
if(enterPress(e)){
var username = t.$('input.impersonate').val();
Meteor.call('impersonate', username, function (err, userId) {
if(err){
notifyError(err)
} else {
Meteor.connection.setUserId(userId);
notifySuccess("Ok you're in! Be very very careful.");
Router.go('/');
}
});
}
}
});
Template.read_admin_ui.helpers({
emailAddress () {
var user = Meteor.users.findOne(this.authorId);
if (user && user.emails) {
return user.emails[0].address;
}
},
twitterHandle () {
var user = Meteor.users.findOne(this.authorId);
if (user && user.services && user.services.twitter) {
return '@' + user.services.twitter.screenName;
}
}
});
Template.admin_recent_drafts.helpers({
recentDrafts () {
return Stories.find({
published : false
}, {
sort: {
savedAt: -1
}
}
);
}
});
Template.admin_recent_drafts.events({
'click .show-more' (){
Session.set("adminRecentDraftsMore", Session.get("adminRecentDraftsMore") + 1);
}
});
Template.admin_recent_drafts.onCreated(function(){
Session.setDefault('adminRecentDraftsMore', 0);
this.autorun(() => {
this.subscribe("adminRecentDraftsPub", {more: Session.get("adminRecentDraftsMore")})
});
});
Template.admin_recent_activities.onCreated(function(){
Session.setDefault('adminRecentActivitiesMore', 0);
this.autorun(() => {
this.subscribe("adminRecentActivitiesPub", {more: Session.get("adminRecentActivitiesMore")})
});
});
Template.admin_recent_activities.events({
'click .show-more' (){
Session.set("adminRecentActivitiesMore", Session.get("adminRecentActivitiesMore") + 1);
}
});
Template.admin_recent_activities.helpers({
activities (){
return Activities.find({}, {sort: {published: -1}});
}
});
<|start_filename|>collections/user-methods.js<|end_filename|>
Meteor.methods({
saveProfilePicture (userId, pictureId) {
check(userId, String);
check(pictureId, String);
if (this.userId === userId) {
Meteor.users.update({
_id: this.userId
}, {
$set: {
"profile.profilePicture": pictureId
}
});
} else {
throw new Meteor.Error("Only the account owner may edit this profile")
}
},
updateProfile (modifier, userId) { // TO-DO cleanup
check(userId, String);
check(modifier, Object);
var bio, name, newName;
var modifierSet = modifier.$set;
var modifierUnset = modifier.$unset;
var setObject = {};
if (bio = modifierSet['profile.bio']) {
check(bio, String);
setObject['profile.bio'] = bio;
} else if (modifierUnset['profile.bio'] === "") {
setObject['profile.bio'] = '';
}
if (name = modifierSet['profile.name']) {
check(name, String);
setObject['profile.name'] = name;
} else if (modifierUnset['profile.name'] === "") {
setObject['profile.name'] = '';
}
if (this.userId === userId) {
if (newName = setObject['profile.name']) {
if (newName !== Meteor.user().profile.name) {
Stories.update({authorId: this.userId}, { // update authorName on stories if name changed
$set: {
authorName: newName
}
})
}
}
Meteor.users.update({
_id: this.userId
}, {
$set: setObject
});
} else {
throw new Meteor.Error("Only the account owner may edit this profile")
}
}
});
<|start_filename|>server/email.js<|end_filename|>
sendWelcomeEmail = function(user){ // this takes actual user instead of userId because user might be in process of being created in db
var email = user.emails[0].address;
var emailName = user.profile.name;
Mandrill.messages.sendTemplate({
template_name: 'welcome-e-mail',
template_content: [
],
message: {
to: [
{
email: email,
name: emailName
}
]
}
});
};
var emailTypeForUnsubscribe = function(emailType){
switch(emailType){
case 'followed-you-back':
return 'followed-you' // these are effectively the same
break;
default:
return emailType;
}
};
var getToFromUserIds = function(userIds, emailType){
var unsubscribeCheck = emailTypeForUnsubscribe(emailType);
var users = Meteor.users.find({_id: {$in: userIds}, unsubscribes: {$ne: unsubscribeCheck}}, {fields: {'emails': 1, 'profile.name': 1}});
return users.map(function(user){
return {
email: user.emails[0].address,
name: user.profile.name
}
});
};
var getMergeVarsFromObj = function(obj){
return _.chain(obj)
.pairs()
.map(function(pair){
return {
name: pair[0],
content: pair[1]
}
})
.value()
}
var sendEmail = function(emailType, userIds, subject, bareMergeVars){
var to = getToFromUserIds(userIds, emailType);
if(to.length === 0){
return
}
if(process.env.NODE_ENV === 'production'){
Mandrill.messages.sendTemplate({
template_name: emailType,
template_content: [
],
message: {
to: to,
subject: subject,
global_merge_vars: getMergeVarsFromObj(_.extend({ unsubscribeUrl: Meteor.absoluteUrl('unsubscribe?email_type=' + emailTypeForUnsubscribe(emailType))}, bareMergeVars))
},
preserve_recipients: false
});
} else {
console.log('Would have sent email')
console.log(arguments)
}
}
sendFollowingPublishedEmail = function(userIds, storyId){
var story = Stories.findOne(storyId, {fields: readStoryFields});
var title = story.title;
var authorName = story.authorName;
var longContentPreview = story.contentPreview();
var subject = authorName + ' just published "' + title + '" on FOLD';
var bareMergeVars = {};
bareMergeVars.title = title;
bareMergeVars.authorName = authorName;
bareMergeVars.subject = subject;
bareMergeVars.headerImageUrl = 'https:' + story.headerImageUrl();
if(longContentPreview){
bareMergeVars.contentPreview = longContentPreview.length > 203 ? longContentPreview.substring(0, 200).replace(/\s+\S*$/, "...") : longContentPreview;
}
bareMergeVars.profileUrl = Meteor.absoluteUrl('profile/' + (story.authorDisplayUsername || story.authorUsername));
bareMergeVars.storyUrl = Meteor.absoluteUrl('read/' + story.userPathSegment + '/' + story.storyPathSegment);
sendEmail('following-published', userIds, subject, bareMergeVars);
};
sendFollowedYouEmail = function(userId, followingUserId){
var followingUser = Meteor.users.findOne(followingUserId, {fields: {'profile.name': 1,'profile.bio': 1,'profile.profilePicture': 1, 'displayUsername': 1, 'services.twitter.id': 1}});
var fullName = followingUser.profile.name; // = story.authorName;
var username = followingUser.displayUsername; // = story.authorName;
var subject = fullName + ' (' + username + ') just followed you on FOLD';
var bareMergeVars = {};
bareMergeVars.fullName = fullName;
bareMergeVars.subject = subject;
bareMergeVars.bio = followingUser.profile.bio || '';
bareMergeVars.firstName = fullName.split(' ')[0];
bareMergeVars.profilePicUrl = 'https:' + getProfileImage(followingUser.profile.profilePicture, (followingUser.services && followingUser.services.twitter) ? followingUser.services.twitter.id : null, 'large', true);
bareMergeVars.profileUrl = Meteor.absoluteUrl('profile/' + followingUser.displayUsername);
sendEmail('followed-you', [userId], subject, bareMergeVars);
};
sendFollowedYouBackEmail = function(userId, followingUserId){
var followingUser = Meteor.users.findOne(followingUserId, {fields: {'profile.name': 1,'profile.bio': 1,'profile.profilePicture': 1, 'displayUsername': 1, 'services.twitter.id': 1}});
var fullName = followingUser.profile.name; // = story.authorName;
var username = followingUser.displayUsername; // = story.authorName;
var subject = fullName + ' (' + username + ') just followed you back on FOLD';
var bareMergeVars = {};
bareMergeVars.fullName = fullName;
bareMergeVars.subject = subject;
bareMergeVars.bio = followingUser.profile.bio || '';
bareMergeVars.firstName = fullName.split(' ')[0];
bareMergeVars.profilePicUrl = 'https:' + getProfileImage(followingUser.profile.profilePicture, (followingUser.services && followingUser.services.twitter) ? followingUser.services.twitter.id : null, 'large', true);
bareMergeVars.profileUrl = Meteor.absoluteUrl('profile/' + followingUser.displayUsername);
sendEmail('followed-you-back', [userId], subject, bareMergeVars);
};
<|start_filename|>package.json<|end_filename|>
{
"name": "fold",
"version": "1.0.0",
"description": "FOLD is a platform allowing storytellers to structure and contextualize stories",
"main": "./start",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/readFOLD/FOLD.git"
},
"author": "<NAME> & <NAME>",
"bugs": {
"url": "https://github.com/readFOLD/FOLD/issues"
},
"homepage": "https://readfold.com",
"dependencies": {
"babel-runtime": "^6.20.0",
"bcrypt": "^1.0.1",
"cheerio": "0.19.0",
"meteor-node-stubs": "^0.2.4",
"prerender-node": "2.0.2",
"twit": "1.1.20",
"vimeo-api": "1.1.2"
}
}
<|start_filename|>server/activities.js<|end_filename|>
generateActivity = function(type, details){
check(type, String);
check(details, Object);
if(details.fanout){
throw new Meteor.Error('Fanout should not be set');
}
var fullDetails = _.extend({}, details, {type: type});
var dedupDetails = {
type: type
};
_.each(['actor', 'object', 'target'], function(key){
if(details[key]){
dedupDetails[key +'.id'] = details[key].id;
}
});
switch(type){
case 'Share':
// pass through
break;
case 'Message':
// pass through
break;
default: // don't allow duplicate activities
if(details.content){
dedupDetails.content = details.content.toString();
}
if(Activities.find(dedupDetails, {limit: 1}).count()){
return // if this is a duplicate. stop here.
}
}
Activities.insert(fullDetails);
};
generateActivityFeedItem = function(userId, activityId, relevancy){
check(userId, String);
check(activityId, String);
check(relevancy, Date);
return ActivityFeedItems.insert({
uId: userId,
aId: activityId,
r: relevancy
})
};
fanToObject = function(activity){
check(activity.object, Object);
generateActivityFeedItem(activity.object.id, activity._id, activity.published);
};
fanToObjectAuthor = function(activity){
check(activity.object, Object);
var populatedObject;
switch (activity.object.type){
case 'Story':
populatedObject = Stories.findOne(activity.object.id, {fields: {authorId: 1}});
break;
default:
throw new Meteor.Error('Object not found in database for activity: ' + activity._id);
}
if(populatedObject){
generateActivityFeedItem(populatedObject.authorId, activity._id, activity.published); // fan to author
}
};
fanoutActivity = function(activity){
check(activity, Object);
check(activity.published, Date);
Activities.update(activity._id, {$set: {fanout: 'in_progress'}});
switch(activity.type){
case 'Favorite':
fanToObjectAuthor(activity);
break;
case 'Follow':
fanToObject(activity);
sendFollowedYouEmail(activity.object.id, activity.actor.id);
break;
case 'FollowBack':
fanToObject(activity);
sendFollowedYouBackEmail(activity.object.id, activity.actor.id);
break;
case 'Publish':
var author = Meteor.users.findOne(activity.actor.id, {fields: {followers: 1}}); // fan to followers
if(author.followers && author.followers.length){
_.each(author.followers, function(follower){
generateActivityFeedItem(follower, activity._id, activity.published);
});
sendFollowingPublishedEmail(author.followers, activity.object.id);
}
break;
case 'Share':
fanToObjectAuthor(activity);
break;
case 'ViewThreshold':
fanToObjectAuthor(activity);
break;
default:
throw new Error('Activity type not matched for activity: ' + activity._id + ' Type: ' + activity.type);
}
// if get here, nothing has thrown
return Activities.update(activity._id, {$set: {fanout: 'done'}});
};
<|start_filename|>client/lib/notifications.js<|end_filename|>
window.notifyRemix = function(message){
$.amaran({
content: {
message: message,
color: 'white',
bgcolor: '#EA1D75' // social-color
},
'position' :'top right',
theme:'colorful'
}
);
};
window.notifyFeature = window.notifyRemix;
window.notifySuccess = function(message){
$.amaran({
content: {
message: message,
color: 'white',
bgcolor: '#1DB259' // action-color
},
'position' :'top right',
theme:'colorful'
}
);
};
window.notifyLogin = function(){
var user = Meteor.user();
var name = user.profile.name ? user.profile.name.split(' ')[0] : user.profile.displayUsername;
notifySuccess('Welcome ' + name + '!');
};
window.notifyError = function(message){
$.amaran({
content: {
message: message,
color: 'white',
bgcolor: '#ff1b0c' // danger-color
},
'position' :'top right',
theme:'colorful',
delay: 8000
}
);
};
window.notifyInfo = function(message){
$.amaran({
content: {
message: message,
color: 'white',
bgcolor: '#585094' // social-color
},
'position' :'top right',
theme:'colorful'
}
);
};
window.notifyBrowser = function(){
$.amaran({
content: {
message: "Hi! We're so glad you're writing a story on FOLD. Feel free to try out our editor in any browser and give us feedback, but for the best experience right now, we recommend using Chrome!",
color: 'white',
bgcolor: '#585094' // social-color
},
sticky: true,
'position' :'top right',
theme:'colorful'
}
);
};
window.notifyDeploy = function(message, sticky){
$.amaran({
content: {
message: message,
color: 'white',
bgcolor: '#585094' // social-color
},
'position' :'top right',
theme:'colorful',
sticky: sticky,
clearAll: true
}
);
$('.amaran').addClass('migration-notification');
};
window.notifyImageSizeError = function(){
notifyError("Wow, that's a really big file! Can you make it any smaller? We support files up to " + CLOUDINARY_FILE_SIZE/1000000 + ' MB');
};
<|start_filename|>client/recover_password.js<|end_filename|>
Template.recover_password_form.onCreated(function() {
this.message = new ReactiveVar('');
})
Template.recover_password_form.helpers({
message () {
return Template.instance().message.get();
}
})
Template.recover_password_form.events({
'submit #recover-password-form' (e, t) {
e.preventDefault();
var forgotPasswordForm = $(e.currentTarget);
var email = t.$('#recover-password-email').val().toLowerCase();
if(_.isEmpty(email)) {
t.message.set('Please fill in all required fields.');
return;
}
if(!SimpleSchema.RegEx.Email.test(email)) {
t.message.set('Please enter a valid email address.');
return;
}
if (t.disableSubmit){
return false
} else {
t.disableSubmit = true;
}
Accounts.forgotPassword({email: email}, function(err) {
t.disableSubmit = false;
if (err) {
if (err.message === 'User not found [403]') {
t.message.set('This email does not exist.');
} else {
t.message.set('We are sorry but something went wrong.');
}
} else {
t.message.set('Email sent, expect it within a few minutes.');
t.disableSubmit = true; // prevent double submit
}
});
return false
},
});
<|start_filename|>client/login.js<|end_filename|>
// TODO close sign in overlay on esc (27) need to do on whole window though
var newUserInfo;
Template.signin_overlay.onCreated(function(){
Session.set('signinStage', 'signup');
newUserInfo = {};
});
Template.signin_overlay.helpers({
explanation (){
var signingIn = Session.get('signingIn');
if(typeof signingIn === 'string'){
return signingIn
}
},
onSignupStage (){
return Session.equals('signinStage', 'signup');
},
onLoginStage (){
return Session.equals('signinStage', 'login');
},
onInfoStage (){
return Session.equals('signinStage', 'info');
},
onPasswordStage (){
return Session.equals('signinStage', 'password');
},
onOnboardingStage (){
return Session.equals('signinStage', 'onboarding');
},
onForgotStage (){
return Session.equals('signinStage', 'forgot');
}
});
Template.signin_overlay.events({
"click .close" (d) {
closeSignInOverlay();
trackEvent('Click close sign-in overlay');
},
"click" (e){
if($(e.currentTarget).hasClass('signin-overlay') && Session.equals('signinStage', 'signup')){
closeSignInOverlay();
trackEvent('Click outside sign-in overlay and close');
}
},
"click .twitter-signin" (d) {
Meteor.loginWithTwitter({
requestPermissions: ['user']
}, function (err) {
if (err) {
notifyError("Twitter login failed");
throw(err); // throw error so we see it on kadira
} else if (!Meteor.user().username) { // if they are signing up for the first time they won't have a username yet
Session.set('signinStage', 'info');
} else { // otherwise they are a returning user, they are now logged in and free to proceed
closeSignInOverlay();
notifyLogin();
}
});
trackEvent('Click login with Twitter');
},
"click .email-signup" (d) {
Session.set('signinStage', 'info');
trackEvent('Click sign up with email');
},
"click .go-to-login" (e, t){
Session.set('signinStage', 'login');
},
"click .back-to-info" (e, t){
Session.set('signinStage', 'info');
},
"click .back-to-signup" (e, t){
Session.set('signinStage', 'signup');
},
"click .back-to-login" (e, t){
Session.set('signinStage', 'login');
},
"click .forgot-password" (e, t){
Session.set('signinStage', 'forgot');
}
});
Template.info_form.onCreated(function() {
this.signupError = new ReactiveVar();
this.emailError = new ReactiveVar();
this.nameError = new ReactiveVar();
this.usernameError = new ReactiveVar();
this.emailComplete = new ReactiveVar();
this.nameComplete = new ReactiveVar();
this.usernameComplete = new ReactiveVar();
this.submitting = new ReactiveVar();
});
Template.info_form.helpers({
tempUsername () {
if (Meteor.user()) {
return Meteor.user().tempUsername;
}
return;
},
signupError () {
return Template.instance().signupError.get();
},
emailError () {
return Template.instance().emailError.get();
},
nameError () {
return Template.instance().nameError.get();
},
usernameError () {
return Template.instance().usernameError.get();
},
emailComplete () {
return Template.instance().emailComplete.get();
},
nameComplete () {
return Template.instance().nameComplete.get();
},
usernameComplete () {
return Template.instance().usernameComplete.get();
},
submitting () {
Template.instance().submitting.get()
},
disableSignup () {
return Template.instance().submitting.get()
|| !Template.instance().emailComplete.get()
|| !Template.instance().nameComplete.get()
|| !Template.instance().usernameComplete.get()
|| Template.instance().emailError.get()
|| Template.instance().nameError.get()
|| Template.instance().usernameError.get()
}
});
var checkEmailField = function(e, t, suppressError) {
var email = t.$('input.signup-email').val();
email = trimInput(email);
var result = checkValidEmail(email);
if (!result.status) {
if(!suppressError) {
t.emailError.set(result.message)
}
} else {
t.emailError.set(false)
t.emailComplete.set(true);
}
};
var checkNameField = function(e, t, suppressError) {
var name = t.$('input.signup-name').val();
name = trimInput(name);
var result = checkValidName(name);
if (!result.status) {
if(!suppressError){
t.nameError.set(result.message)
}
} else {
t.nameError.set(false)
t.nameComplete.set(true)
}
};
var checkUsernameField = function(e, t, suppressError) {
var username = t.$(".signup-username").val();
username = trimInput(username);
var result = checkValidUsername(username);
if (!result.status) {
if(!suppressError){
t.usernameError.set(result.message)
}
} else {
t.usernameError.set(false)
t.usernameComplete.set(true)
}
};
var checkPassword = function(e, t) {
var p1 = t.$(".signup-password").val();
var result = checkValidPassword(p1);
if (!result.status) {
t.passwordError.set(result.message);
} else {
t.passwordError.set(false);
t.passwordComplete.set(true);
}
};
var checkPasswordConfirmation = function(e, t) {
var p1 = t.$(".signup-password").val();
var p2 = t.$(".signup-password2").val();
var result2 = checkValidPasswordConfirmation(p1, p2);
if (!result2.status) {
t.password2Error.set(result2.message);
} else {
t.password2Error.set(false);
t.password2Complete.set(true);
}
};
Template.info_form.onRendered(function(){
this.$('input')[0].focus();
// in case coming back
checkEmailField(null, this, true);
checkNameField(null, this, true);
checkUsernameField(null, this, true);
});
Template.info_form.helpers({
initialName (){
if (newUserInfo.profile && newUserInfo.profile.name ){
return newUserInfo.profile.name
} else {
var user = Meteor.user();
if(user && user.profile && user.profile.name){
return user.profile.name;
}
}
},
initialEmail (){
if (newUserInfo.email){
return newUserInfo.email
}
},
initialUsername (){
if (newUserInfo.username){
return newUserInfo.username
} else {
var user = Meteor.user();
if(user && user.tempUsername){
return user.tempUsername;
}
}
},
})
Template.info_form.events({
'blur input.signup-email': checkEmailField,
'keyup input.signup-email' (e,t) {
if (enterPress(e) || t.emailError.get()) {
Meteor.setTimeout(function() {
checkEmailField(e, t);
});
}
},
'blur input.signup-name': checkNameField,
'keyup input.signup-name' (e,t) {
Meteor.setTimeout(function(){
checkNameField(e, t);
});
},
'blur input.signup-username': checkUsernameField,
'keyup input.signup-username' (e,t) {
if (enterPress(e) || t.usernameError.get()) {
Meteor.setTimeout(function() {
checkUsernameField(e, t);
});
}
},
'submit' (e, t) {
var key;
e.preventDefault();
if(t.submitting.get()){
return
} else {
t.submitting.set(true)
}
if (t.emailError.get() || t.usernameError.get()) {
t.submitting.set(false);
return;
} else {
t.signupError.set(null);
}
var inputs = t.$('#info-form').serializeArray();
var userInfo = {};
_.each(inputs, function (input) {
key = input['name'];
value = input['value'];
userInfo[key] = value;
});
if (Meteor.user()) { // if just finishing signup and already created a user via twitter
Meteor.call('updateInitialTwitterUserInfo', userInfo, function (err) {
t.submitting.set(false);
if (err) {
t.signupError.set(err.reason || err.error);
} else {
Session.set('signinStage', 'onboarding');
notifyLogin();
newUserInfo = {};
trackEvent('New user signed up', {label: 'twitter'});
}
});
} else { // if email user
newUserInfo = {
email: userInfo.email,
username: userInfo.username,
profile: {
"name": userInfo.name
}
};
Meteor.call('validateUserInfo', newUserInfo, function(err) {
t.submitting.set(false);
if (err) {
if (err.error === 'username') {
t.usernameError.set(err.reason || err.error);
} else if (err.error === 'email') {
t.emailError.set(err.reason || err.error);
} else {
t.signupError.set(err.reason || err.error);
}
} else {
Session.set('signinStage', 'password');
}
});
}
}
});
Template.password_form.onCreated(function() {
this.signupError = new ReactiveVar();
this.passwordError = new ReactiveVar();
this.password2Error = new ReactiveVar();
this.passwordComplete = new ReactiveVar();
this.password2Complete = new ReactiveVar();
this.disableSignup = new ReactiveVar();
this.submitting = new ReactiveVar();
});
Template.password_form.onRendered(function(){
this.$('input')[0].focus();
});
Template.password_form.helpers({
signupError () {
return Template.instance().signupError.get();
},
passwordError () {
return Template.instance().passwordError.get();
},
password2Error () {
return Template.instance().password2Error.get();
},
passwordComplete () {
return Template.instance().passwordComplete.get();
},
password2Complete () {
return Template.instance().password2Complete.get();
},
submitting () {
return Template.instance().submitting.get();
},
disableSignup () {
return Template.instance().submitting.get()
|| !Template.instance().passwordComplete.get()
|| !Template.instance().password2Complete.get()
|| Template.instance().passwordError.get()
|| Template.instance().password2Error.get()
}
});
Template.password_form.events({
'blur input.signup-password': checkPassword,
'keyup input.signup-password' (e,t) {
if (enterPress(e) || t.passwordError.get()) {
Meteor.setTimeout(function() {
checkPassword(e, t);
});
}
},
'keyup input.signup-password2' (e,t) {
Meteor.setTimeout(function() {
checkPasswordConfirmation(e, t);
});
},
'submit' (e, t) {
e.preventDefault();
checkPassword(e, t);
checkPasswordConfirmation(e, t);
if(t.submitting.get()){
return
} else {
t.submitting.set(true)
}
if (t.passwordError.get()|| t.password2Error.get()) {
t.submitting.set(false);
return;
} else {
t.signupError.set(null);
}
var inputs = t.$('#password-form').serializeArray();
var userInfo = {};
_.each(inputs, function (input) {
var key = input['name'];
value = input['value'];
userInfo[key] = value;
});
newUserInfo.password = <PASSWORD>;
Accounts.createUser(newUserInfo, function(err) {
t.submitting.set(false);
if (err) {
t.signupError.set(err.reason || err.error);
} else {
Session.set('signinStage', 'onboarding');
newUserInfo = {};
notifyLogin();
trackEvent('New user signed up', {label: 'email'});
}
});
}
});
Template.onboarding_screen.events({
'click a, click button' (){
closeSignInOverlay();
}
});
Template.login_form.onCreated(function() {
this.loginError = new ReactiveVar(false);
this.submitting = new ReactiveVar(false);
});
Template.login_form.onRendered(function(){
this.$('input')[0].focus();
});
Template.login_form.helpers({
loginError () {
return Template.instance().loginError.get();
}
});
Template.login_form.events({
'keypress input' (e, template) {
template.loginError.set(false);
},
'submit #login-form' (e, template) {
e.preventDefault();
if(template.submitting.get()){
return
} else {
template.submitting.set(true);
}
inputs = template.$('#login-form').serializeArray();
user_info = {};
_.each(inputs, function(input) {
var key = input['name'];
value = input['value'];
user_info[key]=value;
});
Meteor.loginWithPassword(user_info.username.toLowerCase(), user_info.password, function(err){
template.submitting.set(false);
if (err) {
var errorText;
switch(err.reason){
case 'User not found':
errorText = "Hmmm... we can't find that username / email";
break;
case 'Incorrect password':
errorText = "Incorrect password";
break;
case 'User has no password set':
errorText = "Looks like you signed up with Twitter.\nClick below!";
break;
default:
errorText = err.reason;
}
template.loginError.set(errorText);
} else {
notifyLogin();
closeSignInOverlay();
}
return;
})
}
});
<|start_filename|>client/helpers.js<|end_filename|>
Handlebars.registerHelper("debugContext", function() {
return console.log(this);
});
Handlebars.registerHelper("log", function(v) {
return console.log(v);
});
Handlebars.registerHelper("hasContext", function(v) {
return !_.isEmpty(this);
});
Handlebars.registerHelper("pastHeader", function() {
return Session.get("pastHeader");
});
Handlebars.registerHelper("read", function() {
return Session.get("read");
});
Handlebars.registerHelper("notRead", function() {
return !Session.get("read");
});
Handlebars.registerHelper("showPublished", function() {
return !Session.get("showDraft");
});
Handlebars.registerHelper("showDraft", function() {
return Session.get("showDraft");
});
Handlebars.registerHelper("saving", function() {
return Session.get("saving");
});
Handlebars.registerHelper("signingIn", function() {
return window.signingIn();
});
Handlebars.registerHelper("currentXReadableIndex", function() {
return Session.get("currentX") + 1;
});
Handlebars.registerHelper("currentYId", function() {
return Session.get("currentYId");
});
Handlebars.registerHelper("addingContext", function() {
return Session.get("addingContext");
});
Handlebars.registerHelper("editingThisContext", function() {
var editingContext = Session.get("editingContext");
if (editingContext){
return editingContext === this._id;
}
});
Handlebars.registerHelper("UsersCollection", Meteor.users);
Handlebars.registerHelper("isAuthor", function() {
var userId = Meteor.userId();
return userId && userId === this.authorId;
});
Handlebars.registerHelper("isAuthorOrAdmin", function() {
var userId = Meteor.userId();
if (userId && userId === this.authorId){
return true
} else {
var user = Meteor.user();
return user && user.admin;
}
});
Handlebars.registerHelper("cardWidth", function() {
return Session.get("cardWidth");
});
Handlebars.registerHelper("cardHeight", function() { // for context cards, particularly in mobile
return Session.get("cardHeight");
});
Handlebars.registerHelper("windowWidth", function() {
return Session.get("windowWidth");
});
Handlebars.registerHelper("windowHeight", function() {
return Session.get("windowHeight");
});
Handlebars.registerHelper("verticalLeft", function() {
return getVerticalLeft();
});
Handlebars.registerHelper("adminMode", function() {
return adminMode();
});
Handlebars.registerHelper("audioPopoutExists", function() {
return Session.equals('poppedOutContextType', 'audio');
});
Handlebars.registerHelper("videoPopoutExists", function() {
return Session.equals('poppedOutContextType', 'video');
});
Handlebars.registerHelper("reactiveStory", function(){
return Stories.findOne(Session.get('storyId'));
});
Handlebars.registerHelper("twitterUser", function() {
var user = Meteor.user();
return user && user.services && user.services.twitter && user.services.twitter.id;
});
Handlebars.registerHelper("firstName", function(user) {
if (user && user.profile) {
return user.profile.name.split(' ')[0];
}
});
Handlebars.registerHelper("userFavorited", function() {
return Meteor.user() && _.contains(Meteor.user().profile.favorites, this._id);
});
Handlebars.registerHelper("userFollowing", function(id) {
return id === Meteor.userId() || Meteor.user() && _.contains(Meteor.user().profile.following, id);
});
Handlebars.registerHelper("showStorySandwichFooter", function () {
return !Meteor.Device.isPhone() && (embedMode() || hiddenContextMode());
});
Handlebars.registerHelper("profileImage", function(user, size) {
var profilePicture = (user && user.profile) ? user.profile.profilePicture : null;
var twitterId = (user && user.services && user.services.twitter) ? user.services.twitter.id : null;
return getProfileImage(profilePicture, twitterId, size);
});
Handlebars.registerHelper("formatNumber", function(num){
if(!num){
return 0;
}
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
Handlebars.registerHelper("formatDate", window.formatDate);
Handlebars.registerHelper("formatDateNice", window.formatDateNice);
Handlebars.registerHelper("formatDateCompact", window.formatDateCompact);
Handlebars.registerHelper("prettyDateInPast", window.prettyDateInPast)
Handlebars.registerHelper('$eq',
function(v1, v2) {
return (v1 === v2);
}
);
Handlebars.registerHelper('capitalize',
function(s) {
return _s.capitalize(s);
}
);
Handlebars.registerHelper("hiddenContextMode", function () {
return window.hiddenContextMode();
});
Handlebars.registerHelper("hiddenContextShown", function () {
return window.hiddenContextShown();
});
Handlebars.registerHelper("sandwichMode", function () {
return window.sandwichMode();
});
Handlebars.registerHelper("embedMode", function () {
return window.embedMode();
});
Handlebars.registerHelper("mobileOrTablet", function () {
return window.mobileOrTablet();
});
Handlebars.registerHelper("searchOverlayShown", function () {
return Session.get('searchOverlayShown');
});
Handlebars.registerHelper("menuOverlayShown", function () {
return Session.get('menuOverlayShown');
});
Handlebars.registerHelper("embedOverlayShown", function () {
return Session.get('embedOverlayShown');
});
Handlebars.registerHelper("howToOverlayShown", function () {
return Session.get('howToOverlayShown');
});
Handlebars.registerHelper("analyticsMode", function () {
return window.analyticsMode();
});
Handlebars.registerHelper("linkActivityShown", function () {
return window.linkActivityShown();
});
Handlebars.registerHelper("cardDataShown", function () {
return window.cardDataShown();
});
<|start_filename|>lib/activities.js<|end_filename|>
infoFor = function(type, id){
switch(type){
case 'Person':
var user = Meteor.users.findOne(id, {fields: {'profile.name' : 1, 'profile.profilePicture' : 1, 'services.twitter.id' : 1, 'displayUsername': 1}});
var userInfo = {
id: user._id,
type: 'Person',
name: user.profile.name,
urlPath: '/profile/' + user.displayUsername,
imageId: user.profile.profilePicture
};
if (user.services && user.services.twitter){
_.extend(userInfo, {
twitterId: user.services.twitter.id
});
}
return userInfo;
case 'Story':
var story = Stories.findOne({_id: id, published: true}, {fields: {'title' : 1, 'userPathSegment': 1, 'storyPathSegment': 1, 'headerImage': 1, authorId: 1, authorDisplayUsername: 1, authorUsername: 1 }});
return {
id: story._id,
type: 'Story',
name: story.title,
urlPath: '/read/' + story.userPathSegment + '/' + story.storyPathSegment,
imageId: story.headerImage,
attributedTo: {
id: story.authorId,
type: 'Person',
name: story.authorDisplayUsername || story.authorUsername,
urlPath: '/profile/' + story.authorDisplayUsername || story.authorUsername
}
};
default:
throw new Meteor.Error('Type not found for infoFor')
}
};
generateFavoriteActivity = function(userId, storyId){
if(Meteor.isServer){
Meteor.defer(function(){ // make non-blocking
check(userId, String);
check(storyId, String);
generateActivity('Favorite', {
actor: infoFor('Person', userId),
object: infoFor('Story', storyId)
})
})
}
};
generateFollowActivity = function(userId, userToFollowId){
if(Meteor.isServer){
Meteor.defer(function(){ // make non-blocking
check(userId, String);
check(userToFollowId, String);
var userToFollow = Meteor.users.findOne(userToFollowId, {fields: {'profile.following': 1}});
var activityType = _.contains(userToFollow.profile.following, userId) ? 'FollowBack' : 'Follow';
generateActivity(activityType, {
actor: infoFor('Person', userId),
object: infoFor('Person', userToFollowId)
})
})
}
};
generatePublishActivity = function(userId, storyId){
if(Meteor.isServer){
Meteor.defer(function(){ // make non-blocking
check(userId, String);
check(storyId, String);
generateActivity('Publish', {
actor: infoFor('Person', userId),
object: infoFor('Story', storyId)
})
})
}
};
generateShareActivity = function(storyId, service){
if(Meteor.isServer){
Meteor.defer(function(){ // make non-blocking
check(storyId, String);
check(service, String);
generateActivity('Share', {
content: service,
object: infoFor('Story', storyId)
});
})
}
};
generateViewThresholdActivity = function(storyId, viewCount){
if(Meteor.isServer){
Meteor.defer(function(){ // make non-blocking
check(storyId, String);
check(viewCount, Number);
generateActivity('ViewThreshold', {
content: viewCount,
object: infoFor('Story', storyId)
});
})
}
};
<|start_filename|>client/search-results.js<|end_filename|>
SearchResults = new Mongo.Collection(null, {
transform (doc) { return window.newTypeSpecificContextBlock(doc) }
});
var options = {
keepHistory: 1000 * 60 * 5,
localSearch: true
};
var fields = ['title', 'keywords', 'authorName', 'authorDisplayUsername'];
StorySearch = new SearchSource('stories', fields, options);
PersonSearch = new SearchSource('people', ['profile.name', 'username'], options);
<|start_filename|>client/main.js<|end_filename|>
var horizontalBlockHelpers, throttledResize, typeHelpers;
UI.registerHelper('selectedIf', function(val) {
return val ? 'selected' : '';
});
Session.set("separation", 20);
window.windowSizeDep = new Tracker.Dependency();
Meteor.startup(function(){
Tracker.autorun(function(){
windowSizeDep.depend();
var windowWidth = $(window).width();
// Safari changes window size in a weird way that jquery doesn't register correctly when scroll up vs down
Session.set("windowHeight", Meteor.Device.isPhone() && !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/) ? window.innerHeight : $(window).height());
Session.set("minimapMaxHeight", Session.get("windowHeight") - 592);
Session.set("windowWidth", windowWidth);
if (Meteor.Device.isPhone()) {
document.body.style.overflowX = "hidden";
$('body').css('max-width', windowWidth);
}
var cardWidthFromWindowSize = getCardWidth(windowWidth);
if(hiddenContextMode()){
var cardHeightFromWidth = cardWidthFromWindowSize * 9 / 16;
var cardHeightFromSpaceAvailable = Math.max($('.horizontal-context').height() - 110, 40);
if(cardHeightFromSpaceAvailable < cardHeightFromWidth){
Session.set("cardHeight", cardHeightFromSpaceAvailable);
Session.set("cardWidth", cardHeightFromSpaceAvailable * 16 / 9);
} else {
if(cardHeightFromWidth < window.constants.baselineCardHeight){
Session.set("cardHeight", cardHeightFromWidth);
} else {
Session.set("cardHeight", null);
}
Session.set("cardWidth", cardWidthFromWindowSize);
}
} else {
Session.set("cardWidth", cardWidthFromWindowSize);
Tracker.nonreactive(() => {
if(Session.get("cardHeight")){
Session.set("cardHeight", null);
}
})
}
throttledScrollUpdate();
});
Tracker.autorun(function(){
if (Session.get('hiddenContextShown')){
freezePageScroll();
} else {
unfreezePageScroll(); // TODO is this helping
}
});
var windowResize = function() {
windowSizeDep.changed();
};
throttledResize = _.throttle(windowResize, 20);
$(window).resize(throttledResize);
var justReloaded = window.codeReloaded;
Tracker.autorun(function(){
var signingIn = Session.get('signingIn');
if (signingIn && !justReloaded){
var trackingInfo = {nonInteraction: 1};
if(typeof signingIn === 'string'){
_.extend(trackingInfo,{
label: signingIn,
message: signingIn
})
}
trackEvent('Opened sign-in overlay', trackingInfo);
}
justReloaded = false;
});
Tracker.autorun(function(){
if( Meteor.Device.isPhone()){
return activateHiddenContextMode()
} else {
var windowWidth = Session.get('windowWidth');
var read = Session.get("read");
var inHiddenContextMode;
Tracker.nonreactive(function(){
inHiddenContextMode = hiddenContextMode();
inEmbedMode = embedMode();
});
var cutoff = inEmbedMode || Meteor.Device.isTablet() ? 1000 : 840;
if (read){
if (windowWidth < cutoff){
if(!inHiddenContextMode){
activateHiddenContextMode();
}
} else if (inHiddenContextMode) {
deactivateHiddenContextMode();
}
} else if (inHiddenContextMode) {
deactivateHiddenContextMode();
}
}
});
var restrictFocusToModal = function( event ) {
var modal = $('.signin-modal');
if (!modal.has(event.target)[0]) {
event.stopPropagation();
Meteor.setTimeout(function(){
modal[0].focus();
var input = $('.signin-modal input')[0];
if(input){
input.focus();
}
})
}
};
Tracker.autorun(function(){
if (Session.get('signingIn')){
$(document).on('focusin', restrictFocusToModal);
} else {
$(document).off('focusin', restrictFocusToModal);
}
});
Blaze.addBodyClass(function() {
if(Router.current() && Router.current().route){
return Router.current().route.getName();
}
});
});
Tracker.autorun(function(){
if(!Session.get('hiddenContextMode')){
Session.set('hiddenContextShown', false);
}
});
Meteor.startup(function(){
var inIFrame = function(){
try {
return window.self !== window.top;
} catch (e) {
return true;
}
};
if (inIFrame()){
activateEmbedMode();
}
});
window.hammerSwipeOptions = {
pointers: 1,
threshold: 8,
velocity: 0.25 // 0.65
};
window.hammerDoubleTapOptions = {
taps: 2
};
Hammer.defaults.cssProps.userSelect = 'text'; // prevent hammer from preventing text-select on mobile
var scrollPauseArmed = false;
var scrollPauseLength = 700;
var currentOrientation = window.orientation;
window.updateCurrentY = function() {
var actualY, h, i, readMode, scrollTop, stickyTitle, vertTop, _i, _len, _ref;
// if this is actually an orientation-change event, don't do anything
var newOrientation = window.orientation;
if(newOrientation !== currentOrientation){
currentOrientation = newOrientation;
return
}
scrollTop = $(document).scrollTop();
readMode = window.constants.readModeOffset - 1;
stickyTitle = 120;
var inEmbedMode = embedMode();
if(!inEmbedMode){
Session.set("scrollTop", scrollTop);
if(!Meteor.Device.isPhone()){
$(".horizontal-context").css({
opacity: 0.5 + Math.min(1.0, scrollTop / readMode) / 2
});
$("div#banner-overlay").css({
opacity: Math.min(1.0, scrollTop / readMode)
});
}
}
if(!Meteor.Device.isPhone() && !inEmbedMode){
if ((scrollTop >= readMode)){
$("div.title-author").addClass("c");
$("div.title-author").removeClass("a");
$("div.title-author").removeClass("b");
} else if (scrollTop >= stickyTitle) {
$("div.title-author").addClass("b");
$("div.title-author").removeClass("a");
$("div.title-author").removeClass("c");
} else {
scrollPauseArmed = true;
$("div.title-author").addClass("a");
$("div.title-author").removeClass("b");
$("div.title-author").removeClass("c");
}
if ((scrollTop >= readMode)) {
$("div.title-overlay, div#banner-overlay").addClass("fixed");
Session.set("pastHeader", true);
$("div.horizontal-context").addClass("fixed");
if(scrollPauseArmed && !inEmbedMode){
freezePageScroll();
$(document).scrollTop(readMode + 1);
Meteor.setTimeout(function () {
unfreezePageScroll();
}, scrollPauseLength);
scrollPauseArmed = false;
}
$("div.vertical-narrative").removeClass("fixed");
$("div.vertical-narrative").addClass("free-scroll");
} else {
$("div.title-overlay, div#banner-overlay").removeClass("fixed");
Session.set("pastHeader", false);
$("div.horizontal-context").removeClass("fixed");
$("div.vertical-narrative").removeClass("fixed");
$("div.vertical-narrative").removeClass("free-scroll");
}
}
if (inEmbedMode || Meteor.Device.isPhone() || (scrollTop >= readMode)) {
if(inEmbedMode && hiddenContextMode() && (scrollTop < $('.title-overlay').height() - 20)){
Session.set('pastHeader', false);
return
} else {
Session.set('pastHeader', true);
}
_ref = _.map(window.getVerticalHeights(), function(height){ return height + window.constants.selectOffset});
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
h = _ref[i];
if (scrollTop < h) {
break;
}
}
actualY = i - 1;
if (Session.get('currentY') !== actualY) {
Session.set("currentX", 0);
return Session.set("currentY", actualY);
}
}
};
var updateSlow = _.throttle(window.updateCurrentY, 20);
var updateFast = _.throttle(window.updateCurrentY, 1);
window.throttledScrollUpdate = function(){
if(scrollPauseArmed){
updateFast();
} else {
updateSlow();
}
};
Tracker.autorun(function(){
if(!Session.get('pastHeader')){
Session.set('currentY', null);
Session.set('currentX', null);
}
});
Tracker.autorun(function(){
var story = Session.get('story');
var currentY = Session.get("currentY");
if (story && (currentY != null)) {
var verticalSection = story.verticalSections[currentY];
if(!verticalSection){
return Session.set('currentYId', null);
} else {
return Session.set('currentYId', verticalSection._id);
}
} else {
return Session.set('currentYId', null);
}
});
Tracker.autorun(function(){
var currentYId = Session.get("currentYId");
if (currentYId){
Session.set("currentX", getXByYId(currentYId));
}
});
Tracker.autorun(function(){
var story = Session.get('story');
var currentY = Session.get("currentY");
var currentXByYId = Session.get("currentXByYId"); // for reactivity
if(!story || !story.verticalSections){
return
}
var verticalSection = story.verticalSections[currentY];
if(!verticalSection){
return
}
if((hiddenContextMode() && !hiddenContextShown())){
//Session.set("currentX", null);
Tracker.nonreactive(function(){
Session.set('previousXId', Session.get('currentXId'));
});
return Session.set("currentXId", null);
} else {
var currentX = getXByYId(verticalSection._id);
if(typeof currentX === 'number'){
var currentContextBlockId = verticalSection.contextBlocks[currentX];
if (currentContextBlockId) {
Tracker.nonreactive(function(){
Session.set('previousXId', Session.get('currentXId'));
});
return Session.set('currentXId', currentContextBlockId);
}
}
return Session.set('currentXId', null);
}
});
Tracker.autorun(function(){
var story = Session.get('story');
if(!story){
return
}
var id = story._id;
var currentY = Session.get("currentY");
var onReadPage;
var storyRead;
Tracker.nonreactive(function(){
onReadPage = Session.get('read') && !Session.get('showDraft');
storyRead = Session.equals('storyRead', id);
});
if(!onReadPage || storyRead){
return
}
var totalLength = story.verticalSections.length;
if (typeof currentY === 'number'){
if((currentY + 1) >= totalLength * 0.66){
Session.set('storyRead', id);
console.log('read')
Meteor.call('countStoryRead', id);
trackEvent('Read story', _.extend({}, trackingInfoFromStory(story), { nonInteraction: 1 }));
}
}
});
Tracker.autorun(function(){
var story = Session.get('story');
if(!story){
return
}
var id = story._id;
var onReadPage;
var storyViewed;
Tracker.nonreactive(function(){
onReadPage = Session.get('read') && !Session.get('showDraft');
storyViewed = Session.equals('storyViewed', id);
});
if(!onReadPage || storyViewed){
return
}
var countStoryView = function(){
Session.set('storyViewed', id);
Session.set('storyRead', null); // should reset whether story was read whenever switch which story was viewed so views and reads are comparable
Meteor.call('countStoryView', id);
trackEvent('View story', _.extend({}, trackingInfoFromStory(story), { nonInteraction: 1 }));
};
if(embedMode()){ // in embed mode, wait for a scroll before counting a view
$(window).one('scroll', countStoryView)
} else {
countStoryView();
}
});
Meteor.startup(function() {
Session.setDefault("filter", "curated");
Session.setDefault("pastY", []);
Session.setDefault("pastX", []);
Session.setDefault("currentY", void 0);
Session.setDefault("previousY", void 0);
Session.setDefault("currentX", void 0);
});
Meteor.startup(function(){
$( window ).konami({
code : [38,38,40,40,37,39,37,39, 66, 65],
cheat () {
$('body').addClass('konami');
}
});
$( window ).konami({
code : [70, 79, 76, 68, 65, 68, 77, 73, 78],
cheat () {
Session.set('adminMode', true);
}
});
});
typeHelpers = {
text () {
return this.type === "text";
},
image () {
return this.type === "image";
},
gif () {
return this.type === "gif";
},
map () {
return this.type === "map";
},
video () {
return this.type === "video";
},
viz () {
return this.type === "viz";
},
twitter () {
return this.type === "twitter";
},
audio () {
return this.type === "audio";
},
link () {
return this.type === "link";
},
action () {
return this.type === "action";
}
};
Template.story_header.onRendered(function() {
var range, sel, titleDiv;
// add cursor to title section if empty
if (!this.data.title) {
if (!Session.get('read')) {
titleDiv = $(this)[0].find('.story-title');
sel = window.getSelection();
if (sel.rangeCount > 0) {
sel.removeAllRanges();
}
range = document.createRange();
range.selectNodeContents(titleDiv);
range.collapse();
return sel.addRange(range);
}
}
});
Template.story_header.helpers({
title () {
if (this.title) {
return this.title;
} else {
return Session.get("storyTitle");
}
},
profileUrl (){
return '/profile/' + (this.authorDisplayUsername || this.authorUsername); // TODO migrate and only use authorDisplayUsername
},
author (){
return Meteor.users.findOne(this.authorId)
}
});
Template.story_header.events = {
"click #to-story" () {
$('#to-story, .attribution').fadeOut();
goToX(0);
return goToY(0);
},
"click #banner-overlay" () {
if (!Session.get("pastHeader")) {
$('#to-story, .attribution').fadeOut();
goToX(0);
return goToY(0);
}
},
"keydown" (e) {
if (enterPress(e) && !Session.get('read')) { // enter
e.preventDefault();
$(':focus').blur(); // TO-DO this should move focus to the first block
$('#to-story, .attribution').fadeOut();
goToX(0);
return goToY(0);
}
}
};
Template.story.helpers({
horizontalExists: horizontalExists,
pastHeader () {
return Session.get("pastHeader");
},
metaviewOpen () {
return Session.get("metaview")
},
showMinimap () {
return Session.get("showMinimap") && !hiddenContextMode() && !(embedMode() && Session.get('poppedOutContextId')) && !analyticsMode();
},
showContextOverlay (){
return Session.get('contextOverlayId');
},
showStoryBrowser (){
return !Session.get('addingContext') && (!hiddenContextMode() || hiddenContextShown())
}
});
Template.story_title.helpers({
storyTitleDiv (){
var initialClasses = Session.get('showDraft') ? 'story-title notranslate' : 'story-title';
if (Session.get('read')) {
return '<div class="' + initialClasses + '">' + _.escape(this.title) + '</div>';
} else {
// this is contenteditable in edit mode
return '<div class="notranslate ' + initialClasses + '" placeholder="Title" contenteditable="true" dir="auto">' + _.escape(this.title) + '</div>';
}
}
});
Template.vertical_section_block.helpers({
notFirst () {
return !Session.equals("currentY", 0);
},
verticalSelected () {
return Session.equals("currentY", this.index) && Session.get("pastHeader") || Session.equals("currentY", null) && this.index === 0 && !hiddenContextMode();
},
titleDiv () {
var initialClasses = Session.get('showDraft') ? 'title notranslate' : 'title';
if (Session.get('read')) {
return '<div class="' + initialClasses + '" dir="auto">' + _.escape(this.title) + '</div>';
} else {
// this is contenteditable in edit mode
return '<div class="editable ' + initialClasses + '" placeholder="Title" contenteditable="true" dir="auto">' + _.escape(this.title) + '</div>';
}
},
// NOTE: contentDiv is weird because the user edits its content but it's not reactive. be careful. if it's made reactive without updating it's semi-reactive contents accordingly, user will lose content
contentDiv () {
var showDraft = Session.get('showDraft');
var initialClasses = showDraft ? 'content notranslate' : 'content';
if (Session.get('read')) {
var content = cleanVerticalSectionContent(this.content);
var html = '<div class="' + initialClasses + '" dir="auto">' + content + '</div>';
if(!showDraft && linkActivityShown()){ // show link analytics
var story = new Story(Session.get('story'));
var heroContextId = this.contextBlocks[0];
jqHtml = $(html);
jqHtml.find('a').each(function(){
let contextId = $(this).data('contextId');
let anchorId = $(this).data('anchorId');
var haveFullData = story.firstPublishedAt > new Date('March 25, 2016') // this is when we started recording
if(haveFullData && story.analytics.anchorClicks){
var anchorClicks = story.analytics.anchorClicks[anchorId || contextId] || 0; // prefer anchor id if available. default to contextId for older stories
} else {
var anchorClicks = '--';
}
if(contextId === heroContextId){
additionalClasses = ' hero';
additionalAttributes = haveFullData ? "title = 'This is a link to the hero card, so people usually dont need to click a link to see it.'" : "title = 'This data is only available for stories published after March 25, 2016.'";
} else {
additionalClasses = '';
additionalAttributes = haveFullData ? '' : "title = 'This data is only available for stories published after March 25, 2016.'";
}
$(this).after("<span class='link-activity" + additionalClasses + "'" + additionalAttributes +">" + anchorClicks + "</span>");
});
return jqHtml[0].outerHTML;
} else {
return html;
}
} else {
// nonReactiveContent preserves browser undo functionality across saves
// this is contenteditable in edit mode
return '<div class="editable fold-editable ' + initialClasses + '" placeholder="Type your text here." contenteditable="true" dir="auto">' + cleanVerticalSectionContent(Template.instance().semiReactiveContent.get()) + '</div>';
}
},
showContextButton () {
if (this.contextBlocks.length && hiddenContextMode()){
if(Meteor.Device.isPhone() || Session.get('windowWidth') < 400){
return true
} else {
return Session.get('pastHeader')
}
}
}
});
Template.vertical_narrative.helpers({
verticalSectionsWithIndex () {
if(!this.verticalSections){ // catch error coming from my_stories for some reason
return
}
return this.verticalSections.map(function(v, i) {
return _.extend(v, {
index: i
});
});
}
});
Template.vertical_section_block.events({
"click" (e, t) {
var afterGoToY;
var enclosingAnchor;
if($(e.target).is('div')){
// do nothing
} else if (enclosingAnchor = $(e.target).closest('a')){
var contextId = $(enclosingAnchor).data('contextId');
var anchorId = $(enclosingAnchor).data('anchorId');
if(!analyticsMode() && Session.get('read') && !Session.get('showDraft')){
countAnchorClick(contextId); // record both, can sort it out later
countAnchorClick(anchorId);
}
e.preventDefault();
afterGoToY = function(){
goToContext(contextId);
};
Meteor.setTimeout(() => {
trackEvent('Click context anchor', _.extend({}, window.trackingInfoFromStory(Session.get('story')), {
verticalIndex: t.data.index,
contextId: contextId,
contextType: $(e.currentTarget).data('contextType'),
contextSource: $(e.currentTarget).data('contextSource'),
numberOfContextCardsOnVertical: t.data.contextBlocks.length,
inReadMode: Session.get('read')
}));
});
}
goToY(t.data.index, {complete: afterGoToY});
},
"click .context-button" (e, t){
afterGoToY = function(){
Session.set("hiddenContextShown", true);
};
Meteor.setTimeout(() => {
trackEvent('Click context button', _.extend({}, window.trackingInfoFromStory(Session.get('story')), {
verticalIndex: t.data.index,
numberOfContextCardsOnVertical: t.data.contextBlocks.length
}));
});
goToY(t.data.index, {complete: afterGoToY});
}
});
Template.story.onRendered(function(){
$(document).on('scroll', throttledScrollUpdate);
if(Meteor.Device.isPhone() || Meteor.Device.isTablet()){
this.$('.entire-story').hammer(hammerSwipeOptions).bind('swipeleft',function(){
if(horizontalExists()){
if (!hiddenContextMode() || hiddenContextShown()){
goRightOneCard();
}
}
}
);
this.$('.entire-story').hammer(hammerSwipeOptions).bind('swiperight',function(){
if(horizontalExists()){
if (!hiddenContextMode() || hiddenContextShown()){
goLeftOneCard();
}
}
}
);
}
windowSizeDep.changed(); // trigger window resizing things
});
Template.story.onDestroyed(function(){
$(document).off('scroll', throttledScrollUpdate);
if(Meteor.Device.isPhone() || Meteor.Device.isTablet()){
this.$('.entire-story').hammer(hammerSwipeOptions).unbind('swipeleft');
this.$('.entire-story').hammer(hammerSwipeOptions).unbind('swiperight');
}
});
var saveMetaviewOrdering = function() {
var newVerticalSectionIDs = $( ".sortable-rows" ).sortable('toArray', {attribute: 'data-id'});
var newContextBlocks = [];
$( ".sortable-blocks" ).each(function(i, e) {
newContextBlocks.push($(e).sortable('toArray', {attribute: 'data-id'} ))
});
var idMap = _.map(newVerticalSectionIDs, function(id, index){
return {
verticalId: id,
contextBlocks: newContextBlocks[index]
}
});
Session.set('saveState', 'saving');
Meteor.call('reorderStory', Session.get("storyId"), idMap, saveCallback);
};
var makeTransformScale = function(ratio){
return {
"-webkit-transform": 'scale(' + ratio + ')',
"-moz-transform": 'scale(' + ratio + ')',
"-ms-transform": 'scale(' + ratio + ')',
"-o-transform": 'scale(' + ratio + ')',
"transform": 'scale(' + ratio + ')'
}
};
window.metaviewScale = 1;
var resizeMetaview = function(){
var metaviewDiv = $('.cards');
var heightRatio = (metaviewDiv.height()) / (Session.get('windowHeight') - 100);
var widthRatio = (metaviewDiv.width()) / (Session.get('windowWidth') - 100);
metaviewScale = 1;
var doAtLeastOnce = true;
while(doAtLeastOnce || (heightRatio >= 1 || widthRatio >= 1) && metaviewScale >= 0.01){
doAtLeastOnce = false;
window.vBlockHeight = metaviewScale * 100;
window.vBlockWidth = metaviewScale * 160;
window.hBlockMargin = metaviewScale * 5;
window.hBlockHeight = metaviewScale * 90;
window.hBlockWidth = metaviewScale * 120;
window.hBlockWidth = metaviewScale * 120;
$('.metaview .row').css({height: vBlockHeight + 'px'});
$('.metaview .vertical-block').css({width: vBlockWidth + 'px', height: vBlockHeight + 'px'});
$('.metaview .horizontal-block').css({width: hBlockWidth + 'px', 'margin-top': hBlockMargin + 'px', 'margin-left': hBlockMargin + 'px', 'height': hBlockHeight + 'px'});
$('.metaview .horizontal-section').css({'height': hBlockHeight + 'px'});
heightRatio = (metaviewDiv.height()) / (Session.get('windowHeight') - 100);
widthRatio = (metaviewDiv.width()) / (Session.get('windowWidth') - 100);
metaviewScale *= 0.9;
}
};
Template.metaview.onRendered(function(){
Meteor.setTimeout(() => {
this.autorun(()=> {
resizeMetaview();
})
}, 100);
});
Template.metaview.onRendered(function() {
document.body.style.overflow = 'hidden'; // prevent document scroll while in metaview
this.$(".sortable-rows").sortable({
start: function(e, ui){
ui.placeholder.height(ui.item.height());
},
stop: saveMetaviewOrdering
});
var removingContext;
this.$(".sortable-blocks").sortable({
connectWith: ".sortable-blocks",
start: function(e, ui){
ui.placeholder.css({'margin-top': ui.item.css('margin-top')});
ui.placeholder.css({'margin-left': ui.item.css('margin-left')});
ui.placeholder.width(ui.item.width());
ui.placeholder.height(ui.item.height());
},
remove (e, ui) { // when a context block is removed from one vertical section and placed in another
removingContext = true;
var removedContextId = ui.item.data('id');
removeAnchorTag($('.vertical-narrative-section .content a[data-context-id="' + removedContextId + '"]')); // remove the broken link
Meteor.setTimeout(() => { // then save the ordering just a moment later to ensure the anchor removal makes it to the server first
removingContext = null;
resetXPositionMemory();
saveMetaviewOrdering();
}, 200);
},
stop (e, ui) {
if(!removingContext){ // if context is being removed, we handle it above
resetXPositionMemory(); // prevent XId stuff from getting all crazy
saveMetaviewOrdering();
}
removingContext = null;
}
});
this.$(".sortable-rows, .sortable-blocks").disableSelection();
});
Template.metaview.onDestroyed(function() {
document.body.style.overflow = 'auto';
});
Template.metaview.events({
"click .close" (d, t) {
Session.set("metaview", false);
},
"click" (d, t) {
d.preventDefault();
},
// these lines below prevent mouseout and mouseover from getting to other dom elements that will release the scroll lock
mouseover (d){
d.preventDefault();
d.stopPropagation();
},
mouseout (d){
d.preventDefault();
d.stopPropagation();
}
})
Template.metaview_context_block.helpers(typeHelpers)
Template.metaview.helpers({
verticalSectionsWithIndex () {
return this.verticalSections.map(function(v, i) {
return _.extend(v, {
index: i
});
});
},
horizontalSections () {
var blocks = this.contextBlocks
.map(function(id) {
return ContextBlocks.findOne({ // by finding one at a time, this keeps in broken links. TO-DO maybe should find a better soln that uses $in
_id: id
}) || {_id: id}; // fallback to just having id if cannot find
});
return blocks;
},
textContent (){
return $($.parseHTML(this.content)).text();
}
});
Template.minimap.events({
"click .minimap" (d, t) {
if (!Session.get('read')){ // only metaview in create for now
Session.set("metaview", true);
trackEvent('Click minimap in create mode');
} else {
if(!analyticsMode()){
notifyFeature('Zoom-out mode: coming soon!');
trackEvent('Click minimap in read mode');
}
}
},
"click .vertical.block" (e, t) {
if(analyticsMode()){
goToY(this.verticalIndex);
}
},
"click .horizontal.block" (e, t) {
if(analyticsMode()){
goToXY(this.horizontalIndex, this.verticalIndex);
}
}
});
Template.minimap.helpers({
horizontalSectionsMap () {
return Session.get("horizontalSectionsMap");
},
selectedX () {
return Session.equals("currentX", this.horizontalIndex);
},
selectedY () {
return Session.equals("currentY", this.verticalIndex);
},
minimapLargeEnough () {
// Ensure minimap height is greater than 0 and sections are at least 5 pixels tall
if (Session.get("minimapMaxHeight") <= 0 || ((Session.get("minimapMaxHeight") / Session.get("horizontalSectionsMap").length < 5) && !analyticsMode())) {
return false;
} else {
return true;
}
},
responsive () {
if(!analyticsMode()){
var maxHeight = Session.get("minimapMaxHeight");
var defaultSectionHeight = 17 + 5; // Section height + margin-bottom
return (Session.get("horizontalSectionsMap").length * defaultSectionHeight >= maxHeight)
}
},
sectionHeight () {
var maxHeight = Session.get("minimapMaxHeight");
return (maxHeight / Session.get("horizontalSectionsMap").length) * 0.75; // 75% of available space
},
verticalCardWidth () {
var maxHeight = Session.get("minimapMaxHeight");
return (maxHeight / Session.get("horizontalSectionsMap").length) * 0.75 * 1.53333; // 1.53333 aspect ratio
},
horizontalCardWidth () {
var maxHeight = Session.get("minimapMaxHeight");
return (maxHeight / Session.get("horizontalSectionsMap").length) * 0.75 * 0.7645 * 1.53333; // Horizontal block is 76.45% of section
},
sectionMargin () {
var maxHeight = Session.get("minimapMaxHeight");
return (maxHeight / Session.get("horizontalSectionsMap").length) * 0.25; // 25% of available space (33% of section)
},
showActivity (){
return cardDataShown();
},
activityLevel (){
var story = new Story(Session.get('story'));
var activeHeartbeats = (this.activeHeartbeats || 0);
var maxActiveHeartbeats = (typeof this.horizontalIndex === 'number') ? story.maxActiveContextHeartbeats() : story.maxActiveNarrativeHeartbeats();
return Math.pow( activeHeartbeats / maxActiveHeartbeats , 0.3) * 100;
},
showActivityMinutes (){
if(cardDataShown()){
return Session.get('story').firstPublishedAt > new Date('January 27, 2016'); // this is when we started recording card data
}
},
activityMinutes (){
return Math.round(this.activeHeartbeats / 60) || 0;
},
activityLevelForLuminance (){
var story = new Story(Session.get('story'));
var activeHeartbeats = (this.activeHeartbeats || 0);
var maxActiveHeartbeats = this.horizontalIndex ? story.maxActiveContextHeartbeats() : story.maxActiveNarrativeHeartbeats();
return 100 - Math.pow( activeHeartbeats / maxActiveHeartbeats , 0.2) * 45;
}
});
Template.horizontal_context.events({
click () {
if(Session.equals('currentY', null)){
goToY(0);
}
},
'click .hidden-context-overlay' (){
Session.set('hiddenContextShown', false);
}
});
Template.horizontal_context.onRendered(function(){
Tracker.autorun(() => {
if(mobileOrTablet()) {
if(Session.get('hiddenContextShown')){
Meteor.defer(()=> {
this.$('.hidden-context-overlay').hammer(hammerDoubleTapOptions).bind('doubletap', () => {
Session.set('hiddenContextShown', false);
});
})
} else {
this.$('.hidden-context-overlay').hammer(hammerDoubleTapOptions).unbind('doubletap');
}
}
})
});
Template.horizontal_context.onDestroyed(function(){
if(mobileOrTablet()) {
this.$('.hidden-context-overlay').hammer(hammerDoubleTapOptions).unbind('doubletap');
}
});
Template.horizontal_context.helpers({
verticalExists () {
return Session.get("horizontalSectionsMap").length;
},
horizontalSections () {
var that = this;
if(!this.verticalSections){ // catch error coming from my_stories for some reason
return
}
return this.verticalSections.map(function(verticalSection, verticalIndex) {
var sortedContext, unsortedContext;
if (Session.get('showDraft')) { // In CREATE, these need to be looked up from the db
sortedContext = _.chain(verticalSection.contextBlocks)
.map(function(id) {
return ContextBlocks.findOne({ // by finding one at a time, this keeps in broken links. TO-DO maybe should find a better soln that uses $in
_id: id
}) || {_id: id}; // fallback to just having id if cannot find
})
.map(function (datum, horizontalIndex) {
return _.extend(datum || {}, {
index: horizontalIndex,
verticalIndex: verticalIndex,
verticalId: verticalSection._id
});
})
.value();
//sortedContext = _.sortBy(unsortedContext, function (datum) {
// return datum.horizontalIndex;
//});
return {
index: verticalIndex,
data: sortedContext
};
} else { // In READ, these are denormalized on the document
var data = _.chain(verticalSection.contextBlocks)
.map(function(id) {
var cBlock = _.findWhere(that.contextBlocks, {_id: id})
if (cBlock) {
return cBlock;
} else {
throw new Meteor.Error('context card not found on story ' + that._id + ' . context card: ' + id);
}
})
.map(window.newTypeSpecificContextBlock)
.map(function (datum, horizontalIndex) {
return _.extend(datum || {}, {
index: horizontalIndex,
verticalIndex: verticalIndex,
verticalId: verticalSection._id
});
})
.value();
return {
data: data,
index: verticalIndex
}
}
});
},
last () {
var lastIndex, _ref;
lastIndex = ((_ref = Session.get("horizontalSectionsMap")[Session.get("currentY")]) != null ? _ref.horizontal.length : void 0) - 1;
return (this.index === lastIndex) && (lastIndex > 0);
},
horizontalShown () {
return Session.equals("currentY", this.index) || (Session.equals("currentY", null) && this.verticalIndex === 0);
}
});
editableDescriptionCreatedBoilerplate = function() {
this.editing = new ReactiveVar(false);
};
//editableDescriptionDestroyedBoilerplate = function(meteorMethod) {
//return function(){
// if(document.body){
// document.body.style.overflow = 'auto';
// }
// console.log(this)
//var that = this;
//if (!Session.get('read') && !Session.get('addingContext')) {
// var textContent = this.$('textarea[name=content]').val();
// Session.set('saveState', 'saving');
// Meteor.call(meteorMethod, that._id, textContent, function (err, numDocs) {
// saveCallback(err, numDocs);
// });
//}
// }
//};
var selected = function() {
var currentYId = Session.get('currentYId');
return ((this.verticalId === currentYId && this.index === getXByYId(currentYId)) || (this.verticalIndex === 0 && Session.get('currentY') == null && this.index === getXByYId(this.verticalId)) && !Session.get("addingContext"));
};
var poppedOut = function(){
return _.contains(['audio','video'], this.type) && this._id === Session.get('poppedOutContextId');
};
horizontalBlockHelpers = _.extend({}, typeHelpers, {
selected: selected,
poppedOut: poppedOut,
textContent () {
var textContent, rows;
if (this.type === 'text'){
textContent = this.content || '';
rows = 10;
placeholder = '';
}
else{
textContent = this.description || '';
rows = 2;
placeholder = 'Add a caption'
}
if (Session.get('read')) {
if (textContent.length){
return '<div class="text-content" dir="auto">' + _.escape(textContent).replace(/\n/g, "<br>") + '</div>';
} else {
return ''
}
} else {
return '<textarea name="content" class="text-content editable" rows="' + rows + '" placeholder="' + placeholder + '" dir="auto">' + _.escape(textContent) + '</textarea>';
}
}
});
var horizontalSectionInDOM = function () {
// on this row, or this card is the current X for another hidden row
return Session.equals("currentY", this.verticalIndex) || (Session.equals("currentY", null) && this.verticalIndex === 0 && !Meteor.Device.isPhone() && !window.isSafari) || this._id === Session.get('poppedOutContextId');
};
Template.horizontal_section_block.onCreated(function(){
this.horizontalSectionInDOM = new ReactiveVar();
Tracker.autorun(()=>{
if(horizontalSectionInDOM.call(this.data)){
this.horizontalSectionInDOM.set(true);
} else {
Meteor.setTimeout(()=>{
var shouldBeInDOM = horizontalSectionInDOM.call(this.data);
if(!shouldBeInDOM ){
this.horizontalSectionInDOM.set(false);
}
}, 500);
}
})
});
Template.horizontal_section_block.onRendered(function(){
// when cards flip from left to right (or vice-versa), they sometimes go above other cards weirdly. this sends it behind for the duration of the animation
//var lastIndex, _ref;
//lastIndex = ((_ref = Session.get("horizontalSectionsMap")[this.data.verticalIndex]) != null ? _ref.horizontal.length : void 0) - 1;
//var isLast = ((this.data.index === lastIndex) && (lastIndex > 0));
if(typeof MutationObserver !== "undefined"){
this.styleObserver = new MutationObserver((mutations) => {
mutations.forEach((mutationRecord) => {
var oldLeft = mutationRecord.oldValue.match(/left\:\W([\-?\d+]+)/)[1];
var newLeft = this.firstNode.style.left.match(/([\-?\d+]+)/)[1];
if ( (oldLeft < 0 && newLeft > 300) || (oldLeft > 300 && newLeft < 0) ){ // if it flips from negative to positive
$(this.firstNode).addClass('hide-behind');
Meteor.setTimeout(() => {
$(this.firstNode).removeClass('hide-behind');
}, 200); // this number should be as long as the .left-transition in the css
}
});
});
this.styleObserver.observe(this.firstNode, { attributes : true, attributeFilter : ['style'], attributeOldValue: true })
}
});
Template.horizontal_section_block.onDestroyed(function(){
if(this.styleObserver){
this.styleObserver.disconnect();
}
});
Template.horizontal_section_block.helpers(horizontalBlockHelpers);
// Magic layout function
Template.horizontal_section_block.helpers({
left: getHorizontalLeft,
lastUpdate () {
Session.get('lastUpdate');
},
hide () {
return !Session.equals("currentY", this.verticalIndex) && !(Session.equals("currentY", null) && this.verticalIndex === 0) && !(this._id === Session.get('poppedOutContextId'));
},
hideContainer () {
return this.type === 'audio' && this._id === Session.get('poppedOutContextId') && !(Session.equals("currentY", this.verticalIndex) || Session.equals("currentY", null) && this.verticalIndex === 0);
},
horizontalSectionInDOM () {
return Template.instance().horizontalSectionInDOM.get();
},
inCurrentRow (){
var currentY = Session.get('currentY');
return (this.verticalIndex === 0 && currentY == null) || this.verticalIndex === currentY;
}
});
Template.horizontal_section_block.events({
'click' (){
goToX(this.index)
}
});
editableDescriptionEventsBoilerplate = function(meteorMethod) {
return {
"blur .text-content.editable" (d, template) {
if (!Session.get('read') && !Session.get('addingContext')) {
var textContent = template.$('textarea[name=content]').val();
Session.set('saveState', 'saving');
Meteor.call(meteorMethod, this._id, textContent, saveCallback);
}
},
"mouseenter .text-content.editable" (d, template) {
document.body.style.overflow = 'hidden';
},
"mouseleave .text-content.editable" (d, template) {
document.body.style.overflow = 'auto';
},
"keypress .image-section .text-content.editable" (e, template) { // save on Enter
if (!Session.get('read') && !Session.get('addingContext') && e.which === 13 ) {
e.preventDefault();
var textContent = template.$('textarea[name=content]').val();
Session.set('saveState', 'saving');
Meteor.call(meteorMethod, this._id, textContent, saveCallback);
}
}
}
};
Template.display_viz_section.helpers(horizontalBlockHelpers);
Template.display_image_section.onCreated(editableDescriptionCreatedBoilerplate);
Template.display_image_section.onCreated(function(){
this.showMobileCaption = new ReactiveVar();
if(mobileOrTablet()){
this.autorun(() => {
if(!Session.equals('contextOverlayId', this.data._id)){
this.showMobileCaption.set(false);
}
})
}
});
Template.display_text_section.events({
'click' (e, t) {
if(Session.get('read')){
Session.set('contextOverlayId', this._id);
countContextInteraction(this._id);
trackEvent('Expand text card');
}
}
});
Template.display_image_section.helpers(horizontalBlockHelpers);
Template.display_image_section.helpers({
showMobileCaption () {
return Template.instance().showMobileCaption.get();
}
});
Template.display_image_section.events(editableDescriptionEventsBoilerplate('editHorizontalBlockDescription'));
Template.display_image_section.events({
'click' (e, t) {
if(mobileOrTablet() && this.description && !Template.instance().showMobileCaption.get()){
countContextInteraction(this._id);
return Template.instance().showMobileCaption.set(true);
}
if (Session.get('read') && !($(e.target).is('a'))) {
Session.set('contextOverlayId', this._id);
trackEvent('Expand image card');
if(!(mobileOrTablet() && this.description)){ // we count the showing caption on mobile
countContextInteraction(this._id);
}
}
}
});
Template.display_audio_section.helpers(horizontalBlockHelpers);
Template.display_audio_section.events({
'click .audio-iframe-overlay' (){
if(mostRecentWidget.activated()){
mostRecentWidget.isPlaying((playing) => {
if(playing){
mostRecentWidget.pause();
}
})
}
}
});
Template.display_video_section.helpers(horizontalBlockHelpers);
Template.display_video_section.onCreated(function(){
this.randomIFrameId = Random.id(8);
});
Template.display_video_section.helpers({
fromVimeo (){
return this.source === 'vimeo';
},
vimeoOnTablet (){
return Meteor.Device.isTablet() && this.source === 'vimeo';
},
randomIFrameId (){
return Template.instance().randomIFrameId
},
apiReadyUrl (){
if(this.source === 'vimeo'){
return this.url() + '&player_id=' + Template.instance().randomIFrameId
} else {
return this.url()
}
}
});
Template.display_video_section.events({
'click .video-iframe-overlay' (){
if(mostRecentWidget.activated()){
mostRecentWidget.isPlaying((playing) => {
if(playing){
mostRecentWidget.pause();
} else {
mostRecentWidget.isPaused((paused) => {
if (paused) {
mostRecentWidget.play();
}
});
}
})
}
},
"click .dismiss-popout" (e, t) {
if(poppedOutWidget.activated()){
poppedOutWidget.pause();
}
clearPoppedOutWidget();
trackEvent('Click dismiss popout button');
}
});
Template.display_twitter_section.helpers(horizontalBlockHelpers);
Template.display_map_section.helpers(horizontalBlockHelpers);
Template.display_action_section.helpers(horizontalBlockHelpers);
Template.display_action_section.events({
'click a' (e, t) {
if (!Session.get('read') && !$(e.target).is('input')) {
e.preventDefault();
return false
}
var url = e.currentTarget.href;
countContextInteraction(this._id);
trackEvent('Click action button in action card', {
label: this.actionButtonText(),
url: url
})
}
})
Template.display_link_section.helpers(horizontalBlockHelpers);
Template.display_link_section.onCreated(function(){
this.editingTitle = new ReactiveVar();
this.editingDescription = new ReactiveVar();
this.editThumbnailPrompt = new ReactiveVar();
this.editingThumbnail = new ReactiveVar();
this.uploadingThumbnail = new ReactiveVar();
});
Template.display_link_section.helpers({
editingTitle (){
return Template.instance().editingTitle.get()
},
editingDescription (){
return Template.instance().editingDescription.get()
},
editThumbnailPrompt (){
return !Session.get('read');
},
uploadingThumbnail (){
return Template.instance().uploadingThumbnail.get();
}
});
Template.display_link_section.events({
'click a' (e, t) {
if(!Session.get('read') && !$(e.target).is('input')){
e.preventDefault();
return false
}
var url = e.currentTarget.href;
countContextInteraction(this._id);
trackEvent('Click external link in link card', {
label: url,
url: url,
targetClassName: e.target.className
})
},
'click div.link-title' (e,t){
if(!Session.get('read') && !Session.get('addingContext')){
t.editingTitle.set(true);
Meteor.setTimeout(function(){
t.$('.link-title').select();
})
}
},
'blur textarea.link-title' (e,t){
if(!Session.get('read') && !Session.get('addingContext')){
Session.set('saveState', 'saving');
Meteor.call('editLinkTitle', this._id, t.$('textarea.link-title').val(), (err, result) =>{
if(result){
t.editingTitle.set(false);
}
saveCallback(err, result)
});
}
},
'click div.link-description' (e,t){
if(!Session.get('read') && !Session.get('addingContext')){
t.editingDescription.set(true);
Meteor.setTimeout(function(){
t.$('.link-description').select();
})
}
},
'blur textarea.link-description' (e,t){
if(!Session.get('read') && !Session.get('addingContext')){
Session.set('saveState', 'saving');
Meteor.call('editLinkDescription', this._id, t.$('textarea.link-description').val(), (err, result) => {
if(result){
t.editingDescription.set(false);
}
saveCallback(err, result)
});
}
},
"click input[type=file]" (d, template) {
return template.editingThumbnail.set(true);
},
"change input[type=file]" (e, template){
var finish = function(){
template.uploadingThumbnail.set(false);
return template.editingThumbnail.set(false);
};
var file = _.first(e.target.files);
if (file) {
if(file.size > CLOUDINARY_FILE_SIZE){
notifyImageSizeError();
return finish()
}
template.uploadingThumbnail.set(true);
Cloudinary.upload([file], {}, (err, doc) => {
if(err){
var input = template.$('input[type=file]');
input.val(null);
input.change();
saveCallback(err);
return finish();
} else {
var cloudinaryImageInfo = {
id: doc.public_id,
fileExtension: doc.format,
width: doc.width,
height: doc.height
};
Meteor.call('editLinkThumbnail', this._id, cloudinaryImageInfo, (err, result) => {
saveCallback(err, result);
return finish()
});
}
})
} else {
return finish()
}
}
});
Template.display_text_section.onCreated(editableDescriptionCreatedBoilerplate);
//Template.display_text_section.onDestroyed(editableDescriptionDestroyedBoilerplate('editTextSection'));
Template.display_text_section.helpers(horizontalBlockHelpers);
Template.display_text_section.events(editableDescriptionEventsBoilerplate('editTextSection'));
Template.horizontal_section_edit_delete.helpers(horizontalBlockHelpers);
Template.story_browser.helpers({
showLeftArrow () {
return !Meteor.Device.isPhone() && (Session.get("currentX") !== 0 || Session.get("wrap")[Session.get('currentYId')]);
},
showRightArrow () {
return !Meteor.Device.isPhone();
}
});
Template.story_browser.events({
"click .right" (d) {
window.goRightOneCard();
trackEvent('Click right arrow');
},
"click .left" (d) {
window.goLeftOneCard();
trackEvent('Click left arrow');
}
});
Template.type_specific_icon.helpers(typeHelpers);
Template.share_buttons.events({
'click .share-embed' (e, t) {
openEmbedOverlay();
trackEvent('Click embed button');
}
});
Template.share_on_facebook.events({
'click .share-facebook' (e, t) {
var width = 575;
var height = 400;
var left = ($(window).width() - width) / 2;
var top = ($(window).height() - height) / 2;
var url = "//facebook.com/sharer/sharer.php?u=" + encodeURIComponent(location.href);
var opts = 'status=1' +
',width=' + width +
',height=' + height +
',top=' + top +
',left=' + left
window.open(url, 'facebook', opts);
Meteor.call('countStoryShare', this._id, 'facebook');
trackEvent('Share on Facebook');
}
});
Template.share_on_twitter.events({
'click .share-twitter' (e, t) {
var title = $(".story-title").text();
var width = 575;
var height = 400;
var left = ($(window).width() - width) / 2;
var top = ($(window).height() - height) / 2;
var url = '//twitter.com/intent/tweet?text=Read "' + title + '" on @readFOLD&url=' + encodeURIComponent(location.href);
var opts = 'status=1' +
',width=' + width +
',height=' + height +
',top=' + top +
',left=' + left
window.open(url, 'twitter', opts);
Meteor.call('countStoryShare', this._id, 'twitter');
trackEvent('Share on Twitter');
}
});
Template.follow_button.helpers({
additionalClasses () {
var classes = '';
if (Template.instance().justFollowed.get()){
classes += 'just-followed'
}
if (Template.instance().justUnfollowed.get()){
classes += 'just-unfollowed'
}
return classes;
},
userFollowing (){
return Meteor.user() && _.contains(Meteor.user().profile.following, Template.instance().data.userId);
},
isYou (){
return Meteor.userId() === Template.instance().data.userId;
}
});
Template.follow_button.onCreated(function() {
this.justFollowed = new ReactiveVar();
this.justUnfollowed = new ReactiveVar();
});
Template.follow_button.events({
"click .follow" (e, t) {
trackEvent('Click follow button');
if (!Meteor.user()) {
openSignInOverlay("Please sign in to follow this author.\nIt'll only take a second!");
return
}
t.justFollowed.set(true);
Meteor.setTimeout(function () {
t.justFollowed.set(null);
}, 1500);
return Meteor.call('followUser', t.data.userId, function (err) {
if (err) {
notifyError(err);
throw(err);
} else {
trackEvent('Follow user');
}
})
},
"click .unfollow" (e, t) {
t.justUnfollowed.set(true);
Meteor.setTimeout(function(){
t.justUnfollowed.set(null);
}, 1000);
return Meteor.call('unfollowUser', t.data.userId, function (err) {
if (err) {
notifyError(err);
throw(err);
} else {
trackEvent('Unfollow user');
}
});
}
});
Template.favorite_button.helpers({
additionalClasses () {
var classes = '';
if (Template.instance().justFavorited.get()){
classes += 'just-favorited'
}
if (Template.instance().justUnfavorited.get()){
classes += 'just-unfavorited'
}
return classes;
}
});
Template.favorite_button.onCreated(function() {
this.justFavorited = new ReactiveVar();
this.justUnfavorited = new ReactiveVar();
});
Template.favorite_button.events({
"click .favorite" (e, t) {
trackEvent('Click favorite button');
if (!Meteor.user()) {
openSignInOverlay('Thanks for showing your love!\nPlease sign in to favorite this FOLD.');
return
}
t.justFavorited.set(true);
Meteor.setTimeout(() => {
t.justFavorited.set(null);
}, 700);
return Meteor.call('favoriteStory', this._id, (err) => {
if (err) {
notifyError(err);
throw(err);
} else {
trackEvent('Favorite story');
}
})
},
"click .unfavorite" (e, t) {
t.justUnfavorited.set(true);
Meteor.setTimeout(function(){
t.justUnfavorited.set(null);
}, 1000);
return Meteor.call('unfavoriteStory', this._id, function (err) {
if (err) {
notifyError(err);
throw(err);
} else {
trackEvent('Unfavorite story');
}
});
}
});
Template.editors_pick_button.events({
"click .pick" () {
return Meteor.call('designateEditorsPick', this._id, function(err) {
if (err) {
notifyError(err);
throw(err);
}
});
},
"click .unpick" () {
return Meteor.call('stripEditorsPick', this._id, function(err) {
if (err) {
notifyError(err);
throw(err);
}
});
}
});
Template.remix_bar.helpers({
showPopoutButton (){
return _.contains(['audio', 'video'], this.type);
}
});
Template.remix_bar.events({
'click .remix-button' (){
trackEvent('Remix context card click', _.pick(this, [
"_id",
"authorId",
"index",
"source",
//"storyId",
"storyShortId",
"type",
"verticalId",
"verticalIndex"
]));
notifyFeature("Remixing cards: coming soon!");
},
'click .popout-button' (){
trackEvent('Pop out card click', _.pick(this, [
"_id",
"authorId",
"index",
"source",
//"storyId",
"storyShortId",
"type",
"verticalId",
"verticalIndex"
]));
goRightOneCard();
Session.set('poppedOutContextId', this._id); // in case there is only one card in the row, force it to pop out
Session.set('poppedOutContextType', this.type);
}
});
Template.display_twitter_section.events({
"click .show-image" (e, template) {
template.$('.twitter-text-section').toggleClass('transparent');
},
"click .image-section" (e, template) {
template.$('.twitter-text-section').removeClass('transparent');
},
"mouseenter .twitter-section" (e, template) {
if (template.data.imgUrl) {
template.$('.twitter-text-section').addClass('show-corner');
template.$('.flag').addClass('show-corner');
}
},
"mouseleave .twitter-section" (e, template) {
if (template.data.imgUrl) {
template.$('.twitter-text-section').removeClass('show-corner');
template.$('.flag').removeClass('show-corner');
}
}
});
var ytScriptLoaded;
var vimeoScriptLoaded;
var ytApiReady = new ReactiveVar(false);
Template.story.onCreated(function(){
if(!ytScriptLoaded){
$.getScript('https://www.youtube.com/iframe_api', function () {});
ytScriptLoaded = true;
}
if(!vimeoScriptLoaded){
$.getScript('https://f.vimeocdn.com/js/froogaloop2.min.js', function () {});
vimeoScriptLoaded = true;
}
clearPoppedOutWidget();
clearMostRecentWidget();
});
onYouTubeIframeAPIReady = function(){
ytApiReady.set(true);
};
getVideoIFrame = function(contextId){
return document.querySelector(".video-section[data-context-id='" + contextId + "'] iframe");
};
createWidget = function(){
return {
activated: function () {
return this.activeSource ? true : false;
},
play(){
switch (this.activeSource) {
case 'youtube':
this._youTubeWidget.playVideo();
break;
case 'vimeo':
this._vimeoWidget.api('play');
break;
case 'soundcloud':
this._soundcloudWidget.play();
break;
default:
throw new Meteor.Error('popped out widget has no active source')
}
},
pause(){
switch (this.activeSource) {
case 'youtube':
this._youTubeWidget.pauseVideo();
break;
case 'vimeo':
this._vimeoWidget.api('pause');
break;
case 'soundcloud':
this._soundcloudWidget.pause();
break;
default:
throw new Meteor.Error('popped out widget has no active source')
}
},
isPlaying(cb){
switch (this.activeSource) {
case 'youtube':
if(this._youTubeWidget && this._youTubeWidget.getPlayerState){
var playing = _.contains([1,3], this._youTubeWidget.getPlayerState());
return cb(playing);
} else {
console.log('yt widget not set up yet')
return cb(false)
}
case 'vimeo':
return this._vimeoWidget.api('paused', function(paused){
return cb(!paused)
});
case 'soundcloud':
return this._soundcloudWidget.isPaused(function(paused){
return cb(!paused)
});
default:
throw new Meteor.Error('popped out widget has no active source')
}
},
isPaused(cb){
switch (this.activeSource) {
case 'youtube':
var paused = this._youTubeWidget.getPlayerState() === 2;
return cb(paused);
case 'vimeo':
return this._vimeoWidget.api('paused', cb);
case 'soundcloud':
return this._soundcloudWidget.isPaused(cb);
default:
throw new Meteor.Error('popped out widget has no active source')
}
},
getMediaInfo(cb){
switch (this.activeSource) {
case 'soundcloud':
return this._soundcloudWidget.getCurrentSound(cb);
}
},
getPosition(cb){
switch (this.activeSource) {
case 'soundcloud':
return this._soundcloudWidget.getPosition(cb);
}
},
bind(){
switch (this.activeSource) {
case 'soundcloud':
return this._soundcloudWidget.bind.apply(this._soundcloudWidget, arguments);
}
},
unbind(){
switch (this.activeSource) {
case 'soundcloud':
return this._soundcloudWidget.unbind.apply(this._soundcloudWidget, arguments);
}
},
hasOwnPlayer(){
switch (this.activeSource) {
case 'soundcloud':
return true;
default:
return false
}
},
seekTo(millis){
switch (this.activeSource) {
case 'soundcloud':
return this._soundcloudWidget.seekTo(millis);
default:
return false
}
}
}
};
window.poppedOutWidget = createWidget();
window.mostRecentWidget = createWidget();
var makeYouTubeWidget = function(id, cb){
var iframe = getVideoIFrame(id);
var options = {
events: {
onStateChange: (e) => {
if (e.data === YT.PlayerState.PLAYING) {
countContextInteraction(id);
}
}
}
};
if(ytApiReady.get()){
cb(new YT.Player(iframe, options));
} else {
Tracker.autorun((c) =>{
if(ytApiReady.get()){
cb(new YT.Player(iframe, options));
c.stop();
}
});
}
};
var makeVimeoWidget = function(id, cb){
$f(getVideoIFrame(id)).addEvent('ready', (iframeCSSId) => {
var widget = $f(iframeCSSId);
widget.addEvent('play', () => { countContextInteraction(id); });
cb(widget);
});
};
var makeSoundcloudWidget = function(id, cb){
var widget = SC.Widget(getAudioIFrame(id));
widget.bind(SC.Widget.Events.PLAY, function (e) {
countContextInteraction(id);
});
cb(widget)
};
window.setPoppedOutWidget = function (id){
//var section = document.querySelector(".audio-section[data-context-id='" + contextId + "']");
var source = $(".display-context-section[data-context-id='" + id + "']").data('contextSource');
poppedOutWidget.id = id;
if (id === mostRecentWidget.id){ // if this is also the most recent card (probably)
poppedOutWidget = mostRecentWidget; // the apis are already set up. just assign it
return
}
poppedOutWidget = createWidget();
Session.set('poppedOutContextType', (source === 'soundcloud') ? 'audio' : 'video');
switch(source){
case 'soundcloud':
makeSoundcloudWidget(id, (widget) => {
poppedOutWidget.activeSource = source;
poppedOutWidget._soundcloudWidget = widget;
});
break;
case 'youtube':
makeYouTubeWidget(id, (widget) => {
poppedOutWidget.activeSource = source;
poppedOutWidget._youTubeWidget = widget;
});
break;
case 'vimeo':
makeVimeoWidget(id, (widget) => {
poppedOutWidget.activeSource = source;
poppedOutWidget._vimeoWidget = widget;
});
break;
}
}
window.popInPoppedOutWidget = function(){
mostRecentWidget = poppedOutWidget;
clearPoppedOutWidget();
};
window.clearPoppedOutWidget = function(){
poppedOutWidget = createWidget();
Session.set('poppedOutContextId', null);
Session.set('poppedOutContextType', null);
};
window.popOutMostRecentWidget = function(){
if(poppedOutWidget.activated()){
poppedOutWidget.pause();
}
poppedOutWidget = mostRecentWidget;
Session.set('poppedOutContextId', mostRecentWidget.id);
Session.set('poppedOutContextType', (mostRecentWidget.activeSource === 'soundcloud') ? 'audio' : 'video');
};
window.setMostRecentWidget = function (id){
var source = $(".display-context-section[data-context-id='" + id + "']").data('contextSource');
if (id === poppedOutWidget.id){ // if this is also the popped out card
mostRecentWidget = poppedOutWidget; // the apis are already set up. just assign it
mostRecentWidget.activeSource = source; // it make have been deactivated
return
}
mostRecentWidget = createWidget();
mostRecentWidget.id = id;
Meteor.setTimeout(() => {
switch(source){
case 'youtube':
makeYouTubeWidget(id, (widget) => {
mostRecentWidget.activeSource = source;
mostRecentWidget._youTubeWidget = widget;
});
break;
case 'vimeo':
makeVimeoWidget(id, (widget) => {
mostRecentWidget.activeSource = source;
mostRecentWidget._vimeoWidget = widget;
});
break;
case 'soundcloud':
makeSoundcloudWidget(id, (widget) => {
mostRecentWidget.activeSource = source;
mostRecentWidget._soundcloudWidget = widget;
});
break;
}
}, 150); // hack to make sure video is in DOM when assign it.
};
window.clearMostRecentWidget = function(){
mostRecentWidget = createWidget();
};
getAudioIFrame = function(contextId){
return document.querySelector(".audio-section[data-context-id='" + contextId + "'] iframe");
};
var widgetSetup = function(){
this.autorun(() => {
var currentXId = Session.get('currentXId');
Tracker.nonreactive(() => {
var previousXId = Session.get('previousXId');
var isCurrent = this.data._id === currentXId;
var isPoppedOut = this.data._id === Session.get('poppedOutContextId');
var isMostRecent = this.data._id === mostRecentWidget.id;
var isPrevious = this.data._id === previousXId;
if(isCurrent){
if (isPoppedOut){ // if this card was popped out
if(!hiddenContextMode() || hiddenContextShown()){
popInPoppedOutWidget(); // pop it back in
return
}
} else {
setMostRecentWidget(currentXId); // it's now the most recent card
}
} else {
if((isPrevious || !previousXId) && !isPoppedOut && isMostRecent && mostRecentWidget.activated()){ // if this is the current widget
mostRecentWidget.isPlaying(function(playing){
if (playing){ // and it's playing
popOutMostRecentWidget();
}
})
}
}
});
});
};
var widgetBreakdown= function(){
if(mostRecentWidget.id === this.data.id){
window.clearMostRecentWidget();
}
};
var activeDisplayHelpers = {
showActiveDisplay (){
return Template.instance().activeDisplay.get();
}
};
var activeDisplayWorker = function(){
this.activeDisplay = new ReactiveVar();
Tracker.autorun(()=>{
var inActiveColumn = this.data.index === getXByYId(this.data.verticalId) && (!hiddenContextMode() || hiddenContextShown());
if(inActiveColumn){
this.activeDisplay.set(true);
} else {
Meteor.setTimeout(()=>{
var isPoppedOut = poppedOut.call(this.data);
var nowInActiveColumn = this.data.index === getXByYId(this.data.verticalId) && (!hiddenContextMode() || hiddenContextShown());
if(!isPoppedOut && !nowInActiveColumn){
this.activeDisplay.set(false);
}
}, 500);
}
})
};
Template.display_audio_section.onCreated(activeDisplayWorker);
Template.display_video_section.onCreated(activeDisplayWorker);
Template.display_audio_section.onRendered(widgetSetup);
Template.display_audio_section.onDestroyed(widgetBreakdown);
if(!Meteor.Device.isPhone()){
Template.display_video_section.onRendered(widgetSetup);
Template.display_video_section.onDestroyed(widgetBreakdown);
}
Template.display_audio_section.helpers(activeDisplayHelpers);
Template.display_video_section.helpers(activeDisplayHelpers);
clearPoppedOutWidget();
window.poppedOutPlayerInfo = new ReactiveDict;
var updatePlayProgress = function (e) {
poppedOutPlayerInfo.set('currentPosition', e.currentPosition);
poppedOutPlayerInfo.set('relativePosition', e.relativePosition);
};
Tracker.autorun(function(){
var poppedOutContextId;
if(poppedOutContextId = Session.get('poppedOutContextId')) {
if(poppedOutWidget.id !== poppedOutContextId){
setPoppedOutWidget(poppedOutContextId);
}
if(poppedOutWidget.hasOwnPlayer()){
var updateBasicPlayerInfo = function(){
poppedOutWidget.getMediaInfo(function (currentSound) {
poppedOutPlayerInfo.set('title', currentSound.title);
poppedOutPlayerInfo.set('duration', currentSound.duration);
poppedOutWidget.isPlaying(function(isPlaying){
poppedOutPlayerInfo.set('status', isPlaying ? 'playing' : 'paused');
});
poppedOutWidget.getPosition(function(position){
poppedOutPlayerInfo.set('currentPosition', position);
poppedOutPlayerInfo.set('relativePosition', position / currentSound.duration);
});
});
};
}
trackEvent('Context popped out', { nonInteraction: 1 }); // we can't be sure the user initiated // TODO, be more specific about audio or video perhaps
if(poppedOutWidget.hasOwnPlayer()) {
// this only works for audio for now, but only audio has its own player
updateBasicPlayerInfo();
poppedOutWidget.bind(SC.Widget.Events.READY, updateBasicPlayerInfo);
poppedOutWidget.bind(SC.Widget.Events.PLAY, function (e) {
poppedOutPlayerInfo.set('status', 'playing');
trackEvent('Popped out audio playing', { nonInteraction: 1 }); // we can't be sure the user initiated
});
poppedOutWidget.bind(SC.Widget.Events.PAUSE, function (e) {
poppedOutPlayerInfo.set('status', 'paused');
trackEvent('Popped out audio pausing', { nonInteraction: 1 }); // we can't be sure the user initiated
});
poppedOutWidget.bind(SC.Widget.Events.FINISH, function (e) {
poppedOutPlayerInfo.set('status', 'paused');
poppedOutPlayerInfo.set('currentPosition', poppedOutPlayerInfo.get('duration'));
poppedOutPlayerInfo.set('relativePosition', 1);
trackEvent('Popped out audio finished', { nonInteraction: 1 });
});
poppedOutWidget.bind(SC.Widget.Events.PLAY_PROGRESS, _.throttle(updatePlayProgress, 200))
}
} else {
if (poppedOutWidget.hasOwnPlayer()){
poppedOutWidget.unbind(SC.Widget.Events.READY);
poppedOutWidget.unbind(SC.Widget.Events.PLAY);
poppedOutWidget.unbind(SC.Widget.Events.PAUSE);
poppedOutWidget.unbind(SC.Widget.Events.FINISH);
poppedOutWidget.unbind(SC.Widget.Events.PLAY_PROGRESS);
}
}
});
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds);
}
Template.audio_popout.helpers({
title (){
return poppedOutPlayerInfo.get('title');
},
totalTime (){
return millisToMinutesAndSeconds(poppedOutPlayerInfo.get('duration'));
},
currentTime (){
var currentPosition;
if(currentPosition = poppedOutPlayerInfo.get('currentPosition')){
return millisToMinutesAndSeconds(currentPosition);
} else {
return "0:00"
}
},
showPauseButton (){
return poppedOutPlayerInfo.get('status') === 'playing';
}
});
var updateAudioPosition = function(e, t){
var millis = Math.min(e.currentTarget.value / 1000, 0.99) * poppedOutPlayerInfo.get('duration'); // min prevents scrub to end weirdness
poppedOutWidget.seekTo(millis);
poppedOutWidget.isPlaying(function(isPlaying){
if(!isPlaying){
poppedOutWidget.play();
}
});
}
Template.audio_popout.events({
'click .play' (){
poppedOutWidget.play();
},
'click .pause' (){
poppedOutWidget.pause();
},
'change .progress': updateAudioPosition,
'input .progress' (e,t) {
if(Meteor.Device.isPhone()){
poppedOutWidget.pause();
} else {
updateAudioPosition(e,t);
}
},
"click .dismiss-popout" (e, t) {
if(poppedOutWidget.activated()){
poppedOutWidget.pause();
}
clearPoppedOutWidget();
trackEvent('Click dismiss popout button');
}
});
Template.audio_popout.onRendered(function(){
this.autorun(() => {
var relativePosition = poppedOutPlayerInfo.get('relativePosition');
if(typeof relativePosition === 'number'){
this.$('input.progress').val(relativePosition * 1000);
}
});
});
Template.create_story.events({
'click' (){
if (Meteor.user()){
var accessPriority = Meteor.user().accessPriority;
if (accessPriority && accessPriority <= window.createAccessLevel){
var shortId = Random.id(8);
var verticalSectionId = Random.id(9);
Meteor.call('createStory',shortId, verticalSectionId, function(err, pathObject){
if (err) {
notifyError(err);
throw(err);
}
trackEvent('User clicked create and created story');
})
} else {
notifyInfo("Due to high demand, we had to turn off 'create new story' functionality for a moment. Stay tuned for updates!");
}
} else {
Session.set('signingIn', "You're almost there!\nPlease sign in to make a story.")
trackEvent('User clicked create and needs to sign in');
}
}
});
Template.read.onCreated(function(){
// analytics autorun
this.autorun(function(){
if (!Session.equals("currentY", null)){
var y = Session.get("currentY");
var storyLength = Session.get("story").verticalSections.length;
trackEvent('View vertical narrative section', {
label: y,
verticalNarrativeIndex: y,
storyLength: storyLength,
verticalNarrativeFraction: (y + 1) / storyLength,
storyId: Session.get("storyId")
})
}
});
this.autorun(() => {
if(adminMode()){
this.subscribe('adminOtherUserPub', this.data.authorId);
} else {
this.subscribe('minimalUsersPub', [this.data.authorId]);
}
});
});
var activityAnalyticsKeys = ['activeHeartbeats', 'anchorClicks', 'contextInteractions'];
var analyticsCount = {
'activeHeartbeats': {},
'anchorClicks':{},
'contextInteractions': {}
};
var analyticsCountSent = {
'activeHeartbeats': {},
'anchorClicks':{},
'contextInteractions': {}
};
subtractSentAnalyticsCount = function(){
_.each(activityAnalyticsKeys, function(topLevelKey){
_.each(_.keys(analyticsCountSent[topLevelKey]), function(k){
analyticsCount[topLevelKey][k] = analyticsCount[topLevelKey][k] - analyticsCountSent[topLevelKey][k];
if(!analyticsCount[topLevelKey][k]){
delete analyticsCount[topLevelKey][k]
}
});
});
analyticsCountSent = {
'activeHeartbeats': {},
'anchorClicks':{},
'contextInteractions': {}
}; // this makes the function safe to run multiple times
};
var sendAnalyticsInterval = 30000;
analyticsCountSender = function(doOnce){
if(_.chain(analyticsCount).values().all(_.isEmpty).value()){
console.log('nothing to send')
if(!doOnce){
Meteor.setTimeout(analyticsCountSender, sendAnalyticsInterval);
}
return
}
analyticsCountSent = _.clone(analyticsCount);
console.log('sending:')
console.log(analyticsCountSent)
Meteor.call('countStoryAnalytics', Session.get('storyId'), analyticsCountSent, function(err){
if(err){
console.warn('Failed to send analytics');
} else {
subtractSentAnalyticsCount();
}
if(!doOnce){
Meteor.setTimeout(analyticsCountSender, sendAnalyticsInterval);
}
});
};
Meteor.startup(function(){
Meteor.setTimeout(analyticsCountSender, sendAnalyticsInterval);
$(window).bind('beforeunload', function(){
subtractSentAnalyticsCount(); // in case there is already a count pending don't double-do it
analyticsCountSender(true);
})
});
window.userInactiveCount = 0;
var inactiveThreshold = 15;
$(window).bind('mousemove mouseup touchstart touchend touchmove keyup scroll resize', function(){
userInactiveCount = 0;
});
var onReadPage = function(){
return Session.get('read') && !Session.get('showDraft')
};
window.addActiveHeartbeat = function(key){
if(onReadPage()){
analyticsCount.activeHeartbeats[key] = (analyticsCount.activeHeartbeats[key] || 0) + 1;
}
};
window.countAnchorClick = function(key){
if(onReadPage()){
analyticsCount.anchorClicks[key] = (analyticsCount.anchorClicks[key] || 0) + 1;
}
};
window.countContextInteraction = function(key){
if(onReadPage()){
analyticsCount.contextInteractions[key] = (analyticsCount.contextInteractions[key] || 0) + 1;
}
};
Template.read.onRendered(function(){
if(sandwichMode()){
updateCurrentY();
} else {
$(window).scrollTop(Session.get('scrollTop'));
}
var startCountingHeartbeats = () => {
this.heartbeatInterval = Meteor.setInterval(function(){
var currentYId = Session.get('currentYId');
var currentXId = Session.get('currentXId');
var poppedOutContextId = Session.get('poppedOutContextId');
var poppedOutPlayerActive = poppedOutContextId && poppedOutPlayerInfo.get('status') === 'playing';
var userActive = !document.hidden && userInactiveCount < inactiveThreshold;
userInactiveCount += 1;
if(poppedOutPlayerActive) {
addActiveHeartbeat(poppedOutContextId);
}
if(userActive){
if(currentYId){
if(!Session.get('contextOverlayId') && !hiddenContextShown()){
addActiveHeartbeat(currentYId);
}
if(currentXId){ // can only truly have active context if have active narrative. currentXId may have a value when viewing header
addActiveHeartbeat(currentXId);
}
} else {
if (!Session.get('pastHeader')){
addActiveHeartbeat('header');
} else if (Session.get("currentY")) { // if no currentYId, but there is currentY, then it's at the footer
addActiveHeartbeat('footer');
}
}
}
if (userActive || poppedOutPlayerActive){
addActiveHeartbeat('story');
}
}, 1000);
};
if(embedMode()){ // in embed mode, wait for a scroll before counting
$(window).one('scroll', startCountingHeartbeats);
} else {
startCountingHeartbeats();
}
});
Template.read.onDestroyed(function(){
$(window).scrollTop(Session.get('scrollTop'));
Meteor.clearInterval(this.heartbeatInterval);
// send all existing heartbeats when leave a story
subtractSentAnalyticsCount(); // in case there is already a count pending don't double-do it
analyticsCountSender(true);
unfreezePageScroll();
});
Template.read.helpers({
showEmbedPlaceholder () {
return embedMode() && (Meteor.Device.isPhone() || Session.get('windowWidth') < 300 || Session.get('windowHeight') < 300)
}
});
Template.context_overlay.helpers({
overlaidContext (){
var id = Session.get('contextOverlayId');
if(Session.get('showDraft')) {
return ContextBlocks.findOne(id);
} else {
return newTypeSpecificContextBlock(_.findWhere(this.contextBlocks, {_id: id}));
}
},
contextLoaded (){
return Template.instance().contextLoaded.get();
},
textContent (){
return _.escape(this.content).replace(/\n/g, "<br>")
}
});
Template.context_overlay.onCreated(function(){
this.contextLoaded = new ReactiveVar();
});
Template.context_overlay.onRendered(function(){
this.contextLoaded.set(false);
$('img, video').load(() => {
this.contextLoaded.set(true);
});
freezePageScroll();
});
Template.context_overlay.onRendered(function(){
if(mobileOrTablet()) {
this.$('.context-overlay').hammer(hammerDoubleTapOptions).bind('doubletap', () => {
Session.set('contextOverlayId', null);
});
}
});
Template.context_overlay.onDestroyed(function(){
if(mobileOrTablet()) {
this.$('.context-overlay').hammer(hammerDoubleTapOptions).unbind('doubletap');
}
});
Template.context_overlay.onDestroyed(function(){
if(!hiddenContextMode() && !hiddenContextShown()){
unfreezePageScroll();
}
});
Template.context_overlay.events({
'click' () {
Session.set('contextOverlayId', null);
},
'scroll' (e) {
e.preventDefault();
e.stopPropagation();
return false
}
});
Template.loading_page.onRendered(function(){
$(window).scrollTop(0);
});
Template.read_options.events({
'click .activate-analytics' () {
trackEvent('Click show story stats');
activateAnalyticsMode();
}
});
Template.read_analytics_ui.events({
'click .show-link-activity' () {
trackEvent('Click show link activity');
Session.set('showLinkActivity', true);
},
'click .hide-link-activity' () {
trackEvent('Click hide link data');
Session.set('showLinkActivity', false);
},
'click .show-card-data' () {
trackEvent('Click show card data');
Session.set('showCardData', true);
},
'click .hide-card-data' () {
trackEvent('Click hide card data');
Session.set('showCardData', false);
},
'click .close' () {
trackEvent('Click hide story stats');
deactivateAnalyticsMode();
},
});
Template.read_analytics_ui.helpers({
readPercentage () {
if(this.analyticsBeforeReads){
return Math.round(this.analytics.reads.byIP / (this.analytics.views.byIP - this.analyticsBeforeReads.views.byIP) * 100);
} else {
return Math.round(this.analytics.reads.byIP / this.analytics.views.byIP * 100);
}
},
showReadPercentage () {
return Session.get('story').firstPublishedAt > new Date('January 27, 2016')
}
});
<|start_filename|>client/lib/constants.js<|end_filename|>
window.GOOGLE_API_CLIENT_KEY = Meteor.settings["public"].GOOGLE_API_CLIENT_KEY;
if (!GOOGLE_API_CLIENT_KEY) {
console.error('Settings must be loaded for apis to work');
throw new Meteor.Error('Settings must be loaded for apis to work');
}
window.panelColor = "#815ed9";
window.remixColor = panelColor;
window.orangeColor = "#fc521f";
window.actionColor = '#00c976';
window.dangerColor = '#fc521f';
window.whiteColor = "white";
<|start_filename|>client/fun.js<|end_filename|>
var handpickedStories = [
"/read/riascience/fifty-years-of-walking-in-space-and-what-we-found-there-uRTtQWQo",
"/read/FOLD/how-close-are-we-to-the-martian-Bret9g44",
"/read/BDatta/this-is-not-a-hologram-w5hosSJa",
"/read/twelvefifths/reaction-diffusion-systems-rvJzfQ6k",
"/read/kimsmith/automating-creativity-n5E8qJeF",
"/read/CorySchmitz/how-i-make-textures-kLiQK8se",
"/read/trainbabie/what-is-hipsterdom-nqeiz7XP",
"/read/HannahRajnicek/friday-the-13th-in-chicago-superstitions-tattoo-culture-MoEmXgMM",
"/read/timdunlop/the-first-time-ever-i-saw-your-face-apFj8gt9",
"/read/smwat/dada-data-and-the-internet-of-paternalistic-things-TsZQXLjK",
"/read/SproutsIO/finding-flavor-2Pf475CJ",
"/read/aminobiotech/why-you-should-grow-your-own-bacteria-at-home-JodcMMXB",
"/read/APCollector/on-a-mans-modular-synth-iRaJbfjY",
"/read/EthanZ/choosing-the-appropriate-extreme-metal-music-to-listen-to-while-grading-masters-theses-SESbL2qK",
"/read/CorySchmitz/how-i-make-halftones-nmQRSPe5",
"/read/manuelaristaran/digital-public-services-user-experience-matters-WwpPfdJq",
"/read/sammireinstein/it-is-what-it-is-conversations-about-iraq-WotpdjNa",
"/read/AnnieHuang/shepard-faireys-obey-NnmADS2Z",
"/read/JanineKwoh/why-diversity-matters-in-the-card-aisle-cR9WaHQe",
"/read/cesifoti/three-women-scholars-you-should-know-but-you-probably-dont-evYYD35C",
"/read/Jeremy/proof-of-work-20-He8cm2WC",
"/read/sgenner/why-screens-can-ruin-your-sleep-XuiGfrJi",
"/read/sultanalqassemi/sultan-al-qassemi-on-mit-media-lab-imagination-realized-i8ZS3Dtg",
"/read/MattCarroll/mr-spock-to-the-rescue-how-a-star-trek-star-earned-the-admiration-of-a-young-fan-v5Rr3gGf"
];
var handpickedPeople = [
"/profile/twelvefifths",
"/profile/FOLD",
"/profile/alexishope",
"/profile/EthanZ",
"/profile/Rochelle",
"/profile/jbobrow",
"/profile/DestinyInFocus",
"/profile/SproutsIO",
"/profile/Cristian_jf",
"/profile/cjaffe",
"/profile/mpetitchou",
"/profile/tor",
"/profile/JanineKwoh",
"/profile/trainbabie",
"/profile/CorySchmitz",
"/profile/MattCarroll",
"/profile/HannahRajnicek",
"/profile/delong",
"/profile/aminobiotech",
"/profile/cesifoti",
"/profile/jovialjoy",
"/profile/shailin",
"/profile/sannabh",
"/profile/sgenner",
"/profile/BDatta",
"/profile/smwat",
"/profile/APCollector",
"/profile/MikeMoschella"
];
Template.random_story.onCreated(function(){
this.options = handpickedStories;
});
Template.random_person.onCreated(function(){
this.options = handpickedPeople;
});
_.each(['random_story', 'random_person'], function(templateName){
Template[templateName].onCreated(function() {
this.randomizedLink = new ReactiveVar();
this.rolling = new ReactiveVar();
});
Template[templateName].onRendered(function(){
this.autorun(() => {
var currentUrl = Router.current().url;
this.links = _.reject(this.options, function(url){
return _s.include(url, idFromPathSegment(currentUrl));
});
this.randomizedLink.set(_.sample(this.links));
});
this.rollTheDice = (cb) => {
this.rolling.set(true);
//var keepRolling = Meteor.setInterval(function(){
// this.randomizedLink.set(_.sample(this.links));
//}, 50);
Meteor.setTimeout(() => {
//clearInterval(keepRolling);
this.rolling.set(false);
if(cb){
cb();
}
}, 1100);
}
});
Template[templateName].helpers({
rolling (){
return Template.instance().rolling.get();
},
randomizedLink (){
return Template.instance().randomizedLink.get();
}
});
Template[templateName].events({
'click' (e, t){
e.preventDefault();
t.rollTheDice(function(){
Router.go(t.randomizedLink.get());
})
trackEvent('Click random story button');
}
});
})
<|start_filename|>client/lib/helpers.js<|end_filename|>
window.startTime = window.performance ? window.performance.timing.navigationStart : Date.now(); // mobile safari doesn't have timing api
$.cloudinary.config({
cloud_name: Meteor.settings["public"].CLOUDINARY_CLOUD_NAME
});
window.isHighDensity = ((window.matchMedia && (window.matchMedia('only screen and (min-resolution: 124dpi), only screen and (min-resolution: 1.3dppx), only screen and (min-resolution: 48.8dpcm)').matches || window.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3)').matches)) || (window.devicePixelRatio && window.devicePixelRatio > 1.3));
// browser detection
window.isChrome = navigator.userAgent.indexOf('Chrome') > -1;
window.isExplorer = navigator.userAgent.indexOf('MSIE') > -1;
window.isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
window.isSafari = navigator.userAgent.indexOf("Safari") > -1;
window.isOpera = navigator.userAgent.toLowerCase().indexOf("op") > -1;
if ((isChrome)&&(isSafari)) {isSafari=false;}
if ((isChrome)&&(isOpera)) {isChrome=false;}
window.isValidPassword = function(p) {
if (p.length >= 6) {
return true;
} else {
return false;
}
}
window.trimInput = function(val) {
return val.replace(/^\s*|\s*$/g, "");
}
window.checkValidEmail = function(email) {
if (email.length === 0 ) {
return { status: false, message: 'Please enter your e-mail address' };
} else if (!SimpleSchema.RegEx.Email.test(email)) {
return { status: false, message: 'Invalid e-mail address' };
} else {
return { status: true, message: false };
}
};
window.checkValidName = function(name) {
if (name.length === 0 ) {
return { status: false, message: 'Please enter your name' };
} else if (name.length > 127 ) {
return { status: false, message: 'Too long (maximum 127 characters)' };
} else {
return { status: true, message: false };
}
};
window.checkValidPassword = function(p1) {
if (p1.length === 0 ) {
return { status: false, message: 'Please enter a password' };
} else if (!isValidPassword(p1)) {
return { status: false, message: 'Too short (minimum 6 characters)' };
} else {
return { status: true, message: false };
}
};
window.checkValidPasswordConfirmation = function(p1, p2) {
if (p2.length && p1!==p2) {
return { status: false, message: 'Passwords do not match' };
} else {
return { status: true, message: false };
}
};
window.checkValidUsername = function(username) {
var usernameRegex = /^[a-zA-Z0-9_]+$/;
if (username.length === 0 ) {
return { status: false, message: 'Please enter a username' };
} else if (username.length < 3) {
return { status: false, message: 'Too short (minimum 3 characters)' };
} else if (username.length > 15) {
return { status: false, message: 'Too long (maximum 15 characters)' };
} else if (!username.match(usernameRegex)) {
return { status: false, message: 'Please only use letters, numbers, and _' };
} else {
return { status: true, message: false };
}
}
window.incrementReactiveVar = function(rv){
return rv.set(rv.get() + 1);
}
window.openSignInOverlay = function(str){
if(str === 'login'){
Session.set('signinStage', 'login');
Session.set('signingIn', true);
} else {
Session.set('signinStage', 'signup');
Session.set('signingIn', str || true);
}
};
window.closeSignInOverlay = function(){
Session.set('signingIn', false);
};
window.signingIn = function(){
return Session.get('signingIn');
};
window.adminMode = function() {
if (Session.get("adminMode")){
var user = Meteor.user();
if (user){
return user.admin ? true : false;
}
}
};
var weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
window.formatDate = function (date) {
if (date) {
var hms;
hms = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
return weekDays[date.getDay()] + " " + (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + hms;
}
};
// February 7th, 2015
window.formatDateNice = function (date) {
if (date){
return monthNames[(date.getMonth())] + " " + date.getDate() + ", " + date.getFullYear();
}
};
// 2/7/2015
window.formatDateCompact = function (date) {
if (date){
return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
}
};
var oneDay = 1000 * 60 * 60 * 24;
var oneWeek = oneDay * 7;
var oneMonth = oneDay * 30;
window.prettyDateInPast = function(date){
if(date){
var now = new Date();
var dayDistance = (now.getDay() - date.getDay());
if(dayDistance < 0){
dayDistance += 7;
}
var exactDistance = now - date;
if(exactDistance <= oneDay && dayDistance === 0){
return 'Today'
} else if (exactDistance <= oneWeek) {
if(dayDistance === 0){
return 'One week ago'
} else if(dayDistance === 1){
return 'Yesterday'
} else {
return dayDistance + ' days ago'
}
} else if (exactDistance <= oneWeek * 1.5) {
return 'One week ago'
} else if (exactDistance <= oneMonth) {
return Math.round(new Date(exactDistance).getDate() / 7) + ' weeks ago'
} else {
return formatDateNice(date);
}
}
};
window.trackingInfoFromStory = function(story) {
return _.chain(story)
.pick([
'_id',
'authorDisplayUsername',
'authorId',
'authorName',
'authorUsername',
'createdAt',
'editorsPick',
'editorsPickAt',
'firstPublishedAt',
'headerImageFormat',
'keywords',
'narrativeRightsReserved',
'publishedAt',
'savedAt',
'shortId',
'title'])
.extend(story.published ? {
'numberOfContextBlocks': story.contextBlockIds.length,
'numberOfVerticalSections': story.verticalSections.length,
'favorites': story.favoritedTotal,
'numberofKeywords': story.keywords.length,
'titleLength': story.title.length
} : {})
.extend(story.countContextTypes ? story.countContextTypes() : {}) // TODO Fix
.value();
};
window.enterPress = function(e){
return e.keyCode === 13
};
window.trackEvent = function(action){
arguments[1] = arguments[1] || {};
var params = _.extend({eventAction: action, eventCategory: 'FOLD'}, arguments[1]); // event category not really used, but required in new ga api
ga('send', 'event', params);
};
var preventDefault = function(event) {
event.preventDefault();
};
window.freezePageScroll = function(){
var b = $('body');
var normalw = window.innerWidth;
var scrollBarWidth = normalw - b.width();
document.body.style.overflowY = 'hidden';
document.body.style.marginRight = scrollBarWidth + 'px';
$('.home-top.fat').width('calc(100% - ' + scrollBarWidth +'px');
if(mobileOrTablet()){
window.document.body.addEventListener("touchmove", preventDefault, false);
}
};
window.unfreezePageScroll = function(){
document.body.style.overflowY = 'auto';
document.body.style.marginRight = 0;
$('.home-top.fat').width('100%');
if(mobileOrTablet()) {
window.document.body.removeEventListener("touchmove", preventDefault, false);
}
};
window.sandwichMode = function(){
return window.embedMode() && !window.hiddenContextMode();
};
window.activateHiddenContextMode = function(){
return Session.set('hiddenContextMode', true);
};
window.deactivateHiddenContextMode = function(){
return Session.set('hiddenContextMode', false);
};
window.hiddenContextMode = function(){
return Session.equals('hiddenContextMode', true);
};
window.hiddenContextShown = function(){
return Session.equals('hiddenContextShown', true);
};
window.embedMode = function(){
return Session.equals('embedMode', true);
};
window.activateEmbedMode = function(){
window.constants.readModeOffset = 0;
$('body').addClass('embed-mode');
return Session.set('embedMode', true);
};
window.mobileOrTablet = function(){
return Meteor.Device.isPhone() || Meteor.Device.isTablet()
};
window.openSearchOverlay = function(){
return Session.set('searchOverlayShown', true);
};
window.closeSearchOverlay = function(){
return Session.set('searchOverlayShown', false);
};
window.openMenuOverlay = function(){
return Session.set('menuOverlayShown', true);
};
window.closeMenuOverlay = function(){
return Session.set('menuOverlayShown', false);
};
window.openEmbedOverlay = function(){
return Session.set('embedOverlayShown', true);
};
window.closeEmbedOverlay = function(){
return Session.set('embedOverlayShown', false);
};
window.openHowToOverlay = function(){
return Session.set('howToOverlayShown', true);
};
window.closeHowToOverlay = function(){
return Session.set('howToOverlayShown', false);
};
window.analyticsMode = function(){
return Session.get('analyticsMode', true);
};
window.activateAnalyticsMode = function(){
return Session.set('analyticsMode', true);
};
window.deactivateAnalyticsMode = function(){
return Session.set('analyticsMode', false);
};
window.linkActivityShown = function () {
return window.analyticsMode() && Session.get('showLinkActivity');
};
window.cardDataShown = function () {
return window.analyticsMode() && Session.get('showCardData');
};
window.getCardWidth = function(windowWidth) {
if (Meteor.Device.isPhone()) {
return Session.get("windowWidth") * .9 - 2 * Session.get("separation");
} else if (hiddenContextMode()){
if(windowWidth <= 685){ // must match up with @resizing-context
return Session.get("windowWidth") * .9 - 2 * Session.get("separation") - 2 * 60;
} else {
return 520;
}
} else if (windowWidth <= window.constants.minPageWidth) {
return 400;
} else {
return Math.min(520, (windowWidth - (16 * 3) - (88 * 2)) / 2);
}
};
<|start_filename|>client/analytics.js<|end_filename|>
// Google Analytics Snippet //
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
// End Snippet //
// Initiate Google Analytics
ga('create', Meteor.settings["public"].GA_TRACKING_KEY, 'auto');
Router.onRun(function() {
Meteor.setTimeout(() => {
$('meta[property="og:url"]').attr('content', window.location.href);
ga('send', 'pageview', {
title: this.route.getName(),
location: window.location.href
}); // maybe should be more page info here
}, 100); // this might even be ok when set to 0
this.next()
});
window.trackTiming = function(category, str, time){ // mobile safari doesn't have timing api so those results will not include initial request time
trackEvent(str, {
time: time,
nonInteraction: 1
});
ga('send', 'timing', category, str, time);
};
var jsLoadTime = Date.now() - startTime;
if (!window.codeReloaded){
trackTiming('JS', 'JS Loaded', jsLoadTime);
}
Meteor.startup(function() {
if (!window.codeReloaded) {
var timeTillDOMReady = Date.now() - startTime;
trackTiming('DOM', 'DOM Ready', timeTillDOMReady);
Tracker.autorun(function(c) {
// waiting for user subscription to load
if (! Router.current() || ! Router.current().ready())
return;
var userId = Meteor.userId();
if (! userId)
return;
ga('set', 'userId', userId);
c.stop();
});
}
});
// TODO alias user when created
//Accounts.createUser({
// email: email,
// password: password,
// profile: {
// name: name
// }
//}, function(error) {
// if (! error) {
// analytics.alias(Meteor.userId());
// } else {
// alert('Error creating account!\n' + EJSON.stringify(error));
// }
//});
<|start_filename|>server/publications.js<|end_filename|>
Stories._ensureIndex({
shortId: 1
}, {
unique: 1
});
Stories._ensureIndex({
published: 1
});
Stories._ensureIndex({
deleted: 1
});
Stories._ensureIndex({
authorId: 1
});
ContextBlocks._ensureIndex({
authorId: 1
});
ContextBlocks._ensureIndex({
storyShortId:1
});
StoryStats._ensureIndex({
storyId: 1
});
ActivityFeedItems._ensureIndex({
uId: 1
});
Meteor.users._ensureIndex({
username: 1
});
readStoryFields = {
draftStory: 0,
history: 0,
narrativeRightsReserved: 0,
//savedAt: 0, // used in analytics
//createdAt:0, // used in analytics
everPublished:0,
//analyticsBeforeReads:0, // need this to calculate read percentage TODO be more specific & ideally don't send to everyone
//deleted: 0, // currently always blank so no need to filter
//deletedAt: 0, // currently always blank so no need to filter
//'analytics.shares': 0,
//'contextBlocks.authorId': 0, // used in analytics
//'contextBlocks.storyShortId': 0, // used in analytics
'contextBlocks.storyId': 0,
'contextBlocks.version': 0,
'contextBlocks.savedAt': 0,
'contextBlocks.publishedAt': 0,
'contextBlocks.createdAt': 0,
'contextBlocks.fullDetails': 0,
'contextBlocks.published': 0,
'contextBlocks.everPublished': 0,
'contextBlocks.searchQuery': 0,
'contextBlocks.searchOption': 0
};
previewStoryFields = {
shortId: 1,
savedAt: 1,
r: 1,
publishedAt: 1,
published: 1,
userPathSegment: 1,
authorId: 1,
authorName: 1,
//authorUsername: 1, // don't need atm. can get from lowercasing the below
authorDisplayUsername: 1,
//favorited: 1, // will need to add this back in for non-curated stories to use preview
editorsPick: 1,
editorsPickAt: 1,
//'analytics.views': 1, // will need to add this back in for non-curated stories to use preview
contextBlockTypeCount: 1,
narrativeBlockCount: 1,
headerImageFormat: 1,
headerImage: 1,
favoritedTotal: 1,
storyPathSegment: 1,
title: 1,
keywords: 1
};
minimalUserFields = {
"profile": 1,
"username": 1,
displayUsername: 1,
"services.twitter.id": 1,
"followersTotal": 1,
"followingTotal": 1
};
// add preview fields again but nested under draftStory. also authorUsername until migrate
previewStoryFieldsWithDraft = _.extend({}, previewStoryFields, _.chain(previewStoryFields).keys().map(function(fieldName){return 'draftStory.' + fieldName}).object(_.values(previewStoryFields)).value(), {'authorUsername': 1});
Meteor.publish("curatedStoriesPub", function(options) {
options = options ? options : {};
_.defaults(options, {page: 0});
return Stories.find({
published: true,
editorsPick: true
}, {
fields: options.preview ? previewStoryFields : readStoryFields,
skip: options.page * PUB_SIZE,
sort: {
editorsPickAt: -1
},
limit: PUB_SIZE
});
});
var doOnlyCurated = function(options){
return Stories.find({
published: true,
editorsPick: true
}, {
fields: options.preview ? previewStoryFields : readStoryFields,
skip: options.page * PUB_SIZE,
sort: {
editorsPickAt: -1
},
limit: PUB_SIZE
});
};
Meteor.publish("curatedAndUserFollowingStoriesPub", function(options) {
options = options ? options : {};
_.defaults(options, {page: 0});
if(!this.userId){
return doOnlyCurated(options);
} else {
var user = Meteor.users.findOne(this.userId, {
fields: {
"profile.following" : 1
}
});
var userFollowing = user.profile.following || [];
if(!userFollowing || !userFollowing.length){
return doOnlyCurated(options)
}
}
// if user is following people, then return the follows and the curated
return Stories.find({
published: true,
$or:[
{authorId: {$in: _.sortBy(userFollowing, _.identity)}},
{editorsPick: true}
]
}, {
fields: options.preview ? previewStoryFields : readStoryFields,
skip: options.page * PUB_SIZE,
sort: {
r: -1
},
limit: PUB_SIZE
});
});
Meteor.publish("mixedStoriesPub", function(options) { // curated and specific authors
options = options ? options : {};
_.defaults(options, {page: 0, authors: []});
if(!this.userId){
return this.ready();
}
return Stories.find({
published: true,
$or:[
{authorId: {$in: _.sortBy(options.authors, _.identity)}},
{editorsPick: true}
]
}, {
fields: options.preview ? previewStoryFields : readStoryFields,
skip: options.page * PUB_SIZE,
sort: {
r: -1
},
limit: PUB_SIZE
});
});
Meteor.publish("newestStoriesPub", function(options) { // for now, it's just publishedAt (later should maybe be firstPublishedAt)
options = options ? options : {};
_.defaults(options, {page: 0});
return Stories.find({
published: true
}, {
fields: options.preview ? previewStoryFields : readStoryFields,
skip: options.page * PUB_SIZE,
sort: {
publishedAt: -1
},
limit: PUB_SIZE
});
});
Meteor.publish("trendingStoriesPub", function(options) { // for now, it's just the most views
options = options ? options : {};
_.defaults(options, {page: 0});
return Stories.find({
published: true
}, {
fields: options.preview ? previewStoryFields : readStoryFields,
skip: options.page * PUB_SIZE,
sort: {
'analytics.views.total': -1
},
limit: PUB_SIZE
});
});
Meteor.publish("starredStoriesPub", function(options) {
options = options ? options : {};
_.defaults(options, {page: 0});
return Stories.find({
published: true,
fields: options.preview ? previewStoryFields : readStoryFields,
skip: options.page * PUB_SIZE,
sort: {
'favoritedTotal': -1
},
limit: PUB_SIZE
});
});
Meteor.publish("favoriteStoriesPub", function(ids) { // requires ids to be passed in
return Stories.find({
published: true,
_id: { $in : ids }
}, {
fields: readStoryFields,
sort: {
publishedAt: -1
},
limit: PUB_SIZE
});
});
Meteor.publish("readStoryPub", function(userPathSegment, shortId) {
return Stories.find({
userPathSegment: userPathSegment,
shortId: shortId,
published: true
}, {
fields: readStoryFields,
limit: 1
});
});
Meteor.publish("createStoryPub", function(userPathSegment, shortId) {
return Stories.find({
userPathSegment: userPathSegment,
shortId: shortId,
deleted: {$ne: true}
}, {
fields: {
history: 0
},
limit: 1
});
});
Meteor.publish("contextBlocksPub", function(storyShortId) {
if(!storyShortId || !this.userId){
return this.ready();
}
return ContextBlocks.find({
storyShortId: storyShortId,
authorId: this.userId,
deleted: {$ne: true}
},{
fields : {
fullDetails: 0
},
limit: 1000
});
});
Meteor.publish("minimalUsersPub", function(userIds) {
if (!userIds || !userIds.length || userIds.length > 1000) {
return this.ready();
}
return Meteor.users.find({_id: {
$in: userIds
}}, {
fields: minimalUserFields
});
});
Meteor.publish("adminOtherUserPub", function(userId) {
if (!userId || !this.userId || !Meteor.users.findOne(this.userId).admin) {
return this.ready();
}
return Meteor.users.find({ _id: userId }, {
fields: {
"profile": 1,
"username": 1,
"services.twitter.id": 1,
"services.twitter.screenName": 1,
"emails.address": 1
},
limit: 1
});
});
Meteor.publish("adminMostFavoritesUsersPub", function() {
if (!this.userId || !Meteor.users.findOne(this.userId).admin) {
return this.ready();
}
return Meteor.users.find({ $where: "this.profile.favorites && this.profile.favorites.length > 5"}, {
fields: {
"services.twitter.screenName": 1,
"emails.address": 1,
"profile": 1
}
});
});
Meteor.publish("adminReadDraftPub", function(shortId) {
if (!this.userId || !Meteor.users.findOne(this.userId).admin) {
return this.ready();
}
return Stories.find({
shortId: shortId
}, {
fields: {
history: 0
},
limit: 1
});
});
Meteor.publish("adminContextBlocksPub", function(storyShortId) {
if(!storyShortId || !this.userId || !Meteor.users.findOne(this.userId).admin){
return this.ready();
}
return ContextBlocks.find({
storyShortId: storyShortId,
deleted: {$ne: true}
},{
fields : {
fullDetails: 0
},
limit: 1000
});
});
Meteor.publish("adminRecentDraftsPub", function(options) {
options = options || {};
options.more = options.more || 0;
if(!this.userId || !Meteor.users.findOne(this.userId).admin){
return this.ready();
}
return Stories.find({
published: false
}, {
fields: previewStoryFieldsWithDraft,
sort: {
savedAt: -1
},
limit: 250 * Math.pow(2, options.more)
});
});
Meteor.publish("adminRecentActivitiesPub", function(options) {
options = options || {};
options.more = options.more || 0;
if(!this.userId || !Meteor.users.findOne(this.userId).admin){
return this.ready();
}
return Activities.find({}, {
sort: {
published: -1
},
limit: 250 * Math.pow(2, options.more)
});
});
Meteor.publish("userProfilePub", function(username) { // includes user profile and favorited stories
var userCursor = Meteor.users.find({
username: username.toLowerCase()
}, {
fields: {
"profile" : 1,
"username" : 1,
"displayUsername" : 1,
"services.twitter.id": 1,
"followers": 1,
"followingTotal": 1,
"followersTotal": 1,
"favoritesTotal": 1
},
limit: 1
});
var user = userCursor.fetch()[0];
if (!user){
return this.ready();
}
var userFavorites = user.profile.favorites || [];
return [
userCursor,
Stories.find({
_id: {
$in: userFavorites
},
published: true
}, {
fields : previewStoryFields,
limit: 100 // initial limit
})]
});
Meteor.publish("userStoriesPub", function(username) { // only published stories
if (!username) {
return this.ready();
}
return Stories.find({
authorUsername: username,
published: true
},{
fields : previewStoryFields,
limit: 100 // initial limit
});
});
Meteor.publish("activityFeedItemsPub", function() {
if (this.userId) {
return ActivityFeedItems.find({
uId: this.userId
}, {
limit: 50,
sort: {
r: -1
}
});
} else {
return this.ready();
}
});
Meteor.publish("myStoriesPub", function() {
if (this.userId) {
return Stories.find({
authorId: this.userId,
deleted: {$ne: true}
}, {
fields: previewStoryFieldsWithDraft,
limit: 1000 // initial limit
});
} else {
return this.ready();
}
});
Meteor.publish("userData", function () {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {
'accessPriority': 1,
"services.twitter.id": 1,
"displayUsername": 1,
'tempUsername': 1,
"admin": 1,
"privileges": 1,
"profile": 1,
"followers": 1
},
limit: 1
});
} else {
this.ready();
}
});
// this publishes info on server facts (used on /stats page)
Facts.setUserIdFilter(function (userId) {
var user = Meteor.users.findOne(userId);
return user && user.admin;
});
<|start_filename|>server/fanout.js<|end_filename|>
var runFanout = function (options) {
options = options || {};
_.defaults(options, {logging: true});
if(options.logging){
console.log('Running fanout...');
}
var startTime = Date.now();
var previousTimepoint = Date.now();
var timeLogs = [];
var pendingActivities;
if (options.cleanup) {
pendingActivities = Activities.find({fanout: "in_progress"}); // find partially fanned out activities
pendingActivities.forEach(function(activity){
ActivityFeedItems.remove({aId: activity._id}); // remove the related feed items
});
// then try to fan them out again
timeLogs.push('in progress activities fetch and activity feed cleanup time: ' + ((Date.now() - previousTimepoint) / 1000) + ' seconds');
previousTimepoint = Date.now();
} else {
pendingActivities = Activities.find({fanout: "pending"}); // this is the default
}
timeLogs.push('pending activities fetch time: ' + ((Date.now() - previousTimepoint) / 1000) + ' seconds');
previousTimepoint = Date.now();
pendingActivities.forEach(fanoutActivity);
timeLogs.push('activity fanout time: ' + ((Date.now() - previousTimepoint) / 1000) + ' seconds');
previousTimepoint = Date.now();
if(options.logging) {
_.each(timeLogs, function (str) {
console.log(str);
});
console.log('Total time to run fanout: ' + ((Date.now() - startTime) / 1000) + ' seconds');
}
};
var fanOutWaitInSeconds = parseInt(process.env.FANOUT_WAIT) || 5 * 60; // default is every 5 minutes
if (process.env.PROCESS_TYPE === 'fanout_worker') { // if a worker process
Meteor.startup(function () {
while (true) {
runFanout();
Meteor._sleepForMs(fanOutWaitInSeconds * 1000);
}
});
} else if (process.env.PROCESS_TYPE === 'cleanup_fanout_worker') { // don't run this while fanout worker is running
Meteor.startup(function () {
runFanout({cleanup: true});
process.exit();
});
} else if (process.env.NODE_ENV === 'development') { // however, in developement, run fanout more quickly
Meteor.startup(function () {
var backgroundFanout = function(){
Meteor.setTimeout(function(){
runFanout({logging: false});
backgroundFanout();
}, 1000);
};
backgroundFanout();
});
}
| readFOLD/FOLD |
<|start_filename|>fbnn/SegSparseLinear.lua<|end_filename|>
local SegSparseLinear = torch.class('fbnn.SegSparseLinear', 'nn.Module')
local function getGetter(t)
if t:numel() == 0 then return nil end
local p = t:data()
assert(t:dim() == 1)
local s1 = t:stride(1)
local function getter(i1)
return p[(i1 - 1) * s1]
end
return getter
end
local function axpy(n, a, x, y)
for i = 0, (n - 1) do
y[i] = y[i] + a * x[i]
end
end
function SegSparseLinear:__init(inputSize, outputSize, useSparseGrad,
learningRateMul)
self.weight = torch.zeros(outputSize, inputSize) -- will be transposed
self.bias = torch.zeros(outputSize)
self.output = torch.zeros(outputSize)
-- sparse gradient of weight
self.sparseGradWeightPtr = {}
self._sparseBuf = torch.zeros(outputSize)
-- using sparse gradient will be a bit slower (D3376618)
self.useSparseGrad = useSparseGrad or false
if not self.useSparseGrad then
self.gradWeight = torch.zeros(inputSize, outputSize)
end
self.gradBias = torch.zeros(outputSize)
self.ones = torch.ones(100000)
self.learningRateMul = learningRateMul or 1
self:reset()
end
function SegSparseLinear:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:size(2))
end
self.weight:uniform(-stdv, stdv)
self.weight = self.weight:t():contiguous()
self.bias:uniform(-stdv, stdv):mul(1e-6)
end
function SegSparseLinear:setLearningRateMul(learningRateMul)
self.learningRateMul = learningRateMul
end
function SegSparseLinear:setUseSparseGrad(useSparseGrad)
if self.useSparseGrad == useSparseGrad then
return
end
if useSparseGrad then
self.gradWeight = nil
else
self.gradWeight = self.weight:clone():zero()
end
self.useSparseGrad = useSparseGrad
end
function SegSparseLinear:updateOutput(input)
local segs, keys, vals = unpack(input)
assert(self.output:isContiguous() and self.weight:isContiguous())
local n = segs:numel()
local m = self.weight:size(2)
local k = self.weight:size(1)
local batch_size = input.batch_size or segs:max()
self.output:resize(batch_size, self.bias:numel()):zero()
self.output:addr(self.ones:sub(1, batch_size), self.bias)
assert(n == 0 or (segs:max() <= batch_size and segs:min() >= 1 and
keys:max() <= k and keys:min() >= 1))
local segGet = getGetter(segs)
local valGet = getGetter(vals)
local keyGet = getGetter(keys)
local outputPtr = self.output:data()
local weightPtr = self.weight:data()
for i = 1, n do
axpy(m, valGet(i),
weightPtr + (keyGet(i) - 1) * m,
outputPtr + (segGet(i) - 1) * m)
end
return self.output
end
function SegSparseLinear:accGradParameters(input, gradOutput, scale)
local segs, keys, vals = unpack(input)
assert(self.gradBias:isContiguous() and gradOutput:isContiguous())
if not self.useSparseGrad then
assert(self.gradWeight:isContiguous())
end
local n = segs:numel()
local m = self.weight:size(2)
local k = self.weight:size(1)
local batch_size = input.batch_size or segs:max()
assert(gradOutput:size(1) == batch_size, 'inconsistent')
assert(n == 0 or (segs:max() <= batch_size and segs:min() >= 1 and
keys:max() <= k and keys:min() >= 1))
local segGet = getGetter(segs)
local valGet = getGetter(vals)
local keyGet = getGetter(keys)
if self.useSparseGrad then
local keySet = {}
local cnt = 0
for i = 1, n do
local key = tonumber(keyGet(i))
if keySet[key] == nil then
keySet[key] = cnt
cnt = cnt + 1
end
end
-- the content of a Tensor after resizing is undetermined
-- the elements of the resized tensor are contiguous in memory
self._sparseBuf:resize(cnt, m):zero()
local sparseBufPtr = self._sparseBuf:data()
for k, v in pairs(keySet) do
self.sparseGradWeightPtr[k] = sparseBufPtr + v * m
end
end
local gradOutputPtr = gradOutput:data()
local gradBiasPtr = self.gradBias:data()
local gradWeightPtr = self.gradWeight and self.gradWeight:data()
self.lastInput = input
for i = 1, n do
local key = tonumber(keyGet(i))
local gradWeightRowPtr
if self.useSparseGrad then
gradWeightRowPtr = self.sparseGradWeightPtr[key]
else
gradWeightRowPtr = gradWeightPtr + (key - 1) * m
end
axpy(m, scale * valGet(i),
gradOutputPtr + (segGet(i) - 1) * m,
gradWeightRowPtr)
end
for i = 1, batch_size do
axpy(m, scale, gradOutputPtr + (i - 1) * m, gradBiasPtr)
end
end
function SegSparseLinear:updateParameters(learningRate)
learningRate = learningRate * self.learningRateMul
assert(self.lastInput, 'call backward first')
local keys = self.lastInput[2]
assert(self.weight:isContiguous() and self.gradBias:isContiguous())
local n = keys:numel()
local m = self.weight:size(2)
local k = self.weight:size(1)
assert(n == 0 or (keys:max() <= k and keys:min() >= 1))
local keyGet = getGetter(keys)
local weightPtr = self.weight:data()
local gradWeightPtr = self.gradWeight and self.gradWeight:data()
local updatedKeys = {}
for i = 1, n do
local key = tonumber(keyGet(i))
if not updatedKeys[key] then
local gradWeightRowPtr
if self.useSparseGrad then
gradWeightRowPtr = self.sparseGradWeightPtr[key]
else
gradWeightRowPtr = gradWeightPtr + (key - 1) * m
end
axpy(m, -learningRate,
gradWeightRowPtr,
weightPtr + (key - 1) * m)
-- zero out dense grad here; zero out sparse grad when resizing
if not self.useSparseGrad then
for j = 0, (m - 1) do
gradWeightRowPtr[j] = 0
end
end
updatedKeys[key] = true
end
end
self.bias:add(-learningRate, self.gradBias)
-- zero out gradBias here
self.gradBias:zero()
self.lastInput = nil
end
function SegSparseLinear:zeroGradParameters()
-- done in updateParameters. not needed here.
self.sparseGradWeightPtr = {}
end
function SegSparseLinear:updateGradInput(input, gradOutput)
-- always assume this is the first layer and we don't back-prop to data
end
function SegSparseLinear:__tostring__()
return torch.type(self) ..
string.format('(%d -> %d)', self.weight:size(1), self.weight:size(2)) ..
(self.bias == nil and ' without bias' or '')
end
<|start_filename|>fbnn/NormalizedLinearNoBias.lua<|end_filename|>
local Linear, parent = torch.class('fbnn.NormalizedLinearNoBias', 'nn.Linear')
--[[
This module creates a Linear layer, but with no bias component.
In training mode, it constantly self-normalizes it's weights to
be of unit norm.
]]--
function Linear:__init(inputSize, outputSize)
parent.__init(self, inputSize, outputSize)
self.bias:zero()
end
function Linear:updateOutput(input)
if self.train then
-- in training mode, renormalize the weights
-- before every forward call
self.weight:div(self.weight:norm())
local scale = math.sqrt(self.weight:size(1))
self.weight:mul(scale)
end
return parent.updateOutput(self, input)
end
function Linear:accGradParameters(input, gradOutput, scale)
scale = scale or 1
if input:dim() == 1 then
self.gradWeight:addr(scale, gradOutput, input)
elseif input:dim() == 2 then
self.gradWeight:addmm(scale, gradOutput:t(), input)
end
end
<|start_filename|>fbnn/SparseKmax.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
local sparse = require 'sparse'
--[[
This module performs a sparse embedding with the following process:
1. Perform a dense embedding
2. Apply a linear transformation (to high dimensional space)
3. Make the output k-sparse
The parameters of the dense embedding and the linear transformation are
learned. Since the fprop may be slow, we keep a candidate set for each word
which consists of the most likely indices to be turned on after the k-max
operation. We record the number of activations for each member of this set,
and periodically resize it to keep only the most active indices.
Thus the initial training with large candidate sets will be slow, but will
get faster and faster as we restrict their sizes.
]]
local SparseKmax, parent = torch.class('nn.SparseKmax','nn.Module')
--[[
Parameters:
* `vocabSize` - number of entries in the dense lookup table
* `nDenseDim` - number of dimensions for initial dense embedding
* `nSparseDim` - number of dimensions for final sparse embedding
* `k` - number of nonzeros in sparse space
* `nCandidates` - initial size of the candidate set
]]
function SparseKmax:__init(vocabSize,nDenseDim,nSparseDim,k,nCandidates)
self.nDenseDim = nDenseDim
self.nSparseDim = nSparseDim
self.K = k
self.nCandidates = nCandidates
self.weights = torch.FloatTensor(nSparseDim,nDenseDim)
self.counts = torch.FloatTensor(vocabSize,nCandidates)
self.candidates = torch.ShortTensor(vocabSize,nCandidates)
self.denseEmbedding = nn.WeightedLookupTable(vocabSize,nDenseDim)
for i = 1,vocabSize do
self.candidates[i]:copy(torch.range(1,nCandidates))
end
-- Intermediate gradients wrt outputs of dense embeddings.
self.gradEmbeddings = torch.FloatTensor(1,nDenseDim)
-- Intermediate gradients wrt inputs to k-max layer.
self.gradInputKmax = torch.FloatTensor(1,self.K,2)
-- This stores activations before k-max operation.
self.activations = torch.FloatTensor(nCandidates,2)
self.output = torch.FloatTensor(1,self.K,2)
self:reset()
end
function SparseKmax:reset(stdv)
self.denseEmbedding:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weights:size(2))
end
self.counts:zero()
self.weights:uniform(-stdv,stdv)
end
function SparseKmax:updateOutput(input)
local nInputs = input:size(1)
-- Compute outputs of the dense embedding.
self.dense = self.denseEmbedding:forward(input)
self.output:resize(nInputs,self.K,2)
-- Loop over the dense embeddings of the input words.
for i = 1,input:size(1) do
local candidates = self.candidates[input[i][1]]
-- Copy the indices of candidates into the output.
self.activations[{{},1}]:copy(candidates)
self.activations[{{},2}]:zero()
-- Compute the activations for each element of the candidate set.
sparse.SaddMtimesDoverlap(self.weights,self.dense[i],self.activations)
-- Pick top k and copy the scores/indices into the output.
-- We sort the indices since this will likely be needed later.
local topk_val,topk_indx = torch.topk(self.activations[{{},2}],self.K)
local sorted_indices,sorting_indx
= torch.sort(candidates:index(1,topk_indx:long()))
self.output[{i,{},1}]:copy(sorted_indices)
self.output[{i,{},2}]:copy(topk_val:index(1,sorting_indx))
-- Increment counts.
for j = 1,self.K do
self.counts[input[i][1]][topk_indx[j]] = self.counts[input[i][1]][topk_indx[j]] + 1
end
end
return self.output
end
-- Update the candidate set based on the counts of activations.
-- `nCandidates` is the size of the new candidate sets.
function SparseKmax:updateCandidateSets(nCandidates)
self.nCandidates = nCandidates
local nEntities = self.candidates:size(1)
local newCandidates = torch.FloatTensor(nEntities,nCandidates)
-- For each entity, find indices of top activations and keep them.
for i = 1,nEntities do
local _,topk = torch.topk(self.counts[i],nCandidates)
newCandidates[i]:copy(self.candidates[i]:index(1,topk:long()))
end
self.candidates = newCandidates
self.counts:zero()
self.activations = torch.FloatTensor(nCandidates,2)
end
-- Note, we assume `gradOutput` is sparse since the output is sparse as well.
function SparseKmax:accUpdateGradParameters(input, gradOutput, lr)
lr = lr or 1
local nInputs = input:size(1)
self.gradEmbeddings:resize(nInputs,self.nDenseDim)
self.gradEmbeddings:zero()
self.gradInputKmax:resize(nInputs,self.K,2)
for i = 1,nInputs do
-- Compute gradients wrt kmax input.
self.gradInputKmax[{i,{},1}]:copy(self.output[i][{{},1}])
self.gradInputKmax[{i,{},2}]:zero()
sparse.SaddSoverlap(self.gradInputKmax[i],gradOutput[i])
-- Compute gradients wrt dense embedding output.
sparse.addMtimesS(self.weights:t(),self.gradInputKmax[i],self.gradEmbeddings[i])
end
-- Update the weights.
for i = 1,nInputs do
sparse.addDouterS(self.denseEmbedding.output[i], self.gradInputKmax[i], self.weights:t(),-lr)
end
-- Update the dense embedding weights.
self.denseEmbedding:accUpdateGradParameters(input,self.gradEmbeddings,lr)
end
<|start_filename|>fbnn/CrossMapNormalization.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
--[[
Cross-map normalization, see
https://code.google.com/p/cuda-convnet/wiki/LayerParams#Local_response_normalization_layer_(across_maps)
formula:
$${f(u_{f}^{x,y})=\frac{u_{f}^{x,y}}{ (1+\frac{\alpha}{N} \sum_{f'=\max(0,F-\lfloor N/2\rfloor )}^{\min(F,f-\lfloor N/2 \rfloor+N) }(u_{f'}^{x,y})^{2})^{\beta}}}$$
where
* ${F}$ is the number of features,
* ${N}$ is the neighborhood size (size),
* ${\alpha}$ is the scaling factor (scale),
* ${\beta}$ is the exponent (power)
This layer normalizes values across feature maps (each spatial location
independently). Borders are zero-padded.
Parameters:
* `size`: size of the neighborhood (typical value: 5)
* `scale`: scaling factor (typical value: 0.0001)
* `power`: exponent used (typical value: 0.75)
]]
local CrossMapNormalization, parent =
torch.class('nn.CrossMapNormalization', 'nn.Module')
function CrossMapNormalization:__init(size, scale, power)
parent.__init(self)
self.size = size
self.scale = scale
self.power = power
self.output = torch.Tensor()
self.gradInput = torch.Tensor()
-- squaredSum is an intermediate results cache computed
-- during updateOutput() and used b updateGradInput() to
-- speedup computation.
self.squaredSum = torch.Tensor()
end
function CrossMapNormalization:updateOutput(input)
return input.nn.CrossMapNormalization_updateOutput(self, input)
end
function CrossMapNormalization:updateGradInput(input, gradOutput)
return input.nn.CrossMapNormalization_updateGradInput(
self, input, gradOutput)
end
<|start_filename|>fbnn/Probe.lua<|end_filename|>
local Probe, parent = torch.class('fbnn.Probe', 'nn.Module')
function Probe:__init(module, name)
-- nn.legacy = true
if not nn.legacy then
error('ATM nn.legacy needs to be set to true for this module to work !')
end
parent.__init(self)
self.name = name or 'unnamed'
-- Use 'modules' in order to specify submodules that get converted to cuda
self.modules = {}
self.modules[1] = module
self:resetTensors()
self._type = self.modules[1]._type
nn._ProbeTimer = nn._ProbeTimer or torch.Timer()
end
function Probe:reset(stdv)
self.modules[1]:reset(stdv)
self:resetTensors()
end
function Probe:resetTensors()
if self.modules[1].weight then
self.weight = self.modules[1].weight
end
if self.modules[1].gradWeight then
self.gradWeight = self.modules[1].gradWeight
end
if self.modules[1].bias then
self.bias = self.modules[1].bias
end
if self.modules[1].gradBias then
self.gradBias = self.modules[1].gradBias
end
if self.modules[1].output then
self.output = self.modules[1].output
end
if self.modules[1].gradInput then
self.gradInput = self.modules[1].gradInput
end
end
function Probe:setTensors()
if self.weight then
self.modules[1].weight = self.weight
end
if self.gradWeight then
self.modules[1].gradWeight = self.gradWeight
end
if self.bias then
self.modules[1].bias = self.bias
end
if self.gradBias then
self.modules[1].gradBias = self.gradBias
end
if self.output then
self.modules[1].output = self.output
end
if self.gradInput then
self.modules[1].gradInput = self.gradInput
end
end
local function dumpTensorMoments(str, t)
if t and t:nDimension() > 0 then
print(str, t:min(), t:max(), t:mean(), t:std(), t:sum())
end
end
local function dumpTensorOrTableMoments(str, t)
if torch.type(t) == 'table' then
for i=1, #t do
if torch.type(t) == 'torch.IntTensor' then
dumpTensorMoments(str, t[i]:float())
else
dumpTensorMoments(str, t[i])
end
end
else
if torch.type(t) == 'torch.IntTensor' then
dumpTensorMoments(str, t:float())
else
dumpTensorMoments(str, t)
end
end
end
function Probe:dumpModule(name, input, ...)
print('\n-----------------------------')
print(name)
local arg = {...}
dumpTensorOrTableMoments('module computation input', input)
for i = 3, #arg do
dumpTensorOrTableMoments('module computation result ' .. (i - 2), arg[i])
end
local m = self.modules[1]
dumpTensorOrTableMoments('module weight ', m.weight)
dumpTensorOrTableMoments('module gradWeight', m.gradWeight)
dumpTensorOrTableMoments('module bias ', m.bias)
dumpTensorOrTableMoments('module gradBias ', m.gradBias)
dumpTensorOrTableMoments('module output ', m.output)
dumpTensorOrTableMoments('module gradInput ', m.gradInput)
end
function Probe:updateOutput(input)
self:setTensors()
self:dumpModule('Start UpdateOutput ' .. self.name, input)
self.modules[1].output = self.modules[1]:updateOutput(input)
self:resetTensors()
self:dumpModule('End UpdateOutput ' .. self.name, input, self.output)
return self.output
end
function Probe:updateGradInput(input, gradOutput)
self:setTensors()
self:dumpModule('Start UpdateGradInput ' .. self.name, gradOutput)
self.modules[1].gradInput =
self.modules[1]:updateGradInput(input, gradOutput)
self:resetTensors()
self:dumpModule('End UpdateGradInput ' .. self.name,
gradOutput,
self.gradInput)
return self.gradInput
end
function Probe:accGradParameters(input, gradOutput, scale)
self:setTensors()
self:dumpModule('Start AccGradParameters ' .. self.name, gradOutput)
self.modules[1]:accGradParameters(input, gradOutput, scale)
self:resetTensors()
self:dumpModule('End AccGradParameters ' .. self.name,
gradOutput,
self.gradWeight,
self.gradBias)
end
<|start_filename|>fbnn/LinearNB.lua<|end_filename|>
local LinearNB, parent = torch.class('nn.LinearNB', 'nn.Linear')
--[[
This file is still here because of backward compatibility. It is preferred you
use `nn.Linear(input, output, false)` instead.
]]--
function LinearNB:__init(inputSize, outputSize)
parent.__init(self, inputSize, outputSize, false)
end
<|start_filename|>src/WeightedLookupTable.cpp<|end_filename|>
/**
* Copyright 2015 Facebook
*/
#include <lua.hpp>
#include <luaT.h>
#include "fblualib/LuaUtils.h"
#include "thpp/Storage.h"
#include "thpp/Tensor.h"
namespace facebook { namespace deeplearning { namespace torch {
using namespace fblualib;
using namespace thpp;
namespace {
template <class T>
int scaleByWeight(lua_State* L) {
auto output = luaGetTensorChecked<T>(L, 1);
auto const input = luaGetTensorChecked<T>(L, 2);
auto const weights = luaGetTensorChecked<T>(L, 3);
#pragma omp parallel for if(output->size(0) * output->size(1) > 100000)
for (int i = 0; i < output->size(0); ++i) {
T weight = weights->at({i});
T *outputData = output->data() + i * output->stride(0);
const T *inputData = input->data() + i * input->stride(0);
for (int j = 0; j < output->size(1); ++j) {
outputData[j * output->stride(1)] =
inputData[j * input->stride(1)] * weight;
}
}
return 0;
}
template <class T>
class Registerer {
private:
static const luaL_Reg functions_[];
public:
static void registerFunctions(lua_State* L);
};
template <class T>
const luaL_Reg Registerer<T>::functions_[] = {
{"WeightedLookupTable_scaleByWeight", scaleByWeight<T>},
{nullptr, nullptr},
};
template <class T>
void Registerer<T>::registerFunctions(lua_State* L) {
luaT_pushmetatable(L, Tensor<T>::kLuaTypeName);
luaT_registeratname(L, functions_, "nn");
lua_pop(L, 1);
}
} // namespace
void initWeightedLookupTable(lua_State* L) {
Registerer<float>::registerFunctions(L);
Registerer<double>::registerFunctions(L);
}
}}} // namespaces
<|start_filename|>fbnn/LeakyReLU.lua<|end_filename|>
local LeakyReLU, parent = torch.class('fbnn.LeakyReLU', 'nn.PReLU')
function LeakyReLU:__init(p)
parent.__init(self)
self.weight:fill(p)
self.gradWeight:fill(0)
end
function LeakyReLU:__tostring__()
return torch.type(self) .. string.format('(%g)', self.weight[1])
end
function LeakyReLU:accGradParameters(input, gradOutput, scale)
end
function LeakyReLU:zeroGradParameters()
end
function LeakyReLU:updateParameters(learningRate)
end
<|start_filename|>fbnn/ClassHierarchicalNLLCriterion.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
--[[
Hierarchical softmax classifier with two levels and arbitrary clusters.
Note:
This criterion does include the lower layer parameters
(this is more `Linear` + `ClassNLLCriterion`, but hierarchical).
Also, this layer does not support the use of mini-batches
(only 1 sample at the time).
]]
local ClassHierarchicalNLLCriterion, parent = torch.class(
'nn.ClassHierarchicalNLLCriterion', 'nn.Criterion')
--[[
Parameters:
* `mapping` is a tensor with as many elements as classes.
`mapping[i][1]` stores the cluster id, and `mapping[i][2]` the class id within
that cluster of the ${i}$-th class.
* `clusterCounts` is a vector with as many entry as clusters.
clusterCounts[i] stores the number of classes in the i-th cluster.
* `inputSize` is the number of input features
]]
function ClassHierarchicalNLLCriterion:__init(mapping, clusterCounts, inputSize)
parent.__init(self)
local numClusters = clusterCounts:size(1)
local numClasses = mapping:size(1)
assert(numClasses == clusterCounts:sum())
self.mapping = torch.Tensor(mapping)
-- stores the start index of each cluster, useful to slice classMatrix
self.startIndex = torch.ones(numClusters)
for cc = 2, numClusters do
self.startIndex[cc] = self.startIndex[cc - 1] + clusterCounts[cc - 1]
end
self.clusterCounts = torch.Tensor(clusterCounts)
-- Parameters
local stdev = 1./math.sqrt(inputSize)
self.clusterMatrix = torch.randn(numClusters, inputSize) * stdev
self.classMatrix = torch.randn(numClasses, inputSize) * stdev
self.clusterBias = torch.zeros(numClusters)
self.classBias = torch.zeros(numClasses)
self.clusterMatrixDx = torch.zeros(numClusters, inputSize)
self.classMatrixDx = torch.zeros(numClasses, inputSize)
self.clusterBiasDx = torch.zeros(numClusters)
self.classBiasDx = torch.zeros(numClasses)
-- Log Losses for cluster and class prediction (the latter is shared across
-- all clusters, since the grad. w.r.t. input is reshaped anyway).
self.logSMCluster = nn.LogSoftMax()
self.logSMClass = nn.LogSoftMax()
self.logLossCluster = nn.ClassNLLCriterion()
self.logLossClass = nn.ClassNLLCriterion()
-- Buffers (values just before logSoftmax)
self.outputCluster = torch.zeros(numClusters)
self.outputClass = torch.zeros(numClasses)
self.outputClusterDx = torch.zeros(numClusters)
self.outputClassDx = torch.zeros(numClasses)
-- Variables storing IDs for current sample
self.clusterID = 0
self.classID = 0
self.startCluster = 0
self.numClasses = 0
end
-- `target` is the class id
function ClassHierarchicalNLLCriterion:updateOutput(input, target)
assert(input:dim() == 1) -- we do not support mini-batch training
self.clusterID = self.mapping[target][1]
self.classID = self.mapping[target][2]
self.startCluster = self.startIndex[self.clusterID]
self.numClasses = self.clusterCounts[self.clusterID]
local loss = 0
-- Prediction of cluster
self.outputCluster:mv(self.clusterMatrix, input)
self.outputCluster:add(self.clusterBias)
loss = self.logLossCluster:forward(self.logSMCluster:forward(
self.outputCluster), self.clusterID)
-- Prediction of class within the cluster
self.outputClass:narrow(1, self.startCluster, self.numClasses):mv(
self.classMatrix:narrow(1, self.startCluster, self.numClasses), input)
self.outputClass:narrow(1, self.startCluster, self.numClasses):add(
self.classBias:narrow(1, self.startCluster, self.numClasses))
loss = loss + self.logLossClass:forward(
self.logSMClass:forward(
self.outputClass:narrow(1, self.startCluster, self.numClasses)),
self.classID)
self.output = loss
return self.output
end
function ClassHierarchicalNLLCriterion:zeroGradParameters()
self.clusterBiasDx:zero()
self.clusterMatrixDx:zero()
self.classBiasDx:zero()
self.classMatrixDx:zero()
end
function ClassHierarchicalNLLCriterion:zeroGradParametersCluster()
self.clusterBiasDx:zero()
self.clusterMatrixDx:zero()
end
function ClassHierarchicalNLLCriterion:zeroGradParametersClass(target)
local clusterID = self.mapping[target][1]
local startCluster = self.startIndex[clusterID]
local numClasses = self.clusterCounts[clusterID]
self.classMatrixDx:narrow(1, startCluster, numClasses):zero()
self.classBiasDx:narrow(1, startCluster, numClasses):zero()
end
-- This computes derivatives w.r.t. input and parameters.
function ClassHierarchicalNLLCriterion:updateGradInput(input, target)
assert(input:dim() == 1) -- we do not support mini-batch training
self.gradInput:resizeAs(input)
-- BPROP through the cluster prediction
self.logLossCluster:updateGradInput(self.logSMCluster.output, self.clusterID)
self.logSMCluster:updateGradInput(self.outputCluster,
self.logLossCluster.gradInput)
self.clusterBiasDx:add(self.logSMCluster.gradInput)
self.gradInput:mv(self.clusterMatrix:t(), self.logSMCluster.gradInput)
self.clusterMatrixDx:addr(self.logSMCluster.gradInput, input)
-- BPROP through the cluster prediction
self.logLossClass:updateGradInput(self.logSMClass.output, self.classID)
self.logSMClass:updateGradInput(
self.outputClass:narrow(1, self.startCluster, self.numClasses),
self.logLossClass.gradInput)
self.classBiasDx:narrow(1, self.startCluster, self.numClasses):add(
self.logSMClass.gradInput)
self.gradInput:addmv(
self.classMatrix:narrow(1, self.startCluster, self.numClasses):t(),
self.logSMClass.gradInput)
self.classMatrixDx:narrow(1, self.startCluster, self.numClasses):addr(
self.logSMClass.gradInput, input)
return self.gradInput
end
-- Update parameters (only those that are used to process this sample).
function ClassHierarchicalNLLCriterion:updateParameters(learningRate)
self.classMatrix:narrow(1, self.startCluster, self.numClasses):add(
-learningRate,
self.classMatrixDx:narrow(1, self.startCluster, self.numClasses))
self.classBias:narrow(1, self.startCluster, self.numClasses):add(
-learningRate,
self.classBiasDx:narrow(1, self.startCluster, self.numClasses))
self.clusterMatrix:add(-learningRate, self.clusterMatrixDx)
self.clusterBias:add(-learningRate, self.clusterBiasDx)
end
-- input is a vector of probabilities (non-negative and sums to 1).
function sampleMultiNomial(input)
local numVal = input:size(1)
local rndu = (math.random(1000000) - 1) / (1000000 - 1)
local tot = 0
local cnt = 0
for c = 1, numVal do
cnt = cnt + 1
tot = tot + input[c]
if tot > rndu then break end
end
return cnt
end
-- Inference of the output (to be used at test time only)
-- If sampling flag is set to true, then the output label is sampled
-- o/w the most likely class is provided.
function ClassHierarchicalNLLCriterion:infer(input, sampling)
assert(input:dim() == 1) -- we do not support mini-batch training
-- Prediction of cluster
self.outputCluster:mv(self.clusterMatrix, input)
self.outputCluster:add(self.clusterBias)
if sampling ~= nil and sampling == true then
local prob = self.logSMCluster:forward(self.outputCluster)
prob:exp()
prob:div(prob:sum())
self.clusterID = sampleMultiNomial(prob)
else
local val, indx = torch.max(self.outputCluster, 1)
self.clusterID = indx[1]
end
self.startCluster = self.startIndex[self.clusterID]
self.numClasses = self.clusterCounts[self.clusterID]
-- Prediction of class within the cluster
self.outputClass:narrow(1, self.startCluster, self.numClasses):mv(
self.classMatrix:narrow(1, self.startCluster, self.numClasses), input)
self.outputClass:narrow(1, self.startCluster, self.numClasses):add(
self.classBias:narrow(1, self.startCluster, self.numClasses))
if sampling ~= nil and sampling == true then
local prob = self.logSMClass:forward(
self.outputClass:narrow(1, self.startCluster, self.numClasses))
prob:exp()
prob:div(prob:sum())
self.classID = sampleMultiNomial(prob)
else
local val, indx = torch.max(
self.outputClass:narrow(1, self.startCluster, self.numClasses), 1)
self.classID = indx[1]
end
return {self.clusterID, self.classID}
end
-- Given some label, it computes the logprob and the ranking error.
function ClassHierarchicalNLLCriterion:eval(input, target)
self:updateOutput(input, target)
self.logSMCluster.output:exp()
self.logSMCluster.output:div(self.logSMCluster.output:sum())
local logProb = math.log10(self.logSMCluster.output[self.clusterID])
self.logSMClass.output:exp()
self.logSMClass.output:div(self.logSMClass.output:sum())
logProb = logProb + math.log10(self.logSMClass.output[self.classID])
-- Estimate ranking error
self.clusterID = math.random(self.logSMCluster.output:size(1))
self.classID = math.random(self.clusterCounts[self.clusterID])
local cnt = 1
while self.clusterID == self.mapping[target][1] and
self.classID == self.mapping[target][2] and cnt < 1000 do
self.clusterID = math.random(self.logSMCluster.output:size(1))
self.classID = math.random(self.clusterCounts[self.clusterID])
cnt = cnt + 1
end
if cnt == 1000 then
print('Warning ClassHierarchicalNLLCriterion:eval ' ..
'I could not find a good negative sample!')
end
self.startCluster = self.startIndex[self.clusterID]
self.numClasses = self.clusterCounts[self.clusterID]
local logProbRandLabel = math.log10(
self.logSMCluster.output[self.clusterID])
self.outputClass:narrow(1, self.startCluster, self.numClasses):mv(
self.classMatrix:narrow(1, self.startCluster, self.numClasses), input)
self.outputClass:narrow(1, self.startCluster, self.numClasses):add(
self.classBias:narrow(1, self.startCluster, self.numClasses))
self.logSMClass:forward(
self.outputClass:narrow(1, self.startCluster, self.numClasses))
self.logSMClass.output:exp()
self.logSMClass.output:div(self.logSMClass.output:sum())
logProbRandLabel = logProbRandLabel +
math.log10(self.logSMClass.output[self.classID])
local rankErr = (logProb > logProbRandLabel) and 0 or 1
return logProb, rankErr
end
<|start_filename|>fbnn/SparseLookupTable.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
--[[
Sparse lookup table. Similar to the regular LookupTable.lua module,
except for the following differences:
1. The outputs are in sparse format.
2. The inputs are pairs (i,w), so the output corresponding to index i
is scaled by w.
3. The indices are fixed, i.e. during a parameter update only the nonzero
coefficents are updated. This is to avoid having to create new indices,
which is expensive and may result in the weights no longer being sparse.
]]
local SparseLookupTable, parent = torch.class('nn.SparseLookupTable','nn.Module')
local sparse = require 'sparse'
--[[
Parameters:
* `indices` is a 2D matrix of indices which will be nonzero.
* `sparseGrad` indicates whether incoming gradients will be sparse or dense.
]]
function SparseLookupTable:__init(indices,sparseGrad)
parent.__init(self)
self.nEntities = indices:size(1)
self.nIndices = indices:size(2)
self.sparseGrad = sparseGrad or true
self.weight = torch.Tensor(self.nEntities,self.nIndices,2)
self.weight[{{},{},1}]:copy(indices)
self.gradWeight = torch.Tensor(self.nEntities,self.nIndices,2)
self:reset()
end
function SparseLookupTable:reset(stdv)
stdv = stdv or 1
self.weight[{{},{},2}]:normal(0, stdv)
end
function SparseLookupTable:updateOutput(input)
local nIndex = input:size(1)
self.output:resize(nIndex,self.nIndices,2)
for i=1,nIndex do
local indx = input[i][1]
local weight = input[i][2]
self.output[i]:copy(self.weight[indx])
self.output[i][{{},2}]:mul(weight)
end
return self.output
end
function SparseLookupTable:accUpdateGradParameters(input, gradOutput,lr)
for i=1,input:size(1) do
local indx = input[i][1]
local weight = input[i][2]
if self.sparseGrad then
sparse.SaddSoverlap(self.weight[indx], gradOutput[i], -lr*weight)
else
sparse.SaddDoverlap(self.weight[indx], gradOutput[i], -lr*weight)
end
end
end
<|start_filename|>init.c<|end_filename|>
#include "TH.h"
#include "luaT.h"
#define torch_(NAME) TH_CONCAT_3(torch_, Real, NAME)
#define torch_Tensor TH_CONCAT_STRING_3(torch.,Real,Tensor)
#define nn_(NAME) TH_CONCAT_3(nn_, Real, NAME)
#include "src/DataSetLabelMe.c"
#include "THGenerateFloatTypes.h"
#include "src/FasterLookup.c"
#include "THGenerateFloatTypes.h"
#include "src/SparseLinear.c"
#include "THGenerateFloatTypes.h"
LUA_EXTERNC DLL_EXPORT int luaopen_libfbnn(lua_State *L);
int luaopen_libfbnn(lua_State *L)
{
nn_FloatDataSetLabelMe_init(L);
nn_DoubleDataSetLabelMe_init(L);
nn_FloatFasterLookup_init(L);
nn_DoubleFasterLookup_init(L);
nn_FloatSparseLinear_init(L);
nn_DoubleSparseLinear_init(L);
lua_newtable(L);
lua_pushvalue(L, -1);
lua_setfield(L, LUA_GLOBALSINDEX, "fbnn");
return 1;
}
<|start_filename|>fbnn/GroupKMaxPooling.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
--[[
Group k-max pooling performs pooling along a dimension of arbitrary length
(e.g. a sentence) down to a length of ${k}$.
Given a matrix where rows are words and columns are embedding dimensions, we
compute the ${L^2}$ norm of each word:
```
o---------o
w1 | | -> norm1
w2 | | -> norm2
w3 | | -> norm3
w4 | | -> norm4
o---------o
```
Group K-max pooling keeps the K words with largest norm and discards the
rest.
]]
local GroupKMaxPooling, parent =
torch.class('nn.GroupKMaxPooling', 'nn.Module')
function GroupKMaxPooling:__init(k, k_dynamic)
parent.__init(self)
self.k = k
self.k_dynamic = k_dynamic or -1
self.output = torch.Tensor()
self.gradInput = torch.Tensor()
self.switches = torch.LongTensor()
end
function GroupKMaxPooling:updateOutput(input)
if input:dim() == 2 then
group_norms = torch.norm(input, 2, 2)
else
group_norms = torch.norm(input, 2, 3)
end
input = input:contiguous()
return input.nn.GroupKMaxPooling_updateOutput(self, input, group_norms)
end
function GroupKMaxPooling:updateGradInput(input, gradOutput)
input = input:contiguous()
gradOutput = gradOutput:contiguous()
return input.nn.GroupKMaxPooling_updateGradInput(self, input, gradOutput)
end
<|start_filename|>src/SparseNLLCriterion.cpp<|end_filename|>
// Copyright 2004-present Facebook. All Rights Reserved.
// Author: <NAME> <<EMAIL>>
#include <algorithm>
#include <cstdio>
#include <memory>
#include <limits>
#include <lua.hpp>
#include <mkl.h>
#include <luaT.h>
#ifndef __clang__
#include <omp.h>
#endif
#include "fblualib/LuaUtils.h"
#include "thpp/Storage.h"
#include "thpp/Tensor.h"
#include "Blas.h"
#include "Vml.h"
#include <folly/Format.h>
namespace facebook {
namespace deeplearning {
namespace torch {
using namespace fblualib;
using namespace thpp;
namespace {
template <class T> using thOps = thpp::detail::TensorOps<T>;
template <class T>
int updateOutput(lua_State* L) {
auto output = luaGetFieldIfTensorChecked<T>(L, 1, "output");
auto input = luaGetTensorChecked<T>(L, 2);
auto targetP = luaGetTensorChecked<T>(L, 3);
auto targetIdx = luaGetTensorChecked<long>(L, 4);
auto batchSize = targetP->size(0);
auto K = targetP->size(1);
auto nClasses = input->size(1);
luaL_argcheck(L, (output->ndims() == 1) && (output->size(0) == 1),
1, "output has wrong dimension");
luaL_argcheck(L, (input->ndims() == 2) && (input->size(0) == batchSize)
&& (input->isContiguous()),
2, "input has wrong dimension");
luaL_argcheck(L, (targetP->ndims() == 2) && (targetP->isContiguous()),
3, "targetP has wrong dimension");
luaL_argcheck(L,
(targetIdx->ndims() == 2) && (targetIdx->size(0) == batchSize)
&& (targetIdx->size(1) == K) && (targetIdx->isContiguous()),
3, "targetIdx has wrong dimension");
auto targetIdxData = targetIdx->data();
auto targetPData = targetP->data();
auto inputData = input->data();
T outputVal = 0.;
for (int i = 0; i < batchSize; ++i) {
auto targetIdxBatch = targetIdxData + i*K;
auto targetPBatch = targetPData + i*K;
auto inputBatch = inputData + i*nClasses;
for (int j = 0; j < K; ++j) {
outputVal += inputBatch[targetIdxBatch[j] - 1] * targetPBatch[j];
}
}
output->data()[0] = - outputVal;
return 0;
}
template <class T>
int updateGradInput(lua_State* L) {
auto gradInput = luaGetFieldIfTensorChecked<T>(L, 1, "gradInput");
auto targetP = luaGetTensorChecked<T>(L, 2);
auto targetIdx = luaGetTensorChecked<long>(L, 3);
auto batchSize = targetP->size(0);
auto K = targetP->size(1);
auto nClasses = gradInput->size(1);
luaL_argcheck(L,
(gradInput->ndims() == 2) && (gradInput->size(0) == batchSize)
&& (gradInput->isContiguous()),
1, "gradInput has wrong dimension");
luaL_argcheck(L, (targetP->ndims() == 2) && (targetP->isContiguous()),
2, "targetP has wrong dimension");
luaL_argcheck(L,
(targetIdx->ndims() == 2) && (targetIdx->size(0) == batchSize)
&& (targetIdx->size(1) == K) && (targetIdx->isContiguous()),
2, "targetIdx has wrong dimension");
auto targetIdxData = targetIdx->data();
auto targetPData = targetP->data();
auto gradInputData = gradInput->data();
gradInput->zero();
for (int i = 0; i < batchSize; ++i) {
auto targetIdxBatch = targetIdxData + i*K;
auto targetPBatch = targetPData + i*K;
auto gradInputBatch = gradInputData + i*nClasses;
for (int j = 0; j < K; ++j) {
gradInputBatch[targetIdxBatch[j] - 1] = - targetPBatch[j];
}
}
return 0;
}
template <class T>
class Registerer {
private:
static const luaL_Reg functions_[];
public:
static void registerFunctions(lua_State* L);
};
template <class T>
const luaL_Reg Registerer<T>::functions_[] = {
{"SparseNLLCriterion_updateOutput", updateOutput<T>},
{"SparseNLLCriterion_updateGradInput", updateGradInput<T>},
{nullptr, nullptr},
};
template <class T>
void Registerer<T>::registerFunctions(lua_State* L) {
luaT_pushmetatable(L, Tensor<T>::kLuaTypeName);
luaT_registeratname(L, functions_, "nn");
lua_pop(L, 1);
}
} // namespace
void initSparseNLLCriterion(lua_State* L) {
Registerer<float>::registerFunctions(L);
Registerer<double>::registerFunctions(L);
}
}}} // namespaces
<|start_filename|>fbnn/TemporalConvolutionTBC.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
-- Temporal Convolution
-- Input format:
-- Time x BatchSize x Channels
local TBC, parent = torch.class('nn.TemporalConvolutionTBC', 'nn.Module')
function TBC:__init(nIn, nOut, kw,pad)
pad = pad or 0
parent.__init(self)
self.kw = kw
self.pad = pad
self.nIn = nIn
self.nOut = nOut
self.weight = torch.Tensor(kw,nIn,nOut)
self.bias = torch.Tensor(nOut)
self.gradWeight = torch.Tensor(kw,nIn,nOut)
self.gradBias = torch.Tensor(nOut)
self:reset()
end
function TBC:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1/math.sqrt(self.kw*self.nIn)
end
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
function TBC:noBias()
assert(false, 'noBias mode not implemented yet!')
end
function TBC:updateOutput(input)
local s = input:size()
assert(s:size() == 3)
assert(s[3] == self.nIn)
self.output:resize(s[1]-self.kw+1+2*self.pad, s[2], self.nOut)
input.nn.TemporalConvolutionTBC_updateOutput(self,input)
return self.output
end
function TBC:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input):zero()
input.nn.TemporalConvolutionTBC_updateGradInput(self,gradOutput)
return self.gradInput
end
function TBC:accGradParameters(input, gradOutput, scale)
scale = scale or 1
input.nn.TemporalConvolutionTBC_accGradParameters(
self,input,gradOutput,scale)
end
-- we do not need to accumulate parameters when sharing
TBC.sharedAccUpdateGradParameters = TBC.accUpdateGradParameters
function TBC:clearState()
return parent.clearState(self)
end
function TBC:test()
local function tensoreq(a, b, epsilon)
local delta = a:clone():add(-1, b):abs():max() / torch.abs(a):max()
print('delta',delta)
return delta < epsilon, delta
end
local function checkforwardbackward(bsz, l, nIn, nOut, kw, pad, type)
require 'nn'
require 'cunn'
type=type or 'torch.FloatTensor'
bsz = bsz or 64
l = l or 25
nIn = nIn or 512
nOut = nOut or 512
kw = kw or 3
local epsilon = (type == 'torch.Tensor') and 1e-14 or 1e-5
-- random input
local input = torch.randn(bsz, l, nIn):type(type)
-- torch reference implementation
local conv = nn.TemporalConvolution(nIn, nOut, kw, 1)
local nopad = conv
if pad then
conv = nn.Sequential()
:add(nn.Padding(2, -pad))
:add(nn.Padding(2, pad))
:add(conv)
end
conv:type(type)
conv:forward(input)
conv:zeroGradParameters()
local gout = torch.randn(conv.output:size()):type(type)
conv:backward(input, gout)
-- our implementation
local tbc = nn.TemporalConvolutionTBC(nIn, nOut, kw, pad)
tbc:type(type)
-- adjust weights and input-output format
input=input:transpose(2,1,3):clone()
tbc.weight:copy(nopad.weight:reshape(nOut,kw,nIn)
:permute(2,3,1):clone())
gout=gout:transpose(2,1,3):clone()
tbc.bias:copy(nopad.bias)
conv.output=conv.output:transpose(2,1,3):clone()
conv.gradInput=conv.gradInput:transpose(2,1,3):clone()
nopad.gradWeight=nopad.gradWeight:reshape(nOut,kw,nIn)
:permute(2,3,1):clone()
tbc:forward(input)
tbc:zeroGradParameters()
tbc:backward(input, gout)
-- check reference and ours have same outputs, gradients
assert(tensoreq(conv.output, tbc.output, epsilon))
assert(tensoreq(nopad.gradBias, tbc.gradBias, epsilon))
assert(tensoreq(nopad.gradWeight, tbc.gradWeight, epsilon))
assert(tensoreq(conv.gradInput, tbc.gradInput, epsilon))
end
return {
checkforwardbackward = checkforwardbackward,
}
end
<|start_filename|>src/HSM.cpp<|end_filename|>
// Copyright 2004-present Facebook. All Rights Reserved.
// Author: <NAME> <<EMAIL>>
#include <algorithm>
#include <cstdio>
#include <memory>
#include <limits>
#include <lua.hpp>
#include <mkl.h>
#include <luaT.h>
#ifndef __clang__
#include <omp.h>
#endif
#include "Blas.h"
#include "Vml.h"
#include <folly/Format.h>
#include "fblualib/LuaUtils.h"
#include "thpp/Storage.h"
#include "thpp/Tensor.h"
namespace facebook {
namespace deeplearning {
namespace torch {
using namespace fblualib;
using namespace thpp;
namespace {
template <class T> using thOps = thpp::detail::TensorOps<T>;
template <class T>
int updateOutputWithTarget(lua_State* L) {
auto class_weight = luaGetFieldIfTensorChecked<T>(L, 1, "class_weight");
auto class_bias = luaGetFieldIfTensorChecked<T>(L, 1, "class_bias");
auto cluster_bias = luaGetFieldIfTensorChecked<T>(L, 1, "cluster_bias");
auto class_score = luaGetFieldIfTensorChecked<T>(L, 1, "class_score");
auto class_logsum = luaGetFieldIfTensorChecked<T>(L, 1, "class_logsum");
auto mapping = luaGetFieldIfTensorChecked<long>(L, 1, "mapping");
auto n_class_in_cluster =
luaGetFieldIfTensorChecked<long>(L, 1, "n_class_in_cluster");
auto class_start_indices =
luaGetFieldIfTensorChecked<long>(L, 1, "class_start_indices");
auto input = luaGetTensorChecked<T>(L, 2);
auto target = luaGetTensorChecked<long>(L, 3);
auto n_clusters = cluster_bias->size(0);
auto n_class = class_bias->size(0);
auto batch_size = input->size(0);
if (input->ndims() == 1)
batch_size = 1;
T output = 0.;
long n_valid = 0;
T loss;
for (int i_batch = 0; i_batch < batch_size; ++i_batch) {
long itarget = target->at({i_batch}) - 1; // 1based->0based
long cluster_target = mapping->at({itarget, 0}) - 1; // 1based->0based
long idx_in_cluster_target =
mapping->at({itarget, 1}) - 1; // 1based->0based
long cluster_size = n_class_in_cluster->at({cluster_target});
Tensor<T> input_local = (input->ndims() == 1) ? *input : (*input)[i_batch];
// class
// get tensors corresponding to target
long istart = class_start_indices->at({cluster_target});
Tensor<T> class_score_used, class_weight_used, class_bias_used;
class_score_used.narrow((*class_score)[i_batch], 0, 0, cluster_size);
class_weight_used.narrow(*class_weight, 0, istart, cluster_size);
class_bias_used.narrow(*class_bias, 0, istart, cluster_size);
// compute score (input * weight + bias)
class_score_used.addmv(1, class_bias_used, 1,
class_weight_used, input_local);
assert(class_score_used.isContiguous());
T* score_data = class_score_used.data();
// compute logsoftmax of score
T maxInput = class_score_used.maxall();
double class_logsum_local = 0.;
for (int d = 0; d < cluster_size; ++d)
class_logsum_local += THExpMinusApprox(maxInput - score_data[d]);
class_logsum_local = maxInput + log(class_logsum_local);
loss = class_logsum_local - class_score_used.at({idx_in_cluster_target});
class_logsum->at({i_batch}) = class_logsum_local;
// output
output += loss;
}
// return value
lua_pushnumber(L, output);
lua_pushnumber(L, n_valid);
return 2;
}
template <class T>
int updateGradInput(lua_State* L) {
auto gradInput = luaGetFieldIfTensorChecked<T>(L, 1, "gradInput");
auto cluster_weight = luaGetFieldIfTensorChecked<T>(L, 1, "cluster_weight");
auto class_weight = luaGetFieldIfTensorChecked<T>(L, 1, "class_weight");
auto class_score = luaGetFieldIfTensorChecked<T>(L, 1, "class_score");
auto class_logsum = luaGetFieldIfTensorChecked<T>(L, 1, "class_logsum");
auto mapping = luaGetFieldIfTensorChecked<long>(L, 1, "mapping");
auto n_class_in_cluster =
luaGetFieldIfTensorChecked<long>(L, 1, "n_class_in_cluster");
auto class_start_indices =
luaGetFieldIfTensorChecked<long>(L, 1, "class_start_indices");
auto target = luaGetTensorChecked<long>(L, 2);
auto n_clusters = cluster_weight->size(0);
auto n_class = class_weight->size(0);
auto batch_size = gradInput->size(0);
if (gradInput->ndims() == 1)
batch_size = 1;
for (int i_batch = 0; i_batch < batch_size; ++i_batch) {
long itarget = target->at({i_batch}) - 1; // 1based->0based
long cluster_target = mapping->at({itarget, 0}) - 1; // 1based->0based
long idx_in_cluster_target =
mapping->at({itarget, 1}) - 1; // 1based->0based
long cluster_size = n_class_in_cluster->at({cluster_target});
Tensor<T> gradInput_local =
(gradInput->ndims() == 1) ? *gradInput : (*gradInput)[i_batch];
// class:
// get tensors corresponding to target
long istart = class_start_indices->at({cluster_target});
Tensor<T> class_score_used, class_weight_used;
class_score_used.narrow((*class_score)[i_batch], 0, 0, cluster_size);
class_weight_used.narrow((*class_weight), 0, istart, cluster_size);
// compute gradInput of the logsoftmax (into class_score)
T class_logsum_local = class_logsum->at({i_batch});
assert(class_score_used.isContiguous());
T* score_data = class_score_used.data();
for (int d = 0; d < cluster_size; ++d)
score_data[d] = exp(score_data[d] - class_logsum_local);
score_data[idx_in_cluster_target] -= 1.;
// compute gradInput of the addmv part
Tensor<T> weight_t;
weight_t.transpose(class_weight_used, 0, 1);
gradInput_local.addmv(1, 1, weight_t, class_score_used);
}
return 0;
}
template <class T>
int accGradParameters(lua_State* L) {
auto class_score = luaGetFieldIfTensorChecked<T>(L, 1, "class_score");
auto mapping = luaGetFieldIfTensorChecked<long>(L, 1, "mapping");
auto class_grad_weight =
luaGetFieldIfTensorChecked<T>(L, 1, "class_grad_weight");
auto class_grad_bias =
luaGetFieldIfTensorChecked<T>(L, 1, "class_grad_bias");
auto n_class_in_cluster =
luaGetFieldIfTensorChecked<long>(L, 1, "n_class_in_cluster");
auto class_start_indices =
luaGetFieldIfTensorChecked<long>(L, 1, "class_start_indices");
auto input = luaGetTensorChecked<T>(L, 2);
auto target = luaGetTensorChecked<long>(L, 3);
auto scale = lua_tonumber(L, 4);
auto batch_size = input->size(0);
if (input->ndims() == 1)
batch_size = 1;
// class:
for (int i_batch = 0; i_batch < batch_size; ++i_batch) {
long itarget = target->at({i_batch}) - 1; // 1based->0based
long cluster_target = mapping->at({itarget, 0}) - 1; // 1based->0based
long idx_in_cluster_target =
mapping->at({itarget, 1}) - 1; // 1based->0based
long cluster_size = n_class_in_cluster->at({cluster_target});
Tensor<T> input_local = (input->ndims() == 1) ? *input : (*input)[i_batch];
// get tensors corresponding to target
long istart = class_start_indices->at({cluster_target});
Tensor<T> class_score_used, class_grad_weight_used, class_grad_bias_used;
class_score_used.narrow((*class_score)[i_batch], 0, 0, cluster_size);
class_grad_weight_used.narrow(*class_grad_weight, 0, istart, cluster_size);
class_grad_bias_used.narrow(*class_grad_bias, 0, istart, cluster_size);
// accumulate gradients
class_grad_weight_used.addr(1, scale, class_score_used, input_local);
class_grad_bias_used.cadd(scale, class_score_used);
}
return 0;
}
template <class T>
int accGradParameters_directUpdate(lua_State* L) {
auto class_score = luaGetFieldIfTensorChecked<T>(L, 1, "class_score");
auto mapping = luaGetFieldIfTensorChecked<long>(L, 1, "mapping");
auto class_weight = luaGetFieldIfTensorChecked<T>(L, 1, "class_weight");
auto class_bias = luaGetFieldIfTensorChecked<T>(L, 1, "class_bias");
auto n_class_in_cluster =
luaGetFieldIfTensorChecked<long>(L, 1, "n_class_in_cluster");
auto class_start_indices =
luaGetFieldIfTensorChecked<long>(L, 1, "class_start_indices");
auto input = luaGetTensorChecked<T>(L, 2);
auto target = luaGetTensorChecked<long>(L, 3);
auto scale = lua_tonumber(L, 4);
auto batch_size = input->size(0);
if (input->ndims() == 1)
batch_size = 1;
// class:
for (int i_batch = 0; i_batch < batch_size; ++i_batch) {
long itarget = target->at({i_batch}) - 1; // 1based->0based
long cluster_target = mapping->at({itarget, 0}) - 1; // 1based->0based
long idx_in_cluster_target =
mapping->at({itarget, 1}) - 1; // 1based->0based
long cluster_size = n_class_in_cluster->at({cluster_target});
Tensor<T> input_local = (input->ndims() == 1) ? *input : (*input)[i_batch];
// get tensors corresponding to target
long istart = class_start_indices->at({cluster_target});
Tensor<T> class_score_used, class_weight_used, class_bias_used;
class_score_used.narrow((*class_score)[i_batch], 0, 0, cluster_size);
class_weight_used.narrow(*class_weight, 0, istart, cluster_size);
class_bias_used.narrow(*class_bias, 0, istart, cluster_size);
// accumulate gradients
class_weight_used.addr(1, scale, class_score_used, input_local);
class_bias_used.cadd(scale, class_score_used);
}
return 0;
}
template <class T>
int zeroGradParametersClass(lua_State* L) {
auto mapping = luaGetFieldIfTensorChecked<long>(L, 1, "mapping");
auto class_grad_weight = luaGetFieldIfTensorChecked<T>(L, 1,
"class_grad_weight");
auto class_grad_bias = luaGetFieldIfTensorChecked<T>(L, 1,
"class_grad_bias");
auto n_class_in_cluster =
luaGetFieldIfTensorChecked<long>(L, 1, "n_class_in_cluster");
auto class_start_indices =
luaGetFieldIfTensorChecked<long>(L, 1, "class_start_indices");
auto target = luaGetTensorChecked<long>(L, 2);
auto batch_size = target->size(0);
// TODO: be smarter and 0 out only once per cluster.
for (int i_batch = 0; i_batch < batch_size; ++i_batch) {
long itarget = target->at({i_batch}) - 1; // 1based->0based
long cluster_target = mapping->at({itarget, 0}) - 1; // 1based->0based
long idx_in_cluster_target =
mapping->at({itarget, 1}) - 1; // 1based->0based
long cluster_size = n_class_in_cluster->at({cluster_target});
// get tensors corresponding to target
long istart = class_start_indices->at({cluster_target});
Tensor<T> class_grad_weight_used, class_grad_bias_used;
class_grad_weight_used.narrow(*class_grad_weight, 0, istart, cluster_size);
class_grad_bias_used.narrow(*class_grad_bias, 0, istart, cluster_size);
// accumulate gradients
class_grad_weight_used.fill(0.0);
class_grad_bias_used.fill(0.0);
}
return 0;
}
template <class T>
class Registerer {
private:
static const luaL_Reg functions_[];
public:
static void registerFunctions(lua_State* L);
};
template <class T>
const luaL_Reg Registerer<T>::functions_[] = {
{"HSM_updateOutputWithTarget" , updateOutputWithTarget<T>},
{"HSM_updateGradInput" , updateGradInput<T>},
{"HSM_accGradParameters" , accGradParameters<T>},
{"HSM_accGradParameters_directUpdate", accGradParameters_directUpdate<T>},
{"HSM_zeroGradParametersClass" , zeroGradParametersClass<T>},
{nullptr, nullptr},
};
template <class T>
void Registerer<T>::registerFunctions(lua_State* L) {
luaT_pushmetatable(L, Tensor<T>::kLuaTypeName);
luaT_registeratname(L, functions_, "nn");
lua_pop(L, 1);
}
} // namespace
void initHSM(lua_State* L) {
Registerer<float>::registerFunctions(L);
Registerer<double>::registerFunctions(L);
}
}}} // namespaces
<|start_filename|>fbnn/KMaxPooling.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
local KMaxPooling, parent =
torch.class('nn.KMaxPooling', 'nn.Module')
function KMaxPooling:__init(k, k_dynamic)
parent.__init(self)
self.k = k
self.k_dynamic = k_dynamic or -1
self.output = torch.Tensor()
self.gradInput = torch.Tensor()
self.switches = torch.LongTensor()
end
function KMaxPooling:updateOutput(input, input_info)
input = input:contiguous()
local return_info = true
if input_info == nil then
input_length = torch.LongTensor(1)
input_length[1] = input:size(1)
input_info = { length = input_length }
return_info = false
end
self.input_length = input_info.length:clone()
-- updated in place
self.output_length = input_info.length:clone()
input.nn.KMaxPooling_updateOutput(self, input)
if return_info then
return {
output = self.output,
info = { length = self.output_length },
}
else
return self.output
end
end
function KMaxPooling:updateGradInput(input, gradOutput)
input = input:contiguous()
gradOutput = gradOutput:contiguous()
return input.nn.KMaxPooling_updateGradInput(self, input, gradOutput)
end
<|start_filename|>fbnn/NestedDropout.lua<|end_filename|>
local NestedDropout, Parent = torch.class('fbnn.NestedDropout', 'nn.Dropout')
--[[
This implements the nested dropout layer described in the paper:
<NAME>, <NAME>, and <NAME>. Learning Ordered Representations
with Nested Dropout. ICML 2014.
The layer applies a different amount of dropout to each of the inputs.
In practice, it samples a value b and drops units b+1,...,K. The value b is
drawn from the geometric distribution p(b) = p^{b-1}(1-p) with free parameter p.
]]--
function NestedDropout:__init(p)
Parent.__init(self)
self.p = p or 0.01
self.train = true
if self.p >= 1 or self.p <= 0 then
error('<NestedDropout> illegal geometric distribution parameter, ' ..
'must be 0 < p < 1')
end
self.logp = math.log(p)
self.log1p = math.log(1 - p)
self.noise = torch.Tensor()
end
function NestedDropout:updateOutput(input)
self.output:resizeAs(input):copy(input)
if self.train then
self.noise:resizeAs(input)
self.noise:fill(1)
local normalization = torch.range(1, self.noise:size(2))
normalization:add(-1):mul(self.log1p):add(self.logp):exp()
normalization = -normalization:cumsum():add(-1)
for n = 1,self.noise:size(1) do
local b = torch.geometric(1 - self.p)
if b < self.noise:size(2) then
self.noise[n]:narrow(1, b + 1, self.noise:size(2) - b):zero()
end
end
normalization = normalization:reshape(1, self.noise:size(2))
normalization = normalization:expandAs(self.noise)
self.noise:cdiv(normalization)
self.output:cmul(self.noise) -- This is inefficient!
end
return self.output
end
function NestedDropout:updateGradInput(input, gradOutput)
if self.train then
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
self.gradInput:cmul(self.noise) -- This is inefficient!
else
error('backprop only defined while training')
end
return self.gradInput
end
function NestedDropout:setp(p)
self.p = p
end
<|start_filename|>fbnn/WeightedLookupTable.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
require('nn')
local WeightedLookupTable, parent =
torch.class('nn.WeightedLookupTable', 'nn.LookupTable')
WeightedLookupTable.__version = 2
function WeightedLookupTable:__init(nIndex, nOutput)
parent.__init(self, nIndex, nOutput)
self._gradOutput = torch.Tensor()
self._embeddings = torch.Tensor()
end
--[[
Parameters:
* `Input` should be an n x 2 tensor where the first column is dictionary indexes
and the second column is weights.
]]
function WeightedLookupTable:updateOutput(input)
if input:dim() ~= 2 or input:size(2) ~= 2 then
error('`Input` should be an n x 2 tensor')
end
local indices = input:select(2, 1)
local weights = input:select(2, 2)
self._embeddings = parent.updateOutput(self, indices)
-- Multiply each row of output by the input weight
input.nn.WeightedLookupTable_scaleByWeight(self.output, self._embeddings,
weights)
return self.output
end
function WeightedLookupTable:accGradParameters(input, gradOutput, scale)
local indices = input:select(2, 1)
local weights = input:select(2, 2)
self._gradOutput = self._gradOutput or torch.Tensor()
self._gradOutput:resizeAs(gradOutput)
-- Multiply each row of gradOutput by input weight
input.nn.WeightedLookupTable_scaleByWeight(self._gradOutput, gradOutput, weights)
parent.accGradParameters(self, indices, self._gradOutput, scale)
end
function WeightedLookupTable:sharedAccUpdateGradParameters(input, gradOutput, lr)
-- we do not need to accumulate parameters when sharing:
self:defaultAccUpdateGradParameters(input, gradOutput, lr)
end
<|start_filename|>fbnn/ProjectiveGradientNormalization.lua<|end_filename|>
--[[
This file implements a projective gradient normalization proposed by <NAME>.
This alters the network from doing true back-propagation.
The operation implemented is:
forward:
Y = X
backward:
dL dL X { X dL }
-- = -- - ---- * | ---- (.) -- |
dX dY ||X|| { ||X|| dY }
2 2
where (.) = dot product
Usage:
fbnn.ProjectiveGradientNormalization([eps = 1e-5]) -- eps is optional defaulting to 1e-5
eps is a small value added to the ||X|| to avoid divide by zero
Defaults to 1e-5
]]--
local BN,parent = torch.class('fbnn.ProjectiveGradientNormalization', 'nn.Module')
function BN:__init(eps)
parent.__init(self)
self.eps = eps or 1e-5
end
function BN:updateOutput(input)
self.output:resizeAs(input):copy(input)
return self.output
end
function BN:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(gradOutput)
local x_norm = input:norm(2) -- L2 norm of x
if x_norm == 0 then
self.gradInput:copy(gradOutput)
else
local inv_x_norm = 1 / x_norm
self.gradInput:copy(input):mul(inv_x_norm)
local proj_norm = torch.dot(self.gradInput:view(-1), gradOutput:view(-1))
self.gradInput:mul(-proj_norm):add(gradOutput)
end
return self.gradInput
end
<|start_filename|>fbnn/UnfoldedTemporalConvolution.lua<|end_filename|>
local UTC, parent = torch.class('nn.UnfoldedTemporalConvolution', 'nn.Module')
function UTC:__init(nin, nout, kw, dW, pad)
dW = dW or 1
assert(dW == 1, "nn.UnfoldedTemporalConvolution only supports dW = 1")
parent.__init(self)
self.linear = nn.Linear(kw*nin, nout)
-- sizes
self.kW = kw
self.dW = 1
self.pad = pad or 0
self.inputFrameSize = nin
self.outputFrameSize = nout
-- expose internal linear parameters
self.weight = self.linear.weight
self.bias = self.linear.bias
self.gradWeight = self.linear.gradWeight
self.gradBias = self.linear.gradBias
-- internal buffer
self._paddedInput = torch.Tensor()
self._paddedGradInput = torch.Tensor()
self._unfoldedInput = torch.Tensor()
self._linearGradOutput = torch.Tensor()
self._unfoldedGradInput = torch.Tensor()
end
function UTC:noBias()
self.bias = nil
self.gradBias = nil
self.linear:noBias()
return self
end
function UTC:reset(stdv)
self.linear:reset(stdv)
end
function UTC:updateOutput(input)
local nout = self.outputFrameSize
local nin = self.inputFrameSize
local kpad = self.kW - 1 -- pad added between sentence in batch
local bsz, l = input:size(1), input:size(2)
-- no batch?
if input:dim() == 2 then
local l = input:size(1)
self:updateOutput(input:view(1, l, nin))
self.output = self.output[1]
return self.output
end
-- pad
-- this a bit complicated but
-- we want padding at beginning, end and between examples = (bsz + 1) pads
local padl = l + 2 * self.pad -- padded length
local n = (bsz + 1) * kpad + bsz * padl -- add kpad between each sample
self._paddedInput
:resize(n, nin)
:zero()
:narrow(1, kpad + 1, bsz * (padl + kpad))
:view(bsz, -1, nin)
:narrow(2, 1 + self.pad, l)
:copy(input)
-- unfold
local uinput = self._paddedInput
:view(-1)
:unfold(1, nin * self.kW, nin)
self._unfoldedInput
:resizeAs(uinput)
:copy(uinput)
-- linear
local loutput = self.linear:updateOutput(self._unfoldedInput)
self.output = loutput
:view(bsz, -1, nout)
:narrow(2, kpad + 1, padl - kpad)
return self.output
end
function UTC:updateGradInput(input, gradOutput)
local nout = self.outputFrameSize
local nin = self.inputFrameSize
local kpad = self.kW - 1
local bsz, l = input:size(1), input:size(2)
local padl = l + 2*self.pad
-- no batch ?
if input:dim() == 2 then
local lin, lout = input:size(1), gradOutput:size(1)
local input = input:view(1, lin, nin)
local gradOutput = gradOutput:view(1, lout, nout)
self:updateGradInput(input, gradOutput)
self.gradInput = self.gradInput[1]
return self.gradInput
end
-- linear
self._linearGradOutput
:resizeAs(self.linear.output)
:zero()
:view(bsz, -1, nout)
:narrow(2, kpad + 1, padl - kpad)
:copy(gradOutput)
self.linear
:updateGradInput(self._unfoldedInput, self._linearGradOutput)
-- reduce
self._unfoldedGradInput:set(
self.linear.gradInput:storage(),
nin * (self.kW - 1) + 1, -- offset
bsz, -- sz1
nin * self.kW * (padl + kpad), -- st1
padl, -- sz2
nin * self.kW, -- st2
self.kW, -- sz3
nin *(self.kW - 1), -- st3
nin, -- sz4
1) -- st4
self._paddedGradInput = self._paddedGradInput
:sum(self._unfoldedGradInput, 3)
:select(3, 1)
self.gradInput = self._paddedGradInput
:narrow(2, 1 + self.pad, l)
return self.gradInput
end
function UTC:accGradParameters(input, gradOutput, scale)
self.linear:accGradParameters(
self._unfoldedInput, self._linearGradOutput, scale
)
end
function UTC:sharedAccUpdateGradParameters(input, gradOutput, lr)
-- we do not need to accumulate parameters when sharing:
self:defaultAccUpdateGradParameters(input, gradOutput, lr)
end
function UTC:clearState()
nn.utils.clear(self, '_paddedInput', '_paddedGradInput', '_unfoldedInput',
'_linearGradOutput', '_unfoldedGradInput')
return parent.clearState(self)
end
function UTC:test()
local function tensoreq(a, b, epsilon)
local delta = a:clone():add(-1, b):abs():max()
return delta < epsilon, delta
end
local function checkforwardbackward(bsz, l, nin, nout, kw, pad, type, eps)
bsz = bsz or 16
l = l or 25
nin = nin or 5
nout = nout or 10
kw = kw or 3
type = type or 'torch.DoubleTensor'
local epsilon = eps or 1e-12
-- random input
local input = torch.randn(bsz, l, nin):type(type)
-- torch reference implementation
local conv = nn.TemporalConvolution(nin, nout, kw, 1)
local nopad = conv
if pad then
conv = nn.Sequential()
:add(nn.Padding(2, -pad))
:add(nn.Padding(2, pad))
:add(conv)
end
conv:type(type)
conv:forward(input)
conv:zeroGradParameters()
local gout = torch.randn(conv.output:size()):type(type)
conv:backward(input, gout)
-- our implementation
local utc = nn.UnfoldedTemporalConvolution(nin, nout, kw, 1, pad)
utc:type(type)
utc.weight:copy(nopad.weight)
utc.bias:copy(nopad.bias)
utc:forward(input)
utc:zeroGradParameters()
utc:backward(input, gout)
-- check reference and ours have same outputs, gradients
assert(tensoreq(conv.output, utc.output, epsilon))
assert(tensoreq(conv.gradInput, utc.gradInput, epsilon))
assert(tensoreq(nopad.gradWeight, utc.gradWeight, epsilon))
assert(tensoreq(nopad.gradBias, utc.gradBias, epsilon))
end
return {
checkforwardbackward = checkforwardbackward,
}
end
<|start_filename|>test/fb_test.lua<|end_filename|>
require 'fb.luaunit'
require 'fbtorch'
require 'nn'
require 'fbnn'
torch.setnumthreads(1)
nn.fbnntest()
<|start_filename|>fbnn/init.lua<|end_filename|>
require('torch')
require('nn')
require('libfbnn')
pcall(function() include('Dropout.lua') end) -- because uses async_rng
include('UnfoldedTemporalConvolution.lua')
include('TemporalConvolutionTBC.lua')
include('NestedDropout.lua')
include('IndividualDropout.lua')
include('CachingLookupTable.lua')
include('Optim.lua')
include('Probe.lua')
include('TrueNLLCriterion.lua')
include('ProjectiveGradientNormalization.lua')
include('ClassNLLCriterionWithUNK.lua')
include('Upsample.lua')
include('test.lua')
include('DataSetLabelMe.lua')
include('LeakyReLU.lua')
include('Constant.lua')
include('SpatialFoveaCuda.lua')
include('SoftPlusLSECriterion.lua')
include('SoftPlusLSEMinusLSECriterion.lua')
-- Former fbcunn.nn_layers
include('ClassHierarchicalNLLCriterion.lua')
include('CrossMapNormalization.lua')
include('GroupKMaxPooling.lua')
include('HSM.lua')
include('KMaxPooling.lua')
include('LinearNB.lua')
include('LaplacianOfGaussian.lua')
include('DifferenceOfGaussian.lua')
include('LinearNoBackprop.lua')
include('LocallyConnected.lua')
include('L2Normalize.lua')
include('NormalizedLinearNoBias.lua')
include('SequentialCriterion.lua')
include('WeightedLookupTable.lua')
include('FasterLookup.lua')
include('SparseNLLCriterion.lua')
include('SparseLinear.lua')
include('SegSparseLinear.lua')
include('SparseThreshold.lua')
local ok, sparse = pcall(require, 'sparse') -- sparse is not oss
if ok then
include('SparseConverter.lua')
include('SparseKmax.lua')
include('SparseLookupTable.lua')
include('SparseSum.lua')
end
-- Former fbcunn.cpu
local ok, _ = pcall(require,'fbcode.torch.fb.fbnn.cpu_ext')
if not ok then require 'libfbnn' end -- for Open Source
<|start_filename|>fbnn/HSM.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
-- Author: <NAME> <<EMAIL>>
require 'math'
require 'nn'
-- Hierarchical soft max with minibatches.
local HSM, parent =
torch.class('nn.HSM', 'nn.Criterion')
--[[
Parameters:
* `mapping` is a table (or tensor) with `n_classes` elements,
such that `mapping[i]` is a table with 2 elements.
* `mapping[i][1]` : index (1-based) of the cluster of class `i`
* `mapping[i][2]` : index (1-based) of the index within its cluster of class `i`
* `input_size` is the number of elements of the previous layer
* `unk_index` is an index that is ignored at test time (not added to the
loss). It can be disabled by setting it to 0 (not nil).
It should only be used uring testing (since during training,
it is not disabled in the backprop (TODO) )
]]
function HSM:__init(mapping, input_size, unk_index)
parent.__init(self)
if type(mapping) == 'table' then
self.mapping = torch.LongTensor(mapping)
else
self.mapping = mapping:long()
end
self:check_mapping(self.mapping)
self.n_classes = self.mapping:size(1)
self.n_class_in_cluster = self:get_n_class_in_cluster(self.mapping)
self.n_clusters = self.n_class_in_cluster:size(1)
self.n_max_class_in_cluster = self.n_class_in_cluster:max()
self.class_start_indices =
torch.LongTensor(self.n_clusters):fill(0) -- 0 based !
for i = 2, self.n_clusters do
self.class_start_indices[i] =
self.class_start_indices[i-1] + self.n_class_in_cluster[i-1]
end
self.unk_index = unk_index or 0
self.cluster_weight = torch.Tensor(self.n_clusters, input_size)
self.cluster_bias = torch.Tensor(self.n_clusters)
self.cluster_score = torch.Tensor(self.n_clusters)
self.cluster_logsum = torch.Tensor(1)
self.class_weight = torch.Tensor(self.n_classes, input_size)
self.class_bias = torch.Tensor(self.n_classes)
self.class_score = torch.Tensor(self.n_max_class_in_cluster)
self.class_logsum = torch.Tensor(1)
self.tmp_ones = torch.Tensor(1):fill(1)
self.gradInput = torch.Tensor(input_size)
self.cluster_grad_weight = torch.Tensor(self.n_clusters, input_size)
self.cluster_grad_bias = torch.Tensor(self.n_clusters)
self.class_grad_weight = torch.Tensor(self.n_classes, input_size)
self.class_grad_bias = torch.Tensor(self.n_classes)
self.logSMCluster = nn.LogSoftMax()
self.logLossCluster = nn.ClassNLLCriterion()
self.logLossCluster.sizeAverage = false
self.batch_size = 0
self:reset()
end
function HSM:clone(...)
return nn.Module.clone(self, ...)
end
function HSM:check_mapping(mapping)
local n_classes = mapping:size(1)
local clusters = {}
for i = 1,n_classes do
local cluster = mapping[i][1]
local idx_in_cluster = mapping[i][2]
clusters[cluster] = clusters[cluster] or {}
table.insert(clusters[cluster], idx_in_cluster)
end
local cluster_max = 0
for k, v in pairs(clusters) do
cluster_max = math.max(cluster_max, k)
end
for i = 1, cluster_max do
if clusters[i] == nil then
error('HSM: bad mapping: not contiguous cluster indices (idx '
.. i .. ' is not skipped)')
end
table.sort(clusters[i])
local last = 0
for k, v in pairs(clusters[i]) do
if k-1 ~= last then
if k == last then
error('HSM: bad mapping: in cluster ' .. i
.. ', index ' .. k .. ' is used twice')
else
error('HSM: bad mapping: in cluster ' .. i
.. ' indices are not contiguous (idx '
.. k .. ' is not skipped)')
end
end
last = k
end
end
end
function HSM:get_n_class_in_cluster(mapping)
local n_classes = mapping:size(1)
local i_cluster_max = 0
for i = 1, n_classes do
i_cluster_max = math.max(i_cluster_max, mapping[i][1])
end
local cluster_counts = torch.LongTensor(i_cluster_max):zero()
for i = 1, n_classes do
cluster_counts[mapping[i][1] ] =
cluster_counts[mapping[i][1] ] + 1
end
return cluster_counts
end
function HSM:parameters()
return {self.cluster_weight, self.cluster_bias,
self.class_weight, self.class_bias},
{self.cluster_grad_weight, self.cluster_grad_bias,
self.class_grad_weight, self.class_grad_bias}
end
function HSM:getParameters()
return nn.Module.getParameters(self)
end
function HSM:reset(weight_stdv, bias_stdv)
weight_stdv = weight_stdv or 0.1
bias_stdv = bias_stdv or 0.1
self.cluster_weight:normal():mul(weight_stdv)
self.cluster_bias:normal():mul(bias_stdv)
self.class_weight:normal():mul(weight_stdv)
self.class_bias:normal():mul(bias_stdv)
end
function HSM:updateOutput(input, target)
if self.cluster_weight:type() == 'torch.CudaTensor' then
return self:updateOutputCUDA(input, target)
else
return self:updateOutputCPU(input, target)
end
end
function HSM:updateOutputCPU(input, target)
self.batch_size = input:size(1)
if input:dim() == 1 then
self.batch_size = 1
else -- minibatch
assert(input:dim() == 2)
end
if self.batch_size ~= self.tmp_ones:size(1) then
self.tmp_ones:resize(self.batch_size):fill(1)
end
self.cluster_score:resize(self.batch_size, self.n_clusters)
self.cluster_logsum:resize(self.batch_size)
self.class_score:resize(self.batch_size, self.n_max_class_in_cluster)
self.class_logsum:resize(self.batch_size)
-- go through the cluster softmax
-- linear layer
if input:dim() == 1 then
self.cluster_score:resize(self.cluster_bias:size(1))
self.cluster_score:copy(self.cluster_bias)
self.cluster_score:addmv(1, self.cluster_weight, input)
loss = self.logLossCluster:forward(self.logSMCluster:forward(
self.cluster_score),
self.mapping[target[1]][1])
else
if self.n_clusters == 1 then
self.cluster_score:zero():add(self.cluster_bias[1])
self.cluster_score:select(2,1):addmv(1, input,
self.cluster_weight:select(1,1))
loss = self.logLossCluster:forward(
self.logSMCluster:forward(self.cluster_score),
torch.Tensor{self.mapping[target[1]][1]})
else
self.cluster_score:zero():addr(1, self.tmp_ones, self.cluster_bias)
self.cluster_score:addmm(1, input, self.cluster_weight:t())
loss = self.logLossCluster:forward(
self.logSMCluster:forward(self.cluster_score),
self.mapping:index(1, target):select(2,1))
end
end
local n_valid
self.output, n_valid = input.nn.HSM_updateOutputWithTarget(self, input,
target)
n_valid = self.batch_size --TODO
assert(self.unk_index == 0)
self.output = self.output + loss
return self.output, n_valid
end
function HSM:updateOutputCUDA(input, target)
if (input:type() ~= 'torch.CudaTensor') or
(target:type() ~= 'torch.CudaTensor') then
error('CudaTensor expected')
end
self.batch_size = input:size(1)
assert(input:dim() ~= 1)
if self.batch_size ~= self.tmp_ones:size(1) then
self.tmp_ones:resize(self.batch_size):fill(1)
end
self.cluster_score:resize(self.batch_size, self.n_clusters)
self.cluster_logsum:resize(self.batch_size)
self.class_score:resize(self.batch_size, self.n_max_class_in_cluster)
self.class_logsum:resize(self.batch_size)
-- go through the cluster softmax
-- linear layer
self.cluster_score:zero():addr(1, self.tmp_ones, self.cluster_bias)
self.cluster_score:addmm(1, input, self.cluster_weight:t())
if (type(self.output) == 'number') or
(self.output:type() ~= 'torch.CudaTensor') then
self.output = torch.CudaTensor(1)
end
self.output:zero()
input.nn.HSM_updateOutputWithTarget(self, input, target)
assert(self.unk_index == 0) --TODO
return self.output, self.batch_size
end
-- Note: call this function at most once after each call `updateOutput`,
-- or the output will be wrong (it uses `class_score` and `cluster_score`
-- as temporary buffers)
function HSM:updateGradInput(input, target)
if input:type() == 'torch.CudaTensor' then
return self:updateGradInputCUDA(input, target)
else
return self:updateGradInputCPU(input, target)
end
end
function HSM:updateGradInputCPU(input, target)
if self.unk_index ~= 0 then
error("HSM: bprop with unk is not implemented")
end
self.gradInput:resizeAs(input)
-- BPROP through the cluster prediction
local clusterID = self.mapping:index(1, target):select(2,1)
if input:dim() == 1 then
clusterID = clusterID[1]
end
self.logLossCluster:updateGradInput(self.logSMCluster.output,
clusterID)
self.logSMCluster:updateGradInput(self.cluster_score,
self.logLossCluster.gradInput)
if input:dim() == 1 then
self.gradInput:addmv(
0, 1, self.cluster_weight:t(), self.logSMCluster.gradInput)
else
self.gradInput:addmm(
0, 1, self.logSMCluster.gradInput, self.cluster_weight)
end
input.nn.HSM_updateGradInput(self, target)
return self.gradInput
end
function HSM:updateGradInputCUDA(input, target)
self.gradInput:resizeAs(input)
assert(input:dim() == 2)
input.nn.HSM_updateGradInput(self, target)
self.gradInput:addmm(1, 1, self.cluster_score, self.cluster_weight)
return self.gradInput
end
-- If `direct_update` is set, the parameters are directly updated (not the
-- gradients). It means that the gradient tensors (like `cluster_grad_weight`)
-- are not used. scale must be set to the negative learning rate
-- (`-learning_rate`). `direct_update` mode is much faster.
-- Before calling this function you have to call `HSM:updateGradInput` first.
function HSM:accGradParameters(input, target, scale, direct_update)
scale = scale or 1
if self.unk_index ~= 0 then
error("HSM: bprop with unk is not implemented")
end
local cluster_gradInput = self.logSMCluster.gradInput
if input:type() == 'torch.CudaTensor' then
cluster_gradInput = self.cluster_score
end
if direct_update then
if input:dim() == 1 then
self.cluster_bias:add(scale, cluster_gradInput)
self.cluster_weight:addr(scale, cluster_gradInput, input)
else
if self.n_clusters == 1 then
self.cluster_weight:select(1,1):addmv(
scale, input:t(), cluster_gradInput:select(2,1))
self.cluster_bias:addmv(
scale, cluster_gradInput:t(),
self.tmp_ones)
else
self.cluster_weight:addmm(scale, cluster_gradInput:t(), input)
self.cluster_bias:addmv(scale, cluster_gradInput:t(),
self.tmp_ones)
end
end
input.nn.HSM_accGradParameters_directUpdate(self, input, target, scale)
else
if input:dim() == 1 then
self.cluster_grad_bias:add(scale, cluster_gradInput)
self.cluster_grad_weight:addr(scale, cluster_gradInput, input)
else
if self.n_clusters == 1 then
self.cluster_grad_weight:select(1,1):addmv(
scale, input:t(), cluster_gradInput:select(2,1))
self.cluster_grad_bias:addmv(
scale, cluster_gradInput:t(), self.tmp_ones)
else
self.cluster_grad_weight:addmm(scale, cluster_gradInput:t(), input)
self.cluster_grad_bias:addmv(scale, cluster_gradInput:t(),
self.tmp_ones)
end
end
input.nn.HSM_accGradParameters(self, input, target, scale)
end
end
function HSM:backward(input, target, scale)
self:updateGradInput(input, target)
self:accGradParameters(input, target, scale)
return self.gradInput
end
function HSM:updateParameters(learning_rate)
self.cluster_weight:add(-learning_rate, self.cluster_grad_weight)
self.cluster_bias :add(-learning_rate, self.cluster_grad_bias )
self.class_weight :add(-learning_rate, self.class_grad_weight )
self.class_bias :add(-learning_rate, self.class_grad_bias )
end
function HSM:zeroGradParameters()
self.cluster_grad_weight:zero()
self.cluster_grad_bias:zero()
self.class_grad_weight:zero()
self.class_grad_bias:zero()
end
function HSM:zeroGradParametersClass(input, target)
input.nn.HSM_zeroGradParametersClass(self, target)
end
<|start_filename|>src/DataSetLabelMe.c<|end_filename|>
#ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "src/DataSetLabelMe.c"
#else
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
#define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
static int nn_(DataSetLabelMe_extract)(lua_State *L)
{
// fprintf(stderr,"test!");
int tags = 1;
THTensor *mask = luaT_checkudata(L, 2, torch_Tensor);
int x_start = lua_tonumber(L, 3);
int x_end = lua_tonumber(L, 4);
int y_start = lua_tonumber(L, 5);
int y_end = lua_tonumber(L, 6);
int idx = lua_tonumber(L, 7);
float filter_ratio = lua_tonumber(L, 8);
int filter_size = lua_tonumber(L, 9);
int filter_step = lua_tonumber(L, 10);
//fprintf(stderr,"test2!");
float ratio = 1;
int x,y,label,tag,size;
THShortStorage *data;
for (x=x_start; x<=x_end; x++) {
for (y=y_start; y<=y_end; y++) {
//fprintf(stderr,"-");
// label = mask[x][y]
label = THTensor_(get2d)(mask, y-1, x-1);
// optional filter: insures that at least N% of local pixels belong to the same class
if (filter_ratio > 0) {
int kx,ky,count=0,good=0;
for (kx=MAX(1,x-filter_size/2); kx<=MIN(x_end,x+filter_size/2); kx+=filter_step) {
for (ky=MAX(1,y-filter_size/2); ky<=MIN(y_end,y+filter_size/2); ky+=filter_step) {
int other = THTensor_(get2d)(mask, ky-1, kx-1);
if (other == label) good++;
count++;
}
}
ratio = (float)good/(float)count;
}
// if filter(s) satisfied, then append label
if (ratio >= filter_ratio) {
lua_rawgeti(L, tags, label); // tag = tags[label]
tag = lua_gettop(L);
lua_pushstring(L, "size"); lua_rawget(L, tag); // size = tag.size
size = lua_tonumber(L,-1); lua_pop(L,1);
lua_pushstring(L, "size"); lua_pushnumber(L, size+3); lua_rawset(L, tag); // tag.size = size + 3
lua_pushstring(L, "data"); lua_rawget(L, tag); // data = tag.data
data = luaT_checkudata(L, -1, "torch.ShortStorage"); lua_pop(L, 1);
//fprintf(stderr,"t4");
data->data[size] = x; // data[size+1] = x
data->data[size+1] = y; // data[size+1] = y
data->data[size+2] = idx; // data[size+1] = idx
lua_pop(L, 1);
}
}
}
return 0;
}
/******************************************************/
// Camille : same function that below except it keeps memory about the employed masking segment.
static int nn_(DataSetSegmentSampling_extract)(lua_State *L)
{
int tags = 1;
THTensor *mask = luaT_checkudata(L, 2, torch_Tensor);
int x_start = lua_tonumber(L, 3);
int x_end = lua_tonumber(L, 4);
int y_start = lua_tonumber(L, 5);
int y_end = lua_tonumber(L, 6);
int idx = lua_tonumber(L, 7);
int idxSegm = lua_tonumber(L, 8);
float filter_ratio = lua_tonumber(L, 9);
int filter_size = lua_tonumber(L, 10);
int filter_step = lua_tonumber(L, 11);
int step = lua_tonumber(L, 12);
float ratio = 1;
int x,y,label,tag,size;
THShortStorage *data;
for (x=x_start; x<=x_end; x=x+step) {
for (y=y_start; y<=y_end; y=y+step) {
// label = mask[x][y]
label = THTensor_(get2d)(mask, y-1, x-1);
// fprintf(stderr,"%d %d \n",x,y);
// optional filter: insures that at least N% of local pixels belong to the same class
if (filter_ratio > 0) {
int kx,ky,count=0,good=0;
for (kx=MAX(1,x-filter_size/2); kx<=MIN(x_end,x+filter_size/2); kx+=filter_step) {
for (ky=MAX(1,y-filter_size/2); ky<=MIN(y_end,y+filter_size/2); ky+=filter_step) {
int other = THTensor_(get2d)(mask, ky-1, kx-1);
if (other == label) good++;
count++;
}
}
ratio = (float)good/(float)count;
}
// if filter(s) satisfied, then append label
if (ratio >= filter_ratio) {
lua_rawgeti(L, tags, label); // tag = tags[label]
tag = lua_gettop(L);
lua_pushstring(L, "size"); lua_rawget(L, tag); // size = tag.size
size = lua_tonumber(L,-1); lua_pop(L,1);
lua_pushstring(L, "size"); lua_pushnumber(L, size+4); lua_rawset(L, tag); // tag.size = size + 4
lua_pushstring(L, "data"); lua_rawget(L, tag); // data = tag.data
data = luaT_checkudata(L, -1, "torch.ShortStorage"); lua_pop(L, 1);
data->data[size] = x; // data[size+1] = x
data->data[size+1] = y; // data[size+1] = y
data->data[size+2] = idx; // data[size+1] = idx
data->data[size+3] = idxSegm; // data[size+1] = idxSegm
lua_pop(L, 1);
}
}
}
return 0;
}
static const struct luaL_Reg nn_(DataSetLabelMe__) [] = {
{"DataSetLabelMe_extract", nn_(DataSetLabelMe_extract)},
{"DataSetSegmentSampling_extract", nn_(DataSetSegmentSampling_extract)},
{NULL, NULL}
};
static void nn_(DataSetLabelMe_init)(lua_State *L)
{
luaT_pushmetatable(L, torch_Tensor);
luaT_registeratname(L, nn_(DataSetLabelMe__), "nn");
lua_pop(L,1);
}
#endif
<|start_filename|>src/TemporalConvolutionTBC.cpp<|end_filename|>
// Copyright 2004-present Facebook. All Rights Reserved.
// Author: <NAME> <<EMAIL>>
// Tensor formats
// Input: ilen * batchSize * inputPlanes
// Output: olen * batchSize * outputPlanes
// Weight: kw * inputPlanes * outputPlanes
#include <lua.hpp>
#include <luaT.h>
#include <mkl.h>
#include <algorithm>
#include <cstring>
#include <iostream>
#include "Blas.h"
#include "Vml.h"
#include "fblualib/LuaUtils.h"
#include "thpp/Storage.h"
#include "thpp/Tensor.h"
namespace facebook {
namespace deeplearning {
namespace torch {
using namespace fblualib;
using namespace thpp;
namespace {
template <class T>
using thOps = thpp::detail::TensorOps<T>;
template <class T>
int updateOutput(lua_State* L) {
auto output = luaGetFieldIfTensorChecked<T>(L, 1, "output");
auto weight = luaGetFieldIfTensorChecked<T>(L, 1, "weight");
auto bias = luaGetFieldIfTensorChecked<T>(L, 1, "bias");
auto input = luaGetTensorChecked<T>(L, 2);
auto ilen = input->size(0);
auto batchSize = input->size(1);
auto inputPlanes = input->size(2);
auto outputPlanes = output->size(2);
auto olen = output->size(0);
auto kw = weight->size(0);
int pad = (olen - ilen + kw - 1) / 2;
luaL_argcheck(
L,
(output->ndims() == 3) && (output->size(1) == batchSize) &&
(olen == ilen - kw + 1 + 2 * pad),
1,
"output has wrong dimension");
luaL_argcheck(L, (input->ndims() == 3), 2, "input has wrong dimension");
luaL_argcheck(
L,
(weight->ndims() == 3) && (weight->size(1) == inputPlanes) &&
(weight->size(2) == outputPlanes),
1,
"weight has wrong dimension");
luaL_argcheck(
L,
(bias->ndims() == 1) && (bias->size(0) == outputPlanes),
1,
"bias has wrong dimension");
auto W = weight->data();
auto B = bias->data();
auto I = input->data();
auto O = output->data();
for (int t = 0; t < olen; t++)
for (int b = 0; b < batchSize; b++)
for (int c = 0; c < outputPlanes; c++)
O[t * output->stride(0) + b * output->stride(1) + c] = B[c];
for (int k = 0; k < kw; k++) {
int iShift = std::max(0, k - pad);
int oShift = std::max(0, pad - k);
int t = std::min(ilen + pad - k, olen) - oShift;
// Note: using gemm in column-major order mode
// input is l*m (row-major)
// weight is m*r (row-major)
// output is l*r (row-major)
if (t > 0)
blas::gemm(
CblasColMajor,
CblasNoTrans,
CblasNoTrans,
outputPlanes, // r
batchSize * t, // l
inputPlanes, // m
1, // alpha
W + k * weight->stride(0),
outputPlanes,
I + iShift * input->stride(0),
input->stride(1),
1, // beta
O + oShift * output->stride(0),
output->stride(1)
);
}
return 0;
}
template <class T>
int updateGradInput(lua_State* L) {
auto dInput = luaGetFieldIfTensorChecked<T>(L, 1, "gradInput");
auto weight = luaGetFieldIfTensorChecked<T>(L, 1, "weight");
auto dOutput = luaGetTensorChecked<T>(L, 2);
auto ilen = dInput->size(0);
auto batchSize = dInput->size(1);
auto inputPlanes = dInput->size(2);
auto outputPlanes = dOutput->size(2);
auto olen = dOutput->size(0);
auto kw = weight->size(0);
int pad = (olen - ilen + kw - 1) / 2;
auto W = weight->data();
auto dI = dInput->data();
auto dO = dOutput->data();
for (int k = 0; k < kw; k++) {
int iShift = std::max(0, k - pad);
int oShift = std::max(0, pad - k);
int t = std::min(ilen + pad - k, olen) - oShift;
// dOutput * T(weight) -> dInput
// Note: using gemm in column-major order mode
// dOutput is l*m (row-major)
// weight is r*m (row-major)
// dInput is l*r (row-major)
if (t > 0)
blas::gemm(
CblasColMajor,
CblasTrans,
CblasNoTrans,
inputPlanes, // r
batchSize * t, // l
outputPlanes, // m
1, // alpha
W + k * weight->stride(0),
outputPlanes,
dO + oShift * dOutput->stride(0),
dOutput->stride(1),
1, // beta
dI + iShift * dInput->stride(0),
dInput->stride(1)
);
}
return 0;
}
template <class T>
int accGradParameters(lua_State* L) {
auto dWeight = luaGetFieldIfTensorChecked<T>(L, 1, "gradWeight");
auto dBias = luaGetFieldIfTensorChecked<T>(L, 1, "gradBias");
auto input = luaGetTensorChecked<T>(L, 2);
auto dOutput = luaGetTensorChecked<T>(L, 3);
T scale = luaGetNumberChecked<T>(L, 4);
auto ilen = input->size(0);
auto batchSize = input->size(1);
auto inputPlanes = input->size(2);
auto outputPlanes = dOutput->size(2);
auto olen = dOutput->size(0);
auto kw = dWeight->size(0);
int pad = (olen - ilen + kw - 1) / 2;
auto dW = dWeight->data();
auto dB = dBias->data();
auto I = input->data();
auto dO = dOutput->data();
for (int t = 0; t < olen; t++)
for (int b = 0; b < batchSize; b++)
for (int c = 0; c < outputPlanes; c++)
dB[c] += dO[t * dOutput->stride(0) + b * dOutput->stride(1) + c];
for (int k = 0; k < kw; k++) {
int iShift = std::max(0, k - pad);
int oShift = std::max(0, pad - k);
int t = std::min(ilen + pad - k, olen) - oShift;
// Note: using gemm in column-major order mode
// Input is m*l (row-major)
// dOutput is m*r (row-major)
// dWeight is l*r (row-major)
if (t > 0)
blas::gemm(
CblasColMajor,
CblasNoTrans,
CblasTrans,
outputPlanes, // r
inputPlanes, // l
batchSize * t, // m
scale, // alpha
dO + oShift * dOutput->stride(0),
dOutput->stride(1),
I + iShift * input->stride(0),
input->stride(1),
1, // beta
dW + k * dWeight->stride(0),
outputPlanes
);
}
return 0;
}
template <class T>
class Registerer {
private:
static const luaL_Reg functions_[];
public:
static void registerFunctions(lua_State* L);
};
template <class T>
const luaL_Reg Registerer<T>::functions_[] = {
{"TemporalConvolutionTBC_updateOutput", updateOutput<T>},
{"TemporalConvolutionTBC_updateGradInput", updateGradInput<T>},
{"TemporalConvolutionTBC_accGradParameters", accGradParameters<T>},
{nullptr, nullptr},
};
template <class T>
void Registerer<T>::registerFunctions(lua_State* L) {
luaT_pushmetatable(L, Tensor<T>::kLuaTypeName);
luaT_registeratname(L, functions_, "nn");
lua_pop(L, 1);
}
} // namespace
void initTemporalConvolutionTBC(lua_State* L) {
Registerer<float>::registerFunctions(L);
Registerer<double>::registerFunctions(L);
}
}
}
} // namespaces
<|start_filename|>fbnn/Upsample.lua<|end_filename|>
local Upsample, parent = torch.class('nn.Upsample', 'nn.Module')
function Upsample:__init(factor)
assert(factor == math.floor(factor), 'Upsampling factor must be integer.')
assert(factor >= 1, 'Upsampling factor cannot be smaller than 1.')
parent.__init(self)
self.factor = factor
self.buffer = torch.Tensor()
end
function Upsample:updateOutput(input)
if self.factor ~= 1 then
-- set some variables:
local batchMode = (input:nDimension() == 4)
local offset = batchMode and 1 or 0
local channels = input:size(1 + offset)
local height = input:size(2 + offset)
local width = input:size(3 + offset)
-- compute sizes for the magic incantation:
local extendedSize, expandedSize
if batchMode then
self.output:resize(
input:size(1),
channels,
height * self.factor,
width * self.factor
)
extendedSize = torch.LongStorage(
{input:size(1), channels, height, width, 1, 1}
)
expandedSize = torch.LongStorage(
{input:size(1), channels, height, width, self.factor,
self.factor}
)
else
self.output:resize(
channels,
height * self.factor,
width * self.factor
)
extendedSize = torch.LongStorage(
{channels, height, width, 1, 1}
)
expandedSize = torch.LongStorage(
{channels, height, width, self.factor, self.factor}
)
end
-- perform upsampling without loops in a single copy:
local inputView =
input:contiguous():view(extendedSize):expand(expandedSize)
inputView = inputView:transpose(3 + offset, 4 + offset)
self.output:viewAs(inputView):copy(inputView)
else
self.output:resizeAs(input):copy(input)
end
return self.output
end
function Upsample:updateGradInput(input, gradOutput)
if self.gradInput then
if self.factor ~= 1 then
-- set some variables:
local batchMode = (input:nDimension() == 4)
local offset = batchMode and 1 or 0
local channels = input:size(1 + offset)
local height = input:size(2 + offset)
local width = input:size(3 + offset)
-- compute size for the magic incantation:
local viewSize, sumSize
if batchMode then
viewSize = torch.LongStorage(
{input:size(1), channels, height, self.factor, width,
self.factor}
)
sumSize = torch.LongStorage(
{input:size(1), channels, height, width,
self.factor * self.factor}
)
else
viewSize = torch.LongStorage(
{channels, height, self.factor, width, self.factor}
)
sumSize = torch.LongStorage(
{channels, height, width, self.factor * self.factor}
)
end
-- perform "downsumming" without loops and a single copy:
local gradView = gradOutput:view(viewSize):transpose(
3 + offset, 4 + offset
):contiguous():view(sumSize)
self.gradInput:sum(gradView, 4 + offset):resizeAs(input)
else
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
end
end
end
function Upsample:__tostring__()
return torch.type(self) .. string.format('(factor %d)', self.factor)
end
<|start_filename|>fbnn/SequentialCriterion.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
-- Author: <NAME> <<EMAIL>>
--[[
Combines a module and a criterion.
It is mainly thought for preprocessing, but trainable parameters
can be used if needed
]]
local SequentialCriterion, parent =
torch.class('nn.SequentialCriterion', 'nn.Criterion')
function SequentialCriterion:__init(module, criterion)
parent.__init(self)
self.module = module
self.criterion = criterion
end
function SequentialCriterion:parameters()
local params, gradParams = self.module:parameters_one()
if self.criterion.parameters then
local cparams, cgradParams = self.criterion:parameters_one()
for i = 1, #cparams do
params[1+#params] = cparams[i]
gradParams[1+#gradParams] = cgradParams[i]
end
end
return params, gradParams
end
function SequentialCriterion:getParameters()
return nn.Module.getParameters(self)
end
function SequentialCriterion:updateOutput(input, target)
self.module:updateOutput(input)
self.output = self.criterion:updateOutput(self.module.output, target)
return self.output
end
function SequentialCriterion:updateGradInput(input, target)
local derr_do = self.criterion:updateGradInput(self.module.output, target)
self.gradInput = self.module:updateGradInput(input, derr_do)
return self.gradInput
end
function SequentialCriterion:accGradParameters(input, target, scale)
if self.criterion.accGradParameters ~= nil then
self.criterion:accGradParameters(self.module.output, target, scale)
end
self.module:accGradParameters(input, self.criterion.gradInput, scale)
end
function SequentialCriterion:accUpdateGradParameters(input, target, scale)
if self.criterion.accUpdateGradParameters ~= nil then
self.criterion:accUpdateGradParameters(self.module.output, target, scale)
end
self.module:accUpdateGradParameters(input, self.criterion.gradInput, scale)
end
function SequentialCriterion:updateParameters(learning_rate)
self.module:updateParameters(learning_rate)
if self.criterion.updateParameters then
self.criterion:updateParameters(learning_rate)
end
end
function SequentialCriterion:zeroGradParameters()
if self.criterion.zeroGradParameters then
self.criterion:zeroGradParameters()
end
self.module:zeroGradParameters()
end
<|start_filename|>fbnn/SparseLinear.lua<|end_filename|>
--[[
A faster variant of `nn.SparseLinear` that imposes stricter
preconditions to speed up `updateParameters`.
]]
local SparseLinear, parent = torch.class('fbnn.SparseLinear', 'nn.SparseLinear')
function SparseLinear:__init(inputSize,
outputSize,
useSparseUpdate,
skipUpdateGradInput)
parent.__init(self, inputSize, outputSize)
self.useSparseUpdate = useSparseUpdate
self.numBackward = 0
-- should be true if this is the first layer
if skipUpdateGradInput then
self.gradInput = nil
end
end
function SparseLinear:reshapeKvInput(input)
if input[1]:dim() == 1 then
return {input[1]:view(1, -1), input[2]:view(1, -1)}
else
return input
end
end
function SparseLinear:updateOutput(input)
if type(input) ~= 'table' then
return parent.updateOutput(self, input)
else
input = self:reshapeKvInput(input)
return self.weight.nn.SparseLinear_updateOutput2(self, input[1], input[2])
end
end
function SparseLinear:accGradParameters(input, gradOutput, scale)
if self.useSparseUpdate then
assert(self.numBackward == 0,
'you can only call one backward() when using sparse update')
self.numBackward = self.numBackward + 1
end
if type(input) ~= 'table' then
return parent.accGradParameters(self, input, gradOutput, scale)
else
input = self:reshapeKvInput(input)
if not self.lastInputKey then
self.lastInputKey = input[1]:clone()
self.lastInputVal = input[2]:clone()
else
self.lastInputKey:resizeAs(input[1]):copy(input[1])
self.lastInputVal:resizeAs(input[2]):copy(input[2])
end
return self.weight.nn.SparseLinear_accGradParameters2(
self, input[1], input[2], gradOutput, scale)
end
end
function SparseLinear:updateParameters(learningRate)
if self.useSparseUpdate then
assert(self.numBackward == 1, 'must call backward() once')
if self.lastInputKey then
self.weight.nn.SparseLinear_updateParameters2(self, learningRate)
else
parent.updateParameters(self, learningRate)
end
else
parent.updateParameters(self, learningRate)
end
end
function SparseLinear:zeroGradParameters()
if self.useSparseUpdate then
if self.lastInputKey == nil and self.lastInput == nil then
if self.numBackward > 1 then
io.stderr:write('SparseLinear: using full zeroGrad - maybe ' ..
'you\'re calling backwards twice somewhere...\n')
end
parent.zeroGradParameters(self)
else
assert(self.numBackward == 1, 'must call backward() once')
if self.lastInputKey then
self.weight.nn.SparseLinear_zeroGradParameters2(self)
else
parent.zeroGradParameters(self)
end
end
self.numBackward = 0
else
parent.zeroGradParameters(self)
end
end
function SparseLinear:updateGradInput(input, gradOutput)
if self.gradInput then
if type(input) ~= 'table' then
return parent.updateGradInput(self,input, gradOutput)
else
error('not supported')
end
end
end
<|start_filename|>fbnn/SoftPlusLSEMinusLSECriterion.lua<|end_filename|>
require 'math'
require 'nn'
local SoftPlusLSEMinusLSECriterion, parent =
torch.class('nn.SoftPlusLSEMinusLSECriterion', 'nn.Criterion')
-- loss(x) = log(1 + SumExp(x)) = logSumExp(x)
function SoftPlusLSEMinusLSECriterion:__init(sizeAverage)
parent.__init(self)
if sizeAverage ~= nil then
self.sizeAverage = sizeAverage
else
self.sizeAverage = true
end
--self.beta = beta or 1
self.threshold = 20 -- avoid overflow
self.LSE = torch.Tensor()
end
local function softplus(x)
if x > 20 then
return x
else
return math.log(1 + math.exp(x))
end
end
function SoftPlusLSEMinusLSECriterion:updateOutput(input)
local max_val = torch.max(input, 2)
input = input - max_val:expand(input:size())
self.LSE = input:exp():sum(2):log()
self.LSE:add(max_val)
self.SoftPlusLSE = self.LSE:clone()
self.SoftPlusLSE:apply(softplus)
self.output = (self.SoftPlusLSE - self.LSE):sum()
return self.output
end
function SoftPlusLSEMinusLSECriterion:updateGradInput(input)
self.gradInput = torch.exp(input - self.SoftPlusLSE:expand(input:size()))
self.gradInput:add(-torch.exp(input - self.LSE:expand(input:size())))
return self.gradInput
end
<|start_filename|>fbnn/SparseNLLCriterion.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
-- Author: <NAME> <<EMAIL>>
require 'math'
require 'nn'
-- Sparse ClassNLL criterion
local SparseNLLCriterion, parent =
torch.class('nn.SparseNLLCriterion', 'nn.Criterion')
--[[
Parameters:
* `K` : number of non-zero elements of the target
* `do`_target_check : checks whether the target is a
probability vector (default true)
* `sizeAverage` : divides the error by the size of the minibatch
]]
function SparseNLLCriterion:__init(K)
parent.__init(self)
self.K = K
self.do_target_check = true
self.sizeAverage = true
self.output = torch.Tensor(1)
self.gradInput = torch.Tensor()
self.tmp_buffer = torch.Tensor()
end
--[[
`target` should be a table containing two tensors :
```
target = {targetP, targetIdx}
```
where `targetP` are the probabilities associated to the indices `targetIdx`
we assume `targetIdx` doesn't have twice the same number in the same sample.
]]
function SparseNLLCriterion:updateOutput(input, target)
-- minibatches
if input:dim() == 1 then
input = input:reshape(1, input:size(1))
target[1] = target[1]:reshape(1, target[1]:size(1))
target[2] = target[2]:reshape(1, target[2]:size(1))
else
assert(input:dim() == 2)
end
-- tests if the target sums to 1
if self.do_target_check then
self.tmp_buffer:resize(input:size(1), 1)
self.tmp_buffer:sum(target[1], 2)
if self.tmp_buffer:add(-1):abs():max() > 1e-3 then
error('SparseNLLCriterion : input is not a probability vector \
(you can disable this error by setting do_target_check to false)')
end
end
-- compute the output
input.nn.SparseNLLCriterion_updateOutput(self, input, target[1], target[2])
-- sizeAverage ?
if self.sizeAverage then
self.output:div(input:size(1))
end
return self.output
end
function SparseNLLCriterion:updateGradInput(input, target)
self.gradInput:resizeAs(input)
input.nn.SparseNLLCriterion_updateGradInput(self, target[1], target[2])
if self.sizeAverage then
self.gradInput:div(input:size(1))
end
return self.gradInput
end
<|start_filename|>fbnn/SparseThreshold.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
-- Same as Threshold module, for sparse vectors.
local SparseThreshold, parent = torch.class('nn.SparseThreshold','nn.Module')
function SparseThreshold:__init(th,v)
parent.__init(self)
self.module = nn.Threshold(th,v)
end
function SparseThreshold:updateOutput(input)
self.output:resize(input:size())
local dim = input:nDimension()
local input_indices = input:select(dim,1)
local input_data = input:select(dim,2)
local output_indices = self.output:select(dim,1)
local output_data = self.output:select(dim,2)
output_indices:copy(input_indices)
output_data:copy(self.module:updateOutput(input_data))
return self.output
end
function SparseThreshold:updateGradInput(input, gradOutput)
self.gradInput:resize(input:size())
local dim = input:nDimension()
local input_data = input:select(dim,2)
local gradInput_indices = self.gradInput:select(dim,1)
local gradInput_data = self.gradInput:select(dim,2)
local gradOutput_indices = gradOutput:select(dim,1)
local gradOutput_data = gradOutput:select(dim,2)
gradInput_indices:copy(gradOutput_indices)
gradInput_data:copy(self.module:updateGradInput(input_data,gradOutput_data))
return self.gradInput
end
<|start_filename|>src/Blas.h<|end_filename|>
/**
* Copyright 2014 Facebook
* @author <NAME> (<EMAIL>)
*/
#ifndef DEEPLEARNING_TORCH_BLAS_H_
#define DEEPLEARNING_TORCH_BLAS_H_
#ifdef USE_MKL
#include <mkl.h>
#endif
#include <folly/Preprocessor.h>
namespace facebook { namespace deeplearning { namespace torch { namespace blas {
#define XI(P, name) FB_CONCATENATE(FB_CONCATENATE(cblas_, P), name)
#define XI_I(P, name) FB_CONCATENATE(FB_CONCATENATE(cblas_i, P), name)
#define DEFINE_OPS(T, P) \
inline T asum(long n, const T* x, long incx) { \
return XI(P, asum)(n, x, incx); \
} \
inline void axpy(long n, T alpha, const T* x, long incx, T* y, long incy) { \
XI(P, axpy)(n, alpha, x, incx, y, incy); \
} \
inline void copy(long n, const T* x, long incx, T* y, long incy) { \
XI(P, copy)(n, x, incx, y, incy); \
} \
inline T dot(long n, const T* x, long incx, const T* y, long incy) { \
return XI(P, dot)(n, x, incx, y, incy); \
} \
inline T nrm2(long n, const T* x, long incx) { \
return XI(P, nrm2)(n, x, incx); \
} \
inline void rot(long n, T* x, long incx, T* y, long incy, T c, T s) { \
XI(P, rot)(n, x, incx, y, incy, c, s); \
} \
inline void rotg(T* a, T* b, T* c, T* s) { \
XI(P, rotg)(a, b, c, s); \
} \
inline void rotm(long n, T* x, long incx, T* y, long incy, const T* p) { \
XI(P, rotm)(n, x, incx, y, incy, p); \
} \
inline void rotmg(T* d1, T* d2, T* x1, T y1, T* p) { \
XI(P, rotmg)(d1, d2, x1, y1, p); \
} \
inline void scal(long n, T alpha, T* x, long incx) { \
XI(P, scal)(n, alpha, x, incx); \
} \
inline void swap(long n, T* x, long incx, T* y, long incy) { \
XI(P, swap)(n, x, incx, y, incy); \
} \
inline long iamax(long n, const T* x, long incx) { \
return XI_I(P, amax)(n, x, incx); \
} \
inline long iamin(long n, const T* x, long incx) { \
return XI_I(P, amin)(n, x, incx); \
} \
inline void gemv(CBLAS_LAYOUT layout, CBLAS_TRANSPOSE transA, long m, \
long n, T alpha, const T* a, long lda, const T* x, \
long incx, T beta, T* y, long incy) { \
XI(P, gemv)(layout, transA, m, n, alpha, a, lda, x, incx, beta, y, incy); \
} \
inline void ger(CBLAS_LAYOUT layout, long m, long n, T alpha, \
const T* x, long incx, const T* y, long incy, \
T* a, long lda) { \
XI(P, ger)(layout, m, n, alpha, x, incx, y, incy, a, lda); \
} \
inline void syr(CBLAS_LAYOUT layout, CBLAS_UPLO uplo, long n, \
T alpha, const T* x, long incx, T* a, long lda) { \
XI(P, syr)(layout, uplo, n, alpha, x, incx, a, lda); \
} \
inline void syr2(CBLAS_LAYOUT layout, CBLAS_UPLO uplo, long n, \
T alpha, const T* x, long incx, const T* y, long incy,\
T* a, long lda) { \
XI(P, syr2)(layout, uplo, n, alpha, x, incx, y, incy, a, lda); \
} \
inline void trmv(CBLAS_LAYOUT layout, CBLAS_UPLO uplo, \
CBLAS_TRANSPOSE transA, CBLAS_DIAG diag, long n, \
const T* a, long lda, T* x, long incx) { \
XI(P, trmv)(layout, uplo, transA, diag, n, a, lda, x, incx); \
} \
inline void trsv(CBLAS_LAYOUT layout, CBLAS_UPLO uplo, \
CBLAS_TRANSPOSE transA, CBLAS_DIAG diag, long n, \
const T* a, long lda, T* x, long incx) { \
XI(P, trsv)(layout, uplo, transA, diag, n, a, lda, x, incx); \
} \
inline void gemm(CBLAS_LAYOUT layout, CBLAS_TRANSPOSE transA, \
CBLAS_TRANSPOSE transB, long m, long n, long k, \
T alpha, const T* a, long lda, const T* b, long ldb, \
T beta, T* c, long ldc) { \
XI(P, gemm)(layout, transA, transB, m, n, k, alpha, a, lda, b, ldb, beta, \
c, ldc); \
} \
inline void symm(CBLAS_LAYOUT layout, CBLAS_SIDE side, CBLAS_UPLO uplo, \
long m, long n, T alpha, const T* a, long lda, \
const T* b, long ldb, T beta, T* c, long ldc) { \
XI(P, symm)(layout, side, uplo, m, n, alpha, a, lda, b, ldb, beta, \
c, ldc); \
} \
inline void syrk(CBLAS_LAYOUT layout, CBLAS_UPLO uplo, \
CBLAS_TRANSPOSE transA, long n, long k, T alpha, \
const T* a, long lda, T beta, T* c, long ldc) { \
XI(P, syrk)(layout, uplo, transA, n, k, alpha, a, lda, beta, c, ldc); \
} \
inline void syr2k(CBLAS_LAYOUT layout, CBLAS_UPLO uplo, \
CBLAS_TRANSPOSE trans, long n, long k, T alpha, \
const T* a, long lda, const T* b, long ldb, \
T beta, T* c, long ldc) { \
XI(P, syr2k)(layout, uplo, trans, n, k, alpha, a, lda, b, ldb, beta, \
c, ldc); \
} \
inline void trmm(CBLAS_LAYOUT layout, CBLAS_SIDE side, CBLAS_UPLO uplo, \
CBLAS_TRANSPOSE transA, CBLAS_DIAG diag, long m, \
long n, T alpha, const T* a, long lda, T* b, long ldb) { \
XI(P, trmm)(layout, side, uplo, transA, diag, m, n, alpha, a, lda, \
b, ldb); \
} \
inline void trsm(CBLAS_LAYOUT layout, CBLAS_SIDE side, CBLAS_UPLO uplo, \
CBLAS_TRANSPOSE transA, CBLAS_DIAG diag, long m, \
long n, T alpha, const T* a, long lda, T* b, long ldb) { \
XI(P, trsm)(layout, side, uplo, transA, diag, m, n, alpha, a, lda, \
b, ldb); \
}
DEFINE_OPS(float, s)
DEFINE_OPS(double, d)
inline float sdsdot(long n, float sb, const float* x, long incx,
const float* y, long incy) {
return cblas_sdsdot(n, sb, x, incx, y, incy);
}
inline double dsdot(long n, const float* x, long incx,
const float* y, long incy) {
return cblas_dsdot(n, x, incx, y, incy);
}
#undef DEFINE_OPS
#undef XI_I
#undef XI
}}}} // namespaces
#endif /* DEEPLEARNING_TORCH_BLAS_H_ */
<|start_filename|>fbnn/LinearNoBackprop.lua<|end_filename|>
local LinearNoBackprop, parent = torch.class('nn.LinearNoBackprop', 'nn.Linear')
-- This is like Linear, except that it does not backpropagate gradients w.r.t.
-- input.
function LinearNoBackprop:__init(inputSize, outputSize)
parent.__init(self, inputSize, outputSize)
end
function LinearNoBackprop:updateGradInput(input, gradOutput)
if self.gradInput then
self.gradInput:resizeAs(input)
self.gradInput:zero()
return self.gradInput
end
end
<|start_filename|>src/FasterLookup.c<|end_filename|>
#ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "src/FasterLookup.c"
#else
// add two vectors
static inline void nn_(FasterLookup_addVec)(
real *res, real alpha, real *vec, int dim) {
int i;
int m = dim - 3;
for (i = 0; i < m; i += 4) {
res[i] += alpha * vec[i];
res[i+1] += alpha * vec[i+1];
res[i+2] += alpha * vec[i+2];
res[i+3] += alpha * vec[i+3];
}
for ( ; i < dim; ++i)
res[i] += alpha * vec[i];
}
// check if input goes outside allowed indicies
static int nn_(FasterLookup_boundError)(
int n_inputs, int max_index, int* input) {
int i; int idx; int err = 0;
for(i=0; i<n_inputs; i++){
idx = *input++;
err = err || idx < 1 || idx > max_index;
}
return err;
}
// accumulate into (grad)weights
static void nn_(FasterLookup_acc)(THTensor *tWeight, real scale,
THIntTensor *tInput, THTensor *tGradOutput, THIntTensor *tCount,
int concUpdates){
// make sure input, gradOutput are contiguous
tInput = THIntTensor_newContiguous(tInput);
tGradOutput = THTensor_(newContiguous)(tGradOutput);
real * weight = THTensor_(data)(tWeight);
int * input = THIntTensor_data(tInput);
real * gradOutput = THTensor_(data)(tGradOutput);
int * count = (tCount) ? (THIntTensor_data(tCount)) : (NULL);
// update
int n_inputs = THIntTensor_nElement(tInput);
int dim = tWeight->size[1];
int i;
int idx;
if (concUpdates) { // with OMP, concurrent updates, might drop some updates
#pragma omp parallel for private(i, idx)
for(i=0; i<n_inputs; i++){
idx = input[i] - 1;
real s = (count) ? (scale / (real)count[idx]) : scale;
real *w = weight + dim * idx;
nn_(FasterLookup_addVec)(w, s, gradOutput + dim * i, dim);
}
} else { // without OMP
for(i=0; i<n_inputs; i++){
idx = input[i] - 1;
real s = (count) ? (scale / (real)count[idx]) : scale;
real *w = weight + dim * idx;
nn_(FasterLookup_addVec)(w, s, gradOutput + dim * i, dim);
}
}
THIntTensor_free(tInput);
THTensor_(free)(tGradOutput);
}
// count frequency of each index
static void nn_(FasterLookup_incrementCount)(
THIntTensor *tInput, THIntTensor *tCount, int reset) {
// make sure input is contiguous
tInput = THIntTensor_newContiguous(tInput);
int * input = THIntTensor_data(tInput);
int * count = THIntTensor_data(tCount);
int n_inputs = THIntTensor_nElement(tInput);
int i;
count -= 1; // this is lua everything starts at 1
int * cur_input = input;
// set to 0 seen indices if necessary
if (reset) { for(i=0; i<n_inputs; i++){ count[*cur_input++] = 0; } }
// count seen indices
cur_input = input;
for(i=0; i<n_inputs; i++){ count[*cur_input++]++; }
THIntTensor_free(tInput);
}
int nn_(FasterLookup_updateOutput)(lua_State *L) {
THIntTensor *tInput = luaT_checkudata(L, 2, "torch.IntTensor");
THTensor * tWeight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
int skipBC = luaT_getfieldcheckboolean(L, 1, "skipBoundChecking");
THTensor * tOutput = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor);
tInput = THIntTensor_newContiguous(tInput); // make sure input is contiguous
int dim = tWeight->size[1];
if (tInput->nDimension == 1) { // resize output
THTensor_(resize2d)(tOutput, tInput->size[0], dim);
} else if (tInput->nDimension == 2) {
THTensor_(resize3d)(tOutput, tInput->size[0], tInput->size[1], dim);
} else {
luaL_error(L, "input should have 1 or 2 dimensions");
}
int n_inputs = THIntTensor_nElement(tInput);
int *input = THIntTensor_data(tInput); // pointers
real * weight = THTensor_(data)(tWeight);
real * output = THTensor_(data)(tOutput);
if (!skipBC) { // bound checking?
int max_index = tWeight->size[0];
int err = nn_(FasterLookup_boundError)(n_inputs, max_index, input);
if (err) { luaL_error(L, "input contains an index out of bounds"); }
}
int i;
size_t vec_size = dim*sizeof(real);
weight -= dim; // this is lua everything starts at 1
#pragma omp parallel for private(i)
for(i=0; i<n_inputs; i++){
memcpy(output + i*dim, weight + input[i]*dim, vec_size);
}
THIntTensor_free(tInput);
return 1;
}
int nn_(FasterLookup_updateParameters)(lua_State *L){
real lr = (real)luaL_checknumber(L, 2);
THTensor * tWeight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor * tGradWeight = luaT_getfieldcheckudata(L, 1, "gradWeight", torch_Tensor);
THIntTensor * tCount = luaT_getfieldcheckudata(L, 1, "count", "torch.IntTensor");
int scaleGradByFreq = luaT_getfieldcheckboolean(L, 1, "scaleGradByFreq");
real * weight = THTensor_(data)(tWeight);
real * gradWeight = THTensor_(data)(tGradWeight);
int * count = THIntTensor_data(tCount);
int i;
int c;
int n_indexes = tWeight->size[0];
int dim = tWeight->size[1];
#pragma omp parallel for private(i, c)
for(i=0; i < n_indexes; i++){
c = count[i];
if (c > 0) { // each non zero count need add
real scale = (scaleGradByFreq) ? (lr / ((real)c)) : (lr);
real *w = weight + dim * i;
real *gw = gradWeight + dim * i;
nn_(FasterLookup_addVec)(w, -scale, gw, dim);
}
}
return 0;
}
int nn_(FasterLookup_accGradParameters)(lua_State *L){
THIntTensor * tInput = luaT_checkudata(L, 2, "torch.IntTensor");
THTensor * tGradOutput = luaT_checkudata(L, 3, torch_Tensor);
real scale = (real)luaL_checknumber(L, 4);
THTensor * tGradWeight = luaT_getfieldcheckudata(L, 1, "gradWeight", torch_Tensor);
// increment count
THIntTensor * tCount = luaT_getfieldcheckudata(L, 1, "count", "torch.IntTensor");
nn_(FasterLookup_incrementCount)(tInput, tCount, 0);
// increment grad weight
int concUpdates = luaT_getfieldcheckboolean(L, 1, "concUpdates");
nn_(FasterLookup_acc)(tGradWeight, scale, tInput, tGradOutput, NULL, concUpdates);
return 0;
}
int nn_(FasterLookup_accUpdateGradParameters)(lua_State *L){
THIntTensor * tInput = luaT_checkudata(L, 2, "torch.IntTensor");
THTensor * tGradOutput = luaT_checkudata(L, 3, torch_Tensor);
real lr = (real)luaL_checknumber(L, 4);
THTensor * tWeight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
// reset and increment count
THIntTensor * tCount = NULL;
int scaleGradByFreq = luaT_getfieldcheckboolean(L, 1, "scaleGradByFreq");
if (scaleGradByFreq) {
tCount = luaT_getfieldcheckudata(L, 1, "count", "torch.IntTensor");
nn_(FasterLookup_incrementCount)(tInput, tCount, 1);
}
// increment weight
int concUpdates = luaT_getfieldcheckboolean(L, 1, "concUpdates");
nn_(FasterLookup_acc)(tWeight, -lr, tInput, tGradOutput, tCount, concUpdates);
return 0;
}
static const struct luaL_Reg nn_(FasterLookup__) [] = {
{"FasterLookup_updateOutput", nn_(FasterLookup_updateOutput)},
{"FasterLookup_updateParameters", nn_(FasterLookup_updateParameters)},
{"FasterLookup_accGradParameters", nn_(FasterLookup_accGradParameters)},
{"FasterLookup_accUpdateGradParameters",nn_(FasterLookup_accUpdateGradParameters)},
{NULL, NULL}
};
void nn_(FasterLookup_init)(lua_State *L)
{
luaT_pushmetatable(L, torch_Tensor);
luaT_registeratname(L, nn_(FasterLookup__), "nn");
lua_pop(L,1);
}
#endif
<|start_filename|>fbnn/Dropout.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
local async_rng = require('fb.torch.async_rng')
local trace = require('fb.util.trace')
-- Hack: store RNG externally so that we don't try to serialize it...
local rngs = {}
-- Weak keys, so we don't leak RNG objects if the corresponding Dropout
-- objects are destroyed
setmetatable(rngs, {__mode = 'k'})
--[[
A faster variant of `nn.Dropout` that uses the `fblualib` asynchronous RNG.
]]
local Dropout, Parent = torch.class('fbnn.Dropout', 'nn.Module')
--[[
Parameter:
- `p`: the dropout probability (the probability that a given activation will be dropped)
]]
function Dropout:__init(p)
Parent.__init(self)
self.p = p or 0.5
self.train = true
if self.p >= 1 or self.p < 0 then
error('<Dropout> illegal percentage, must be 0 <= p < 1')
end
self.noise = torch.Tensor()
end
local function concat_tensors(dest, size, tensors)
local next_index = 1
dest:resize(size)
for _, tensor in ipairs(tensors) do
local n = tensor:nElement()
dest:narrow(1, next_index, n):copy(tensor)
next_index = next_index + n
end
assert(next_index == dest:nElement() + 1)
end
function Dropout:updateOutput(input)
self.output:resizeAs(input):copy(input)
if self.train then
local n = input:nElement()
local rng = rngs[self]
if not rng then
rng = async_rng.bernoulli('torch.FloatTensor', n, 1 - self.p)
rngs[self] = rng
end
local fnoise = rng:generate(n)
concat_tensors(self.noise, n, fnoise)
self.noise:resizeAs(input)
self.output:cmul(self.noise)
else
self.output:mul(1-self.p)
end
return self.output
end
function Dropout:updateGradInput(input, gradOutput)
if self.train then
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
-- simply mask the gradients with the noise vector
self.gradInput:cmul(self.noise)
else
error('backprop only defined while training')
end
return self.gradInput
end
function Dropout:setp(p)
self.p = p
rngs[self] = nil
end
<|start_filename|>fbnn/DifferenceOfGaussian.lua<|end_filename|>
local DifferenceOfGaussian, parent =
torch.class('nn.DifferenceOfGaussian', 'nn.Module')
--[[
This Module implements a layer that performs a difference of Gaussian pyrmiad
filtering of the input. The user needs to specify the number of octaves to
produce (`nOctaves`; default = 3) as well as the number of scales returned per
octave (`nScalesPerOctave`; default = 5).
Example usage:
> im = image.lena()
> nOctaves = 3
> nScalesPerOctave = 5
> net = nn.Sequential()
> net:add(nn.DifferenceOfGaussian(nOctaves, nScalesPerOctave))
> local filteredIm = net:forward(im)
]]--
-- helper function to make Gaussian filter:
local function getGaussianFilter(sigma, sz)
local sz = sz or math.floor(sigma * 4)
local filter = torch.Tensor(sz, sz)
for i = 1,sz do
for j = 1,sz do
local D = (i - math.floor(sz / 2)) * (i - math.floor(sz / 2))
+ (j - math.floor(sz / 2)) * (j - math.floor(sz / 2))
filter[i][j] = math.exp(-D / (2 * sigma * sigma))
end
end
filter:div(filter:sum())
return filter
end
-- helper function to subsample an image:
local function subsample(im, stride)
local sub
if im:nDimension() == 4 then
sub = im:index(4, torch.range(stride, im:size(4), stride):long()):index(
3, torch.range(stride, im:size(3), stride):long()
)
else
sub = im:index(3, torch.range(stride, im:size(3), stride):long()):index(
2, torch.range(stride, im:size(2), stride):long()
)
end
return sub
end
-- constructor for the layer:
-- * nInputPlane is the number of input planes (channels)
-- * nOctaves is the number of octaves (number of times bandwidth doubles)
-- * nScalesPerOctave is the number of sigma values per octave
--
-- * the output of forward() is a table with nOctaves cell, in which each cell
-- contains a tensor with nScalesPerOctave planes
function DifferenceOfGaussian:__init(nInputPlane, nOctaves, nScalesPerOctave)
parent.__init(self)
assert(nInputPlane)
self.nOctaves = nOctaves or 3
self.nScalesPerOctave = nScalesPerOctave or 5
self.nInputPlane = nInputPlane
self.nOutputPlane = nOctaves
self.dW = 1
self.dH = 1
-- compute sigmas for which to compute filter responses:
self.sigma = torch.Tensor(self.nScalesPerOctave + 1):fill(1)
for n = 2,self.nScalesPerOctave do
self.sigma[n] = self.sigma[n - 1] *
(math.pow(2, 1 / self.nScalesPerOctave))
end
self.sigma[self.nScalesPerOctave + 1] = 2.0
local sz = math.ceil(self.sigma:max() * 2.5)
if sz % 2 == 0 then sz = sz + 1 end
-- construct the Gaussian filters for an octave:
self.filter = torch.Tensor(self.sigma:nElement(), sz, sz)
for n = 1,self.sigma:nElement() do
self.filter[n]:copy(getGaussianFilter(self.sigma[n], sz))
end
-- set padding and kernel size:
self.kH = self.filter[1]:size(1)
self.kW = self.filter[1]:size(2)
self.padH = math.floor(self.filter[1]:size(1) / 2)
self.padW = math.floor(self.filter[1]:size(2) / 2)
-- initialize buffers for efficiency on GPU:
self.finput = torch.Tensor()
self.fgradInput = torch.Tensor()
self.outputBuf = torch.Tensor()
end
-- function implementing a forward pass in the layer:
function DifferenceOfGaussian:updateOutput(input)
-- determine which dimension contains channels:
local batchMode = false
if input:nDimension() == 4 then
batchMode = true
elseif input:nDimension() ~= 3 then
error('3D or 4D(batch mode) tensor expected')
end
local dim = batchMode and 2 or 1
assert(input:size(dim) == self.nInputPlane)
local numChannels = self.nInputPlane
local input = input:clone()
-- loop over all octaves:
local finalOutput = {}
self.output = input.new()
for m = 1,self.nOctaves do
-- resize output buffer:
if batchMode then
self.outputBuf:resize(
input:size(1),
self.sigma:nElement() * numChannels,
input:size(3),
input:size(4)
)
else
self.outputBuf:resize(
self.sigma:nElement() * numChannels,
input:size(2),
input:size(3)
)
end
-- apply filters (loop because channels shouldn't be merged):
self:__prepareFilter(input)
for c = 1,numChannels do
local inputPlane = input:narrow(dim, c, 1)
local output = self.outputBuf:narrow(
dim, (c - 1) * self.sigma:nElement() + 1,
self.sigma:nElement())
input.THNN.SpatialConvolutionMM_updateOutput(
inputPlane:cdata(),
output:cdata(),
self.weight:cdata(),
self.bias:cdata(),
self.finput:cdata(),
self.fgradInput:cdata(),
self.kW, self.kH,
self.dW, self.dH,
self.padW, self.padH
)
end
-- compute the difference of Gaussian responses in-place:
for c = 1,numChannels do
self.outputBuf:narrow(
dim, (c - 1) * self.sigma:nElement() + 1,
self.nScalesPerOctave
):add(
-self.outputBuf:narrow(
dim, (c - 1) * self.sigma:nElement() + 2,
self.nScalesPerOctave
)
)
end -- leaves the image for sigma = 2 unaltered
-- set final output of layer:
local columnInd = torch.LongTensor(self.nScalesPerOctave * numChannels)
for c = 1,numChannels do
columnInd:narrow(
1, (c - 1) * self.nScalesPerOctave + 1,
self.nScalesPerOctave
):copy(
torch.range(
(c - 1) * self.sigma:nElement() + 1,
(c - 1) * self.sigma:nElement() + self.nScalesPerOctave
):long()
) -- we are not storing sigma = 2, will be in next octave
end
finalOutput[m] = self.outputBuf:index(dim, columnInd)
-- subsample blurred input image:
for c = 1,numChannels do
input:select(dim, c):copy(
self.outputBuf:select(
dim,
(c - 1) * self.sigma:nElement() + self.nScalesPerOctave + 1
)
)
end
input = subsample(input, 2)
end
-- clean up and return:
self:__cleanStateVars(numChannels)
self.output = finalOutput
return self.output
end
-- we do not need to compute parameter gradients as there are no parameters:
function DifferenceOfGaussian:accUpdateGradParameters(input, gradOutput, lr)
end
-- do never update the filters:
function DifferenceOfGaussian:updateParameters(lr)
end
-- this function facilitates different behavior of buffers on CPU and GPU:
function DifferenceOfGaussian:type(type)
self.finput = torch.Tensor()
self.fgradInput = torch.Tensor()
self.outputBuf = torch.Tensor()
return parent.type(self, type)
end
-- helper function to prepare for filtering:
function DifferenceOfGaussian:__prepareFilter(input)
-- copy filter here to weights so we can use SpatialConvolutionMM:
self.weight = input.new(
self.filter:size(1),
self.filter:size(2) * self.filter:size(3)
):copy(self.filter)
self.bias = input.new(self.filter:size(1)):zero()
self.nInputPlane = 1
self.nOutputPlane = self.sigma:nElement()
end
-- helper function for cleaning up state variables:
function DifferenceOfGaussian:__cleanStateVars(numChannels)
self.weight = nil
self.bias = nil
self.nInputPlane = numChannels
self.nOutputPlane = self.nOctaves
end
<|start_filename|>fbnn/ClassNLLCriterionWithUNK.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
-- Author: <NAME> <<EMAIL>>
-- This file implements a wrapper for ClassNLLCriterion, which ignores a
-- specific label <unk>
require 'nn'
local ClassNLLCriterionWithUNK, parent =
torch.class('nn.ClassNLLCriterionWithUNK', 'nn.Criterion')
function ClassNLLCriterionWithUNK:__init(unk_index, sizeAverage)
self.unk_index = unk_index
self.crit = nn.ClassNLLCriterion()
if sizeAverage ~= nil then
self.crit.sizeAverage = sizeAverage
end
self.tmp = torch.LongTensor()
self.output = 0 --TODO: this doesn't work with CudaTensors
self.gradInputExtra = torch.Tensor()
self.gradInput = self.crit.gradInput
self.tensortype = torch.Tensor():type()
end
function ClassNLLCriterionWithUNK:cuda()
nn.Criterion.cuda(self)
self.crit:cuda()
self.tensortype = 'torch.CudaTensor'
return self
end
function ClassNLLCriterionWithUNK:updateOutput(input, target)
local n = 0
if input:dim() == 1 then
if ((type(target) == 'number') and (target ~= self.unk_index)) or
((type(target) ~= 'number') and (target[1] ~= self.unk_index))
then
self.output = self.crit:updateOutput(input, target)
n = 1
end
else -- minibatch
assert(input:dim() == 2)
assert(target:dim() == 1)
self.tmp:resize(target:size())
self.use_unk = false
if self.tensortype == 'torch.CudaTensor' then
self.use_unk = (self.unk_index ~= nil)
elseif self.unk_index then
torch.eq(self.tmp, target, self.unk_index)
if self.tmp:sum() > 0 then
self.use_unk = true
end
end
if self.use_unk then -- to go faster, do only that if needed
self.output = 0
for i = 1,input:size(1) do
if target[i] ~= self.unk_index then
self.output = self.output +
self.crit:updateOutput(input[i], target[i])
n = n + 1
end
end
else
self.output = self.crit:updateOutput(input, target)
n = target:size(1)
end
end
return self.output, n
end
function ClassNLLCriterionWithUNK:updateGradInput(input, target)
if input:dim() == 1 then
if ((type(target) == 'number') and (target ~= self.unk_index)) or
((type(target) ~= 'number') and (target[1] ~= self.unk_index))
then
self.gradInput = self.crit:updateGradInput(input, target)
end
else --minibatch
assert(input:dim() == 2)
assert(target:dim() == 1)
if self.use_unk then
self.gradInputExtra:resizeAs(input)
for i = 1,input:size(1) do
if target[i] ~= self.unk_index then
self.gradInputExtra[i]
:copy(self.crit:updateGradInput(input[i], target[i]))
else
self.gradInputExtra[i]:zero()
end
end
self.gradInput = self.gradInputExtra
else
self.gradInput = self.crit:updateGradInput(input, target)
end
end
return self.gradInput
end
<|start_filename|>src/SparseLinear.c<|end_filename|>
#ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "src/SparseLinear.c"
#else
#ifdef _OPENMP
#include <omp.h>
#endif
#define ROW_PTR2(t, r) (THTensor_(data)(t) + (r) * (t)->stride[0])
#define COL_PTR2(t, c) (THTensor_(data)(t) + (c) * (t)->stride[1])
static int nn_(checkInput)(THTensor* t) {
return t->nDimension == 3 && t->size[2] == 2;
}
static int nn_(checkKvInput)(THLongTensor* key, THTensor* val) {
return THLongTensor_nDimension(key) == 2 &&
THTensor_(nDimension)(val) == 2 &&
THTensor_(size)(val, 0) == THLongTensor_size(key, 0) &&
THTensor_(size)(val, 1) == THLongTensor_size(key, 1);
}
static int nn_(checkSize2D)(THTensor* t, long size0, long size1) {
return t->nDimension == 2 && t->size[0] == size0 && t->size[1] == size1;
}
static int nn_(checkSize1D)(THTensor* t, long size0) {
return t->nDimension == 1 && t->size[0] == size0;
}
static void nn_(set1d)(THTensor *t, long x0, real value) {
THStorage_(set)(t->storage, t->storageOffset + x0*t->stride[0], value);
}
static real nn_(get3d)(const THTensor *t, long x0, long x1, long x2) {
return THStorage_(get)(t->storage, t->storageOffset +
x0*t->stride[0] + x1*t->stride[1] + x2*t->stride[2]);
}
static real nn_(get2d)(const THTensor *t, long x0, long x1) {
return THStorage_(get)(t->storage, t->storageOffset +
x0*t->stride[0] + x1*t->stride[1]);
}
static long nn_(get2dL)(const THLongTensor *t, long x0, long x1) {
return THLongStorage_get(t->storage, t->storageOffset +
x0*t->stride[0] + x1*t->stride[1]);
}
static int nn_(SparseLinear_updateOutput)(lua_State* L) {
long h, i;
THTensor* input = luaT_checkudata(L, 2, torch_Tensor);
THTensor* weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor* bias = luaT_getfieldcheckudata(L, 1, "bias", torch_Tensor);
THTensor* output = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor);
long outDim = THTensor_(size)(weight, 0);
long inDim = THTensor_(size)(weight, 1);
luaL_argcheck(L, nn_(checkSize1D)(bias, outDim), 1, "bias size wrong");
luaL_argcheck(L, nn_(checkInput)(input), 2,
"input size must be batchsize x nnz x 2");
luaL_argcheck(L, THTensor_(isContiguous)(output), 1,
"output must be contiguous");
long batchSize = THTensor_(size)(input, 0);
long nnz = THTensor_(size)(input, 1);
THTensor_(resize2d)(output, batchSize, outDim);
// output = weight * input + bias
THTensor_(zero)(output);
#pragma omp parallel for private(h, i) schedule(static) if ( \
batchSize > 1 && batchSize * nnz * outDim > 10000)
for (h = 0; h < batchSize; h++) {
for (i = 0; i < nnz; i++) {
real val = nn_(get3d)(input, h, i, 1);
if (val == 0) {
continue;
}
long offset = (long)(nn_(get3d)(input, h, i, 0)) - 1;
if (offset >= 0 && offset < inDim) {
THBlas_(axpy)(outDim,
val,
COL_PTR2(weight, offset), weight->stride[0],
ROW_PTR2(output, h), output->stride[1]);
} else {
luaL_error(
L,
"index out of bound. updateOutput: %d not between 1 and %d",
offset + 1,
inDim);
}
}
}
THTensor* output_row = THTensor_(new)();
for (h = 0; h < batchSize; h++) {
THTensor_(select)(output_row, output, 0, h);
THTensor_(cadd)(output_row, bias, 1.0, output_row);
}
THTensor_(free)(output_row);
if (batchSize == 1) {
THTensor_(resize1d)(output, outDim);
}
lua_getfield(L, 1, "output");
return 1;
}
static int nn_(SparseLinear_updateOutput2)(lua_State* L) {
long h, i;
THLongTensor* inputKey = luaT_checkudata(L, 2, "torch.LongTensor");
THTensor* inputVal = luaT_checkudata(L, 3, torch_Tensor);
THTensor* weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor* bias = luaT_getfieldcheckudata(L, 1, "bias", torch_Tensor);
THTensor* output = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor);
long outDim = THTensor_(size)(weight, 0);
long inDim = THTensor_(size)(weight, 1);
luaL_argcheck(L, nn_(checkSize1D)(bias, outDim), 1, "bias size wrong");
luaL_argcheck(L, nn_(checkKvInput)(inputKey, inputVal), 3, "input wrong");
luaL_argcheck(L, THTensor_(isContiguous)(output), 1,
"output must be contiguous");
long batchSize = THLongTensor_size(inputKey, 0);
long nnz = THLongTensor_size(inputKey, 1);
THTensor_(resize2d)(output, batchSize, outDim);
// output = weight * input + bias
THTensor_(zero)(output);
#pragma omp parallel for private(h, i) schedule(static) if ( \
batchSize > 1 && batchSize * nnz * outDim > 10000)
for (h = 0; h < batchSize; ++h) {
for (i = 0; i < nnz; ++i) {
real val = nn_(get2d)(inputVal, h, i);
if (val == 0) {
continue;
}
long offset = nn_(get2dL)(inputKey, h, i) - 1;
if (offset >= 0 && offset < inDim) {
THBlas_(axpy)(outDim,
val,
COL_PTR2(weight, offset), weight->stride[0],
ROW_PTR2(output, h), output->stride[1]);
} else {
luaL_error(
L, "wrong index. updateOutput2: %d vs %d", offset + 1, inDim);
}
}
}
THTensor* output_row = THTensor_(new)();
for (h = 0; h < batchSize; ++h) {
THTensor_(select)(output_row, output, 0, h);
THTensor_(cadd)(output_row, bias, 1.0, output_row);
}
THTensor_(free)(output_row);
if (batchSize == 1) {
THTensor_(resize1d)(output, outDim);
}
lua_getfield(L, 1, "output");
return 1;
}
static int nn_(SparseLinear_accGradParameters)(lua_State* L) {
long h, i;
THTensor* input = luaT_checkudata(L, 2, torch_Tensor);
THTensor* gradOutput = luaT_checkudata(L, 3, torch_Tensor);
real scale = luaL_optnumber(L, 4, 1);
THTensor* weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor* gradBias = luaT_getfieldcheckudata(L, 1, "gradBias", torch_Tensor);
THTensor* gradWeight = luaT_getfieldcheckudata(
L, 1, "gradWeight", torch_Tensor);
real weightDecay = luaT_getfieldchecknumber(L, 1, "weightDecay");
long outDim = THTensor_(size)(weight, 0);
long inDim = THTensor_(size)(weight, 1);
luaL_argcheck(L, nn_(checkSize2D)(gradWeight, outDim, inDim), 1,
"gradWeight size wrong");
luaL_argcheck(L, nn_(checkSize1D)(gradBias, outDim), 1,
"gradBias size wrong");
luaL_argcheck(L, nn_(checkInput)(input), 2,
"input must be a batchsize x nnz x 2");
luaL_argcheck(L, THTensor_(isContiguous)(gradOutput), 1,
"output must be contiguous");
long batchSize = THTensor_(size)(input, 0);
long nnz = THTensor_(size)(input, 1);
THTensor_(resize2d)(gradOutput, batchSize, outDim);
// gradWeight += gradOutput * input
#pragma omp parallel for private(h, i) schedule(static) if (\
batchSize * nnz * outDim > 10000)
for (i = 0; i < nnz; i++) {
for (h = 0; h < batchSize; h++) {
real val = scale * nn_(get3d)(input, h, i, 1);
if (val == 0) {
continue;
}
long offset = (long)(nn_(get3d)(input, h, i, 0)) - 1;
if (offset >= 0 && offset < inDim) {
THBlas_(axpy)(outDim,
val,
ROW_PTR2(gradOutput, h), gradOutput->stride[1],
COL_PTR2(gradWeight, offset), gradWeight->stride[0]);
} else {
luaL_error(
L,
"index out of bound. accGradParameters: %d not between 1 and %d",
offset + 1,
inDim);
}
}
}
// gradBias += gradOutput
THTensor* gradOutput_row = THTensor_(new)();
for (h = 0; h < batchSize; h++) {
THTensor_(select)(gradOutput_row, gradOutput, 0, h);
THTensor_(cadd)(gradBias, gradBias, scale, gradOutput_row);
}
THTensor_(free)(gradOutput_row);
if (weightDecay != 0) {
THTensor_(cadd)(gradWeight, gradWeight, weightDecay, weight);
}
if (batchSize == 1) {
THTensor_(resize1d)(gradOutput, outDim);
}
return 0;
}
static int nn_(SparseLinear_accGradParameters2)(lua_State* L) {
long h, i;
THLongTensor* inputKey = luaT_checkudata(L, 2, "torch.LongTensor");
THTensor* inputVal = luaT_checkudata(L, 3, torch_Tensor);
THTensor* gradOutput = luaT_checkudata(L, 4, torch_Tensor);
real scale = luaL_optnumber(L, 5, 1);
THTensor* weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor* gradBias = luaT_getfieldcheckudata(L, 1, "gradBias", torch_Tensor);
THTensor* gradWeight = luaT_getfieldcheckudata(
L, 1, "gradWeight", torch_Tensor);
real weightDecay = luaT_getfieldchecknumber(L, 1, "weightDecay");
long outDim = THTensor_(size)(weight, 0);
long inDim = THTensor_(size)(weight, 1);
luaL_argcheck(L, nn_(checkSize2D)(gradWeight, outDim, inDim), 1,
"gradWeight size wrong");
luaL_argcheck(L, nn_(checkSize1D)(gradBias, outDim), 1,
"gradBias size wrong");
luaL_argcheck(L, nn_(checkKvInput)(inputKey, inputVal), 3, "input wrong");
luaL_argcheck(L, THTensor_(isContiguous)(gradOutput), 1,
"output must be contiguous");
// unify dimensions for batch and non-batch input
long batchSize = THLongTensor_size(inputKey, 0);
long nnz = THLongTensor_size(inputKey, 1);
THTensor_(resize2d)(gradOutput, batchSize, outDim);
// gradWeight += gradOutput * input
#pragma omp parallel for private(h, i) schedule(static) if (\
batchSize * nnz * outDim > 10000)
for (i = 0; i < nnz; ++i) {
for (h = 0; h < batchSize; ++h) {
real val = scale * nn_(get2d)(inputVal, h, i);
if (val == 0) {
continue;
}
long offset = nn_(get2dL)(inputKey, h, i) - 1;
if (offset >= 0 && offset < inDim) {
THBlas_(axpy)(outDim,
val,
ROW_PTR2(gradOutput, h), gradOutput->stride[1],
COL_PTR2(gradWeight, offset), gradWeight->stride[0]);
} else {
luaL_error(
L, "wrong index. accGradParameters: %d vs %d", offset + 1, inDim);
}
}
}
// gradBias += gradOutput
THTensor* gradOutput_row = THTensor_(new)();
for (h = 0; h < batchSize; h++) {
THTensor_(select)(gradOutput_row, gradOutput, 0, h);
THTensor_(cadd)(gradBias, gradBias, scale, gradOutput_row);
}
THTensor_(free)(gradOutput_row);
if (weightDecay != 0) {
THTensor_(cadd)(gradWeight, gradWeight, weightDecay, weight);
}
if (batchSize == 1) {
THTensor_(resize1d)(gradOutput, outDim);
}
return 0;
}
int nn_(SparseLinear_updateParameters)(lua_State* L) {
long h, i;
real learningRate = luaL_checknumber(L, 2);
THTensor* weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor* bias = luaT_getfieldcheckudata(L, 1, "bias", torch_Tensor);
THTensor* gradBias = luaT_getfieldcheckudata(L, 1, "gradBias", torch_Tensor);
THTensor* gradWeight = luaT_getfieldcheckudata(
L, 1, "gradWeight", torch_Tensor);
THTensor* lastInput = luaT_getfieldcheckudata(
L, 1, "lastInput", torch_Tensor);
long outDim = THTensor_(size)(weight, 0);
long inDim = THTensor_(size)(weight, 1);
luaL_argcheck(L, nn_(checkSize2D)(gradWeight, outDim, inDim), 1,
"gradWeight size wrong");
luaL_argcheck(L, nn_(checkSize1D)(bias, outDim), 1, "bias size wrong");
luaL_argcheck(L, nn_(checkSize1D)(gradBias, outDim), 1,
"gradBias size wrong");
luaL_argcheck(L, nn_(checkInput)(lastInput), 1,
"input size must be batchsize x nnz x 2");
long batchSize = THTensor_(size)(lastInput, 0);
long nnz = THTensor_(size)(lastInput, 1);
// collect unique offsets of non-0 val in input
THTensor* offsets = THTensor_(newWithSize1d)(batchSize * nnz);
long cnt = 0;
for (h = 0; h < batchSize; h++) {
for (i = 0; i < nnz; i++) {
real val = nn_(get3d)(lastInput, h, i, 1);
if (val == 0 ) {
continue;
}
long offset = (long)(nn_(get3d)(lastInput, h, i, 0)) - 1;
if (offset >= 0 && offset < inDim) {
nn_(set1d)(offsets, cnt++, offset);
} else {
luaL_error(
L,
"index out of bound. updateParameters: %d not between 1 and %d",
offset + 1,
inDim);
}
}
}
THTensor_(resize1d)(offsets, cnt);
THTensor* uniqueOffsets = THTensor_(new)();
THLongTensor* ri = THLongTensor_new();
THTensor_(sort)(uniqueOffsets, ri, offsets, 0, 0);
THLongTensor_free(ri);
THTensor_(free)(offsets);
cnt = 1;
real* uniqueOffsets_p = THTensor_(data)(uniqueOffsets);
for (i = 1; i < THTensor_(size)(uniqueOffsets, 0); i++) {
if (uniqueOffsets_p[i] != uniqueOffsets_p[i - 1]) {
uniqueOffsets_p[cnt++] = uniqueOffsets_p[i];
}
}
THTensor_(resize1d)(uniqueOffsets, cnt);
// weight += -learningRate * gradWeight
THTensor_(cadd)(bias, bias, -learningRate, gradBias);
#pragma omp parallel for private(i) schedule(static) if (cnt * outDim > 10000)
for (i = 0; i < cnt; i++) {
long offset = (long)uniqueOffsets_p[i];
THBlas_(axpy)(outDim,
-learningRate,
COL_PTR2(gradWeight, offset), gradWeight->stride[0],
COL_PTR2(weight, offset), weight->stride[0]);
}
THTensor_(free)(uniqueOffsets);
return 0;
}
int nn_(SparseLinear_updateParameters2)(lua_State* L) {
long h, i;
real learningRate = luaL_checknumber(L, 2);
THTensor* weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor* bias = luaT_getfieldcheckudata(L, 1, "bias", torch_Tensor);
THTensor* gradBias = luaT_getfieldcheckudata(L, 1, "gradBias", torch_Tensor);
THTensor* gradWeight = luaT_getfieldcheckudata(
L, 1, "gradWeight", torch_Tensor);
THLongTensor* lastInputKey = luaT_getfieldcheckudata(
L, 1, "lastInputKey", "torch.LongTensor");
THTensor* lastInputVal = luaT_getfieldcheckudata(
L, 1, "lastInputVal", torch_Tensor);
long outDim = THTensor_(size)(weight, 0);
long inDim = THTensor_(size)(weight, 1);
luaL_argcheck(L, nn_(checkSize2D)(gradWeight, outDim, inDim), 1,
"gradWeight size wrong");
luaL_argcheck(L, nn_(checkSize1D)(bias, outDim), 1, "bias size wrong");
luaL_argcheck(L, nn_(checkSize1D)(gradBias, outDim), 1,
"gradBias size wrong");
luaL_argcheck(
L, nn_(checkKvInput)(lastInputKey, lastInputVal), 1, "input wrong");
long batchSize = THLongTensor_size(lastInputKey, 0);
long nnz = THLongTensor_size(lastInputKey, 1);
// collect unique offsets of non-0 val in input
THLongTensor* offsets = THLongTensor_newWithSize1d(batchSize * nnz);
long* offsets_p = THLongTensor_data(offsets);
long cnt = 0;
for (h = 0; h < batchSize; ++h) {
for (i = 0; i < nnz; ++i) {
real val = nn_(get2d)(lastInputVal, h, i);
if (val == 0 ) {
continue;
}
long offset = nn_(get2dL)(lastInputKey, h, i) - 1;
if (offset >= 0 && offset < inDim) {
offsets_p[cnt++] = offset;
} else {
luaL_error(
L, "index wrong. updateParameters: %d vs %d", offset + 1, inDim);
}
}
}
THLongTensor_resize1d(offsets, cnt);
THLongTensor* uniqueOffsets = THLongTensor_new();
THLongTensor* ri = THLongTensor_new();
THLongTensor_sort(uniqueOffsets, ri, offsets, 0, 0);
THLongTensor_free(ri);
THLongTensor_free(offsets);
cnt = 1;
long* uniqueOffsets_p = THLongTensor_data(uniqueOffsets);
for (i = 1; i < THLongTensor_size(uniqueOffsets, 0); ++i) {
if (uniqueOffsets_p[i] != uniqueOffsets_p[i - 1]) {
uniqueOffsets_p[cnt++] = uniqueOffsets_p[i];
}
}
THLongTensor_resize1d(uniqueOffsets, cnt);
// weight += -learningRate * gradWeight
THTensor_(cadd)(bias, bias, -learningRate, gradBias);
#pragma omp parallel for private(i) schedule(static) if (cnt * outDim > 10000)
for (i = 0; i < cnt; ++i) {
long offset = uniqueOffsets_p[i];
THBlas_(axpy)(outDim,
-learningRate,
COL_PTR2(gradWeight, offset), gradWeight->stride[0],
COL_PTR2(weight, offset), weight->stride[0]);
}
THLongTensor_free(uniqueOffsets);
return 0;
}
int nn_(SparseLinear_zeroGradParameters)(lua_State* L) {
long h, i, j;
THTensor* gradBias = luaT_getfieldcheckudata(
L, 1, "gradBias", torch_Tensor);
THTensor* gradWeight = luaT_getfieldcheckudata(
L, 1, "gradWeight", torch_Tensor);
THTensor* lastInput = luaT_getfieldcheckudata(
L, 1, "lastInput", torch_Tensor);
long outDim = THTensor_(size)(gradWeight, 0);
long inDim = THTensor_(size)(gradWeight, 1);
luaL_argcheck(
L, nn_(checkSize1D)(gradBias, outDim), 1, "gradBias size wrong");
luaL_argcheck(L, nn_(checkInput)(lastInput), 1,
"input size must be batchsize x nnz x 2");
THTensor_(zero)(gradBias);
long batchSize = THTensor_(size)(lastInput, 0);
long nnz = THTensor_(size)(lastInput, 1);
#pragma omp parallel for private(h, i, j) schedule(static) if ( \
batchSize > 1 && batchSize * nnz * outDim > 10000)
for (h = 0; h < batchSize; h++) {
for (i = 0; i < nnz; i++) {
if (nn_(get3d)(lastInput, h, i, 1) == 0 ) {
continue;
}
long offset = (long)(nn_(get3d)(lastInput, h, i, 0)) - 1;
if (offset >= 0 && offset < inDim) {
real* pGradWeight = COL_PTR2(gradWeight, offset);
if (gradWeight->stride[0] == 1) {
THVector_(fill)(pGradWeight, 0, outDim);
} else {
long stride = gradWeight->stride[0];
for (j = 0; j < outDim; ++j) {
pGradWeight[j * stride] = 0;
}
}
} else {
luaL_error(
L,
"index out of bound. zeroGradParameters: %d not between 1 and %d",
offset + 1,
inDim);
}
}
}
return 0;
}
int nn_(SparseLinear_zeroGradParameters2)(lua_State* L) {
long h, i, j;
THTensor* gradBias = luaT_getfieldcheckudata(
L, 1, "gradBias", torch_Tensor);
THTensor* gradWeight = luaT_getfieldcheckudata(
L, 1, "gradWeight", torch_Tensor);
THLongTensor* lastInputKey = luaT_getfieldcheckudata(
L, 1, "lastInputKey", "torch.LongTensor");
THTensor* lastInputVal = luaT_getfieldcheckudata(
L, 1, "lastInputVal", torch_Tensor);
long outDim = THTensor_(size)(gradWeight, 0);
long inDim = THTensor_(size)(gradWeight, 1);
luaL_argcheck(
L, nn_(checkKvInput)(lastInputKey, lastInputVal), 1, "input wrong");
luaL_argcheck(
L, nn_(checkSize1D)(gradBias, outDim), 1, "gradBias size wrong");
THTensor_(zero)(gradBias);
long batchSize = THLongTensor_size(lastInputKey, 0);
long nnz = THLongTensor_size(lastInputKey, 1);
#pragma omp parallel for private(h, i, j) schedule(static) if ( \
batchSize > 1 && batchSize * nnz * outDim > 10000)
for (h = 0; h < batchSize; ++h) {
for (i = 0; i < nnz; ++i) {
if (nn_(get2d)(lastInputVal, h, i) == 0 ) {
continue;
}
long offset = nn_(get2dL)(lastInputKey, h, i) - 1;
if (offset >= 0 && offset < inDim) {
real* pGradWeight = COL_PTR2(gradWeight, offset);
if (gradWeight->stride[0] == 1) {
THVector_(fill)(pGradWeight, 0, outDim);
} else {
long stride = gradWeight->stride[0];
for (j = 0; j < outDim; ++j) {
pGradWeight[j * stride] = 0;
}
}
} else {
luaL_error(
L, "index wrong. zeroGradParameters: %d vs %d", offset + 1, inDim);
}
}
}
return 0;
}
static int nn_(SparseLinear_updateGradInput)(lua_State* L) {
THTensor* weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor* gradInput =
luaT_getfieldcheckudata(L, 1, "gradInput", torch_Tensor);
THTensor* input = luaT_checkudata(L, 2, torch_Tensor);
THTensor* gradOutput = luaT_checkudata(L, 3, torch_Tensor);
long h, i;
long outDim = THTensor_(size)(weight, 0);
long inDim = THTensor_(size)(weight, 1);
luaL_argcheck(L, nn_(checkInput)(input), 2,
"input must be a batchsize x nnz x 2 or nnz x 2 tensor");
luaL_argcheck(L, THTensor_(isContiguous)(gradInput), 1,
"gradInput must be contiguous");
luaL_argcheck(L, THTensor_(isContiguous)(gradOutput), 1,
"gradOutput must be contiguous");
long batchSize = THTensor_(size)(input, 0);
long nnz = THTensor_(size)(input, 1);
THTensor_(resize2d)(gradOutput, batchSize, outDim);
THTensor_(resize3d)(gradInput, batchSize, nnz, 2);
#pragma omp parallel for private(h, i) schedule(static) if (\
batchSize > 1 && batchSize * nnz * outDim > 10000)
for (h = 0; h < batchSize; h++) {
for (i = 0; i < nnz; ++i) {
long offset = (long)(THTensor_(get3d)(input, h, i, 0)) - 1;
THTensor_(set3d)(gradInput, h, i, 0, offset + 1);
if (offset >= 0 && offset < inDim) {
real val = THBlas_(dot)(
outDim,
ROW_PTR2(gradOutput, h), gradOutput->stride[1],
COL_PTR2(weight, offset), weight->stride[0]);
THTensor_(set3d)(gradInput, h, i, 1, val);
} else {
luaL_error(
L,
"index out of bound. updateGradInput: %d not between 1 and %d",
offset + 1,
inDim);
}
}
}
if (batchSize == 1) {
THTensor_(resize1d)(gradOutput, outDim);
THTensor_(resize2d)(gradInput, nnz, 2);
}
return 0;
}
static const struct luaL_Reg nn_(SparseLinear__)[] = {
{"SparseLinear_updateOutput", nn_(SparseLinear_updateOutput)},
{"SparseLinear_accGradParameters", nn_(SparseLinear_accGradParameters)},
{"SparseLinear_updateParameters", nn_(SparseLinear_updateParameters)},
{"SparseLinear_zeroGradParameters", nn_(SparseLinear_zeroGradParameters)},
{"SparseLinear_updateGradInput", nn_(SparseLinear_updateGradInput)},
{"SparseLinear_updateOutput2", nn_(SparseLinear_updateOutput2)},
{"SparseLinear_accGradParameters2", nn_(SparseLinear_accGradParameters2)},
{"SparseLinear_updateParameters2", nn_(SparseLinear_updateParameters2)},
{"SparseLinear_zeroGradParameters2", nn_(SparseLinear_zeroGradParameters2)},
{NULL, NULL}};
void nn_(SparseLinear_init)(lua_State* L) {
luaT_pushmetatable(L, torch_Tensor);
luaT_registeratname(L, nn_(SparseLinear__), "nn");
lua_pop(L, 1);
}
#undef ROW_PTR2
#undef COL_PTR2
#endif
<|start_filename|>fbnn/test.lua<|end_filename|>
local ok = pcall(function() require 'fb.luaunit' end)
if not ok then
print('For running tests, please manually install fb.luaunit from fblualib.')
print('fblualib does not have rockspecs yet')
return
end
require 'nn'
local precision = 1e-5
local pl = require'pl.import_into'()
local mytester = torch.Tester()
local jac = nn.Jacobian
local fbnntest = {}
local function assertTensorEq(a, b, epsilon)
local epsilon = epsilon or 0.000001
local diff = a - b
assert(diff:abs():max() < epsilon)
end
function fbnntest.Optim_weight_bias_parameters()
local n = nn.Sequential()
n:add(nn.Linear(10, 10))
n:add(nn.Tanh())
n:add(nn.Add(10))
for i = 1, 3 do
local cur_mod = n:get(1)
local params = nn.Optim.weight_bias_parameters(cur_mod)
local has_bias = cur_mod.bias ~= nil
local has_weight = cur_mod.weight ~= nil
if not has_bias and not has_weight then
mytester:asserteq(pl.tablex.size(params), 0)
else
mytester:asserteq(pl.tablex.size(params), 2)
if has_weight then
mytester:assert(not params[1].is_bias)
mytester:asserteq(params[1][1], cur_mod.weight)
mytester:asserteq(params[1][2], cur_mod.gradWeight)
else
mytester:assert(not params[1])
end
if has_bias then
mytester:assert(params[2].is_bias)
mytester:assert(params[2][1])
mytester:assert(params[2][2])
else
mytester:assert(not params[2])
end
end
end
end
function fbnntest.CachingLookupTableCoherence()
-- Make sure that we don't lose writes even with multiple caches
-- attached
local function buildCaches(numCaches, rows, cacheRows, cols)
local lut = nn.LookupTable(rows, cols)
-- Nice, even values are easier to debug.
lut.weight = torch.range(1, rows * cols):reshape(rows, cols)
local caches = { }
for i = 1, numCaches do
table.insert(caches, nn.CachingLookupTable(lut, cacheRows, cols))
end
return lut, caches
end
local cases = {
-- rows, cols, cacheRows, numCaches, numUpdates
{ 1, 1, 1, 1, 100, },
{ 100, 10, 100, 2, 200, },
{ 500, 100, 100, 2, 500 },
{ 500, 100, 500, 2, 2000 },
}
for _,case in pairs(cases) do
print(case)
local rows, cols, cacheRows, numCaches, numUpdates = unpack(case)
local lut, caches = buildCaches(numCaches, rows, cacheRows, cols)
local lutClone = lut:clone()
for j = 1,numUpdates do
local start = math.random(rows)
local finish = math.min(start + math.random(100), rows)
local rows = torch.range(start, finish)
local n = rows:size(1)
local grad = torch.randn(n, cols)
for i =1,rows:size(1) do
lutClone.weight[rows[i]]:add(grad[i] * -#caches)
end
for _,cache in ipairs(caches) do
assert(cache.accUpdateGradParameters ==
nn.CachingLookupTable.accUpdateGradParameters)
cache:accUpdateGradParameters(rows, grad, 1.0)
end
end
for _,cache in ipairs(caches) do
cache:flush()
end
assertTensorEq(lutClone.weight, lut.weight)
end
end
function fbnntest.testLoGLayer()
-- load image:
require 'image'
local im = image.lena()
-- test forward pass in simple net:
local net = nn.Sequential()
local sigma = 1
net:add(nn.LaplacianOfGaussian(3, sigma))
local filteredIm = net:forward(im)
assert(filteredIm)
assert(im:size(1) == filteredIm:size(1))
assert(im:size(2) == filteredIm:size(2))
assert(im:size(3) == filteredIm:size(3))
end
local function criterionJacobianTest(cri, input, target)
local eps = 1e-6
local _ = cri:forward(input, target)
local dfdx = cri:backward(input, target)
-- for each input perturbation, do central difference
local centraldiff_dfdx = torch.Tensor():resizeAs(dfdx)
local input_s = input:storage()
local centraldiff_dfdx_s = centraldiff_dfdx:storage()
for i=1,input:nElement() do
-- f(xi + h)
input_s[i] = input_s[i] + eps
local fx1 = cri:forward(input, target)
-- f(xi - h)
input_s[i] = input_s[i] - 2*eps
local fx2 = cri:forward(input, target)
-- f'(xi) = (f(xi + h) - f(xi - h)) / 2h
local cdfx = (fx1 - fx2) / (2*eps)
-- store f' in appropriate place
centraldiff_dfdx_s[i] = cdfx
-- reset input[i]
input_s[i] = input_s[i] + eps
end
-- compare centraldiff_dfdx with :backward()
local err = (centraldiff_dfdx - dfdx):abs():max()
print(err)
mytester:assertlt(err, precision,
'error in difference between central difference and :backward')
end
function fbnntest.testSoftPlusLSEMinusLSECriterion()
local input = torch.rand(10, 100)
local cri = nn.SoftPlusLSEMinusLSECriterion()
criterionJacobianTest(cri, input)
end
function fbnntest.testSoftPlusLSECriterion()
local input = torch.rand(10, 100)
local cri = nn.SoftPlusLSECriterion()
criterionJacobianTest(cri, input)
end
function fbnntest.testLoGNetwork()
-- load image:
require 'image'
local im = image.lena()
local target = torch.DoubleTensor(1)
target[1] = 1
-- set up prediction network:
local net = nn.Sequential()
local sigma = 1
local layer = nn.LaplacianOfGaussian(3, sigma)
net:add(layer)
net:add(nn.View(im:nElement()))
net:add(nn.Linear(im:nElement(), 1))
net:add(nn.LogSigmoid())
local criterion = nn.BCECriterion()
-- forward backward pass:
local loss = criterion:forward(net:forward(im), target)
net:backward(im, criterion:backward(net.output, target))
assert(layer.gradInput:size(1) == im:size(1))
assert(layer.gradInput:size(2) == im:size(2))
assert(layer.gradInput:size(3) == im:size(3))
assert(loss)
end
function fbnntest.testConstantLayer()
local net = nn.Sequential()
local cst = math.random()
net:add(nn.Linear(2,3))
net:add(fbnn.Constant(cst))
local output = net:forward(torch.randn(2))
for i=1,output:size()[1] do
assert(output[i][1] == cst)
end
end
function fbnntest.testDoG()
-- load image:
require 'image'
local input = image.scale(image.lena(), 16, 16, 'bilinear')
local numChannels = input:size(1)
-- construct module:
local nOctaves = 3
local nScalesPerOctave = 4
local module = nn.DifferenceOfGaussian(
numChannels,
nOctaves,
nScalesPerOctave
)
-- test forward pass:
local output = module:forward(input)
assert(type(output) == 'table')
assert(#output == nOctaves)
for n = 1,nOctaves do
assert(output[n]:size(1) == nScalesPerOctave * numChannels)
end
-- repeat the forward tests in batch mode:
local batchSize = 8
local batchInput = input.new(
batchSize,
input:size(1),
input:size(2),
input:size(3)
)
for n = 1,batchSize do
batchInput[n]:copy(input):add(torch.randn(input:size()), 0.05)
end
output = module:forward(batchInput)
assert(type(output) == 'table')
assert(#output == nOctaves)
for n = 1,nOctaves do
assert(output[n]:size(1) == batchSize)
assert(output[n]:size(2) == nScalesPerOctave * numChannels)
end
end
function fbnntest.testUpsample()
require 'image'
local factors = torch.DoubleTensor({1, 2, 3, 4})
local im = image.scale(image.lena(), 32, 32, 'bilinear')
-- test for single image:
for n = 1,factors:nElement() do
local net = nn.Sequential()
net:add(nn.Upsample(factors[n]))
local upsampledIm = net:forward(im)
assert(upsampledIm:size(1) == im:size(1))
assert(upsampledIm:size(2) == im:size(2) * factors[n])
assert(upsampledIm:size(3) == im:size(3) * factors[n])
local recon = net:backward(im, upsampledIm):div(factors[n] * factors[n])
assert(recon:size(1) == im:size(1))
assert(recon:size(2) == im:size(2))
assert(recon:size(3) == im:size(3))
assert(recon:add(-im):abs():sum() < 1e-5)
end
-- test for image batch:
im:resize(1, im:size(1), im:size(2), im:size(3))
local batch = im:expand(8, im:size(2), im:size(3), im:size(4))
batch:add(torch.randn(batch:size()))
for n = 1,factors:nElement() do
local net = nn.Sequential()
net:add(nn.Upsample(factors[n]))
local upsampledBatch = net:forward(batch)
assert(upsampledBatch:size(1) == batch:size(1))
assert(upsampledBatch:size(2) == batch:size(2))
assert(upsampledBatch:size(3) == batch:size(3) * factors[n])
assert(upsampledBatch:size(4) == batch:size(4) * factors[n])
local recon = net:backward(batch, upsampledBatch)
recon:div(factors[n] * factors[n])
assert(recon:size(1) == batch:size(1))
assert(recon:size(2) == batch:size(2))
assert(recon:size(3) == batch:size(3))
assert(recon:size(4) == batch:size(4))
assert(recon:add(-batch):abs():sum() < 1e-5)
end
end
function fbnntest.WeightedLookupTable()
local totalIndex = math.random(6,9)
local nIndex = math.random(3,5)
local entry_size = math.random(2,5)
local indices = torch.randperm(totalIndex):narrow(1,1,nIndex)
local weights = torch.randn(nIndex)
local module = nn.WeightedLookupTable(totalIndex, entry_size)
local minval = 1
local maxval = totalIndex
local input = torch.Tensor(indices:size(1), 2)
input:select(2, 1):copy(indices)
input:select(2, 2):copy(weights)
local output = module:forward(input)
for r=1,nIndex do
for c=1,entry_size do
mytester:assertlt(math.abs(output[r][c] - module.weight[input[r][1]][c] * input[r][2]), 1e-3, 'incorrect output')
end
end
module:backwardUpdate(input, output, 0.1)
input:zero()
-- 1D
local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight, minval, maxval)
mytester:assertlt(err, 1e-4, '1D error on weight ')
local err = jac.testJacobianUpdateParameters(module, input, module.weight, minval, maxval)
mytester:assertlt(err, 1e-4, '1D error on weight [direct update] ')
module.gradWeight:zero()
for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do
mytester:assertlt(err, 1e-4, string.format(
'1D error on weight [%s]', t))
end
end
function fbnntest.IndividualDropout()
local N = 1024
local D = 5
local net = nn.Sequential()
net:add(fbnn.IndividualDropout(torch.range(0, .8, .8 / (D - 1))))
local output = net:forward(torch.ones(N, D))
assert(output)
assert(output:size(1) == N)
assert(output:size(2) == D)
end
function fbnntest.FasterLookup()
local runtest = function(type)
local totalIndex = math.random(6,9)
local nIndex = math.random(3,5)
local entry_size = math.random(2,5)
local input = torch.randperm(totalIndex):narrow(1,1,nIndex):int()
local module = nn.FasterLookup(totalIndex, entry_size)
local minval = 1
local maxval = totalIndex
module:type(type)
local output = module:forward(input)
module:backwardUpdate(input, output, 0.1)
input:zero()
-- 1D
local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight, minval, maxval)
mytester:assertlt(err,1e-5, '1D error on weight ')
local err = jac.testJacobianUpdateParameters(module, input, module.weight, minval, maxval)
mytester:assertlt(err,1e-5, '1D error on weight [direct update] ')
module.gradWeight:zero()
for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do
mytester:assertlt(err, 1e-5, string.format(
'1D error on weight [%s]', t))
end
-- 2D
local nframe = math.random(2,5)
local input = torch.IntTensor(nframe, nIndex):zero()
local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight, minval, maxval)
mytester:assertlt(err,1e-5, '2D error on weight ')
local err = jac.testJacobianUpdateParameters(module, input, module.weight, minval, maxval)
mytester:assertlt(err,1e-5, '2D error on weight [direct update] ')
module.gradWeight:zero()
for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do
mytester:assertlt(err, 1e-5, string.format(
'2D error on weight [%s]', t))
end
-- IO
local ferr,berr = jac.testIO(module,input,minval,maxval)
mytester:asserteq(ferr, 0, torch.typename(module) .. ' - i/o forward err ')
mytester:asserteq(berr, 0, torch.typename(module) .. ' - i/o backward err ')
end
runtest(torch.DoubleTensor():type())
end
mytester:add(fbnntest)
function nn.fbnntest(tests)
math.randomseed(os.time())
mytester:run(tests)
end
<|start_filename|>fbnn/SparseSum.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
local sparse = require 'sparse'
-- Sum module for sparse vectors.
local SparseSum, parent = torch.class('nn.SparseSum','nn.Module')
function SparseSum:__init()
parent.__init(self)
end
function SparseSum:updateOutput(input)
local nInputs = input:size(1)
if nInputs == 1 then
self.output = input[1]:clone()
else
self.output = sparse.sumSameSizeSupport(input)
end
return self.output
end
function SparseSum:updateGradInput(input, gradOutput)
self.gradInput:resize(input:size(1),gradOutput:size(1),2)
for i = 1,input:size(1) do
self.gradInput[i]:copy(gradOutput)
end
return self.gradInput
end
<|start_filename|>fbnn/FasterLookup.lua<|end_filename|>
local FasterLookup, parent = torch.class('nn.FasterLookup', 'nn.Module')
function FasterLookup:__init(
nIndex, dim, skipBoundChecking, scaleGradByFreq, concurrentUpdates)
parent.__init(self)
self.count = torch.IntTensor(nIndex);
self.weight = torch.Tensor(nIndex, dim)
self.gradWeight = torch.Tensor() -- do not set size yet to save mem
self.weight:normal(0, 1.0)
self.skipBoundChecking = skipBoundChecking and true or false
self.scaleGradByFreq = scaleGradByFreq and true or false
self.concUpdates = concurrentUpdates and true or false
end
function FasterLookup:type(type, tensorCache)
self.weight = nn.utils.recursiveType(self.weight, type, tensorCache)
self.gradWeight = nn.utils.recursiveType(self.gradWeight, type, tensorCache)
self.output = nn.utils.recursiveType(self.output, type, tensorCache)
end
function FasterLookup:updateOutput(input)
local updateOutput = self.weight.nn.FasterLookup_updateOutput
return updateOutput(self, input)
end
function FasterLookup:zeroGradParameters()
self.gradWeight:resizeAs(self.weight)
self.gradWeight:zero()
self.count:zero()
end
function FasterLookup:accGradParameters(input, gradOutput, scale)
local scale = scale or 1
local acc = self.weight.nn.FasterLookup_accGradParameters
acc(self, input, gradOutput, scale)
end
function FasterLookup:updateParameters(lr)
local updateParameters = self.weight.nn.FasterLookup_updateParameters
updateParameters(self, lr)
end
function FasterLookup:accUpdateGradParameters(input, gradOutput, lr)
local acc = self.weight.nn.FasterLookup_accUpdateGradParameters
acc(self, input, gradOutput, lr)
end
<|start_filename|>fbnn/Constant.lua<|end_filename|>
------------------------------------------------------------------------
--[[ Constant ]]--
-- author : <NAME>
-- Outputs a constant value given an input.
------------------------------------------------------------------------
local Constant, parent = torch.class("fbnn.Constant", "nn.Module")
function Constant:__init(value)
self.value = value
if torch.type(self.value) == 'number' then
self.value = torch.Tensor{self.value}
end
assert(torch.isTensor(self.value), "Expecting number or tensor at arg 1")
parent.__init(self)
end
function Constant:updateOutput(input)
-- "input:size(1)"" makes the assumption that you're in batch mode
local vsize = self.value:size():totable()
self.output:resize(input:size(1), table.unpack(vsize))
local value = self.value:view(1, table.unpack(vsize))
self.output:copy(value:expand(self.output:size()))
return self.output
end
function Constant:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input):zero()
return self.gradInput
end
<|start_filename|>src/Vml.h<|end_filename|>
/**
* Copyright 2014 Facebook
* @author <NAME> (<EMAIL>)
*/
#ifndef DEEPLEARNING_TORCH_VML_H_
#define DEEPLEARNING_TORCH_VML_H_
#include <mkl.h>
#include <folly/Preprocessor.h>
namespace facebook { namespace deeplearning { namespace torch { namespace vml {
#define XO(name) name
#define XI(P, name) FB_CONCATENATE(P, name)
#define DEFINE_V(T, P, ours, theirs) \
inline void XO(ours)(long n, const T* a, T* y) { \
return XI(P, theirs)(n, a, y); \
}
#define DEFINE_VV(T, P, ours, theirs) \
inline void XO(ours)(long n, const T* a, const T* b, T* y) { \
return XI(P, theirs)(n, a, b, y); \
}
#define DEFINE_VS(T, P, ours, theirs) \
inline void XO(ours)(long n, const T* a, T b, T* y) { \
return XI(P,theirs)(n, a, b, y); \
}
#define DEFINE_V2(T, P, ours, theirs) \
inline void XO(ours)(long n, const T* a, T* y, T* z) { \
return XI(P,theirs)(n, a, y, z); \
}
#define DEFINE_OPS(T, P) \
DEFINE_VV(T, P, add, Add) \
DEFINE_VV(T, P, sub, Sub) \
DEFINE_V(T, P, sqr, Sqr) \
DEFINE_VV(T, P, mul, Mul) \
DEFINE_V(T, P, abs, Abs) \
\
DEFINE_V(T, P, inv, Inv) \
DEFINE_VV(T, P, div, Div) \
DEFINE_V(T, P, sqrt, Sqrt) \
DEFINE_V(T, P, invSqrt, InvSqrt) \
DEFINE_V(T, P, pow2o3, Pow2o3) \
DEFINE_V(T, P, pow3o2, Pow3o2) \
DEFINE_VV(T, P, pow, Pow) \
DEFINE_VS(T, P, powx, Powx) \
DEFINE_VV(T, P, hypot, Hypot) \
\
DEFINE_V(T, P, exp, Exp) \
DEFINE_V(T, P, expm1, Expm1) \
DEFINE_V(T, P, ln, Ln) \
DEFINE_V(T, P, log10, Log10) \
DEFINE_V(T, P, log1p, Log1p) \
\
DEFINE_V(T, P, sin, Sin) \
DEFINE_V(T, P, cos, Cos) \
DEFINE_V2(T, P, sinCos, SinCos) \
DEFINE_V(T, P, tan, Tan) \
DEFINE_V(T, P, asin, Asin) \
DEFINE_V(T, P, acos, Acos) \
DEFINE_V(T, P, atan, Atan) \
DEFINE_VV(T, P, atan2, Atan2) \
\
DEFINE_V(T, P, sinh, Sinh) \
DEFINE_V(T, P, cosh, Cosh) \
DEFINE_V(T, P, tanh, Tanh) \
DEFINE_V(T, P, asinh, Asinh) \
DEFINE_V(T, P, acosh, Acosh) \
DEFINE_V(T, P, atanh, Atanh) \
\
DEFINE_V(T, P, erf, Erf) \
DEFINE_V(T, P, erfc, Erfc) \
DEFINE_V(T, P, cdfNorm, CdfNorm) \
DEFINE_V(T, P, erfInv, ErfInv) \
DEFINE_V(T, P, erfcInv, ErfcInv) \
DEFINE_V(T, P, cdfNormInv, CdfNormInv) \
DEFINE_V(T, P, lGamma, LGamma) \
DEFINE_V(T, P, tGamma, TGamma) \
\
DEFINE_V(T, P, floor, Floor) \
DEFINE_V(T, P, ceil, Ceil) \
DEFINE_V(T, P, trunc, Trunc) \
DEFINE_V(T, P, round, Round) \
DEFINE_V(T, P, nearbyInt, NearbyInt) \
DEFINE_V(T, P, rint, Rint) \
DEFINE_V2(T, P, modf, Modf) \
DEFINE_V(T, P, frac, Frac) \
DEFINE_OPS(float, vs)
DEFINE_OPS(double, vd)
#undef DEFINE_OPS
#undef DEFINE_V2
#undef DEFINE_VS
#undef DEFINE_VV
#undef DEFINE_V
#undef XI
#undef XO
}}}} // namespaces
#endif /* DEEPLEARNING_TORCH_VML_H_ */
<|start_filename|>fbnn/SparseConverter.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
local SparseConverter, parent = torch.class('nn.SparseConverter','nn.Module')
local sparse = require 'sparse'
--[[
Parameters:
* `fconv` - conversion to perform in fprop, either 'StoD','DtoS' or nil
* `bconv` - conversion to perform in bprop, either 'StoD','DtoS' or nil
* `dim` - number of dimensions
* `thresh` - threshold for sparsifying (0 by default)
]]
function SparseConverter:__init(fconv,bconv,dim,thresh)
parent.__init(self)
if fconv == 'DtoS' and bconv == 'DtoS'
or fconv == 'StoD' and bconv == 'StoD' then
error('incompatible transformations')
end
self.dim = dim
self.fconv = fconv
self.bconv = bconv
self.thresh = thresh or 0
end
function SparseConverter:updateOutput(input)
if self.fconv == 'StoD' then
self.output = sparse.StoD(input,self.dim)
elseif self.fconv == 'DtoS' then
self.output = sparse.DtoS(input,self.thresh)
else
self.output = input
end
return self.output
end
function SparseConverter:updateGradInput(input, gradOutput)
if self.bconv == 'StoD' then
self.gradInput = sparse.StoD(gradOutput,self.dim)
elseif self.bconv == 'DtoS' then
self.gradInput = sparse.DtoS(gradOutput,self.thresh)
else
self.gradInput = gradOutput
end
return self.gradInput
end
<|start_filename|>fbnn/IndividualDropout.lua<|end_filename|>
local async_rng = require 'fb.torch.async_rng'
-- Hack: store RNG externally so that we don't try to serialize it...
local rngs = {}
-- Weak keys, so we don't leak RNG objects if the corresponding
-- IndividualDropout objects are destroyed
setmetatable(rngs, {__mode = 'k'})
local IndividualDropout, Parent =
torch.class('fbnn.IndividualDropout', 'nn.Module')
--[[
This module implements a dropout layer with dropout level p. The level p can
either b a number (same dropout level for all units), or a Tensor with the same
width as the input (separate dropout level for every unit).
Parameter:
- `p`: the dropout probabilities (the probability that a given activation will
be dropped) in a Tensor. The number of elements in the Tensor must equal the
number of variables in a single input. Both batch mode and single-instance
mode are supported.
]]--
function IndividualDropout:__init(p)
Parent.__init(self)
if torch.lt(p, 0):sum() > 0 or torch.ge(p, 1):sum() > 0 then
error('<IndividualDropout> illegal percentage, must be 0 <= p < 1')
end
self:setp(p)
self.train = true
end
function IndividualDropout:updateOutput(input)
-- copy input and make buffers correct size:
assert(input:nDimension() == 2)
assert(input:size(2) == self.p:nElement())
self.output = self.output or input.new()
self.noise = self.noise or torch.FloatTensor()
self.noisegpu = self.noisegpu or input.new()
self.output:resizeAs(input):copy(input)
-- only apply dropout at training time:
if self.train then
-- initialize async samplers if they do not exist yet:
local rng = rngs[self]
if not rng then
rng = {}
for d = 1,self.p:nElement() do
rng[d] = async_rng.bernoulli(
'torch.FloatTensor', 10 * input:size(1), self.p[d]
)
end
rngs[self] = rng
end
-- perform sampling and copy to GPU:
self.noise:resize(input:size())
for d = 1,self.p:nElement() do
self.noise:narrow(2, d, 1):copy(rng[d]:generate(input:size(1))[1])
end
self.noisegpu:resize(self.noise:size()):copy(self.noise)
-- normalize so that we don't need to do anything at test time:
if not self.pgpu then
self.pgpu = input.new(1, self.p:nElement()):copy(self.p)
end
self.noisegpu:cdiv(self.pgpu:expandAs(self.noisegpu))
-- apply the dropout:
self.output:cmul(self.noisegpu)
end
return self.output
end
function IndividualDropout:updateGradInput(input, gradOutput)
if self.train then
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
self.gradInput:cmul(self.noisegpu)
else
error('backprop only defined while training')
end
return self.gradInput
end
function IndividualDropout:setp(p)
self.p = torch.FloatTensor(p:nElement())
self.p:copy(-p):add(1)
self.pgpu = nil -- initialized in updateOutput()
end
function IndividualDropout:type(type, tensorCache)
self.noise = nil -- make sure this is not copied to GPU
return Parent.type(self, type, tensorCache)
end
<|start_filename|>fbnn/SoftPlusLSECriterion.lua<|end_filename|>
require 'math'
require 'nn'
local SoftPlusLSECriterion, parent =
torch.class('nn.SoftPlusLSECriterion', 'nn.Criterion')
-- loss(x) = log(1 + sumExp(x))
function SoftPlusLSECriterion:__init(sizeAverage)
parent.__init(self)
if sizeAverage ~= nil then
self.sizeAverage = sizeAverage
else
self.sizeAverage = true
end
--self.beta = beta or 1
self.threshold = 20 -- avoid overflow
self.LSE = torch.Tensor()
end
local function softplus(x)
if x > 20 then
return x
else
return math.log(1 + math.exp(x))
end
end
function SoftPlusLSECriterion:updateOutput(input)
local max_val = torch.max(input, 2)
input = input - max_val:expand(input:size())
self.LSE = input:exp():sum(2):log()
self.LSE:add(max_val)
self.LSE:apply(softplus)
self.output = self.LSE:sum()
return self.output
end
function SoftPlusLSECriterion:updateGradInput(input)
self.gradInput = torch.exp(input - self.LSE:expand(input:size()))
return self.gradInput
end
<|start_filename|>fbnn/TrueNLLCriterion.lua<|end_filename|>
-- Copyright 2004-present Facebook. All Rights Reserved.
--[[
`TrueNLLCriterion` computes the negative log-loss criterion directly.
]]
local TrueNLLCriterion, parent = torch.class('nn.TrueNLLCriterion',
'nn.Criterion')
-- For numerical stability
local eps = 0.00000001
function TrueNLLCriterion:__init()
parent.__init(self)
self.sizeAverage = true
end
function TrueNLLCriterion:updateOutput(input, target)
if input:dim() == 1 then
self.output = -math.log(input[target] + eps)
elseif input:dim() == 2 then
local output = 0
for i=1,target:size(1) do
output = output - math.log(input[i][target[i]] + eps)
end
if self.sizeAverage then
output = output / target:size(1)
end
self.output = output
else
error('matrix or vector expected')
end
return self.output
end
function TrueNLLCriterion:updateGradInput(input, target)
self.gradInput:resizeAs(input)
self.gradInput:zero()
if input:dim() == 1 then
self.gradInput[target] = -1 / (input[target] + eps)
else
local z = -1
if self.sizeAverage then
z = z / target:size(1)
end
local gradInput = self.gradInput
for i=1,target:size(1) do
gradInput[i][target[i]] = z / (input[i][target[i]] + eps)
end
end
return self.gradInput
end
<|start_filename|>fbnn/LaplacianOfGaussian.lua<|end_filename|>
local LaplacianOfGaussian, parent =
torch.class('nn.LaplacianOfGaussian', 'nn.Module')
--[[
This Module implements a layer that performs a Laplacian of Gaussian filtering
of the input at a particular scale, which is defined by the filter bandwidth
sigma. The parameter sigma is defined in terms of pixels (note that this is
different from the definition of sigma in image.gaussian, where sigma is defined
relative to the size of the filter). By default, the used filter size will be
10 times sigma, rounded to the nearest odd number. Also, the input will be
padded by default such that the output size equals the input size.
Alternatively, the filter size and the padding can be specified manually.
Example usage:
> im = image.lena()
> net = nn.Sequential()
> net:add(nn.LaplacianOfGaussian(1))
> local filteredIm = net:forward(im)
]]--
-- function that generates a Laplacian of Gaussian filter:
local function getFilter(sigma, sz)
-- defaults:
local sz = sz or math.ceil(sigma * 10)
if sz % 2 == 0 then sz = sz + 1 end
-- generate Gaussian kernel:
local image = require 'image'
local ker = image.gaussian{normalize = true,
width = sz,
height = sz,
sigma = .1}
-- compute first derivatives in both directions:
local dKdY = torch.add(ker:narrow(1, 1, ker:size(1) - 1),
-ker:narrow(1, 2, ker:size(1) - 1))
local dKdX = torch.add(ker:narrow(2, 1, ker:size(2) - 1),
-ker:narrow(2, 2, ker:size(2) - 1))
-- compute second derivatives in both directions:
local dKdYY = torch.add(dKdY:narrow(1, 1, dKdY:size(1) - 1),
-dKdY:narrow(1, 2, dKdY:size(1) - 1))
local dKdXX = torch.add(dKdX:narrow(2, 1, dKdX:size(2) - 1),
-dKdX:narrow(2, 2, dKdX:size(2) - 1))
-- compute final Laplacian of Gaussian kernel:
local LoG = torch.add(dKdYY:narrow(2, 2, dKdXX:size(2)),
dKdXX:narrow(1, 2, dKdYY:size(1)))
-- return filter:
return LoG
end
-- function that initializes the layer:
-- * nInputPlane is the number of input planes
-- * sigma is the filter bandwidth in pixels
-- * k is the filter size (square filters only; default = 10 * sigma)
-- * padding is the padding (on both sides; default is half the filter size)
function LaplacianOfGaussian:__init(nInputPlane, sigma, k, padding)
local filter = getFilter(sigma, k)
self.nInputPlane = nInputPlane
self.nOutputPlane = nInputPlane
self.weight = torch.Tensor(self.nInputPlane, filter:size(1), filter:size(2))
for c = 1,self.nInputPlane do
self.weight[c]:copy(filter)
end
self.bias = self.weight.new(1):zero()
self.padding = padding or math.floor(filter:size(1) / 2)
self.kH = filter:size(1)
self.kW = filter:size(2)
self.dW = 1
self.dH = 1
self.connTable = nn.tables.oneToOne(self.nInputPlane)
self.output = torch.Tensor()
self.finput = torch.Tensor()
self.fgradInput = torch.Tensor()
self:reset()
end
function LaplacianOfGaussian:reset()
end
-- function implementing a forward pass in the layer:
function LaplacianOfGaussian:updateOutput(input)
-- assertions on input:
local dim
if input:nDimension() == 3 then dim = 1
elseif input:nDimension() == 4 then dim = 2
else error('3D or 4D(batch mode) tensor expected') end
assert(input:size(dim) == self.nInputPlane)
-- perform padding (SpatialConvolutionMap doesn't support this):
local paddedInput
local padding = self.padding
if padding > 0 then
if dim == 1 then
paddedInput = input.new(input:size(1), input:size(2) + 2 * padding,
input:size(3) + 2 * padding)
paddedInput:sub(1, self.nInputPlane,
padding + 1, padding + input:size(2),
padding + 1, padding + input:size(3)):copy(input)
else
paddedInput = input.new(input:size(1), input:size(2),
input:size(3) + 2 * padding,
input:size(4) + 2 * padding)
paddedInput:sub(1, input:size(1), 1, self.nInputPlane,
padding + 1, padding + input:size(2),
padding + 1, padding + input:size(3)):copy(input)
end
else
paddedInput = input
end
-- apply filter to each channel separately:
self.output:resizeAs(input)
input.THNN.SpatialConvolutionMap_updateOutput(
paddedInput:cdata(),
self.output:cdata(),
self.weight:cdata(),
self.bias:cdata(),
self.connTable:cdata(),
self.nInputPlane,
self.nOutputPlane,
self.dW, self.dH
)
-- return:
return self.output
end
-- function implementing a backward pass in the layer:
function LaplacianOfGaussian:updateGradInput(input, gradOutput)
self.gradInput = input.new(1)
--if self.gradInput then
-- determine which dimension contains channels:
local dim
if input:nDimension() == 3 then dim = 1
elseif input:nDimension() == 4 then dim = 2
else error('3D or 4D(batch mode) tensor expected') end
assert(input:size(dim) == self.nInputPlane)
-- perform padding (SpatialConvolutionMap doesn't support this):
local paddedInput
local padding = self.padding
if padding > 0 then
if dim == 1 then
paddedInput = input.new(input:size(1),
input:size(2) + 2 * padding,
input:size(3) + 2 * padding)
paddedInput:sub(1, self.nInputPlane,
padding + 1, padding + input:size(2),
padding + 1, padding + input:size(3)):copy(input)
else
paddedInput = input.new(input:size(1),
input:size(2),
input:size(3) + 2 * padding,
input:size(4) + 2 * padding)
paddedInput:sub(1, input:size(1), 1, self.nInputPlane,
padding + 1, padding + input:size(2),
padding + 1, padding + input:size(3)):copy(input)
end
else
paddedInput = input
end
-- perform backwards pass for each channel separately:
local gradInputBuf = gradOutput.new(paddedInput:size())
input.THNN.SpatialConvolutionMap_updateGradInput(
paddedInput:cdata(),
gradOutput:cdata(),
gradInputBuf:cdata(),
self.weight:cdata(),
self.bias:cdata(),
self.connTable:cdata(),
self.nInputPlane,
self.nOutputPlane,
self.dW, self.dH
)
-- remove padding and return:
if dim == 1 then
self.gradInput:resizeAs(input):copy(
gradInputBuf:sub(1, self.nInputPlane,
padding + 1, padding + input:size(2),
padding + 1, padding + input:size(3))
)
else
self.gradInput:resizeAs(input):copy(
gradInputBuf:sub(1, input:size(1), 1, self.nInputPlane,
padding + 1, padding + input:size(3),
padding + 1, padding + input:size(4))
)
end
--end
return self.gradInput
end
-- we do not need to compute gradients as there are no parameters:
function LaplacianOfGaussian:accUpdateGradParameters(input, gradOutput, lr)
end
-- do never update the filters:
function LaplacianOfGaussian:updateParameters(lr)
end
-- this function facilitates different behavior of buffers on CPU and GPU:
function LaplacianOfGaussian:type(type)
self.finput = torch.Tensor()
self.fgradInput = torch.Tensor()
return parent.type(self, type)
end
<|start_filename|>fbnn/L2Normalize.lua<|end_filename|>
local No, parent = torch.class('fbnn.L2Normalize', 'nn.Module')
--[[
This module normalizes it's input to unit euclidean norm
Authors: <NAME>, <NAME>
]]--
function No:__init()
parent.__init(self)
end
function No:updateOutput(input)
-- store the number of dimensions of the input
local ldim = input:nDimension()
assert(ldim <= 2,
'This module should only (realistically) '
.. 'be used for 1-D or 2-D inputs')
self.output:resizeAs(input)
self.output:copy(input)
-- compute the Euclidean norm over the last dimension of the input
self.norms = self.norms or input.new()
torch.norm(self.norms, input, 2, ldim)
-- divide the input by the Euclidean norms to produce the output
self.output:cdiv(self.norms:expand(self.output:size()))
return self.output
end
function No:updateGradInput(input,gradOutput)
self.gradInput:resizeAs(gradOutput)
self.gradInput:copy(gradOutput)
-- store the number of dimensions of the input
local ldim = input:nDimension()
local proj = self.gradInput
-- compute the negative of the dot product between the normalized input,
-- that is, self.output, and gradInput=gradOutput
local dotprod = proj:clone():cmul(self.output):sum(ldim):mul(-1)
-- orthogonalize gradInput=gradOutput to the normalized input,
-- that is, self.output
proj:add(self.output:clone():cmul(dotprod:expand(proj:size())))
-- normalize by the norms of the input
proj:cdiv(self.norms:expand(proj:size()))
return proj
end
| facebook/fbnn |
<|start_filename|>dataset/preProcess_div256.lua<|end_filename|>
----------------------------------------------------------------------
-- This script downloads and loads the (SVHN) House Numbers dataset
-- http://ufldl.stanford.edu/housenumbers/
----------------------------------------------------------------------
print '==> downloading dataset'
-- Here we download dataset files.
-- Note: files were converted from their original Matlab format
-- to Torch's internal format using the mattorch package. The
-- mattorch package allows 1-to-1 conversion between Torch and Matlab
-- files.
-- The SVHN dataset contains 3 files:
-- + train: training data
-- + test: test data
-- + extra: extra training data
tar = 'http://torch7.s3-website-us-east-1.amazonaws.com/data/svhn.t7.tgz'
if not paths.dirp('housenumbers') then
os.execute('wget ' .. tar)
os.execute('tar xvf ' .. paths.basename(tar))
end
train_file = 'housenumbers/train_32x32.t7'
test_file = 'housenumbers/test_32x32.t7'
extra_file = 'housenumbers/extra_32x32.t7'
----------------------------------------------------------------------
print '==> loading dataset'
-- We load the dataset from disk, and re-arrange it to be compatible
-- with Torch's representation. Matlab uses a column-major representation,
-- Torch is row-major, so we just have to transpose the data.
-- Note: the data, in X, is 4-d: the 1st dim indexes the samples, the 2nd
-- dim indexes the color channels (RGB), and the last two dims index the
-- height and width of the samples.
loaded = torch.load(train_file,'ascii')
trainData = {
data = loaded.X:transpose(3,4),
labels = loaded.y[1],
size = function() return trsize end
}
loaded = torch.load(extra_file,'ascii')
extraTrainData = {
data = loaded.X:transpose(3,4),
labels = loaded.y[1],
size = function() return trsize end
}
loaded = torch.load(test_file,'ascii')
testData = {
data = loaded.X:transpose(3,4),
labels = loaded.y[1],
size = function() return tesize end
}
trainData.data=trainData.data:float():div(256)
--train_mean=trainData.data:mean(1)
--train_std=trainData.data:std()
--print(train_mean)
--print('train std'..train_std)
--trainData.data:add(-train_mean:expandAs(trainData.data)):mul(1/train_std)
testData.data=testData.data:float():div(256)
--test_mean=testData.data:mean(1)
--test_std=testData.data:std()
--print(test_mean)
--print('test std'..test_std)
--testData.data:add(-test_mean:expandAs(testData.data)):mul(1/test_std)
set={}
set.trainData=trainData
set.testData=testData
torch.save('svhn_div256.dat',set)
----------------------------------------------------------------------
print '==> visualizing data'
-- Visualization is quite easy, using itorch.image().
if itorch then
print('training data:')
itorch.image(trainData.data[{ {1,256} }])
print('extra training data:')
itorch.image(extraTrainData.data[{ {1,256} }])
print('test data:')
itorch.image(testData.data[{ {1,256} }])
end
<|start_filename|>models/googlenetbn_CWN_NS.lua<|end_filename|>
-- Batch normalized googlenet
--this code is from: https://github.com/soumith/imagenet-multiGPU.torch
---- We simply replace the standard linear module by our centered linear module in this architecture
require '../module/spatial/Spatial_Scaling'
require '../module/spatial/cudnn_Spatial_Weight_CenteredBN'
local function inception(input_size, config)
local concat = nn.Concat(2)
if config[1][1] ~= 0 then
local conv1 = nn.Sequential()
conv1:add(cudnn.Spatial_Weight_CenteredBN(input_size, config[1][1],1,1,1,1)):add(nn.ReLU(true))
conv1:add(nn.SpatialBatchNormalization(config[1][1],1e-3))
conv1:add(nn.ReLU(true))
concat:add(conv1)
end
local conv3 = nn.Sequential()
conv3:add(cudnn.Spatial_Weight_CenteredBN( input_size, config[2][1],1,1,1,1)):add(nn.ReLU(true))
conv3:add(nn.SpatialBatchNormalization(config[2][1],1e-3))
conv3:add(nn.ReLU(true))
conv3:add(cudnn.Spatial_Weight_CenteredBN(config[2][1], config[2][2],3,3,1,1,1,1)):add(nn.ReLU(true))
conv3:add(nn.SpatialBatchNormalization(config[2][2],1e-3))
conv3:add(nn.ReLU(true))
concat:add(conv3)
local conv3xx = nn.Sequential()
conv3xx:add(cudnn.Spatial_Weight_CenteredBN( input_size, config[3][1],1,1,1,1)):add(nn.ReLU(true))
conv3xx:add(nn.SpatialBatchNormalization(config[3][1],1e-3))
conv3xx:add(nn.ReLU(true))
conv3xx:add(cudnn.Spatial_Weight_CenteredBN(config[3][1], config[3][2],3,3,1,1,1,1)):add(nn.ReLU(true))
conv3xx:add(nn.SpatialBatchNormalization(config[3][2],1e-3))
conv3xx:add(nn.ReLU(true))
conv3xx:add(cudnn.Spatial_Weight_CenteredBN(config[3][2], config[3][2],3,3,1,1,1,1)):add(nn.ReLU(true))
conv3xx:add(nn.SpatialBatchNormalization(config[3][2],1e-3))
conv3xx:add(nn.ReLU(true))
concat:add(conv3xx)
local pool = nn.Sequential()
--pool:add(nn.SpatialZeroPadding(1,1,1,1)) -- remove after getting nn R2 into fbcode
if config[4][1] == 'max' then
pool:add(nn.SpatialMaxPooling(3,3,1,1,1,1):ceil())
elseif config[4][1] == 'avg' then
pool:add(nn.SpatialAveragePooling(3,3,1,1,1,1):ceil())
else
error('Unknown pooling')
end
if config[4][2] ~= 0 then
pool:add(cudnn.Spatial_Weight_CenteredBN(input_size, config[4][2],1,1,1,1)):add(nn.ReLU(true))
pool:add(nn.SpatialBatchNormalization(config[4][2],1e-3))
pool:add(nn.ReLU(true))
end
concat:add(pool)
return concat
end
function createModel(opt)
local features = nn.Sequential()
-- features:add(cudnn.Spatial_Weight_CenteredBN(3,64,7,7,2,2,3,3))
-- features:add(nn.SpatialBatchNormalization(64,1e-3))
-- features:add(nn.ReLU(true))
-- features:add(nn.SpatialMaxPooling(3,3,2,2):ceil())
-- features:add(cudnn.Spatial_Weight_CenteredBN(64,64,1,1))
-- features:add(nn.SpatialBatchNormalization(64,1e-3))
-- features:add(nn.ReLU(true))
features:add(cudnn.Spatial_Weight_CenteredBN(3,64,3,3,1,1,0,0))
features:add(nn.SpatialBatchNormalization(64,1e-3))
features:add(nn.ReLU(true))
features:add(cudnn.Spatial_Weight_CenteredBN(64,192,3,3,1,1,0,0))
features:add(nn.SpatialBatchNormalization(192,1e-3))
features:add(nn.ReLU(true))
-- features:add(nn.SpatialMaxPooling(3,3,2,2):ceil())
features:add(inception( 192, {{ 64},{ 64, 64},{ 64, 96},{'avg', 32}})) -- 3(a)
features:add(inception( 256, {{ 64},{ 64, 96},{ 64, 96},{'avg', 64}})) -- 3(b)
features:add(inception( 320, {{ 0},{128,160},{ 64, 96},{'max', 0}})) -- 3(c)
features:add(cudnn.Spatial_Weight_CenteredBN(576,576,2,2,2,2))
features:add(nn.SpatialBatchNormalization(576,1e-3))
features:add(nn.ReLU(true))
features:add(inception( 576, {{224},{ 64, 96},{ 96,128},{'avg',128}})) -- 4(a)
features:add(inception( 576, {{192},{ 96,128},{ 96,128},{'avg',128}})) -- 4(b)
features:add(inception( 576, {{160},{128,160},{128,160},{'avg', 96}})) -- 4(c)
features:add(inception( 576, {{ 96},{128,192},{160,192},{'avg', 96}})) -- 4(d)
local main_branch = nn.Sequential()
main_branch:add(inception( 576, {{ 0},{128,192},{192,256},{'max', 0}})) -- 4(e)
main_branch:add(cudnn.Spatial_Weight_CenteredBN(1024,1024,2,2,2,2))
main_branch:add(nn.SpatialBatchNormalization(1024,1e-3))
main_branch:add(nn.ReLU(true))
main_branch:add(inception(1024, {{352},{192,320},{160,224},{'avg',128}})) -- 5(a)
main_branch:add(inception(1024, {{352},{192,320},{192,224},{'max',128}})) -- 5(b)
main_branch:add(nn.SpatialAveragePooling(7,7,1,1))
main_branch:add(nn.View(1024):setNumInputDims(3))
main_branch:add(nn.Linear(1024,opt.num_classes))
main_branch:add(nn.LogSoftMax())
local model = nn.Sequential():add(features):add(main_branch)
model:cuda()
model.imageSize = 256
model.imageCrop = 224
return model
end
return createModel(opt)
<|start_filename|>module/Linear_Weight_CenteredBN_Row.lua<|end_filename|>
--[[
----This file implements Centered linear module, which wraps Centered weight normalization
----into the linear module for 2D input used in MLP architecture.
----
---------------------------------------------------------------------
----Author: <NAME>
----mail: <EMAIL>
-----
----]]
--]]
local Linear_Weight_CenteredBN_Row, parent = torch.class('nn.Linear_Weight_CenteredBN_Row', 'nn.Module')
function Linear_Weight_CenteredBN_Row:__init(inputSize,outputSize, flag_adjustScale,init_flag)
parent.__init(self)
self.weight = torch.Tensor( outputSize,inputSize)
self.gradWeight = torch.Tensor(outputSize, inputSize)
if flag_adjustScale ~= nil then
self.flag_adjustScale= flag_adjustScale
else
self.flag_adjustScale= false
end
if init_flag ~= nil then
self.init_flag = init_flag
else
self.init_flag = 'RandInit'
end
self.g=torch.Tensor(outputSize):fill(1)
if self.flag_adjustScale then
self.gradG=torch.Tensor(outputSize)
self.gradBias = torch.Tensor(outputSize)
self.bias = torch.Tensor(outputSize):fill(0)
end
self:reset()
end
function Linear_Weight_CenteredBN_Row:reset(stdv)
if self.init_flag=='RandInit' then
self:reset_RandInit(stdv)
elseif self.init_flag=='OrthInit' then
self:reset_orthogonal(stdv)
end
return self
end
function Linear_Weight_CenteredBN_Row:reset_RandInit(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:size(2))
end
if nn.oldSeed then
for i=1,self.weight:size(1) do
self.weight:select(1, i):apply(function()
return torch.uniform(-stdv, stdv)
end)
-- self.bias[i] = torch.uniform(-stdv, stdv)
end
else
self.weight:uniform(-stdv, stdv)
-- self.bias:uniform(-stdv, stdv)
end
end
function Linear_Weight_CenteredBN_Row:reset_orthogonal()
local initScale = 1.1 -- math.sqrt(2)
local M1 = torch.randn(self.weight:size(1), self.weight:size(1))
local M2 = torch.randn(self.weight:size(2), self.weight:size(2))
local n_min = math.min(self.weight:size(1), self.weight:size(2))
-- QR decomposition of random matrices ~ N(0, 1)
local Q1, R1 = torch.qr(M1)
local Q2, R2 = torch.qr(M2)
self.weight:copy(Q1:narrow(2,1,n_min) * Q2:narrow(1,1,n_min)):mul(initScale)
-- self.bias:zero()
end
function Linear_Weight_CenteredBN_Row:updateOutput(input)
if input:dim() == 2 then
local nframe = input:size(1)
local nElement = self.output:nElement()
local n_output=self.weight:size(1)
local n_input=self.weight:size(2)
self.output:resize(nframe, n_output)
if self.output:nElement() ~= nElement then
self.output:zero()
end
self.addBuffer = self.addBuffer or input.new()
self.addBuffer:resize(nframe):fill(1)
self.mean=self.mean or input.new()
self.std=self.std or input.new()
self.W=self.W or input.new()
self.W_hat=self.W_hat or input.new()
self.W:resizeAs(self.weight)
self.mean:mean(self.weight, 2)
self.weight:add(-self.mean:expand(n_output,n_input))
self.std:resize(n_output,1):copy(self.weight:norm(2,2)):pow(-1)
self.W_hat:resizeAs(self.weight):copy(self.weight):cmul(self.std:expand(n_output,n_input))
self.W:copy(self.W_hat):cmul(self.g:view(n_output,1):expand(n_output,n_input))
self.output:addmm(0, self.output, 1, input, self.W:t())
if self.flag_adjustScale then
self.output:addr(1, self.addBuffer, self.bias)
end
else
error('input must be vector or matrix')
end
return self.output
end
function Linear_Weight_CenteredBN_Row:updateGradInput(input, gradOutput)
if self.gradInput then
local nElement = self.gradInput:nElement()
self.gradInput:resizeAs(input)
if self.gradInput:nElement() ~= nElement then
self.gradInput:zero()
end
if input:dim() == 2 then
self.gradInput:addmm(0, 1, gradOutput, self.W)
else
error('input must be vector or matrix')
end
return self.gradInput
end
end
function Linear_Weight_CenteredBN_Row:accGradParameters(input, gradOutput, scale)
-- if self.flag_inner_lr then
-- scale = self.scale or 1.0
-- else
scale =scale or 1.0
-- end
if input:dim() == 2 then
local n_output=self.weight:size(1)
local n_input=self.weight:size(2)
self.gradW=self.gradW or input.new()
self._scale=self._scale or input.new()
self._scale:resizeAs(self.std):copy(self.std):cmul(self.g)
self.gradW:resize(gradOutput:size(2),input:size(2))
self.gradW:mm(gradOutput:t(), input) --dL/dW
self.gradWeight:cmul(self.W_hat, self.gradW)
self.mean:sum(self.gradWeight,2)
self.gradWeight:copy(-self.W_hat):cmul(self.mean:expand(n_output,n_input))
self.mean:mean(self.gradW,2)
self.gradWeight:add(self.gradW):add(-self.mean:expand(n_output,n_input))
self.gradWeight:cmul(self._scale:expand(n_output,n_input))
--print(self.g)
--print(self.bias)
if self.flag_adjustScale then
self.gradBias:addmv(scale, gradOutput:t(), self.addBuffer)
self.W_hat:cmul(self.gradW)
self.gradG:sum(self.W_hat,2)
end
else
error('input must be vector or matrix')
end
end
function Linear_Weight_CenteredBN_Row:parameters()
if self.flag_adjustScale then
return {self.weight, self.g, self.bias}, {self.gradWeight, self.gradG, self.gradBias}
else
return {self.weight}, {self.gradWeight}
end
end
-- we do not need to accumulate parameters when sharing
Linear_Weight_CenteredBN_Row.sharedAccUpdateGradParameters = Linear_Weight_CenteredBN_Row.accUpdateGradParameters
function Linear_Weight_CenteredBN_Row:__tostring__()
return torch.type(self) ..
string.format('(%d -> %d)', self.weight:size(2), self.weight:size(1))
end
<|start_filename|>models/MLP/model_WN.lua<|end_filename|>
require 'nn'
--require 'module/BatchLinear_FIM'
require 'module/NormLinear_new'
require 'module/Affine_module'
--require 'module/Linear_ForDebug'
require 'module/Linear_Weight_BN_Row'
require 'module/Linear_Weight_CenteredBN_Row'
function create_model(opt)
------------------------------------------------------------------------------
------------------------------------------------------------------------------
local model=nn.Sequential()
--local cfg_hidden=torch.Tensor({128,128,128,128,128})
-- config_table={}
-- for i=1, opt.layer do
-- table.insert(config_table, opt.n_hidden_number)
-- end
-- local cfg_hidden=torch.Tensor(config_table)
local cfg_hidden=torch.Tensor({opt.n_hidden_number,opt.n_hidden_number,opt.n_hidden_number,opt.n_hidden_number,opt.n_hidden_number})
local n=cfg_hidden:size(1)
local nonlinear
if opt.mode_nonlinear==0 then --sigmod
nonlinear=nn.Sigmoid
elseif opt.mode_nonlinear==1 then --tanh
nonlinear=nn.Tanh
elseif opt.mode_nonlinear==2 then --ReLU
nonlinear=nn.ReLU
elseif opt.mode_nonlinear==3 then --ReLU
nonlinear=nn.ELU
end
local linear=nn.Linear
local module_BN=nn.BatchNormalization
local module_nnn=nn.NormLinear_new
local module_affine=nn.Affine_module
local function block_sgd(n_input, n_output)
local s=nn.Sequential()
s:add(nonlinear())
s:add(linear(n_input,n_output))
return s
end
local function block_batch(n_input, n_output)
local s=nn.Sequential()
s:add(module_BN(n_input))
s:add(nonlinear())
s:add(linear(n_input,n_output))
return s
end
local function block_batch_var(n_input, n_output)
local s=nn.Sequential()
s:add(nonlinear())
s:add(module_BN(n_input))
s:add(linear(n_input,n_output))
return s
end
local function block_nnn(n_input, n_output)
local s=nn.Sequential()
s:add(nonlinear())
s:add(module_nnn(n_input,n_output))
return s
end
local function block_nnn_batch(n_input, n_output)
local s=nn.Sequential()
s:add(module_BN(n_input))
s:add(nonlinear())
s:add(module_nnn(n_input,n_output))
return s
end
--------------------------------------------------Weight Normalizaiton realted--------------------------
local function block_WN_Row(n_input, n_output)
local s=nn.Sequential()
s:add(nonlinear())
s:add(nn.Linear_Weight_BN_Row(n_input, n_output))
-- s:add(module_affine(n_output,1,true))
return s
end
local function block_WN_Row_scale(n_input, n_output)
local s=nn.Sequential()
s:add(nonlinear())
s:add(nn.Linear_Weight_BN_Row(n_input, n_output))
s:add(module_affine(n_output,1,true))
return s
end
local function block_WCBN_Row(n_input, n_output)
local s=nn.Sequential()
s:add(nonlinear())
s:add(nn.Linear_Weight_CenteredBN_Row(n_input, n_output))
return s
end
local function block_WCBN_Row_scale(n_input, n_output)
local s=nn.Sequential()
s:add(nonlinear())
s:add(nn.Linear_Weight_CenteredBN_Row(n_input, n_output))
s:add(module_affine(n_output,1,true))
return s
end
local function block_WN_Row_batch(n_input, n_output)
local s=nn.Sequential()
s:add(module_BN(n_input))
s:add(nonlinear())
s:add(nn.Linear_Weight_BN_Row(n_input,n_output))
return s
end
local function block_WN_Row_scale_batch(n_input, n_output)
local s=nn.Sequential()
s:add(module_BN(n_input))
s:add(nonlinear())
s:add(nn.Linear_Weight_BN_Row(n_input,n_output))
s:add(module_affine(n_output,1,true))
return s
end
---------------------WCBN---------------------
local function block_WCBN_Row_batch(n_input, n_output)
local s=nn.Sequential()
s:add(module_BN(n_input))
s:add(nonlinear())
s:add(nn.Linear_Weight_CenteredBN_Row(n_input, n_output))
return s
end
local function block_WCBN_Row_scale_batch(n_input, n_output)
local s=nn.Sequential()
s:add(module_BN(n_input))
s:add(nonlinear())
s:add(nn.Linear_Weight_CenteredBN_Row(n_input, n_output))
s:add(module_affine(n_output,1,true))
return s
end
-----------------------------------------model configure-------------------
if opt.model=='sgd' then
model:add(linear(opt.n_inputs,cfg_hidden[1]))
for i=1,n do
if i==n then
model:add(block_sgd(cfg_hidden[i],opt.n_outputs))
else
model:add(block_sgd(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='batch' then
model:add(linear(opt.n_inputs,cfg_hidden[1]))
for i=1,n do
if i==n then
model:add(block_batch(cfg_hidden[i],opt.n_outputs))
else
model:add(block_batch(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='batch_var' then
model:add(linear(opt.n_inputs,cfg_hidden[1]))
for i=1,n do
if i==n then
model:add(block_batch_var(cfg_hidden[i],opt.n_outputs))
else
model:add(block_batch_var(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='nnn' then
model:add(linear(opt.n_inputs,cfg_hidden[1]))
for i=1,n do
if i==n then
model:add(block_nnn(cfg_hidden[i],opt.n_outputs))
else
model:add(block_nnn(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='nnn_batch' then
model:add(linear(opt.n_inputs,cfg_hidden[1]))
for i=1,n do
if i==n then
model:add(block_nnn_batch(cfg_hidden[i],opt.n_outputs))
else
model:add(block_nnn_batch(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='WN_Row' then
model:add(nn.Linear_Weight_BN_Row(opt.n_inputs,cfg_hidden[1]))
-- model:add(module_affine(cfg_hidden[1],1,true))
for i=1,n do
if i==n then
model:add(block_WN_Row(cfg_hidden[i],opt.n_outputs))
--model:add(block_sgd(cfg_hidden[i],opt.n_outputs))--the last module don't use weightNormalization
else
model:add(block_WN_Row(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='WN_Row_scale' then
model:add(nn.Linear_Weight_BN_Row(opt.n_inputs,cfg_hidden[1]))
model:add(module_affine(cfg_hidden[1],1,true))
for i=1,n do
if i==n then
model:add(block_WN_Row_scale(cfg_hidden[i],opt.n_outputs))
--model:add(block_sgd(cfg_hidden[i],opt.n_outputs))--the last module don't use weightNormalization
else
model:add(block_WN_Row_scale(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='CWN_Row' then
model:add(nn.Linear_Weight_CenteredBN_Row(opt.n_inputs,cfg_hidden[1]))
-- model:add(module_affine(cfg_hidden[1],1,true))
for i=1,n do
if i==n then
model:add(block_WCBN_Row(cfg_hidden[i],opt.n_outputs))
--model:add(block_sgd(cfg_hidden[i],opt.n_outputs))
else
model:add(block_WCBN_Row(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='CWN_Row_scale' then
model:add(nn.Linear_Weight_CenteredBN_Row(opt.n_inputs,cfg_hidden[1]))
model:add(module_affine(cfg_hidden[1],1,true))
for i=1,n do
if i==n then
model:add(block_WCBN_Row_scale(cfg_hidden[i],opt.n_outputs))
--model:add(block_sgd(cfg_hidden[i],opt.n_outputs))
else
model:add(block_WCBN_Row_scale(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='WN_Row_batch' then
model:add(nn.Linear_Weight_BN_Row(opt.n_inputs,cfg_hidden[1]))
-- model:add(module_affine(cfg_hidden[1],1,true))
for i=1,n do
if i==n then
model:add(block_WN_Row_batch(cfg_hidden[i],opt.n_outputs))
else
model:add(block_WN_Row_batch(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='WN_Row_scale_batch' then
model:add(nn.Linear_Weight_BN_Row(opt.n_inputs,cfg_hidden[1]))
model:add(module_affine(cfg_hidden[1],1,true))
for i=1,n do
if i==n then
model:add(block_WN_Row_scale_batch(cfg_hidden[i],opt.n_outputs))
else
model:add(block_WN_Row_scale_batch(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='CWN_Row_batch' then
model:add(nn.Linear_Weight_CenteredBN_Row(opt.n_inputs,cfg_hidden[1]))
-- model:add(module_affine(cfg_hidden[1],1,true))
for i=1,n do
if i==n then
model:add(block_WCBN_Row_batch(cfg_hidden[i],opt.n_outputs))
else
model:add(block_WCBN_Row_batch(cfg_hidden[i],cfg_hidden[i+1]))
end
end
elseif opt.model=='CWN_Row_scale_batch' then
model:add(nn.Linear_Weight_CenteredBN_Row(opt.n_inputs,cfg_hidden[1]))
model:add(module_affine(cfg_hidden[1],1,true))
for i=1,n do
if i==n then
model:add(block_WCBN_Row_scale_batch(cfg_hidden[i],opt.n_outputs))
else
model:add(block_WCBN_Row_scale_batch(cfg_hidden[i],cfg_hidden[i+1]))
end
end
end
model:add(nn.LogSoftMax())
------------------------------------------------------------------------------
-- LOSS FUNCTION
------------------------------------------------------------------------------
local criterion = nn.ClassNLLCriterion()
return model, criterion
end
<|start_filename|>module/BatchLinear_FIM.lua<|end_filename|>
--[[
This paper is from the offcial implementation on torch
This file implements Batch Normalization as described in the paper:
"Batch Normalization: Accelerating Deep Network Training
by Reducing Internal Covariate Shift"
by <NAME>, <NAME>
This implementation is useful for inputs NOT coming from convolution layers.
For Convolution layers, see SpatialBatchNormalization.lua
The operation implemented is:
y = ( x - mean(x) )
-------------------- * gamma + beta
standard-deviation(x)
where gamma and beta are learnable parameters.
The learning of gamma and beta is optional.
Usage:
with learnable parameters: nn.BatchNormalization(N [, eps] [,momentum])
where N = dimensionality of input
without learnable parameters: nn.BatchNormalization(0 [, eps] [,momentum])
eps is a small value added to the standard-deviation to avoid divide-by-zero.
Defaults to 1e-5
In training time, this layer keeps a running estimate of it's computed mean and std.
The running sum is kept with a default momentup of 0.1 (unless over-ridden)
In test time, this running mean/std is used to normalize.
]]--
local BatchLinear_FIM,parent = torch.class('nn.BatchLinear_FIM', 'nn.Module')
function BatchLinear_FIM:__init(nOutput, affine, eps, momentum)
parent.__init(self)
assert(nOutput and type(nOutput) == 'number',
'Missing argument #1: dimensionality of input. ')
assert(nOutput ~= 0, 'To set affine=false call BatchNormalization'
.. '(nOutput, eps, momentum, false) ')
if affine ~= nil then
assert(type(affine) == 'boolean', 'affine has to be true/false')
self.affine = affine
else
self.affine = false
end
self.eps = eps or 1e-5
self.train = true
self.momentum = momentum or 0.1
self.running_mean = torch.zeros(nOutput)
self.running_std = torch.ones(nOutput)
if self.affine then
self.weight = torch.Tensor(nOutput)
self.bias = torch.Tensor(nOutput)
self.gradWeight = torch.Tensor(nOutput)
self.gradBias = torch.Tensor(nOutput)
self:reset()
end
self.isCalculateFIM=true
--for debug
self.debug=false
self.debug_detailInfo=false
self.printInterval=1
self.count=0
end
function BatchLinear_FIM:reset()
self.weight:uniform()
-- self.weight:fill(1)
self.bias:zero()
self.running_mean:zero()
self.running_std:fill(1)
end
function BatchLinear_FIM:updateOutput(input)
assert(input:dim() == 2, 'only mini-batch supported (2D tensor), got '
.. input:dim() .. 'D tensor instead')
local nBatch = input:size(1)
-- buffers that are reused
self.buffer = self.buffer or input.new()
self.buffer2 = self.buffer2 or input.new()
self.centered = self.centered or input.new()
self.centered:resizeAs(input)
self.std = self.std or input.new()
self.normalized = self.normalized or input.new()
self.normalized:resizeAs(input)
self.output:resizeAs(input)
self.gradInput:resizeAs(input)
if self.train == false then
if self.debug then
print('--------------------------batch:test mode-------------------')
end
self.output:copy(input)
self.buffer:repeatTensor(self.running_mean, nBatch, 1)
self.output:add(-1, self.buffer)
self.buffer:repeatTensor(self.running_std, nBatch, 1)
-- print(self.running_std:clone():pow(-1):mean())
self.output:cmul(self.buffer)
else -- training mode
-- calculate mean over mini-batch
if self.debug then
print('--------------------------batch:train mode-------------------')
end
self.buffer:mean(input, 1) -- E(x) = expectation of x.
self.running_mean:mul(1 - self.momentum):add(self.momentum, self.buffer) -- add to running mean
self.buffer:repeatTensor(self.buffer, nBatch, 1)
-- subtract mean
self.centered:add(input, -1, self.buffer) -- x - E(x)
-- calculate standard deviation over mini-batch
self.buffer:copy(self.centered):cmul(self.buffer) -- [x - E(x)]^2
-- 1 / E([x - E(x)]^2)
self.std:mean(self.buffer, 1):add(self.eps):sqrt():pow(-1)
self.running_std:mul(1 - self.momentum):add(self.momentum, self.std) -- add to running stdv
self.buffer:repeatTensor(self.std, nBatch, 1)
if self.debug and (self.count % self.printInterval==0) then
print('--------the scale value-------------')
print(self.std)
end
-- divide standard-deviation + eps
self.output:cmul(self.centered, self.buffer)
self.normalized:copy(self.output)
end
if self.affine then
-- multiply with gamma and add beta
self.buffer:repeatTensor(self.weight, nBatch, 1)
self.output:cmul(self.buffer)
self.buffer:repeatTensor(self.bias, nBatch, 1)
self.output:add(self.buffer)
end
if self.debug then
self.buffer:resize(self.output:size(2),self.output:size(2))
self.buffer:addmm(0,self.buffer,1/input:size(1),self.output:t(),self.output) ---the validate matrix
-- print("------debug_batch_module:diagonal of validate matrix------")
-- print(self.buffer)
local rotation,eig,_=torch.svd(self.buffer)
print("-------debug_eig of the correlate matrix r.w.t nomalized activation-----")
print(eig)
print("-------debug_dignoal of the correlate matrix r.w.t nomalized activation-----")
for i=1,self.buffer:size(1) do
print(i..': '..self.buffer[i][i])
end
end
if self.debug_detailInfo and (self.count % self.printInterval==0)then
local input_mean=input:mean(1)
local input_normPerDim=torch.norm(input,1,1)/input:size(1)
local output_mean=self.output:mean(1)
local output_normPerDim=torch.norm(self.output,1,1)/self.output:size(1)
print('debug_batchModule--input_mean:')
print(input_mean)
print('debug_batchModule--input_normPerDim:')
print(input_normPerDim)
print('debug_batchModule--output_mean:')
print(output_mean)
print('debug_batchModule--output_normPerDim:')
print(output_normPerDim)
end
-- print('-----------BN:output:--------')
-- print(self.output)
return self.output
end
function BatchLinear_FIM:updateGradInput(input, gradOutput)
assert(input:dim() == 2, 'only mini-batch supported')
assert(gradOutput:dim() == 2, 'only mini-batch supported')
-- assert(self.train == true, 'should be in training mode when self.train is true')
local nBatch = input:size(1)
if self.train==false then
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
self.buffer:repeatTensor(self.running_std, nBatch, 1)
self.gradInput:cmul(self.buffer)
else
self.gradInput:cmul(self.centered, gradOutput)
self.buffer:mean(self.gradInput, 1)
self.gradInput:repeatTensor(self.buffer, nBatch, 1)
self.gradInput:cmul(self.centered):mul(-1)
self.buffer:repeatTensor(self.std, nBatch, 1)
self.gradInput:cmul(self.buffer):cmul(self.buffer)
self.buffer:mean(gradOutput, 1)
self.buffer:repeatTensor(self.buffer, nBatch, 1)
self.gradInput:add(gradOutput):add(-1, self.buffer)
if self.debug_detailInfo then
print('-----------------hidden gradInput:-----------')
print(self.gradInput[{{1,20},{}}])
end
self.buffer:repeatTensor(self.std, nBatch, 1)
self.gradInput:cmul(self.buffer)
end
if self.affine then
self.buffer:repeatTensor(self.weight, nBatch, 1)
self.gradInput:cmul(self.buffer)
end
-------------debug information------------
if self.debug_detailInfo and (self.count % self.printInterval==0)then
local gradOutput_norm=torch.norm(gradOutput,1)
local gradInput_norm=torch.norm(self.gradInput,1)
print('debug_batchModule--gradOutput_norm_elementWise:'..gradOutput_norm..' --gradInput_norm_elementWise:'..gradInput_norm)
end
if self.debug_detailInfo and (self.count % self.printInterval==0)then
local gradInput_mean=self.gradInput:mean(1)
local gradInput_normPerDim=torch.norm(self.gradInput,1,1)/self.gradInput:size(1)
local gradOutput_mean=gradOutput:mean(1)
local gradOutput_normPerDim=torch.norm(gradOutput,1,1)/gradOutput:size(1)
print('debug_batchModule--gradInput_mean:')
print(gradInput_mean)
print('debug_batchModule--gradInput_normPerDim:')
print(gradInput_normPerDim)
print('debug_batchModule--gradOutput_mean:')
print(gradOutput_mean)
print('debug_batchModule--gradOutput_normPerDim:')
print(gradOutput_normPerDim)
-- print('-------------gradOuput----------')
-- print(gradOutput)
-- print('--------------gradInput-------')
-- print(self.gradInput)
end
if self.debug_detailInfo then
print('-----------------gradInput:-----------')
print(self.gradInput[{{1,20},{}}])
end
self.count=self.count+1 --the ending of all the operation in this module
-- print('-----------BN:gradInput-------------')
-- print(self.gradInput)
return self.gradInput
end
function BatchLinear_FIM:setTrainMode(isTrain)
if isTrain ~= nil then
assert(type(isTrain) == 'boolean', 'isTrain has to be true/false')
self.train = isTrain
else
self.train=true
end
end
function BatchLinear_FIM:accGradParameters(input, gradOutput, scale)
if self.affine then
scale = scale or 1.0
self.buffer2:resizeAs(self.normalized):copy(self.normalized)
self.buffer2:cmul(gradOutput)
self.buffer:sum(self.buffer2, 1) -- sum over mini-batch
self.gradWeight:add(scale, self.buffer)
self.buffer:sum(gradOutput, 1) -- sum over mini-batch
self.gradBias:add(scale, self.buffer)
end
end
<|start_filename|>module/NormLinear_new.lua<|end_filename|>
--[[
----This file implements natural neural network based on the paper:https://arxiv.org/abs/1507.00210
----
--Only for 2D input used in MLP architecture.
----
---------------------------------------------------------------------
----Author: <NAME>
----mail: <EMAIL>
-----
----]]
--]]
local NormLinear_new, parent = torch.class('nn.NormLinear_new', 'nn.Module')
function NormLinear_new:__init(inputSize, outputSize,affine)
parent.__init(self)
self.weight = torch.Tensor(outputSize, inputSize)
self.bias = torch.Tensor(outputSize)
self.gradWeight = torch.Tensor(outputSize, inputSize)
self.gradBias = torch.Tensor(outputSize)
self.proMatrix=torch.eye(inputSize)
self.mean=torch.Tensor(inputSize)
self.mean:fill(0)
self.isDeleteActivation=true -- is used for decide whether deleting the activaion:self.D per updation for projection matrix
-- self.D=torch.Tensor() -- store the output in the layer for estimating the mean and variance, It should be a 2 dim Tensor
if affine ~= nil then
assert(type(affine) == 'boolean', 'affine has to be true/false')
self.affine = affine
else
self.affine = false
end
--------------------------------------------------------
---plan 1: the method of affine transform is followed by Batch Normalization, where:
-- a_hat=V*U*(h-c)+d, the affine do like this a=weight_affine * a_hat + b_affine, we see this
-- as a independent module, and when updat U, we don't consider this module to make sure a^old=a^new,
-- rather making sure a_hat^old=a_hat^new.
-- -----------------------------------------------------
self.debug=false -- whether use debug mode..
self.useSVD=true -- whether use SVD do get the eigenValue, generally speaking, SVD is more stable and efficient
self.useCenteredEstimation=true -- whether use centered data to estimate the correlation matrix sigma, generally, not use centered is more stable
self.FIM=torch.Tensor()
self.conditionNumber={}
self.epcilo=10^-100
self.updateFIM_flag=false
self.printInterval=50
self.count=0
self:reset()
end
function NormLinear_new:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:size(2))
end
if nn.oldSeed then
for i=1,self.weight:size(1) do
self.weight:select(1, i):apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias[i] = torch.uniform(-stdv, stdv)
end
else
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
return self
end
function NormLinear_new:updateOutput(input)
assert(input:dim() == 2, 'only mini-batch supported (2D tensor), got '
.. input:dim() .. 'D tensor instead')
local nframe = input:size(1)
local nElement = self.output:nElement()
self.output:resize(nframe, self.bias:size(1))
if self.output:nElement() ~= nElement then
self.output:zero()
end
--buffers that are reused
self.addBuffer = self.addBuffer or input.new() -- used for plus the bias, have the size of input(1)
if self.addBuffer:nElement() ~= nframe then
self.addBuffer:resize(nframe):fill(1)
end
self.input=self.input or input.new() --used to store the input for calulate the Correlation matrix
self.buffer=self.buffer or input.new()
self.W = self.W or input.new()
self.W:resizeAs(self.weight)
self.buffer_1=self.buffer_1 or input.new()
self.buffer_1:resizeAs(input)
self.input:resizeAs(input):copy(input)
--------------------------------run mode for efficiency----------------------
------------------y=(x-E(x))*U^T * V^T+d_i
self.buffer:repeatTensor(self.mean,nframe,1) --buffer has the same dimensions as input
self.buffer_1:add(input,-1,self.buffer) --subtract mean: x-E(x), sotre in buffer_1
self.W:mm(self.weight,self.proMatrix) --V*U
self.output:addmm(0, self.output, 1, self.buffer_1, self.W:t())--(x-E(x))*U^T * V^T
self.output:addr(1, self.addBuffer, self.bias)
------------------------------------------------
----if scale the dimension
-- ----------------------------------------------
return self.output
end
function NormLinear_new:updateGradInput(input, gradOutput)
-- print('------------updateGradInput--------------')
if self.gradInput then
local nElement = self.gradInput:nElement()
self.gradInput:resizeAs(input)
if self.gradInput:nElement() ~= nElement then
self.gradInput:zero()
end
self.W:mm(self.weight,self.proMatrix)
------------------------------------
if self.affine then
self.buffer:repeatTensor(self.weight_affine, self.W:size(2), 1)
self.W:cmul(self.buffer:t())
end
self.gradInput:addmm(0, 1, gradOutput, self.W)
end
--------------------------------------------------
--calculate the FIM----------
--------------------------------------------------
if self.updateFIM_flag then
print('--------calculate condition number----------------')
local batchNumber=input:size(1)
self.buffer_FIM=self.buffer_FIM or input.new()
self.buffer=self.buffer or input.new()
self.normalizedInput=self.normalizedInput or input.new()
self.buffer:repeatTensor(self.mean,input:size(1),1) --buffer has the same dimensions as input
self.buffer_FIM:add(input,-1,self.buffer)
self.normalizedInput:resizeAs(self.buffer_FIM)
self.normalizedInput:mm(self.buffer_FIM,self.proMatrix:t())
local eleNumber=gradOutput:size(2)*self.normalizedInput:size(2)
self.FIM=torch.Tensor(eleNumber,eleNumber):zero()
self.buffer_FIM:resize(gradOutput:size(2),self.normalizedInput:size(2))
for i=1,batchNumber do
self.buffer_FIM:mm(gradOutput[{{i},{}}]:t(),self.normalizedInput[{{i},{}}])
self.buffer=torch.reshape(self.buffer_FIM,eleNumber,1)
self.FIM:addmm(self.buffer,self.buffer:t())
end
self.FIM:mul(1/batchNumber)
---calculate condition number----------------------
_,self.buffer_FIM,_=torch.svd(self.FIM) --SVD Decompositon for singular value
self.buffer_FIM:add(self.epcilo)
local conditionNumber=torch.abs(torch.max(self.buffer_FIM)/torch.min(self.buffer_FIM))
print('Normlinear module: conditionNumber='..conditionNumber)
self.conditionNumber[#self.conditionNumber + 1]=conditionNumber
if self.debug then
print('eignValue: \n')
print(self.buffer_FIM)
end
end
return self.gradInput
end
function NormLinear_new:accGradParameters(input, gradOutput, scale)
scale = scale or 1
-- print('------------accGradParameters--------------')
assert(input:dim() == 2, 'only mini-batch supported (2D tensor), got '
.. input:dim() .. 'D tensor instead')
self.buffer:repeatTensor(self.mean,input:size(1),1) --buffer has the same dimensions as input
self.buffer_1:add(input,-1,self.buffer) --subtract mean: x-E(x)
self.buffer:mm(self.buffer_1,self.proMatrix:t())
self.gradWeight:addmm(scale, gradOutput:t(), self.buffer)
self.gradBias:addmv(scale, gradOutput:t(), self.addBuffer)
end
function NormLinear_new:updatePromatrix(epsilo)
-- if self.debug then
print('------------update Norm--------------')
-- end
self.buffer_sigma=self.buffer_sigma or self.input.new()
self.centered_input=self.centered_input or self.input.new()
self.b=self.b or self.input.new()
self.b:resizeAs( self.bias)
self.b:zero()
self.W:mm(self.weight, self.proMatrix)
self.b:addmv(1,self.bias,-1,self.W,self.mean)
local nBatch=self.input:size()[1]
self.mean=torch.mean(self.input,1)[1]
--------begin centering the self.input------
self.buffer_1:repeatTensor(self.mean,nBatch,1)
self.centered_input:add(self.input,-1,self.buffer_1)
--------------------end: centering the input--------
self.buffer_sigma:resize(self.input:size(2),self.input:size(2)) --buffer_sigma is used for store the sigma
self.buffer_sigma:addmm(0,self.buffer_sigma,1/nBatch,self.centered_input:t(),self.centered_input)
self.buffer_sigma:add(epsilo,torch.eye(self.buffer_sigma:size(1)))
-----------------------matrix decomposition-------------
if self.useSVD then
self.buffer_1,self.buffer,_=torch.svd(self.buffer_sigma) --reuse the buffer: 'buffer' record e, 'buffer_1' record V
if self.debug then
print('----debug_NormLinear_newModeul:--eigenValue_SVD decomposition------')
print(self.buffer)
end
self.buffer:pow(-1/2)
self.buffer_sigma:diag(self.buffer) --self.buffer_sigma cache the scale matrix
else
self.buffer,self.buffer_1=torch.eig(self.buffer_sigma,'V') --reuse the buffer: 'buffer' record e, 'buffer_1' record V
if self.debug then
print('----debug_NormLinear_newModeul:--eigenValue------')
print(self.buffer:select(2,1))
end
self.buffer=self.buffer:select(2,1) -- the first colum is the real eign value
self.buffer:pow(-1/2)
self.buffer_sigma:diag(self.buffer) --self.buffer_sigma cache the scale matrix
end
self.proMatrix:mm(self.buffer_sigma,self.buffer_1:t())
--update the model parameters
------------ self.weight=self.W*torch.inverse(self.proMatrix)
--print(self.weight)
self.weight:mm(self.W,torch.inverse(self.proMatrix))
----------self.bias=self.b+torch.mv(self.W,self.mean)
self.bias:addmv(1,self.b,1,self.W,self.mean)
if self.debug then
self.buffer:resizeAs(self.centered_input)
self.buffer:mm(self.centered_input,self.proMatrix:t())--record the normalized input
self.buffer_1:resize(self.buffer:size(2),self.buffer:size(2))
self.buffer_1:addmm(0,self.buffer_1,1/Ns,self.buffer:t(),self.buffer) ---the validate matrix
local W_norm=torch.norm(self.W)
print('debug_NormLinear_newModeul:--W_norm:'..W_norm)
print("------debug_NormLinear_newModeul:--diagonal of validate matri------")
for i=1,self.buffer_1:size(1) do
print(i..': '..self.buffer_1[i][i])
end
end
end
-- we do not need to accumulate parameters when sharing
NormLinear_new.sharedAccUpdateGradParameters = NormLinear_new.accUpdateGradParameters
function NormLinear_new:update_FIM_flag(flag)
self.updateFIM_flag=flag or false
end
function NormLinear_new:__tostring__()
return torch.type(self) ..
string.format('(%d -> %d)', self.weight:size(2), self.weight:size(1))
end
<|start_filename|>models/vggA_CWN.lua<|end_filename|>
require 'nn'
require 'cunn'
require 'cudnn'
require '../module/spatial/cudnn_Spatial_Weight_CenteredBN'
require '../module/spatial/Spatial_Scaling'
local backend_name = 'cudnn'
local backend
if backend_name == 'cudnn' then
require 'cudnn'
backend = cudnn
else
backend = nn
end
local vgg = nn.Sequential()
-- building block
local function ConvBNReLU(nInputPlane, nOutputPlane)
vgg:add(cudnn.Spatial_Weight_CenteredBN(nInputPlane, nOutputPlane, 3,3, 1,1, 1,1):noBias())
--vgg:add(nn.Spatial_Scaling(nOutputPlane,_,_,nInputPlane))
vgg:add(nn.Spatial_Scaling(nOutputPlane,opt.BNScale,true))
vgg:add(backend.ReLU(true))
return vgg
end
-- Will use "ceil" MaxPooling because we want to save as much
-- space as we can
local MaxPooling = backend.SpatialMaxPooling
local n=opt.base_hidden
ConvBNReLU(3,n)
vgg:add(MaxPooling(2,2,2,2))
ConvBNReLU(n,n*2)
vgg:add(MaxPooling(2,2,2,2))
ConvBNReLU(n*2,n*4)
ConvBNReLU(n*4,n*4)
vgg:add(MaxPooling(2,2,2,2))
ConvBNReLU(n*4,n*8)
ConvBNReLU(n*8,n*8)
vgg:add(MaxPooling(2,2,2,2))
-- In the last block of convolutions the inputs are smaller than
-- the kernels and cudnn doesn't handle that, have to use cunn
backend = nn
ConvBNReLU(n*8,n*8)
ConvBNReLU(n*8,n*8)
vgg:add(MaxPooling(2,2,2,2))
vgg:add(nn.View(n*8))
classifier = nn.Sequential()
--classifier:add(nn.Dropout(0.5))
classifier:add(nn.Linear(n*8,n*8))
classifier:add(nn.BatchNormalization(n*8))
classifier:add(nn.ReLU(true))
--classifier:add(nn.Dropout(0.5))
classifier:add(nn.Linear(n*8,10))
vgg:add(classifier)
-- initialization from MSR
local function MSRinit(net)
local function init(name)
for k,v in pairs(net:findModules(name)) do
local n = v.kW*v.kH*v.nOutputPlane
v.weight:normal(0,math.sqrt(2/n))
v.bias:zero()
end
end
-- have to do for both backends
init'cudnn.SpatialConvolution'
init'nn.SpatialConvolution'
end
MSRinit(vgg)
-- check that we can propagate forward without errors
-- should get 16x10 tensor
--print(#vgg:cuda():forward(torch.CudaTensor(16,3,32,32)))
return vgg
| huangleiBuaa/CenteredWN |
<|start_filename|>src/styles/styles.module.css<|end_filename|>
.carousel-base {
width: 100%;
box-sizing: border-box;
display: flex;
outline: none;
}
.item-provider {
overflow: hidden;
width: 100%;
cursor: pointer;
}
.item-container img {
user-select: none;
-webkit-user-drag: none;
}
.item-tracker {
height: 100%;
display: flex;
}
.carousel-arrow {
z-index: 1;
}
| draszek/react-carousel |
<|start_filename|>src/6455.fs<|end_filename|>
namespace N2O
open System
open System.IO
open System.Text
open System.Security.Cryptography
// RFC 6455 WebSocket handshake
[<AutoOpen>]
module RFC6455 =
type WebsocketFrame =
| ContinuationFrame //%x0
| TextFrame //%x1
| BinaryFrame //%x2
| ReservedNonControl //%x3-7
| ConnectionClosed //%x8
| Ping //%x9
| Pong //%xA
| ReservedControl //%xB-F
let isWebSocketsUpgrade (req : Req) =
req.headers.["upgrade"].ToLower() = "websocket"
let getLines (bytes : Byte []) len =
if len > 8 then
bytes.[..(len)]
|> UTF8Encoding.UTF8.GetString
|> fun hs -> hs.Split([| "\r\n" |], StringSplitOptions.RemoveEmptyEntries)
else
[||]
let acceptString6455 acceptCode =
"HTTP/1.1 101 Switching Protocols\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
"Sec-WebSocket-Accept: " + acceptCode + "\r\n\r\n"
let handshake (req : Req) =
req.headers.["sec-websocket-key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|> Encoding.ASCII.GetBytes
|> SHA1CryptoServiceProvider.Create().ComputeHash
|> Convert.ToBase64String
|> acceptString6455
|> Encoding.ASCII.GetBytes
let swapEndian (bs : byte array) = if BitConverter.IsLittleEndian then Array.rev bs else bs
let decodeFrame (stream : Stream) =
async {
let! firstByte_t = stream.AsyncRead(1)
let firstByte = firstByte_t.[0]
let final = firstByte &&& 128uy <> 0uy
let opcode =
match firstByte &&& 15uy with
| 0uy -> ContinuationFrame
| 1uy -> TextFrame
| 2uy -> BinaryFrame
| 3uy | 4uy | 5uy | 6uy | 7uy -> ReservedNonControl
| 8uy -> ConnectionClosed
| 9uy -> Ping
| 10uy -> Pong
| 11uy | 12uy | 13uy | 14uy | 15uy -> ReservedControl
| _ -> failwith "given the mask above this cannot happen"
let! secondByte_t = stream.AsyncRead(1)
let secondByte = secondByte_t.[0]
let mask = secondByte &&& 128uy <> 0uy
let! payloadLength =
match secondByte &&& 127uy with
| 127uy ->
async {
let! int64Bytes = stream.AsyncRead(8)
return BitConverter.ToUInt64(int64Bytes |> swapEndian, 0)
}
| 126uy ->
async {
let! int16Bytes = stream.AsyncRead(2)
return uint64 (BitConverter.ToUInt16(int16Bytes |> swapEndian, 0))
}
| x -> async { return uint64 (Convert.ToUInt16(x)) }
let payloadLength' = int32 payloadLength
let! data =
if mask
then
async {
let! mask = stream.AsyncRead(4)
let! data = stream.AsyncRead(payloadLength')
return data |> Array.mapi (fun i b -> b ^^^ mask.[i % 4])
}
else
stream.AsyncRead(payloadLength')
return (opcode, data, final)
}
let encodeFrame (opcode : WebsocketFrame, data : byte array, final : bool, mask : uint32 option) =
let firstByte =
match opcode with
| ContinuationFrame -> 0uy
| TextFrame -> 1uy
| BinaryFrame -> 2uy
| ReservedNonControl -> failwith "Use of reserved unsuported opcode \"ReservedNonControl\""
| ConnectionClosed -> 8uy
| Ping -> 9uy
| Pong -> 10uy
| ReservedControl -> failwith "Use of reserved unsuported opcode \"ReservedControl\""
|> fun x -> if final then x ||| 128uy else x
let length = data |> Array.length // NOTE Length cannot be > int32 but can be > int16
let lengthBytes =
if length < 126 then [Convert.ToByte(length)]
else if length < int32 UInt16.MaxValue then 126uy :: (BitConverter.GetBytes(length) |> swapEndian |> Seq.skip 2 |> Seq.toList)
else 127uy :: ([0uy;0uy;0uy;0uy] @ ((BitConverter.GetBytes(length) |> swapEndian |> Seq.toList)))
|> function
| (x::xs) as ys -> if mask.IsSome then (x ||| 128uy) :: xs else ys // Set the mask bit if one is available
| _ -> failwith "Should not happen - should have at least one byte in the list"
let maskedData =
match mask with
| None -> data
| Some(m) ->
let maskBits = BitConverter.GetBytes(m) |> swapEndian
Array.append maskBits (data |> Array.mapi (fun i b -> b ^^^ maskBits.[i % 4]))
Array.append (firstByte :: lengthBytes |> List.toArray) maskedData
<|start_filename|>src/server.fs<|end_filename|>
namespace N2O
open System
open System.IO
open System.Net
open System.Net.Sockets
open System.Text
open System.Threading
// The 7 processes of pure MailboxProcessor-based WebSocket Server
[<AutoOpen>]
module Server =
let mutable interval = 5000 // ticker interval
let mutable ticker = true // enable server-initiated Tick messages
let mutable proto : Req -> Msg -> Msg = fun _ _ -> Nope // choose protocol by Req
let sendBytes (ns: NetworkStream) bytes =
ns.AsyncWrite (encodeFrame (BinaryFrame, bytes, true, None))
let sendMsg ns (msg: Msg) = async {
match msg with
| Text text -> do! sendBytes ns (Encoding.UTF8.GetBytes text)
| Bin arr -> do! sendBytes ns arr
| Nope -> ()
}
let telemetry (ns: NetworkStream) (inbox: MailboxProcessor<Msg>)
(ct: CancellationToken) (sup: MailboxProcessor<Sup>) =
async {
try
while not ct.IsCancellationRequested do
let! _ = inbox.Receive()
do! sendMsg ns (Text "TICK")
finally
sup.Post(Disconnect <| inbox)
ns.Close () |> ignore
}
let looper (ns: NetworkStream) (req: Req) (bufferSize: int)
(ct: CancellationToken) (sup: MailboxProcessor<Sup>) =
async {
try
while not ct.IsCancellationRequested do
match! decodeFrame(ns) with
| (TextFrame, recv, true) ->
do! proto req (Text (Encoding.UTF8.GetString recv))
|> sendMsg ns
| (BinaryFrame, recv, true) ->
do! proto req (Bin recv)
|> sendMsg ns
| _ -> ()
finally
sup.Post(Close ns)
ns.Close() |> ignore
}
let startClient (tcp: TcpClient) (sup: MailboxProcessor<Sup>) (ct: CancellationToken) =
MailboxProcessor.Start(
(fun (inbox: MailboxProcessor<Msg>) ->
async {
let ns = tcp.GetStream()
let size = tcp.ReceiveBufferSize
let bytes = Array.create size (byte 0)
let! len = ns.ReadAsync(bytes, 0, bytes.Length) |> Async.AwaitTask
let cts = new CancellationTokenSource ()
ct.Register (fun () -> cts.Cancel ()) |> ignore
let token = cts.Token
try
let req = request <| getLines bytes len
if isWebSocketsUpgrade req then
do! ns.AsyncWrite <| handshake req
sup.Post(Connect(inbox, ns))
if ticker then Async.Start(telemetry ns inbox token sup, token)
return! looper ns req size token sup
else ()
finally
cts.Cancel ()
tcp.Close ()
}),
cancellationToken = ct
)
let heartbeat (interval: int) (ct: CancellationToken) (sup: MailboxProcessor<Sup>) =
async {
while not ct.IsCancellationRequested do
do! Async.Sleep interval
sup.Post(Tick)
}
let listen (listener: TcpListener) (ct: CancellationToken) (sup: MailboxProcessor<Sup>) =
async {
while not ct.IsCancellationRequested do
let! client = listener.AcceptTcpClientAsync() |> Async.AwaitTask
client.NoDelay <- true
startClient client sup ct |> ignore
}
let startSupervisor (ct: CancellationToken) =
MailboxProcessor.Start(
(fun (inbox: MailboxProcessor<Sup>) ->
let listeners = ResizeArray<_>()
async {
printfn "Веб-сокет сервер ДП «IНФОТЕХ» для .NET Framework 4.6.2"
while not ct.IsCancellationRequested do
match! inbox.Receive() with
| Close ws -> ()
| Connect (l, ns) -> listeners.Add(l)
| Disconnect l -> listeners.Remove(l) |> ignore
| Tick -> listeners.ForEach(fun l -> l.Post Nope)
}),
cancellationToken = ct
)
let start (addr: string) (port: int) =
let cts = new CancellationTokenSource()
let token = cts.Token
let sup = startSupervisor token
let listener = TcpListener(IPAddress.Parse(addr), port)
// starters
try listener.Start(10) with | err -> printfn "%s" err.Message ; Environment.Exit(0)
Async.Start(listen listener token sup, token)
if ticker then Async.Start(heartbeat interval token sup, token)
{ new IDisposable with member x.Dispose() = cts.Cancel() }
| erpuno/ws |
<|start_filename|>user-auth-service/Dockerfile<|end_filename|>
FROM registry.access.redhat.com/ubi8-minimal
LABEL org.opencontainers.image.source="https://github.com/drogue-iot/drogue-cloud"
ADD target/release/drogue-cloud-user-auth-service /
ENTRYPOINT [ "/drogue-cloud-user-auth-service" ]
<|start_filename|>test-cert-generator/Dockerfile<|end_filename|>
FROM registry.access.redhat.com/ubi8-minimal
LABEL org.opencontainers.image.source="https://github.com/drogue-iot/drogue-cloud"
VOLUME /etc/drogue-certs
RUN microdnf install -y make openssl
RUN mkdir -p /usr/src
ADD test-cert-generator/scripts/ /usr/src/
WORKDIR /usr/src
ENV \
EGEN=/etc/drogue-certs
ENTRYPOINT [ "make" ]
<|start_filename|>device-management-service/Makefile<|end_filename|>
CURRENT_DIR:=$(strip $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))))
TOP_DIR := $(CURRENT_DIR)/..
include ../Makefile
BASE=tests/certs
.PHONY: clean-certs
CA_FILES=$(BASE)/ca-cert.pem $(BASE)/ca-key.pem $(BASE)/root-cert.pem $(BASE)/root-key.pem $(BASE)/ca-cert.srl
clean-certs:
rm -f $(CA_FILES) $(BASE)/*.pem $(BASE)/*.req $(BASE)/*.crt
rm -f $(BASE)/device.*
create-certs: $(CA_FILES)
create-certs: $(BASE)/trusted-certs.pem
create-certs: $(BASE)/device.1.key $(BASE)/device.1.crt $(BASE)/device.1.fullchain.crt
create-certs: $(BASE)/device.1.pem
$(BASE)/trusted-certs.pem: $(BASE)/ca-cert.pem $(BASE)/root-cert.pem
cat $^ > $@
$(CA_FILES):
openssl req -x509 -config "$(BASE)/ca.cnf" -nodes -newkey rsa:4096 -keyout "$(BASE)/root-key.pem" -out "$(BASE)/root-cert.pem" -days 3650 -subj "/O=Drogue IoT/OU=Cloud/CN=Application 1"
openssl req -config "$(BASE)/ca.cnf" -reqexts intermediate_ext -nodes -newkey rsa:4096 -keyout "$(BASE)/ca-key.pem" -days 3650 -subj "/O=Drogue IoT/OU=Cloud/CN=Application 1" | \
openssl x509 -req -extfile "$(BASE)/ca.cnf" -extensions intermediate_ext -out "$(BASE)/ca-cert.pem" -days 3650 -CA "$(BASE)/root-cert.pem" -CAkey "$(BASE)/root-key.pem" -CAcreateserial
$(BASE)/device.%.key $(BASE)/device.%.req: $(BASE)/ca.cnf
openssl req -config "$(BASE)/ca.cnf" -nodes -newkey rsa:4096 -keyout "$(BASE)/device.$*.key" -days 3650 -subj "/O=Drogue IoT/OU=Cloud/CN=Device $*" > $(BASE)/device.$*.req
$(BASE)/device.%.crt $(BASE)/%.pem: $(BASE)/device.%.key $(BASE)/device.%.req $(BASE)/ca.cnf
cat $(BASE)/device.$*.req | openssl x509 -req -extfile "$(BASE)/ca.cnf" -extensions "san_ext" -out "$(BASE)/device.$*.crt" -days 3650 -CA "$(BASE)/ca-cert.pem" -CAkey "$(BASE)/ca-key.pem" -CAcreateserial
$(BASE)/device.%.fullchain.crt: $(BASE)/device.%.crt $(BASE)/ca-cert.pem
cat $^ > $@
$(BASE)/device.%.pem: $(BASE)/device.%.crt $(BASE)/device.%.key
cat $^ > $@
<|start_filename|>outbox-controller/Dockerfile<|end_filename|>
FROM registry.access.redhat.com/ubi8-minimal
LABEL org.opencontainers.image.source="https://github.com/drogue-iot/drogue-cloud"
ADD target/release/drogue-cloud-outbox-controller /
ENTRYPOINT [ "/drogue-cloud-outbox-controller" ]
<|start_filename|>console-frontend/api.js<|end_filename|>
import SwaggerUI from 'swagger-ui'
import 'swagger-ui/dist/swagger-ui.css';
const ui = SwaggerUI({
configUrl: "/endpoints/ui-config.json",
dom_id: '#ui'
})
ui.initOAuth({
clientId: "drogue",
scopes: "openid",
additionalQueryStringParams: {nonce: "1"}
})
<|start_filename|>websocket-integration/Makefile<|end_filename|>
CURRENT_DIR:=$(strip $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))))
TOP_DIR := $(CURRENT_DIR)/..
include ../Makefile
| pranav-bhatt/drogue-cloud |
<|start_filename|>examples/from_rdf.go<|end_filename|>
// +build ignore
// Copyright 2015-2017 Piprate Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"github.com/piprate/json-gold/ld"
)
func main() {
proc := ld.NewJsonLdProcessor()
options := ld.NewJsonLdOptions("")
triples := `
<http://example.com/Subj1> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://example.com/Type> .
<http://example.com/Subj1> <http://example.com/prop1> <http://example.com/Obj1> .
<http://example.com/Subj1> <http://example.com/prop2> "Plain" .
<http://example.com/Subj1> <http://example.com/prop2> "2012-05-12"^^<http://www.w3.org/2001/XMLSchema#date> .
<http://example.com/Subj1> <http://example.com/prop2> "English"@en .
`
doc, err := proc.FromRDF(triples, options)
if err != nil {
panic(err)
}
ld.PrintDocument("JSON-LD output", doc)
}
<|start_filename|>examples/frame.go<|end_filename|>
// +build ignore
// Copyright 2015-2017 Piprate Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"github.com/piprate/json-gold/ld"
)
func main() {
proc := ld.NewJsonLdProcessor()
options := ld.NewJsonLdOptions("")
doc := map[string]interface{}{
"@context": map[string]interface{}{
"dc": "http://purl.org/dc/elements/1.1/",
"ex": "http://example.org/vocab#",
"ex:contains": map[string]interface{}{"@type": "@id"},
},
"@graph": []interface{}{
map[string]interface{}{
"@id": "http://example.org/test/#library",
"@type": "ex:Library",
"ex:contains": "http://example.org/test#book",
},
map[string]interface{}{
"@id": "http://example.org/test#book",
"@type": "ex:Book",
"dc:contributor": "Writer",
"dc:title": "My Book",
"ex:contains": "http://example.org/test#chapter",
},
map[string]interface{}{
"@id": "http://example.org/test#chapter",
"@type": "ex:Chapter",
"dc:description": "Fun",
"dc:title": "Chapter One",
},
},
}
frame := map[string]interface{}{
"@context": map[string]interface{}{
"dc": "http://purl.org/dc/elements/1.1/",
"ex": "http://example.org/vocab#",
},
"@type": "ex:Library",
"ex:contains": map[string]interface{}{
"@type": "ex:Book",
"ex:contains": map[string]interface{}{
"@type": "ex:Chapter",
},
},
}
framedDoc, err := proc.Frame(doc, frame, options)
if err != nil {
panic(err)
}
ld.PrintDocument("JSON-LD framing succeeded", framedDoc)
}
<|start_filename|>ld/api_frame.go<|end_filename|>
// Copyright 2015-2017 Piprate Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ld
import (
"fmt"
"strings"
)
// EmbedNode represents embed meta info
type EmbedNode struct {
parent interface{}
property string
}
type StackNode struct {
subject map[string]interface{}
graph string
}
// FramingContext stores framing state
type FramingContext struct {
embed Embed
explicit bool
requireAll bool
omitDefault bool
uniqueEmbeds map[string]map[string]*EmbedNode
graphMap map[string]interface{}
subjects map[string]interface{}
graph string
graphStack []string // TODO: is this field needed?
subjectStack []*StackNode
bnodeMap map[string]interface{}
}
// NewFramingContext creates and returns as new framing context.
func NewFramingContext(opts *JsonLdOptions) *FramingContext {
context := &FramingContext{
embed: EmbedLast,
explicit: false,
requireAll: false,
omitDefault: false,
uniqueEmbeds: make(map[string]map[string]*EmbedNode),
graphMap: map[string]interface{}{
"@default": make(map[string]interface{}),
},
graph: "@default",
graphStack: make([]string, 0),
subjectStack: make([]*StackNode, 0),
bnodeMap: make(map[string]interface{}),
}
if opts != nil {
context.embed = opts.Embed
context.explicit = opts.Explicit
context.requireAll = opts.RequireAll
context.omitDefault = opts.OmitDefault
}
return context
}
// Frame performs JSON-LD framing as defined in:
//
// http://json-ld.org/spec/latest/json-ld-framing/
//
// Frames the given input using the frame according to the steps in the Framing Algorithm.
// The input is used to build the framed output and is returned if there are no errors.
//
// Returns the framed output.
func (api *JsonLdApi) Frame(input interface{}, frame []interface{}, opts *JsonLdOptions, merged bool) ([]interface{}, []string, error) {
// create framing state
state := NewFramingContext(opts)
// produce a map of all graphs and name each bnode
issuer := NewIdentifierIssuer("_:b")
if _, err := api.GenerateNodeMap(input, state.graphMap, "@default", issuer, "", "", nil); err != nil {
return nil, nil, err
}
if merged {
state.graphMap["@merged"] = api.mergeNodeMapGraphs(state.graphMap)
state.graph = "@merged"
}
state.subjects = state.graphMap[state.graph].(map[string]interface{})
// validate the frame
if err := validateFrame(frame); err != nil {
return nil, nil, err
}
// 1.
// If frame is an array, set frame to the first member of the array.
var frameParam map[string]interface{}
if len(frame) > 0 {
frameParam = frame[0].(map[string]interface{})
} else {
frameParam = make(map[string]interface{})
}
framed := make([]interface{}, 0)
framedVal, err := api.matchFrame(state, GetOrderedKeys(state.subjects), frameParam, framed, "")
if err != nil {
return nil, nil, err
}
bnodesToClear := make([]string, 0)
for id, val := range state.bnodeMap {
if valArray, isArray := val.([]interface{}); isArray && len(valArray) == 1 {
bnodesToClear = append(bnodesToClear, id)
}
}
return framedVal.([]interface{}), bnodesToClear, nil
}
func createsCircularReference(id string, graph string, state *FramingContext) bool {
for i := len(state.subjectStack) - 1; i >= 0; i-- {
subject := state.subjectStack[i]
if subject.graph == graph && subject.subject["@id"] == id {
return true
}
}
return false
}
func (api *JsonLdApi) mergeNodeMapGraphs(graphs map[string]interface{}) map[string]interface{} {
merged := make(map[string]interface{})
for _, name := range GetOrderedKeys(graphs) {
graph := graphs[name].(map[string]interface{})
for _, id := range GetOrderedKeys(graph) {
var mergedNode map[string]interface{}
mv, hasID := merged[id]
if !hasID {
mergedNode = map[string]interface{}{
"@id": id,
}
merged[id] = mergedNode
} else {
mergedNode = mv.(map[string]interface{})
}
node := graph[id].(map[string]interface{})
for _, property := range GetOrderedKeys(node) {
if IsKeyword(property) {
// copy keywords
mergedNode[property] = CloneDocument(node[property])
} else {
// merge objects
for _, v := range node[property].([]interface{}) {
AddValue(mergedNode, property, CloneDocument(v), true, false, false, false)
}
}
}
}
}
return merged
}
// matchFrame frames subjects according to the given frame.
//
// state: the current framing state
// nodes:
// frame: the frame
// parent: the parent subject or top-level array
// property: the parent property, initialized to ""
func (api *JsonLdApi) matchFrame(state *FramingContext, subjects []string,
frame map[string]interface{}, parent interface{}, property string) (interface{}, error) {
// https://json-ld.org/spec/latest/json-ld-framing/#framing-algorithm
// 2.
// Initialize flags embed, explicit, and requireAll from object embed flag,
// explicit inclusion flag, and require all flag in state overriding from
// any property values for @embed, @explicit, and @requireAll in frame.
// TODO: handle @requireAll
embed, err := getFrameEmbed(frame, state.embed)
if err != nil {
return nil, err
}
explicitOn := GetFrameFlag(frame, "@explicit", state.explicit)
requireAll := GetFrameFlag(frame, "@requireAll", state.requireAll)
flags := map[string]interface{}{
"@explicit": []interface{}{explicitOn},
"@requireAll": []interface{}{requireAll},
"@embed": []interface{}{embed},
}
// 3.
// Create a list of matched subjects by filtering subjects against frame
// using the Frame Matching algorithm with state, subjects, frame, and requireAll.
matches, err := FilterSubjects(state, subjects, frame, requireAll)
if err != nil {
return nil, err
}
// 5.
// For each id and associated node object node from the set of matched subjects, ordered by id:
for _, id := range GetOrderedKeys(matches) {
// Note: In order to treat each top-level match as a
// compartmentalized result, clear the unique embedded subjects map
// when the property is None, which only occurs at the top-level.
if property == "" {
state.uniqueEmbeds = map[string]map[string]*EmbedNode{
state.graph: make(map[string]*EmbedNode),
}
} else if _, found := state.uniqueEmbeds[state.graph]; !found {
state.uniqueEmbeds[state.graph] = make(map[string]*EmbedNode)
}
// Initialize output to a new dictionary with @id and id
output := make(map[string]interface{})
output["@id"] = id
// keep track of objects having blank nodes
if strings.HasPrefix(id, "_:") {
AddValue(state.bnodeMap, id, output, true, false, true, false)
}
// 5.3
// Otherwise, if embed is @never or if a circular reference would be created by an embed,
// add output to parent and do not perform additional processing for this node.
if embed == EmbedNever || createsCircularReference(id, state.graph, state) {
parent = addFrameOutput(parent, property, output)
continue
}
// 5.4
// Otherwise, if embed is @last, remove any existing embedded node from parent associated
// with graph name in state. Requires sorting of subjects.
if embed == EmbedLast {
if _, containsId := state.uniqueEmbeds[state.graph][id]; containsId {
removeEmbed(state, id)
}
state.uniqueEmbeds[state.graph][id] = &EmbedNode{
parent: parent,
property: property,
}
}
subject := matches[id].(map[string]interface{})
state.subjectStack = append(state.subjectStack, &StackNode{
subject: subject,
graph: state.graph,
})
// subject is also the name of a graph
if _, isAlsoGraph := state.graphMap[id]; isAlsoGraph {
recurse := false
var subframe map[string]interface{}
if _, hasGraph := frame["@graph"]; !hasGraph {
recurse = state.graph != "@merged"
subframe = make(map[string]interface{})
} else {
if v, isMap := frame["@graph"].([]interface{})[0].(map[string]interface{}); isMap {
subframe = v
} else {
subframe = make(map[string]interface{})
}
recurse = !(id == "@merged" || id == "@default")
}
if recurse {
state.graphStack = append(state.graphStack, state.graph)
state.graph = id
// recurse into graph
subjects := GetOrderedKeys(state.graphMap[state.graph].(map[string]interface{}))
if _, err = api.matchFrame(state, subjects, subframe, output, "@graph"); err != nil {
return nil, err
}
// reset to current graph
state.graph = state.graphStack[len(state.graphStack)-1]
state.graphStack = state.graphStack[:len(state.graphStack)-1]
}
}
// iterate over subject properties in order
for _, prop := range GetOrderedKeys(subject) {
// if property is a keyword, add property and objects to output.
if IsKeyword(prop) {
output[prop] = CloneDocument(subject[prop])
if prop == "@type" {
// count bnode values of @type
for _, t := range subject[prop].([]interface{}) {
if strings.HasPrefix(t.(string), "_:") {
AddValue(state.bnodeMap, t.(string), output, true, false, true, false)
}
}
}
continue
}
// explicit is on and property isn't in frame, skip processing
framePropVal, containsProp := frame[prop]
if explicitOn && !containsProp {
continue
}
// add objects
// 5.5.2.3 For each item in objects:
for _, item := range subject[prop].([]interface{}) {
itemMap, isMap := item.(map[string]interface{})
listValue, hasList := itemMap["@list"]
if isMap && hasList {
// add empty list
list := map[string]interface{}{
"@list": make([]interface{}, 0),
}
addFrameOutput(output, prop, list)
// add list objects
for _, listitem := range listValue.([]interface{}) {
if IsSubjectReference(listitem) {
// recurse into subject reference
itemid := listitem.(map[string]interface{})["@id"].(string)
var subframe map[string]interface{}
if containsProp && IsList(framePropVal.([]interface{})[0]) {
subframe = framePropVal.([]interface{})[0].(map[string]interface{})["@list"].([]interface{})[0].(map[string]interface{})
} else {
subframe = flags
}
res, err := api.matchFrame(state, []string{itemid}, subframe, list, "@list")
if err != nil {
return nil, err
}
list = res.(map[string]interface{})
} else {
// include other values automatically (TODO:
// may need Clone(n)
addFrameOutput(list, "@list", listitem)
}
}
} else {
var subframe map[string]interface{}
if containsProp {
subframe = framePropVal.([]interface{})[0].(map[string]interface{})
} else {
subframe = flags
}
if IsSubjectReference(item) { // recurse into subject reference
itemid := itemMap["@id"].(string)
if _, err = api.matchFrame(state, []string{itemid}, subframe, output, prop); err != nil {
return nil, err
}
} else if valueMatch(subframe, itemMap) {
addFrameOutput(output, prop, CloneDocument(item))
}
}
}
}
// handle defaults
for _, prop := range GetOrderedKeys(frame) {
// skip keywords
if IsKeyword(prop) {
continue
}
// if omit default is off, then include default values for
// properties that appear in the next frame but are not in
// the matching subject
var next map[string]interface{}
if pf, found := frame[prop].([]interface{}); found && len(pf) > 0 {
next = pf[0].(map[string]interface{})
} else {
next = make(map[string]interface{})
}
omitDefaultOn := GetFrameFlag(next, "@omitDefault", state.omitDefault)
if _, hasProp := output[prop]; !omitDefaultOn && !hasProp {
var preserve interface{} = "@null"
if defaultVal, hasDefault := next["@default"]; hasDefault {
preserve = CloneDocument(defaultVal)
}
preserve = Arrayify(preserve)
output[prop] = []interface{}{
map[string]interface{}{
"@preserve": preserve,
},
}
}
}
// embed reverse values by finding nodes having this subject as a
// value of the associated property
if reverse, hasReverse := frame["@reverse"]; hasReverse {
for _, reverseProp := range GetOrderedKeys(reverse.(map[string]interface{})) {
for subject, subjectValue := range state.subjects {
nodeValues := Arrayify(subjectValue.(map[string]interface{})[reverseProp])
for _, v := range nodeValues {
if v != nil && v.(map[string]interface{})["@id"] == id {
// node has property referencing this subject, recurse
outputReverse, hasReverse := output["@reverse"]
if !hasReverse {
outputReverse = make(map[string]interface{})
output["@reverse"] = outputReverse
}
AddValue(output["@reverse"], reverseProp, []interface{}{}, true,
false, true, false)
var subframe map[string]interface{}
sf := reverse.(map[string]interface{})[reverseProp]
if sfArray, isArray := sf.([]interface{}); isArray {
subframe = sfArray[0].(map[string]interface{})
} else {
subframe = sf.(map[string]interface{})
}
res, err := api.matchFrame(state, []string{subject}, subframe, outputReverse.(map[string]interface{})[reverseProp], property)
if err != nil {
return nil, err
}
outputReverse.(map[string]interface{})[reverseProp] = res
break
}
}
}
}
}
// add output to parent
parent = addFrameOutput(parent, property, output)
// pop matching subject from circular ref-checking stack
state.subjectStack = state.subjectStack[:len(state.subjectStack)-1]
}
return parent, nil
}
// validateFrame validates a JSON-LD frame, returning an error if the frame is invalid.
func validateFrame(frame interface{}) error {
valid := true
if frameList, isList := frame.([]interface{}); isList {
if len(frameList) > 1 {
valid = false
} else if len(frameList) == 1 {
frame = frameList[0]
if _, isMap := frame.(map[string]interface{}); !isMap {
valid = false
}
} else {
// TODO: other JSON-LD implementations don't cater for this case (frame==[]). Investigate.
return nil
}
} else if _, isMap := frame.(map[string]interface{}); !isMap {
valid = false
}
if !valid {
return NewJsonLdError(InvalidFrame, "Invalid JSON-LD syntax; a JSON-LD frame must be a single object")
}
frameMap := frame.(map[string]interface{})
if id, hasID := frameMap["@id"]; hasID {
for _, idVal := range Arrayify(id) {
if _, isMap := idVal.(map[string]interface{}); isMap {
continue
}
if strings.HasPrefix(idVal.(string), "_:") {
return NewJsonLdError(InvalidFrame,
fmt.Sprintf("Invalid JSON-LD frame syntax; invalid value of @id: %v", id))
}
}
}
if t, hasType := frameMap["@type"]; hasType {
for _, typeVal := range Arrayify(t) {
if _, isMap := typeVal.(map[string]interface{}); isMap {
continue
}
if strings.HasPrefix(typeVal.(string), "_:") {
return NewJsonLdError(InvalidFrame,
fmt.Sprintf("Invalid JSON-LD frame syntax; invalid value of @type: %v", t))
}
}
}
return nil
}
func getFrameValue(frame map[string]interface{}, name string) interface{} {
value := frame[name]
if valueList, isList := value.([]interface{}); isList {
if len(valueList) > 0 {
value = valueList[0]
}
} else if valueMap, isMap := value.(map[string]interface{}); isMap {
if v, containsValue := valueMap["@value"]; containsValue {
value = v
}
}
return value
}
// GetFrameFlag gets the frame flag value for the given flag name.
// If boolean value is not found, returns theDefault
func GetFrameFlag(frame map[string]interface{}, name string, theDefault bool) bool {
value := frame[name]
switch v := value.(type) {
case []interface{}:
if len(v) > 0 {
value = v[0]
}
case map[string]interface{}:
if valueVal, present := v["@value"]; present {
value = valueVal
}
case bool:
return v
}
if valueBool, isBool := value.(bool); isBool {
return valueBool
} else if value == "true" {
return true
} else if value == "false" {
return false
}
return theDefault
}
func getFrameEmbed(frame map[string]interface{}, theDefault Embed) (Embed, error) {
value := getFrameValue(frame, "@embed")
if value == nil {
return theDefault, nil
}
if boolVal, isBoolean := value.(bool); isBoolean {
if boolVal {
return EmbedLast, nil
} else {
return EmbedNever, nil
}
}
if embedVal, isEmbed := value.(Embed); isEmbed {
return embedVal, nil
}
if stringVal, isString := value.(string); isString {
switch stringVal {
case "@always":
return EmbedAlways, nil
case "@never":
return EmbedNever, nil
case "@last":
return EmbedLast, nil
default:
return EmbedLast, NewJsonLdError(InvalidEmbedValue,
fmt.Sprintf("Invalid JSON-LD frame syntax; invalid value of @embed: %s", stringVal))
}
}
return EmbedLast, NewJsonLdError(InvalidEmbedValue, "Invalid JSON-LD frame syntax; invalid value of @embed")
}
// removeEmbed removes an existing embed with the given id.
func removeEmbed(state *FramingContext, id string) {
// get existing embed
links := state.uniqueEmbeds[state.graph]
embed := links[id]
parent := embed.parent
property := embed.property
// create reference to replace embed
subject := map[string]interface{}{
"@id": id,
}
// remove existing embed
if _, isArray := parent.([]interface{}); isArray {
// replace subject with reference
newVals := make([]interface{}, 0)
parentMap := parent.(map[string]interface{})
oldvals := parentMap[property].([]interface{})
for _, v := range oldvals {
vMap, isMap := v.(map[string]interface{})
if isMap && vMap["@id"] == id {
newVals = append(newVals, subject)
} else {
newVals = append(newVals, v)
}
}
parentMap[property] = newVals
} else {
// replace subject with reference
parentMap := parent.(map[string]interface{})
_, useArray := parentMap[property]
RemoveValue(parentMap, property, subject, useArray)
AddValue(parentMap, property, subject, useArray, false, true, false)
}
// recursively remove dependent dangling embeds
removeDependents(links, id)
}
// removeDependents recursively removes dependent dangling embeds.
func removeDependents(embeds map[string]*EmbedNode, id string) {
// get embed keys as a separate array to enable deleting keys in map
for idDep, e := range embeds {
var p map[string]interface{}
if e.parent != nil {
var isMap bool
p, isMap = e.parent.(map[string]interface{})
if !isMap {
continue
}
} else {
p = make(map[string]interface{})
}
pid := p["@id"].(string)
if id == pid {
delete(embeds, idDep)
removeDependents(embeds, idDep)
}
}
}
// FilterSubjects returns a map of all of the nodes that match a parsed frame.
func FilterSubjects(state *FramingContext, subjects []string, frame map[string]interface{}, requireAll bool) (map[string]interface{}, error) {
rval := make(map[string]interface{})
for _, id := range subjects {
// id, elementVal
elementVal := state.graphMap[state.graph].(map[string]interface{})[id]
element, _ := elementVal.(map[string]interface{})
if element != nil {
res, err := FilterSubject(state, element, frame, requireAll)
if res {
if err != nil {
return nil, err
}
rval[id] = element
}
}
}
return rval, nil
}
// FilterSubject returns true if the given node matches the given frame.
//
// Matches either based on explicit type inclusion where the node has any
// type listed in the frame. If the frame has empty types defined matches
// nodes not having a @type. If the frame has a type of {} defined matches
// nodes having any type defined.
//
// Otherwise, does duck typing, where the node must have all of the
// properties defined in the frame.
func FilterSubject(state *FramingContext, subject map[string]interface{}, frame map[string]interface{}, requireAll bool) (bool, error) {
// check ducktype
wildcard := true
matchesSome := false
for _, k := range GetOrderedKeys(frame) {
v := frame[k]
matchThis := false
var nodeValues []interface{}
if kVal, found := subject[k]; found {
nodeValues = Arrayify(kVal)
} else {
nodeValues = make([]interface{}, 0)
}
vList, _ := v.([]interface{})
vMap, _ := v.(map[string]interface{})
isEmpty := (len(vList) + len(vMap)) == 0
if IsKeyword(k) {
// skip non-@id and non-@type
if k != "@id" && k != "@type" {
continue
}
wildcard = true
// check @id for a specific @id value
if k == "@id" {
// if @id is not a wildcard and is not empty, then match
// or not on specific value
frameID := Arrayify(frame["@id"])
if len(frameID) >= 0 {
_, isString := frameID[0].(string)
if !isEmptyObject(frameID[0]) || isString {
return inArray(nodeValues[0], frameID), nil
}
}
matchThis = true
continue
}
// check @type (object value means 'any' type, fall through to
// ducktyping)
if k == "@type" {
if isEmpty {
if len(nodeValues) > 0 {
// don't match on no @type
return false, nil
}
matchThis = true
} else {
frameType := frame["@type"].([]interface{})
if isEmptyObject(frameType[0]) {
matchThis = len(nodeValues) > 0
} else {
// match on a specific @type
r := make([]interface{}, 0)
for _, tv := range nodeValues {
for _, tf := range frameType {
if tv == tf {
r = append(r, tv)
// break early, as we just need one element to succeed
break
}
}
}
return len(r) > 0, nil
}
}
}
}
// force a copy of this frame entry so it can be manipulated
var thisFrame interface{}
if x := Arrayify(frame[k]); len(x) > 0 {
thisFrame = x[0]
}
hasDefault := false
if thisFrame != nil {
if err := validateFrame(thisFrame); err != nil {
return false, err
}
_, hasDefault = thisFrame.(map[string]interface{})["@default"]
}
// no longer a wildcard pattern if frame has any non-keyword
// properties
wildcard = false
// skip, but allow match if node has no value for property, and
// frame has a default value
if len(nodeValues) == 0 && hasDefault {
continue
}
// if frame value is empty, don't match if subject has any value
if len(nodeValues) > 0 && isEmpty {
return false, nil
}
if thisFrame == nil {
// node does not match if values is not empty and the value of
// property in frame is match none.
if len(nodeValues) > 0 {
return false, nil
}
matchThis = true
} else if _, isMap := thisFrame.(map[string]interface{}); isMap {
// node matches if values is not empty and the value of
// property in frame is wildcard
matchThis = len(nodeValues) > 0
} else {
if IsValue(thisFrame) {
for _, nv := range nodeValues {
if valueMatch(thisFrame.(map[string]interface{}), nv.(map[string]interface{})) {
matchThis = true
break
}
}
} else if IsList(thisFrame) {
listValue := thisFrame.(map[string]interface{})["@list"].([]interface{})[0]
if len(nodeValues) > 0 && IsList(nodeValues[0]) {
nodeListValues := nodeValues[0].(map[string]interface{})["@list"]
if IsValue(listValue) {
for _, lv := range nodeListValues.([]interface{}) {
if valueMatch(listValue.(map[string]interface{}), lv.(map[string]interface{})) {
matchThis = true
break
}
}
} else if IsSubject(listValue) || IsSubjectReference(listValue) {
for _, lv := range nodeListValues.([]interface{}) {
if nodeMatch(state, listValue.(map[string]interface{}), lv.(map[string]interface{}), requireAll) {
matchThis = true
break
}
}
}
}
}
}
if !matchThis && requireAll {
return false, nil
}
matchesSome = matchesSome || matchThis
}
return wildcard || matchesSome, nil
}
// addFrameOutput adds framing output to the given parent.
// parent: the parent to add to.
// property: the parent property.
// output: the output to add.
func addFrameOutput(parent interface{}, property string, output interface{}) interface{} {
if parentMap, isMap := parent.(map[string]interface{}); isMap {
AddValue(parentMap, property, output, true, false, true, false)
return parentMap
}
return append(parent.([]interface{}), output)
}
func nodeMatch(state *FramingContext, pattern, value map[string]interface{}, requireAll bool) bool {
id, hasID := value["@id"]
if !hasID {
return false
}
nodeObject, found := state.subjects[id.(string)]
if !found {
return false
}
ok, _ := FilterSubject(state, nodeObject.(map[string]interface{}), pattern, requireAll)
return ok
}
// ValueMatch returns true if it is a value and matches the value pattern
//
// * `pattern` is empty
// * @values are the same, or `pattern[@value]` is a wildcard,
// * @types are the same or `value[@type]` is not None
// and `pattern[@type]` is `{}` or `value[@type]` is None
// and `pattern[@type]` is None or `[]`, and
// * @languages are the same or `value[@language]` is not None
// and `pattern[@language]` is `{}`, or `value[@language]` is None
// and `pattern[@language]` is None or `[]`
func valueMatch(pattern, value map[string]interface{}) bool {
v2v := pattern["@value"]
t2v := pattern["@type"]
l2v := pattern["@language"]
if v2v == nil && t2v == nil && l2v == nil {
return true
}
var v2 []interface{}
if v2v != nil {
v2 = Arrayify(v2v)
}
var t2 []interface{}
if t2v != nil {
t2 = Arrayify(t2v)
}
var l2 []interface{}
if l2v != nil {
l2 = Arrayify(l2v)
}
v1 := value["@value"]
t1 := value["@type"]
l1 := value["@language"]
if !(inArray(v1, v2) || (len(v2) > 0 && isEmptyObject(v2[0]))) {
return false
}
if !((t1 == nil && len(t2) == 0) || (inArray(t1, t2)) || (t1 != nil && len(t2) > 0 && isEmptyObject(t2[0]))) {
return false
}
if !((l1 == nil && len(l2) == 0) || (inArray(l1, l2)) || (l1 != nil && len(l2) > 0 && isEmptyObject(l2[0]))) {
return false
}
return true
}
| kdimak/json-gold |
<|start_filename|>js/blur.js<|end_filename|>
function blur() {
this.blur();
return true;
}
<|start_filename|>js/setAttribute.js<|end_filename|>
function setAttribute(n, v) {
this[n] = v;
if (n === 'value') {
this.dispatchEvent(new Event('input', {bubbles: true}));
this.dispatchEvent(new Event('change', {bubbles: true}));
}
return this[n];
}
<|start_filename|>js/visible.js<|end_filename|>
function visible() {
return Boolean(this.offsetWidth || this.offsetHeight || this.getClientRects().length);
}
<|start_filename|>device/device.go<|end_filename|>
// Package device contains device emulation definitions for use with chromedp's
// Emulate action.
//
// See: https://raw.githubusercontent.com/puppeteer/puppeteer/main/src/common/DeviceDescriptors.ts
package device
// Generated by gen.go. DO NOT EDIT.
//go:generate go run gen.go
// Info holds device information for use with chromedp.Emulate.
type Info struct {
// Name is the device name.
Name string
// UserAgent is the device user agent string.
UserAgent string
// Width is the viewport width.
Width int64
// Height is the viewport height.
Height int64
// Scale is the device viewport scale factor.
Scale float64
// Landscape indicates whether or not the device is in landscape mode or
// not.
Landscape bool
// Mobile indicates whether it is a mobile device or not.
Mobile bool
// Touch indicates whether the device has touch enabled.
Touch bool
}
// String satisfies fmt.Stringer.
func (i Info) String() string {
return i.Name
}
// Device satisfies chromedp.Device.
func (i Info) Device() Info {
return i
}
// infoType provides the enumerated device type.
type infoType int
// String satisfies fmt.Stringer.
func (i infoType) String() string {
return devices[i].String()
}
// Device satisfies chromedp.Device.
func (i infoType) Device() Info {
return devices[i]
}
// Devices.
const (
// Reset is the reset device.
Reset infoType = iota
// BlackberryPlayBook is the "Blackberry PlayBook" device.
BlackberryPlayBook
// BlackberryPlayBooklandscape is the "Blackberry PlayBook landscape" device.
BlackberryPlayBooklandscape
// BlackBerryZ30 is the "BlackBerry Z30" device.
BlackBerryZ30
// BlackBerryZ30landscape is the "BlackBerry Z30 landscape" device.
BlackBerryZ30landscape
// GalaxyNote3 is the "Galaxy Note 3" device.
GalaxyNote3
// GalaxyNote3landscape is the "Galaxy Note 3 landscape" device.
GalaxyNote3landscape
// GalaxyNoteII is the "Galaxy Note II" device.
GalaxyNoteII
// GalaxyNoteIIlandscape is the "Galaxy Note II landscape" device.
GalaxyNoteIIlandscape
// GalaxySIII is the "Galaxy S III" device.
GalaxySIII
// GalaxySIIIlandscape is the "Galaxy S III landscape" device.
GalaxySIIIlandscape
// GalaxyS5 is the "Galaxy S5" device.
GalaxyS5
// GalaxyS5landscape is the "Galaxy S5 landscape" device.
GalaxyS5landscape
// GalaxyS8 is the "Galaxy S8" device.
GalaxyS8
// GalaxyS8landscape is the "Galaxy S8 landscape" device.
GalaxyS8landscape
// GalaxyS9 is the "Galaxy S9+" device.
GalaxyS9
// GalaxyS9landscape is the "Galaxy S9+ landscape" device.
GalaxyS9landscape
// GalaxyTabS4 is the "Galaxy Tab S4" device.
GalaxyTabS4
// GalaxyTabS4landscape is the "Galaxy Tab S4 landscape" device.
GalaxyTabS4landscape
// IPad is the "iPad" device.
IPad
// IPadlandscape is the "iPad landscape" device.
IPadlandscape
// IPadgen6 is the "iPad (gen 6)" device.
IPadgen6
// IPadgen6landscape is the "iPad (gen 6) landscape" device.
IPadgen6landscape
// IPadgen7 is the "iPad (gen 7)" device.
IPadgen7
// IPadgen7landscape is the "iPad (gen 7) landscape" device.
IPadgen7landscape
// IPadMini is the "iPad Mini" device.
IPadMini
// IPadMinilandscape is the "iPad Mini landscape" device.
IPadMinilandscape
// IPadPro is the "iPad Pro" device.
IPadPro
// IPadProlandscape is the "iPad Pro landscape" device.
IPadProlandscape
// IPadPro11 is the "iPad Pro 11" device.
IPadPro11
// IPadPro11landscape is the "iPad Pro 11 landscape" device.
IPadPro11landscape
// IPhone4 is the "iPhone 4" device.
IPhone4
// IPhone4landscape is the "iPhone 4 landscape" device.
IPhone4landscape
// IPhone5 is the "iPhone 5" device.
IPhone5
// IPhone5landscape is the "iPhone 5 landscape" device.
IPhone5landscape
// IPhone6 is the "iPhone 6" device.
IPhone6
// IPhone6landscape is the "iPhone 6 landscape" device.
IPhone6landscape
// IPhone6Plus is the "iPhone 6 Plus" device.
IPhone6Plus
// IPhone6Pluslandscape is the "iPhone 6 Plus landscape" device.
IPhone6Pluslandscape
// IPhone7 is the "iPhone 7" device.
IPhone7
// IPhone7landscape is the "iPhone 7 landscape" device.
IPhone7landscape
// IPhone7Plus is the "iPhone 7 Plus" device.
IPhone7Plus
// IPhone7Pluslandscape is the "iPhone 7 Plus landscape" device.
IPhone7Pluslandscape
// IPhone8 is the "iPhone 8" device.
IPhone8
// IPhone8landscape is the "iPhone 8 landscape" device.
IPhone8landscape
// IPhone8Plus is the "iPhone 8 Plus" device.
IPhone8Plus
// IPhone8Pluslandscape is the "iPhone 8 Plus landscape" device.
IPhone8Pluslandscape
// IPhoneSE is the "iPhone SE" device.
IPhoneSE
// IPhoneSElandscape is the "iPhone SE landscape" device.
IPhoneSElandscape
// IPhoneX is the "iPhone X" device.
IPhoneX
// IPhoneXlandscape is the "iPhone X landscape" device.
IPhoneXlandscape
// IPhoneXR is the "iPhone XR" device.
IPhoneXR
// IPhoneXRlandscape is the "iPhone XR landscape" device.
IPhoneXRlandscape
// IPhone11 is the "iPhone 11" device.
IPhone11
// IPhone11landscape is the "iPhone 11 landscape" device.
IPhone11landscape
// IPhone11Pro is the "iPhone 11 Pro" device.
IPhone11Pro
// IPhone11Prolandscape is the "iPhone 11 Pro landscape" device.
IPhone11Prolandscape
// IPhone11ProMax is the "iPhone 11 Pro Max" device.
IPhone11ProMax
// IPhone11ProMaxlandscape is the "iPhone 11 Pro Max landscape" device.
IPhone11ProMaxlandscape
// IPhone12 is the "iPhone 12" device.
IPhone12
// IPhone12landscape is the "iPhone 12 landscape" device.
IPhone12landscape
// IPhone12Pro is the "iPhone 12 Pro" device.
IPhone12Pro
// IPhone12Prolandscape is the "iPhone 12 Pro landscape" device.
IPhone12Prolandscape
// IPhone12ProMax is the "iPhone 12 Pro Max" device.
IPhone12ProMax
// IPhone12ProMaxlandscape is the "iPhone 12 Pro Max landscape" device.
IPhone12ProMaxlandscape
// IPhone12Mini is the "iPhone 12 Mini" device.
IPhone12Mini
// IPhone12Minilandscape is the "iPhone 12 Mini landscape" device.
IPhone12Minilandscape
// IPhone13 is the "iPhone 13" device.
IPhone13
// IPhone13landscape is the "iPhone 13 landscape" device.
IPhone13landscape
// IPhone13Pro is the "iPhone 13 Pro" device.
IPhone13Pro
// IPhone13Prolandscape is the "iPhone 13 Pro landscape" device.
IPhone13Prolandscape
// IPhone13ProMax is the "iPhone 13 Pro Max" device.
IPhone13ProMax
// IPhone13ProMaxlandscape is the "iPhone 13 Pro Max landscape" device.
IPhone13ProMaxlandscape
// IPhone13Mini is the "iPhone 13 Mini" device.
IPhone13Mini
// IPhone13Minilandscape is the "iPhone 13 Mini landscape" device.
IPhone13Minilandscape
// JioPhone2 is the "JioPhone 2" device.
JioPhone2
// JioPhone2landscape is the "JioPhone 2 landscape" device.
JioPhone2landscape
// KindleFireHDX is the "Kindle Fire HDX" device.
KindleFireHDX
// KindleFireHDXlandscape is the "Kindle Fire HDX landscape" device.
KindleFireHDXlandscape
// LGOptimusL70 is the "LG Optimus L70" device.
LGOptimusL70
// LGOptimusL70landscape is the "LG Optimus L70 landscape" device.
LGOptimusL70landscape
// MicrosoftLumia550 is the "Microsoft Lumia 550" device.
MicrosoftLumia550
// MicrosoftLumia950 is the "Microsoft Lumia 950" device.
MicrosoftLumia950
// MicrosoftLumia950landscape is the "Microsoft Lumia 950 landscape" device.
MicrosoftLumia950landscape
// Nexus10 is the "Nexus 10" device.
Nexus10
// Nexus10landscape is the "Nexus 10 landscape" device.
Nexus10landscape
// Nexus4 is the "Nexus 4" device.
Nexus4
// Nexus4landscape is the "Nexus 4 landscape" device.
Nexus4landscape
// Nexus5 is the "Nexus 5" device.
Nexus5
// Nexus5landscape is the "Nexus 5 landscape" device.
Nexus5landscape
// Nexus5X is the "Nexus 5X" device.
Nexus5X
// Nexus5Xlandscape is the "Nexus 5X landscape" device.
Nexus5Xlandscape
// Nexus6 is the "Nexus 6" device.
Nexus6
// Nexus6landscape is the "Nexus 6 landscape" device.
Nexus6landscape
// Nexus6P is the "Nexus 6P" device.
Nexus6P
// Nexus6Plandscape is the "Nexus 6P landscape" device.
Nexus6Plandscape
// Nexus7 is the "Nexus 7" device.
Nexus7
// Nexus7landscape is the "Nexus 7 landscape" device.
Nexus7landscape
// NokiaLumia520 is the "Nokia Lumia 520" device.
NokiaLumia520
// NokiaLumia520landscape is the "Nokia Lumia 520 landscape" device.
NokiaLumia520landscape
// NokiaN9 is the "Nokia N9" device.
NokiaN9
// NokiaN9landscape is the "Nokia N9 landscape" device.
NokiaN9landscape
// Pixel2 is the "Pixel 2" device.
Pixel2
// Pixel2landscape is the "Pixel 2 landscape" device.
Pixel2landscape
// Pixel2XL is the "Pixel 2 XL" device.
Pixel2XL
// Pixel2XLlandscape is the "Pixel 2 XL landscape" device.
Pixel2XLlandscape
// Pixel3 is the "Pixel 3" device.
Pixel3
// Pixel3landscape is the "Pixel 3 landscape" device.
Pixel3landscape
// Pixel4 is the "Pixel 4" device.
Pixel4
// Pixel4landscape is the "Pixel 4 landscape" device.
Pixel4landscape
// Pixel4a5G is the "Pixel 4a (5G)" device.
Pixel4a5G
// Pixel4a5Glandscape is the "Pixel 4a (5G) landscape" device.
Pixel4a5Glandscape
// Pixel5 is the "Pixel 5" device.
Pixel5
// Pixel5landscape is the "Pixel 5 landscape" device.
Pixel5landscape
// MotoG4 is the "Moto G4" device.
MotoG4
// MotoG4landscape is the "Moto G4 landscape" device.
MotoG4landscape
)
// devices is the list of devices.
var devices = [...]Info{
{"", "", 0, 0, 0.000000, false, false, false},
{"Blackberry PlayBook", "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+", 600, 1024, 1.000000, false, true, true},
{"Blackberry PlayBook landscape", "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+", 1024, 600, 1.000000, true, true, true},
{"BlackBerry Z30", "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+", 360, 640, 2.000000, false, true, true},
{"BlackBerry Z30 landscape", "Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+", 640, 360, 2.000000, true, true, true},
{"Galaxy Note 3", "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", 360, 640, 3.000000, false, true, true},
{"Galaxy Note 3 landscape", "Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", 640, 360, 3.000000, true, true, true},
{"Galaxy Note II", "Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", 360, 640, 2.000000, false, true, true},
{"Galaxy Note II landscape", "Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", 640, 360, 2.000000, true, true, true},
{"Galaxy S III", "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", 360, 640, 2.000000, false, true, true},
{"Galaxy S III landscape", "Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30", 640, 360, 2.000000, true, true, true},
{"Galaxy S5", "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 360, 640, 3.000000, false, true, true},
{"Galaxy S5 landscape", "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 640, 360, 3.000000, true, true, true},
{"Galaxy S8", "Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36", 360, 740, 3.000000, false, true, true},
{"Galaxy S8 landscape", "Mozilla/5.0 (Linux; Android 7.0; SM-G950U Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36", 740, 360, 3.000000, true, true, true},
{"Galaxy S9+", "Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36", 320, 658, 4.500000, false, true, true},
{"Galaxy S9+ landscape", "Mozilla/5.0 (Linux; Android 8.0.0; SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 Mobile Safari/537.36", 658, 320, 4.500000, true, true, true},
{"Galaxy Tab S4", "Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Safari/537.36", 712, 1138, 2.250000, false, true, true},
{"Galaxy Tab S4 landscape", "Mozilla/5.0 (Linux; Android 8.1.0; SM-T837A) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Safari/537.36", 1138, 712, 2.250000, true, true, true},
{"iPad", "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1", 768, 1024, 2.000000, false, true, true},
{"iPad landscape", "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1", 1024, 768, 2.000000, true, true, true},
{"iPad (gen 6)", "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 768, 1024, 2.000000, false, true, true},
{"iPad (gen 6) landscape", "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 1024, 768, 2.000000, true, true, true},
{"iPad (gen 7)", "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 810, 1080, 2.000000, false, true, true},
{"iPad (gen 7) landscape", "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 1080, 810, 2.000000, true, true, true},
{"iPad Mini", "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1", 768, 1024, 2.000000, false, true, true},
{"iPad Mini landscape", "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1", 1024, 768, 2.000000, true, true, true},
{"iPad Pro", "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1", 1024, 1366, 2.000000, false, true, true},
{"iPad Pro landscape", "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1", 1366, 1024, 2.000000, true, true, true},
{"iPad Pro 11", "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 834, 1194, 2.000000, false, true, true},
{"iPad Pro 11 landscape", "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 1194, 834, 2.000000, true, true, true},
{"iPhone 4", "Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53", 320, 480, 2.000000, false, true, true},
{"iPhone 4 landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53", 480, 320, 2.000000, true, true, true},
{"iPhone 5", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1", 320, 568, 2.000000, false, true, true},
{"iPhone 5 landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1", 568, 320, 2.000000, true, true, true},
{"iPhone 6", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 375, 667, 2.000000, false, true, true},
{"iPhone 6 landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 667, 375, 2.000000, true, true, true},
{"iPhone 6 Plus", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 414, 736, 3.000000, false, true, true},
{"iPhone 6 Plus landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 736, 414, 3.000000, true, true, true},
{"iPhone 7", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 375, 667, 2.000000, false, true, true},
{"iPhone 7 landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 667, 375, 2.000000, true, true, true},
{"iPhone 7 Plus", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 414, 736, 3.000000, false, true, true},
{"iPhone 7 Plus landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 736, 414, 3.000000, true, true, true},
{"iPhone 8", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 375, 667, 2.000000, false, true, true},
{"iPhone 8 landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 667, 375, 2.000000, true, true, true},
{"iPhone 8 Plus", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 414, 736, 3.000000, false, true, true},
{"iPhone 8 Plus landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 736, 414, 3.000000, true, true, true},
{"iPhone SE", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1", 320, 568, 2.000000, false, true, true},
{"iPhone SE landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1", 568, 320, 2.000000, true, true, true},
{"iPhone X", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 375, 812, 3.000000, false, true, true},
{"iPhone X landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1", 812, 375, 3.000000, true, true, true},
{"iPhone XR", "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1", 414, 896, 3.000000, false, true, true},
{"iPhone XR landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1", 896, 414, 3.000000, true, true, true},
{"iPhone 11", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1", 414, 828, 2.000000, false, true, true},
{"iPhone 11 landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1", 828, 414, 2.000000, true, true, true},
{"iPhone 11 Pro", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1", 375, 812, 3.000000, false, true, true},
{"iPhone 11 Pro landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1", 812, 375, 3.000000, true, true, true},
{"iPhone 11 Pro Max", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1", 414, 896, 3.000000, false, true, true},
{"iPhone 11 Pro Max landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1", 896, 414, 3.000000, true, true, true},
{"iPhone 12", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 390, 844, 3.000000, false, true, true},
{"iPhone 12 landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 844, 390, 3.000000, true, true, true},
{"iPhone 12 Pro", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 390, 844, 3.000000, false, true, true},
{"iPhone 12 Pro landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 844, 390, 3.000000, true, true, true},
{"iPhone 12 Pro Max", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 428, 926, 3.000000, false, true, true},
{"iPhone 12 Pro Max landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 926, 428, 3.000000, true, true, true},
{"iPhone 12 Mini", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 375, 812, 3.000000, false, true, true},
{"iPhone 12 Mini landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 812, 375, 3.000000, true, true, true},
{"iPhone 13", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 390, 844, 3.000000, false, true, true},
{"iPhone 13 landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 844, 390, 3.000000, true, true, true},
{"iPhone 13 Pro", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 390, 844, 3.000000, false, true, true},
{"iPhone 13 Pro landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 844, 390, 3.000000, true, true, true},
{"iPhone 13 Pro Max", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 428, 926, 3.000000, false, true, true},
{"iPhone 13 Pro Max landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 926, 428, 3.000000, true, true, true},
{"iPhone 13 Mini", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 375, 812, 3.000000, false, true, true},
{"iPhone 13 Mini landscape", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/604.1", 812, 375, 3.000000, true, true, true},
{"JioPhone 2", "Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5", 240, 320, 1.000000, false, true, true},
{"JioPhone 2 landscape", "Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5", 320, 240, 1.000000, true, true, true},
{"Kindle Fire HDX", "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true", 800, 1280, 2.000000, false, true, true},
{"Kindle Fire HDX landscape", "Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true", 1280, 800, 2.000000, true, true, true},
{"LG Optimus L70", "Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36", 384, 640, 1.250000, false, true, true},
{"LG Optimus L70 landscape", "Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36", 640, 384, 1.250000, true, true, true},
{"Microsoft Lumia 550", "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263", 640, 360, 2.000000, false, true, true},
{"Microsoft Lumia 950", "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263", 360, 640, 4.000000, false, true, true},
{"Microsoft Lumia 950 landscape", "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263", 640, 360, 4.000000, true, true, true},
{"Nexus 10", "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36", 800, 1280, 2.000000, false, true, true},
{"Nexus 10 landscape", "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36", 1280, 800, 2.000000, true, true, true},
{"Nexus 4", "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 384, 640, 2.000000, false, true, true},
{"Nexus 4 landscape", "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 640, 384, 2.000000, true, true, true},
{"Nexus 5", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 360, 640, 3.000000, false, true, true},
{"Nexus 5 landscape", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 640, 360, 3.000000, true, true, true},
{"Nexus 5X", "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 412, 732, 2.625000, false, true, true},
{"Nexus 5X landscape", "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 732, 412, 2.625000, true, true, true},
{"Nexus 6", "Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 412, 732, 3.500000, false, true, true},
{"Nexus 6 landscape", "Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 732, 412, 3.500000, true, true, true},
{"Nexus 6P", "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 412, 732, 3.500000, false, true, true},
{"Nexus 6P landscape", "Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 732, 412, 3.500000, true, true, true},
{"Nexus 7", "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36", 600, 960, 2.000000, false, true, true},
{"Nexus 7 landscape", "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36", 960, 600, 2.000000, true, true, true},
{"Nokia Lumia 520", "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)", 320, 533, 1.500000, false, true, true},
{"Nokia Lumia 520 landscape", "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)", 533, 320, 1.500000, true, true, true},
{"Nokia N9", "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13", 480, 854, 1.000000, false, true, true},
{"Nokia N9 landscape", "Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13", 854, 480, 1.000000, true, true, true},
{"Pixel 2", "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 411, 731, 2.625000, false, true, true},
{"Pixel 2 landscape", "Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 731, 411, 2.625000, true, true, true},
{"Pixel 2 XL", "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 411, 823, 3.500000, false, true, true},
{"Pixel 2 XL landscape", "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36", 823, 411, 3.500000, true, true, true},
{"Pixel 3", "Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.158 Mobile Safari/537.36", 393, 786, 2.750000, false, true, true},
{"Pixel 3 landscape", "Mozilla/5.0 (Linux; Android 9; Pixel 3 Build/PQ1A.181105.017.A1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.158 Mobile Safari/537.36", 786, 393, 2.750000, true, true, true},
{"Pixel 4", "Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36", 353, 745, 3.000000, false, true, true},
{"Pixel 4 landscape", "Mozilla/5.0 (Linux; Android 10; Pixel 4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36", 745, 353, 3.000000, true, true, true},
{"Pixel 4a (5G)", "Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36", 353, 745, 3.000000, false, true, true},
{"Pixel 4a (5G) landscape", "Mozilla/5.0 (Linux; Android 11; Pixel 4a (5G)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36", 745, 353, 3.000000, true, true, true},
{"Pixel 5", "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36", 393, 851, 3.000000, false, true, true},
{"Pixel 5 landscape", "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36", 851, 393, 3.000000, true, true, true},
{"Moto G4", "Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36", 360, 640, 3.000000, false, true, true},
{"Moto G4 landscape", "Mozilla/5.0 (Linux; Android 7.0; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4812.0 Mobile Safari/537.36", 640, 360, 3.000000, true, true, true},
}
<|start_filename|>js/getClientRect.js<|end_filename|>
function getClientRect() {
const e = this.getBoundingClientRect(),
t = this.ownerDocument.documentElement.getBoundingClientRect();
return {
x: e.left - t.left,
y: e.top - t.top,
width: e.width,
height: e.height,
};
}
<|start_filename|>allocate_linux.go<|end_filename|>
//go:build linux
// +build linux
package chromedp
import (
"os"
"os/exec"
"syscall"
)
func allocateCmdOptions(cmd *exec.Cmd) {
if _, ok := os.LookupEnv("LAMBDA_TASK_ROOT"); ok {
// do nothing on AWS Lambda
return
}
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = new(syscall.SysProcAttr)
}
// When the parent process dies (Go), kill the child as well.
cmd.SysProcAttr.Pdeathsig = syscall.SIGKILL
}
<|start_filename|>js/reset.js<|end_filename|>
function reset() {
if (this.nodeName === 'FORM') {
HTMLFormElement.prototype.reset.call(this);
return true;
} else if (this.form !== null) {
HTMLFormElement.prototype.reset.call(this.form);
return true;
}
return false;
}
<|start_filename|>js/textContent.js<|end_filename|>
function textContent() {
return this.textContent;
}
<|start_filename|>js.go<|end_filename|>
package chromedp
import (
_ "embed"
)
var (
// textJS is a javascript snippet that returns the innerText of the specified
// visible (ie, offsetWidth || offsetHeight || getClientRects().length ) element.
//go:embed js/text.js
textJS string
// textContentJS is a javascript snippet that returns the textContent of the
// specified element.
//go:embed js/textContent.js
textContentJS string
// blurJS is a javascript snippet that blurs the specified element.
//go:embed js/blur.js
blurJS string
// submitJS is a javascript snippet that will call the containing form's
// submit function, returning true or false if the call was successful.
//go:embed js/submit.js
submitJS string
// resetJS is a javascript snippet that will call the containing form's
// reset function, returning true or false if the call was successful.
//go:embed js/reset.js
resetJS string
// attributeJS is a javascript snippet that returns the attribute of a specified
// node.
//go:embed js/attribute.js
attributeJS string
// setAttributeJS is a javascript snippet that sets the value of the specified
// node, and returns the value.
//go:embed js/setAttribute.js
setAttributeJS string
// visibleJS is a javascript snippet that returns true or false depending on if
// the specified node's offsetWidth, offsetHeight or getClientRects().length is
// not null.
//go:embed js/visible.js
visibleJS string
// getClientRectJS is a javascript snippet that returns the information about the
// size of the specified node and its position relative to its owner document.
//go:embed js/getClientRect.js
getClientRectJS string
// waitForPredicatePageFunction is a javascript snippet that runs the polling in the
// browser. It's copied from puppeteer. See
// https://github.com/puppeteer/puppeteer/blob/669f04a7a6e96cc8353a8cb152898edbc25e7c15/src/common/DOMWorld.ts#L870-L944
// It's modified to make mutation polling respect timeout even when there is not DOM mutation.
//go:embed js/waitForPredicatePageFunction.js
waitForPredicatePageFunction string
)
<|start_filename|>js/waitForPredicatePageFunction.js<|end_filename|>
async function waitForPredicatePageFunction(predicateBody, polling, timeout, ...args) {
const predicate = new Function('...args', predicateBody);
let timedOut = false;
if (timeout)
setTimeout(() => (timedOut = true), timeout);
if (polling === 'raf')
return await pollRaf();
if (polling === 'mutation')
return await pollMutation();
if (typeof polling === 'number')
return await pollInterval(polling);
/**
* @returns {!Promise<*>}
*/
async function pollMutation() {
const success = await predicate(...args);
if (success)
return Promise.resolve(success);
let fulfill;
const result = new Promise((x) => (fulfill = x));
const observer = new MutationObserver(async () => {
if (timedOut) {
observer.disconnect();
fulfill();
}
const success = await predicate(...args);
if (success) {
observer.disconnect();
fulfill(success);
}
});
observer.observe(document, {
childList: true,
subtree: true,
attributes: true,
});
if (timeout)
setTimeout(() => {
observer.disconnect();
fulfill();
}, timeout);
return result;
}
async function pollRaf() {
let fulfill;
const result = new Promise((x) => (fulfill = x));
await onRaf();
return result;
async function onRaf() {
if (timedOut) {
fulfill();
return;
}
const success = await predicate(...args);
if (success)
fulfill(success);
else
requestAnimationFrame(onRaf);
}
}
async function pollInterval(pollInterval) {
let fulfill;
const result = new Promise((x) => (fulfill = x));
await onTimeout();
return result;
async function onTimeout() {
if (timedOut) {
fulfill();
return;
}
const success = await predicate(...args);
if (success)
fulfill(success);
else
setTimeout(onTimeout, pollInterval);
}
}
}
<|start_filename|>device/gen.go<|end_filename|>
//go:build ignore
// +build ignore
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"go/format"
"io/ioutil"
"net/http"
"os"
"regexp"
"strings"
)
const deviceDescriptorsURL = "https://raw.githubusercontent.com/puppeteer/puppeteer/main/src/common/DeviceDescriptors.ts"
func main() {
out := flag.String("out", "device.go", "out")
flag.Parse()
if err := run(*out); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
type deviceDescriptor struct {
Name string `json:"name"`
UserAgent string `json:"userAgent"`
Viewport struct {
Width int64 `json:"width"`
Height int64 `json:"height"`
DeviceScaleFactor float64 `json:"deviceScaleFactor"`
IsMobile bool `json:"isMobile"`
HasTouch bool `json:"hasTouch"`
IsLandscape bool `json:"isLandscape"`
} `json:"viewport"`
}
var cleanRE = regexp.MustCompile(`[^a-zA-Z0-9_]`)
// run runs the program.
func run(out string) error {
var descriptors []deviceDescriptor
if err := get(&descriptors); err != nil {
return err
}
// add reset device
descriptors = append([]deviceDescriptor{{}}, descriptors...)
buf := new(bytes.Buffer)
fmt.Fprintf(buf, hdr, deviceDescriptorsURL)
fmt.Fprintln(buf, "\n// Devices.")
fmt.Fprintln(buf, "const (")
for i, d := range descriptors {
if i == 0 {
fmt.Fprintln(buf, "// Reset is the reset device.")
fmt.Fprintln(buf, "Reset infoType = iota\n")
} else {
name := cleanRE.ReplaceAllString(d.Name, "")
name = strings.ToUpper(name[0:1]) + name[1:]
fmt.Fprintf(buf, "// %s is the %q device.\n", name, d.Name)
fmt.Fprintf(buf, "%s\n\n", name)
}
}
fmt.Fprintln(buf, ")\n")
fmt.Fprintln(buf, "// devices is the list of devices.")
fmt.Fprintln(buf, "var devices = [...]Info{")
for _, d := range descriptors {
fmt.Fprintf(buf, "{%q, %q, %d, %d, %f, %t, %t, %t},\n",
d.Name, d.UserAgent,
d.Viewport.Width, d.Viewport.Height, d.Viewport.DeviceScaleFactor,
d.Viewport.IsLandscape, d.Viewport.IsMobile, d.Viewport.HasTouch,
)
}
fmt.Fprintln(buf, "}")
src, err := format.Source(buf.Bytes())
if err != nil {
return err
}
return ioutil.WriteFile(out, src, 0o644)
}
var (
startRE = regexp.MustCompile(`(?m)^const\s+devices:\s*Device\[\]\s*=\s*\[`)
endRE = regexp.MustCompile(`(?m)^\];`)
fixLandscapeRE = regexp.MustCompile(`isLandscape:\s*(true|false),`)
fixKeysRE = regexp.MustCompile(`(?m)^(\s+)([a-zA-Z]+):`)
fixClosesRE = regexp.MustCompile(`([\]\}]),\n(\s*[\]\}])`)
)
// get retrieves and decodes the device descriptors.
func get(v interface{}) error {
req, err := http.NewRequest("GET", deviceDescriptorsURL, nil)
if err != nil {
return err
}
// retrieve
cl := &http.Client{}
res, err := cl.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return fmt.Errorf("got status code %d", res.StatusCode)
}
buf, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
start := startRE.FindIndex(buf)
if start == nil {
return errors.New("could not find start")
}
buf = buf[start[1]-1:]
end := endRE.FindIndex(buf)
if end == nil {
return errors.New("could not find end")
}
buf = buf[:end[1]-1]
buf = bytes.Replace(buf, []byte("'"), []byte(`"`), -1)
buf = fixLandscapeRE.ReplaceAll(buf, []byte(`"isLandscape": $1`))
buf = fixKeysRE.ReplaceAll(buf, []byte(`$1"$2":`))
buf = fixClosesRE.ReplaceAll(buf, []byte("$1\n$2"))
buf = fixClosesRE.ReplaceAll(buf, []byte("$1\n$2"))
return json.Unmarshal(buf, v)
}
const hdr = `// Package device contains device emulation definitions for use with chromedp's
// Emulate action.
//
// See: %s
package device
` + `// Generated by gen.go. DO NOT EDIT.` + `
//go:generate go run gen.go
// Info holds device information for use with chromedp.Emulate.
type Info struct {
// Name is the device name.
Name string
// UserAgent is the device user agent string.
UserAgent string
// Width is the viewport width.
Width int64
// Height is the viewport height.
Height int64
// Scale is the device viewport scale factor.
Scale float64
// Landscape indicates whether or not the device is in landscape mode or
// not.
Landscape bool
// Mobile indicates whether it is a mobile device or not.
Mobile bool
// Touch indicates whether the device has touch enabled.
Touch bool
}
// String satisfies fmt.Stringer.
func (i Info) String() string {
return i.Name
}
// Device satisfies chromedp.Device.
func (i Info) Device() Info {
return i
}
// infoType provides the enumerated device type.
type infoType int
// String satisfies fmt.Stringer.
func (i infoType) String() string {
return devices[i].String()
}
// Device satisfies chromedp.Device.
func (i infoType) Device() Info {
return devices[i]
}
`
<|start_filename|>js/submit.js<|end_filename|>
function submit() {
if (this.nodeName === 'FORM') {
HTMLFormElement.prototype.submit.call(this);
return true;
} else if (this.form !== null) {
HTMLFormElement.prototype.submit.call(this.form);
return true;
}
return false;
}
<|start_filename|>js/attribute.js<|end_filename|>
function attribute(n) {
return this[n];
}
<|start_filename|>js/text.js<|end_filename|>
function text() {
if (this.offsetWidth || this.offsetHeight || this.getClientRects().length) {
return this.innerText;
}
return '';
}
| knq/chromedp |
<|start_filename|>vendor/github.com/KeyTalk/keytalk-go/vendor/github.com/gonuts/commander/examples/my-cmd/cmd_subcmd1.go<|end_filename|>
package main
import (
"github.com/gonuts/commander"
"github.com/gonuts/flag"
)
var cmd_subcmd1 = &commander.Command{
UsageLine: "subcmd1 <command>",
Short: "subcmd1 subcommand. does subcmd1 thingies",
Subcommands: []*commander.Command{
cmd_subcmd1_cmd1,
cmd_subcmd1_cmd2,
},
Flag: *flag.NewFlagSet("my-cmd-subcmd1", flag.ExitOnError),
}
// EOF
<|start_filename|>openssl-1.0.2j/test/v3nametest.c<|end_filename|>
../crypto/x509v3/v3nametest.c
<|start_filename|>openssl-1.0.2j/include/openssl/asn1.h<|end_filename|>
../../crypto/asn1/asn1.h
<|start_filename|>openssl-1.0.2j/test/rmdtest.c<|end_filename|>
../crypto/ripemd/rmdtest.c
<|start_filename|>vendor/github.com/KeyTalk/keytalk-go/vendor/github.com/gonuts/commander/examples/my-cmd/cmd_cmd1.go<|end_filename|>
package main
import (
"fmt"
"github.com/gonuts/commander"
"github.com/gonuts/flag"
)
var cmd_cmd1 = &commander.Command{
Run: ex_run_cmd_cmd1,
UsageLine: "cmd1 [options]",
Short: "runs cmd1 and exits",
Long: `
runs cmd1 and exits.
ex:
$ my-cmd cmd1
`,
Flag: *flag.NewFlagSet("my-cmd-cmd1", flag.ExitOnError),
}
func init() {
cmd_cmd1.Flag.Bool("q", true, "only print error and warning messages, all other output will be suppressed")
}
func ex_run_cmd_cmd1(cmd *commander.Command, args []string) error {
name := "my-cmd-" + cmd.Name()
quiet := cmd.Flag.Lookup("q").Value.Get().(bool)
fmt.Printf("%s: hello from cmd1 (quiet=%v)\n", name, quiet)
return nil
}
// EOF
<|start_filename|>openssl-1.0.2j/test/mdc2test.c<|end_filename|>
../crypto/mdc2/mdc2test.c
<|start_filename|>openssl-1.0.2j/test/rsa_test.c<|end_filename|>
../crypto/rsa/rsa_test.c
<|start_filename|>openssl-1.0.2j/test/randtest.c<|end_filename|>
../crypto/rand/randtest.c
<|start_filename|>openssl-1.0.2j/test/casttest.c<|end_filename|>
../crypto/cast/casttest.c
<|start_filename|>vendor/github.com/KeyTalk/keytalk-go/vendor/github.com/gonuts/commander/examples/my-cmd/cmd_subcmd2.go<|end_filename|>
package main
import (
"github.com/gonuts/commander"
"github.com/gonuts/flag"
)
func ex_make_cmd_subcmd2() *commander.Command {
cmd := &commander.Command{
UsageLine: "subcmd2",
Short: "subcmd2 subcommand. does subcmd2 thingies (help list)",
List: commander.HelpTopicsList,
Subcommands: []*commander.Command{
ex_make_cmd_subcmd2_cmd1(),
ex_make_cmd_subcmd2_cmd2(),
},
Flag: *flag.NewFlagSet("my-cmd-subcmd2", flag.ExitOnError),
}
return cmd
}
// EOF
<|start_filename|>openssl-1.0.2j/include/openssl/bio.h<|end_filename|>
../../crypto/bio/bio.h
<|start_filename|>openssl-1.0.2j/include/openssl/pem2.h<|end_filename|>
../../crypto/pem/pem2.h
<|start_filename|>openssl-1.0.2j/include/openssl/pem.h<|end_filename|>
../../crypto/pem/pem.h
<|start_filename|>openssl-1.0.2j/test/ectest.c<|end_filename|>
../crypto/ec/ectest.c
<|start_filename|>vendor/github.com/KeyTalk/keytalk-go/vendor/github.com/gonuts/commander/examples/my-cmd/main.go<|end_filename|>
package main
import (
"fmt"
"os"
"github.com/gonuts/commander"
)
var g_cmd = &commander.Command{
UsageLine: os.Args[0] + " does cool things",
}
func init() {
g_cmd.Subcommands = []*commander.Command{
cmd_cmd1,
ex_make_cmd_cmd2(),
cmd_subcmd1,
ex_make_cmd_subcmd2(),
}
}
func main() {
err := g_cmd.Dispatch(os.Args[1:])
if err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
}
return
}
// EOF
<|start_filename|>openssl-1.0.2j/test/ideatest.c<|end_filename|>
../crypto/idea/ideatest.c
<|start_filename|>openssl-1.0.2j/include/openssl/hmac.h<|end_filename|>
../../crypto/hmac/hmac.h
<|start_filename|>openssl-1.0.2j/test/sha512t.c<|end_filename|>
../crypto/sha/sha512t.c | KeyTalk/goproxyclient |
<|start_filename|>pygraphblas/cdef/LAGraph/LAGraph_toc.c<|end_filename|>
//------------------------------------------------------------------------------
// LAGraph_toc: a portable timer for accurate performance measurements
//------------------------------------------------------------------------------
/*
LAGraph: graph algorithms based on GraphBLAS
Copyright 2019 LAGraph Contributors.
(see Contributors.txt for a full list of Contributors; see
ContributionInstructions.txt for information on how you can Contribute to
this project).
All Rights Reserved.
NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH
CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR
PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF
THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH
RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.
Released under a BSD license, please see the LICENSE file distributed with
this Software or contact <EMAIL> for full terms.
Created, in part, with funding and support from the United States
Government. (see Acknowledgments.txt file).
This program includes and/or can make use of certain third party source
code, object code, documentation and other files ("Third Party Software").
See LICENSE file for more details.
*/
//------------------------------------------------------------------------------
// LAGraph_toc: return the time since the last LAGraph_tic
// Contributed by <NAME>, Texas A&M
#include "LAGraph_internal.h"
double LAGraph_toc // returns time since last LAGraph_tic
(
const double tic [2] // tic from last call to LAGraph_tic
)
{
double toc [2] ;
LAGraph_tic (toc) ;
return ((toc [0] - tic [0]) + 1e-9 * (toc [1] - tic [1])) ;
}
<|start_filename|>pygraphblas/cdef/LAGraph/LAGraph_rand.c<|end_filename|>
//------------------------------------------------------------------------------
// LAGraph_rand: return a random number
//------------------------------------------------------------------------------
/*
LAGraph: graph algorithms based on GraphBLAS
Copyright 2019 LAGraph Contributors.
(see Contributors.txt for a full list of Contributors; see
ContributionInstructions.txt for information on how you can Contribute to
this project).
All Rights Reserved.
NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH
CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR
PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF
THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH
RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.
Released under a BSD license, please see the LICENSE file distributed with
this Software or contact <EMAIL> for full terms.
Created, in part, with funding and support from the United States
Government. (see Acknowledgments.txt file).
This program includes and/or can make use of certain third party source
code, object code, documentation and other files ("Third Party Software").
See LICENSE file for more details.
*/
//------------------------------------------------------------------------------
// LAGraph_rand: return a random number, contributed by <NAME>, Texas A&M.
// Modified from the POSIX-1.2001 example of rand.
// A simple thread-safe random number generator that returns a random number
// between 0 and LAGRAPH_RAND_MAX. The quality of the random values it
// generates is very low, but this is not important. This method is used to
// create random test matrices, which must be identical on any operating
// system.
#include "LAGraph_internal.h"
uint64_t LAGraph_rand (uint64_t *seed)
{
(*seed) = (*seed) * 1103515245 + 12345 ;
return (((*seed)/65536) % (LAGRAPH_RAND_MAX + 1)) ;
}
| szarnyasg/pygraphblas |
<|start_filename|>NavigationKit/NavigationKit.h<|end_filename|>
//
// NavigationKit.h
// NavigationKit
//
// Created by Salah on 8/26/20.
// Copyright © 2020 Salah. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for NavigationKit.
FOUNDATION_EXPORT double NavigationKitVersionNumber;
//! Project version string for NavigationKit.
FOUNDATION_EXPORT const unsigned char NavigationKitVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <NavigationKit/PublicHeader.h>
| salah-mohammed/NavigationK |
<|start_filename|>Makefile<|end_filename|>
miditones: miditones.c
gcc -O2 -Wall -o midi2tones midi2tones.c
clean:
rm -f midi2tones
| MLXXXp/miditones |
<|start_filename|>src/mp3.js<|end_filename|>
const fs = require('fs')
const progress = require('progress-stream')
const lame = require('lame')
module.exports = {
isMp3 (input) {
return typeof input === 'string' && hasMp3Extension(input) && isFileReadable(input)
function hasMp3Extension () {
return /\.mp3$/.test(input)
}
function isFileReadable () {
try {
fs.accessSync(input, fs.constants.R_OK)
return true
} catch (e) {
return false
}
}
},
getMp3Stream (filename, log) {
filename = fs.realpathSync(filename)
return fs.createReadStream(filename)
.pipe(progress(
{ time: 500, length: fs.statSync(filename).size },
progress => log(`Mp3 read stream: ${Math.round(progress.percentage)}%`)
))
.pipe(new lame.Decoder())
}
}
<|start_filename|>test/index.spec.js<|end_filename|>
/* global jest */
const { test, expect } = require('@jest/globals')
const createMusicStream = require('..')
const path = require('path')
const { Writable } = require('stream')
test.each([
['local_file', path.join(__dirname, '../track.mp3')],
['youtube', 'https://www.youtube.com/watch?v=QohH89Eu5iM']
])('load stream from %s', (sourceType, source, done) => {
const logFunc = jest.fn()
let receivedBytes = 0
const stream = createMusicStream(source, logFunc)
const myWritable = new Writable({
write (chunk, encoding, callback) {
// console.log(`Received ${chunk.length} bytes of data.`);
receivedBytes += chunk.length
callback()
},
final (callback) {
// console.log(`Eventually received ${receivedBytes} bytes of data.`)
expect(receivedBytes).toMatchSnapshot()
expect(logFunc).toHaveBeenCalled()
expect(receivedBytes).toBeGreaterThan(0)
done()
callback()
}
})
stream.pipe(myWritable)
}, 20 * 1000)
test('unable to handle', () => {
expect(() => createMusicStream('/tmp/not_found')).toThrow()
})
<|start_filename|>src/youtube.js<|end_filename|>
const ytdl = require('ytdl-core')
const ffmpeg = require('fluent-ffmpeg')
module.exports = {
isYoutube (input) {
return typeof input === 'string' && (ytdl.validateURL(input) || ytdl.validateID(input))
},
getYoutubeStream (videoID, log) {
const youtubeDownloader = ytdl(videoID, {
quality: 'highestaudio',
filter: 'audioonly'
})
return ffmpeg(youtubeDownloader)
.outputOptions([
'-f s16le',
'-acodec pcm_s16le',
'-vn',
'-ac 2',
'-ar 44100'
])
.on('progress', p => log(`Downloaded ${p.targetSize}kb`))
}
}
| chrvadala/create-music-stream |
<|start_filename|>docs/about.html<|end_filename|>
<html>
<head>
<title>About Jasmin</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<table>
<tr><td width=550>
<center>
<p><img src=jasmin_icon.jpg></p>
<p>
<div class="h1">ABOUT JASMIN</div>
<NAME>, July 1996
</p>
</center>
<h1>Introduction</h1>
This document tries to answer some questions you might have
about Jasmin. In particular, several people have asked me what
Jasmin is, why they might use Jasmin, and why I wrote it in the
first place. I've tried to give some answers to these questions
below.<p>
<h1>Jasmin Assembler</h1>
Jasmin is a Java Assembler Interface. It takes ASCII descriptions for Java
classes, written in a simple assembler-like syntax using the Java Virtual
Machine instructions set. It converts them into binary Java class files
suitable for loading into a Java interpreter.<p>
To give you a flavor, here is the Jasmin assembly code for HelloWorld:<p>
<pre>
.class public HelloWorld
.super java/lang/Object
;
; standard initializer (calls java.lang.Object's initializer)
;
.method public <init>()V
aload_0
invokenonvirtual java/lang/Object/<init>()V
return
.end method
;
; main() - prints out Hello World
;
.method public static main([Ljava/lang/String;)V
.limit stack 2 ; up to two items can be pushed
; push System.out onto the stack
getstatic java/lang/System/out Ljava/io/PrintStream;
; push a string onto the stack
ldc "Hello World!"
; call the PrintStream.println() method.
invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
; done
return
.end method
</pre>
<p>
Jasmin was originally created as a companion to the book "Java Virtual Machine",
written by <NAME> and <NAME> and published by O'Reilly Associates. The
book is now out of print. Jasmin survives as a SourceForge Open Source project.
</p>
<h1>Motivation for Jasmin</h1>
<p>
Jasmin was written because, at the time that we wrote the Java Virtual Machine
book for O'Reilly, Sun had not published an assembler format for the
Java virtual machine.
</p>
<p>
Generating a binary Java .class file is pretty fiddly. Its like
creating an a.out (or .exe) file by hand. Even using a Java package like
JAS (a Java API for creating class files, used internally by Jasmin and written by KB Sriram), you
need to know a lot about the philosophy of the Java Virtual
Machine before you can write something at the Virtual
Machine level and generate a Java class. <p>
We wanted something that made it very easy for a student or programmer
to explore the Java Virtual Machine, or write a new language
which targets the VM, without getting into the details of constant
pool indices, attribute tables, and so on.<p>
<p>
Creating a Java assembler seemed like a good solution.
</p>
<p>
Unfortunately, Sun has not seen the need to define a standard Java
assembler format, and has not released tools perform Java assembly.
</p>
<p>Sun does provide a javap program which can print the assembly code
in a class file. However, the javap output is inappropriate for
use as an assembler format. It is designed to be read by a person,
not to be parsed by an assembler, so it has a number of
omissions and drawbacks. </p>
<p>
Internally, Sun has a Java assembler tool. In hindsight, the syntax used by their internal tool is nicer than
the Jasmin syntax. However, to my knowledge, their tool is still not widely available, nor is it a formally
supported part of the Sun JDK.
</p>
<h1>Update on Jasmin Today (2004) </h1>
Since Jasmin was written, it has become the de-facto standard assembly format for Java. It is used in dozens of compiler classes throughout the world, and has
been ported and cloned multiple times. For better or worse, Jasmin remains the original Java assembler.
<p>
[As an interesting comparison, Microsoft .NET shipped out-of-box with an
assembler, a disassembler, a standard IL assembly format, and built-in libraries
for code-genning (generating classes on the fly). It would be great if Sun was
as comprehensive in their support of the JVM].
</p>
<h1>What can I do with Jasmin?</h1>
To give you some ideas, below are some theoretical Jasmin users/uses.<p>
<h3>Teachers</h3>
If you are teaching a compilers course, you could have students
write a compiler which generates Jasmin assembly files,
and then assembles those files into Java class files. Then you
can integrate the advantages of the Virtual Machine (portability,
the verifier, an object model...) into your courseware.<p>
<h3>Hobbyists</h3>
Jasmin lets you poke around in Java at the VM level, so that
you can gain a real understanding of how Java works and
what the Virtual Machine is like.<p>
<h3>System Implementors</h3>
If you are implementing a Java runtime system, Jasmin is
an essential tool for generating test classes.<p>
<h3>Advanced Programmers</h3>
You could use Jasmin to write a critical class or method by
hand (e.g. if you think that Java isn't doing things
as well as it could). <p>
Alternatively, you could create a syntax extension to the
Java language which uses Jasmin (or JAS). <p>
<h3>Language Implementors</h3>
If you want to create an implementation of your
favorite programming language which targets the
Virtual Machine, Jasmin may be a simpler approach than
writing a Java class file generator. This is especially
true if your compiler is implemented in something other
than Java, since you can create Java class files easily
without having to get involved in the details of the
binary file format.<p>
<h3>Security Wizards</h3>
Sun's claim that the Java class verifier protects you from
hostile programs is a pretty strong one. Jasmin lets you create
'hostile' class files and see if a Java implementation is really as
secure as it should be. <p>
<hr><address>Copyright (c) <NAME>, July 1996</address>
<hr>
<a href="http://jasmin.sourceforge.net">Jasmin Home</a> |
<a href="http://www.cybergrain.com/">Jon Meyer's Home</a>
<|start_filename|>docs/index.html<|end_filename|>
<html>
<head>
<title>Jasmin Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<table>
<tr><td width=550>
<center>
<p><img src=jasmin_icon.jpg></p>
<p>
<div class="h1">JASMIN HOME PAGE</div>
<NAME>, Oct 2004
</p>
</center>
<h1>Introduction</h1>
<p>
Jasmin is an assembler for the Java Virtual Machine. It takes
ASCII descriptions of Java classes, written in a simple
assembler-like syntax using the Java Virtual
Machine instruction set. It converts them into binary Java class files,
suitable for loading by a Java runtime system.<p>
</p>
<p>
Jasmin was originally created as a companion to the book "Java Virtual Machine",
written by <NAME> and <NAME> and published by O'Reilly Associates.
Since then, it has become the de-facto standard assembly format for Java. It is used in dozens of compiler classes throughout the world, and has
been ported and cloned multiple times. For better or worse, Jasmin remains the oldest and the original Java assembler.
</p>
<p>
The O'Reilly JVM book is now out of print. Jasmin continues to survive as a SourceForge Open Source project.
</p>
<h1>Documentation</h1>
<dl>
<dt>
<a href = "http://jasmin.sourceforge.net">Jasmin Home Page</a>
<dd>this file (on SourceForge.net).<p>
<dt>
<a href = "guide.html">Jasmin User Guide</a>
<dd>a brief user guide for using Jasmin.<p>
<dt><a href = "instructions.html">Jasmin Instructions</a>
<dd>the syntax of JVM instructions in Jasmin.<p>
<dt>
<a href = "about.html">About Jasmin</a>
<dd>describes the background to Jasmin, who might find it interesting, etc.
Includes an example piece of Jasmin assembler to look at.<p>
</dl>
<hr><address>Copyright (c) <NAME>, 2004</address>
<hr>
<a href="http://jasmin.sourceforge.net">Jasmin Home</a> |
<a href="http://www.cybergrain.com">Jon Meyer's Home</a>
</td></tr></table>
</body>
</html>
<|start_filename|>lib/java_cup/simple_calc/scanner.java<|end_filename|>
// Simple Example Scanner Class
import java_cup.runtime.*;
public class scanner {
/* single lookahead character */
protected static int next_char;
/* advance input by one character */
protected static void advance() throws java.io.IOException
{
next_char = System.in.read();
}
/* initialize the scanner */
public static void init() throws java.io.IOException { advance(); }
/* recognize and return the next complete token */
public static token next_token() throws java.io.IOException
{
for (;;)
switch (next_char)
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
/* parse a decimal integer */
int i_val = 0;
do {
i_val = i_val * 10 + (next_char - '0');
advance();
} while (next_char >= '0' && next_char <= '9');
return new int_token(sym.NUMBER, i_val);
case ';': advance(); return new token(sym.SEMI);
case '+': advance(); return new token(sym.PLUS);
case '-': advance(); return new token(sym.MINUS);
case '*': advance(); return new token(sym.TIMES);
case '/': advance(); return new token(sym.DIVIDE);
case '%': advance(); return new token(sym.MOD);
case '(': advance(); return new token(sym.LPAREN);
case ')': advance(); return new token(sym.RPAREN);
case -1: return new token(sym.EOF);
default:
/* in this simple scanner we just ignore everything else */
advance();
break;
}
}
};
<|start_filename|>src/main/java/jas/AnnotDefAttr.java<|end_filename|>
/**
* This attribute can associated with a method, field or class.
*
* @author $Author: <NAME> $
* @version $Revision: 1.0 $
*/
package jas;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;
public class AnnotDefAttr
{
static final CP attr = new AsciiCP("AnnotationDefault");
Annotation ann;
public AnnotDefAttr()
{ ann = new Annotation(); }
public Annotation get()
{ return(ann); }
void resolve(ClassEnv e)
{
e.addCPItem(attr);
ann.resolve(e);
}
void write(ClassEnv e, DataOutputStream out)
throws IOException, jasError
{
out.writeShort(e.getCPIndex(attr));
out.writeInt(ann.size());
ann.write(e, out);
}
}
<|start_filename|>src/main/java/jas/jasError.java<|end_filename|>
package jas;
/**
* Error thrown on problems encountered while running the
* basic jas assembler itself.
* @author $Author: jonmeyerny $
* @version $Revision: 1.1 $
*/
public class jasError extends Exception
{
public boolean numTag;
public jasError() { super(); numTag = false; }
public jasError(String s) { super(s); numTag = false; }
public jasError(String s, boolean isNum) { super(s); numTag = true; }
}
<|start_filename|>src/main/java/jas/TableswitchInsn.java<|end_filename|>
/**
* Some instructions are perniticky enough that its simpler
* to write them separately instead of smushing them with
* all the rest. The tableswitch instruction is one of them.
* @author $Author: jonmeyerny $
* @version $Revision: 1.1 $
*/
package jas;
import java.io.*;
public class TableswitchInsn extends Insn implements RuntimeConstants
{
/**
* @param min minimum index value
* @param max maximum index value
* @param def default Label for switch
* @param j array of Labels, one for each possible index.
*/
public TableswitchInsn(int min, int max, LabelOrOffset def, LabelOrOffset j[])
{
opc = opc_tableswitch;
operand = new TableswitchOperand(this, min, max, def, j);
}
}
<|start_filename|>docs/instructions.html<|end_filename|>
<html>
<head>
<title>Jasmin Instructions</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<table ID="Table1">
<tr><td width=550>
<center>
<p><img src=jasmin_icon.jpg></p>
<p>
<div class="h1">JASMIN INSTRUCTIONS</div>
<NAME>, July 1996
</p>
</center>
<h1>Introduction</h1>
This document shows the syntax and the types of parameters required by
each Java VM instruction in Jasmin. It also shows brief illustrative
examples.<p>
See <a href="guide.html">The Jasmin User Guide</a> for a description
of other aspects of the Jasmin syntax.<p>
<h1>Local variable instructions</h1>
The following instructions use local variables:<p>
<pre>
ret <var-num>
aload <var-num>
astore <var-num>
dload <var-num>
dstore <var-num>
fload <var-num>
fstore <var-num>
iload <var-num>
istore <var-num>
lload <var-num>
lstore <var-num>
</pre>
for example:<p>
<pre>
aload 1 ; push local variable 1 onto the stack
ret 2 ; return to the address held in local variable 2
</pre>
<h1>The bipush, sipush and iinc instructions</h1>
The bipush and sipush instructions take an integer as a
parameter:<p>
<pre>
bipush <int>
sipush <int>
</pre>
for example:<p>
<pre>
bipush 100 ; push 100 onto the stack
</pre>
The iinc instruction takes two integer parameters:<p>
<pre>
iinc <var-num> <amount>
</pre>
for example:<p>
<pre>
iinc 3 -10 ; subtract 10 from local variable 3
</pre>
<h1>Branch instructions</h1>
The following instructions take a label as a parameter:
<pre>
goto <label>
goto_w <label>
if_acmpeq <label>
if_acmpne <label>
if_icmpeq <label>
if_icmpge <label>
if_icmpgt <label>
if_icmple <label>
if_icmplt <label>
if_icmpne <label>
ifeq <label>
ifge <label>
ifgt <label>
ifle <label>
iflt <label>
ifne <label>
ifnonnull <label>
ifnull <label>
jsr <label>
jsr_w <label>
</pre>
For example:<p>
<pre>
Label1:
goto Label1 ; jump to the code at Label1
; (an infinite loop!)
</pre>
<h1>Class and object operations</h1>
The following instructions take a class name
as a parameter:
<pre>
anewarray <class>
checkcast <class>
instanceof <class>
new <class>
</pre>
For example:<p>
<pre>
new java/lang/String ; create a new String object
</pre>
<h1>Method invokation</h1>
The following instructions are used to invoke methods:<p>
<pre>
invokenonvirtual <method-spec>
invokestatic <method-spec>
invokevirtual <method-spec>
</pre>
for example:<p>
<pre>
; invokes java.io.PrintStream.println(String);
invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
</pre>
A method specification is formed of three parts: the characters before the
last '/' form the class name. The characters between the last '/' and '(' are
the method name. The rest of the string is the descriptor.<p>
<pre>
foo/baz/Myclass/myMethod(Ljava/lang/String;)V
--------------- ---------------------
| -------- |
| | |
class method descriptor
</pre>
A special case is invokeinterface, which takes a <method-spec> and
an integer indicating how many arguments the method takes:<p>
<pre>
invokeinterface <method-spec> <num-args>
</pre>
for example:<p>
<pre>
invokeinterface foo/Baz/myMethod(I)V 1
</pre>
<h1>Field manipulation instructions</h1>
The four instructions getfield, getstatic, putfield and
putstatic have the form:<p>
<pre>
getfield <field-spec> <descriptor>
getstatic <field-spec> <descriptor>
putfield <field-spec> <descriptor>
putstatic <field-spec> <descriptor>
</pre>
for example:
<pre>
; get java.lang.System.out, which is a PrintStream
getstatic java/lang/System/out Ljava/io/PrintStream;
</pre>
<field-spec> is composed of two parts, a classname and a fieldname. The
classname is all of the characters in the <field-spec> up to the last
'/' character, and the fieldname is the rest of the characters after the last
'/'. For example: <p>
<pre>
foo/baz/AnotherClass/anotherFunField
-- class name ------ --field name --
</pre>
<descriptor> is the Java type descriptor of the field.
For example:<p>
<pre>
Ljava/io/PrintStream;
</pre>
<h1>The newarray instruction</h1>
The newarray instruction is followed by the type of the array,<p>
<pre>
newarray <array-type>
</pre>
for example:<p>
<pre>
newarray int
newarray short
newarray float
etc.
</pre>
<h1>The multianewarray instruction</h1>
The multianewarray instruction takes two parameters,
the type descriptor for the array and the number of
dimensions to allocate:<p>
<pre>
multianewarray <array-descriptor> <num-dimensions>
</pre>
for example:<p>
<pre>
multianewarray [[[I 2
</pre>
<h1>The ldc and ldc_w instructions</h1>
The ldc and ldc_w instructions are followed by a constant:<p>
<pre>
ldc <constant>
ldc_w <constant>
</pre>
<constant> is either an integer, a floating point number, or a
quoted string. For example:<p>
<pre>
ldc 1.2 ; push a float
ldc 10 ; push an int
ldc "<NAME>" ; push a String
ldc_w 3.141592654 ; push PI as a double
</pre>
<h1>The lookupswitch instruction</h1>
The lookupswitch instruction has the syntax:<p>
<pre>
<lookupswitch> ::=
lookupswitch
<int1> : <label1>
<int2> : <label2>
...
default : <default-label>
</pre>
For example:<p>
<pre>
; If the int on the stack is 3, jump to Label1.
; If it is 5, jump to Label2.
; Otherwise jump to DefaultLabel.
lookupswitch
3 : Label1
5 : Label2
default : DefaultLabel
Label1:
... got 3
Label2:
... got 5
DefaultLabel:
... got something else
</pre>
<h1>The tableswitch instruction</h1>
The tableswitch instruction has the syntax:<p>
<pre>
<tableswitch> ::=
tableswitch <low>
<label1>
<label2>
...
default : <default-label>
</pre>
For example:<p>
<pre>
; If the int on the stack is 0, jump to Label1.
; If it is 1, jump to Label2.
; Otherwise jump to DefaultLabel.
tableswitch 0
Label1
Label2
default : DefaultLabel
Label1:
... got 0
Label2:
... got 1
DefaultLabel:
... got something else
</pre>
<h1>No parameter</h1>
The following instructions (the majority) take no parameters:<p>
<dl><dd>
aaload
aastore
aconst_null
aload_0
aload_1
aload_2
aload_3
areturn
arraylength
astore_0
astore_1
astore_2
astore_3
athrow
baload
bastore
breakpoint
caload
castore
d2f
d2i
d2l
dadd
daload
dastore
dcmpg
dcmpl
dconst_0
dconst_1
ddiv
dload_0
dload_1
dload_2
dload_3
dmul
dneg
drem
dreturn
dstore_0
dstore_1
dstore_2
dstore_3
dsub
dup
dup2
dup2_x1
dup2_x2
dup_x1
dup_x2
f2d
f2i
f2l
fadd
faload
fastore
fcmpg
fcmpl
fconst_0
fconst_1
fconst_2
fdiv
fload_0
fload_1
fload_2
fload_3
fmul
fneg
frem
freturn
fstore_0
fstore_1
fstore_2
fstore_3
fsub
i2d
i2f
i2l
iadd
iaload
iand
iastore
iconst_0
iconst_1
iconst_2
iconst_3
iconst_4
iconst_5
iconst_m1
idiv
iload_0
iload_1
iload_2
iload_3
imul
ineg
int2byte
int2char
int2short
ior
irem
ireturn
ishl
ishr
istore_0
istore_1
istore_2
istore_3
isub
iushr
ixor
l2d
l2f
l2i
ladd
laload
land
lastore
lcmp
lconst_0
lconst_1
ldiv
lload_0
lload_1
lload_2
lload_3
lmul
lneg
lor
lrem
lreturn
lshl
lshr
lstore_0
lstore_1
lstore_2
lstore_3
lsub
lushr
lxor
monitorenter
monitorexit
nop
pop
pop2
return
saload
sastore
swap
</dl>
for example:
<pre>
pop ; remove the top item from the stack
iconst_1 ; push 1 onto the stack
swap ; swap the top two items on the stack
</pre>
<hr><address>Copyright (c) <NAME>, July 1996</address>
<hr>
<a href="http://mrl.nyu.edu/meyer/jvm/jasmin.html">Jasmin Home</a> |
<a href="http://mrl.nyu.edu/meyer/">Jon Meyer's Home</a>
<|start_filename|>src/main/java/jas/Catchtable.java<|end_filename|>
/**
* This is used to make a table of catch handlers for a method.
* @author $Author: jonmeyerny $
* @version $Revision: 1.1 $
*/
package jas;
import java.io.*;
import java.util.*;
public class Catchtable
{
Vector entries;
public Catchtable() { entries = new Vector(); }
/**
* add an entry to the catch table
*/
public void addEntry(CatchEntry entry) { entries.addElement(entry); }
/**
* add an entry to the catch table
* @param start Label marking the beginning of the area
* where the catch table is active.
* @param end Label marking the end of the area where the
* table is active.
* @param handler Label marking the entrypoint into the
* exception handling routine.
* @param cat (usually a classCP) informing the VM to direct
* any exceptions of this (or its subclasses) to the handler.
*/
public void
addEntry(Label start, Label end, Label handler, CP cat)
{ addEntry(new CatchEntry(start, end, handler, cat)); }
public void
addEntry(int start, int end, int handler, CP cat)
{ addEntry(new CatchEntry(start, end, handler, cat)); }
void resolve(ClassEnv e)
{
for (Enumeration en=entries.elements(); en.hasMoreElements(); )
{
CatchEntry ce = (CatchEntry)(en.nextElement());
ce.resolve(e);
}
}
int size()
{ return (8*entries.size()); } // each entry is 8 bytes
void write(ClassEnv e, CodeAttr ce, DataOutputStream out)
throws IOException, jasError
{
out.writeShort(entries.size());
for (Enumeration en = entries.elements(); en.hasMoreElements();)
{
CatchEntry entry = (CatchEntry)(en.nextElement());
entry.write(e, ce, out);
}
}
}
<|start_filename|>src/main/java/java_cup/runtime/long_token.java<|end_filename|>
package java_cup.runtime;
/** This subclass of token represents symbols that need to maintain one
* long value as an attribute. It maintains that value in the public
* field int_val.
*
* @see java_cup.runtime.str_token
* @version last updated: 1/7/96
* @author <NAME>
*/
public class long_token extends token {
/** Full constructor. */
public long_token(int term_num, long lv)
{
/* super class does most of the work */
super(term_num);
long_val = lv;
}
/** Constructor with default value of 0. */
public long_token(int term_num)
{
this(term_num,0);
}
/** The stored long value. */
public long long_val;
};
<|start_filename|>docs/guide.html<|end_filename|>
<html>
<head>
<title>Jasmin User Guide</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<table>
<tr><td width=550>
<center>
<p><img src=jasmin_icon.jpg></p>
<p>
<div class="h1">JASMIN USER GUIDE</div>
<NAME>, July 1996
</p>
</center>
<h1>About This Document</h1>
This guide describes the rules and syntax used in Jasmin, and
how to run Jasmin. Note that this document doesn't
explain the Java Virtual Machine itself, or give syntax notes for
every instruction known to Jasmin. See the Java Virtual Machine specification
for more information on the JVM.<p>
<h1>What is Jasmin?</h1>
<p>
Jasmin is an assembler for the Java Virtual Machine. It takes
ASCII descriptions of Java classes, written in a simple
assembler-like syntax using the Java Virtual
Machine instruction set. It converts them into binary Java class files,
suitable for loading by a Java runtime system.<p>
</p>
<p>
Jasmin was originally created as a companion to the book "Java Virtual Machine",
written by <NAME> and <NAME> and published by O'Reilly Associates. The
book is now out of print. Jasmin survives as a SourceForge Open Source project.
</p>
<h1>Jasmin Design</h1>
<p>
Jasmin is designed as a simple assembler. It has a clean easy-to-learn
syntax with few bells and whistles. Where possible, Jasmin adopts a
one-to-one mapping between its syntax and the conventions followed by Java class files.
For example, package names in Jasmin are delimited with the '/' character
(e.g. "java/lang/String") used by the class file format, instead
of the '.' character (java.lang.String) used in the Java language.</p>
<p>
The Jasmin assembler does little compile-time processing or
checking of the input code. For example, it doesn't check that
classes you reference actually exist, or that your type descriptors are
well formed. Jasmin also lacks many of the feautures
found in full macro assemblers. For example, it doesn't
inline mathematical expressions, perform variable
substitutions, or support macros.</p>
<p>
On the other hand, using Jasmin you can quickly try out nearly
all of the features of the Java Virtual Machine, including
methods, fields, subroutines, exception handlers, and so on.
The Jasmin syntax is also readable and compact.</p>
<h1>Running Jasmin</h1>
<p>
The <code>jasmin.jar</code> file is an executable JAR file that runs Jasmin.
For example:</p>
<pre><strong> java -jar jasmin.jar myfile.j</strong></pre>
<p>assembles the file "myfile.j". Jasmin looks at the
<code>.class</code> directive contained in the file to
decide where to place the output class file. So if myfile.j starts
with:</p>
<pre>
.class mypackage/MyClass
</pre>
<p>then Jasmin will place the output class file "MyClass.class" in the
subdirectory "mypackage" of the current directory. It will create the
mypackage directory if it doesn't exist.</p>
<p>You can use the "-d" option to tell jasmin to place the output
in an alternative directory. For example,</p>
<pre><strong> java -jar jasmin.jar -d /tmp myfile.j </strong></pre>
<p>will place the output in /tmp/mypackage/MyClass.class.</p>
<p>Finally, you can use the "-g" option to tell Jasmin to include
line number information (used by debuggers) in the resulting
.class file. Jasmin will number the lines in the Jasmin source
file that JVM instructions appear on. Then, if an error occurs,
you can see what instruction in the Jasmin source caused the error.
Note that specifying "-g" causes any .line directives within the
Jasmin file to be ignored.
</p>
<h1>Statements</h1>
<p>Jasmin source files consists of a sequence of newline-separated statements.
There are three types of statement: </p>
<ul>
<li>directives
<li>instructions
<li>labels
</ul>
<p>
Directives and instructions can take <i>parameters</i>. These parameters
are placed on the same line as the directive or instruction,
separated by spaces.</p>
<h3>Directives</h3>
<p>
Directive statements are used to give Jasmin meta-level information.
Directive statements consist of a directive name, and then zero or more
parameters separated by spaces, then a newline.</p>
<p>
All directive names start with a "." character. The directives in Jasmin are:</p>
<pre>
.catch .class .end .field .implements .interface .limit .line
.method .source .super .throws .var
</pre>
<p>
Some example directive statements are:</p>
<pre>
.limit stack 10
.method public myMethod()V
.class Foo
</pre>
<p>
The parameters used by each directive are described in more detail
later in the document.</p>
<h3>Instructions</h3>
<p>
An instruction statement consists of an instruction name, zero or
more parameters separated by spaces, and a newline.</p>
<p>
Jasmin uses the standard mnemonics for JVM opcodes as instruction names.
For example, aload_1, bipush and iinc are all Jasmin instruction names.</p>
<p>
Here are some examples of instruction statements:</p>
<pre>
ldc "Hello World"
iinc 1 -1
bipush 10
</pre>
<p>
</p>See <a href="instructions.html">Jasmin Instructions</a> for more details on
the syntax of instructions in Jasmin.</p>
<h3>Labels</h3>
<p>
</p>A Jasmin label statement consists of a name followed by a ':', and a newline.
For example:</p>
<pre>
Foo:
Label:
</pre>
<p>Label names cannot start with a numeric digit, and cannot contain
any of the special characters:</p>
<pre>
= : . " -
</pre>
<p>
You cannot use directive names or instruction names as labels. Other
than that, there are few restrictions on label names.
For example, you could use the label:</p>
<pre>
#_1:
</pre>
<p>
Labels can only be used within method definitions. The names are
local to that method.</p>
<h1>The Jasmin Tokenizer</h1>
<p>
Jasmin tokenizes its input stream, splitting the stream into tokens
by looking for whitespace characters (spaces, tabs and newlines).
The tokenizer looks for:</p>
<ul>
<li>directive names
<li>instruction names
<li>labels
<li>comments
<li>type descriptor names
<li>class names
<li>numbers and quoted strings
<li>etc.
</ul>
<p>
The rules used by the tokenizer are described below:</p>
<h3>Comments</h3>
<p>
A comment is a token that starts with a ';' character, and
terminates with the newline character at the end of the line. </p>
<p>
Note that the semicolon must be preceded by a whitespace character (a space, tab, newline), i.e.
embedded semicolons are ignored. For example,</p>
<pre>
abc;def
</pre>
<p>
is treated as a single token "abc;def", and</p>
<pre>
Ljava/lang/String;
</pre>
<p>
is the token "Ljava/lang/String;", whereas</p>
<pre>
foo ; baz ding
</pre>
<p>
is the token "foo" followed by a comment "baz ding".</p>
<h3>Numbers and Strings</h3>
<p>
In Jasmin, only simple decimal and integer numeric formats are
recognized. Floats in scientific or exponent format are not yet
supported. Character codes and octal aren't currently supported either. This
means you can have:</p>
<pre>
1, 123, .25, 0.03, 0xA
</pre>
<p>
but not</p>
<pre>
1e-10, 'a', '\u123'
</pre>
<p>
Quoted strings are also very basic. The full range of
backslash escape sequences are not supported yet, although "\n" and "\t"
are.</p>
<h3>Class Names</h3>
<p></p>Class names in Jasmin should be written using the Java class file format
conventions, so java.lang.String becomes java/lang/String.</p>
<h3>Type Descriptors</h3>
<p>
Type information is also written as they appear in class files (e.g.
the descriptor I speficies an integer, [Ljava/lang/Thread; is an
array of Threads, etc.).</p>
<h3>Methods</h3>
<p>
Method names are specified using a single token, e.g.</p>
<pre>
java/io/PrintStream/println(Ljava/lang/String;)V
</pre>
<p>
is the method called "println" in the class java.io.PrintStream, which
has the type descriptor "(Ljava/lang/String;)V" (i.e. it takes a String
and returns no result). In general, a method specification
is formed of three parts: the characters before the last '/' form the class
name. The characters between the last '/' and '(' are the method name. The
rest of the string is the type descriptor for the method.</p>
<pre>
foo/baz/Myclass/myMethod(Ljava/lang/String;)V
--------------- ---------------------
| -------- |
| | |
class method descriptor
</pre>
<p>
As another example, you would call the Java method: </p>
<pre>
class mypackage.MyClass {
int foo(Object a, int b[]) { ... }
}
</pre>
<p>
using:</p>
<pre>
invokevirtual mypackage/MyClass/foo(Ljava/lang/Object;[I)I
</pre>
<h3>Fields</h3>
<p>
Field names are specified in Jasmin using two tokens, one giving the name
and class of the field, the other giving its descriptor. For example:</p>
<pre>
getstatic mypackage/MyClass/my_font Ljava/lang/Font;
</pre>
<p>
gets the value of the field called "my_font" in the class mypackage.MyClass.
The type of the field is "Ljava/lang/Font;" (i.e. a Font object).</p>
<h1>FILES</h1>
<p>
Jasmin files start by giving information on the class
being defined in the file - such as the name of the
class, the name of the source file that the class originated from,
the name of the superclass, etc.</p>
<p>
Typically, a Jasmin file starts with the three directives:</p>
<pre>
.source <source-file>
.class <access-spec> <class-name>
.super <class-name>
</pre>
<p>
For example, the file defining MyClass might start with the directives:</p>
<pre>
.source MyClass.j
.class public MyClass
.super java/lang/Object
</pre>
<h3>.source directive</h3>
<p>
The .source directive is optional. It specifies the
value of the "SourceFile" attribute for the class
file. (This is used by Java to print out debugging info
if something goes wrong in one of the methods in the class).
If you generated the Jasmin file automatically (e.g. as the result of
compiling a file written in another syntax) you should use the .source
directive to tell Java the name of the originating file. Note that
the source file name should not include any pathname. Use "foo.src"
but not "/home/user/foo.src".</p>
<p>
If no .source directive is given, the name of the Jasmin
file you are compiling is used instead as the SourceFile attribute
instead.</p>
<h3>.class and .super directives</h3>
<p>
The .class and .super directive tell the JVM the name of this
class and its superclass. These directives take parameters as
follows:
</p>
<dl>
<dt><class-name></dt>
<dd>is the full name of the class, including
any package names. For example foo/baz/MyClass.<p>
</dd>
<dt><access-spec></dt>
<dd>defines access permissions and other attributes for
the class. This is a list of zero or more of the following
keywords:<p>
<dl><dd>
public, final, super, interface, abstract
</dl>
</dl>
<h3>.interface directive</h3>
<p>
Note that, instead of using the directive .class,
you can alternatively use the directive .interface. This has
the same syntax as the .class directive, but indicates that the Jasmin file
is defining a Java interface. e.g.</p>
<pre>
.interface public foo
</pre>
<h3>.implements directive</h3>
<p>
After .source, .class and .super, you can list the
interfaces that are implemented by the class you are defining, using
the .implements directive. The syntax of .implements is:</p>
<pre>
.implements <class-name>
</pre>
<p>
where <class-name> has the same format as was used by .class and .super.
For example:</p>
<pre>
.class foo
.super java/lang/Object
.implements Edible
.implements java/lang/Throwable
</pre>
<h1>Field Definitions</h1>
<p>
After the header information, the next section of the Jasmin file
is a list of field definitions.</p>
<p>
A field is defined using the .field directive:</p>
<pre>
.field <access-spec> <field-name> <descriptor> [ = <value> ]
</pre>
<p>
where:</p>
<dl>
<dt><access-spec>
<dd>is one of the keywords:
<dl><dd>
public, private, protected, static, final,
volatile, transient
</dl>
</dl><p>
<dt><field-name>
<dd>is the name of the field.<p>
<dt><descriptor>
<dd>is its type descriptor.<p>
<dt><value>
<dd>is an integer, a quoted string or a decimal number, giving the
initial value of the field (for final fields).<p>
</dl>
<p>
For example, the Java field definition:</p>
<pre>
public int foo;
</pre>
<p>
becomes</p>
<pre>
.field public foo I
</pre>
<p>
whereas the constant:</p>
<pre>
public static final float PI = 3.14;
</pre>
<p>
becomes</p>
<pre>
.field public static final PI F = 3.14
</pre>
<h1>Method Definitions</h1>
<p>
After listing the fields of the class, the rest of the Jasmin file lists
methods defined by the class.</p>
<p>
A method is defined using the basic form:</p>
<pre>
.method <access-spec> <method-spec>
<statements>
.end method
</pre>
<p>
where:</p>
<dl>
<dt><access-spec>
<dd>is one of the keywords: public, private, protected, static, final,
synchronized, native, abstract<p>
<dt><method-spec>
<dd>is the name and type descriptor of the method.<p>
<dt><statements>
<dd>is the code defining the body of the method.<p>
</dl>
<p>
Method definitions cannot be nested. Also, Jasmin does not
insert an implicit 'return' instruction at the end of a method. It is
up to you to ensure that your methods return cleanly. So
the most basic Jasmin method is something like:</p>
<pre>
.method foo()V
return ; must give a return statement
.end method
</pre>
<h3>Method Directives</h3>
<p>
The following directives can be used only within method definitions:</p>
<dl>
<dt><pre>.limit stack <integer></pre><p>
<dd>Sets the maximum size of the operand stack
required by the method.
<dt><pre>.limit locals <integer></pre><p>
<dd>Sets the number of local variables
required by the method.
<dt><pre>.line <integer></pre><p>
<dd>This is used to tag the subsequent
instruction(s) with a line number. Debuggers use this information,
together with the name of the source file (see .source above)
to show at what line in a method things went wrong. If you are
generating Jasmin files by compiling a source file,
this directive lets you indicate what line
numbers in the source file produced corrosponding Jasmin
instructions. For example:
<pre>
.method foo()V
.line 5
bipush 10 // these instructions generated from line 5
istore_2 // of the source file.
.line 6
...
</pre>
<dt><pre>.var <var-number> is <name> <descriptor> from <label1> to <label2></pre><p>
<dd>The .var directive is used to define the name, type descriptor and scope of
a local variable number. This information is used by debuggers
so that they can be more helpful when printing out the values of local
variables (rather than printing just a local variable number, the
debugger can actually print out the name of the variable). For example:
<pre>
.method foo()V
.limit locals 1
; declare variable 0 as an "int Count;"
; whose scope is the code between Label1 and Label2
;
.var 0 is Count I from Label1 to Label2
Label1:
bipush 10
istore_0
Label2:
return
.end method
</pre>
<dt><pre>.throws <classname></pre><p>
<dd>Indicates that this method can throw
exceptions of the type indicated by <classname>.
e.g.
<pre>
.throws java/io/IOException
</pre>
This information isn't required by Java runtime systems,
but it is used by the Java compiler to check that methods
either catch exceptions they can cause, or declare
that they throw them.
<dt><pre>.catch <classname> from <label1> to <label2> using <label3></pre><p>
<dd>Appends an entry to the end of the exceptions table for the
method. The entry indicates that when an exception which is
an instance of <classname> or one of its subclasses is thrown
while executing the code between <label1> and <label2>, then
the runtime system should jump to <label3>. e.g.<p>
<pre>
.catch java/io/IOException from L1 to L2 using IO_Handler
</pre>
If classname is the keyword "all", then exceptions of any
class are caught by the handler.<p>
</dl>
<h3>Abstract Methods</h3>
<p>
To declare an abstract method, write a method with no body. e.g.</p>
<pre>
.method abstract myAbstract()V
.end method
</pre>
<p>
note that abstract methods can have .throws directives, e.g.</p>
<pre>
.method abstract anotherAbstract()V
.throws java/io/IOException
.end method
</pre>
<h1>Instructions</h1>
<p>
JVM instructions are placed between the <code>.method</code> and
<code>.end method</code> directives. VM instructions can take zero or more
parameters, depending on the type of instruction used. Some example
instructions are shown below:
</p>
<pre>
iinc 1 -3 ; decrement local variable 1 by 3
bipush 10 ; push the integer 10 onto the stack
pop ; remove the top item from the stack.
</pre>
<p>
See <a href="instructions.html">Jasmin Instructions</a> for more details on the syntax
of instructions in Jasmin.
</p>
<hr><address>Copyright (c) <NAME>, July 1996</address>
<hr>
<a href="http://jasmin.sourceforge.net">Jasmin Home</a> |
<a href="http://www.cybergrain.com">Jon Meyer's Home</a>
</td></tr></table>
</body>
</html>
<|start_filename|>src/main/java/jas/AnnotationElement.java<|end_filename|>
/**
* AnnotationElement are used by Annotation attributes
* @author $Author: <NAME> $
* @version $Revision: 1.0 $
*/
package jas;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;
public class AnnotationElement
{
private boolean array;
private char sign;
private CP name, exttype;
private Vector values;
private static final char type_int = 'I'; // integer
private static final char type_byte = 'B'; // signed byte
private static final char type_char = 'C'; // unicode character
private static final char type_short = 'S'; // signed short
private static final char type_bool = 'Z'; // boolean true or false
// end of int types
private static final char type_float = 'F'; // single precision IEEE foat
private static final char type_double = 'D'; // double precision IEEE float
private static final char type_long = 'J'; // long integer
//prefix
private static final char type_array = '[';
//annotation special
private static final char type_string = 's'; // constant string
private static final char type_class = 'c'; // return type descriptor
//complex types
private static final char type_enum = 'e'; // enum constant (type + name)
private static final char type_annot = '@'; // nested annotation
private static void badsignature() throws jasError
{ throw new jasError("invalid type signature for annotation field"); }
public AnnotationElement(String name, String type, String exttype)
throws jasError
{
this.name = null;
if(name != null) this.name = new AsciiCP(name);
values = new Vector();
array = false;
sign = type.charAt(0);
if(sign != type_array) {
if(type.length() != 1) badsignature();
} else {
array = true;
if(type.length() != 2) badsignature();
sign = type.charAt(1);
}
switch(sign) {
default:
badsignature();
case type_enum:
case type_annot:
if(exttype == null) badsignature();
this.exttype = new AsciiCP(exttype);
break;
case type_int:
case type_byte:
case type_char:
case type_short:
case type_bool:
case type_float:
case type_double:
case type_long:
case type_string:
case type_class:
if(exttype != null) badsignature();
this.exttype = null;
break;
}
}
void addValue(Object value) throws jasError
{
if(value == null) Annotation.ParserError();
if(!array && values.size() != 0)
throw new jasError("too many values for nonarray annotation field type");
CP cp = null;
switch(sign) {
case type_char:
case type_bool:
case type_byte:
case type_short:
case type_int:
if(value instanceof Integer) {
int val = ((Integer)value).intValue();
boolean badval = false;
switch(sign) {
case type_bool:
if(val < 0 || val > 1) badval = true;
break;
case type_char:
if(val < 0 || val > 0xFFFF) badval = true;
break;
case type_byte:
if(val < -128 || val > 127) badval = true;
case type_short:
if(val < -32768 || val > 32767) badval = true;
default: // type_int
break;
}
if(badval)
throw new jasError("annotation field value exceed range of type", true);
cp = new IntegerCP(val);
}
break;
case type_float:
if(value instanceof Float)
cp = new FloatCP(((Float)value).floatValue());
break;
case type_double:
if(value instanceof Double) {
cp = new DoubleCP(((Double)value).doubleValue());
} else if(value instanceof Float) {
cp = new DoubleCP(((Float)value).floatValue());
}
break;
case type_long:
if(value instanceof Long) {
cp = new LongCP(((Long)value).longValue());
} else if(value instanceof Integer) {
cp = new LongCP(((Integer)value).intValue());
}
break;
case type_string:
case type_class:
case type_enum:
if(value instanceof String)
cp = new AsciiCP((String)value);
break;
case type_annot:
if(value instanceof Annotation)
cp = (Annotation)value;
default:
break;
}
if(cp == null)
throw new jasError("incompatible value for annotation field type");
values.add(cp);
}
public AsciiCP nestType() throws jasError
{
if(sign != type_annot) Annotation.ParserError();
return((AsciiCP)exttype);
}
public void done() throws jasError
{
switch(values.size()) {
case 1:
return;
default:
if(array) return;
//pass thru
case 0:
Annotation.ParserError();
}
}
void resolve(ClassEnv e)
{
if(name != null) e.addCPItem(name);
if(sign == type_enum) e.addCPItem(exttype);
for(Enumeration en = values.elements(); en.hasMoreElements(); ) {
CP cp = ((CP)en.nextElement());
if(sign != type_annot) e.addCPItem(cp);
else cp.resolve(e);
}
}
int size() throws jasError
{
done();
int len;
if(sign == type_annot) {
len = values.size(); // tags
for(Enumeration en = values.elements(); en.hasMoreElements(); )
len += ((Annotation)en.nextElement()).size();
} else {
len = 1+2;
if(sign == type_enum) len += 2;
len *= values.size();
}
if(array) len += 1+2;
if(name != null) len += 2;
return(len);
}
void write(ClassEnv e, DataOutputStream out) throws IOException, jasError
{
done();
if(name != null) out.writeShort(e.getCPIndex(name));
if(array) {
out.writeByte(type_array);
out.writeShort((short)values.size());
}
short id = 0;
if(sign == type_enum) id = e.getCPIndex(exttype);
for(Enumeration en = values.elements(); en.hasMoreElements(); ) {
out.writeByte(sign);
CP cp = ((CP)en.nextElement());
switch(sign) {
case type_annot:
((Annotation)cp).write(e, out);
break;
case type_enum:
out.writeShort(id);
//pass thru
default:
out.writeShort(e.getCPIndex(cp));
break;
}
}
}
}
<|start_filename|>lib/java_cup/simple_calc/sym.java<|end_filename|>
//----------------------------------------------------
// The following code was generated by Java(tm) CUP v0.9d
// Sun Jan 07 17:10:10 EST 1996
//----------------------------------------------------
/** JavaCup generated class containing symbol constants. */
public class sym {
/* terminals */
static final int SEMI = 2;
static final int EOF = 0;
static final int DIVIDE = 6;
static final int NUMBER = 10;
static final int error = 1;
static final int MINUS = 4;
static final int TIMES = 5;
static final int LPAREN = 8;
static final int RPAREN = 9;
static final int MOD = 7;
static final int PLUS = 3;
};
<|start_filename|>src/main/java/jas/ConstAttr.java<|end_filename|>
/**
* This is typically used to represent a constant value for
* a field entry (as in static final int foo = 20).
*
* @author $Author: jonmeyerny $
* @version $Revision: 1.1 $
*/
package jas;
import java.io.*;
public class ConstAttr
{
static final CP attr = new AsciiCP("ConstantValue");
CP val;
/**
* Create a new constant attribute whose constant value
* is picked up from constant pool with the given entry.
* @param val Constant pool item whose value is associated
* with the constant value attribute
*/
public ConstAttr(CP val)
{ this.val = val; }
void resolve(ClassEnv e)
{
e.addCPItem(val);
e.addCPItem(attr);
}
void write(ClassEnv e, DataOutputStream out)
throws IOException, jasError
{
out.writeShort(e.getCPIndex(attr));
out.writeInt(2);
out.writeShort(e.getCPIndex(val));
}
}
<|start_filename|>src/main/java/jas/StackMap.java<|end_filename|>
/**
* @see StackMapAttr
* @see StackMapFrameAttr
* @author $Author: <NAME> $
* @author $Author: <NAME> $
* @version $Revision: 1.3 $
*/
package jas;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;
public class StackMap
{
static private final int JDK_SMF_MIN = 50;
static CP attr = null;
static boolean java6 = false;
protected Vector frames;
public static void reinit()
{ attr = null;
java6 = false; }
protected StackMap(CP attr)
{ this.attr = attr;
frames = new Vector(); }
public StackMap(ClassEnv e)
{
if(attr == null)
{
if(e.version_hi >= JDK_SMF_MIN) java6 = true;
attr = new AsciiCP(java6 ? "StackMapTable" : "StackMap");
}
frames = new Vector();
}
public void addFrame(VerifyFrame f)
{ frames.add(f); }
// get copy of previous locals frame (possible with choping)
public Vector getLastFrame(int count) throws jasError
{
if(frames.isEmpty())
return null;
return ((VerifyFrame)frames.lastElement()).getFrame(count);
}
// this method call BEFORE write method
public int size(ClassEnv e, CodeAttr ce)
{
try {
if(java6) shellSort(ce);
return write(e, ce, null);
} catch(IOException ex) {
System.err.println("UNEXPECTED IO EXCEPTION");
ex.printStackTrace();
} catch(jasError ex) {
System.err.println("UNEXPECTED JAS ERROR");
ex.printStackTrace();
}
return 0;
}
void resolve(ClassEnv e)
{ e.addCPItem(attr);
Enumeration en = frames.elements();
while(en.hasMoreElements())
((VerifyFrame)en.nextElement()).resolve(e);
}
int write(ClassEnv e, CodeAttr ce, DataOutputStream out)
throws IOException, jasError
{
// writing to a buffer first, so that we can print the length
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream bufout = new DataOutputStream(buf);
// not fully compliant to the CLDC spec !
bufout.writeShort(frames.size());
VerifyFrame prev = null; // prepare for StackMapFrameAttr
Enumeration en = frames.elements();
while(en.hasMoreElements())
{
VerifyFrame cur = (VerifyFrame)en.nextElement();
if(!java6) prev = cur; // as flag
cur.write(e, ce, bufout, prev);
prev = cur;
}
int len = buf.toByteArray().length;
if(out != null) // else, call for size calculation
{
out.writeShort(e.getCPIndex(attr));
out.writeInt(len);
buf.writeTo(out);
}
return (2 + 4) + len;
}
// sort (method of Shell) frames by offset (before writing)
// used for StackMapFrameAttr mode.
private void shellSort(CodeAttr ce) throws jasError
{
int n = frames.size();
if(--n <= 0) return;
int g = 3;
if(g > n) g = 1;
do {
int i = g;
do {
VerifyFrame tmp = (VerifyFrame)frames.elementAt(i);
int jn, j, ts = tmp.getOffset(ce);
for(j = i; j >= g; j = jn) {
jn = j - g;
VerifyFrame t1 = (VerifyFrame)frames.elementAt(jn);
if(t1.getOffset(ce) <= ts) break;
frames.setElementAt(t1, j);
}
frames.setElementAt(tmp, j);
}while(++i <= n);
}while((g /= 2) > 0);
}
}
/* --- Revision History ---------------------------------------------------
--- <NAME>, May 07 2010, reset java6-mode for new compiled file
*/
<|start_filename|>src/main/java/java_cup/runtime/int_token.java<|end_filename|>
package java_cup.runtime;
/** This subclass of token represents symbols that need to maintain one
* int value as an attribute. It maintains that value in the public
* field int_val.
*
* @see java_cup.runtime.str_token
* @version last updated: 11/25/95
* @author <NAME>
*/
public class int_token extends token {
/** Full constructor. */
public int_token(int term_num, int iv)
{
/* super class does most of the work */
super(term_num);
int_val = iv;
}
/** Constructor with default value of 0. */
public int_token(int term_num)
{
this(term_num,0);
}
/** The stored int value. */
public int int_val;
};
<|start_filename|>src/main/java/java_cup/runtime/char_token.java<|end_filename|>
package java_cup.runtime;
/** This subclass of token represents symbols that need to maintain one
* char value as an attribute. It maintains that value in the public
* field int_val.
*
* @see java_cup.runtime.str_token
* @version last updated: 1/7/96
* @author <NAME>
*/
public class char_token extends token {
/** Full constructor. */
public char_token(int term_num, char v)
{
/* super class does most of the work */
super(term_num);
char_val = v;
}
/** Constructor with default value of 0 */
public char_token(int term_num)
{
this(term_num, '\0');
}
/** The stored char value. */
public char char_val;
};
<|start_filename|>docs/html2x/xt.html<|end_filename|>
<html>
<head>
<title>Jasmin User Guide</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<table>
<tr><td width=550>
<center>
<p><img src=jasmin_icon.jpg></p>
<p>
<div class="h1">JasminXT Syntax</div>
<NAME>, Mart 2006
</p>
</center>
<h1>About This Document</h1>
This guide describes the rules and syntax used in JasminXT, the extension of
the Jasmin language in version 2.0. If you are new to Jasmin, you should
refer to the Jasmin user guide. Note that this document doesn't
explain the Java Virtual Machine itself, or give syntax notes for
every instruction known to Jasmin. See the Java Virtual Machine specification
for more information on the JVM.<p>
<h1>Why a new Jasmin language ?</h1>
<p>
Jasmin is the de-facto standard Java assembly language. It is useful to explore
the possibilities of bytecode, but it does not offer a real low level control
over the produced output. Therefore it is not suitable to generate test cases
for virtual machines or bytecode verifier. This new version of the Jasmin
language, called JasminXT, provides optional directives and other syntax
updates to have more control over the output and to stick with the latest
changes of the Java language.</p>
<p>JasminXT has been defined for the tinapoc project. The purpose of the tinapoc
project is to create a reliable Java reverse engineering toolkit. See the tinapoc
homepage for more information : <a href="http://tinapoc.sourceforge.net/">http://tinapoc.sourceforge.net/</a></p>
<h1>Summary of the new features</h1>
<p>
<b>Since 2.4 :</b><br>
<li> accept 'd'-suffix in float constant (no attempt cast to float)
<li> redesign to dynamic compiler class creation
<li> some cosmetic bugfixes
<br><br>
<b>Since 2.3 :</b><br>
<li> added 'wide'-aliases to two-face instructions
<br><br>
<b>Since 2.2 :</b><br>
<li> some bug fixes in the diagnostic
<li> added support for attribute StackMapTable (directive .stack) described in JDK1.6
<li> added keyword 'use' to directive .stack
<li> added support for \uXXXX escape sequence in the names (just as in the Java)
<li> instruction ldc_w always generates wide index
<li> changed syntaxes of the non-standard identifiers (or overloaded keywords), now it hasto be signgle quoted and can't be empty
<br><br>
<b>Since 2.1 :</b><br>
<li> some bug fixes with string and number parsing
<li> added support for \uXXXX escape sequences
<li> added support for access flags ACC_STRICT (fpstrict) and ACC_SYNTHETIC (synthetic)
<li> added signatures for local variables support
<li> several .debug directives are permitted
<li> added the invokedynamic instruction
<li> improved the syntax of the StackMap attribute (.stack directive)
<li> new command-line option -e to support different encodings
<li> added support for non-standard identifiers in double-quotes
<li> fields can now be defined on multiple lines
<li> new directives have been included : .inner, .attribute, .deprecated, .annotation
<br><br>
<b>Since 2.0 :</b><br><br>
<li>use of offsets for branch targets, local variable visibility and exception handlers. The offsets can either be absolute or relative :<br>
<pre>
goto 12 ; absolute offset : go to bytecode at offset 12
goto +5 ; relative offset : go 12 bytes forward
goto -8 ; relative offset : go 8 bytes backwards
</pre>
<li>the following access flags are now supported : ACC_ENUM, ACC_ANNOTATION, ACC_BRIDGE and ACC_VARARGS<br>
<li>the .bytecode directive has been added, to set the bytecode version in the class file.<br>
Example : <pre>.bytecode 49.0</pre><br>
<li>it is now possible to add a SourceDebugExtension attribute to the class with the following directive :<br>
<pre>.debug "some string here"</pre><br>
<li>same thing for the EnclosingMethod attribute :<br>
<pre>.enclosing method "some/package/Foo/someMethod(I)V"</pre><br>
<li>support for the Signature attribute (in the classes, methods and fields) :<br>
<pre>.signature "<my::own>Signature()"
.field myField Ljava/lang/String; signature "<my::own>Signature()"</pre><br>
<li>support for the StackMap attribute, using the .stack directive in a method definition<br>
<li>it is now possible to give the offset of an instruction before the instruction itself, like in the following code snippet :<br>
<pre>
0: aload_0
1: invokespecial java/lang/Object/<init>()V
4: aload_0
5: ldc2_w 3.14159
</pre>
</p>
<h1>JasminXT File Format</h1>
<p>
This new version is an extension of the existing Jasmin language, therefore old
Jasmin files should still compile correctly with newer versions of Jasmin.
JasminXT is supported by Jasmin 2.0 or higher. <b>Changes in Jasmin 2.4 are in bold.</b></p>
<p>
In the rest of this document, words between '[' and ']' are optional. The
syntax of a JasminXT file is the following :</p>
<pre>
<jas_file> {
<jasmin_header>
[<field>]*
[<method>]*
}
</pre>
<h1>JasminXT Header</h1>
<pre>
<jasmin_header> {
[.bytecode <x.y>]
[.source <sourcefile>]
<class_spec>
<super_spec>
<implements>
[.signature "<signature>"]
[.enclosing method <method_name>]
[.debug "<debug_source_extension>"]*
[.inner class [<access>] [<name>] [inner <classname>] [outer <name>]]*
[.inner interface [<access>] [<name>] [inner <classname>] [outer <name>]]*
}
example :
.bytecode 49.0
.source hello.j
.class hello
.super java/lang/Object
.signature "<my::own>Signature()"
.enclosing method foo/bar/Whatever/someMethod()</pre>
.debug "this string will be included in the SourceDebugExtension attribute"
.debug "this string too"
<p>The .bytecode directive sets the version of the bytecode in the class file.</p>
<p>The .signature directive, when used in the header of the Jasmin file, sets the
Signature attribute for the class (the argument is a string between double
quotes)</p>
<p>The .enclosing directive sets the EnclosingMethod attribute for the class. The
argument is a supposed to be a method name, but it can be any string between
double quotes.</p>
<p>The .debug directive sets the SourceDebugExtension attribute for the class (the
argument is also a string between double quotes)</p>
<h1>JasminXT Class, Super Class and Interfaces Definition</h1>
<pre>
<class_spec> {
.class <access_spec> <class_name>
}
</pre>
<p>where <access_spec> is any number of words taken from this list : public,
private, protected, static, final, synchronized, native, final, super,
interface, abstract, annotation, enum, bridge/volatile, transient/varargs</p>
<p>and <class_name> is the fully qualified internal form of the class, such as
my/package/MyClass</p><br>
<pre>
<super_spec> {
.super <class_name>
}
</pre>
<pre>
<implements> {
.implements <class_name>*
}
</pre>
<p>
The .super and .implements directives have not been modified in JasminXT<br>
The .implements directive can be repeated in order to implement multiple interfaces</p><br>
<h1>JasminXT Field Definition</h1>
<pre>
<field> {
.field <access_spec> <field_name> <descriptor> [signature <signature>]
[ = <value> ]
|
.field <access_spec> <field_name> <descriptor> [signature <signature>]
[ = <value> ]
[<field_attribute>]*
.end field
(...)
}
</pre>
<p>
If present, the Signature attribute will be set in the class file for this field with the given
quoted string as an argument.</p>
<pre>
<field_attribute> {
.deprecated
| .attribute <name> <file_name>
| .signature <signature>
| .annotation (...)
}
</pre>
(see below for the definition of the annotation and the attribute directives)
<p>examples :
<pre>.field enum myField Ljava/lang/String; signature "<my::own>Signature()" = "val"</pre>
<pre>.field static hello_string Ljava/lang/String;
.signature "mySignature"
.deprecated
.end field</pre>
</p>
<h1>JasminXT Method Definition</h1>
The general format of a method definition has not changed in JasminXT.
<pre>
<method> {
.method <access_spec> <method_name> <descriptor>
<statement>*
.end method
}
</pre>
<h1>JasminXT Method Statements</h1>
<pre>
<statement> {
.limit stack <integer>
| .limit locals <integer>
| .line <integer>
| .var <var_number> is <var_name> <descriptor> [signature <sign>] from <label1> to <label2>
| .var <var_number> is <var_name> <descriptor> [signature <sign>] from <offset1> to <offset2>
| .throws <classname>
| .catch <classname> from <label1> to <label2> using <label3>
| .catch <classname> from <offset1> to <offset2> using <offset3>
| .signature "<signature>"
| .stack
[offset {<pc> | <label>}]
[locals <verification_type> [<verification_arg>]]
(...)
[stack <verification_type> [<verification_arg>]]
(...)
.end stack
| .stack use [n] locals
(...)
.end stack
| <instruction> [<instruction_args>]
| <Label>:
| .deprecated
| <generic> ; see below for the use of generic attributes
}
</pre>
<p>
In Jasmin XT you can now use offsets instead of labels for the local variable
definitions and for the exception handlers definitions.</p>
<p>The .signature sets the Signature attribute for this method with the given
quoted string.<p>
<p>You can now also define StackMap (or StackMapTable) attributes using
the .stack directive. <pc> is an offset in the local bytecode array.
<verification_type> is one of the following keywords : Top, Integer,
Float, Long, Double, Null, UninitializedThis, Object or Uninitialized. Object
takes a <classname> as a parameter. Uninitialized takes an integer or a
label as a parameter. Also, jasmin allows to use "short" notation. The
'.stack use [n] locals' directive results in copy first <n> values from
previous .stack directive. If <n> is omitted, all values are copied.</p>
<p>NOTE: If bytecode version is 50 or above jasmin generates StackMapTable
attribute in accordance with specification of the new 'ClassFile Format'
edition. If bytecode version is 49 or below jasmin generate StakMap attribute
in accordance with CLDC specification.<p>
examples :
<pre>
.stack
offset 16
locals Null
locals Top
locals Object allo
stack Uninitialized 12
.end stack
.stack
; offset is not specified, the offset of the current opcode will be used
locals Null
locals Top
locals Object allo
stack Uninitialized Label0
.end stack
</pre>
<p>
This statement defines a single stack map frame. All the stack map frames
defined in a method are then aggregated and form the StackMap attribute for the
method. The last example my be wrote at the short notation as:</p>
<pre>
.stack use locals
stack Uninitialized Label0
.end stack
</pre>
<p>
<h1>JasminXT Instructions</h1>
<pre>
<instruction> {
[<pc>:] <opcode> [<instruction_args>]
}
</pre>
<p>
The main change in JasminXT is that it is now possible to put the offset of the
instruction before the opcode (the <pc>: statement). The pc is processed as a
label, therefore you can virtually put any number as the pc but it won't change
the actual pc of the bytecode.</p>
<p>
Another update is that it is now possible to use offsets (both relative and
absolute) as branch targets instead of labels. The offset is considered to be
relative if it begins with '$+' or '$-'.</p>
example :
<pre>
goto n ; absolute offset : go to the bytecode labelled n
goto $+n ; relative offset : go n bytes forward (from the offset of this goto)
goto $-n ; relative offset : go n bytes backwards
</pre>
<p>
If something hasn't been documented here, it means that it hasn't changed, so
you can still refer to the Jasmin <a href="guide.html">user guide</a></p>
<p>
<b>Added '_w' aliase to [adfli]-load/store, iinc and ret instructions (e.g. aload - aload_w).
Using '_w' postfix guarantees wide-form of byte-code generation</b></p>
<h1>Generic Attributes</h1>
Generic attributes are supported in class/field/method definitions as follows :
<pre><generic> = {
.attribute <name> <file_name>
}</pre>
<name> is the name of the attribute and <file_name> is the name of the file containing the data of the attribute (between double quotes). If the generic attribute is in the body of the method, the following logic is used : if it is the first statement in the method, the attribute will be added as a method attribute, otherwise it will be added as a Code attribute.
<h1>Annotations</h1>
Thanks to <NAME> for implementing this. Here are his explanations :<br>
<p>Added a new directive .annotation to create the AnnotationDefault,
RuntimeVisibleAnnotation, RuntimeInvisibleAnnotation,
RuntimeVisibeParameterAnnotation, RuntimeInvisibleParameterAnnotation
attributes. The directive arguments are verified to have valid values
and correct signatures.<br>
Complex (nested) annotations are supported as well as arrays of them.<br>
The generic format is:
<pre>
<annotation> = {
.annotation visible <classname>
| .annotation invisible <classname>>
| .annotation visibleparam <paramnum> <classname>
| .annotation invisibleparam <paramnum> <classname>
| .annotation default
........
.end annotation
Field format (except AnnotationDefault):
<name> <signchar> = <value>*
| <name> @ = .annotation
........
.end annotation
}
</pre>
AnnotationDefault supports only one field and the <name> tag is not used.
Nested annotations must be with the <name> tag and can have any number
of fields. Besides, 'empty annotation' is forbidden for AnnotationDefault.
Lastly, AnnotationDefault can be used only once for each method.
Other annotation types can be used many times and will accumulate information.</p>
<hr><address>Copyright (c) <NAME>, Mart 2006</address>
<hr>
<a href="http://jasmin.sourceforge.net">Jasmin Home</a>
</td></tr></table>
</body>
</html>
<|start_filename|>lib/java_cup/simple_calc/Main.java<|end_filename|>
public class Main {
public static void main(String argv[])
{
try {
/* allocate a parser object */
parser parse_obj = new parser();
/* prompt the user */
System.out.println("Reading expressions from standard input...");
/* deterimine if we doing debug or normal parse, and do it */
if (argv.length >= 1 && argv[0].equals("-debug"))
{
parse_obj.debug_parse();
}
else
{
parse_obj.parse();
}
} catch (java.lang.Exception ex) {
System.err.println("Exception: " + ex.getMessage());
ex.printStackTrace();
System.exit(-1);
}
}
};
<|start_filename|>src/main/java/jas/AnnotParamAttr.java<|end_filename|>
/**
* This attribute can associated with a method, field or class.
*
* @author $Author: <NAME> $
* @version $Revision: 1.0 $
*/
package jas;
import java.io.*;
import java.util.Vector;
import java.util.Enumeration;
public class AnnotParamAttr
{
CP attr;
Vector anns; // Vector<Vector<Annotation>>
public AnnotParamAttr(boolean visible)
{
attr = new AsciiCP(visible ? "RuntimeVisibleParameterAnnotations" :
"RuntimeInvisibleParameterAnnotations");
anns = new Vector();
}
public void add(Annotation annotation, int paramnum)
{
Vector ap = null;
int top = anns.size();
if(paramnum < top) ap = (Vector)anns.elementAt(paramnum);
if(ap == null) {
if(paramnum >= top) anns.setSize(paramnum+1);
anns.set(paramnum, ap = new Vector());
}
ap.add(annotation);
}
void resolve(ClassEnv e)
{
e.addCPItem(attr);
for(int i = 0, top = anns.size(); i < top; i++) {
Vector ap = (Vector)anns.elementAt(i);
if(ap == null) continue;
for(Enumeration en = ap.elements(); en.hasMoreElements(); )
((Annotation)en.nextElement()).resolve(e);
}
}
void write(ClassEnv e, DataOutputStream out)
throws IOException, jasError
{
out.writeShort(e.getCPIndex(attr));
int top = anns.size(), len = 1 + 2*top;
for(int i = 0; i < top; i++) {
Vector ap = (Vector)anns.elementAt(i);
if(ap != null)
for(Enumeration en = ap.elements(); en.hasMoreElements(); )
len += ((Annotation)en.nextElement()).size();
}
out.writeInt(len);
out.writeByte((byte)top);
for(int i = 0; i < top; i++) {
Vector ap = (Vector)anns.elementAt(i);
if(ap == null) out.writeShort(0);
else {
out.writeShort((short)ap.size());
for(Enumeration en = ap.elements(); en.hasMoreElements(); )
((Annotation)en.nextElement()).write(e, out);
}
}
}
}
<|start_filename|>lib/jas/examples/simple.java<|end_filename|>
import jas.*;
import java.io.*;
import sun.tools.java.RuntimeConstants;
//
// This is program that makes calls into the jas package
// to generate a class that does nothing at all.
//
class simple implements RuntimeConstants
{
public static void main(String argv[])
throws jasError, IOException
{
// CodeAttr's contain the body of
// a method.
CodeAttr init = new CodeAttr();
init.addInsn(new Insn(opc_aload_0));
init.addInsn(new Insn(opc_invokenonvirtual,
new MethodCP("java/lang/Object", "<init>", "()V")));
init.addInsn(new Insn(opc_return));
// ClassEnv's are used as a container
// to hold all information about a class.
ClassEnv nclass = new ClassEnv();
nclass.setClass(new ClassCP("out"));
nclass.setSuperClass(new ClassCP("java/lang/Object"));
// Add the init code to the class.
nclass.addMethod((short)ACC_PUBLIC, "<init>", "()V", init, null);
// write it all out
nclass.write(new DataOutputStream
(new FileOutputStream("out.class")));
}
}
<|start_filename|>src/main/java/jasmin/InsnInfo.java<|end_filename|>
/* --- Copyright <NAME> 1997. All rights reserved. -----------------
> File: jasmin/src/jasmin/InsnInfo.java
> Purpose: Information about instructions (opcode, type of args, etc)
> Author: <NAME>, 8 Feb 1996
*/
//
// InsnInfo is used to hold info about the opcode and parameters needed
// by an instruction. Instances of InsnInfo are created by a static
// initializer and stored in a table.
//
package jasmin;
import jas.RuntimeConstants;
import java.util.Hashtable;
class InsnInfo {
// maps instruction name -> InsnInfo object
private static Hashtable infoTable;
// information maintained about each instruction:
public String name; // instruction name
public int opcode; // its opcode
public String args; // the argument code
public static InsnInfo get(String name) {
return (InsnInfo)infoTable.get(name);
}
public static boolean contains(String name) {
return infoTable.get(name) != null;
}
//
// used to initialize the infoTable table (see below)
//
static private void addInfo(String name, int opcode, String args) {
InsnInfo info = new InsnInfo();
info.name = name;
info.opcode = opcode;
info.args = args;
infoTable.put(name, info);
}
//
// initializes the infoTable table
//
static {
infoTable = new Hashtable();
addInfo("aaload", RuntimeConstants.opc_aaload, "");
addInfo("aastore", RuntimeConstants.opc_aastore, "");
addInfo("aconst_null", RuntimeConstants.opc_aconst_null, "");
addInfo("aload", RuntimeConstants.opc_aload, "i");
addInfo("aload_w", RuntimeConstants.opc_aload, "I");
addInfo("aload_0", RuntimeConstants.opc_aload_0, "");
addInfo("aload_1", RuntimeConstants.opc_aload_1, "");
addInfo("aload_2", RuntimeConstants.opc_aload_2, "");
addInfo("aload_3", RuntimeConstants.opc_aload_3, "");
addInfo("anewarray", RuntimeConstants.opc_anewarray, "class");
addInfo("areturn", RuntimeConstants.opc_areturn, "");
addInfo("arraylength", RuntimeConstants.opc_arraylength, "");
addInfo("astore", RuntimeConstants.opc_astore, "i");
addInfo("astore_w", RuntimeConstants.opc_astore, "I");
addInfo("astore_0", RuntimeConstants.opc_astore_0, "");
addInfo("astore_1", RuntimeConstants.opc_astore_1, "");
addInfo("astore_2", RuntimeConstants.opc_astore_2, "");
addInfo("astore_3", RuntimeConstants.opc_astore_3, "");
addInfo("athrow", RuntimeConstants.opc_athrow, "");
addInfo("baload", RuntimeConstants.opc_baload, "");
addInfo("bastore", RuntimeConstants.opc_bastore, "");
addInfo("bipush", RuntimeConstants.opc_bipush, "i");
addInfo("breakpoint", RuntimeConstants.opc_breakpoint, "");
addInfo("caload", RuntimeConstants.opc_caload, "");
addInfo("castore", RuntimeConstants.opc_castore, "");
addInfo("checkcast", RuntimeConstants.opc_checkcast, "class");
addInfo("d2f", RuntimeConstants.opc_d2f, "");
addInfo("d2i", RuntimeConstants.opc_d2i, "");
addInfo("d2l", RuntimeConstants.opc_d2l, "");
addInfo("dadd", RuntimeConstants.opc_dadd, "");
addInfo("daload", RuntimeConstants.opc_daload, "");
addInfo("dastore", RuntimeConstants.opc_dastore, "");
addInfo("dcmpg", RuntimeConstants.opc_dcmpg, "");
addInfo("dcmpl", RuntimeConstants.opc_dcmpl, "");
addInfo("dconst_0", RuntimeConstants.opc_dconst_0, "");
addInfo("dconst_1", RuntimeConstants.opc_dconst_1, "");
addInfo("ddiv", RuntimeConstants.opc_ddiv, "");
addInfo("dload", RuntimeConstants.opc_dload, "i");
addInfo("dload_w", RuntimeConstants.opc_dload, "I");
addInfo("dload_0", RuntimeConstants.opc_dload_0, "");
addInfo("dload_1", RuntimeConstants.opc_dload_1, "");
addInfo("dload_2", RuntimeConstants.opc_dload_2, "");
addInfo("dload_3", RuntimeConstants.opc_dload_3, "");
addInfo("dmul", RuntimeConstants.opc_dmul, "");
addInfo("dneg", RuntimeConstants.opc_dneg, "");
addInfo("drem", RuntimeConstants.opc_drem, "");
addInfo("dreturn", RuntimeConstants.opc_dreturn, "");
addInfo("dstore", RuntimeConstants.opc_dstore, "i");
addInfo("dstore_w", RuntimeConstants.opc_dstore, "I");
addInfo("dstore_0", RuntimeConstants.opc_dstore_0, "");
addInfo("dstore_1", RuntimeConstants.opc_dstore_1, "");
addInfo("dstore_2", RuntimeConstants.opc_dstore_2, "");
addInfo("dstore_3", RuntimeConstants.opc_dstore_3, "");
addInfo("dsub", RuntimeConstants.opc_dsub, "");
addInfo("dup", RuntimeConstants.opc_dup, "");
addInfo("dup2", RuntimeConstants.opc_dup2, "");
addInfo("dup2_x1", RuntimeConstants.opc_dup2_x1, "");
addInfo("dup2_x2", RuntimeConstants.opc_dup2_x2, "");
addInfo("dup_x1", RuntimeConstants.opc_dup_x1, "");
addInfo("dup_x2", RuntimeConstants.opc_dup_x2, "");
addInfo("f2d", RuntimeConstants.opc_f2d, "");
addInfo("f2i", RuntimeConstants.opc_f2i, "");
addInfo("f2l", RuntimeConstants.opc_f2l, "");
addInfo("fadd", RuntimeConstants.opc_fadd, "");
addInfo("faload", RuntimeConstants.opc_faload, "");
addInfo("fastore", RuntimeConstants.opc_fastore, "");
addInfo("fcmpg", RuntimeConstants.opc_fcmpg, "");
addInfo("fcmpl", RuntimeConstants.opc_fcmpl, "");
addInfo("fconst_0", RuntimeConstants.opc_fconst_0, "");
addInfo("fconst_1", RuntimeConstants.opc_fconst_1, "");
addInfo("fconst_2", RuntimeConstants.opc_fconst_2, "");
addInfo("fdiv", RuntimeConstants.opc_fdiv, "");
addInfo("fload", RuntimeConstants.opc_fload, "i");
addInfo("fload_w", RuntimeConstants.opc_fload, "I");
addInfo("fload_0", RuntimeConstants.opc_fload_0, "");
addInfo("fload_1", RuntimeConstants.opc_fload_1, "");
addInfo("fload_2", RuntimeConstants.opc_fload_2, "");
addInfo("fload_3", RuntimeConstants.opc_fload_3, "");
addInfo("fmul", RuntimeConstants.opc_fmul, "");
addInfo("fneg", RuntimeConstants.opc_fneg, "");
addInfo("frem", RuntimeConstants.opc_frem, "");
addInfo("freturn", RuntimeConstants.opc_freturn, "");
addInfo("fstore", RuntimeConstants.opc_fstore, "i");
addInfo("fstore_w", RuntimeConstants.opc_fstore, "I");
addInfo("fstore_0", RuntimeConstants.opc_fstore_0, "");
addInfo("fstore_1", RuntimeConstants.opc_fstore_1, "");
addInfo("fstore_2", RuntimeConstants.opc_fstore_2, "");
addInfo("fstore_3", RuntimeConstants.opc_fstore_3, "");
addInfo("fsub", RuntimeConstants.opc_fsub, "");
addInfo("getfield", RuntimeConstants.opc_getfield, "field");
addInfo("getstatic", RuntimeConstants.opc_getstatic, "field");
addInfo("goto", RuntimeConstants.opc_goto, "label");
addInfo("goto_w", RuntimeConstants.opc_goto_w, "label");
addInfo("i2d", RuntimeConstants.opc_i2d, "");
addInfo("i2f", RuntimeConstants.opc_i2f, "");
addInfo("i2l", RuntimeConstants.opc_i2l, "");
addInfo("iadd", RuntimeConstants.opc_iadd, "");
addInfo("iaload", RuntimeConstants.opc_iaload, "");
addInfo("iand", RuntimeConstants.opc_iand, "");
addInfo("iastore", RuntimeConstants.opc_iastore, "");
addInfo("iconst_0", RuntimeConstants.opc_iconst_0, "");
addInfo("iconst_1", RuntimeConstants.opc_iconst_1, "");
addInfo("iconst_2", RuntimeConstants.opc_iconst_2, "");
addInfo("iconst_3", RuntimeConstants.opc_iconst_3, "");
addInfo("iconst_4", RuntimeConstants.opc_iconst_4, "");
addInfo("iconst_5", RuntimeConstants.opc_iconst_5, "");
addInfo("iconst_m1", RuntimeConstants.opc_iconst_m1, "");
addInfo("idiv", RuntimeConstants.opc_idiv, "");
addInfo("if_acmpeq", RuntimeConstants.opc_if_acmpeq, "label");
addInfo("if_acmpne", RuntimeConstants.opc_if_acmpne, "label");
addInfo("if_icmpeq", RuntimeConstants.opc_if_icmpeq, "label");
addInfo("if_icmpge", RuntimeConstants.opc_if_icmpge, "label");
addInfo("if_icmpgt", RuntimeConstants.opc_if_icmpgt, "label");
addInfo("if_icmple", RuntimeConstants.opc_if_icmple, "label");
addInfo("if_icmplt", RuntimeConstants.opc_if_icmplt, "label");
addInfo("if_icmpne", RuntimeConstants.opc_if_icmpne, "label");
addInfo("ifeq", RuntimeConstants.opc_ifeq, "label");
addInfo("ifge", RuntimeConstants.opc_ifge, "label");
addInfo("ifgt", RuntimeConstants.opc_ifgt, "label");
addInfo("ifle", RuntimeConstants.opc_ifle, "label");
addInfo("iflt", RuntimeConstants.opc_iflt, "label");
addInfo("ifne", RuntimeConstants.opc_ifne, "label");
addInfo("ifnonnull", RuntimeConstants.opc_ifnonnull, "label");
addInfo("ifnull", RuntimeConstants.opc_ifnull, "label");
addInfo("iinc", RuntimeConstants.opc_iinc, "ii");
addInfo("iinc_w", RuntimeConstants.opc_iinc, "Ii");
addInfo("iload", RuntimeConstants.opc_iload, "i");
addInfo("iload_w", RuntimeConstants.opc_iload, "I");
addInfo("iload_0", RuntimeConstants.opc_iload_0, "");
addInfo("iload_1", RuntimeConstants.opc_iload_1, "");
addInfo("iload_2", RuntimeConstants.opc_iload_2, "");
addInfo("iload_3", RuntimeConstants.opc_iload_3, "");
addInfo("imul", RuntimeConstants.opc_imul, "");
addInfo("ineg", RuntimeConstants.opc_ineg, "");
addInfo("instanceof", RuntimeConstants.opc_instanceof, "class");
addInfo("int2byte", RuntimeConstants.opc_int2byte, "");
addInfo("int2char", RuntimeConstants.opc_int2char, "");
addInfo("int2short", RuntimeConstants.opc_int2short, "");
// added this synonym
addInfo("i2b", RuntimeConstants.opc_int2byte, "");
// added this synonym
addInfo("i2c", RuntimeConstants.opc_int2char, "");
// added this synonym
addInfo("i2s", RuntimeConstants.opc_int2short, "");
addInfo("invokedynamic", RuntimeConstants.opc_invokedynamic, "method");
addInfo("invokeinterface", RuntimeConstants.opc_invokeinterface, "interface");
addInfo("invokenonvirtual", RuntimeConstants.opc_invokenonvirtual, "method");
// added this synonym
addInfo("invokespecial", RuntimeConstants.opc_invokenonvirtual, "method");
addInfo("invokestatic", RuntimeConstants.opc_invokestatic, "method");
addInfo("invokevirtual", RuntimeConstants.opc_invokevirtual, "method");
addInfo("ior", RuntimeConstants.opc_ior, "");
addInfo("irem", RuntimeConstants.opc_irem, "");
addInfo("ireturn", RuntimeConstants.opc_ireturn, "");
addInfo("ishl", RuntimeConstants.opc_ishl, "");
addInfo("ishr", RuntimeConstants.opc_ishr, "");
addInfo("istore", RuntimeConstants.opc_istore, "i");
addInfo("istore_w", RuntimeConstants.opc_istore, "I");
addInfo("istore_0", RuntimeConstants.opc_istore_0, "");
addInfo("istore_1", RuntimeConstants.opc_istore_1, "");
addInfo("istore_2", RuntimeConstants.opc_istore_2, "");
addInfo("istore_3", RuntimeConstants.opc_istore_3, "");
addInfo("isub", RuntimeConstants.opc_isub, "");
addInfo("iushr", RuntimeConstants.opc_iushr, "");
addInfo("ixor", RuntimeConstants.opc_ixor, "");
addInfo("jsr", RuntimeConstants.opc_jsr, "label");
addInfo("jsr_w", RuntimeConstants.opc_jsr_w, "label");
addInfo("l2d", RuntimeConstants.opc_l2d, "");
addInfo("l2f", RuntimeConstants.opc_l2f, "");
addInfo("l2i", RuntimeConstants.opc_l2i, "");
addInfo("ladd", RuntimeConstants.opc_ladd, "");
addInfo("laload", RuntimeConstants.opc_laload, "");
addInfo("land", RuntimeConstants.opc_land, "");
addInfo("lastore", RuntimeConstants.opc_lastore, "");
addInfo("lcmp", RuntimeConstants.opc_lcmp, "");
addInfo("lconst_0", RuntimeConstants.opc_lconst_0, "");
addInfo("lconst_1", RuntimeConstants.opc_lconst_1, "");
addInfo("ldc", RuntimeConstants.opc_ldc, "constant");
addInfo("ldc_w", RuntimeConstants.opc_ldc_w, "constant");
addInfo("ldc2_w", RuntimeConstants.opc_ldc2_w, "bigconstant");
addInfo("ldiv", RuntimeConstants.opc_ldiv, "");
addInfo("lload", RuntimeConstants.opc_lload, "i");
addInfo("lload_w", RuntimeConstants.opc_lload, "I");
addInfo("lload_0", RuntimeConstants.opc_lload_0, "");
addInfo("lload_1", RuntimeConstants.opc_lload_1, "");
addInfo("lload_2", RuntimeConstants.opc_lload_2, "");
addInfo("lload_3", RuntimeConstants.opc_lload_3, "");
addInfo("lmul", RuntimeConstants.opc_lmul, "");
addInfo("lneg", RuntimeConstants.opc_lneg, "");
addInfo("lookupswitch", RuntimeConstants.opc_lookupswitch, "switch");
addInfo("lor", RuntimeConstants.opc_lor, "");
addInfo("lrem", RuntimeConstants.opc_lrem, "");
addInfo("lreturn", RuntimeConstants.opc_lreturn, "");
addInfo("lshl", RuntimeConstants.opc_lshl, "");
addInfo("lshr", RuntimeConstants.opc_lshr, "");
addInfo("lstore", RuntimeConstants.opc_lstore, "i");
addInfo("lstore_w", RuntimeConstants.opc_lstore, "I");
addInfo("lstore_0", RuntimeConstants.opc_lstore_0, "");
addInfo("lstore_1", RuntimeConstants.opc_lstore_1, "");
addInfo("lstore_2", RuntimeConstants.opc_lstore_2, "");
addInfo("lstore_3", RuntimeConstants.opc_lstore_3, "");
addInfo("lsub", RuntimeConstants.opc_lsub, "");
addInfo("lushr", RuntimeConstants.opc_lushr, "");
addInfo("lxor", RuntimeConstants.opc_lxor, "");
addInfo("monitorenter", RuntimeConstants.opc_monitorenter, "");
addInfo("monitorexit", RuntimeConstants.opc_monitorexit, "");
addInfo("multianewarray", RuntimeConstants.opc_multianewarray, "marray");
addInfo("new", RuntimeConstants.opc_new, "class");
addInfo("newarray", RuntimeConstants.opc_newarray, "atype");
addInfo("nop", RuntimeConstants.opc_nop, "");
addInfo("pop", RuntimeConstants.opc_pop, "");
addInfo("pop2", RuntimeConstants.opc_pop2, "");
addInfo("putfield", RuntimeConstants.opc_putfield, "field");
addInfo("putstatic", RuntimeConstants.opc_putstatic, "field");
addInfo("ret", RuntimeConstants.opc_ret, "i");
addInfo("ret_w", RuntimeConstants.opc_ret, "I");
addInfo("return", RuntimeConstants.opc_return, "");
addInfo("saload", RuntimeConstants.opc_saload, "");
addInfo("sastore", RuntimeConstants.opc_sastore, "");
addInfo("sipush", RuntimeConstants.opc_sipush, "i");
addInfo("swap", RuntimeConstants.opc_swap, "");
addInfo("tableswitch", RuntimeConstants.opc_tableswitch, "switch");
}
};
/* --- Revision History ---------------------------------------------------
--- <NAME>, Aug 10 2006
Removed 'wide' as 'ignored' instruction
Added definition for '_w' aliases for some instructions
--- <NAME>, Mar 14 2006
Change: 'ldc_w' is NOT synonym for 'ldc'
--- <NAME>, Dec 23 2005
Added invokedynamic
Change: 'jsr_w' is NOT synonym for 'jsr'
--- <NAME>, Feb 8 1997
Added invokespecial as a synonym for invokenonvirtual
*/
<|start_filename|>src/main/java/jas/GenericAttr.java<|end_filename|>
/**
* This is an opaque attribute that lets you add an uninterpreted
* stream of bytes into an attribute in a class file. This can be
* used (for instance) to embed versioning or signatures into the
* class file or method.
*
* @author $Author: jonmeyerny $
* @version $Revision: 1.1 $
*/
package jas;
import java.io.*;
public class GenericAttr
{
CP attr_name;
byte data[];
/**
* Make up a new attribute
* @param data stream of bytes to be placed with the attribute
* @see ClassEnv#addGenericAttr
* @see CodeAttr#addGenericAttr
*/
public GenericAttr(String name, byte data[])
{
attr_name = new AsciiCP(name);
this.data = data;
}
/**
* Make up a new attribute
* @param name CP to be defined as the name of the attribute
* @param data stream of bytes to be placed with the attribute
* @see ClassEnv#addGenericAttr
* @see CodeAttr#addGenericAttr
*/
public GenericAttr(CP name, byte data[])
{
attr_name = name;
this.data = data;
}
/**
* Make up a new attribute
* @param name Name to be associated with the attribute
* @param file name of file with attribute contens
*/
public GenericAttr(String name, String file) throws IOException, jasError
{
FileInputStream inp;
try {
inp = new FileInputStream(file);
} catch(FileNotFoundException e) {
throw new jasError("Generic atribute file " +file+ " not found");
}
data = new byte[inp.available()];
inp.read(data);
inp.close();
attr_name = new AsciiCP(name);
}
void resolve(ClassEnv e)
{ e.addCPItem(attr_name); }
int size()
{ return (2 + 4 + data.length); }
void write(ClassEnv e, DataOutputStream out)
throws IOException, jasError
{
out.writeShort(e.getCPIndex(attr_name));
out.writeInt(data.length);
out.write(data);
}
}
<|start_filename|>src/main/java/jas/Insn.java<|end_filename|>
/**
* An Insn is a generic instruction that is added to a
* CodeAttr to build up the code for a method.
* @see CodeAttr
* @see RuntimeConstants
* @author $Author: jonmeyerny $
* @version $Revision: 1.1 $
*/
package jas;
import java.io.*;
import java.util.*;
public class Insn implements RuntimeConstants
{
int opc;
InsnOperand operand;
// private constructor, for the
// "strange" opcodes
Insn() { return; }
/**
* Instructions with no arguments are built with
* this constructor.
*/
public Insn(int opc)
throws jasError
{
if (opcLengths[opc] == 1)
{ operand = null; this.opc = opc; return; }
throw new jasError
(opcNames[opc] + " cannot be used without more parameters");
}
private void check_short(int val, int opc) throws jasError
{
if (val > 32767 || val < -32768)
throw new jasError
(opcNames[opc] + " numeric value exceed size for short");
}
/**
* Instructions that take a single numeric argument. These are
* opc_bipush,
* opc_sipush,
* opc_ret,
* opc_iload,
* opc_lload,
* opc_fload,
* opc_dload,
* opc_aload,
* opc_istore,
* opc_lstore,
* opc_fstore,
* opc_dstore,
* opc_astore,
* opc_newarray
*
* Note that an extra wide prefix is automatically added
* for the following instructions if the numeric argument
* is larger than 256. Also note that while the spec makes
* no mention of opc_ret as being a "wideable" opcode, thats
* how the VM is implemented.
*
* opc_ret:
* opc_iload:
* opc_lload:
* opc_fload:
* opc_dload:
* opc_aload:
* opc_istore:
* opc_lstore:
* opc_fstore:
* opc_dstore:
* opc_astore:
*
*/
/**
* Added branch instructions
*/
public Insn(int opc, int val, boolean Wide)
throws jasError
{
this.opc = opc;
switch (opc)
{
case opc_bipush:
if(val > 127 || val < -128)
throw new jasError("bipush value exceed size of byte", true);
operand = new ByteOperand(val);
break;
case opc_sipush:
case opc_goto:
case opc_if_acmpeq:
case opc_if_acmpne:
case opc_if_icmpeq:
case opc_if_icmpge:
case opc_if_icmpgt:
case opc_if_icmple:
case opc_if_icmplt:
case opc_if_icmpne:
case opc_ifeq:
case opc_ifge:
case opc_ifgt:
case opc_ifle:
case opc_iflt:
case opc_ifne:
case opc_ifnonnull:
case opc_ifnull:
case opc_jsr:
check_short(val, opc);
operand = new OffsetOperand(this, val); break;
case opc_goto_w:
case opc_jsr_w:
operand = new OffsetOperand(this, val, true); break;
case opc_newarray:
if(val < 0 || val > 255)
throw new jasError("newarray counter is illegal", true);
operand = new UnsignedByteOperand(val);
break;
case opc_ret:
case opc_iload:
case opc_lload:
case opc_fload:
case opc_dload:
case opc_aload:
case opc_istore:
case opc_lstore:
case opc_fstore:
case opc_dstore:
case opc_astore:
operand = new UnsignedByteWideOperand(val, Wide);
break;
default:
throw new jasError
(opcNames[opc] + " does not take a numeric argument");
}
}
// used for relative offsets (ex : goto $+5)
public Insn(int opc, int val, char relative)
throws jasError
{
this.opc = opc;
switch (opc)
{
case opc_goto:
case opc_if_acmpeq:
case opc_if_acmpne:
case opc_if_icmpeq:
case opc_if_icmpge:
case opc_if_icmpgt:
case opc_if_icmple:
case opc_if_icmplt:
case opc_if_icmpne:
case opc_ifeq:
case opc_ifge:
case opc_ifgt:
case opc_ifle:
case opc_iflt:
case opc_ifne:
case opc_ifnonnull:
case opc_ifnull:
case opc_jsr:
check_short(val, opc);
operand = new RelativeOffsetOperand(this, val); break;
case opc_goto_w:
case opc_jsr_w:
operand = new RelativeOffsetOperand(this, val, true); break;
default:
throw new jasError
(opcNames[opc] + " does not take a relative numeric argument");
}
}
/**
* Instructions that take a Label as an argument. These are
* opc_jsr,
* opc_goto,
* opc_if_acmpne,
* opc_if_acmpeq,
* opc_if_icmpge,
* opc_if_icmple,
* opc_if_icmpgt,
* opc_if_icmplt,
* opc_if_icmpne,
* opc_if_icmpeq,
* opc_ifge,
* opc_ifgt,
* opc_ifne,
* opc_ifle,
* opc_iflt,
* opc_ifeq,
* opc_ifnull,
* opc_ifnonnull,
* opc_goto_w,
* opc_jsr_w
*/
public Insn(int opc, Label target, int line)
throws jasError
{
this.opc = opc;
switch(opc)
{
case opc_jsr:
case opc_goto:
case opc_if_acmpne:
case opc_if_acmpeq:
case opc_if_icmpge:
case opc_if_icmple:
case opc_if_icmpgt:
case opc_if_icmplt:
case opc_if_icmpne:
case opc_if_icmpeq:
case opc_ifge:
case opc_ifgt:
case opc_ifne:
case opc_ifle:
case opc_iflt:
case opc_ifeq:
case opc_ifnull:
case opc_ifnonnull:
operand = new LabelOperand(target, this, line);
break;
case opc_goto_w:
case opc_jsr_w:
operand = new LabelOperand(target, this, true, line);
break;
default:
throw new jasError
(opcNames[opc] + " does not take a label as its argument");
}
}
/**
* This constructor is used for instructions that take a CP item
* as their argument. These are
* opc_anewarray,
* opc_ldc_w,
* opc_ldc2_w,
* opc_invokedynamic,
* opc_invokenonvirtual,
* opc_invokestatic,
* opc_invokevirtual,
* opc_new,
* opc_checkcast,
* opc_instanceof,
* opc_getstatic,
* opc_putstatic,
* opc_getfield,
* opc_putfield,
* opc_ldc
*/
public Insn(int opc, CP arg)
throws jasError
{
this.opc = opc;
switch(opc)
{
case opc_anewarray:
case opc_invokedynamic:
case opc_invokenonvirtual:
case opc_invokestatic:
case opc_invokevirtual:
case opc_new:
case opc_checkcast:
case opc_instanceof:
case opc_getstatic:
case opc_putstatic:
case opc_getfield:
case opc_putfield:
operand = new CPOperand(arg);
break;
case opc_ldc2_w:
case opc_ldc_w:
operand = new LdcOperand(this, arg);
break;
case opc_ldc:
operand = new LdcOperand(this, arg, false);
break;
default:
throw new jasError
(opcNames[opc] + " does not take a CP item as an argument");
}
}
// This allows the Insn a chance to
// add things to the global env if
// necessary. The CPInsnOperands
// use this to add the CP to the
// classEnv
void resolve(ClassEnv e)
{ if (operand != null) { operand.resolve(e); } }
void write(ClassEnv e, CodeAttr ce, DataOutputStream out)
throws IOException, jasError
{
if (operand != null)
operand.writePrefix(e, ce, out);
out.writeByte((byte) opc);
if (operand != null)
operand.write(e, ce, out);
}
int size(ClassEnv e, CodeAttr ce)
throws jasError
{
if (operand == null) return 1;
return (1 + operand.size(e, ce));
}
public String toString() {
return "instruction "+opc+" "+((operand!=null)?operand.toString():"");
}
}
/* --- Revision History ---------------------------------------------------
--- <NAME>, Aug 10 2006
Added 'wide' prefix to some instructions
*/
<|start_filename|>src/main/java/java_cup/runtime/str_token.java<|end_filename|>
package java_cup.runtime;
/** This subclass of token represents symbols that need to maintain one
* String value as an attribute. It maintains that value in the public
* field str_val.
*
* @see java_cup.runtime.int_token
* @version last updated: 11/25/95
* @author <NAME>
*/
public class str_token extends token {
/** Full constructor. */
public str_token(int term_num, String v)
{
/* super class does most of the work */
super(term_num);
str_val = v;
}
/** Constructor for value defaulting to an empty string. */
public str_token(int term_num)
{
this(term_num, "");
}
/** The stored string value. */
public String str_val;
};
<|start_filename|>src/main/java/java_cup/runtime/token.java<|end_filename|>
package java_cup.runtime;
/** This subclass of symbol represents (at least) terminal symbols returned
* by the scanner and placed on the parse stack. At present, this
* class does nothing more than its super class.
*
* @see java_cup.runtime.int_token
* @see java_cup.runtime.str_token
* @version last updated: 11/25/95
* @author <NAME>
*/
public class token extends symbol {
/* Simple constructor -- just delegates to the super class. */
public token(int term_num)
{
/* super class does all the work */
super(term_num);
}
};
<|start_filename|>src/main/java/jasmin/var_token.java<|end_filename|>
package jasmin;
import java_cup.*;
/** This subclass of token represents symbols that need to maintain one
* number value as an attribute. It maintains that value in the public
* field var_val.
*
* @see java_cup.runtime.str_token
* @version last updated: 1/7/96
* @author <NAME>
*/
class var_token extends java_cup.runtime.token {
/** Full constructor. */
public var_token(int term_num, Number v)
{
/* super class does most of the work */
super(term_num);
var_val = v;
}
public var_token(int term_num, String v)
{
/* super class does most of the work */
super(term_num);
var_val = v;
}
/** Constructor with default value of 0 */
public var_token(int term_num)
{
this(term_num, new Integer(0));
}
/** The stored number reference. */
public Object var_val;
};
<|start_filename|>docs/style.css<|end_filename|>
td { font-family: Verdana,Arial,Helvetica,sans-serif; color: #000000; font-size: 12px; line-height: 16px; }
td h1 { font-family: Tahoma; padding: 1px; padding-left: 4px; color: white; background-color: #303030; font-size: 20px; line-height: 24px; font-weight: bold; }
td h2{ font-family: Tahoma; color: #000000; font-size: 14px; line-height: 16px; font-weight: bold; }
td h3 { font-family: Tahoma; color: #000000; font-size: 12px; line-height: 16px; font-weight: bold; }
.h1 { font-family: Times; color: #000000; font-size: 18px; line-height: 20px; font-weight: bold; }
/* main text hyperlinks */
a { color: #b11; TEXT-DECORATION: underline; }
a:visited {color: #b11}
a:hover {color: #f88}
pre.code{ font-family: courier new; color: #202060; font-size: 12px; line-height: 14px;}
font.code{ font-family: courier new; color: #202060; font-size: 12px; line-height: 14px;}
| TamilanPeriyasamy/jasmin |
<|start_filename|>Dockerfile<|end_filename|>
FROM python:3.8-alpine
VOLUME [ "/config"]
# Install required dependencies
RUN apk add --no-cache \
# Support for Timezones
tzdata \
# ujson won't compile without these libs
g++
# Always use latest versions
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . .
# Install
RUN pip3 install .
CMD [ "python", "-m", "HABApp", "--config", "/config" ]
<|start_filename|>_doc/_static/theme_overrides.css<|end_filename|>
/* override table width restrictions */
@media screen and (min-width: 767px) {
.wy-nav-content {
max-width: 1100px !important;
}
.wy-table-responsive table td {
/* !important prevents the common CSS stylesheets from overriding
this as on RTD they are loaded after this stylesheet */
white-space: normal !important;
}
.wy-table-responsive {
overflow: visible !important;
}
}
h1 { font-size: 200% }
h2 { font-size: 180% }
h3 { font-size: 160% }
h4 { font-size: 140% }
h5 { font-size: 120% }
h6 { font-size: 100% }
| DerOetzi/HABApp |
<|start_filename|>tslint.json<|end_filename|>
{
"extends": "tslint-config-standard",
"rules": {
"quotemark": false,
"semicolon": true,
"space-before-function-paren": false,
"whitespace": true
},
"linterOptions": {
"exclude": ["node_modules/**", "lin/**/**"]
}
}
<|start_filename|>example/logger.js<|end_filename|>
const Logger = require('egg-logger').Logger;
const { FileTransport } = require('../lin/logger/file');
const { ConsoleTransport } = require('../lin/logger/console');
const logger = new Logger();
logger.set(
'file',
new FileTransport({
dir: 'log',
sizeLimit: 1024 * 5,
level: 'DEBUG'
})
);
logger.set(
'console',
new ConsoleTransport({
level: 'DEBUG'
})
);
logger.debug('debug foo'); // only output to stdout
logger.info('info foo');
// for (let i = 0; i < 1000; i++) {}
setInterval(() => {
logger.info('we will never be slavers!!!');
}, 100);
logger.warn('warn foo');
// logger.error(new Error('error foo'));
<|start_filename|>example/simple.js<|end_filename|>
const Koa = require('koa');
const { Lin, log, error } = require('../lin');
const { config } = require('../lin/config');
// 需要mysql数据库,数据库名为lin-cms,默认用户名:root,密码:<PASSWORD>
const run = async () => {
config.setItem('pluginPath', {});
config.setItem('apiDir', 'example');
const app = new Koa();
config.initApp(app);
app.use(log);
app.on('error', error);
const lin = new Lin();
await lin.initApp(app, true, true);
// const { File } = require('../lin/core');
// File.createRecord(
// {
// path: '/flow.png',
// type: 1,
// name: 'flow',
// extension: '.png',
// size: 1024
// },
// true
// );
app.listen(3000, () => {
console.log('listening at http://localhost:3000');
});
};
run();
| hpmax00/lin-cms-koa-core |
<|start_filename|>assets_user/libs/@iconscout/unicons/scripts/line/folder-move.js<|end_filename|>
const fs = require('fs-plus')
const path = require('path')
const glob = require('glob')
const sourcePath = path.join(process.cwd(), 'fontello-*')
const destPath = path.join(process.cwd())
glob(sourcePath, function (err, files) {
const fontFolder = files[0]
console.log(fontFolder, destPath)
// Keep Custom Files
// i.e. Animations
fs.renameSync(destPath + '/css/animation.css', fontFolder + '/css/animation.css', (err) => {
if (err) throw err
console.log('Animation.css moved!')
})
// Clear Directories
fs.removeSync(destPath + '/font')
fs.removeSync(destPath + '/css')
fs.removeSync(destPath + '/index.html')
// Move Font Files
fs.rename(fontFolder + '/font', destPath + '/font', (err) => {
if (err) throw err
console.log('Fonts moved!')
})
// Move CSS Files
fs.rename(fontFolder + '/css', destPath + '/css', (err) => {
if (err) throw err
console.log('CSS moved!')
})
// Move Demo File
fs.rename(fontFolder + '/demo.html', destPath + '/index.html', (err) => {
if (err) throw err
console.log('Demo.html moved!')
})
})
<|start_filename|>assets_user/libs/@iconscout/unicons/scripts/monochrome/validate.js<|end_filename|>
const path = require('path')
const glob = require('glob')
const fs = require('fs-plus')
const sourcePath = path.join(process.cwd(), 'dist/test', '**/*.svg')
const replaceFill = require('./replaceFill')
glob(sourcePath, function (err, files) {
if (err) {
console.log(err)
return false
}
files = files.map((f) => path.normalize(f))
files.forEach(filename => {
const svg = fs.readFileSync(filename, 'utf-8')
replaceFill(svg, filename)
})
})
<|start_filename|>assets_user/libs/@iconscout/unicons/css/animation.css<|end_filename|>
/* Spin Animation Start */
.animate.spin {
-moz-animation: spin 2s infinite linear;
-o-animation: spin 2s infinite linear;
-webkit-animation: spin 2s infinite linear;
animation: spin 2s infinite linear;
display: inline-block;
}
.animate.spin-slow {
-moz-animation: spin 4s infinite linear;
-o-animation: spin 4s infinite linear;
-webkit-animation: spin 4s infinite linear;
animation: spin 4s infinite linear;
display: inline-block;
}
.animate.spin-fast {
-moz-animation: spin 1s infinite linear;
-o-animation: spin 1s infinite linear;
-webkit-animation: spin 1s infinite linear;
animation: spin 1s infinite linear;
display: inline-block;
}
@keyframes spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@-moz-keyframes spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@-o-keyframes spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@-webkit-keyframes spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@-ms-keyframes spin {
0% {
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-moz-transform: rotate(359deg);
-o-transform: rotate(359deg);
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
/* Spin Animation End */
/* Pulse Animation Start */
.animate.pulse {
-moz-animation: pulse 2s infinite linear;
-o-animation: pulse 2s infinite linear;
-webkit-animation: pulse 2s infinite linear;
animation: pulse 2s infinite linear;
display: inline-block;
}
.animate.pulse-slow {
-moz-animation: pulse 4s infinite linear;
-o-animation: pulse 4s infinite linear;
-webkit-animation: pulse 4s infinite linear;
animation: pulse 4s infinite linear;
display: inline-block;
}
.animate.pulse-fast {
-moz-animation: pulse 1s infinite linear;
-o-animation: pulse 1s infinite linear;
-webkit-animation: pulse 1s infinite linear;
animation: pulse 1s infinite linear;
display: inline-block;
}
@keyframes pulse {
50% {
-moz-transform: scale(0.5);
-o-transform: scale(0.5);
-webkit-transform: scale(0.5);
transform: scale(0.5);
}
}
@-moz-keyframes pulse {
50% {
-moz-transform: scale(0.5);
-o-transform: scale(0.5);
-webkit-transform: scale(0.5);
transform: scale(0.5);
}
}
@-o-keyframes pulse {
50% {
-moz-transform: scale(0.5);
-o-transform: scale(0.5);
-webkit-transform: scale(0.5);
transform: scale(0.5);
}
}
@-webkit-keyframes pulse {
50% {
-moz-transform: scale(0.5);
-o-transform: scale(0.5);
-webkit-transform: scale(0.5);
transform: scale(0.5);
}
}
@-ms-keyframes pulse {
50% {
-moz-transform: scale(0.5);
-o-transform: scale(0.5);
-webkit-transform: scale(0.5);
transform: scale(0.5);
}
}
/* Pulse Animation End */
/* Vibrate Animation Start */
.animate.vibrate {
-moz-animation: vibrate 0.1s infinite linear;
-o-animation: vibrate 0.1s infinite linear;
-webkit-animation: vibrate 0.1s infinite linear;
animation: vibrate 0.1s infinite linear;
display: inline-block;
}
.animate.vibrate-slow {
-moz-animation: vibrate 0.2s infinite linear;
-o-animation: vibrate 0.2s infinite linear;
-webkit-animation: vibrate 0.2s infinite linear;
animation: vibrate 0.2s infinite linear;
display: inline-block;
}
.animate.vibrate-fast {
-moz-animation: vibrate 0.07s infinite linear;
-o-animation: vibrate 0.07s infinite linear;
-webkit-animation: vibrate 0.07s infinite linear;
animation: vibrate 0.07s infinite linear;
display: inline-block;
}
@keyframes vibrate {
25% {
-moz-transform: translate(-2px);
-o-transform: translate(-2px);
-webkit-transform: translate(-2px);
transform: translate(-2px);
}
75% {
-moz-transform: translate(2px);
-o-transform: translate(2px);
-webkit-transform: translate(2px);
transform: translate(2px);
}
}
@-moz-keyframes vibrate {
25% {
-moz-transform: translate(-2px);
-o-transform: translate(-2px);
-webkit-transform: translate(-2px);
transform: translate(-2px);
}
75% {
-moz-transform: translate(2px);
-o-transform: translate(2px);
-webkit-transform: translate(2px);
transform: translate(2px);
}
}
@-o-keyframes vibrate {
25% {
-moz-transform: translate(-2px);
-o-transform: translate(-2px);
-webkit-transform: translate(-2px);
transform: translate(-2px);
}
75% {
-moz-transform: translate(2px);
-o-transform: translate(2px);
-webkit-transform: translate(2px);
transform: translate(2px);
}
}
@-webkit-keyframes vibrate {
25% {
-moz-transform: translate(-2px);
-o-transform: translate(-2px);
-webkit-transform: translate(-2px);
transform: translate(-2px);
}
75% {
-moz-transform: translate(2px);
-o-transform: translate(2px);
-webkit-transform: translate(2px);
transform: translate(2px);
}
}
@-ms-keyframes vibrate {
25% {
-moz-transform: translate(-2px);
-o-transform: translate(-2px);
-webkit-transform: translate(-2px);
transform: translate(-2px);
}
75% {
-moz-transform: translate(2px);
-o-transform: translate(2px);
-webkit-transform: translate(2px);
transform: translate(2px);
}
}
/* Vibrate Animation End */
/* Blink Smooth Animation Start */
.animate.blink-smooth {
-moz-animation: blink-s 0.8s infinite linear;
-o-animation: blink-s 0.8s infinite linear;
-webkit-animation: blink-s 0.8s infinite linear;
animation: blink-s 0.8s infinite linear;
display: inline-block;
}
.animate.blink-smooth-slow {
-moz-animation: blink-s 1.2s infinite linear;
-o-animation: blink-s 1.2s infinite linear;
-webkit-animation: blink-s 1.2s infinite linear;
animation: blink-s 1.2s infinite linear;
display: inline-block;
}
.animate.blink-smooth-fast {
-moz-animation: blink-s 0.4s infinite linear;
-o-animation: blink-s 0.4s infinite linear;
-webkit-animation: blink-s 0.4s infinite linear;
animation: blink-s 0.4s infinite linear;
display: inline-block;
}
@keyframes blink-s {
50% {
opacity: 0;
filter: alpha(opacity=100);
}
}
@-moz-keyframes blink-s {
50% {
opacity: 0;
filter: alpha(opacity=100);
}
}
@-o-keyframes blink-s {
50% {
opacity: 0;
filter: alpha(opacity=100);
}
}
@-webkit-keyframes blink-s {
50% {
opacity: 0;
filter: alpha(opacity=100);
}
}
@-ms-keyframes blink-s {
50% {
opacity: 0;
filter: alpha(opacity=100);
}
}
/* Blink Smooth Animation End */
/* Blink Animation Start */
.animate.blink {
-moz-animation: blink 0.8s infinite linear;
-o-animation: blink 0.8s infinite linear;
-webkit-animation: blink 0.8s infinite linear;
animation: blink 0.8s infinite linear;
display: inline-block;
}
.animate.blink-slow {
-moz-animation: blink 1.2s infinite linear;
-o-animation: blink 1.2s infinite linear;
-webkit-animation: blink 1.2s infinite linear;
animation: blink 1.2s infinite linear;
display: inline-block;
}
.animate.blink-fast {
-moz-animation: blink 0.4s infinite linear;
-o-animation: blink 0.4s infinite linear;
-webkit-animation: blink 0.4s infinite linear;
animation: blink 0.4s infinite linear;
display: inline-block;
}
@keyframes blink {
50%, 100% {
visibility: hidden;
}
}
@-moz-keyframes blink {
50%, 100% {
visibility: hidden;
}
}
@-o-keyframes blink {
50%, 100% {
visibility: hidden;
}
}
@-webkit-keyframes blink {
50%, 100% {
visibility: hidden;
}
}
@-ms-keyframes blink {
50%, 100% {
visibility: hidden;
}
}
/* Blink Animation End */
| yusrilihzaM/Discharge-Planning-Post-Covid-Hospital-Syarifah-Ambami-Rato-Ebu |
<|start_filename|>goim-nats/dao/nats.go<|end_filename|>
package dao
import (
"context"
"strconv"
"sync"
"time"
"github.com/gogo/protobuf/proto"
"github.com/gomodule/redigo/redis"
"github.com/liftbridge-io/go-liftbridge"
"github.com/nats-io/go-nats"
log "github.com/tsingson/zaplogger"
pb "github.com/tsingson/ex-goim/api/logic/grpc"
"github.com/tsingson/ex-goim/goim-nats/logic/conf"
"github.com/tsingson/ex-goim/pkg/utils"
)
// NatsDao dao for nats
type Dao struct {
c *conf.LogicConfig
natsClient *nats.Conn
liftClient liftbridge.Client
redis *redis.Pool
redisExpire int32
}
type NatsDao = Dao
// LogicConfig configuration for nats / liftbridge queue
type Config struct {
Channel string
ChannelID string
Group string
NatsAddr string
LiftAddr string
}
type NatsConfig = Config
// New new a dao and return.
func New(c *conf.LogicConfig) *Dao {
conn, err := newNatsClient(c.Nats.NatsAddr, c.Nats.LiftAddr, c.Nats.Channel, c.Nats.ChannelID)
if err != nil {
return nil
}
d := &Dao{
c: c,
natsClient: conn,
redis: newRedis(),
// TODO: handler redis expire
redisExpire: int32(time.Duration(c.Redis.Expire) / time.Second),
}
return d
}
// Close close the resource.
func (d *Dao) Close() error {
d.natsClient.Close()
return d.redis.Close()
}
// Ping dao ping.
func (d *Dao) Ping(c context.Context) error {
return d.pingRedis(c)
}
// PushMsg push a message to databus.
func (d *Dao) PushMsg(c context.Context, op int32, server string, keys []string, msg []byte) (err error) {
pushMsg := &pb.PushMsg{
Type: pb.PushMsg_PUSH,
Operation: op,
Server: server,
Keys: keys,
Msg: msg,
}
b, err := proto.Marshal(pushMsg)
if err != nil {
return
}
d.publishMessage(d.c.Nats.Channel, d.c.Nats.AckInbox, []byte(keys[0]), b)
return
}
// BroadcastRoomMsg push a message to databus.
func (d *Dao) BroadcastRoomMsg(c context.Context, op int32, room string, msg []byte) (err error) {
pushMsg := &pb.PushMsg{
Type: pb.PushMsg_ROOM,
Operation: op,
Room: room,
Msg: msg,
}
b, err := proto.Marshal(pushMsg)
if err != nil {
return
}
d.publishMessage(d.c.Nats.Channel, d.c.Nats.AckInbox, []byte(room), b)
return
}
// BroadcastMsg push a message to databus.
func (d *Dao) BroadcastMsg(c context.Context, op, speed int32, msg []byte) (err error) {
pushMsg := &pb.PushMsg{
Type: pb.PushMsg_BROADCAST,
Operation: op,
Speed: speed,
Msg: msg,
}
b, err := proto.Marshal(pushMsg)
if err != nil {
return
}
key := strconv.FormatInt(int64(op), 10)
d.publishMessage(d.c.Nats.Channel, d.c.Nats.AckInbox, []byte(key), b)
return
}
func newNatsClient(natsAddr, liftAddr, channel, channelID string) (*nats.Conn, error) {
// liftAddr := "localhost:9292" // address for lift-bridge
// channel := "bar"
// channelID := "bar-stream"
// ackInbox := "acks"
if err := createStream(liftAddr, channel, channelID); err != nil {
if err != liftbridge.ErrStreamExists {
return nil, err
}
}
// conn, err := nats.GetDefaultOptions().Connect()
// natsAddr := "nats://localhost:4222"
return nats.Connect(natsAddr)
// defer conn.Flush()
// defer conn.Close()
}
func (d *Dao) publishMessage(channel, ackInbox string, key, value []byte) error {
// var wg sync.WaitGroup
// wg.Add(1)
// sub, err := d.natsClient.Subscribe(ackInbox, func(m *nats.Msg) {
// ack, err := liftbridge.UnmarshalAck(m.Data)
// if err != nil {
// // TODO: handel error write to log
// return
// }
//
// log.Info(utils.StrBuilder("ack:", ack.StreamSubject, " stream: ", ack.StreamName, " offset: ", strconv.FormatInt(ack.Offset,10), " msg: ", ack.MsgSubject) )
// wg.Done()
// })
// if err != nil {
// return err
// }
// defer sub.Unsubscribe()
m := liftbridge.NewMessage(value, liftbridge.MessageOptions{Key: key, AckInbox: ackInbox})
if err := d.natsClient.Publish(channel, m); err != nil {
return err
}
// wg.Wait()
return nil
}
func (d *Dao) publishMessageSync(channel, ackInbox string, key, value []byte) error {
var wg sync.WaitGroup
wg.Add(1)
sub, err := d.natsClient.Subscribe(ackInbox, func(m *nats.Msg) {
ack, err := liftbridge.UnmarshalAck(m.Data)
if err != nil {
// TODO: handel error write to log
return
}
log.Info(utils.StrBuilder("ack:", ack.StreamSubject, " stream: ", ack.StreamName, " offset: ", strconv.FormatInt(ack.Offset, 10), " msg: ", ack.MsgSubject))
wg.Done()
})
if err != nil {
return err
}
defer sub.Unsubscribe()
m := liftbridge.NewMessage(value, liftbridge.MessageOptions{Key: key, AckInbox: ackInbox})
if err := d.natsClient.Publish(channel, m); err != nil {
return err
}
wg.Wait()
return nil
}
func createStream(liftAddr, subject, name string) error {
client, err := liftbridge.Connect([]string{liftAddr})
if err != nil {
return err
}
defer client.Close()
stream := liftbridge.StreamInfo{
Subject: subject,
Name: name,
ReplicationFactor: 1,
}
if err := client.CreateStream(context.Background(), stream); err != nil {
if err != liftbridge.ErrStreamExists {
return err
}
}
return nil
}
<|start_filename|>cmd/nats/comet/main.go<|end_filename|>
package main
import (
"context"
"flag"
"fmt"
"math/rand"
"net"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/tsingson/discovery/naming"
discovery "github.com/tsingson/discovery/naming/grpc"
log "github.com/tsingson/zaplogger"
"github.com/tsingson/ex-goim/pkg/utils"
"github.com/tsingson/ex-goim/goim-nats/comet"
"github.com/tsingson/ex-goim/goim-nats/comet/conf"
"github.com/tsingson/ex-goim/goim-nats/comet/grpc"
"github.com/tsingson/ex-goim/goim-nats/model"
"github.com/tsingson/ex-goim/pkg/ip"
)
const (
ver = "2.0.0"
appid = "goim.comet"
)
var (
cfg *conf.CometConfig
)
func main() {
path, _ := utils.GetCurrentExecDir()
confPath := path + "/comet-config.toml"
flag.Parse()
var err error
cfg, err = conf.Load(confPath)
if err != nil {
panic(err)
}
cfg.Env = &conf.Env{
Region: "china",
Zone: "gd",
DeployEnv: "dev",
Host: "comet",
}
rand.Seed(time.Now().UTC().UnixNano())
runtime.GOMAXPROCS(runtime.NumCPU())
println(cfg.Debug)
log.Infof("goim-comet [version: %s env: %+v] start", ver, cfg.Env)
// register discovery
dis := naming.New(cfg.Discovery)
discovery.Register(dis)
// new comet server
srv := comet.NewServer(cfg)
if err := comet.InitWhitelist(cfg.Whitelist); err != nil {
panic(err)
}
if err := comet.InitTCP(srv, cfg.TCP.Bind, runtime.NumCPU()); err != nil {
panic(err)
}
if err := comet.InitWebsocket(srv, cfg.Websocket.Bind, runtime.NumCPU()); err != nil {
panic(err)
}
if cfg.Websocket.TLSOpen {
if err := comet.InitWebsocketWithTLS(srv, cfg.Websocket.TLSBind, cfg.Websocket.CertFile, cfg.Websocket.PrivateFile, runtime.NumCPU()); err != nil {
panic(err)
}
}
// new grpc server
rpcSrv := grpc.New(cfg.RPCServer, srv)
cancel := register(dis, srv)
// signal
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Infof("goim-comet get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
if cancel != nil {
cancel()
}
rpcSrv.GracefulStop()
srv.Close()
log.Infof("goim-comet [version: %s] exit", ver)
// log.Flush()
return
case syscall.SIGHUP:
default:
return
}
}
}
func register(dis *naming.Discovery, srv *comet.Server) context.CancelFunc {
env := cfg.Env
addr := ip.InternalIP()
_, port, _ := net.SplitHostPort(cfg.RPCServer.Addr)
ins := &naming.Instance{
Region: env.Region,
Zone: env.Zone,
Env: env.DeployEnv,
Hostname: env.Host,
AppID: appid,
Addrs: []string{
"grpc://" + addr + ":" + port,
},
Metadata: map[string]string{
model.MetaWeight: strconv.FormatInt(env.Weight, 10),
model.MetaOffline: strconv.FormatBool(env.Offline),
model.MetaAddrs: strings.Join(env.Addrs, ","),
},
}
cancel, err := dis.Register(ins)
if err != nil {
panic(err)
}
// renew discovery metadata
go func() {
for {
var (
err error
conns int
ips = make(map[string]struct{})
)
for _, bucket := range srv.Buckets() {
for ip := range bucket.IPCount() {
ips[ip] = struct{}{}
}
conns += bucket.ChannelCount()
}
ins.Metadata[model.MetaConnCount] = fmt.Sprint(conns)
ins.Metadata[model.MetaIPCount] = fmt.Sprint(len(ips))
if err = dis.Set(ins); err != nil {
log.Errorf("dis.Set(%+v) error(%v)", ins, err)
time.Sleep(time.Second)
continue
}
time.Sleep(time.Second * 10)
}
}()
return cancel
}
<|start_filename|>third-party/discoveryd/file.go<|end_filename|>
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"github.com/BurntSushi/toml"
)
func SaveToml(v interface{}, filename string) error {
// currentPath+"/toml1.toml"
var err error
b := &bytes.Buffer{}
encoder := toml.NewEncoder(b)
if err = encoder.Encode(v); err != nil {
}
WriteToFile(b.Bytes(), filename)
return err
}
func WriteToFile(c []byte, filename string) error {
// 将指定内容写入到文件中
err := ioutil.WriteFile(filename, c, 0666)
return err
}
func GetCurrentPath() (string, error) {
return filepath.Abs(filepath.Dir(os.Args[0]))
}
func GetCurrentExecDir() (dir string, err error) {
path, err := exec.LookPath(os.Args[0])
if err != nil {
fmt.Printf("exec.LookPath(%s), err: %s\n", os.Args[0], err)
return "", err
}
absPath, err := filepath.Abs(path)
if err != nil {
fmt.Printf("filepath.Abs(%s), err: %s\n", path, err)
return "", err
}
dir = filepath.Dir(absPath)
return dir, nil
}
<|start_filename|>third-party/gnatsd/main.go<|end_filename|>
// Copyright 2012-2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"runtime"
"time"
gnatsd "github.com/nats-io/gnatsd/server"
)
func main() {
runtime.MemProfileRate = 0
runtime.GOMAXPROCS(128)
signal := make(chan struct{})
s := RunDefaultServer()
s.Start()
defer s.Shutdown()
<-signal
}
// So we can pass tests and benchmarks..
type tLogger interface {
Fatalf(format string, args ...interface{})
Errorf(format string, args ...interface{})
}
// DefaultTestOptions are default options for the unit tests.
var DefaultTestOptions = &gnatsd.Options{
Host: "127.0.0.1",
Port: 4222,
NoLog: true,
NoSigs: true,
MaxControlLine: 2048,
}
// RunDefaultServer starts a new Go routine based gnatsd using the default options
func RunDefaultServer() *gnatsd.Server {
return RunServer(DefaultTestOptions)
}
// To turn on gnatsd tracing and debugging and logging which are
// normally suppressed.
var (
doLog = false
doTrace = false
doDebug = false
)
// RunServer starts a new Go routine based gnatsd
func RunServer(opts *gnatsd.Options) *gnatsd.Server {
// if opts == nil {
// opts = &DefaultTestOptions
// }
// Optionally override for individual debugging of tests
// opts.NoLog = !doLog
// opts.Trace = doTrace
opts.Debug = true
s := gnatsd.New(opts)
// if err != nil || s == nil {
// panic(fmt.Sprintf("No NATS Server object returned: %v", err))
// }
if doLog {
s.ConfigureLogger()
}
// Run gnatsd in Go routine.
go s.Start()
// Wait for accept loop(s) to be started
if !s.ReadyForConnections(10 * time.Second) {
panic("Unable to start NATS Server in Go Routine")
}
return s
}
// LoadConfig loads a configuration from a filename
func LoadConfig(configFile string) *gnatsd.Options {
opts, err := gnatsd.ProcessConfigFile(configFile)
if err != nil {
panic(fmt.Sprintf("Error processing configuration file: %v", err))
}
return opts
}
// RunServerWithConfig starts a new Go routine based gnatsd with a configuration file.
func RunServerWithConfig(configFile string) (srv *gnatsd.Server, opts *gnatsd.Options) {
opts = LoadConfig(configFile)
srv = RunServer(opts)
return
}
<|start_filename|>third-party/discoveryd/init.go<|end_filename|>
package main
import (
"os"
"github.com/spf13/afero"
config "github.com/tsingson/discovery/conf"
)
var ( // global variable
// cacheSize int
// cacheTimeOut int64
path, logPath string
cfg *config.Config
)
func init() {
var err error
afs := afero.NewOsFs()
{ // setup path for storage of log / configuration / cache
// path = "/Users/qinshen/git/linksmart/bin" // for test
path, err = GetCurrentExecDir()
if err != nil {
// fmt.Println("无法读取可执行程序的存储路径")
panic("无法读取可执行程序的存储路径")
os.Exit(-1)
}
}
{ // load config for discovery daemon
configToml := path + "/discoveryd-config.toml"
cfg, err = config.LoadConfig(configToml)
if err != nil {
// fmt.Println("无法读取可执行程序的存储路径")
panic("无法读取可执行程序的存储路径")
os.Exit(-1)
}
}
{
logPath = path + "/log"
check, _ := afero.DirExists(afs, logPath)
if !check {
err = afs.MkdirAll(logPath, 0755)
if err != nil {
panic("mkdir log path fail")
os.Exit(-1)
}
}
}
}
<|start_filename|>goim-nats/comet/client.go<|end_filename|>
package comet
import (
"context"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/balancer/roundrobin"
"google.golang.org/grpc/keepalive"
logic "github.com/tsingson/ex-goim/api/logic/grpc"
"github.com/tsingson/ex-goim/goim-nats/comet/conf"
)
const (
// grpc options
grpcInitialWindowSize = 1 << 24
grpcInitialConnWindowSize = 1 << 24
grpcMaxSendMsgSize = 1 << 24
grpcMaxCallMsgSize = 1 << 24
grpcKeepAliveTime = time.Second * 10
grpcKeepAliveTimeout = time.Second * 3
grpcBackoffMaxDelay = time.Second * 3
)
// NewLogicClient grpc client for logic
func NewLogicClient(c *conf.RPCClient) logic.LogicClient {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.Dial))
defer cancel()
conn, err := grpc.DialContext(ctx, "discovery://default/goim.logic",
[]grpc.DialOption{
grpc.WithInsecure(),
grpc.WithInitialWindowSize(grpcInitialWindowSize),
grpc.WithInitialConnWindowSize(grpcInitialConnWindowSize),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(grpcMaxCallMsgSize)),
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(grpcMaxSendMsgSize)),
grpc.WithBackoffMaxDelay(grpcBackoffMaxDelay),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: grpcKeepAliveTime,
Timeout: grpcKeepAliveTimeout,
PermitWithoutStream: true,
}),
grpc.WithBalancerName(roundrobin.Name),
}...)
if err != nil {
panic(err)
}
return logic.NewLogicClient(conn)
}
<|start_filename|>goim-nats/job/job_test.go<|end_filename|>
package job
import (
"os"
"testing"
"github.com/tsingson/ex-goim/goim-nats/job/conf"
)
var (
d *NatsJob
)
func TestMain(m *testing.M) {
conf.Conf = conf.Default()
d = New(conf.Conf)
os.Exit(m.Run())
}
func TestNatsJob_ConsumeCheck(t *testing.T) {
d.ConsumeCheck()
}
// func TestNatsJob_Subscribe(t *testing.T) {
// d.Subscribe(d.c.Nats.Channel, d.c.Nats.ChannelID)
// }
// func TestNatsJob_WatchComet(t *testing.T) {
// d.WatchComet(d.c.Discovery)
// }
<|start_filename|>api/logic/grpc/apipb_test.go<|end_filename|>
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: api.proto
package grpc
import (
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
github_com_gogo_protobuf_jsonpb "github.com/gogo/protobuf/jsonpb"
github_com_golang_protobuf_proto "github.com/golang/protobuf/proto"
proto "github.com/golang/protobuf/proto"
_ "github.com/tsingson/ex-goim/api/comet/grpc"
math "math"
math_rand "math/rand"
testing "testing"
time "time"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
func TestPushMsgProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsg(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PushMsg{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestPushMsgMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsg(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PushMsg{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkPushMsgProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*PushMsg, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedPushMsg(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkPushMsgProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedPushMsg(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &PushMsg{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestCloseReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &CloseReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestCloseReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &CloseReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkCloseReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*CloseReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedCloseReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkCloseReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedCloseReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &CloseReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestCloseReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &CloseReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestCloseReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &CloseReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkCloseReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*CloseReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedCloseReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkCloseReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedCloseReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &CloseReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestPingReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PingReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestPingReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PingReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkPingReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*PingReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedPingReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkPingReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedPingReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &PingReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestPingReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PingReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestPingReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PingReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkPingReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*PingReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedPingReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkPingReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedPingReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &PingReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestConnectReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ConnectReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestConnectReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ConnectReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkConnectReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*ConnectReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedConnectReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkConnectReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedConnectReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &ConnectReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestConnectReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ConnectReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestConnectReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ConnectReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkConnectReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*ConnectReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedConnectReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkConnectReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedConnectReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &ConnectReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestDisconnectReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &DisconnectReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestDisconnectReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &DisconnectReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkDisconnectReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*DisconnectReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedDisconnectReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkDisconnectReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedDisconnectReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &DisconnectReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestDisconnectReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &DisconnectReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestDisconnectReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &DisconnectReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkDisconnectReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*DisconnectReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedDisconnectReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkDisconnectReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedDisconnectReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &DisconnectReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestHeartbeatReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &HeartbeatReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestHeartbeatReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &HeartbeatReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkHeartbeatReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*HeartbeatReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedHeartbeatReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkHeartbeatReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedHeartbeatReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &HeartbeatReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestHeartbeatReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &HeartbeatReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestHeartbeatReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &HeartbeatReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkHeartbeatReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*HeartbeatReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedHeartbeatReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkHeartbeatReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedHeartbeatReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &HeartbeatReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestOnlineReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &OnlineReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestOnlineReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &OnlineReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkOnlineReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*OnlineReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedOnlineReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkOnlineReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedOnlineReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &OnlineReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestOnlineReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &OnlineReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestOnlineReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &OnlineReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkOnlineReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*OnlineReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedOnlineReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkOnlineReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedOnlineReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &OnlineReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestReceiveReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ReceiveReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestReceiveReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ReceiveReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkReceiveReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*ReceiveReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedReceiveReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkReceiveReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedReceiveReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &ReceiveReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestReceiveReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ReceiveReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestReceiveReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ReceiveReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkReceiveReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*ReceiveReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedReceiveReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkReceiveReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedReceiveReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &ReceiveReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestNodesReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &NodesReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestNodesReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &NodesReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkNodesReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*NodesReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedNodesReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkNodesReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedNodesReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &NodesReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestNodesReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &NodesReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestNodesReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &NodesReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkNodesReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*NodesReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedNodesReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkNodesReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedNodesReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &NodesReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestBackoffProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBackoff(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Backoff{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestBackoffMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBackoff(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Backoff{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkBackoffProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*Backoff, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedBackoff(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkBackoffProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedBackoff(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &Backoff{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestPushMsgJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsg(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PushMsg{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestCloseReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &CloseReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestCloseReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &CloseReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestPingReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PingReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestPingReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PingReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestConnectReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ConnectReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestConnectReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ConnectReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestDisconnectReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &DisconnectReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestDisconnectReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &DisconnectReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestHeartbeatReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &HeartbeatReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestHeartbeatReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &HeartbeatReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestOnlineReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &OnlineReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestOnlineReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &OnlineReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestReceiveReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ReceiveReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestReceiveReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &ReceiveReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestNodesReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &NodesReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestNodesReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &NodesReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestBackoffJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBackoff(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Backoff{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestPushMsgProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsg(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &PushMsg{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestPushMsgProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsg(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &PushMsg{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestCloseReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &CloseReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestCloseReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &CloseReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestCloseReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &CloseReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestCloseReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &CloseReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestPingReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &PingReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestPingReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &PingReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestPingReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &PingReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestPingReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &PingReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestConnectReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &ConnectReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestConnectReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &ConnectReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestConnectReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &ConnectReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestConnectReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &ConnectReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestDisconnectReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &DisconnectReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestDisconnectReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &DisconnectReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestDisconnectReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &DisconnectReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestDisconnectReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &DisconnectReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestHeartbeatReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &HeartbeatReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestHeartbeatReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &HeartbeatReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestHeartbeatReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &HeartbeatReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestHeartbeatReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &HeartbeatReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestOnlineReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &OnlineReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestOnlineReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &OnlineReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestOnlineReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &OnlineReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestOnlineReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &OnlineReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestReceiveReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &ReceiveReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestReceiveReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &ReceiveReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestReceiveReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &ReceiveReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestReceiveReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &ReceiveReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestNodesReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &NodesReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestNodesReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &NodesReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestNodesReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &NodesReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestNodesReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &NodesReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestBackoffProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBackoff(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &Backoff{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestBackoffProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBackoff(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &Backoff{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestPushMsgSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsg(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkPushMsgSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*PushMsg, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedPushMsg(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestCloseReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkCloseReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*CloseReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedCloseReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestCloseReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedCloseReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkCloseReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*CloseReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedCloseReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestPingReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkPingReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*PingReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedPingReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestPingReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPingReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkPingReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*PingReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedPingReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestConnectReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkConnectReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*ConnectReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedConnectReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestConnectReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedConnectReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkConnectReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*ConnectReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedConnectReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestDisconnectReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkDisconnectReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*DisconnectReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedDisconnectReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestDisconnectReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedDisconnectReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkDisconnectReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*DisconnectReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedDisconnectReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestHeartbeatReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkHeartbeatReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*HeartbeatReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedHeartbeatReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestHeartbeatReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedHeartbeatReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkHeartbeatReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*HeartbeatReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedHeartbeatReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestOnlineReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkOnlineReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*OnlineReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedOnlineReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestOnlineReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedOnlineReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkOnlineReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*OnlineReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedOnlineReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestReceiveReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkReceiveReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*ReceiveReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedReceiveReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestReceiveReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedReceiveReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkReceiveReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*ReceiveReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedReceiveReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestNodesReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkNodesReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*NodesReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedNodesReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestNodesReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedNodesReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkNodesReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*NodesReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedNodesReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestBackoffSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBackoff(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkBackoffSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*Backoff, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedBackoff(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
//These tests are generated by github.com/gogo/protobuf/plugin/testgen
<|start_filename|>goim-nats/comet/server.go<|end_filename|>
package comet
import (
"context"
"math/rand"
"time"
log "github.com/tsingson/zaplogger"
"github.com/zhenjl/cityhash"
logic "github.com/tsingson/ex-goim/api/logic/grpc"
"github.com/tsingson/ex-goim/goim-nats/comet/conf"
)
const (
minServerHeartbeat = time.Minute * 10
maxServerHeartbeat = time.Minute * 30
)
// Server is comet server.
type Server struct {
c *conf.CometConfig
round *Round // accept round store
buckets []*Bucket // subkey bucket
bucketIdx uint32
serverID string
rpcClient logic.LogicClient
}
// NewServer returns a new Server.
func NewServer(cfg *conf.CometConfig) *Server {
s := &Server{
c: cfg,
round: NewRound(cfg),
rpcClient: NewLogicClient(cfg.RPCClient),
}
// init bucket
s.buckets = make([]*Bucket, cfg.Bucket.Size)
s.bucketIdx = uint32(cfg.Bucket.Size)
for i := 0; i < cfg.Bucket.Size; i++ {
s.buckets[i] = NewBucket(cfg.Bucket)
}
s.serverID = cfg.Env.Host
go s.onlineproc()
return s
}
// Buckets return all buckets.
func (s *Server) Buckets() []*Bucket {
return s.buckets
}
// Bucket get the bucket by subkey.
func (s *Server) Bucket(subKey string) *Bucket {
idx := cityhash.CityHash32([]byte(subKey), uint32(len(subKey))) % s.bucketIdx
if conf.Conf.Debug {
log.Infof("%s hit channel bucket index: %d use cityhash", subKey, idx)
}
return s.buckets[idx]
}
// RandServerHearbeat rand server heartbeat.
func (s *Server) RandServerHearbeat() time.Duration {
return (minServerHeartbeat + time.Duration(rand.Int63n(int64(maxServerHeartbeat-minServerHeartbeat))))
}
// Close close the server.
func (s *Server) Close() (err error) {
return
}
func (s *Server) onlineproc() {
for {
var (
allRoomsCount map[string]int32
err error
)
roomCount := make(map[string]int32)
for _, bucket := range s.buckets {
for roomID, count := range bucket.RoomsCount() {
roomCount[roomID] += count
}
}
if allRoomsCount, err = s.RenewOnline(context.Background(), s.serverID, roomCount); err != nil {
time.Sleep(time.Second)
continue
}
for _, bucket := range s.buckets {
bucket.UpRoomsCount(allRoomsCount)
}
time.Sleep(time.Second * 10)
}
}
<|start_filename|>goim-nats/comet/channel.go<|end_filename|>
package comet
import (
"sync"
"github.com/tsingson/ex-goim/api/comet/grpc"
"github.com/tsingson/ex-goim/pkg/bufio"
)
// Channel used by message pusher send msg to write goroutine.
type Channel struct {
Room *Room
CliProto Ring
signal chan *grpc.Proto
Writer bufio.Writer
Reader bufio.Reader
Next *Channel
Prev *Channel
Mid int64 // memberid
Key string
IP string
watchOps map[int32]struct{}
mutex sync.RWMutex
}
// NewChannel new a channel.
func NewChannel(cli, svr int) *Channel {
c := new(Channel)
c.CliProto.Init(cli)
c.signal = make(chan *grpc.Proto, svr)
c.watchOps = make(map[int32]struct{})
return c
}
// Watch watch a operation.
func (c *Channel) Watch(accepts ...int32) {
c.mutex.Lock()
for _, op := range accepts {
c.watchOps[op] = struct{}{}
}
c.mutex.Unlock()
}
// UnWatch unwatch an operation
func (c *Channel) UnWatch(accepts ...int32) {
c.mutex.Lock()
for _, op := range accepts {
delete(c.watchOps, op)
}
c.mutex.Unlock()
}
// NeedPush verify if in watch.
func (c *Channel) NeedPush(op int32) bool {
c.mutex.RLock()
if _, ok := c.watchOps[op]; ok {
c.mutex.RUnlock()
return true
}
c.mutex.RUnlock()
return false
}
// Push server push message.
func (c *Channel) Push(p *grpc.Proto) (err error) {
select {
case c.signal <- p:
default:
}
return
}
// Ready check the channel ready or close?
func (c *Channel) Ready() *grpc.Proto {
return <-c.signal
}
// Signal send signal to the channel, protocol ready.
func (c *Channel) Signal() {
c.signal <- grpc.ProtoReady
}
// Close close the channel.
func (c *Channel) Close() {
c.signal <- grpc.ProtoFinish
}
<|start_filename|>cmd/nats/job/main.go<|end_filename|>
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"github.com/tsingson/discovery/naming"
"github.com/tsingson/ex-goim/goim-nats/job"
"github.com/tsingson/ex-goim/goim-nats/job/conf"
"github.com/tsingson/ex-goim/pkg/utils"
resolver "github.com/tsingson/discovery/naming/grpc"
log "github.com/tsingson/zaplogger"
)
var (
ver = "2.0.0"
cfg *conf.JobConfig
)
func main() {
path, _ := utils.GetCurrentExecDir()
confPath := path + "/job-config.toml"
flag.Parse()
cfg, err := conf.Load(confPath)
if err != nil {
panic(err)
}
log.Infof("goim-job [version: %s env: %+v] start", ver, cfg.Env)
// grpc register naming
dis := naming.New(cfg.Discovery)
resolver.Register(dis)
// job
j := job.New(cfg)
go j.Consume()
// signal
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Infof("goim-job get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
j.Close()
log.Infof("goim-job [version: %s] exit", ver)
// log.Flush()
return
case syscall.SIGHUP:
default:
return
}
}
}
<|start_filename|>goim-nats/comet/grpc/server.go<|end_filename|>
package grpc
import (
"context"
"net"
"time"
"github.com/tsingson/ex-goim/goim-nats/comet/conf"
pb "github.com/tsingson/ex-goim/api/comet/grpc"
"github.com/tsingson/ex-goim/goim-nats/comet"
"github.com/tsingson/ex-goim/goim-nats/comet/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
)
// New comet grpc Server.
func New(c *conf.RPCServer, s *comet.Server) *grpc.Server {
keepParams := grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionIdle: time.Duration(c.IdleTimeout),
MaxConnectionAgeGrace: time.Duration(c.ForceCloseWait),
Time: time.Duration(c.KeepAliveInterval),
Timeout: time.Duration(c.KeepAliveTimeout),
MaxConnectionAge: time.Duration(c.MaxLifeTime),
})
srv := grpc.NewServer(keepParams)
pb.RegisterCometServer(srv, &Server{s})
lis, err := net.Listen(c.Network, c.Addr)
if err != nil {
panic(err)
}
go func() {
if err := srv.Serve(lis); err != nil {
panic(err)
}
}()
return srv
}
type Server struct {
srv *comet.Server
}
type CometGrpcServer = Server
var _ pb.CometServer = &Server{}
// Ping Service
func (s *Server) Ping(ctx context.Context, req *pb.Empty) (*pb.Empty, error) {
return &pb.Empty{}, nil
}
// Close Service
func (s *Server) Close(ctx context.Context, req *pb.Empty) (*pb.Empty, error) {
// TODO: some graceful close
return &pb.Empty{}, nil
}
// PushMsg push a message to specified sub keys.
func (s *Server) PushMsg(ctx context.Context, req *pb.PushMsgReq) (reply *pb.PushMsgReply, err error) {
if len(req.Keys) == 0 || req.Proto == nil {
return nil, errors.ErrPushMsgArg
}
for _, key := range req.Keys {
if channel := s.srv.Bucket(key).Channel(key); channel != nil {
if !channel.NeedPush(req.ProtoOp) {
continue
}
if err = channel.Push(req.Proto); err != nil {
return
}
}
}
return &pb.PushMsgReply{}, nil
}
// Broadcast broadcast msg to all user.
func (s *Server) Broadcast(ctx context.Context, req *pb.BroadcastReq) (*pb.BroadcastReply, error) {
if req.Proto == nil {
return nil, errors.ErrBroadCastArg
}
// TODO use broadcast queue
go func() {
for _, bucket := range s.srv.Buckets() {
bucket.Broadcast(req.GetProto(), req.ProtoOp)
if req.Speed > 0 {
t := bucket.ChannelCount() / int(req.Speed)
time.Sleep(time.Duration(t) * time.Second)
}
}
}()
return &pb.BroadcastReply{}, nil
}
// BroadcastRoom broadcast msg to specified room.
func (s *Server) BroadcastRoom(ctx context.Context, req *pb.BroadcastRoomReq) (*pb.BroadcastRoomReply, error) {
if req.Proto == nil || req.RoomID == "" {
return nil, errors.ErrBroadCastRoomArg
}
for _, bucket := range s.srv.Buckets() {
bucket.BroadcastRoom(req)
}
return &pb.BroadcastRoomReply{}, nil
}
// Rooms gets all the room ids for the Server.
func (s *Server) Rooms(ctx context.Context, req *pb.RoomsReq) (*pb.RoomsReply, error) {
var (
roomIds = make(map[string]bool)
)
for _, bucket := range s.srv.Buckets() {
for roomID := range bucket.Rooms() {
roomIds[roomID] = true
}
}
return &pb.RoomsReply{Rooms: roomIds}, nil
}
<|start_filename|>goim-nats/logic/conn.go<|end_filename|>
package logic
import (
"context"
"encoding/json"
"time"
"github.com/tsingson/uuid"
log "github.com/tsingson/zaplogger"
"github.com/tsingson/ex-goim/api/comet/grpc"
"github.com/tsingson/ex-goim/goim-nats/model"
)
// Connect connected a conn.
func (l *Logic) Connect(c context.Context, server, cookie string, token []byte) (mid int64, key, roomID string, accepts []int32, hb int64, err error) {
var params struct {
Mid int64 `json:"mid"`
Key string `json:"key"`
RoomID string `json:"room_id"`
Platform string `json:"platform"`
Accepts []int32 `json:"accepts"`
}
if err = json.Unmarshal(token, ¶ms); err != nil {
log.Errorf("json.Unmarshal(%s) error(%v)", token, err)
return
}
mid = params.Mid
roomID = params.RoomID
accepts = params.Accepts
hb = int64(l.c.Node.Heartbeat) * int64(l.c.Node.HeartbeatMax)
if key = params.Key; key == "" {
keyUuid, _ := uuid.NewV4()
key = keyUuid.String()
}
if err = l.dao.AddMapping(c, mid, key, server); err != nil {
log.Errorf("l.dao.AddMapping(%d,%s,%s) error(%v)", mid, key, server, err)
}
log.Infof("conn connected key:%s server:%s mid:%d token:%s", key, server, mid, token)
return
}
// Disconnect disconnect a conn.
func (l *Logic) Disconnect(c context.Context, mid int64, key, server string) (has bool, err error) {
if has, err = l.dao.DelMapping(c, mid, key, server); err != nil {
log.Errorf("l.dao.DelMapping(%d,%s) error(%v)", mid, key, server)
return
}
log.Infof("conn disconnected key:%s server:%s mid:%d", key, server, mid)
return
}
// Heartbeat heartbeat a conn.
func (l *Logic) Heartbeat(c context.Context, mid int64, key, server string) (err error) {
has, err := l.dao.ExpireMapping(c, mid, key)
if err != nil {
log.Errorf("l.dao.ExpireMapping(%d,%s,%s) error(%v)", mid, key, server, err)
return
}
if !has {
if err = l.dao.AddMapping(c, mid, key, server); err != nil {
log.Errorf("l.dao.AddMapping(%d,%s,%s) error(%v)", mid, key, server, err)
return
}
}
log.Infof("conn heartbeat key:%s server:%s mid:%d", key, server, mid)
return
}
// RenewOnline renew a server online.
func (l *Logic) RenewOnline(c context.Context, server string, roomCount map[string]int32) (map[string]int32, error) {
online := &model.Online{
Server: server,
RoomCount: roomCount,
Updated: time.Now().Unix(),
}
if err := l.dao.AddServerOnline(context.Background(), server, online); err != nil {
return nil, err
}
return l.roomCount, nil
}
// Receive receive a message.
func (l *Logic) Receive(c context.Context, mid int64, proto *grpc.Proto) (err error) {
log.Infof("receive mid:%d message:%+v", mid, proto)
return
}
<|start_filename|>api/comet/grpc/apipb_test.go<|end_filename|>
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: api.proto
package grpc
import (
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
github_com_gogo_protobuf_jsonpb "github.com/gogo/protobuf/jsonpb"
github_com_golang_protobuf_proto "github.com/golang/protobuf/proto"
proto "github.com/golang/protobuf/proto"
math "math"
math_rand "math/rand"
testing "testing"
time "time"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
func TestProtoProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedProto(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Proto{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestProtoMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedProto(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Proto{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkProtoProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*Proto, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedProto(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkProtoProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedProto(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &Proto{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestEmptyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedEmpty(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Empty{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestEmptyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedEmpty(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Empty{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkEmptyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*Empty, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedEmpty(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkEmptyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedEmpty(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &Empty{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestPushMsgReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PushMsgReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestPushMsgReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PushMsgReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkPushMsgReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*PushMsgReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedPushMsgReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkPushMsgReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedPushMsgReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &PushMsgReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestPushMsgReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PushMsgReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestPushMsgReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PushMsgReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkPushMsgReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*PushMsgReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedPushMsgReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkPushMsgReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedPushMsgReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &PushMsgReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestBroadcastReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestBroadcastReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkBroadcastReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*BroadcastReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedBroadcastReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkBroadcastReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedBroadcastReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &BroadcastReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestBroadcastReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestBroadcastReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkBroadcastReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*BroadcastReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedBroadcastReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkBroadcastReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedBroadcastReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &BroadcastReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestBroadcastRoomReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastRoomReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestBroadcastRoomReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastRoomReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkBroadcastRoomReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*BroadcastRoomReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedBroadcastRoomReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkBroadcastRoomReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedBroadcastRoomReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &BroadcastRoomReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestBroadcastRoomReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastRoomReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestBroadcastRoomReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastRoomReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkBroadcastRoomReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*BroadcastRoomReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedBroadcastRoomReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkBroadcastRoomReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedBroadcastRoomReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &BroadcastRoomReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestRoomsReqProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReq(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &RoomsReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestRoomsReqMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReq(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &RoomsReq{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkRoomsReqProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*RoomsReq, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedRoomsReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkRoomsReqProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedRoomsReq(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &RoomsReq{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestRoomsReplyProto(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReply(popr, false)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &RoomsReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
littlefuzz := make([]byte, len(dAtA))
copy(littlefuzz, dAtA)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
if len(littlefuzz) > 0 {
fuzzamount := 100
for i := 0; i < fuzzamount; i++ {
littlefuzz[popr.Intn(len(littlefuzz))] = byte(popr.Intn(256))
littlefuzz = append(littlefuzz, byte(popr.Intn(256)))
}
// shouldn't panic
_ = github_com_golang_protobuf_proto.Unmarshal(littlefuzz, msg)
}
}
func TestRoomsReplyMarshalTo(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReply(popr, false)
size := p.Size()
dAtA := make([]byte, size)
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
_, err := p.MarshalTo(dAtA)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &RoomsReply{}
if err := github_com_golang_protobuf_proto.Unmarshal(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
for i := range dAtA {
dAtA[i] = byte(popr.Intn(256))
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func BenchmarkRoomsReplyProtoMarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*RoomsReply, 10000)
for i := 0; i < 10000; i++ {
pops[i] = NewPopulatedRoomsReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(pops[i%10000])
if err != nil {
panic(err)
}
total += len(dAtA)
}
b.SetBytes(int64(total / b.N))
}
func BenchmarkRoomsReplyProtoUnmarshal(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
datas := make([][]byte, 10000)
for i := 0; i < 10000; i++ {
dAtA, err := github_com_golang_protobuf_proto.Marshal(NewPopulatedRoomsReply(popr, false))
if err != nil {
panic(err)
}
datas[i] = dAtA
}
msg := &RoomsReply{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += len(datas[i%10000])
if err := github_com_golang_protobuf_proto.Unmarshal(datas[i%10000], msg); err != nil {
panic(err)
}
}
b.SetBytes(int64(total / b.N))
}
func TestProtoJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedProto(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Proto{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestEmptyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedEmpty(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &Empty{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestPushMsgReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PushMsgReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestPushMsgReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &PushMsgReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestBroadcastReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestBroadcastReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestBroadcastRoomReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastRoomReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestBroadcastRoomReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &BroadcastRoomReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestRoomsReqJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReq(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &RoomsReq{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestRoomsReplyJSON(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReply(popr, true)
marshaler := github_com_gogo_protobuf_jsonpb.Marshaler{}
jsondata, err := marshaler.MarshalToString(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
msg := &RoomsReply{}
err = github_com_gogo_protobuf_jsonpb.UnmarshalString(jsondata, msg)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Json Equal %#v", seed, msg, p)
}
}
func TestProtoProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedProto(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &Proto{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestProtoProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedProto(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &Proto{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestEmptyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedEmpty(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &Empty{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestEmptyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedEmpty(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &Empty{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestPushMsgReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &PushMsgReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestPushMsgReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &PushMsgReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestPushMsgReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &PushMsgReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestPushMsgReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &PushMsgReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestBroadcastReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &BroadcastReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestBroadcastReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &BroadcastReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestBroadcastReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &BroadcastReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestBroadcastReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &BroadcastReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestBroadcastRoomReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &BroadcastRoomReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestBroadcastRoomReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &BroadcastRoomReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestBroadcastRoomReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &BroadcastRoomReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestBroadcastRoomReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &BroadcastRoomReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestRoomsReqProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReq(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &RoomsReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestRoomsReqProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReq(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &RoomsReq{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestRoomsReplyProtoText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReply(popr, true)
dAtA := github_com_golang_protobuf_proto.MarshalTextString(p)
msg := &RoomsReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestRoomsReplyProtoCompactText(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReply(popr, true)
dAtA := github_com_golang_protobuf_proto.CompactTextString(p)
msg := &RoomsReply{}
if err := github_com_golang_protobuf_proto.UnmarshalText(dAtA, msg); err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
if !p.Equal(msg) {
t.Fatalf("seed = %d, %#v !Proto %#v", seed, msg, p)
}
}
func TestProtoSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedProto(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkProtoSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*Proto, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedProto(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestEmptySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedEmpty(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkEmptySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*Empty, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedEmpty(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestPushMsgReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkPushMsgReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*PushMsgReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedPushMsgReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestPushMsgReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedPushMsgReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkPushMsgReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*PushMsgReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedPushMsgReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestBroadcastReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkBroadcastReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*BroadcastReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedBroadcastReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestBroadcastReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkBroadcastReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*BroadcastReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedBroadcastReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestBroadcastRoomReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkBroadcastRoomReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*BroadcastRoomReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedBroadcastRoomReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestBroadcastRoomReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedBroadcastRoomReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkBroadcastRoomReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*BroadcastRoomReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedBroadcastRoomReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestRoomsReqSize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReq(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkRoomsReqSize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*RoomsReq, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedRoomsReq(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
func TestRoomsReplySize(t *testing.T) {
seed := time.Now().UnixNano()
popr := math_rand.New(math_rand.NewSource(seed))
p := NewPopulatedRoomsReply(popr, true)
size2 := github_com_golang_protobuf_proto.Size(p)
dAtA, err := github_com_golang_protobuf_proto.Marshal(p)
if err != nil {
t.Fatalf("seed = %d, err = %v", seed, err)
}
size := p.Size()
if len(dAtA) != size {
t.Errorf("seed = %d, size %v != marshalled size %v", seed, size, len(dAtA))
}
if size2 != size {
t.Errorf("seed = %d, size %v != before marshal proto.Size %v", seed, size, size2)
}
size3 := github_com_golang_protobuf_proto.Size(p)
if size3 != size {
t.Errorf("seed = %d, size %v != after marshal proto.Size %v", seed, size, size3)
}
}
func BenchmarkRoomsReplySize(b *testing.B) {
popr := math_rand.New(math_rand.NewSource(616))
total := 0
pops := make([]*RoomsReply, 1000)
for i := 0; i < 1000; i++ {
pops[i] = NewPopulatedRoomsReply(popr, false)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
total += pops[i%1000].Size()
}
b.SetBytes(int64(total / b.N))
}
//These tests are generated by github.com/gogo/protobuf/plugin/testgen
<|start_filename|>goim-nats/comet/errors/errors.go<|end_filename|>
package errors
import (
"golang.org/x/xerrors"
)
// .
var (
// server
ErrHandshake = xerrors.New("handshake failed")
ErrOperation = xerrors.New("request operation not valid")
// ring
ErrRingEmpty = xerrors.New("ring buffer empty")
ErrRingFull = xerrors.New("ring buffer full")
// timer
ErrTimerFull = xerrors.New("timer full")
ErrTimerEmpty = xerrors.New("timer empty")
ErrTimerNoItem = xerrors.New("timer item not exist")
// channel
ErrPushMsgArg = xerrors.New("rpc pushmsg arg error")
ErrPushMsgsArg = xerrors.New("rpc pushmsgs arg error")
ErrMPushMsgArg = xerrors.New("rpc mpushmsg arg error")
ErrMPushMsgsArg = xerrors.New("rpc mpushmsgs arg error")
// bucket
ErrBroadCastArg = xerrors.New("rpc broadcast arg error")
ErrBroadCastRoomArg = xerrors.New("rpc broadcast room arg error")
// room
ErrRoomDroped = xerrors.New("room droped")
// rpc
ErrLogic = xerrors.New("logic rpc is not available")
)
<|start_filename|>goim-nats/model/interface.go<|end_filename|>
package model
import (
"context"
)
type Dao interface {
PushMsg(c context.Context, op int32, server string, keys []string, msg []byte) (err error)
BroadcastRoomMsg(c context.Context, op int32, room string, msg []byte) (err error)
AddMapping(c context.Context, mid int64, key, server string) (err error)
ExpireMapping(c context.Context, mid int64, key string) (has bool, err error)
DelMapping(c context.Context, mid int64, key, server string) (has bool, err error)
ServersByKeys(c context.Context, keys []string) (res []string, err error)
KeysByMids(c context.Context, mids []int64) (ress map[string]string, olMids []int64, err error)
AddServerOnline(c context.Context, server string, online *Online) (err error)
ServerOnline(c context.Context, server string) (online *Online, err error)
DelServerOnline(c context.Context, server string) (err error)
Close() error
}
<|start_filename|>goim-nats/comet/conf/conf.go<|end_filename|>
package conf
import (
"time"
"github.com/BurntSushi/toml"
"github.com/imdario/mergo"
"github.com/tsingson/discovery/naming"
"golang.org/x/xerrors"
xtime "github.com/tsingson/ex-goim/pkg/time"
)
var (
// Conf configuration for comet
Conf *Config
)
// Config is comet config.
type Config struct {
Debug bool
Env *Env
Discovery *naming.Config
TCP *TCP
Websocket *Websocket
Protocol *Protocol
Bucket *Bucket
RPCClient *RPCClient
RPCServer *RPCServer
Whitelist *Whitelist
}
// CometConfig is alias name
type CometConfig = Config
// Env is env config.
type Env struct {
Region string
Zone string
DeployEnv string
Host string
Weight int64
Offline bool
Addrs []string
}
// RPCClient is RPC client config.
type RPCClient struct {
Dial xtime.Duration
Timeout xtime.Duration
}
// RPCServer is RPC server config.
type RPCServer struct {
Network string
Addr string
Timeout xtime.Duration
IdleTimeout xtime.Duration
MaxLifeTime xtime.Duration
ForceCloseWait xtime.Duration
KeepAliveInterval xtime.Duration
KeepAliveTimeout xtime.Duration
}
// TCP is tcp config.
type TCP struct {
Bind []string
Sndbuf int
Rcvbuf int
KeepAlive bool
Reader int
ReadBuf int
ReadBufSize int
Writer int
WriteBuf int
WriteBufSize int
}
// Websocket is websocket config.
type Websocket struct {
Bind []string
TLSOpen bool
TLSBind []string
CertFile string
PrivateFile string
}
// Protocol is protocol config.
type Protocol struct {
Timer int
TimerSize int
SvrProto int
CliProto int
HandshakeTimeout xtime.Duration
}
// Bucket is bucket config.
type Bucket struct {
Size int
Channel int
Room int
RoutineAmount uint64
RoutineSize int
}
// Whitelist is white list config.
type Whitelist struct {
Whitelist []int64
WhiteLog string
}
// Load init config.
func Load(path string) (cfg *Config, err error) {
if len(path) == 0 {
return cfg, xerrors.New("config path is nil")
}
Conf = Default()
cfg = Default()
_, err = toml.DecodeFile(path, &cfg)
if err != nil {
return
}
err = mergo.Merge(&Conf, cfg, mergo.WithOverride)
if err != nil {
return Conf, err
}
return Conf, nil
}
// Default new a config with specified defualt value.
func Default() *Config {
return &Config{
Debug: true,
Env: &Env{
Region: "china",
Zone: "gd",
DeployEnv: "dev",
Host: "comet",
Weight: 100,
Addrs: []string{"127.0.0.1:3101"},
Offline: false,
},
Discovery: &naming.Config{
Nodes: []string{"127.0.0.1:7171"},
Region: "china",
Zone: "gd",
Env: "dev",
Host: "discovery",
},
RPCClient: &RPCClient{
Dial: xtime.Duration(time.Second),
Timeout: xtime.Duration(time.Second),
},
RPCServer: &RPCServer{
Network: "tcp",
Addr: ":3109",
Timeout: xtime.Duration(time.Second),
IdleTimeout: xtime.Duration(time.Second * 60),
MaxLifeTime: xtime.Duration(time.Hour * 2),
ForceCloseWait: xtime.Duration(time.Second * 20),
KeepAliveInterval: xtime.Duration(time.Second * 60),
KeepAliveTimeout: xtime.Duration(time.Second * 20),
},
TCP: &TCP{
Bind: []string{":3101"},
Sndbuf: 4096,
Rcvbuf: 4096,
KeepAlive: false,
Reader: 32,
ReadBuf: 1024,
ReadBufSize: 8192,
Writer: 32,
WriteBuf: 1024,
WriteBufSize: 8192,
},
Websocket: &Websocket{
Bind: []string{":3102"},
},
Protocol: &Protocol{
Timer: 32,
TimerSize: 2048,
CliProto: 5,
SvrProto: 10,
HandshakeTimeout: xtime.Duration(time.Second * 5),
},
Bucket: &Bucket{
Size: 32,
Channel: 1024,
Room: 1024,
RoutineAmount: 32,
RoutineSize: 1024,
},
}
}
<|start_filename|>goim-nats/logic/logic_test.go<|end_filename|>
package logic
import (
"context"
"os"
"testing"
"github.com/tsingson/ex-goim/goim-nats/logic/conf"
)
var (
lg *NatsLogic
)
func TestMain(m *testing.M) {
lg = New(conf.Conf)
if err := lg.Ping(context.TODO()); err != nil {
panic(err)
}
os.Exit(m.Run())
}
<|start_filename|>goim-nats/model/logicInterface.go<|end_filename|>
package model
import (
"context"
"github.com/tsingson/discovery/naming"
"github.com/tsingson/ex-goim/api/comet/grpc"
pb "github.com/tsingson/ex-goim/api/logic/grpc"
)
// Action interface for logic
type LogicProcess interface {
Connect(c context.Context, server, cookie string, token []byte) (mid int64, key, roomID string, accepts []int32, hb int64, err error)
Disconnect(c context.Context, mid int64, key, server string) (has bool, err error)
Heartbeat(c context.Context, mid int64, key, server string) (err error)
RenewOnline(c context.Context, server string, roomCount map[string]int32) (map[string]int32, error)
Receive(c context.Context, mid int64, proto *grpc.Proto) (err error)
PushKeys(c context.Context, op int32, keys []string, msg []byte) (err error)
PushMids(c context.Context, op int32, mids []int64, msg []byte) (err error)
PushRoom(c context.Context, op int32, typ, room string, msg []byte) (err error)
PushAll(c context.Context, op, speed int32, msg []byte) (err error)
NodesInstances(c context.Context) (res []*naming.Instance)
NodesWeighted(c context.Context, platform, clientIP string) *pb.NodesReply
Ping(c context.Context) (err error)
Close()
OnlineTop(c context.Context, typ string, n int) (tops []*Top, err error)
OnlineRoom(c context.Context, typ string, rooms []string) (res map[string]int32, err error)
OnlineTotal(c context.Context) (int64, int64)
}
<|start_filename|>goim-nats/job/job.go<|end_filename|>
package job
import (
"context"
"fmt"
"sync"
"time"
"github.com/gogo/protobuf/proto"
"github.com/liftbridge-io/go-liftbridge"
"github.com/tsingson/discovery/naming"
"github.com/tsingson/ex-goim/goim-nats/job/conf"
"github.com/tsingson/ex-goim/goim-nats/job/grpc-client"
liftprpc "github.com/liftbridge-io/go-liftbridge/liftbridge-grpc"
pb "github.com/tsingson/ex-goim/api/logic/grpc"
log "github.com/tsingson/zaplogger"
)
// NatsJob is push job.
type Job struct {
c *conf.JobConfig
consumer liftbridge.Client
cometServers map[string]*grpc_client.Comet
rooms map[string]*Room
roomsMutex sync.RWMutex
}
type NatsJob = Job
// var natsCfg *conf.Nats
//
// func init() {
// natsCfg = &conf.Nats{
// Channel: "channel",
// ChannelID: "channel-stream",
// Group: "group",
// LiftAddr: "localhost:9292", // address for lift-bridge
// NatsAddr: "localhost:4222",
// }
// }
// New new a push job.
func New(cfg *conf.JobConfig) *Job {
cl, err := newLiftClient(cfg)
if err != nil {
return nil
}
j := &NatsJob{
c: cfg,
consumer: cl,
rooms: make(map[string]*Room),
}
// j.WatchComet(cfg.Discovery)
return j
}
// WatchComet watch commet active
func (j *Job) WatchComet(c *naming.Config) {
dis := naming.New(c)
resolver := dis.Build("goim.comet")
event := resolver.Watch()
select {
case _, ok := <-event:
if !ok {
panic("WatchComet init failed")
}
if ins, ok := resolver.Fetch(); ok {
if err := j.newAddress(ins.Instances); err != nil {
panic(err)
}
log.Infof("WatchComet init newAddress:%+v", ins)
}
case <-time.After(10 * time.Second):
log.Error("WatchComet init instances timeout")
}
go func() {
for {
if _, ok := <-event; !ok {
log.Info("WatchComet exit")
return
}
ins, ok := resolver.Fetch()
if ok {
if err := j.newAddress(ins.Instances); err != nil {
log.Errorf("WatchComet newAddress(%+v) error(%+v)", ins, err)
continue
}
log.Infof("WatchComet change newAddress:%+v", ins)
}
}
}()
}
func (j *Job) newAddress(insMap map[string][]*naming.Instance) error {
ins := insMap[j.c.Env.Zone]
if len(ins) == 0 {
return fmt.Errorf("WatchComet instance is empty")
}
comets := map[string]*grpc_client.Comet{}
for _, in := range ins {
if old, ok := j.cometServers[in.Hostname]; ok {
comets[in.Hostname] = old
continue
}
c, err := grpc_client.NewComet(in, j.c.Comet)
if err != nil {
log.Errorf("WatchComet NewComet(%+v) error(%v)", in, err)
return err
}
comets[in.Hostname] = c
log.Infof("WatchComet AddComet grpc:%+v", in)
}
for key, old := range j.cometServers {
if _, ok := comets[key]; !ok {
old.Cancel()
log.Infof("WatchComet DelComet:%s", key)
}
}
j.cometServers = comets
return nil
}
// newLiftClient new liftbridge client
func newLiftClient(cfg *conf.JobConfig) (liftbridge.Client, error) {
// liftAddr := "localhost:9292" // address for lift-bridge
return liftbridge.Connect([]string{cfg.Nats.LiftAddr})
}
// Subscribe get message
func (d *Job) Subscribe(channel, channelID string) error {
ctx := context.Background()
if err := d.consumer.Subscribe(ctx, channel, channelID, func(msg *liftprpc.Message, err error) {
if err != nil {
return
}
log.Info(msg.Offset, "--> ", string(msg.Value))
}); err != nil {
return err
}
<-ctx.Done()
return nil
}
// Consume messages, watch signals
func (j *Job) Consume() {
ctx := context.Background()
// process push message
pushMsg := new(pb.PushMsg)
if err := j.consumer.Subscribe(ctx, j.c.Nats.Channel, j.c.Nats.ChannelID, func(msg *liftprpc.Message, err error) {
if err != nil {
return
}
log.Info(msg.Offset, "------------> ", string(msg.Value))
if err := proto.Unmarshal(msg.Value, pushMsg); err != nil {
log.Errorf("proto.Unmarshal(%v) error(%v)", msg, err)
return
}
if err := j.push(context.Background(), pushMsg); err != nil {
log.Errorf("j.push(%v) error(%v)", pushMsg, err)
}
log.Infof("consume: %d %s \t%+v", msg.Offset, msg.Key, pushMsg)
}); err != nil {
return
}
<-ctx.Done()
return
}
// ConsumeCheck messages, watch signals
func (j *Job) ConsumeCheck() {
ctx := context.Background()
if err := j.consumer.Subscribe(ctx, j.c.Nats.Channel, j.c.Nats.ChannelID, func(msg *liftprpc.Message, err error) {
if err != nil {
return
}
log.Info(msg.Offset, "------------> ", string(msg.Value))
// process push message
pushMsg := new(pb.PushMsg)
if err := proto.Unmarshal(msg.Value, pushMsg); err != nil {
log.Errorf("proto.Unmarshal(%v) error(%v)", msg, err)
return
}
// if err := j.push(context.Background(), pushMsg); err != nil {
// log.Errorf("j.push(%v) error(%v)", pushMsg, err)
// }
log.Infof("consume: %d %s \t%+v", msg.Offset, msg.Key, pushMsg)
}); err != nil {
return
}
<-ctx.Done()
return
}
// Close close resounces.
func (j *Job) Close() error {
if j.consumer != nil {
return j.consumer.Close()
}
return nil
}
<|start_filename|>goim-nats/comet/discovery.go<|end_filename|>
package comet
import (
"context"
"time"
"github.com/tsingson/discovery/naming"
log "github.com/tsingson/zaplogger"
)
// Register register to discovery services
func Register(cfg *naming.Config, appid string, addrs []string) (context.CancelFunc, error) {
discoveryClient := naming.New(cfg)
ins := &naming.Instance{
Zone: cfg.Zone,
Env: cfg.Env,
AppID: appid, // "goim.comet",
// Hostname:"", // NOTE: hostname 不需要,会优先使用discovery new时Config配置的值,如没有则从os.Hostname方法获取!!!
Addrs: addrs, // []string{"http://192.168.127.12:8888"},
LastTs: time.Now().Unix(),
Metadata: map[string]string{"weight": "10"},
}
log.Info("register")
return discoveryClient.Register(ins)
// defer cancel() // NOTE: 注意一般在进程退出的时候执行,会调用discovery的cancel接口,使实例从discovery移除
}
<|start_filename|>api/logic/grpc/api.pb.go<|end_filename|>
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: api.proto
package grpc
import (
context "context"
encoding_binary "encoding/binary"
fmt "fmt"
_ "github.com/gogo/protobuf/gogoproto"
proto "github.com/golang/protobuf/proto"
grpc "github.com/tsingson/ex-goim/api/comet/grpc"
grpc1 "google.golang.org/grpc"
io "io"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type PushMsg_Type int32
const (
PushMsg_PUSH PushMsg_Type = 0
PushMsg_ROOM PushMsg_Type = 1
PushMsg_BROADCAST PushMsg_Type = 2
)
var PushMsg_Type_name = map[int32]string{
0: "PUSH",
1: "ROOM",
2: "BROADCAST",
}
var PushMsg_Type_value = map[string]int32{
"PUSH": 0,
"ROOM": 1,
"BROADCAST": 2,
}
func (x PushMsg_Type) String() string {
return proto.EnumName(PushMsg_Type_name, int32(x))
}
func (PushMsg_Type) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{0, 0}
}
type PushMsg struct {
Type PushMsg_Type `protobuf:"varint,1,opt,name=type,proto3,enum=goim.logic.PushMsg_Type" json:"type,omitempty"`
Operation int32 `protobuf:"varint,2,opt,name=operation,proto3" json:"operation,omitempty"`
Speed int32 `protobuf:"varint,3,opt,name=speed,proto3" json:"speed,omitempty"`
Server string `protobuf:"bytes,4,opt,name=server,proto3" json:"server,omitempty"`
Room string `protobuf:"bytes,5,opt,name=room,proto3" json:"room,omitempty"`
Keys []string `protobuf:"bytes,6,rep,name=keys,proto3" json:"keys,omitempty"`
Msg []byte `protobuf:"bytes,7,opt,name=msg,proto3" json:"msg,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PushMsg) Reset() { *m = PushMsg{} }
func (m *PushMsg) String() string { return proto.CompactTextString(m) }
func (*PushMsg) ProtoMessage() {}
func (*PushMsg) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{0}
}
func (m *PushMsg) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PushMsg) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PushMsg.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *PushMsg) XXX_Merge(src proto.Message) {
xxx_messageInfo_PushMsg.Merge(m, src)
}
func (m *PushMsg) XXX_Size() int {
return m.Size()
}
func (m *PushMsg) XXX_DiscardUnknown() {
xxx_messageInfo_PushMsg.DiscardUnknown(m)
}
var xxx_messageInfo_PushMsg proto.InternalMessageInfo
func (m *PushMsg) GetType() PushMsg_Type {
if m != nil {
return m.Type
}
return PushMsg_PUSH
}
func (m *PushMsg) GetOperation() int32 {
if m != nil {
return m.Operation
}
return 0
}
func (m *PushMsg) GetSpeed() int32 {
if m != nil {
return m.Speed
}
return 0
}
func (m *PushMsg) GetServer() string {
if m != nil {
return m.Server
}
return ""
}
func (m *PushMsg) GetRoom() string {
if m != nil {
return m.Room
}
return ""
}
func (m *PushMsg) GetKeys() []string {
if m != nil {
return m.Keys
}
return nil
}
func (m *PushMsg) GetMsg() []byte {
if m != nil {
return m.Msg
}
return nil
}
type CloseReply struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *CloseReply) Reset() { *m = CloseReply{} }
func (m *CloseReply) String() string { return proto.CompactTextString(m) }
func (*CloseReply) ProtoMessage() {}
func (*CloseReply) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{1}
}
func (m *CloseReply) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *CloseReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_CloseReply.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *CloseReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_CloseReply.Merge(m, src)
}
func (m *CloseReply) XXX_Size() int {
return m.Size()
}
func (m *CloseReply) XXX_DiscardUnknown() {
xxx_messageInfo_CloseReply.DiscardUnknown(m)
}
var xxx_messageInfo_CloseReply proto.InternalMessageInfo
type CloseReq struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *CloseReq) Reset() { *m = CloseReq{} }
func (m *CloseReq) String() string { return proto.CompactTextString(m) }
func (*CloseReq) ProtoMessage() {}
func (*CloseReq) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{2}
}
func (m *CloseReq) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *CloseReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_CloseReq.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *CloseReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_CloseReq.Merge(m, src)
}
func (m *CloseReq) XXX_Size() int {
return m.Size()
}
func (m *CloseReq) XXX_DiscardUnknown() {
xxx_messageInfo_CloseReq.DiscardUnknown(m)
}
var xxx_messageInfo_CloseReq proto.InternalMessageInfo
type PingReply struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PingReply) Reset() { *m = PingReply{} }
func (m *PingReply) String() string { return proto.CompactTextString(m) }
func (*PingReply) ProtoMessage() {}
func (*PingReply) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{3}
}
func (m *PingReply) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PingReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PingReply.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *PingReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_PingReply.Merge(m, src)
}
func (m *PingReply) XXX_Size() int {
return m.Size()
}
func (m *PingReply) XXX_DiscardUnknown() {
xxx_messageInfo_PingReply.DiscardUnknown(m)
}
var xxx_messageInfo_PingReply proto.InternalMessageInfo
type PingReq struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PingReq) Reset() { *m = PingReq{} }
func (m *PingReq) String() string { return proto.CompactTextString(m) }
func (*PingReq) ProtoMessage() {}
func (*PingReq) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{4}
}
func (m *PingReq) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *PingReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_PingReq.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *PingReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_PingReq.Merge(m, src)
}
func (m *PingReq) XXX_Size() int {
return m.Size()
}
func (m *PingReq) XXX_DiscardUnknown() {
xxx_messageInfo_PingReq.DiscardUnknown(m)
}
var xxx_messageInfo_PingReq proto.InternalMessageInfo
type ConnectReq struct {
Server string `protobuf:"bytes,1,opt,name=server,proto3" json:"server,omitempty"`
Cookie string `protobuf:"bytes,2,opt,name=cookie,proto3" json:"cookie,omitempty"`
Token []byte `protobuf:"bytes,3,opt,name=token,proto3" json:"token,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ConnectReq) Reset() { *m = ConnectReq{} }
func (*ConnectReq) ProtoMessage() {}
func (*ConnectReq) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{5}
}
func (m *ConnectReq) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ConnectReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ConnectReq.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ConnectReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_ConnectReq.Merge(m, src)
}
func (m *ConnectReq) XXX_Size() int {
return m.Size()
}
func (m *ConnectReq) XXX_DiscardUnknown() {
xxx_messageInfo_ConnectReq.DiscardUnknown(m)
}
var xxx_messageInfo_ConnectReq proto.InternalMessageInfo
func (m *ConnectReq) GetServer() string {
if m != nil {
return m.Server
}
return ""
}
func (m *ConnectReq) GetCookie() string {
if m != nil {
return m.Cookie
}
return ""
}
func (m *ConnectReq) GetToken() []byte {
if m != nil {
return m.Token
}
return nil
}
type ConnectReply struct {
Mid int64 `protobuf:"varint,1,opt,name=mid,proto3" json:"mid,omitempty"`
Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"`
RoomID string `protobuf:"bytes,3,opt,name=roomID,proto3" json:"roomID,omitempty"`
Accepts []int32 `protobuf:"varint,4,rep,packed,name=accepts,proto3" json:"accepts,omitempty"`
Heartbeat int64 `protobuf:"varint,5,opt,name=heartbeat,proto3" json:"heartbeat,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ConnectReply) Reset() { *m = ConnectReply{} }
func (m *ConnectReply) String() string { return proto.CompactTextString(m) }
func (*ConnectReply) ProtoMessage() {}
func (*ConnectReply) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{6}
}
func (m *ConnectReply) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ConnectReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ConnectReply.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ConnectReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_ConnectReply.Merge(m, src)
}
func (m *ConnectReply) XXX_Size() int {
return m.Size()
}
func (m *ConnectReply) XXX_DiscardUnknown() {
xxx_messageInfo_ConnectReply.DiscardUnknown(m)
}
var xxx_messageInfo_ConnectReply proto.InternalMessageInfo
func (m *ConnectReply) GetMid() int64 {
if m != nil {
return m.Mid
}
return 0
}
func (m *ConnectReply) GetKey() string {
if m != nil {
return m.Key
}
return ""
}
func (m *ConnectReply) GetRoomID() string {
if m != nil {
return m.RoomID
}
return ""
}
func (m *ConnectReply) GetAccepts() []int32 {
if m != nil {
return m.Accepts
}
return nil
}
func (m *ConnectReply) GetHeartbeat() int64 {
if m != nil {
return m.Heartbeat
}
return 0
}
type DisconnectReq struct {
Mid int64 `protobuf:"varint,1,opt,name=mid,proto3" json:"mid,omitempty"`
Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"`
Server string `protobuf:"bytes,3,opt,name=server,proto3" json:"server,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *DisconnectReq) Reset() { *m = DisconnectReq{} }
func (m *DisconnectReq) String() string { return proto.CompactTextString(m) }
func (*DisconnectReq) ProtoMessage() {}
func (*DisconnectReq) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{7}
}
func (m *DisconnectReq) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *DisconnectReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_DisconnectReq.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *DisconnectReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_DisconnectReq.Merge(m, src)
}
func (m *DisconnectReq) XXX_Size() int {
return m.Size()
}
func (m *DisconnectReq) XXX_DiscardUnknown() {
xxx_messageInfo_DisconnectReq.DiscardUnknown(m)
}
var xxx_messageInfo_DisconnectReq proto.InternalMessageInfo
func (m *DisconnectReq) GetMid() int64 {
if m != nil {
return m.Mid
}
return 0
}
func (m *DisconnectReq) GetKey() string {
if m != nil {
return m.Key
}
return ""
}
func (m *DisconnectReq) GetServer() string {
if m != nil {
return m.Server
}
return ""
}
type DisconnectReply struct {
Has bool `protobuf:"varint,1,opt,name=has,proto3" json:"has,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *DisconnectReply) Reset() { *m = DisconnectReply{} }
func (m *DisconnectReply) String() string { return proto.CompactTextString(m) }
func (*DisconnectReply) ProtoMessage() {}
func (*DisconnectReply) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{8}
}
func (m *DisconnectReply) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *DisconnectReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_DisconnectReply.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *DisconnectReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_DisconnectReply.Merge(m, src)
}
func (m *DisconnectReply) XXX_Size() int {
return m.Size()
}
func (m *DisconnectReply) XXX_DiscardUnknown() {
xxx_messageInfo_DisconnectReply.DiscardUnknown(m)
}
var xxx_messageInfo_DisconnectReply proto.InternalMessageInfo
func (m *DisconnectReply) GetHas() bool {
if m != nil {
return m.Has
}
return false
}
type HeartbeatReq struct {
Mid int64 `protobuf:"varint,1,opt,name=mid,proto3" json:"mid,omitempty"`
Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"`
Server string `protobuf:"bytes,3,opt,name=server,proto3" json:"server,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HeartbeatReq) Reset() { *m = HeartbeatReq{} }
func (m *HeartbeatReq) String() string { return proto.CompactTextString(m) }
func (*HeartbeatReq) ProtoMessage() {}
func (*HeartbeatReq) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{9}
}
func (m *HeartbeatReq) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *HeartbeatReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_HeartbeatReq.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *HeartbeatReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_HeartbeatReq.Merge(m, src)
}
func (m *HeartbeatReq) XXX_Size() int {
return m.Size()
}
func (m *HeartbeatReq) XXX_DiscardUnknown() {
xxx_messageInfo_HeartbeatReq.DiscardUnknown(m)
}
var xxx_messageInfo_HeartbeatReq proto.InternalMessageInfo
func (m *HeartbeatReq) GetMid() int64 {
if m != nil {
return m.Mid
}
return 0
}
func (m *HeartbeatReq) GetKey() string {
if m != nil {
return m.Key
}
return ""
}
func (m *HeartbeatReq) GetServer() string {
if m != nil {
return m.Server
}
return ""
}
type HeartbeatReply struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *HeartbeatReply) Reset() { *m = HeartbeatReply{} }
func (m *HeartbeatReply) String() string { return proto.CompactTextString(m) }
func (*HeartbeatReply) ProtoMessage() {}
func (*HeartbeatReply) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{10}
}
func (m *HeartbeatReply) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *HeartbeatReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_HeartbeatReply.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *HeartbeatReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_HeartbeatReply.Merge(m, src)
}
func (m *HeartbeatReply) XXX_Size() int {
return m.Size()
}
func (m *HeartbeatReply) XXX_DiscardUnknown() {
xxx_messageInfo_HeartbeatReply.DiscardUnknown(m)
}
var xxx_messageInfo_HeartbeatReply proto.InternalMessageInfo
type OnlineReq struct {
Server string `protobuf:"bytes,1,opt,name=server,proto3" json:"server,omitempty"`
RoomCount map[string]int32 `protobuf:"bytes,2,rep,name=roomCount,proto3" json:"roomCount,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *OnlineReq) Reset() { *m = OnlineReq{} }
func (*OnlineReq) ProtoMessage() {}
func (*OnlineReq) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{11}
}
func (m *OnlineReq) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *OnlineReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_OnlineReq.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *OnlineReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_OnlineReq.Merge(m, src)
}
func (m *OnlineReq) XXX_Size() int {
return m.Size()
}
func (m *OnlineReq) XXX_DiscardUnknown() {
xxx_messageInfo_OnlineReq.DiscardUnknown(m)
}
var xxx_messageInfo_OnlineReq proto.InternalMessageInfo
func (m *OnlineReq) GetServer() string {
if m != nil {
return m.Server
}
return ""
}
func (m *OnlineReq) GetRoomCount() map[string]int32 {
if m != nil {
return m.RoomCount
}
return nil
}
type OnlineReply struct {
AllRoomCount map[string]int32 `protobuf:"bytes,1,rep,name=allRoomCount,proto3" json:"allRoomCount,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *OnlineReply) Reset() { *m = OnlineReply{} }
func (*OnlineReply) ProtoMessage() {}
func (*OnlineReply) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{12}
}
func (m *OnlineReply) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *OnlineReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_OnlineReply.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *OnlineReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_OnlineReply.Merge(m, src)
}
func (m *OnlineReply) XXX_Size() int {
return m.Size()
}
func (m *OnlineReply) XXX_DiscardUnknown() {
xxx_messageInfo_OnlineReply.DiscardUnknown(m)
}
var xxx_messageInfo_OnlineReply proto.InternalMessageInfo
func (m *OnlineReply) GetAllRoomCount() map[string]int32 {
if m != nil {
return m.AllRoomCount
}
return nil
}
type ReceiveReq struct {
Mid int64 `protobuf:"varint,1,opt,name=mid,proto3" json:"mid,omitempty"`
Proto *grpc.Proto `protobuf:"bytes,2,opt,name=proto,proto3" json:"proto,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ReceiveReq) Reset() { *m = ReceiveReq{} }
func (m *ReceiveReq) String() string { return proto.CompactTextString(m) }
func (*ReceiveReq) ProtoMessage() {}
func (*ReceiveReq) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{13}
}
func (m *ReceiveReq) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ReceiveReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ReceiveReq.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ReceiveReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_ReceiveReq.Merge(m, src)
}
func (m *ReceiveReq) XXX_Size() int {
return m.Size()
}
func (m *ReceiveReq) XXX_DiscardUnknown() {
xxx_messageInfo_ReceiveReq.DiscardUnknown(m)
}
var xxx_messageInfo_ReceiveReq proto.InternalMessageInfo
func (m *ReceiveReq) GetMid() int64 {
if m != nil {
return m.Mid
}
return 0
}
func (m *ReceiveReq) GetProto() *grpc.Proto {
if m != nil {
return m.Proto
}
return nil
}
type ReceiveReply struct {
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *ReceiveReply) Reset() { *m = ReceiveReply{} }
func (m *ReceiveReply) String() string { return proto.CompactTextString(m) }
func (*ReceiveReply) ProtoMessage() {}
func (*ReceiveReply) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{14}
}
func (m *ReceiveReply) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *ReceiveReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_ReceiveReply.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *ReceiveReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_ReceiveReply.Merge(m, src)
}
func (m *ReceiveReply) XXX_Size() int {
return m.Size()
}
func (m *ReceiveReply) XXX_DiscardUnknown() {
xxx_messageInfo_ReceiveReply.DiscardUnknown(m)
}
var xxx_messageInfo_ReceiveReply proto.InternalMessageInfo
type NodesReq struct {
Platform string `protobuf:"bytes,1,opt,name=platform,proto3" json:"platform,omitempty"`
ClientIP string `protobuf:"bytes,2,opt,name=clientIP,proto3" json:"clientIP,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *NodesReq) Reset() { *m = NodesReq{} }
func (m *NodesReq) String() string { return proto.CompactTextString(m) }
func (*NodesReq) ProtoMessage() {}
func (*NodesReq) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{15}
}
func (m *NodesReq) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *NodesReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_NodesReq.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *NodesReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_NodesReq.Merge(m, src)
}
func (m *NodesReq) XXX_Size() int {
return m.Size()
}
func (m *NodesReq) XXX_DiscardUnknown() {
xxx_messageInfo_NodesReq.DiscardUnknown(m)
}
var xxx_messageInfo_NodesReq proto.InternalMessageInfo
func (m *NodesReq) GetPlatform() string {
if m != nil {
return m.Platform
}
return ""
}
func (m *NodesReq) GetClientIP() string {
if m != nil {
return m.ClientIP
}
return ""
}
type NodesReply struct {
Domain string `protobuf:"bytes,1,opt,name=domain,proto3" json:"domain"`
TcpPort int32 `protobuf:"varint,2,opt,name=tcpPort,proto3" json:"tcp_port"`
WsPort int32 `protobuf:"varint,3,opt,name=wsPort,proto3" json:"ws_port"`
WssPort int32 `protobuf:"varint,4,opt,name=wssPort,proto3" json:"wss_port"`
Heartbeat int32 `protobuf:"varint,5,opt,name=heartbeat,proto3" json:"heartbeat"`
Nodes []string `protobuf:"bytes,6,rep,name=nodes,proto3" json:"nodes"`
Backoff *Backoff `protobuf:"bytes,7,opt,name=backoff,proto3" json:"backoff"`
HeartbeatMax int32 `protobuf:"varint,8,opt,name=heartbeatMax,proto3" json:"heartbeat_max"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *NodesReply) Reset() { *m = NodesReply{} }
func (m *NodesReply) String() string { return proto.CompactTextString(m) }
func (*NodesReply) ProtoMessage() {}
func (*NodesReply) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{16}
}
func (m *NodesReply) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *NodesReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_NodesReply.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *NodesReply) XXX_Merge(src proto.Message) {
xxx_messageInfo_NodesReply.Merge(m, src)
}
func (m *NodesReply) XXX_Size() int {
return m.Size()
}
func (m *NodesReply) XXX_DiscardUnknown() {
xxx_messageInfo_NodesReply.DiscardUnknown(m)
}
var xxx_messageInfo_NodesReply proto.InternalMessageInfo
func (m *NodesReply) GetDomain() string {
if m != nil {
return m.Domain
}
return ""
}
func (m *NodesReply) GetTcpPort() int32 {
if m != nil {
return m.TcpPort
}
return 0
}
func (m *NodesReply) GetWsPort() int32 {
if m != nil {
return m.WsPort
}
return 0
}
func (m *NodesReply) GetWssPort() int32 {
if m != nil {
return m.WssPort
}
return 0
}
func (m *NodesReply) GetHeartbeat() int32 {
if m != nil {
return m.Heartbeat
}
return 0
}
func (m *NodesReply) GetNodes() []string {
if m != nil {
return m.Nodes
}
return nil
}
func (m *NodesReply) GetBackoff() *Backoff {
if m != nil {
return m.Backoff
}
return nil
}
func (m *NodesReply) GetHeartbeatMax() int32 {
if m != nil {
return m.HeartbeatMax
}
return 0
}
type Backoff struct {
MaxDelay int32 `protobuf:"varint,1,opt,name=MaxDelay,proto3" json:"max_delay"`
BaseDelay int32 `protobuf:"varint,2,opt,name=BaseDelay,proto3" json:"base_delay"`
Factor float32 `protobuf:"fixed32,3,opt,name=Factor,proto3" json:"factor"`
Jitter float32 `protobuf:"fixed32,4,opt,name=Jitter,proto3" json:"jitter"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Backoff) Reset() { *m = Backoff{} }
func (m *Backoff) String() string { return proto.CompactTextString(m) }
func (*Backoff) ProtoMessage() {}
func (*Backoff) Descriptor() ([]byte, []int) {
return fileDescriptor_00212fb1f9d3bf1c, []int{17}
}
func (m *Backoff) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *Backoff) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_Backoff.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (m *Backoff) XXX_Merge(src proto.Message) {
xxx_messageInfo_Backoff.Merge(m, src)
}
func (m *Backoff) XXX_Size() int {
return m.Size()
}
func (m *Backoff) XXX_DiscardUnknown() {
xxx_messageInfo_Backoff.DiscardUnknown(m)
}
var xxx_messageInfo_Backoff proto.InternalMessageInfo
func (m *Backoff) GetMaxDelay() int32 {
if m != nil {
return m.MaxDelay
}
return 0
}
func (m *Backoff) GetBaseDelay() int32 {
if m != nil {
return m.BaseDelay
}
return 0
}
func (m *Backoff) GetFactor() float32 {
if m != nil {
return m.Factor
}
return 0
}
func (m *Backoff) GetJitter() float32 {
if m != nil {
return m.Jitter
}
return 0
}
func init() {
proto.RegisterEnum("goim.logic.PushMsg_Type", PushMsg_Type_name, PushMsg_Type_value)
proto.RegisterType((*PushMsg)(nil), "goim.logic.PushMsg")
proto.RegisterType((*CloseReply)(nil), "goim.logic.CloseReply")
proto.RegisterType((*CloseReq)(nil), "goim.logic.CloseReq")
proto.RegisterType((*PingReply)(nil), "goim.logic.PingReply")
proto.RegisterType((*PingReq)(nil), "goim.logic.PingReq")
proto.RegisterType((*ConnectReq)(nil), "goim.logic.ConnectReq")
proto.RegisterType((*ConnectReply)(nil), "goim.logic.ConnectReply")
proto.RegisterType((*DisconnectReq)(nil), "goim.logic.DisconnectReq")
proto.RegisterType((*DisconnectReply)(nil), "goim.logic.DisconnectReply")
proto.RegisterType((*HeartbeatReq)(nil), "goim.logic.HeartbeatReq")
proto.RegisterType((*HeartbeatReply)(nil), "goim.logic.HeartbeatReply")
proto.RegisterType((*OnlineReq)(nil), "goim.logic.OnlineReq")
proto.RegisterMapType((map[string]int32)(nil), "goim.logic.OnlineReq.RoomCountEntry")
proto.RegisterType((*OnlineReply)(nil), "goim.logic.OnlineReply")
proto.RegisterMapType((map[string]int32)(nil), "goim.logic.OnlineReply.AllRoomCountEntry")
proto.RegisterType((*ReceiveReq)(nil), "goim.logic.ReceiveReq")
proto.RegisterType((*ReceiveReply)(nil), "goim.logic.ReceiveReply")
proto.RegisterType((*NodesReq)(nil), "goim.logic.NodesReq")
proto.RegisterType((*NodesReply)(nil), "goim.logic.NodesReply")
proto.RegisterType((*Backoff)(nil), "goim.logic.Backoff")
}
func init() { proto.RegisterFile("api.proto", fileDescriptor_00212fb1f9d3bf1c) }
var fileDescriptor_00212fb1f9d3bf1c = []byte{
// 1076 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x56, 0xdd, 0x6e, 0xe3, 0x44,
0x14, 0xae, 0xf3, 0xef, 0x93, 0xb4, 0xb4, 0x43, 0xb7, 0x18, 0x83, 0x92, 0xc8, 0x8b, 0x20, 0x15,
0xbb, 0x89, 0x14, 0x58, 0x09, 0x15, 0x10, 0xaa, 0x5b, 0x60, 0x77, 0xa1, 0x34, 0x9a, 0x5d, 0x24,
0xc4, 0x4d, 0xe5, 0xb8, 0xd3, 0xd4, 0xd4, 0xf1, 0xb8, 0xf6, 0xf4, 0x27, 0xb7, 0x3c, 0xc5, 0x5e,
0x22, 0x71, 0x07, 0x2f, 0xc0, 0x25, 0x97, 0x5c, 0xf2, 0x04, 0x11, 0x2a, 0x12, 0x42, 0xe1, 0x25,
0xd0, 0xfc, 0xf8, 0x8f, 0x4d, 0x11, 0x62, 0xaf, 0x32, 0xe7, 0x9c, 0x6f, 0xbe, 0x39, 0xf3, 0xcd,
0xcc, 0xe7, 0x80, 0xee, 0x84, 0x5e, 0x3f, 0x8c, 0x28, 0xa3, 0x08, 0x26, 0xd4, 0x9b, 0xf6, 0x7d,
0x3a, 0xf1, 0x5c, 0xf3, 0xdd, 0x89, 0xc7, 0x4e, 0x2f, 0xc6, 0x7d, 0x97, 0x4e, 0x07, 0x2c, 0xf6,
0x82, 0x49, 0x4c, 0x83, 0x01, 0xb9, 0xbe, 0xcf, 0x21, 0x03, 0x27, 0xf4, 0x06, 0x2e, 0x9d, 0x12,
0x36, 0x98, 0x44, 0xa1, 0x3b, 0x48, 0x19, 0xcc, 0xfb, 0xb9, 0x59, 0x13, 0x3a, 0xa1, 0x03, 0x91,
0x1e, 0x5f, 0x9c, 0x88, 0x48, 0x04, 0x62, 0x24, 0xe1, 0xd6, 0x9f, 0x1a, 0xd4, 0x47, 0x17, 0xf1,
0xe9, 0x41, 0x3c, 0x41, 0xf7, 0xa0, 0xc2, 0x66, 0x21, 0x31, 0xb4, 0xae, 0xd6, 0x5b, 0x1b, 0x1a,
0xfd, 0xac, 0x97, 0xbe, 0x82, 0xf4, 0x9f, 0xce, 0x42, 0x82, 0x05, 0x0a, 0xbd, 0x0e, 0x3a, 0x0d,
0x49, 0xe4, 0x30, 0x8f, 0x06, 0x46, 0xa9, 0xab, 0xf5, 0xaa, 0x38, 0x4b, 0xa0, 0x4d, 0xa8, 0xc6,
0x21, 0x21, 0xc7, 0x46, 0x59, 0x54, 0x64, 0x80, 0xb6, 0xa0, 0x16, 0x93, 0xe8, 0x92, 0x44, 0x46,
0xa5, 0xab, 0xf5, 0x74, 0xac, 0x22, 0x84, 0xa0, 0x12, 0x51, 0x3a, 0x35, 0xaa, 0x22, 0x2b, 0xc6,
0x3c, 0x77, 0x46, 0x66, 0xb1, 0x51, 0xeb, 0x96, 0x79, 0x8e, 0x8f, 0xd1, 0x3a, 0x94, 0xa7, 0xf1,
0xc4, 0xa8, 0x77, 0xb5, 0x5e, 0x0b, 0xf3, 0xa1, 0xb5, 0x0d, 0x15, 0xde, 0x13, 0x6a, 0x40, 0x65,
0xf4, 0xe5, 0x93, 0x87, 0xeb, 0x2b, 0x7c, 0x84, 0x0f, 0x0f, 0x0f, 0xd6, 0x35, 0xb4, 0x0a, 0xba,
0x8d, 0x0f, 0x77, 0xf7, 0xf7, 0x76, 0x9f, 0x3c, 0x5d, 0x2f, 0x59, 0x2d, 0x80, 0x3d, 0x9f, 0xc6,
0x04, 0x93, 0xd0, 0x9f, 0x59, 0x00, 0x0d, 0x15, 0x9d, 0x5b, 0x4d, 0xd0, 0x47, 0x5e, 0x30, 0x91,
0x05, 0x1d, 0xea, 0x32, 0x38, 0xb7, 0xbe, 0x02, 0xd8, 0xa3, 0x41, 0x40, 0x5c, 0x86, 0xc9, 0x79,
0xae, 0x79, 0xad, 0xd0, 0xfc, 0x16, 0xd4, 0x5c, 0x4a, 0xcf, 0x3c, 0x22, 0x54, 0xd0, 0xb1, 0x8a,
0xb8, 0x04, 0x8c, 0x9e, 0x91, 0x40, 0x48, 0xd0, 0xc2, 0x32, 0xd8, 0xa9, 0x3c, 0xfb, 0xae, 0xb3,
0x62, 0x7d, 0xab, 0x41, 0x2b, 0xa5, 0x0e, 0xfd, 0x99, 0xd8, 0x99, 0x77, 0x2c, 0x98, 0xcb, 0x98,
0x0f, 0x79, 0xe6, 0x8c, 0xcc, 0x14, 0x27, 0x1f, 0xf2, 0x85, 0xb8, 0x32, 0x8f, 0xf6, 0x05, 0xa3,
0x8e, 0x55, 0x84, 0x0c, 0xa8, 0x3b, 0xae, 0x4b, 0x42, 0x16, 0x1b, 0x95, 0x6e, 0xb9, 0x57, 0xc5,
0x49, 0xc8, 0xcf, 0xe8, 0x94, 0x38, 0x11, 0x1b, 0x13, 0x87, 0x09, 0x71, 0xcb, 0x38, 0x4b, 0x58,
0x9f, 0xc1, 0xea, 0xbe, 0x17, 0xbb, 0xd9, 0x0e, 0xff, 0x63, 0x13, 0x4a, 0x85, 0x72, 0x5e, 0x05,
0xeb, 0x2e, 0xbc, 0x94, 0x27, 0x53, 0x7b, 0x3a, 0x75, 0x62, 0x41, 0xd7, 0xc0, 0x7c, 0x68, 0x3d,
0x86, 0xd6, 0xc3, 0x64, 0xf9, 0x17, 0x5d, 0x70, 0x1d, 0xd6, 0x72, 0x5c, 0xfc, 0xe4, 0x7e, 0xd4,
0x40, 0x3f, 0x0c, 0x7c, 0x2f, 0x20, 0xff, 0x76, 0x5c, 0x36, 0xe8, 0x5c, 0xb7, 0x3d, 0x7a, 0x11,
0x30, 0xa3, 0xd4, 0x2d, 0xf7, 0x9a, 0xc3, 0x37, 0xf2, 0x57, 0x3d, 0x65, 0xe8, 0xe3, 0x04, 0xf6,
0x71, 0xc0, 0xa2, 0x19, 0xce, 0xa6, 0x99, 0x1f, 0xc0, 0x5a, 0xb1, 0x98, 0xf4, 0xad, 0x65, 0x7d,
0x6f, 0x42, 0xf5, 0xd2, 0xf1, 0x2f, 0x88, 0x7a, 0x1b, 0x32, 0xd8, 0x29, 0xbd, 0xa7, 0xa9, 0x2b,
0xf0, 0xbd, 0x06, 0xcd, 0x64, 0x2d, 0xae, 0xd6, 0x01, 0xb4, 0x1c, 0xdf, 0x4f, 0x69, 0x0d, 0x4d,
0xb4, 0xb6, 0xbd, 0xac, 0xb5, 0xd0, 0x9f, 0xf5, 0x77, 0x73, 0x58, 0xd9, 0x5f, 0x61, 0xba, 0xf9,
0x11, 0x6c, 0x3c, 0x07, 0xf9, 0x1f, 0x5d, 0x7e, 0x0a, 0x80, 0x89, 0x4b, 0xbc, 0x4b, 0xb2, 0xfc,
0xbc, 0xde, 0x82, 0xaa, 0x30, 0x12, 0x31, 0xbf, 0x39, 0xdc, 0x90, 0xed, 0x0a, 0x67, 0xea, 0x8f,
0x78, 0x01, 0xcb, 0xba, 0xb5, 0x06, 0xad, 0x94, 0x88, 0x1f, 0x96, 0x0d, 0x8d, 0x2f, 0xe8, 0x31,
0x89, 0x39, 0xad, 0x09, 0x8d, 0xd0, 0x77, 0xd8, 0x09, 0x8d, 0xa6, 0xaa, 0xb7, 0x34, 0xe6, 0x35,
0xd7, 0xf7, 0x48, 0xc0, 0x1e, 0x8d, 0xd4, 0xad, 0x48, 0x63, 0xeb, 0x8f, 0x12, 0x80, 0x22, 0xe1,
0x0a, 0x5a, 0x50, 0x3b, 0xa6, 0x53, 0xc7, 0x0b, 0x24, 0x89, 0x0d, 0x8b, 0x79, 0x47, 0x65, 0xb0,
0xfa, 0x45, 0x6f, 0x42, 0x9d, 0xb9, 0xe1, 0x88, 0x46, 0x4c, 0xee, 0xd8, 0x6e, 0x2d, 0xe6, 0x9d,
0x06, 0x73, 0xc3, 0xa3, 0x90, 0x46, 0x0c, 0x27, 0x45, 0x74, 0x17, 0x6a, 0x57, 0xb1, 0x80, 0x09,
0x03, 0xb3, 0x9b, 0x8b, 0x79, 0xa7, 0x7e, 0x15, 0x4b, 0x94, 0x2a, 0x71, 0xb2, 0xab, 0x58, 0xa2,
0x2a, 0x19, 0xd9, 0x55, 0xac, 0x60, 0x49, 0x11, 0xbd, 0xfd, 0xcf, 0x67, 0x58, 0xb5, 0x57, 0x17,
0xf3, 0x4e, 0x96, 0xcc, 0xbd, 0x4a, 0xd4, 0x81, 0x6a, 0xc0, 0xf7, 0x24, 0x8d, 0xcf, 0xd6, 0x17,
0xf3, 0x8e, 0x4c, 0x60, 0xf9, 0x83, 0x76, 0xa0, 0x3e, 0x76, 0xdc, 0x33, 0x7a, 0x72, 0x22, 0x8c,
0xb0, 0x39, 0x7c, 0x39, 0x7f, 0x47, 0x6c, 0x59, 0x92, 0x0d, 0x2b, 0x1c, 0x4e, 0x06, 0xe8, 0x01,
0xb4, 0xd2, 0x95, 0x0e, 0x9c, 0x6b, 0xa3, 0x21, 0x9a, 0xd9, 0x58, 0xcc, 0x3b, 0xab, 0x69, 0xfe,
0x68, 0xea, 0x5c, 0xe3, 0x02, 0xcc, 0xfa, 0x41, 0x83, 0xba, 0x22, 0x46, 0xdb, 0xd0, 0x38, 0x70,
0xae, 0xf7, 0x89, 0xef, 0xc8, 0x8b, 0xa4, 0xf6, 0x32, 0x75, 0xae, 0x8f, 0x8e, 0x79, 0x12, 0xa7,
0x65, 0x74, 0x0f, 0x74, 0xdb, 0x89, 0x89, 0xc4, 0x4a, 0xb9, 0xd7, 0x16, 0xf3, 0x0e, 0x8c, 0x9d,
0x98, 0x28, 0x70, 0x06, 0xe0, 0xc7, 0xf7, 0x89, 0xe3, 0x32, 0x2a, 0x1f, 0x7a, 0x49, 0x1e, 0xdf,
0x89, 0xc8, 0x60, 0x55, 0xe1, 0x98, 0xc7, 0x1e, 0x63, 0xea, 0x03, 0xa2, 0x30, 0xdf, 0x88, 0x0c,
0x56, 0x95, 0xe1, 0x5f, 0x65, 0xa8, 0x7e, 0xce, 0xb5, 0x40, 0x43, 0xa8, 0x70, 0x2b, 0x47, 0x05,
0x81, 0x94, 0xb9, 0x9b, 0x77, 0x9e, 0x4f, 0xf2, 0x4b, 0xf4, 0x00, 0xaa, 0xe2, 0xbb, 0x80, 0x36,
0xf3, 0xf5, 0xe4, 0x53, 0x61, 0x6e, 0x2d, 0xc9, 0xf2, 0x69, 0xef, 0x43, 0x5d, 0xf9, 0x39, 0x2a,
0x42, 0x52, 0x77, 0x35, 0x8d, 0xa5, 0x79, 0x3e, 0x79, 0x1f, 0x20, 0xf3, 0x4e, 0xf4, 0x6a, 0x1e,
0x57, 0x30, 0x68, 0xf3, 0xb5, 0xdb, 0x4a, 0x9c, 0x65, 0x17, 0xf4, 0xd4, 0x10, 0x51, 0x61, 0xb1,
0xbc, 0xe7, 0x9a, 0xe6, 0x2d, 0x15, 0x4e, 0xf1, 0x21, 0x34, 0x31, 0x09, 0xc8, 0x95, 0x34, 0x1a,
0x74, 0x67, 0xa9, 0x2f, 0x9a, 0xaf, 0xdc, 0xe2, 0x49, 0x5c, 0x04, 0xf5, 0xc6, 0x8b, 0x22, 0x64,
0x0e, 0x52, 0x14, 0x21, 0x6f, 0x08, 0x5c, 0x78, 0xf1, 0x96, 0x8b, 0xc2, 0x27, 0x1e, 0x51, 0x14,
0x3e, 0x7b, 0xf4, 0x76, 0xfb, 0xa7, 0x9b, 0xb6, 0xf6, 0xf3, 0x4d, 0x5b, 0xfb, 0xe5, 0xa6, 0xad,
0xfd, 0x7a, 0xd3, 0xd6, 0x7e, 0xbb, 0x69, 0x6b, 0xcf, 0x7e, 0x6f, 0xaf, 0x7c, 0x5d, 0xe1, 0xff,
0x8c, 0xc6, 0x35, 0x61, 0x3f, 0xef, 0xfc, 0x1d, 0x00, 0x00, 0xff, 0xff, 0xde, 0x7e, 0x44, 0x5c,
0x65, 0x09, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc1.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc1.SupportPackageIsVersion4
// LogicClient is the client API for Logic service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type LogicClient interface {
// Ping Service
Ping(ctx context.Context, in *PingReq, opts ...grpc1.CallOption) (*PingReply, error)
// Close Service
Close(ctx context.Context, in *CloseReq, opts ...grpc1.CallOption) (*CloseReply, error)
// Connect
Connect(ctx context.Context, in *ConnectReq, opts ...grpc1.CallOption) (*ConnectReply, error)
// Disconnect
Disconnect(ctx context.Context, in *DisconnectReq, opts ...grpc1.CallOption) (*DisconnectReply, error)
// Heartbeat
Heartbeat(ctx context.Context, in *HeartbeatReq, opts ...grpc1.CallOption) (*HeartbeatReply, error)
// RenewOnline
RenewOnline(ctx context.Context, in *OnlineReq, opts ...grpc1.CallOption) (*OnlineReply, error)
// Receive
Receive(ctx context.Context, in *ReceiveReq, opts ...grpc1.CallOption) (*ReceiveReply, error)
//ServerList
Nodes(ctx context.Context, in *NodesReq, opts ...grpc1.CallOption) (*NodesReply, error)
}
type logicClient struct {
cc *grpc1.ClientConn
}
func NewLogicClient(cc *grpc1.ClientConn) LogicClient {
return &logicClient{cc}
}
func (c *logicClient) Ping(ctx context.Context, in *PingReq, opts ...grpc1.CallOption) (*PingReply, error) {
out := new(PingReply)
err := c.cc.Invoke(ctx, "/goim.logic.Logic/Ping", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *logicClient) Close(ctx context.Context, in *CloseReq, opts ...grpc1.CallOption) (*CloseReply, error) {
out := new(CloseReply)
err := c.cc.Invoke(ctx, "/goim.logic.Logic/Close", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *logicClient) Connect(ctx context.Context, in *ConnectReq, opts ...grpc1.CallOption) (*ConnectReply, error) {
out := new(ConnectReply)
err := c.cc.Invoke(ctx, "/goim.logic.Logic/Connect", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *logicClient) Disconnect(ctx context.Context, in *DisconnectReq, opts ...grpc1.CallOption) (*DisconnectReply, error) {
out := new(DisconnectReply)
err := c.cc.Invoke(ctx, "/goim.logic.Logic/Disconnect", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *logicClient) Heartbeat(ctx context.Context, in *HeartbeatReq, opts ...grpc1.CallOption) (*HeartbeatReply, error) {
out := new(HeartbeatReply)
err := c.cc.Invoke(ctx, "/goim.logic.Logic/Heartbeat", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *logicClient) RenewOnline(ctx context.Context, in *OnlineReq, opts ...grpc1.CallOption) (*OnlineReply, error) {
out := new(OnlineReply)
err := c.cc.Invoke(ctx, "/goim.logic.Logic/RenewOnline", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *logicClient) Receive(ctx context.Context, in *ReceiveReq, opts ...grpc1.CallOption) (*ReceiveReply, error) {
out := new(ReceiveReply)
err := c.cc.Invoke(ctx, "/goim.logic.Logic/Receive", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *logicClient) Nodes(ctx context.Context, in *NodesReq, opts ...grpc1.CallOption) (*NodesReply, error) {
out := new(NodesReply)
err := c.cc.Invoke(ctx, "/goim.logic.Logic/Nodes", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// LogicServer is the server API for Logic service.
type LogicServer interface {
// Ping Service
Ping(context.Context, *PingReq) (*PingReply, error)
// Close Service
Close(context.Context, *CloseReq) (*CloseReply, error)
// Connect
Connect(context.Context, *ConnectReq) (*ConnectReply, error)
// Disconnect
Disconnect(context.Context, *DisconnectReq) (*DisconnectReply, error)
// Heartbeat
Heartbeat(context.Context, *HeartbeatReq) (*HeartbeatReply, error)
// RenewOnline
RenewOnline(context.Context, *OnlineReq) (*OnlineReply, error)
// Receive
Receive(context.Context, *ReceiveReq) (*ReceiveReply, error)
//ServerList
Nodes(context.Context, *NodesReq) (*NodesReply, error)
}
func RegisterLogicServer(s *grpc1.Server, srv LogicServer) {
s.RegisterService(&_Logic_serviceDesc, srv)
}
func _Logic_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc1.UnaryServerInterceptor) (interface{}, error) {
in := new(PingReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LogicServer).Ping(ctx, in)
}
info := &grpc1.UnaryServerInfo{
Server: srv,
FullMethod: "/goim.logic.Logic/Ping",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LogicServer).Ping(ctx, req.(*PingReq))
}
return interceptor(ctx, in, info, handler)
}
func _Logic_Close_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc1.UnaryServerInterceptor) (interface{}, error) {
in := new(CloseReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LogicServer).Close(ctx, in)
}
info := &grpc1.UnaryServerInfo{
Server: srv,
FullMethod: "/goim.logic.Logic/Close",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LogicServer).Close(ctx, req.(*CloseReq))
}
return interceptor(ctx, in, info, handler)
}
func _Logic_Connect_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc1.UnaryServerInterceptor) (interface{}, error) {
in := new(ConnectReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LogicServer).Connect(ctx, in)
}
info := &grpc1.UnaryServerInfo{
Server: srv,
FullMethod: "/goim.logic.Logic/Connect",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LogicServer).Connect(ctx, req.(*ConnectReq))
}
return interceptor(ctx, in, info, handler)
}
func _Logic_Disconnect_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc1.UnaryServerInterceptor) (interface{}, error) {
in := new(DisconnectReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LogicServer).Disconnect(ctx, in)
}
info := &grpc1.UnaryServerInfo{
Server: srv,
FullMethod: "/goim.logic.Logic/Disconnect",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LogicServer).Disconnect(ctx, req.(*DisconnectReq))
}
return interceptor(ctx, in, info, handler)
}
func _Logic_Heartbeat_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc1.UnaryServerInterceptor) (interface{}, error) {
in := new(HeartbeatReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LogicServer).Heartbeat(ctx, in)
}
info := &grpc1.UnaryServerInfo{
Server: srv,
FullMethod: "/goim.logic.Logic/Heartbeat",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LogicServer).Heartbeat(ctx, req.(*HeartbeatReq))
}
return interceptor(ctx, in, info, handler)
}
func _Logic_RenewOnline_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc1.UnaryServerInterceptor) (interface{}, error) {
in := new(OnlineReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LogicServer).RenewOnline(ctx, in)
}
info := &grpc1.UnaryServerInfo{
Server: srv,
FullMethod: "/goim.logic.Logic/RenewOnline",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LogicServer).RenewOnline(ctx, req.(*OnlineReq))
}
return interceptor(ctx, in, info, handler)
}
func _Logic_Receive_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc1.UnaryServerInterceptor) (interface{}, error) {
in := new(ReceiveReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LogicServer).Receive(ctx, in)
}
info := &grpc1.UnaryServerInfo{
Server: srv,
FullMethod: "/goim.logic.Logic/Receive",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LogicServer).Receive(ctx, req.(*ReceiveReq))
}
return interceptor(ctx, in, info, handler)
}
func _Logic_Nodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc1.UnaryServerInterceptor) (interface{}, error) {
in := new(NodesReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(LogicServer).Nodes(ctx, in)
}
info := &grpc1.UnaryServerInfo{
Server: srv,
FullMethod: "/goim.logic.Logic/Nodes",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(LogicServer).Nodes(ctx, req.(*NodesReq))
}
return interceptor(ctx, in, info, handler)
}
var _Logic_serviceDesc = grpc1.ServiceDesc{
ServiceName: "goim.logic.Logic",
HandlerType: (*LogicServer)(nil),
Methods: []grpc1.MethodDesc{
{
MethodName: "Ping",
Handler: _Logic_Ping_Handler,
},
{
MethodName: "Close",
Handler: _Logic_Close_Handler,
},
{
MethodName: "Connect",
Handler: _Logic_Connect_Handler,
},
{
MethodName: "Disconnect",
Handler: _Logic_Disconnect_Handler,
},
{
MethodName: "Heartbeat",
Handler: _Logic_Heartbeat_Handler,
},
{
MethodName: "RenewOnline",
Handler: _Logic_RenewOnline_Handler,
},
{
MethodName: "Receive",
Handler: _Logic_Receive_Handler,
},
{
MethodName: "Nodes",
Handler: _Logic_Nodes_Handler,
},
},
Streams: []grpc1.StreamDesc{},
Metadata: "api.proto",
}
func (m *PushMsg) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *PushMsg) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Type != 0 {
dAtA[i] = 0x8
i++
i = encodeVarintApi(dAtA, i, uint64(m.Type))
}
if m.Operation != 0 {
dAtA[i] = 0x10
i++
i = encodeVarintApi(dAtA, i, uint64(m.Operation))
}
if m.Speed != 0 {
dAtA[i] = 0x18
i++
i = encodeVarintApi(dAtA, i, uint64(m.Speed))
}
if len(m.Server) > 0 {
dAtA[i] = 0x22
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Server)))
i += copy(dAtA[i:], m.Server)
}
if len(m.Room) > 0 {
dAtA[i] = 0x2a
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Room)))
i += copy(dAtA[i:], m.Room)
}
if len(m.Keys) > 0 {
for _, s := range m.Keys {
dAtA[i] = 0x32
i++
l = len(s)
for l >= 1<<7 {
dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
l >>= 7
i++
}
dAtA[i] = uint8(l)
i++
i += copy(dAtA[i:], s)
}
}
if len(m.Msg) > 0 {
dAtA[i] = 0x3a
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Msg)))
i += copy(dAtA[i:], m.Msg)
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *CloseReply) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *CloseReply) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *CloseReq) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *CloseReq) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *PingReply) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *PingReply) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *PingReq) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *PingReq) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *ConnectReq) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ConnectReq) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.Server) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Server)))
i += copy(dAtA[i:], m.Server)
}
if len(m.Cookie) > 0 {
dAtA[i] = 0x12
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Cookie)))
i += copy(dAtA[i:], m.Cookie)
}
if len(m.Token) > 0 {
dAtA[i] = 0x1a
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Token)))
i += copy(dAtA[i:], m.Token)
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *ConnectReply) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ConnectReply) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Mid != 0 {
dAtA[i] = 0x8
i++
i = encodeVarintApi(dAtA, i, uint64(m.Mid))
}
if len(m.Key) > 0 {
dAtA[i] = 0x12
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Key)))
i += copy(dAtA[i:], m.Key)
}
if len(m.RoomID) > 0 {
dAtA[i] = 0x1a
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.RoomID)))
i += copy(dAtA[i:], m.RoomID)
}
if len(m.Accepts) > 0 {
dAtA2 := make([]byte, len(m.Accepts)*10)
var j1 int
for _, num1 := range m.Accepts {
num := uint64(num1)
for num >= 1<<7 {
dAtA2[j1] = uint8(uint64(num)&0x7f | 0x80)
num >>= 7
j1++
}
dAtA2[j1] = uint8(num)
j1++
}
dAtA[i] = 0x22
i++
i = encodeVarintApi(dAtA, i, uint64(j1))
i += copy(dAtA[i:], dAtA2[:j1])
}
if m.Heartbeat != 0 {
dAtA[i] = 0x28
i++
i = encodeVarintApi(dAtA, i, uint64(m.Heartbeat))
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *DisconnectReq) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *DisconnectReq) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Mid != 0 {
dAtA[i] = 0x8
i++
i = encodeVarintApi(dAtA, i, uint64(m.Mid))
}
if len(m.Key) > 0 {
dAtA[i] = 0x12
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Key)))
i += copy(dAtA[i:], m.Key)
}
if len(m.Server) > 0 {
dAtA[i] = 0x1a
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Server)))
i += copy(dAtA[i:], m.Server)
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *DisconnectReply) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *DisconnectReply) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Has {
dAtA[i] = 0x8
i++
if m.Has {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i++
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *HeartbeatReq) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *HeartbeatReq) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Mid != 0 {
dAtA[i] = 0x8
i++
i = encodeVarintApi(dAtA, i, uint64(m.Mid))
}
if len(m.Key) > 0 {
dAtA[i] = 0x12
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Key)))
i += copy(dAtA[i:], m.Key)
}
if len(m.Server) > 0 {
dAtA[i] = 0x1a
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Server)))
i += copy(dAtA[i:], m.Server)
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *HeartbeatReply) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *HeartbeatReply) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *OnlineReq) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *OnlineReq) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.Server) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Server)))
i += copy(dAtA[i:], m.Server)
}
if len(m.RoomCount) > 0 {
for k, _ := range m.RoomCount {
dAtA[i] = 0x12
i++
v := m.RoomCount[k]
mapSize := 1 + len(k) + sovApi(uint64(len(k))) + 1 + sovApi(uint64(v))
i = encodeVarintApi(dAtA, i, uint64(mapSize))
dAtA[i] = 0xa
i++
i = encodeVarintApi(dAtA, i, uint64(len(k)))
i += copy(dAtA[i:], k)
dAtA[i] = 0x10
i++
i = encodeVarintApi(dAtA, i, uint64(v))
}
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *OnlineReply) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *OnlineReply) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.AllRoomCount) > 0 {
for k, _ := range m.AllRoomCount {
dAtA[i] = 0xa
i++
v := m.AllRoomCount[k]
mapSize := 1 + len(k) + sovApi(uint64(len(k))) + 1 + sovApi(uint64(v))
i = encodeVarintApi(dAtA, i, uint64(mapSize))
dAtA[i] = 0xa
i++
i = encodeVarintApi(dAtA, i, uint64(len(k)))
i += copy(dAtA[i:], k)
dAtA[i] = 0x10
i++
i = encodeVarintApi(dAtA, i, uint64(v))
}
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *ReceiveReq) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ReceiveReq) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Mid != 0 {
dAtA[i] = 0x8
i++
i = encodeVarintApi(dAtA, i, uint64(m.Mid))
}
if m.Proto != nil {
dAtA[i] = 0x12
i++
i = encodeVarintApi(dAtA, i, uint64(m.Proto.Size()))
n3, err := m.Proto.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n3
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *ReceiveReply) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *ReceiveReply) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *NodesReq) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *NodesReq) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.Platform) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Platform)))
i += copy(dAtA[i:], m.Platform)
}
if len(m.ClientIP) > 0 {
dAtA[i] = 0x12
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.ClientIP)))
i += copy(dAtA[i:], m.ClientIP)
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *NodesReply) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *NodesReply) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.Domain) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintApi(dAtA, i, uint64(len(m.Domain)))
i += copy(dAtA[i:], m.Domain)
}
if m.TcpPort != 0 {
dAtA[i] = 0x10
i++
i = encodeVarintApi(dAtA, i, uint64(m.TcpPort))
}
if m.WsPort != 0 {
dAtA[i] = 0x18
i++
i = encodeVarintApi(dAtA, i, uint64(m.WsPort))
}
if m.WssPort != 0 {
dAtA[i] = 0x20
i++
i = encodeVarintApi(dAtA, i, uint64(m.WssPort))
}
if m.Heartbeat != 0 {
dAtA[i] = 0x28
i++
i = encodeVarintApi(dAtA, i, uint64(m.Heartbeat))
}
if len(m.Nodes) > 0 {
for _, s := range m.Nodes {
dAtA[i] = 0x32
i++
l = len(s)
for l >= 1<<7 {
dAtA[i] = uint8(uint64(l)&0x7f | 0x80)
l >>= 7
i++
}
dAtA[i] = uint8(l)
i++
i += copy(dAtA[i:], s)
}
}
if m.Backoff != nil {
dAtA[i] = 0x3a
i++
i = encodeVarintApi(dAtA, i, uint64(m.Backoff.Size()))
n4, err := m.Backoff.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n4
}
if m.HeartbeatMax != 0 {
dAtA[i] = 0x40
i++
i = encodeVarintApi(dAtA, i, uint64(m.HeartbeatMax))
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *Backoff) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Backoff) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.MaxDelay != 0 {
dAtA[i] = 0x8
i++
i = encodeVarintApi(dAtA, i, uint64(m.MaxDelay))
}
if m.BaseDelay != 0 {
dAtA[i] = 0x10
i++
i = encodeVarintApi(dAtA, i, uint64(m.BaseDelay))
}
if m.Factor != 0 {
dAtA[i] = 0x1d
i++
encoding_binary.LittleEndian.PutUint32(dAtA[i:], uint32(math.Float32bits(float32(m.Factor))))
i += 4
}
if m.Jitter != 0 {
dAtA[i] = 0x25
i++
encoding_binary.LittleEndian.PutUint32(dAtA[i:], uint32(math.Float32bits(float32(m.Jitter))))
i += 4
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func encodeVarintApi(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return offset + 1
}
func (m *PushMsg) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Type != 0 {
n += 1 + sovApi(uint64(m.Type))
}
if m.Operation != 0 {
n += 1 + sovApi(uint64(m.Operation))
}
if m.Speed != 0 {
n += 1 + sovApi(uint64(m.Speed))
}
l = len(m.Server)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
l = len(m.Room)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
if len(m.Keys) > 0 {
for _, s := range m.Keys {
l = len(s)
n += 1 + l + sovApi(uint64(l))
}
}
l = len(m.Msg)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *CloseReply) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *CloseReq) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *PingReply) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *PingReq) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *ConnectReq) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Server)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
l = len(m.Cookie)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
l = len(m.Token)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *ConnectReply) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Mid != 0 {
n += 1 + sovApi(uint64(m.Mid))
}
l = len(m.Key)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
l = len(m.RoomID)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
if len(m.Accepts) > 0 {
l = 0
for _, e := range m.Accepts {
l += sovApi(uint64(e))
}
n += 1 + sovApi(uint64(l)) + l
}
if m.Heartbeat != 0 {
n += 1 + sovApi(uint64(m.Heartbeat))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *DisconnectReq) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Mid != 0 {
n += 1 + sovApi(uint64(m.Mid))
}
l = len(m.Key)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
l = len(m.Server)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *DisconnectReply) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Has {
n += 2
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *HeartbeatReq) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Mid != 0 {
n += 1 + sovApi(uint64(m.Mid))
}
l = len(m.Key)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
l = len(m.Server)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *HeartbeatReply) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *OnlineReq) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Server)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
if len(m.RoomCount) > 0 {
for k, v := range m.RoomCount {
_ = k
_ = v
mapEntrySize := 1 + len(k) + sovApi(uint64(len(k))) + 1 + sovApi(uint64(v))
n += mapEntrySize + 1 + sovApi(uint64(mapEntrySize))
}
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *OnlineReply) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if len(m.AllRoomCount) > 0 {
for k, v := range m.AllRoomCount {
_ = k
_ = v
mapEntrySize := 1 + len(k) + sovApi(uint64(len(k))) + 1 + sovApi(uint64(v))
n += mapEntrySize + 1 + sovApi(uint64(mapEntrySize))
}
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *ReceiveReq) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Mid != 0 {
n += 1 + sovApi(uint64(m.Mid))
}
if m.Proto != nil {
l = m.Proto.Size()
n += 1 + l + sovApi(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *ReceiveReply) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *NodesReq) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Platform)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
l = len(m.ClientIP)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *NodesReply) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
l = len(m.Domain)
if l > 0 {
n += 1 + l + sovApi(uint64(l))
}
if m.TcpPort != 0 {
n += 1 + sovApi(uint64(m.TcpPort))
}
if m.WsPort != 0 {
n += 1 + sovApi(uint64(m.WsPort))
}
if m.WssPort != 0 {
n += 1 + sovApi(uint64(m.WssPort))
}
if m.Heartbeat != 0 {
n += 1 + sovApi(uint64(m.Heartbeat))
}
if len(m.Nodes) > 0 {
for _, s := range m.Nodes {
l = len(s)
n += 1 + l + sovApi(uint64(l))
}
}
if m.Backoff != nil {
l = m.Backoff.Size()
n += 1 + l + sovApi(uint64(l))
}
if m.HeartbeatMax != 0 {
n += 1 + sovApi(uint64(m.HeartbeatMax))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *Backoff) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.MaxDelay != 0 {
n += 1 + sovApi(uint64(m.MaxDelay))
}
if m.BaseDelay != 0 {
n += 1 + sovApi(uint64(m.BaseDelay))
}
if m.Factor != 0 {
n += 5
}
if m.Jitter != 0 {
n += 5
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func sovApi(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozApi(x uint64) (n int) {
return sovApi(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *PushMsg) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: PushMsg: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PushMsg: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType)
}
m.Type = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Type |= PushMsg_Type(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Operation", wireType)
}
m.Operation = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Operation |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Speed", wireType)
}
m.Speed = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Speed |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Server", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Server = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Room", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Room = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Keys", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Keys = append(m.Keys, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...)
if m.Msg == nil {
m.Msg = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *CloseReply) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: CloseReply: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: CloseReply: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *CloseReq) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: CloseReq: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: CloseReq: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *PingReply) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: PingReply: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PingReply: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *PingReq) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: PingReq: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: PingReq: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ConnectReq) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ConnectReq: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ConnectReq: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Server", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Server = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Cookie", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Cookie = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Token", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + byteLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Token = append(m.Token[:0], dAtA[iNdEx:postIndex]...)
if m.Token == nil {
m.Token = []byte{}
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ConnectReply) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ConnectReply: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ConnectReply: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Mid", wireType)
}
m.Mid = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Mid |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field RoomID", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.RoomID = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 4:
if wireType == 0 {
var v int32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Accepts = append(m.Accepts, v)
} else if wireType == 2 {
var packedLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
packedLen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if packedLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + packedLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
var elementCount int
var count int
for _, integer := range dAtA[iNdEx:postIndex] {
if integer < 128 {
count++
}
}
elementCount = count
if elementCount != 0 && len(m.Accepts) == 0 {
m.Accepts = make([]int32, 0, elementCount)
}
for iNdEx < postIndex {
var v int32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Accepts = append(m.Accepts, v)
}
} else {
return fmt.Errorf("proto: wrong wireType = %d for field Accepts", wireType)
}
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Heartbeat", wireType)
}
m.Heartbeat = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Heartbeat |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *DisconnectReq) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: DisconnectReq: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: DisconnectReq: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Mid", wireType)
}
m.Mid = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Mid |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Server", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Server = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *DisconnectReply) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: DisconnectReply: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: DisconnectReply: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Has", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
m.Has = bool(v != 0)
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *HeartbeatReq) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: HeartbeatReq: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: HeartbeatReq: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Mid", wireType)
}
m.Mid = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Mid |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Key = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Server", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Server = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *HeartbeatReply) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: HeartbeatReply: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: HeartbeatReply: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *OnlineReq) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: OnlineReq: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: OnlineReq: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Server", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Server = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field RoomCount", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.RoomCount == nil {
m.RoomCount = make(map[string]int32)
}
var mapkey string
var mapvalue int32
for iNdEx < postIndex {
entryPreIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
if fieldNum == 1 {
var stringLenmapkey uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLenmapkey |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLenmapkey := int(stringLenmapkey)
if intStringLenmapkey < 0 {
return ErrInvalidLengthApi
}
postStringIndexmapkey := iNdEx + intStringLenmapkey
if postStringIndexmapkey < 0 {
return ErrInvalidLengthApi
}
if postStringIndexmapkey > l {
return io.ErrUnexpectedEOF
}
mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
iNdEx = postStringIndexmapkey
} else if fieldNum == 2 {
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
mapvalue |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
} else {
iNdEx = entryPreIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > postIndex {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
m.RoomCount[mapkey] = mapvalue
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *OnlineReply) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: OnlineReply: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: OnlineReply: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field AllRoomCount", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.AllRoomCount == nil {
m.AllRoomCount = make(map[string]int32)
}
var mapkey string
var mapvalue int32
for iNdEx < postIndex {
entryPreIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
if fieldNum == 1 {
var stringLenmapkey uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLenmapkey |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLenmapkey := int(stringLenmapkey)
if intStringLenmapkey < 0 {
return ErrInvalidLengthApi
}
postStringIndexmapkey := iNdEx + intStringLenmapkey
if postStringIndexmapkey < 0 {
return ErrInvalidLengthApi
}
if postStringIndexmapkey > l {
return io.ErrUnexpectedEOF
}
mapkey = string(dAtA[iNdEx:postStringIndexmapkey])
iNdEx = postStringIndexmapkey
} else if fieldNum == 2 {
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
mapvalue |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
} else {
iNdEx = entryPreIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > postIndex {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
m.AllRoomCount[mapkey] = mapvalue
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ReceiveReq) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ReceiveReq: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ReceiveReq: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Mid", wireType)
}
m.Mid = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Mid |= int64(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Proto", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Proto == nil {
m.Proto = &grpc.Proto{}
}
if err := m.Proto.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *ReceiveReply) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: ReceiveReply: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: ReceiveReply: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *NodesReq) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: NodesReq: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: NodesReq: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Platform", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Platform = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field ClientIP", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.ClientIP = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *NodesReply) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: NodesReply: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: NodesReply: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Domain", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Domain = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field TcpPort", wireType)
}
m.TcpPort = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.TcpPort |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field WsPort", wireType)
}
m.WsPort = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.WsPort |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field WssPort", wireType)
}
m.WssPort = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.WssPort |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Heartbeat", wireType)
}
m.Heartbeat = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Heartbeat |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Nodes", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + intStringLen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Nodes = append(m.Nodes, string(dAtA[iNdEx:postIndex]))
iNdEx = postIndex
case 7:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Backoff", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= int(b&0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthApi
}
postIndex := iNdEx + msglen
if postIndex < 0 {
return ErrInvalidLengthApi
}
if postIndex > l {
return io.ErrUnexpectedEOF
}
if m.Backoff == nil {
m.Backoff = &Backoff{}
}
if err := m.Backoff.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
iNdEx = postIndex
case 8:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field HeartbeatMax", wireType)
}
m.HeartbeatMax = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.HeartbeatMax |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *Backoff) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= uint64(b&0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Backoff: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Backoff: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field MaxDelay", wireType)
}
m.MaxDelay = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.MaxDelay |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field BaseDelay", wireType)
}
m.BaseDelay = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowApi
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.BaseDelay |= int32(b&0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 5 {
return fmt.Errorf("proto: wrong wireType = %d for field Factor", wireType)
}
var v uint32
if (iNdEx + 4) > l {
return io.ErrUnexpectedEOF
}
v = uint32(encoding_binary.LittleEndian.Uint32(dAtA[iNdEx:]))
iNdEx += 4
m.Factor = float32(math.Float32frombits(v))
case 4:
if wireType != 5 {
return fmt.Errorf("proto: wrong wireType = %d for field Jitter", wireType)
}
var v uint32
if (iNdEx + 4) > l {
return io.ErrUnexpectedEOF
}
v = uint32(encoding_binary.LittleEndian.Uint32(dAtA[iNdEx:]))
iNdEx += 4
m.Jitter = float32(math.Float32frombits(v))
default:
iNdEx = preIndex
skippy, err := skipApi(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) < 0 {
return ErrInvalidLengthApi
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipApi(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowApi
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowApi
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
return iNdEx, nil
case 1:
iNdEx += 8
return iNdEx, nil
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowApi
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if length < 0 {
return 0, ErrInvalidLengthApi
}
iNdEx += length
if iNdEx < 0 {
return 0, ErrInvalidLengthApi
}
return iNdEx, nil
case 3:
for {
var innerWire uint64
var start int = iNdEx
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowApi
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
innerWire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
innerWireType := int(innerWire & 0x7)
if innerWireType == 4 {
break
}
next, err := skipApi(dAtA[start:])
if err != nil {
return 0, err
}
iNdEx = start + next
if iNdEx < 0 {
return 0, ErrInvalidLengthApi
}
}
return iNdEx, nil
case 4:
return iNdEx, nil
case 5:
iNdEx += 4
return iNdEx, nil
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
}
panic("unreachable")
}
var (
ErrInvalidLengthApi = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowApi = fmt.Errorf("proto: integer overflow")
)
<|start_filename|>goim-nats/logic/conf/conf.go<|end_filename|>
package conf
import (
"time"
"github.com/BurntSushi/toml"
"github.com/imdario/mergo"
"github.com/tsingson/discovery/naming"
"golang.org/x/xerrors"
xtime "github.com/tsingson/ex-goim/pkg/time"
)
// Config config.
type Config struct {
Env *Env
Discovery *naming.Config
RPCClient *RPCClient
RPCServer *RPCServer
HTTPServer *HTTPServer
// Kafka *Kafka
Nats *Nats
Redis *Redis
Node *Node
Backoff *Backoff
Regions map[string][]string
}
// LogicConfig as alias of Config
type LogicConfig = Config
// Env is env config.
type Env struct {
Region string
Zone string
DeployEnv string
Host string
Weight int64
}
// Node node config.
type Node struct {
DefaultDomain string
HostDomain string
TCPPort int
WSPort int
WSSPort int
HeartbeatMax int
Heartbeat xtime.Duration
RegionWeight float64
}
// Backoff backoff.
type Backoff struct {
MaxDelay int32
BaseDelay int32
Factor float32
Jitter float32
}
// Redis .
type Redis struct {
Network string
Addr string
Auth string
Active int
Idle int
DialTimeout xtime.Duration
ReadTimeout xtime.Duration
WriteTimeout xtime.Duration
IdleTimeout xtime.Duration
Expire xtime.Duration
}
// Kafka .
type Kafka struct {
Topic string
Brokers []string
}
// Nats .
type Nats struct {
NatsAddr string // "nats://localhost:4222"
LiftAddr string // "localhost:9292" // address for lift-bridge
Channel string // "channel"
ChannelID string // "channel-stream"
AckInbox string // "acks"
}
// NatsConfig as alias of Nats
type NatsConfig = Nats
// RPCClient is RPC client config.
type RPCClient struct {
Dial xtime.Duration
Timeout xtime.Duration
}
// RPCServer is RPC server config.
type RPCServer struct {
Network string
Addr string
Timeout xtime.Duration
IdleTimeout xtime.Duration
MaxLifeTime xtime.Duration
ForceCloseWait xtime.Duration
KeepAliveInterval xtime.Duration
KeepAliveTimeout xtime.Duration
}
// HTTPServer is http server config.
type HTTPServer struct {
Network string
Addr string
ReadTimeout xtime.Duration
WriteTimeout xtime.Duration
}
var (
confPath string
region string
zone string
deployEnv string
host string
weight int64
// Conf config
Conf *Config
)
func init() {
Conf = Default()
}
// Load init config.
func Load(path string) (cfg *Config, err error) {
if len(path) == 0 {
return cfg, xerrors.New("config path is nil")
}
Conf = Default()
cfg = Default()
_, err = toml.DecodeFile(path, &cfg)
if err != nil {
return
}
err = mergo.Merge(&Conf, cfg, mergo.WithOverride)
if err != nil {
return Conf, err
}
return Conf, nil
}
// LoadToml init config.
func LoadToml(path string) (cfg *Config, err error) {
Conf = Default()
if len(path) == 0 {
return Conf, xerrors.New("no configuration")
}
//
_, err = toml.DecodeFile(path, &Conf)
return Conf, nil
}
// Default new a config with specified defualt value.
func Default() *Config {
cfg := &Config{
Env: &Env{
Region: "china",
Zone: "gd",
DeployEnv: "dev",
Host: "logic",
Weight: 100,
},
Discovery: &naming.Config{
Nodes: []string{"127.0.0.1:7171"},
Region: "china",
Zone: "gd",
Env: "dev",
Host: "discovery",
},
Nats: &Nats{
NatsAddr: "nats://localhost:4222",
LiftAddr: "localhost:9292", // address for lift-bridge
Channel: "channel",
ChannelID: "channel-stream",
AckInbox: "acks",
},
HTTPServer: &HTTPServer{
Network: "tcp",
Addr: "3111",
ReadTimeout: xtime.Duration(time.Second),
WriteTimeout: xtime.Duration(time.Second),
},
RPCClient: &RPCClient{
Dial: xtime.Duration(time.Second),
Timeout: xtime.Duration(time.Second),
},
RPCServer: &RPCServer{
Network: "tcp",
Addr: "3119",
Timeout: xtime.Duration(time.Second),
IdleTimeout: xtime.Duration(time.Second * 60),
MaxLifeTime: xtime.Duration(time.Hour * 2),
ForceCloseWait: xtime.Duration(time.Second * 20),
KeepAliveInterval: xtime.Duration(time.Second * 60),
KeepAliveTimeout: xtime.Duration(time.Second * 20),
},
Backoff: &Backoff{MaxDelay: 300,
BaseDelay: 3,
Factor: 1.8,
Jitter: 1.3,
},
Redis: &Redis{
Network: "tcp",
Addr: "127.0.0.1:6379",
Active: 60000,
Idle: 1024,
DialTimeout: xtime.Duration(200 * time.Second),
ReadTimeout: xtime.Duration(500 * time.Microsecond),
WriteTimeout: xtime.Duration(500 * time.Microsecond),
IdleTimeout: xtime.Duration(120 * time.Second),
Expire: xtime.Duration(30 * time.Minute),
},
}
cfg.Regions = make(map[string][]string, 0)
return cfg
}
<|start_filename|>third-party/discoveryd/main.go<|end_filename|>
package main
import (
"os"
"os/signal"
"runtime"
"syscall"
"time"
"github.com/tsingson/go-daemon"
log "github.com/tsingson/zaplogger"
"go.uber.org/zap"
"github.com/tsingson/discovery/discovery"
"github.com/tsingson/discovery/http"
)
func main() {
runtime.MemProfileRate = 0
runtime.GOMAXPROCS(128)
/**
tw = timingwheel.NewTimingWheel(time.Minute, 60)
tw.StartCron()
defer tw.StopCron()
*/
var cntxt = &daemon.Context{
PidFileName: "pid-discoveryd",
PidFilePerm: 0644,
LogFileName: logPath + "/discoveryd-daemon.log",
LogFilePerm: 0640,
WorkDir: path,
Umask: 027,
// Args: []string{"aaa-demo"},
}
var d, err = cntxt.Reborn()
if err != nil {
log.Fatal("cat's reborn ", zap.Error(err))
}
if d != nil {
return
}
defer cntxt.Release()
log.Info("trying to start daemon")
svr, cancel := discovery.New(cfg)
http.Init(cfg, svr)
// if err != nil {
// cancel()
// os.Exit(-1)
// }
runtime.Goexit()
// init signal
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Infof("discovery get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
cancel()
time.Sleep(time.Second)
log.Info("discovery quit !!!")
// log.Flush()
return
case syscall.SIGHUP:
default:
return
}
}
}
<|start_filename|>goim-nats/dao/nats_test.go<|end_filename|>
package dao
import (
"context"
"os"
"strconv"
"testing"
"github.com/tsingson/ex-goim/goim-nats/logic/conf"
)
var (
d *NatsDao
)
func TestMain(m *testing.M) {
conf.Conf = conf.Default()
d = New(conf.Conf)
os.Exit(m.Run())
}
func TestPushMsg(t *testing.T) {
d.PushMsg(context.TODO(), 122, "room111", []string{"test", "tttt"}, []byte("test"))
}
func BenchmarkNatsDao_PushMsg(b *testing.B) {
// b.StopTimer()
//
// b.StartTimer()
for n := 0; n < b.N; n++ {
d.PushMsg(context.TODO(), 122, "room111", []string{strconv.Itoa(n), "tttt"}, []byte("test"))
}
}
<|start_filename|>Makefile<|end_filename|>
GOCMD=GO111MODULE=on go
GOBUILD=$(GOCMD) build
GOTEST=$(GOCMD) test
all: setup build
setup:
rm -rdf ./dist/
mkdir -p ./dist/linux
mkdir -p ./dist/windows
mkdir -p ./dist/mac
mkdir -p ./dist/log
build-linux:
cp ./cmd/nats/comet/comet-config.toml ./dist/linux/comet-config.toml
cp ./cmd/nats/logic/logic-config.toml ./dist/linux/logic-config.toml
cp ./cmd/nats/job/job-config.toml ./dist/linux/job-config.toml
cp ./third-party/discoveryd/discoveryd-config.toml ./dist/linux/
${BUILD_ENV} GOARCH=amd64 GOOS=linux go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/linux/gnatsd ./third-party/gnatsd/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=linux go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/linux/discoveryd ./third-party/discoveryd/
${BUILD_ENV} GOARCH=amd64 GOOS=linux go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/linux/liftbridge ./third-party/liftbridge/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=linux go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/linux/comet ./cmd/nats/comet/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=linux go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/linux/logic ./cmd/nats/logic/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=linux go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/linux/job ./cmd/nats/job/main.go
build-win:
cp ./cmd/nats/comet/comet-config.toml ./dist/windows/comet-config.toml
cp ./cmd/nats/logic/logic-config.toml ./dist/windows/logic-config.toml
cp ./cmd/nats/job/job-config.toml ./dist/windows/job-config.toml
cp ./third-party/discoveryd/discoveryd-config.toml ./dist/windows/
${BUILD_ENV} GOARCH=amd64 GOOS=windows go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/windows/gnatsd ./third-party/gnatsd/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=windows go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/windows/discoveryd ./third-party/discoveryd/
${BUILD_ENV} GOARCH=amd64 GOOS=windows go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/windows/liftbridge ./third-party/liftbridge/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=windows go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/windows/comet.exe ./cmd/nats/comet/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=windows go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/windows/logic.exe ./cmd/nats/logic/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=windows go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/windows/job.exe ./cmd/nats/job/main.go
build-mac:
cp ./cmd/nats/comet/comet-config.toml ./dist/mac/comet-config.toml
cp ./cmd/nats/logic/logic-config.toml ./dist/mac/logic-config.toml
cp ./cmd/nats/job/job-config.toml ./dist/mac/job-config.toml
cp ./third-party/discoveryd/discoveryd-config.toml ./dist/mac/
${BUILD_ENV} GOARCH=amd64 GOOS=darwin go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/mac/gnatsd ./third-party/gnatsd/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=darwin go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/mac/discoveryd ./third-party/discoveryd/
${BUILD_ENV} GOARCH=amd64 GOOS=darwin go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/mac/liftbridge ./third-party/liftbridge/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=darwin go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/mac/comet ./cmd/nats/comet/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=darwin go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/mac/logic ./cmd/nats/logic/main.go
${BUILD_ENV} GOARCH=amd64 GOOS=darwin go build -gcflags=-trimpath=OPATH -asmflags=-trimpath=OPATH -a -tags netgo -ldflags "-w -s -extldflags '-static'" -o ./dist/mac/job ./cmd/nats/job/main.go
test:
$(GOTEST) -v ./...
clean:
rm -rf dist/
run-linux:
nohup ./dist/linux/gnatsd 2>&1 > dist/log/gnatsd.log &
nohup ./dist/linux/liftbridge --raft-bootstrap-seed 2>&1 > dist/log/liftbridge.log &
nohup ./dist/linux/discoveryd 2>&1 > dist/log/discoveryd.log &
nohup ./dist/linux/logic 2>&1 > dist/log/logic.log &
nohup ./dist/linux/comet 2>&1 > dist/log/comet.log &
nohup ./dist/linux/job 2>&1 > dist/log/job.log &
run-mac:
nohup ./dist/mac/gnatsd 2>&1 > dist/log/gnatsd.log &
nohup ./dist/mac/liftbridge --raft-bootstrap-seed 2>&1 > dist/log/liftbridge.log &
nohup ./dist/mac/discoveryd 2>&1 > dist/log/discoveryd.log &
nohup ./dist/mac/logic 2>&1 > dist/log/logic.log &
nohup ./dist/mac/comet 2>&1 > dist/log/comet.log &
nohup ./dist/mac/job 2>&1 > dist/log/job.log &
stop:
pkill -f ./dist/linux/gnatsd
pkill -f ./dist/linux/liftbridge
pkill -f ./dist/linux/discoveryd
pkill -f ./dist/linux/logic
pkill -f ./dist/linux/job
pkill -f ./dist/linux/comet
<|start_filename|>goim-nats/job/conf/conf.go<|end_filename|>
package conf
import (
"time"
"github.com/BurntSushi/toml"
"github.com/imdario/mergo"
"github.com/tsingson/discovery/naming"
"golang.org/x/xerrors"
xtime "github.com/tsingson/ex-goim/pkg/time"
)
// Config is job config.
type Config struct {
Env *Env
Nats *Nats
Discovery *naming.Config
Comet *Comet
Room *Room
}
// JobConfig is alias of Config
type JobConfig = Config
// Room is room config.
type Room struct {
Batch int
Signal xtime.Duration
Idle xtime.Duration
}
// Comet is comet config.
type Comet struct {
RoutineChan int
RoutineSize int
}
// Kafka is kafka config.
type Kafka struct {
Topic string
Group string
Brokers []string
}
// Env is env config.
type Env struct {
Region string
Zone string
DeployEnv string
Host string
}
type Nats struct {
Channel string
ChannelID string
Group string
NatsAddr string
LiftAddr string
}
type NatsConfig = Nats
var (
confPath string
region string
zone string
deployEnv string
host string
Conf *JobConfig
)
func init() {
Conf = Default()
}
// Default new a config with specified defualt value.
func Default() *Config {
return &Config{
Nats: &Nats{
Channel: "channel",
ChannelID: "channel-stream",
Group: "group",
LiftAddr: "localhost:9292", // address for lift-bridge
NatsAddr: "localhost:4222",
},
Env: &Env{
Region: "china",
Zone: "gd",
DeployEnv: "dev",
Host: "job",
},
Discovery: &naming.Config{
Nodes: []string{"127.0.0.1:7171"},
Region: "china",
Zone: "gd",
Env: "dev",
Host: "discovery",
},
Comet: &Comet{
RoutineChan: 1024,
RoutineSize: 32,
},
Room: &Room{
Batch: 20,
Signal: xtime.Duration(time.Second),
Idle: xtime.Duration(time.Minute * 15),
},
}
}
// Load init config.
func Load(path string) (cfg *Config, err error) {
if len(path) == 0 {
return cfg, xerrors.New("config path is nil")
}
Conf = Default()
cfg = Default()
_, err = toml.DecodeFile(path, &cfg)
if err != nil {
return
}
err = mergo.Merge(&Conf, cfg, mergo.WithOverride)
if err != nil {
return Conf, err
}
return Conf, nil
}
<|start_filename|>goim-nats/comet/discovery_test.go<|end_filename|>
package comet
import (
"testing"
"github.com/tsingson/discovery/naming"
)
func TestRegister(t *testing.T) {
cfg := &naming.Config{
Nodes: []string{"127.0.0.1:7171"}, // NOTE: 配置种子节点(1个或多个),client内部可根据/discovery/nodes节点获取全部node(方便后面增减节点)
Zone: "sh1",
Env: "test",
}
AppID := "goim.comet"
// Hostname:"", // NOTE: hostname 不需要,会优先使用discovery new时Config配置的值,如没有则从os.Hostname方法获取!!!
Addrs := []string{"http://172.0.0.1:8888"}
Register(cfg, AppID, Addrs)
}
<|start_filename|>pkg/utils/utils.go<|end_filename|>
package utils
import (
"bufio"
"crypto/md5"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"reflect"
"sort"
"strings"
"unsafe"
"github.com/karrick/godirwalk"
"github.com/pkg/errors"
"github.com/spf13/afero"
)
const bufferSize = 65536
func Exists(name string) bool {
afs := afero.NewOsFs()
b, e := afero.Exists(afs, name)
if e != nil {
return false
}
return b
}
func DirExists(name string) bool {
afs := afero.NewOsFs()
b, e := afero.DirExists(afs, name)
if e != nil {
return false
}
return b
}
func WriteToFile(c []byte, filename string) error {
// 将指定内容写入到文件中
err := ioutil.WriteFile(filename, c, 0666)
return err
}
// 获取指定目录下的所有文件,不进入下一级目录搜索,可以匹配后缀过滤。
func ListFiles(dirPth string, suffix string) (files []string, err error) {
files = make([]string, 0, 10)
dir, err := ioutil.ReadDir(dirPth)
if err != nil {
return nil, err
}
PthSep := string(os.PathSeparator)
suffix = strings.ToUpper(suffix) // 忽略后缀匹配的大小写
for _, fi := range dir {
if fi.IsDir() { // 忽略目录
continue
}
if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) { // 匹配文件
files = append(files, dirPth+PthSep+fi.Name())
}
}
return files, nil
}
func ListDir(dirPth string) (files []string, err error) {
files = make([]string, 0, 100)
dir, err := ioutil.ReadDir(dirPth)
if err != nil {
return nil, err
}
PthSep := string(os.PathSeparator)
for _, fi := range dir {
if fi.IsDir() { // 忽略目录
files = append(files, StrBuilder(dirPth, PthSep, fi.Name()))
}
}
// litter.Dump(files)
return files, nil
}
func Md5CheckSum(filename string) (string, error) {
if info, err := os.Stat(filename); err != nil {
return "", err
} else if info.IsDir() {
return "", nil
}
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
hash := md5.New()
for buf, reader := make([]byte, bufferSize), bufio.NewReader(file); ; {
n, err := reader.Read(buf)
if err != nil {
if err == io.EOF {
break
}
return "", err
}
hash.Write(buf[:n])
}
checksum := fmt.Sprintf("%x", hash.Sum(nil))
return checksum, nil
}
func ListSubPath(osDirname string) ([]string, error) {
children, err := godirwalk.ReadDirnames(osDirname, nil)
if err != nil {
err1 := errors.Wrap(err, "cannot get list of directory children")
return nil, err1
}
sort.Strings(children)
var sublist []string
sublist = make([]string, len(children))
for _, child := range children {
pathNode := StrBuilder(osDirname, "/", child, "/")
// fmt.Printf("%s\n", pathNode)
sublist = append(sublist, pathNode)
}
return sublist, nil
}
func GetCurrentPath() (string, error) {
return filepath.Abs(filepath.Dir(os.Args[0]))
}
func GetCurrentExecDir() (dir string, err error) {
path, err := exec.LookPath(os.Args[0])
if err != nil {
// fmt.Printf("exec.LookPath(%s), err: %s\n", os.Args[0], err)
return "", err
}
absPath, err := filepath.Abs(path)
if err != nil {
// fmt.Printf("filepath.Abs(%s), err: %s\n", path, err)
return "", err
}
dir = filepath.Dir(absPath)
return dir, nil
}
// B2S converts a byte slice to a string.
// It's fasthttpgx, but not safe. Use it only if you know what you're doing.
func B2S(b []byte) string {
bytesHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
strHeader := reflect.StringHeader{
Data: bytesHeader.Data,
Len: bytesHeader.Len,
}
return *(*string)(unsafe.Pointer(&strHeader))
}
// S2B converts a string to a byte slice.
// It's fasthttpgx, but not safe. Use it only if you know what you're doing.
func S2B(s string) []byte {
strHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))
bytesHeader := reflect.SliceHeader{
Data: strHeader.Data,
Len: strHeader.Len,
Cap: strHeader.Len,
}
return *(*[]byte)(unsafe.Pointer(&bytesHeader))
}
func StrBuilder(args ...string) string {
var str strings.Builder
for _, v := range args {
str.WriteString(v)
}
return str.String()
}
| tsingson/ex-goim |
<|start_filename|>domain/stock/mem_stock.go<|end_filename|>
package stock
import (
"errors"
"github.com/letian0805/seckill/infrastructure/stores"
)
type memStock struct {
eventID string
goodsID string
key string
}
var (
cache = stores.NewIntCache()
ErrNotFound = errors.New("not found")
)
func NewMemStock(eventID string, goodsID string) (Stock, error) {
if eventID == "" || goodsID == "" {
return nil, errors.New("invalid event id or goods id")
}
key := eventID + "." + goodsID
stock := &memStock{
eventID: eventID,
goodsID: goodsID,
key: key,
}
return stock, nil
}
func (ms *memStock) Set(val int64, expiration int64) error {
cache.Set(ms.key, val)
return nil
}
func (ms *memStock) Get() (int64, error) {
val, ok := cache.Get(ms.key)
if !ok {
return 0, ErrNotFound
}
return val, nil
}
func (ms *memStock) Sub(uid string) (int64, error) {
return cache.Add(ms.key, -1), nil
}
func (ms *memStock) Del() error {
cache.Del(ms.key)
return nil
}
func (ms *memStock) EventID() string {
return ms.eventID
}
func (ms *memStock) GoodsID() string {
return ms.goodsID
}
<|start_filename|>interfaces/api/api.go<|end_filename|>
package api
import (
"net"
"github.com/letian0805/seckill/domain/shop"
"github.com/letian0805/seckill/infrastructure/stores/redis"
"github.com/sirupsen/logrus"
"github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/spf13/viper"
)
var lis net.Listener
func Run() error {
var err error
bind := viper.GetString("api.bind")
logrus.Info("run api server on ", bind)
lis, err = utils.Listen("tcp", bind)
if err != nil {
return err
}
g := gin.New()
// 更新程序,给老版本发送信号
go utils.UpdateProc("api")
if err := redis.Init(); err != nil {
return err
}
// 监控黑名单变更
utils.WatchBlacklist()
// 初始化路由
initRouters(g)
// 初始化 shop
shop.Init()
pprof.Register(g)
// 运行服务
return g.RunListener(lis)
}
func Exit() {
lis.Close()
// TODO: 等待请求处理完
// time.Sleep(10 * time.Second)
logrus.Info("api server exit")
}
<|start_filename|>infrastructure/stores/etcd/etcd.go<|end_filename|>
package etcd
import (
"sync"
"time"
etcd "github.com/coreos/etcd/clientv3"
"github.com/spf13/viper"
)
var etcdCli *etcd.Client
var etcdOnce = &sync.Once{}
func Init() error {
var err error
etcdOnce.Do(
func() {
endpoints := viper.GetStringSlice("etcd.endpoints")
username := viper.GetString("etcd.username")
password := viper.GetString("etcd.password")
cfg := etcd.Config{
Endpoints: endpoints,
DialTimeout: time.Second,
Username: username,
Password: password,
}
etcdCli, err = etcd.New(cfg)
})
return err
}
func GetClient() *etcd.Client {
return etcdCli
}
<|start_filename|>infrastructure/mq/memory.go<|end_filename|>
package mq
import (
"errors"
"fmt"
"github.com/letian0805/seckill/infrastructure/pool"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/spf13/viper"
)
type memoryQueue struct {
q utils.RateLimiter
}
func init() {
Register("memory", FactoryFunc(memoryQueueFactory))
}
func memoryQueueFactory(name string) (Queue, error) {
rate := viper.GetInt64(fmt.Sprintf("queue.%s.rate", name))
size := viper.GetInt(fmt.Sprintf("queue.%s.size", name))
q, _ := utils.NewRateLimiter(size, rate, utils.FanIn)
mq := &memoryQueue{
q: q,
}
return mq, nil
}
func (mq *memoryQueue) Produce(task pool.Task) error {
if ok := mq.q.Push(task); !ok {
return errors.New("queue producer error")
}
return nil
}
func (mq *memoryQueue) Consume() (pool.Task, error) {
t, ok := mq.q.Pop()
if !ok {
return nil, errors.New("queue consumer error")
}
return t, nil
}
func (mq *memoryQueue) Close() error {
return mq.q.Close()
}
<|start_filename|>application/api/rpc/event.pb.go<|end_filename|>
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: application/api/rpc/event.proto
package rpc
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type Goods struct {
Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Desc string `protobuf:"bytes,2,opt,name=desc,proto3" json:"desc,omitempty"`
Img string `protobuf:"bytes,3,opt,name=img,proto3" json:"img,omitempty"`
Price string `protobuf:"bytes,4,opt,name=price,proto3" json:"price,omitempty"`
EventPrice string `protobuf:"bytes,5,opt,name=event_price,json=eventPrice,proto3" json:"event_price,omitempty"`
EventStock int32 `protobuf:"varint,6,opt,name=event_stock,json=eventStock,proto3" json:"event_stock,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Goods) Reset() { *m = Goods{} }
func (m *Goods) String() string { return proto.CompactTextString(m) }
func (*Goods) ProtoMessage() {}
func (*Goods) Descriptor() ([]byte, []int) {
return fileDescriptor_83ae9c5481ac0209, []int{0}
}
func (m *Goods) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Goods.Unmarshal(m, b)
}
func (m *Goods) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Goods.Marshal(b, m, deterministic)
}
func (m *Goods) XXX_Merge(src proto.Message) {
xxx_messageInfo_Goods.Merge(m, src)
}
func (m *Goods) XXX_Size() int {
return xxx_messageInfo_Goods.Size(m)
}
func (m *Goods) XXX_DiscardUnknown() {
xxx_messageInfo_Goods.DiscardUnknown(m)
}
var xxx_messageInfo_Goods proto.InternalMessageInfo
func (m *Goods) GetId() int32 {
if m != nil {
return m.Id
}
return 0
}
func (m *Goods) GetDesc() string {
if m != nil {
return m.Desc
}
return ""
}
func (m *Goods) GetImg() string {
if m != nil {
return m.Img
}
return ""
}
func (m *Goods) GetPrice() string {
if m != nil {
return m.Price
}
return ""
}
func (m *Goods) GetEventPrice() string {
if m != nil {
return m.EventPrice
}
return ""
}
func (m *Goods) GetEventStock() int32 {
if m != nil {
return m.EventStock
}
return 0
}
type Event struct {
Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
TopicId int32 `protobuf:"varint,2,opt,name=topic_id,json=topicId,proto3" json:"topic_id,omitempty"`
StartTime int64 `protobuf:"varint,3,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"`
EndTime int64 `protobuf:"varint,4,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"`
Limit int32 `protobuf:"varint,5,opt,name=limit,proto3" json:"limit,omitempty"`
GoodsList []*Goods `protobuf:"bytes,6,rep,name=goods_list,json=goodsList,proto3" json:"goods_list,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Event) Reset() { *m = Event{} }
func (m *Event) String() string { return proto.CompactTextString(m) }
func (*Event) ProtoMessage() {}
func (*Event) Descriptor() ([]byte, []int) {
return fileDescriptor_83ae9c5481ac0209, []int{1}
}
func (m *Event) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Event.Unmarshal(m, b)
}
func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Event.Marshal(b, m, deterministic)
}
func (m *Event) XXX_Merge(src proto.Message) {
xxx_messageInfo_Event.Merge(m, src)
}
func (m *Event) XXX_Size() int {
return xxx_messageInfo_Event.Size(m)
}
func (m *Event) XXX_DiscardUnknown() {
xxx_messageInfo_Event.DiscardUnknown(m)
}
var xxx_messageInfo_Event proto.InternalMessageInfo
func (m *Event) GetId() int32 {
if m != nil {
return m.Id
}
return 0
}
func (m *Event) GetTopicId() int32 {
if m != nil {
return m.TopicId
}
return 0
}
func (m *Event) GetStartTime() int64 {
if m != nil {
return m.StartTime
}
return 0
}
func (m *Event) GetEndTime() int64 {
if m != nil {
return m.EndTime
}
return 0
}
func (m *Event) GetLimit() int32 {
if m != nil {
return m.Limit
}
return 0
}
func (m *Event) GetGoodsList() []*Goods {
if m != nil {
return m.GoodsList
}
return nil
}
type Topic struct {
Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"`
Desc string `protobuf:"bytes,3,opt,name=desc,proto3" json:"desc,omitempty"`
Banner string `protobuf:"bytes,4,opt,name=banner,proto3" json:"banner,omitempty"`
StartTime int64 `protobuf:"varint,5,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"`
EndTime int64 `protobuf:"varint,6,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Topic) Reset() { *m = Topic{} }
func (m *Topic) String() string { return proto.CompactTextString(m) }
func (*Topic) ProtoMessage() {}
func (*Topic) Descriptor() ([]byte, []int) {
return fileDescriptor_83ae9c5481ac0209, []int{2}
}
func (m *Topic) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Topic.Unmarshal(m, b)
}
func (m *Topic) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Topic.Marshal(b, m, deterministic)
}
func (m *Topic) XXX_Merge(src proto.Message) {
xxx_messageInfo_Topic.Merge(m, src)
}
func (m *Topic) XXX_Size() int {
return xxx_messageInfo_Topic.Size(m)
}
func (m *Topic) XXX_DiscardUnknown() {
xxx_messageInfo_Topic.DiscardUnknown(m)
}
var xxx_messageInfo_Topic proto.InternalMessageInfo
func (m *Topic) GetId() int32 {
if m != nil {
return m.Id
}
return 0
}
func (m *Topic) GetTitle() string {
if m != nil {
return m.Title
}
return ""
}
func (m *Topic) GetDesc() string {
if m != nil {
return m.Desc
}
return ""
}
func (m *Topic) GetBanner() string {
if m != nil {
return m.Banner
}
return ""
}
func (m *Topic) GetStartTime() int64 {
if m != nil {
return m.StartTime
}
return 0
}
func (m *Topic) GetEndTime() int64 {
if m != nil {
return m.EndTime
}
return 0
}
type Response struct {
Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"`
Msg string `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Response) Reset() { *m = Response{} }
func (m *Response) String() string { return proto.CompactTextString(m) }
func (*Response) ProtoMessage() {}
func (*Response) Descriptor() ([]byte, []int) {
return fileDescriptor_83ae9c5481ac0209, []int{3}
}
func (m *Response) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_Response.Unmarshal(m, b)
}
func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_Response.Marshal(b, m, deterministic)
}
func (m *Response) XXX_Merge(src proto.Message) {
xxx_messageInfo_Response.Merge(m, src)
}
func (m *Response) XXX_Size() int {
return xxx_messageInfo_Response.Size(m)
}
func (m *Response) XXX_DiscardUnknown() {
xxx_messageInfo_Response.DiscardUnknown(m)
}
var xxx_messageInfo_Response proto.InternalMessageInfo
func (m *Response) GetCode() int32 {
if m != nil {
return m.Code
}
return 0
}
func (m *Response) GetMsg() string {
if m != nil {
return m.Msg
}
return ""
}
func init() {
proto.RegisterType((*Goods)(nil), "rpc.Goods")
proto.RegisterType((*Event)(nil), "rpc.Event")
proto.RegisterType((*Topic)(nil), "rpc.Topic")
proto.RegisterType((*Response)(nil), "rpc.Response")
}
func init() { proto.RegisterFile("application/api/rpc/event.proto", fileDescriptor_83ae9c5481ac0209) }
var fileDescriptor_83ae9c5481ac0209 = []byte{
// 389 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x52, 0x5f, 0xab, 0xd3, 0x30,
0x14, 0xa7, 0xeb, 0xd2, 0xbb, 0x9d, 0xaa, 0x48, 0x18, 0x52, 0x05, 0xb9, 0xa3, 0x4f, 0xbd, 0x2f,
0x9b, 0x5c, 0x3f, 0x82, 0x88, 0x08, 0x82, 0x97, 0x78, 0xdf, 0x4b, 0x97, 0x64, 0xe3, 0x60, 0x9b,
0x84, 0x26, 0xf8, 0x45, 0xc4, 0x8f, 0xe1, 0x9b, 0x1f, 0x50, 0x72, 0x52, 0x86, 0x75, 0x43, 0xdf,
0xce, 0xef, 0xcf, 0x4e, 0x7e, 0xe7, 0xb7, 0xc2, 0x6d, 0xe7, 0x5c, 0x8f, 0xb2, 0x0b, 0x68, 0xcd,
0xbe, 0x73, 0xb8, 0x1f, 0x9d, 0xdc, 0xeb, 0x6f, 0xda, 0x84, 0x9d, 0x1b, 0x6d, 0xb0, 0x3c, 0x1f,
0x9d, 0xac, 0x7f, 0x64, 0xc0, 0x3e, 0x58, 0xab, 0x3c, 0x7f, 0x06, 0x0b, 0x54, 0x55, 0xb6, 0xcd,
0x1a, 0x26, 0x16, 0xa8, 0x38, 0x87, 0xa5, 0xd2, 0x5e, 0x56, 0x8b, 0x6d, 0xd6, 0xac, 0x05, 0xcd,
0xfc, 0x39, 0xe4, 0x38, 0x9c, 0xaa, 0x9c, 0xa8, 0x38, 0xf2, 0x0d, 0x30, 0x37, 0xa2, 0xd4, 0xd5,
0x92, 0xb8, 0x04, 0xf8, 0x2d, 0x94, 0xf4, 0x52, 0x9b, 0x34, 0x46, 0x1a, 0x10, 0xf5, 0x30, 0x37,
0xf8, 0x60, 0xe5, 0xd7, 0xaa, 0xa0, 0x57, 0x93, 0xe1, 0x4b, 0x64, 0xea, 0x9f, 0x19, 0xb0, 0xf7,
0x11, 0x5e, 0xe4, 0x7a, 0x09, 0xab, 0x60, 0x1d, 0xca, 0x16, 0x15, 0x65, 0x63, 0xe2, 0x86, 0xf0,
0x47, 0xc5, 0x5f, 0x03, 0xf8, 0xd0, 0x8d, 0xa1, 0x0d, 0x38, 0x68, 0x4a, 0x99, 0x8b, 0x35, 0x31,
0x8f, 0x38, 0xe8, 0xf8, 0x4b, 0x6d, 0x54, 0x12, 0x97, 0x24, 0xde, 0x68, 0xa3, 0x48, 0xda, 0x00,
0xeb, 0x71, 0xc0, 0x40, 0x51, 0x99, 0x48, 0x80, 0xdf, 0x01, 0x9c, 0x62, 0x37, 0x6d, 0x8f, 0x3e,
0x54, 0xc5, 0x36, 0x6f, 0xca, 0x7b, 0xd8, 0x8d, 0x4e, 0xee, 0xa8, 0x32, 0xb1, 0x26, 0xf5, 0x13,
0xfa, 0x50, 0x7f, 0xcf, 0x80, 0x3d, 0xc6, 0x18, 0x17, 0x79, 0x37, 0xc0, 0x02, 0x86, 0x5e, 0x4f,
0x45, 0x26, 0x70, 0x6e, 0x37, 0xff, 0xa3, 0xdd, 0x17, 0x50, 0x1c, 0x3a, 0x63, 0xf4, 0x38, 0x95,
0x39, 0xa1, 0xbf, 0xce, 0x62, 0xff, 0x3a, 0xab, 0x98, 0x9d, 0x55, 0xbf, 0x81, 0x95, 0xd0, 0xde,
0x59, 0xe3, 0xe9, 0x45, 0x69, 0x95, 0x9e, 0x92, 0xd1, 0x1c, 0xff, 0xcf, 0xc1, 0x9f, 0xa6, 0x64,
0x71, 0xbc, 0xff, 0x95, 0xc1, 0x8a, 0x7a, 0x17, 0x0f, 0xef, 0x78, 0x03, 0x25, 0xcd, 0x9f, 0x4d,
0x8f, 0x46, 0xf3, 0x74, 0x3a, 0x31, 0xaf, 0x9e, 0xd2, 0x7c, 0x5e, 0x7e, 0x07, 0x4f, 0x92, 0xf3,
0x78, 0xfc, 0x9f, 0xb5, 0x81, 0x92, 0x8a, 0x9a, 0x2d, 0x25, 0xe6, 0xca, 0xd2, 0xe4, 0x9c, 0x2d,
0xbd, 0x66, 0x3d, 0x14, 0xf4, 0x49, 0xbf, 0xfd, 0x1d, 0x00, 0x00, 0xff, 0xff, 0x7e, 0x20, 0x74,
0x1f, 0xf5, 0x02, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// EventRPCClient is the client API for EventRPC service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type EventRPCClient interface {
EventOnline(ctx context.Context, in *Event, opts ...grpc.CallOption) (*Response, error)
EventOffline(ctx context.Context, in *Event, opts ...grpc.CallOption) (*Response, error)
TopicOnline(ctx context.Context, in *Topic, opts ...grpc.CallOption) (*Response, error)
TopicOffline(ctx context.Context, in *Topic, opts ...grpc.CallOption) (*Response, error)
}
type eventRPCClient struct {
cc *grpc.ClientConn
}
func NewEventRPCClient(cc *grpc.ClientConn) EventRPCClient {
return &eventRPCClient{cc}
}
func (c *eventRPCClient) EventOnline(ctx context.Context, in *Event, opts ...grpc.CallOption) (*Response, error) {
out := new(Response)
err := c.cc.Invoke(ctx, "/rpc.EventRPC/EventOnline", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *eventRPCClient) EventOffline(ctx context.Context, in *Event, opts ...grpc.CallOption) (*Response, error) {
out := new(Response)
err := c.cc.Invoke(ctx, "/rpc.EventRPC/EventOffline", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *eventRPCClient) TopicOnline(ctx context.Context, in *Topic, opts ...grpc.CallOption) (*Response, error) {
out := new(Response)
err := c.cc.Invoke(ctx, "/rpc.EventRPC/TopicOnline", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *eventRPCClient) TopicOffline(ctx context.Context, in *Topic, opts ...grpc.CallOption) (*Response, error) {
out := new(Response)
err := c.cc.Invoke(ctx, "/rpc.EventRPC/TopicOffline", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// EventRPCServer is the server API for EventRPC service.
type EventRPCServer interface {
EventOnline(context.Context, *Event) (*Response, error)
EventOffline(context.Context, *Event) (*Response, error)
TopicOnline(context.Context, *Topic) (*Response, error)
TopicOffline(context.Context, *Topic) (*Response, error)
}
// UnimplementedEventRPCServer can be embedded to have forward compatible implementations.
type UnimplementedEventRPCServer struct {
}
func (*UnimplementedEventRPCServer) EventOnline(ctx context.Context, req *Event) (*Response, error) {
return nil, status.Errorf(codes.Unimplemented, "method EventOnline not implemented")
}
func (*UnimplementedEventRPCServer) EventOffline(ctx context.Context, req *Event) (*Response, error) {
return nil, status.Errorf(codes.Unimplemented, "method EventOffline not implemented")
}
func (*UnimplementedEventRPCServer) TopicOnline(ctx context.Context, req *Topic) (*Response, error) {
return nil, status.Errorf(codes.Unimplemented, "method TopicOnline not implemented")
}
func (*UnimplementedEventRPCServer) TopicOffline(ctx context.Context, req *Topic) (*Response, error) {
return nil, status.Errorf(codes.Unimplemented, "method TopicOffline not implemented")
}
func RegisterEventRPCServer(s *grpc.Server, srv EventRPCServer) {
s.RegisterService(&_EventRPC_serviceDesc, srv)
}
func _EventRPC_EventOnline_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Event)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EventRPCServer).EventOnline(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpc.EventRPC/EventOnline",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EventRPCServer).EventOnline(ctx, req.(*Event))
}
return interceptor(ctx, in, info, handler)
}
func _EventRPC_EventOffline_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Event)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EventRPCServer).EventOffline(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpc.EventRPC/EventOffline",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EventRPCServer).EventOffline(ctx, req.(*Event))
}
return interceptor(ctx, in, info, handler)
}
func _EventRPC_TopicOnline_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Topic)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EventRPCServer).TopicOnline(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpc.EventRPC/TopicOnline",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EventRPCServer).TopicOnline(ctx, req.(*Topic))
}
return interceptor(ctx, in, info, handler)
}
func _EventRPC_TopicOffline_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Topic)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(EventRPCServer).TopicOffline(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/rpc.EventRPC/TopicOffline",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(EventRPCServer).TopicOffline(ctx, req.(*Topic))
}
return interceptor(ctx, in, info, handler)
}
var _EventRPC_serviceDesc = grpc.ServiceDesc{
ServiceName: "rpc.EventRPC",
HandlerType: (*EventRPCServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "EventOnline",
Handler: _EventRPC_EventOnline_Handler,
},
{
MethodName: "EventOffline",
Handler: _EventRPC_EventOffline_Handler,
},
{
MethodName: "TopicOnline",
Handler: _EventRPC_TopicOnline_Handler,
},
{
MethodName: "TopicOffline",
Handler: _EventRPC_TopicOffline_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "application/api/rpc/event.proto",
}
<|start_filename|>domain/stock/mem_stock_test.go<|end_filename|>
package stock
import (
"testing"
)
func TestMemStock(t *testing.T) {
var (
st Stock
err error
val int64
)
if st, err = NewMemStock("101", "1001"); err != nil {
t.Fatal(err)
}
if err = st.Set(10, 1); err != nil {
t.Fatal(err)
}
if val, err = st.Get(); err != nil {
t.Fatal(err)
} else if val != 10 {
t.Fatal("not equal 10")
}
if val, err = st.Sub("123"); err != nil {
t.Fatal(err)
} else if val != 9 {
t.Fatal("not equal 9")
}
if err = st.Del(); err != nil {
t.Fatal(err)
}
if val, err = st.Get(); err != ErrNotFound {
t.Fatal(err)
} else if val != 0 {
t.Fatal("not equal 0")
}
}
<|start_filename|>infrastructure/stores/mysql/mysql_test.go<|end_filename|>
package mysql
import (
"testing"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
)
func TestMysql(t *testing.T) {
db, err := xorm.NewEngine("mysql", "root:123@tcp(127.0.0.1:3306)/test")
if err != nil {
t.Fatal(err)
}
_ = db
if rows, err := db.Query("show tables"); err != nil {
t.Error(err)
} else {
t.Log(string(rows[0]["Tables_in_test"]))
}
}
<|start_filename|>domain/stock/stock.go<|end_filename|>
package stock
import (
"errors"
"fmt"
"time"
"github.com/letian0805/seckill/infrastructure/stores/redis"
)
type Stock interface {
// 设置库存,并设置过期时间
Set(val int64, expire int64) error
// 直接返回剩余库存
Get() (int64, error)
// 尝试扣减一个库存,并返回剩余库存
Sub(uid string) (int64, error)
// 删除库存数据
Del() error
// 返回活动 ID
EventID() string
// 返回商品 ID
GoodsID() string
}
type redisStock struct {
eventID string
goodsID string
key string
}
func NewRedisStock(eventID string, goodsID string) (Stock, error) {
if eventID == "" || goodsID == "" {
return nil, errors.New("invalid event id or goods id")
}
stock := &redisStock{
eventID: eventID,
goodsID: goodsID,
key: fmt.Sprintf("seckill#%s#%s", eventID, goodsID),
}
return stock, nil
}
func (rs *redisStock) Set(val int64, expiration int64) error {
cli := redis.GetClient()
return cli.Set(rs.key, val, time.Duration(expiration)*time.Second).Err()
}
func (rs *redisStock) Sub(uid string) (int64, error) {
cli := redis.GetClient()
script := `
local history=redis.call('get',KEYS[1])
local stock=redis.call('get', KEYS[2])
if (history and history >= '1') or stock==false or stock <= '0' then
return -1
else
stock=redis.call('decr', KEYS[2])
if stock >= 0 and redis.call('set', KEYS[1], '1', 'ex', 86400) then
return stock
else
return -1
end
end`
if res, err := cli.Eval(script, []string{fmt.Sprintf("%s#%s", rs.key, uid), rs.key}).Result(); err != nil {
return -1, err
} else if resInt, ok := res.(int64); ok && resInt != -1 {
return resInt, nil
} else {
return -1, errors.New("redis error")
}
}
func (rs *redisStock) Get() (int64, error) {
cli := redis.GetClient()
if val, err := cli.Get(rs.key).Int64(); err != nil && err != redis.Nil {
return 0, err
} else {
return val, nil
}
}
func (rs *redisStock) Del() error {
cli := redis.GetClient()
return cli.Del(rs.key).Err()
}
func (rs *redisStock) EventID() string {
return rs.eventID
}
func (rs *redisStock) GoodsID() string {
return rs.goodsID
}
<|start_filename|>interfaces/api/routers.go<|end_filename|>
package api
import (
"github.com/gin-gonic/gin"
"github.com/letian0805/seckill/application/api"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/letian0805/seckill/interfaces/api/middlewares"
)
func initRouters(g *gin.Engine) {
g.POST("/login", api.User{}.Login)
eventCB := utils.NewCircuitBreaker(
utils.WithDuration(100),
utils.WithTotalLimit(20000),
utils.WithLatencyLimit(100),
utils.WithFailsLimit(5),
)
eventCBMdw := middlewares.NewCircuitBreakMiddleware(eventCB)
event := g.Group("/event").Use(eventCBMdw, middlewares.NewAuthMiddleware(false))
eventApp := api.Event{}
event.GET("/list", eventApp.List)
event.GET("/info", eventApp.Info)
subscribe := g.Group("/event/subscribe").Use(middlewares.NewAuthMiddleware(true))
subscribe.POST("/", eventApp.Subscribe)
shopCB := utils.NewCircuitBreaker(
utils.WithDuration(100),
utils.WithTotalLimit(1000),
utils.WithLatencyLimit(200),
utils.WithFailsLimit(5),
)
mdws := []gin.HandlerFunc{
middlewares.NewCircuitBreakMiddleware(shopCB),
middlewares.NewAuthMiddleware(true),
middlewares.Blacklist,
}
shop := g.Group("/shop").Use(mdws...)
shopApp := api.Shop{}
shop.PUT("/cart/add", shopApp.AddCart)
}
<|start_filename|>domain/user/auth.go<|end_filename|>
package user
import (
"crypto/aes"
"encoding/base64"
"encoding/json"
"time"
"github.com/sirupsen/logrus"
)
type Info struct {
UID string `json:"uid"`
LoginTime int64 `json:"loginTime"`
ExpireTime int64 `json:"expireTime"`
}
const (
TokenPrefix = "Bearer "
TokenHeader = "Authorization"
)
var authKey = []byte("seckill2021")
func padding(src []byte, blkSize int) []byte {
l := len(src)
for i := 0; i < blkSize-l%blkSize; i++ {
src = append(src, byte(0))
}
return src
}
func Auth(token string) *Info {
defer func() {
if err := recover(); err != nil {
logrus.Error(err)
}
}()
cipher, err := aes.NewCipher(padding(authKey, 16))
if err != nil {
logrus.Error(err)
return nil
}
src, err1 := base64.StdEncoding.DecodeString(token)
if err1 != nil || len(src) == 0 {
return nil
}
src = padding(src, cipher.BlockSize())
output := make([]byte, len(src))
cipher.Decrypt(output, src)
var info *Info
err = json.Unmarshal(output, &info)
if err != nil || info.ExpireTime < time.Now().Unix() {
return nil
}
return info
}
func Login(uid string, passwd string) (*Info, string) {
defer func() {
if err := recover(); err != nil {
logrus.Error(err)
}
}()
info := &Info{
UID: uid,
LoginTime: time.Now().Unix(),
ExpireTime: time.Now().Unix() + 24*3600,
}
data, err := json.Marshal(info)
if err != nil {
return nil, ""
}
cipher, err1 := aes.NewCipher(padding(authKey, 16))
if err1 != nil {
logrus.Error(err1)
return nil, ""
}
data1 := padding(data, cipher.BlockSize())
dst := make([]byte, len(data1))
cipher.Encrypt(dst, data1)
logrus.Info(len(data), len(data1))
return info, base64.StdEncoding.EncodeToString(dst[:len(data)])
}
<|start_filename|>infrastructure/stores/cache_test.go<|end_filename|>
package stores_test
import (
"os"
"strconv"
"sync"
"testing"
. "github.com/letian0805/seckill/infrastructure/stores"
)
func TestIntCache(t *testing.T) {
c := NewIntCache()
key := "test"
c.Set(key, 1)
if v, ok := c.Get(key); !ok || v != 1 {
t.Fatal("failed")
}
if v := c.Add(key, 5); v != 6 {
t.Fatal("failed")
}
c.Del(key)
if _, ok := c.Get(key); ok {
t.Fatal("failed")
}
}
func TestIntCache_Add(t *testing.T) {
cache := NewIntCache()
cases := []struct {
key string
delta int64
expect int64
}{
{"test1", 0, 0},
{"test1", 1, 1},
{"test1", -1, 0},
{"test1", 0, 0},
{"test2", 1, 1},
{"test3", -1, -1},
}
for _, c := range cases {
if cache.Add(c.key, c.delta) != c.expect {
t.Fatal(c)
}
}
}
func TestObjCache(t *testing.T) {
c := NewObjCache()
key := "test"
c.Set(key, int64(1))
if v, ok := c.Get(key); !ok || v.(int64) != 1 {
t.Fatal("failed")
t.Error()
}
c.Del(key)
if _, ok := c.Get(key); ok {
t.Fatal("failed")
}
}
func initKeys(b *testing.B) []string {
var keys = make([]string, 0)
maxKeyStr := os.Getenv("maxKey")
maxKey, _ := strconv.Atoi(maxKeyStr)
if maxKey <= 0 {
maxKey = b.N
}
for i := 0; i < maxKey; i++ {
keys = append(keys, strconv.Itoa(i))
}
return keys
}
func initIntCache(b *testing.B, c IntCache, keys []string) {
l := len(keys)
for i := 0; i < b.N; i++ {
c.Set(keys[i%l], int64(i))
}
}
func initSyncMap(b *testing.B, c sync.Map, keys []string) {
l := len(keys)
for i := 0; i < b.N; i++ {
c.Store(keys[i%l], int64(i))
}
}
func initObjCache(b *testing.B, c ObjCache, keys []string) {
l := len(keys)
for i := 0; i < b.N; i++ {
c.Set(keys[i%l], int64(i))
}
}
func BenchmarkIntCache_Add(b *testing.B) {
keys := initKeys(b)
c := NewIntCache()
initIntCache(b, c, keys)
l := len(keys)
b.ReportAllocs()
b.StartTimer()
for i := 0; i < b.N; i++ {
c.Add(keys[i%l], 1)
}
b.StopTimer()
}
func benchmarkCacheSet(b *testing.B, setter func(key string, val int64), keys []string) {
b.ReportAllocs()
b.StartTimer()
l := len(keys)
for i := 0; i < b.N; i++ {
setter(keys[i%l], int64(i))
}
b.StopTimer()
}
func BenchmarkCache_Set(b *testing.B) {
keys := make([]string, b.N, b.N)
for i := 0; i < b.N; i++ {
keys[i] = strconv.Itoa(i)
}
b.ResetTimer()
b.Run("intCache", func(b *testing.B) {
c := NewIntCache()
setter := func(key string, val int64) {
c.Set(key, val)
}
benchmarkCacheSet(b, setter, keys)
})
b.Run("objCache", func(b *testing.B) {
c := NewObjCache()
setter := func(key string, val int64) {
c.Set(key, val)
}
benchmarkCacheSet(b, setter, keys)
})
b.Run("syncMap", func(b *testing.B) {
c := sync.Map{}
setter := func(key string, val int64) {
c.Store(key, val)
}
benchmarkCacheSet(b, setter, keys)
})
}
func BenchmarkIntCache_Set(b *testing.B) {
keys := initKeys(b)
c := NewIntCache()
b.ReportAllocs()
b.StartTimer()
initIntCache(b, c, keys)
b.StopTimer()
}
func BenchmarkObjCache_Set(b *testing.B) {
keys := initKeys(b)
c := NewObjCache()
b.ReportAllocs()
b.StartTimer()
initObjCache(b, c, keys)
b.StopTimer()
}
func BenchmarkSyncMap_Set(b *testing.B) {
keys := initKeys(b)
c := sync.Map{}
b.ReportAllocs()
b.StartTimer()
initSyncMap(b, c, keys)
b.StopTimer()
}
func BenchmarkIntCache_Get(b *testing.B) {
keys := initKeys(b)
c := NewIntCache()
initIntCache(b, c, keys)
l := len(keys)
b.ReportAllocs()
b.StartTimer()
for i := 0; i < b.N; i++ {
c.Get(keys[i%l])
}
b.StopTimer()
}
func BenchmarkObjCache_Get(b *testing.B) {
keys := initKeys(b)
c := NewObjCache()
initObjCache(b, c, keys)
l := len(keys)
b.ReportAllocs()
b.StartTimer()
for i := 0; i < b.N; i++ {
c.Get(keys[i%l])
}
b.StopTimer()
}
func BenchmarkSyncMap_Get(b *testing.B) {
keys := initKeys(b)
c := sync.Map{}
initSyncMap(b, c, keys)
l := len(keys)
b.ReportAllocs()
b.StartTimer()
for i := 0; i < b.N; i++ {
c.Load(keys[i%l])
}
b.StopTimer()
}
func BenchmarkIntCache_Del(b *testing.B) {
keys := initKeys(b)
c := NewIntCache()
initIntCache(b, c, keys)
l := len(keys)
b.ReportAllocs()
b.StartTimer()
for i := 0; i < b.N; i++ {
c.Del(keys[i%l])
}
b.StopTimer()
}
func BenchmarkObjCache_Del(b *testing.B) {
keys := initKeys(b)
c := NewObjCache()
initObjCache(b, c, keys)
l := len(keys)
b.ReportAllocs()
b.StartTimer()
for i := 0; i < b.N; i++ {
c.Del(keys[i%l])
}
b.StopTimer()
}
func BenchmarkSyncMap_Del(b *testing.B) {
keys := initKeys(b)
c := sync.Map{}
initSyncMap(b, c, keys)
l := len(keys)
b.ReportAllocs()
b.StartTimer()
for i := 0; i < b.N; i++ {
c.Delete(keys[i%l])
}
b.StopTimer()
}
<|start_filename|>infrastructure/utils/proc.go<|end_filename|>
package utils
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"syscall"
"github.com/spf13/viper"
)
func UpdateProc(service string) {
fileName := viper.GetString("global.pid")
fileName = fmt.Sprintf("%s.%s", fileName, service)
if pidFile, err := os.Open(fileName); err == nil {
pidBytes, _ := ioutil.ReadAll(pidFile)
pid, _ := strconv.Atoi(string(pidBytes))
if pid > 0 {
// 为了避免因某些原因老版本程序无法退出,尝试发送多个信号,最后一次 SIGKILL 将强制结束老版程序
signals := []syscall.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL}
if proc, err := os.FindProcess(pid); err == nil {
for _, sig := range signals {
if err = proc.Signal(sig); err != nil {
break
}
var stat *os.ProcessState
// 等待老版程序退出
stat, err = proc.Wait()
if err != nil || stat.Exited() {
break
}
}
}
}
pidFile.Close()
}
if pidFile, err := os.Create(fileName); err == nil {
pid := os.Getpid()
pidFile.Write([]byte(strconv.Itoa(pid)))
pidFile.Close()
}
}
<|start_filename|>infrastructure/stores/cache.go<|end_filename|>
package stores
import (
"sync"
"sync/atomic"
)
type IntCache interface {
Get(key string) (int64, bool)
Set(key string, val int64)
Add(key string, delta int64) int64
Del(key string)
Keys() []string
}
type ObjCache interface {
Get(key string) (interface{}, bool)
Set(key string, val interface{})
Del(key string)
Keys() []string
}
type intCache struct {
sync.RWMutex
data map[string]*int64
}
func NewIntCache() IntCache {
return &intCache{
data: make(map[string]*int64),
}
}
func (c *intCache) getPtr(key string) *int64 {
c.RLock()
vp, _ := c.data[key]
c.RUnlock()
return vp
}
func (c *intCache) Set(key string, val int64) {
vp := c.getPtr(key)
if vp != nil {
atomic.StoreInt64(vp, val)
} else {
vp = new(int64)
*vp = val
c.Lock()
c.data[key] = vp
c.Unlock()
}
}
func (c *intCache) Get(key string) (int64, bool) {
vp := c.getPtr(key)
if vp != nil {
return atomic.LoadInt64(vp), true
}
return 0, false
}
func (c *intCache) Add(key string, delta int64) int64 {
vp := c.getPtr(key)
if vp != nil {
return atomic.AddInt64(vp, delta)
} else {
var val int64
var ok bool
c.Lock()
if vp, ok = c.data[key]; ok {
val = atomic.AddInt64(vp, delta)
} else {
val = delta
vp = &val
c.data[key] = vp
}
c.Unlock()
return val
}
}
func (c *intCache) Del(key string) {
vp := c.getPtr(key)
if vp != nil {
c.Lock()
delete(c.data, key)
c.Unlock()
}
}
func (c *intCache) Keys() []string {
keys := make([]string, 0)
c.RLock()
for k, _ := range c.data {
keys = append(keys, k)
}
c.RUnlock()
return keys
}
type objCache struct {
sync.RWMutex
data map[string]interface{}
}
func NewObjCache() ObjCache {
return &objCache{
data: make(map[string]interface{}),
}
}
func (oc *objCache) Set(key string, data interface{}) {
oc.Lock()
oc.data[key] = data
oc.Unlock()
}
func (oc *objCache) Get(key string) (interface{}, bool) {
oc.RLock()
v, ok := oc.data[key]
oc.RUnlock()
return v, ok
}
func (oc *objCache) Del(key string) {
if _, ok := oc.Get(key); ok {
oc.Lock()
delete(oc.data, key)
oc.Unlock()
}
}
func (oc *objCache) Keys() []string {
keys := make([]string, 0)
oc.RLock()
for k, _ := range oc.data {
keys = append(keys, k)
}
oc.RUnlock()
return keys
}
<|start_filename|>infrastructure/stores/redis/redis.go<|end_filename|>
package redis
import (
"errors"
"github.com/go-redis/redis"
"github.com/spf13/viper"
)
const Nil = redis.Nil
var cli *redis.Client
func Init() error {
addr := viper.GetString("redis.address")
auth := viper.GetString("redis.auth")
if addr == "" {
addr = "127.0.0.1:6379"
}
opt := &redis.Options{
Network: "tcp",
Addr: addr,
Password: <PASSWORD>,
}
cli = redis.NewClient(opt)
if cli == nil {
return errors.New("init redis client failed")
}
return nil
}
func GetClient() *redis.Client {
return cli
}
<|start_filename|>infrastructure/mq/mq.go<|end_filename|>
package mq
import (
"io"
"github.com/letian0805/seckill/infrastructure/pool"
)
type Queue interface {
Producer
Consumer
io.Closer
}
type Producer interface {
Produce(task pool.Task) error
}
type Consumer interface {
Consume() (pool.Task, error)
}
type Factory interface {
New(name string) (Queue, error)
NewProducer(name string) (Producer, error)
NewConsumer(name string) (Consumer, error)
}
type FactoryFunc func(name string) (Queue, error)
func (f FactoryFunc) New(name string) (Queue, error) {
return f(name)
}
func (f FactoryFunc) NewProducer(name string) (Producer, error) {
return f.New(name)
}
func (f FactoryFunc) NewConsumer(name string) (Consumer, error) {
return f.New(name)
}
var queueFactories = make(map[string]Factory)
func Register(tp string, f Factory) {
if _, ok := queueFactories[tp]; ok {
panic("duplicate queue factory " + tp)
}
queueFactories[tp] = f
}
func NewFactory(tp string) Factory {
return queueFactories[tp]
}
<|start_filename|>application/api/api.go<|end_filename|>
package api
import (
"net/http"
"github.com/letian0805/seckill/domain/event"
"github.com/letian0805/seckill/domain/stock"
"github.com/letian0805/seckill/domain/shop"
"github.com/letian0805/seckill/domain/user"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/sirupsen/logrus"
"github.com/gin-gonic/gin"
)
type Event struct{}
type Shop struct{}
func (e *Event) List(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: event.TestData,
Msg: "ok",
}
status := http.StatusOK
//logrus.Info("event list")
ctx.JSON(status, resp)
}
func (e *Event) Info(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("event info")
ctx.JSON(status, resp)
}
func (e *Event) Subscribe(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("event subscribe")
ctx.JSON(status, resp)
}
func (s *Shop) AddCart(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
params := struct {
GoodsID string `json:"goods_id"`
EventID string `json:"event_id"`
}{}
var userInfo *user.Info
if v, ok := ctx.Get("userInfo"); ok {
userInfo, _ = v.(*user.Info)
}
err := ctx.BindJSON(¶ms)
if err != nil || params.EventID == "" || params.GoodsID == "" || userInfo == nil {
resp.Msg = "bad request"
status = http.StatusBadRequest
ctx.JSON(status, resp)
return
}
logrus.Info(params)
st, _ := stock.NewMemStock(params.EventID, params.GoodsID)
if s, _ := st.Sub(userInfo.UID); s < 0 {
resp.Code = shop.ErrNoStock
resp.Msg = "no stock"
ctx.JSON(http.StatusOK, resp)
return
}
conn, w, err1 := ctx.Writer.Hijack()
if err1 != nil {
resp.Msg = "bad request"
status = http.StatusBadRequest
ctx.JSON(status, resp)
return
}
logrus.Info("shop add cart")
shopCtx := &shop.Context{
Request: ctx.Request,
Conn: conn,
Writer: w,
GoodsID: params.GoodsID,
EventID: params.EventID,
UID: userInfo.UID,
}
shop.Handle(shopCtx)
}
type User struct{}
func (u User) Login(ctx *gin.Context) {
var (
uid string
passwd string
ok bool
)
if uid, ok = ctx.GetPostForm("uid"); !ok {
utils.Abort(ctx, http.StatusUnauthorized, "login failed")
return
}
if passwd, ok = ctx.GetPostForm("password"); !ok {
utils.Abort(ctx, http.StatusUnauthorized, "login failed")
return
}
info, token := user.Login(uid, passwd)
if info != nil {
ctx.Header(user.TokenHeader, user.TokenPrefix+token)
utils.ResponseJSON(ctx, http.StatusOK, "success", nil)
} else {
utils.Abort(ctx, http.StatusUnauthorized, "login failed")
}
}
<|start_filename|>infrastructure/utils/addr.go<|end_filename|>
package utils
import (
"fmt"
"strings"
"github.com/micro/go-micro/util/addr"
)
func Extract(bind string) (string, error) {
var (
ip string
port string
err error
)
parts := strings.Split(bind, ":")
if len(parts) == 2 {
ip = parts[0]
port = parts[1]
} else {
ip = "0.0.0.0"
port = parts[0]
}
ip, err = addr.Extract(ip)
if err != nil {
return "", err
}
return fmt.Sprintf("%s:%s", ip, port), err
}
<|start_filename|>infrastructure/utils/blacklist.go<|end_filename|>
package utils
import (
"bufio"
"os"
"sync"
"github.com/sirupsen/logrus"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
var blacklist struct {
sync.RWMutex
data map[string]struct{}
}
func init() {
blacklist.data = make(map[string]struct{})
}
func WatchBlacklist() {
v := viper.New()
v.SetConfigFile(viper.GetString("blacklist.filePath"))
v.OnConfigChange(onBlacklistChange)
go v.WatchConfig()
}
func onBlacklistChange(in fsnotify.Event) {
const writeOrCreateMask = fsnotify.Write | fsnotify.Create
if in.Op&writeOrCreateMask != 0 {
updateBlacklist()
}
}
func updateBlacklist() {
filePath := viper.GetString("blacklist.filePath")
fp, err := os.Open(filePath)
if err != nil {
logrus.Error(err)
return
}
defer fp.Close()
data := make(map[string]struct{})
f := bufio.NewReader(fp)
for {
line, _, err := f.ReadLine()
if err != nil {
break
}
data[string(line)] = struct{}{}
}
blacklist.Lock()
blacklist.data = data
blacklist.Unlock()
}
func InBlacklist(uid string) bool {
blacklist.RLock()
_, ok := blacklist.data[uid]
blacklist.RUnlock()
return ok
}
<|start_filename|>infrastructure/pool/pool.go<|end_filename|>
package pool
import (
"io"
)
type Pool interface {
Get() (io.Closer, error)
Put(c io.Closer)
Close() error
}
type poolError string
func (e poolError) Error() string {
return string(e)
}
const Failed = poolError("failed to get connection from pool")
<|start_filename|>infrastructure/logger/log.go<|end_filename|>
package logger
import (
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
func InitLogger() {
logLevel := strings.ToLower(viper.GetString("global.logLevel"))
if logLevel == "debug" {
gin.SetMode(gin.DebugMode)
logrus.SetLevel(logrus.DebugLevel)
} else if logLevel == "info" {
gin.SetMode(gin.ReleaseMode)
logrus.SetLevel(logrus.InfoLevel)
} else {
gin.SetMode(gin.ReleaseMode)
logrus.SetLevel(logrus.ErrorLevel)
}
formatter := &logrus.JSONFormatter{
TimestampFormat: time.RFC3339,
DisableTimestamp: false,
FieldMap: logrus.FieldMap{
logrus.FieldKeyTime: "@timestamp",
logrus.FieldKeyFile: "file",
logrus.FieldKeyLevel: "level",
},
PrettyPrint: false,
}
logrus.SetFormatter(formatter)
}
<|start_filename|>interfaces/api/middlewares/auth.go<|end_filename|>
package middlewares
import (
"net/http"
"strings"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/letian0805/seckill/domain/user"
"github.com/gin-gonic/gin"
)
func NewAuthMiddleware(redirect bool) gin.HandlerFunc {
return func(ctx *gin.Context) {
var info *user.Info
token := ctx.Request.Header.Get(user.TokenHeader)
if token != "" && strings.Contains(token, user.TokenPrefix) {
token = strings.Trim(token, user.TokenPrefix)
token = strings.TrimSpace(token)
info = user.Auth(token)
}
if info != nil {
ctx.Set("UserInfo", info)
} else if redirect {
utils.Abort(ctx, http.StatusUnauthorized, "need login")
return
}
ctx.Next()
}
}
<|start_filename|>infrastructure/stores/mysql/mysql.go<|end_filename|>
package mysql
import (
"fmt"
"github.com/sirupsen/logrus"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
"github.com/spf13/viper"
)
var db *xorm.Engine
func Init() error {
var err error
var cfgs = []string{"username", "password", "address", "databases"}
var cfgVals = make([]interface{}, 0)
for _, cfg := range cfgs {
cfgVals = append(cfgVals, viper.GetString("mysql."+cfg))
}
db, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s", cfgVals...))
if db != nil {
logrus.Info(db.Query("show tables"))
}
return err
}
<|start_filename|>domain/shop/shop.go<|end_filename|>
package shop
import (
"bufio"
"bytes"
"encoding/json"
"io/ioutil"
"net"
"net/http"
"time"
"github.com/letian0805/seckill/infrastructure/pool"
"github.com/letian0805/seckill/domain/stock"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/sirupsen/logrus"
"github.com/letian0805/seckill/infrastructure/mq"
)
const (
OK = 0
ErrNoStock = 1001
ErrRedis = 1002
ErrTimeout = 1003
requestTimeout = 60
)
type Context struct {
Request *http.Request
Conn net.Conn
Writer *bufio.ReadWriter
GoodsID string
EventID string
UID string
}
var queue mq.Queue
func Init() {
queueFactory := mq.NewFactory("memory")
if queueFactory == nil {
panic("no memory queue factory")
}
queue, _ = queueFactory.New("shop")
go func() {
for {
task, err := queue.Consume()
if err != nil {
logrus.Error(err)
break
}
task.Do()
}
}()
}
func Handle(ctx *Context) {
start := time.Now().Unix()
t := func() {
data := &utils.Response{
Code: OK,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
now := time.Now().Unix()
if now-start > requestTimeout {
data.Msg = "request timeout"
data.Code = ErrTimeout
} else {
// 扣减 Redis 库存
st, _ := stock.NewRedisStock(ctx.EventID, ctx.GoodsID)
if s, err := st.Sub(ctx.UID); err != nil {
data.Msg = err.Error()
data.Code = ErrRedis
} else if s < 0 {
data.Msg = "no stock"
data.Code = ErrNoStock
}
}
// 此处实现操作购物车的逻辑
body, _ := json.Marshal(data)
resp := &http.Response{
Proto: ctx.Request.Proto,
ProtoMinor: ctx.Request.ProtoMinor,
ProtoMajor: ctx.Request.ProtoMajor,
Header: make(http.Header),
ContentLength: int64(len(body)),
Body: ioutil.NopCloser(bytes.NewReader(body)),
StatusCode: status,
Close: false,
}
resp.Header.Set("Content-Type", "application/json")
resp.Write(ctx.Writer)
ctx.Writer.Flush()
ctx.Conn.Close()
}
queue.Produce(pool.TaskFunc(t))
}
<|start_filename|>infrastructure/utils/rate_limiter.go<|end_filename|>
package utils
import (
"errors"
"sync"
"sync/atomic"
"time"
"github.com/letian0805/seckill/infrastructure/pool"
)
type RateLimiter interface {
Push(t pool.Task) bool
Pop() (pool.Task, bool)
Close() error
}
type fanInOut struct {
sync.RWMutex
queueIn chan pool.Task
queueOut chan pool.Task
timer time.Timer
lastTime int64
rate int64
duration time.Duration
closed int64
mode int
}
const (
minRate = 1
minSize = 10
FanIn = 1 << 0
FanOut = 1 << 1
)
func NewRateLimiter(size int, rate int64, mode int) (RateLimiter, error) {
modeMask := FanIn | FanOut
if mode > modeMask || modeMask&mode == 0 {
return nil, errors.New("wrong flag")
}
if rate < minRate {
rate = minRate
}
if size < minSize {
size = minSize
}
f := &fanInOut{
timer: time.Timer{},
lastTime: 0,
rate: rate,
duration: time.Second / time.Duration(rate),
closed: 0,
mode: mode,
}
if FanIn&mode != 0 {
f.queueIn = make(chan pool.Task, size)
}
if FanOut&mode != 0 {
f.queueOut = make(chan pool.Task, size)
}
if mode == modeMask {
go f.exchange()
}
return f, nil
}
func (f *fanInOut) Push(t pool.Task) bool {
if atomic.LoadInt64(&f.closed) == 1 {
return false
}
f.RLock()
defer f.RUnlock()
if atomic.LoadInt64(&f.closed) == 1 {
return false
}
if FanIn&f.mode != 0 {
select {
case f.queueIn <- t:
return true
default:
return false
}
} else {
f.sleep()
f.queueOut <- t
return true
}
}
func (f *fanInOut) Pop() (pool.Task, bool) {
if FanOut&f.mode != 0 {
t, ok := <-f.queueOut
return t, ok
} else {
f.sleep()
t, ok := <-f.queueIn
return t, ok
}
}
func (f *fanInOut) sleep() {
now := time.Now().UnixNano()
delta := f.duration - time.Duration(now-atomic.LoadInt64(&f.lastTime))
if delta > time.Millisecond {
time.Sleep(delta)
}
atomic.StoreInt64(&f.lastTime, now)
}
func (f *fanInOut) exchange() {
for t := range f.queueIn {
f.sleep()
f.queueOut <- t
}
close(f.queueOut)
}
func (f *fanInOut) Close() error {
f.Lock()
defer f.Unlock()
if atomic.CompareAndSwapInt64(&f.closed, 0, 1) {
if f.mode&FanIn != 0 {
close(f.queueIn)
} else if f.mode == FanOut {
close(f.queueOut)
}
}
return nil
}
<|start_filename|>application/admin/topic.go<|end_filename|>
package admin
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/sirupsen/logrus"
)
type Topic struct{}
func (t *Topic) Post(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("topic post")
ctx.JSON(status, resp)
}
func (t *Topic) Get(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("topic get")
ctx.JSON(status, resp)
}
func (t *Topic) Put(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("topic put")
ctx.JSON(status, resp)
}
func (t *Topic) Delete(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("topic delete")
ctx.JSON(status, resp)
}
func (t *Topic) Status(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("topic status")
ctx.JSON(status, resp)
}
<|start_filename|>application/admin/goods.go<|end_filename|>
package admin
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/sirupsen/logrus"
)
type Goods struct{}
func (t *Goods) Post(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("goods post")
ctx.JSON(status, resp)
}
func (t *Goods) Get(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("goods get")
ctx.JSON(status, resp)
}
func (t *Goods) Put(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("goods put")
ctx.JSON(status, resp)
}
func (t *Goods) Delete(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("goods delete")
ctx.JSON(status, resp)
}
<|start_filename|>Makefile<|end_filename|>
all: build
proto: application/api/rpc/event.proto
protoc --go_out=plugins=grpc:./ application/api/rpc/event.proto
build:
go build -o bin/seckill main.go
clean:
rm bin/seckill
runApi:
ulimit -n 1000000
./bin/seckill api -c ./config/seckill.toml
ab:
ulimit -n 1000000
ab -n 1000000 -c 50 http://localhost:8080/event/list
ab-k:
ulimit -n 1000000
ab -n 1000000 -c 50 -k http://localhost:8080/event/list
bench:
ulimit -n 1000000
./bin/seckill bench -C 16 -r 1000000 -u http://localhost:8080/event/list
bench-k:
ulimit -n 1000000
./bin/seckill bench -C 16 -k -r 1000000 -u http://localhost:8080/event/list
test:
go test -bench=. -cover ./...
.PHONY: clean build all
<|start_filename|>interfaces/api/middlewares/circuit_break.go<|end_filename|>
package middlewares
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/letian0805/seckill/infrastructure/utils"
)
func NewCircuitBreakMiddleware(cb *utils.CircuitBreaker) gin.HandlerFunc {
return func(c *gin.Context) {
ok := cb.Allow(func() bool {
c.Next()
if c.Writer.Status() >= http.StatusInternalServerError {
return false
}
return true
})
if !ok {
c.AbortWithStatus(http.StatusServiceUnavailable)
}
}
}
<|start_filename|>interfaces/api/middlewares/blacklist.go<|end_filename|>
package middlewares
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/letian0805/seckill/domain/user"
"github.com/letian0805/seckill/infrastructure/utils"
)
func Blacklist(ctx *gin.Context) {
data, _ := ctx.Get("UserInfo")
info, ok := data.(*user.Info)
if !ok {
utils.Abort(ctx, http.StatusUnauthorized, "need login")
return
}
if utils.InBlacklist(info.UID) {
utils.Abort(ctx, http.StatusForbidden, "blocked")
return
}
ctx.Next()
}
<|start_filename|>infrastructure/pool/worker_test.go<|end_filename|>
package pool_test
import (
"runtime"
"sync"
"testing"
"github.com/letian0805/seckill/infrastructure/pool"
)
type testTask struct {
wg *sync.WaitGroup
ch chan struct{}
m bool
p int
}
func (t *testTask) Do() {
if t.m {
<-t.ch
}
t.wg.Done()
}
func newTestTask(wg *sync.WaitGroup) *testTask {
return &testTask{
wg: wg,
}
}
func newMemTask(ch chan struct{}, wg *sync.WaitGroup) *testTask {
return &testTask{
wg: wg,
ch: ch,
m: true,
}
}
func (t *testTask) Priority() int {
return t.p
}
func newPriorityTask(p int, wg *sync.WaitGroup) *testTask {
return &testTask{
wg: wg,
p: p,
}
}
func runTest(b *testing.B, f func(i int, wg *sync.WaitGroup)) *sync.WaitGroup {
//初始化
runtime.GC()
b.ReportAllocs()
b.ResetTimer()
var memStats1 runtime.MemStats
runtime.ReadMemStats(&memStats1)
wg := &sync.WaitGroup{}
wg.Add(b.N)
//执行测试
for i := 0; i < b.N; i++ {
f(i, wg)
}
//输出内存信息
var memStats2 runtime.MemStats
runtime.ReadMemStats(&memStats2)
b.ReportMetric(float64(memStats2.HeapInuse-memStats1.HeapInuse)/(1024*1024), "heap(MB)")
b.ReportMetric(float64(memStats2.StackInuse-memStats1.StackInuse)/(1024*1024), "stack(MB)")
return wg
}
func BenchmarkNoGoroutine(b *testing.B) {
wg := runTest(b, func(i int, wg *sync.WaitGroup) {
t := newTestTask(wg)
t.Do()
})
wg.Wait()
b.StopTimer()
}
const (
priority = 2
number = 2 * priority
)
func BenchmarkWorker(b *testing.B) {
w := pool.NewWorker(number, b.N)
wg := runTest(b, func(i int, wg *sync.WaitGroup) {
w.Push(newTestTask(wg))
})
w.Close()
wg.Wait()
b.StopTimer()
}
func BenchmarkPriorityWorker(b *testing.B) {
w := pool.NewPriorityWorker(number, b.N, priority)
wg := runTest(b, func(i int, wg *sync.WaitGroup) {
w.Push(newPriorityTask(i%priority, wg))
})
w.Close()
wg.Wait()
b.StopTimer()
}
func BenchmarkWorkerMem(b *testing.B) {
w := pool.NewWorker(number, b.N)
ch := make(chan struct{})
wg := runTest(b, func(i int, wg *sync.WaitGroup) {
w.Push(newMemTask(ch, wg))
})
close(ch)
w.Close()
wg.Wait()
b.StopTimer()
}
func BenchmarkGoroutineCPU(b *testing.B) {
wg := runTest(b, func(i int, wg *sync.WaitGroup) {
go func() {
t := newTestTask(wg)
t.Do()
}()
})
wg.Wait()
b.StopTimer()
}
func BenchmarkGoroutineMem(b *testing.B) {
ch := make(chan struct{})
wg := runTest(b, func(i int, wg *sync.WaitGroup) {
go func() {
t := newMemTask(ch, wg)
t.Do()
}()
})
close(ch)
wg.Wait()
b.StopTimer()
}
<|start_filename|>interfaces/api/middlewares/middleware_test.go<|end_filename|>
package middlewares_test
import (
"fmt"
"net/http"
"testing"
)
type Middleware http.HandlerFunc
func (m Middleware) Add(f http.HandlerFunc) Middleware {
return func(w http.ResponseWriter, r *http.Request) {
f(w, r)
m(w, r)
}
}
func handlerA(w http.ResponseWriter, r *http.Request) {
fmt.Println("A")
}
func handlerB(w http.ResponseWriter, r *http.Request) {
fmt.Println("B")
}
func handlerC(w http.ResponseWriter, r *http.Request) {
fmt.Println("C")
}
func TestMiddleware(t *testing.T) {
m := Middleware(handlerA).Add(handlerB).Add(handlerC)
var w http.ResponseWriter
var r *http.Request
m(w, r)
}
type MiddlewareGroup struct {
group []Middleware
}
func NewMiddlewareGroup() *MiddlewareGroup {
return &MiddlewareGroup{
group: make([]Middleware, 0),
}
}
func (mg *MiddlewareGroup) Add(m ...Middleware) *MiddlewareGroup {
mg.group = append(mg.group, m...)
return mg
}
func (mg *MiddlewareGroup) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, m := range mg.group {
m(w, r)
}
}
func TestMiddlewareGroup(t *testing.T) {
mg := NewMiddlewareGroup()
mg.Add(handlerA, handlerB, handlerC)
var w http.ResponseWriter
var r *http.Request
mg.ServeHTTP(w, r)
}
<|start_filename|>cmd/admin.go<|end_filename|>
/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"os"
"os/signal"
"syscall"
"github.com/letian0805/seckill/interfaces/admin"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
// adminCmd represents the admin command
var adminCmd = &cobra.Command{
Use: "admin",
Short: "Seckill admin server.",
Long: `Seckill admin server.`,
Run: func(cmd *cobra.Command, args []string) {
onExit := make(chan error)
go func() {
if err := admin.Run(); err != nil {
logrus.Error(err)
onExit <- err
}
close(onExit)
}()
onSignal := make(chan os.Signal)
signal.Notify(onSignal, syscall.SIGINT, syscall.SIGTERM)
select {
case sig := <-onSignal:
logrus.Info("exit by signal ", sig)
admin.Exit()
case err := <-onExit:
logrus.Info("exit by error ", err)
}
},
}
func init() {
rootCmd.AddCommand(adminCmd)
}
<|start_filename|>interfaces/rpc/rpc.go<|end_filename|>
package rpc
import (
"sync"
"github.com/letian0805/seckill/infrastructure/cluster"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/letian0805/seckill/application/api"
"github.com/letian0805/seckill/application/api/rpc"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/reflection"
"github.com/spf13/viper"
"google.golang.org/grpc"
)
var (
grpcS *grpc.Server
once = &sync.Once{}
node *cluster.Node
)
func Run() error {
bind := viper.GetString("api.rpc")
logrus.Info("run RPC server on ", bind)
lis, err := utils.Listen("tcp", bind)
if err != nil {
return err
}
grpcS = grpc.NewServer()
eventRPC := &api.EventRPCServer{}
rpc.RegisterEventRPCServer(grpcS, eventRPC)
// 支持 gRPC reflection,方便调试
reflection.Register(grpcS)
//初始化集群
cluster.Init("seckill")
var addr string
if addr, err = utils.Extract(bind); err == nil {
//注册节点信息
version := viper.GetString("api.version")
if version == "" {
version = "v0.1"
}
once.Do(func() {
node = &cluster.Node{
Addr: addr,
Version: version,
Proto: "gRPC",
}
err = cluster.Register(node, 6)
})
}
if err != nil {
return err
}
return grpcS.Serve(lis)
}
func Exit() {
cluster.Deregister(node)
grpcS.GracefulStop()
logrus.Info("rpc server exit")
}
<|start_filename|>infrastructure/utils/listen.go<|end_filename|>
package utils
import (
"context"
"net"
"syscall"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
func Listen(network string, addr string) (net.Listener, error) {
lisCfg := &net.ListenConfig{
Control: func(network, address string, c syscall.RawConn) error {
var err error
err1 := c.Control(func(fd uintptr) {
err = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1)
if err != nil {
logrus.Error("set socket option failed ", err)
}
})
if err1 != nil {
logrus.Error("control listener failed ", err1)
err = err1
}
return err
},
}
return lisCfg.Listen(context.Background(), "tcp", addr)
}
<|start_filename|>cmd/bench.go<|end_filename|>
/*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"runtime"
"sync"
"sync/atomic"
"time"
etcdv3 "github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/letian0805/seckill/infrastructure/stores/etcd"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
type Task struct {
ID int `json:"id"`
Servers []string `json:"servers"`
Path string `json:"path"`
Method string `json:"method"`
Data string `json:"data"`
ContentType string `json:"content_type"`
Concurrency int `json:"concurrency"`
Number int `json:"number"`
Duration int `json:"duration"`
Status int32 `json:"status"`
}
type TaskManager struct {
sync.Mutex
task Task
}
func (tm *TaskManager) onConfigChange(task Task) {
if atomic.LoadInt32(&tm.task.Status) == 1 {
atomic.StoreInt32(&tm.task.Status, 2)
}
for atomic.LoadInt32(&tm.task.Status) == 2 {
time.Sleep(time.Second)
}
tm.Lock()
tm.task = task
tm.Unlock()
if task.Status == 1 {
tm.task.doBench()
}
}
// benchCmd represents the bench command
var benchCmd = &cobra.Command{
Use: "bench",
Short: "Seckill benchmark tool.",
Long: `Seckill benchmark tool.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("bench called")
logrus.SetLevel(logrus.DebugLevel)
logrus.Info("requests ", requests, " concurrency ", concurrency, " url ", url)
doBench()
// TODO: 还需要加上初始化 etcd 的代码,待完善
// watchTaskConfig((&TaskManager{}).onConfigChange)
},
}
var (
requests int32
concurrency int
url string
keepalive bool
)
func init() {
rootCmd.AddCommand(benchCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
benchCmd.PersistentFlags().Int32VarP(&requests, "requests", "r", 10000, "requests")
benchCmd.PersistentFlags().IntVarP(&concurrency, "concurrency", "C", 50, "concurrency")
benchCmd.PersistentFlags().StringVarP(&url, "url", "u", "", "url")
benchCmd.PersistentFlags().BoolVarP(&keepalive, "keepalive", "k", false, "k")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// benchCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func watchTaskConfig(callback func(cfg Task)) error {
var err error
cli := etcd.GetClient()
key := "/bench/task/config"
update := func(kv *mvccpb.KeyValue) (bool, error) {
if string(kv.Key) == key {
var tmpConfig Task
err = json.Unmarshal(kv.Value, &tmpConfig)
if err != nil {
logrus.Error("update bench config failed, error:", err)
return false, err
}
logrus.Info("update bench config ", tmpConfig)
callback(tmpConfig)
return true, nil
}
return false, nil
}
watchCh := cli.Watch(context.Background(), key)
for resp := range watchCh {
for _, evt := range resp.Events {
if evt.Type == etcdv3.EventTypePut {
if ok, err := update(evt.Kv); ok {
break
} else if err != nil {
break
}
}
}
}
return nil
}
func (t *Task) doBench() {
wg := &sync.WaitGroup{}
wg.Add(t.Concurrency)
for i := 0; i < t.Concurrency; i++ {
go func() {
for atomic.LoadInt32(&t.Status) == 1 {
// do test
}
atomic.StoreInt32(&t.Status, 3)
wg.Done()
}()
}
wg.Wait()
}
func doBench() {
runtime.GOMAXPROCS(4)
wg := &sync.WaitGroup{}
startCh := make(chan struct{})
success := int32(0)
failed := int32(0)
reqs := requests
wg.Add(concurrency)
wg1 := &sync.WaitGroup{}
wg1.Add(concurrency)
for i := 0; i < concurrency; i++ {
go func() {
cli := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{},
},
Timeout: 10 * time.Second,
}
wg1.Done()
<-startCh
for atomic.AddInt32(&reqs, -1) >= 0 {
if !keepalive {
cli = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{},
DisableKeepAlives: true,
},
Timeout: 10 * time.Second,
}
}
resp, err := cli.Get(url)
if err != nil || resp.StatusCode > 404 {
logrus.Error(err)
atomic.AddInt32(&failed, 1)
} else {
atomic.AddInt32(&success, 1)
}
if resp != nil {
ioutil.ReadAll(resp.Body)
resp.Body.Close()
}
if !keepalive {
cli.CloseIdleConnections()
}
}
wg.Done()
}()
}
wg1.Wait()
close(startCh)
start := time.Now().Unix()
wg.Wait()
end := time.Now().Unix()
fmt.Printf("total: %d, cost: %d, success: %d, failed: %d, qps: %d\n", requests, end-start, success, failed, requests/int32(end-start))
}
<|start_filename|>infrastructure/utils/response.go<|end_filename|>
package utils
import "github.com/gin-gonic/gin"
type Response struct {
Code int `json:"code"` // 业务错误码
Data interface{} `json:"data"` // 数据
Msg string `json:"msg"` // 提示信息
}
func Abort(ctx *gin.Context, code int, msg string) {
ctx.AbortWithStatusJSON(code, &Response{
Code: code,
Msg: msg,
})
}
func ResponseJSON(ctx *gin.Context, code int, msg string, data interface{}) {
ctx.JSON(code, &Response{
Code: code,
Data: data,
Msg: msg,
})
}
<|start_filename|>application/api/rpc.go<|end_filename|>
package api
import (
"context"
"github.com/sirupsen/logrus"
"github.com/letian0805/seckill/application/api/rpc"
)
type EventRPCServer struct {
}
func (s *EventRPCServer) EventOnline(ctx context.Context, evt *rpc.Event) (*rpc.Response, error) {
logrus.Info("event online ", evt)
resp := &rpc.Response{}
return resp, nil
}
func (s *EventRPCServer) EventOffline(ctx context.Context, evt *rpc.Event) (*rpc.Response, error) {
logrus.Info("event offline ", evt)
resp := &rpc.Response{}
return resp, nil
}
func (s *EventRPCServer) TopicOnline(ctx context.Context, t *rpc.Topic) (*rpc.Response, error) {
logrus.Info("topic online ", t)
resp := &rpc.Response{}
return resp, nil
}
func (s *EventRPCServer) TopicOffline(ctx context.Context, t *rpc.Topic) (*rpc.Response, error) {
logrus.Info("topic offline ", t)
resp := &rpc.Response{}
return resp, nil
}
<|start_filename|>domain/user/auth_test.go<|end_filename|>
package user
import "testing"
func TestAuth(t *testing.T) {
_, token := Login("<PASSWORD>", "abcd")
t.Log(token)
}
<|start_filename|>infrastructure/pool/ringbuffer.go<|end_filename|>
package pool
import (
"sync/atomic"
"unsafe"
)
type RingBuffer struct {
count int32
size int32
head int32
tail int32
buf []unsafe.Pointer
}
func NewRingBuffer(size int32) *RingBuffer {
return &RingBuffer{
size: size,
head: 0,
tail: 0,
buf: make([]unsafe.Pointer, size),
}
}
// Get方法从buf中取出对象
func (r *RingBuffer) Get() interface{} {
// 在高并发开始的时候,队列容易空,直接判断空性能最优
if atomic.LoadInt32(&r.count) <= 0 {
return nil
}
// 当扣减数量后没有超,就从队列里取出对象
if atomic.AddInt32(&r.count, -1) >= 0 {
idx := (atomic.AddInt32(&r.head, 1) - 1) % r.size
if obj := atomic.LoadPointer(&r.buf[idx]); obj != unsafe.Pointer(nil) {
o := *(*interface{})(obj)
atomic.StorePointer(&r.buf[idx], nil)
return o
}
} else {
// 当减数量超了,再加回去
atomic.AddInt32(&r.count, 1)
}
return nil
}
// Put方法将对象放回到buf中。如果buf满了,返回false
func (r *RingBuffer) Put(obj interface{}) bool {
// 在高并发结束的时候,队列容易满,直接判满性能最优
if atomic.LoadInt32(&r.count) >= r.size {
return false
}
// 当增加数量后没有超,就将对象放到队列里
if atomic.AddInt32(&r.count, 1) <= r.size {
idx := (atomic.AddInt32(&r.tail, 1) - 1) % r.size
atomic.StorePointer(&r.buf[idx], unsafe.Pointer(&obj))
return true
}
// 当加的数量超了,再减回去
atomic.AddInt32(&r.count, -1)
return false
}
<|start_filename|>infrastructure/pool/worker.go<|end_filename|>
package pool
import (
"sync"
"sync/atomic"
"github.com/sirupsen/logrus"
)
type Worker interface {
Push(t Task) bool
Close() error
}
type Task interface {
Do()
}
type TaskFunc func()
func (tf TaskFunc) Do() {
tf()
}
type worker struct {
number int
size int
closed int32
taskPool chan Task
wg sync.WaitGroup
}
const (
minBufferSize = 10
minNumber = 2
)
func NewWorker(number int, size int) Worker {
if number < minNumber {
number = minNumber
}
if size < minBufferSize {
size = minNumber
}
w := &worker{
number: number,
size: size,
taskPool: make(chan Task, size),
}
w.wg.Add(number)
for i := 0; i < number; i++ {
go w.run()
}
return w
}
func (w *worker) run() {
defer w.wg.Done()
for task := range w.taskPool {
w.process(task)
}
}
func (w *worker) process(t Task) {
defer func() {
if err := recover(); err != nil {
logrus.Error(err)
}
}()
t.Do()
}
func (w *worker) Push(t Task) bool {
if w.isClosed() {
return false
}
w.taskPool <- t
return true
}
func (w *worker) Close() error {
if !w.isClosed() && atomic.CompareAndSwapInt32(&w.closed, 0, 1) {
close(w.taskPool)
w.wg.Wait()
}
return nil
}
func (w *worker) isClosed() bool {
return atomic.LoadInt32(&w.closed) == 1
}
type PriorityTask interface {
Priority() int
Do()
}
type priorityWorker struct {
priorities int
number int
size int
closed int32
workers []Worker
}
func NewPriorityWorker(number, size, priorities int) Worker {
if priorities < minNumber {
priorities = minNumber
}
number = (number - 1 + priorities) / priorities
if number < minNumber {
number = minNumber
}
size = (size - 1 + priorities) / priorities
if size < minBufferSize {
size = minBufferSize
}
w := &priorityWorker{
priorities: priorities,
number: number,
size: size,
closed: 0,
workers: make([]Worker, priorities),
}
for i := 0; i < priorities; i++ {
w.workers[i] = NewWorker(number, size)
}
return w
}
func (pw *priorityWorker) Push(t Task) bool {
if pw.isClosed() {
return false
}
if pt, ok := t.(PriorityTask); !ok {
return pw.workers[pw.priorities-1].Push(t)
} else {
p := pt.Priority()
if p < 0 {
p = 0
} else if p >= pw.priorities {
p = pw.priorities - 1
}
return pw.workers[p].Push(t)
}
}
func (pw *priorityWorker) Close() error {
if !pw.isClosed() && atomic.CompareAndSwapInt32(&pw.closed, 0, 1) {
for _, w := range pw.workers {
w.Close()
}
return nil
}
return nil
}
func (pw *priorityWorker) isClosed() bool {
return atomic.LoadInt32(&pw.closed) == 1
}
<|start_filename|>application/admin/event.go<|end_filename|>
package admin
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/sirupsen/logrus"
)
type Event struct{}
func (t *Event) Post(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("event post")
ctx.JSON(status, resp)
}
func (t *Event) Get(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("event get")
ctx.JSON(status, resp)
}
func (t *Event) Put(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("event put")
ctx.JSON(status, resp)
}
func (t *Event) Delete(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("event delete")
ctx.JSON(status, resp)
}
func (t *Event) Status(ctx *gin.Context) {
resp := &utils.Response{
Code: 0,
Data: nil,
Msg: "ok",
}
status := http.StatusOK
logrus.Info("event status")
ctx.JSON(status, resp)
}
<|start_filename|>domain/event/cache.go<|end_filename|>
package event
import (
"sync"
"github.com/letian0805/seckill/infrastructure/stores"
)
type Cache struct {
cache stores.ObjCache
}
var cache *Cache
var once = &sync.Once{}
func InitCache() error {
var err error
once.Do(func() {
cache = &Cache{
cache: stores.NewObjCache(),
}
err = cache.load()
})
return err
}
func GetCache() *Cache {
return cache
}
func (c *Cache) load() error {
return nil
}
func (c *Cache) GetList() *Topic {
return nil
}
func (c *Cache) getCurrentEvent() *Event {
return nil
}
func (c *Cache) GetEventInfo(goodsID int64) *Info {
return nil
}
<|start_filename|>infrastructure/pool/chan_pool.go<|end_filename|>
package pool
import (
"io"
)
type chanPool struct {
name string
size int
ch chan io.Closer
newFunc func() (io.Closer, error)
}
func NewChanPool(name string, size int, newFunc func() (io.Closer, error)) Pool {
return &chanPool{
name: name,
size: size,
ch: make(chan io.Closer, size),
newFunc: newFunc,
}
}
func (p *chanPool) Get() (io.Closer, error) {
select {
case c := <-p.ch:
return c, nil
default:
if p.newFunc != nil {
return p.newFunc()
}
}
return nil, Failed
}
func (p *chanPool) Put(c io.Closer) {
if c == nil {
return
}
select {
case p.ch <- c:
break
default:
_ = c.Close()
}
}
func (p *chanPool) Close() error {
close(p.ch)
p.ch = nil
return nil
}
<|start_filename|>infrastructure/pool/ringbuffer_pool.go<|end_filename|>
package pool
import (
"io"
"sync/atomic"
)
type ringBufferPool struct {
closed int32
name string
rb *RingBuffer
newFunc func() (io.Closer, error)
}
func NewRingBufferPool(name string, size int, newFunc func() (io.Closer, error)) Pool {
return &ringBufferPool{
name: name,
rb: NewRingBuffer(int32(size)),
newFunc: newFunc,
}
}
func (p *ringBufferPool) Get() (io.Closer, error) {
var err error
var c io.Closer
if atomic.LoadInt32(&p.closed) != 0 {
return nil, Failed
}
obj := p.rb.Get()
if c, _ = obj.(io.Closer); c != io.Closer(nil) {
return c, err
} else if p.newFunc != nil {
return p.newFunc()
}
return nil, Failed
}
func (p *ringBufferPool) Put(c io.Closer) {
if c == io.Closer(nil) {
return
}
if atomic.LoadInt32(&p.closed) != 0 || !p.rb.Put(c) {
_ = c.Close()
}
}
func (p *ringBufferPool) Close() error {
if !atomic.CompareAndSwapInt32(&p.closed, 0, 1) {
return nil
}
for obj := p.rb.Get(); obj != nil; obj = p.rb.Get() {
if c, ok := obj.(io.Closer); ok {
_ = c.Close()
}
}
return nil
}
<|start_filename|>interfaces/admin/admin.go<|end_filename|>
package admin
import (
"encoding/json"
"net"
"github.com/letian0805/seckill/infrastructure/cluster"
"github.com/sirupsen/logrus"
"github.com/gin-gonic/gin"
"github.com/letian0805/seckill/infrastructure/utils"
"github.com/spf13/viper"
)
var lis net.Listener
func Run() error {
var err error
bind := viper.GetString("admin.bind")
logrus.Info("run admin server on ", bind)
lis, err = utils.Listen("tcp", bind)
if err != nil {
return err
}
g := gin.New()
// 更新程序,给老版本发送信号
go utils.UpdateProc("admin")
// 初始化路由
initRouters(g)
cluster.Init("seckill")
if nodes, err := cluster.Discover(); err == nil {
log, _ := json.Marshal(nodes)
logrus.Info("discover nodes ", string(log))
} else {
logrus.Error("discover nodes error:", err)
}
// 运行服务
return g.RunListener(lis)
}
func Exit() {
lis.Close()
// TODO: 等待请求处理完
// time.Sleep(10 * time.Second)
logrus.Info("admin server exit")
}
<|start_filename|>infrastructure/cluster/cluster.go<|end_filename|>
package cluster
import (
"context"
"encoding/json"
"fmt"
"strings"
"sync"
"time"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
etcdv3 "github.com/coreos/etcd/clientv3"
"github.com/letian0805/seckill/infrastructure/stores/etcd"
"github.com/sirupsen/logrus"
)
type Config struct {
LogLevel string `json:"logLevel"`
RateLimit struct {
Middle int `json:"middle"`
Low int `json:"low"`
} `json:"rateLimit"`
CircuitBreaker struct {
Cpu int `json:"cpu"`
Latency int `json:"latency"`
} `json:"circuitBreaker"`
}
var configLock = &sync.RWMutex{}
var config = &Config{}
func WatchClusterConfig() error {
cli := etcd.GetClient()
key := "/seckill/config"
resp, err := cli.Get(context.Background(), key)
if err != nil {
return err
}
update := func(kv *mvccpb.KeyValue) (bool, error) {
if string(kv.Key) == key {
var tmpConfig *Config
err = json.Unmarshal(kv.Value, &tmpConfig)
if err != nil {
logrus.Error("update cluster config failed, error:", err)
return false, err
}
configLock.Lock()
*config = *tmpConfig
logrus.Info("update cluster config ", *config)
configLock.Unlock()
return true, nil
}
return false, nil
}
for _, kv := range resp.Kvs {
if ok, err := update(kv); ok {
break
} else if err != nil {
return err
}
}
go func() {
watchCh := cli.Watch(context.Background(), key)
for resp := range watchCh {
for _, evt := range resp.Events {
if evt.Type == etcdv3.EventTypePut {
if ok, err := update(evt.Kv); ok {
break
} else if err != nil {
break
}
}
}
}
}()
return nil
}
func GetClusterConfig() Config {
configLock.RLock()
defer configLock.RUnlock()
return *config
}
type Node struct {
Addr string `json:"addr"`
Version string `json:"version"`
Proto string `json:"proto"`
}
type cluster struct {
sync.RWMutex
cli *etcdv3.Client
service string
once *sync.Once
deregCh map[string]chan struct{}
nodes map[string]*Node
}
var defaultCluster *cluster
var once = &sync.Once{}
func Init(service string) {
once.Do(func() {
defaultCluster = &cluster{
cli: etcd.GetClient(),
service: service,
once: &sync.Once{},
deregCh: make(map[string]chan struct{}),
nodes: make(map[string]*Node),
}
})
}
func Register(node *Node, ttl int) error {
const minTTL = 2
c := defaultCluster
key := c.makeKey(node)
if ttl < minTTL {
ttl = minTTL
}
var errCh = make(chan error)
go func() {
kv := etcdv3.NewKV(c.cli)
closeCh := make(chan struct{})
lease := etcdv3.NewLease(c.cli)
val, _ := json.Marshal(node)
var curLeaseId etcdv3.LeaseID = 0
ticker := time.NewTicker(time.Duration(ttl/2) * time.Second)
register := func() error {
if curLeaseId == 0 {
leaseResp, err := lease.Grant(context.TODO(), int64(ttl))
if err != nil {
return err
}
if _, err := kv.Put(context.TODO(), key, string(val), etcdv3.WithLease(leaseResp.ID)); err != nil {
return err
}
curLeaseId = leaseResp.ID
} else {
// 续约租约,如果租约已经过期将curLeaseId复位到0重新走创建租约的逻辑
if _, err := lease.KeepAliveOnce(context.TODO(), curLeaseId); err == rpctypes.ErrLeaseNotFound {
curLeaseId = 0
}
}
return nil
}
if err := register(); err != nil {
logrus.Error("register node failed, error:", err)
errCh <- err
}
close(errCh)
for {
select {
case <-ticker.C:
if err := register(); err != nil {
logrus.Error("register node failed, error:", err)
panic(err)
}
case <-closeCh:
ticker.Stop()
return
}
}
}()
err := <-errCh
return err
}
func Deregister(node *Node) error {
c := defaultCluster
c.Lock()
defer c.Unlock()
key := c.makeKey(node)
if ch, ok := c.deregCh[key]; ok {
close(ch)
delete(c.deregCh, key)
}
_, err := c.cli.Delete(context.Background(), key, etcdv3.WithPrefix())
return err
}
func Discover() (output []*Node, err error) {
c := defaultCluster
key := fmt.Sprintf("/%s/nodes/", c.service)
c.once.Do(func() {
var resp *etcdv3.GetResponse
resp, err = c.cli.Get(context.Background(), key, etcdv3.WithPrefix())
if err != nil {
return
}
for _, kv := range resp.Kvs {
k := string(kv.Key)
if len(k) > len(key) {
var node *Node
json.Unmarshal(kv.Value, &node)
if node != nil {
c.Lock()
c.nodes[k] = node
c.Unlock()
}
}
}
watchCh := c.cli.Watch(context.Background(), key, etcdv3.WithPrefix())
go func() {
for {
select {
case resp := <-watchCh:
for _, evt := range resp.Events {
k := string(evt.Kv.Key)
if len(k) <= len(key) {
continue
}
switch evt.Type {
case etcdv3.EventTypePut:
var node *Node
json.Unmarshal(evt.Kv.Value, &node)
if node != nil {
c.Lock()
c.nodes[k] = node
c.Unlock()
}
case etcdv3.EventTypeDelete:
c.Lock()
if _, ok := c.nodes[k]; ok {
delete(c.nodes, k)
}
c.Unlock()
}
}
}
}
}()
})
if err != nil {
return nil, err
}
c.RLock()
for _, node := range c.nodes {
output = append(output, node)
}
c.RUnlock()
return
}
func (c *cluster) makeKey(node *Node) string {
id := strings.Replace(node.Addr, ".", "-", -1)
id = strings.Replace(id, ":", "-", -1)
return fmt.Sprintf("/%s/nodes/%s", c.service, id)
}
<|start_filename|>interfaces/admin/routers.go<|end_filename|>
package admin
import (
"github.com/gin-gonic/gin"
"github.com/letian0805/seckill/application/admin"
)
func initRouters(g *gin.Engine) {
topic := g.Group("/topic")
topicApp := admin.Topic{}
topic.POST("/", topicApp.Post)
topic.GET("/", topicApp.Get)
topic.GET("/:id", topicApp.Get)
topic.PUT("/:id", topicApp.Put)
topic.PUT("/:id/:status", topicApp.Status)
topic.DELETE("/:id", topicApp.Delete)
event := g.Group("/event")
eventApp := admin.Event{}
event.POST("/", eventApp.Post)
event.GET("/", eventApp.Get)
event.GET("/:id", eventApp.Get)
event.PUT("/:id", eventApp.Put)
event.PUT("/:id/:status", eventApp.Status)
event.DELETE("/:id", eventApp.Delete)
goods := g.Group("/goods")
goodsApp := admin.Goods{}
goods.POST("/", goodsApp.Post)
goods.GET("/", goodsApp.Get)
goods.GET("/:id", goodsApp.Get)
goods.PUT("/:id", goodsApp.Put)
goods.DELETE("/:id", goodsApp.Delete)
}
<|start_filename|>domain/product/types.go<|end_filename|>
package product
type Goods struct {
ID string `json:"id"`
Name string `json:"name"`
Desc string `json:"desc"`
Img string `json:"img"`
Price string `json:"price"`
}
<|start_filename|>infrastructure/pool/pool_test.go<|end_filename|>
package pool
import (
"io"
"sync"
"testing"
)
type testCloser struct {
}
func (c *testCloser) Close() error {
return nil
}
func newCloser() (io.Closer, error) {
return &testCloser{}, nil
}
func testPool(b *testing.B, p Pool) {
var data = make([]io.Closer, b.N, b.N)
for i := 0; i < b.N; i++ {
data[i], _ = p.Get()
}
ch := make(chan struct{})
wg1 := &sync.WaitGroup{}
wg2 := &sync.WaitGroup{}
wg1.Add(b.N)
wg2.Add(b.N)
for i := 0; i < b.N; i++ {
go func(c io.Closer) {
wg1.Done()
<-ch
p.Put(c)
p.Get()
wg2.Done()
}(data[i])
}
wg1.Wait()
b.ReportAllocs()
b.StartTimer()
close(ch)
wg2.Wait()
b.StopTimer()
}
func BenchmarkChanPool(b *testing.B) {
p := NewChanPool("test", b.N, newCloser)
testPool(b, p)
}
func BenchmarkRingBufferPool(b *testing.B) {
p := NewRingBufferPool("test", b.N, newCloser)
testPool(b, p)
}
<|start_filename|>domain/event/types.go<|end_filename|>
package event
import "github.com/letian0805/seckill/domain/product"
type Topic struct {
ID int64 `json:"id"`
Topic string `json:"topic"`
Banner string `json:"banner"`
StartTime int64 `json:"start_time"`
EndTime int64 `json:"end_time"`
List []*Event `json:"list"`
}
type Event struct {
ID int64 `json:"id"`
StartTime int64 `json:"start_time"`
EndTime int64 `json:"end_time"`
List []*Goods `json:"list"`
}
type Goods struct {
product.Goods
EventPrice string `json:"event_price"`
EventType string `json:"event_type"`
}
type Info struct {
EventPrice string `json:"event_price"`
EventType string `json:"event_type"`
StartTime int64 `json:"start_time"`
EndTime int64 `json:"end_time"`
}
var TestData *Topic
func init() {
t := &Topic{
ID: 0,
Topic: "test",
Banner: "",
StartTime: 0,
EndTime: 0,
List: []*Event{},
}
for i := 0; i < 10; i++ {
t.List = append(t.List, &Event{
ID: 0,
StartTime: 0,
EndTime: 0,
List: []*Goods{},
})
for j := 0; j < 10; j++ {
g := &Goods{
Goods: product.Goods{},
EventPrice: "",
EventType: "",
}
t.List[i].List = append(t.List[i].List, g)
}
}
TestData = t
}
<|start_filename|>domain/stock/stock_test.go<|end_filename|>
package stock
import (
"reflect"
"testing"
"github.com/letian0805/seckill/infrastructure/stores/redis"
)
func TestStock(t *testing.T) {
var (
st Stock
err error
val int64
)
if err = redis.Init(); err != nil {
t.Fatal(err)
}
if st, err = NewRedisStock("101", "1001"); err != nil {
t.Fatal(err)
}
defer func() {
cli := redis.GetClient()
cli.Del("seckill#101#1001")
cli.Del("seckill#101#1001#123")
}()
if err = st.Set(10, 100); err != nil {
t.Fatal(err)
}
if val, err = st.Get(); err != nil {
t.Fatal(err)
} else if val != 10 {
t.Fatal("not equal 10")
}
if val, err = st.Sub("123"); err != nil {
t.Fatal(err)
} else if val != 9 {
t.Fatal("not equal 9", val)
}
if err = st.Del(); err != nil {
t.Fatal(err)
}
if val, err = st.Get(); err != nil {
t.Fatal(err)
} else if val != 0 {
t.Fatal("not equal 0")
}
}
func TestRedis(t *testing.T) {
redis.Init()
cli := redis.GetClient()
script := `
return redis.call('get', 'seckill#101#1001')
`
res, err := cli.Eval(script, []string{}).Result()
t.Log(res, reflect.TypeOf(res), err)
}
| lagoueduCol/MiaoSha-Yiletian |
<|start_filename|>server/js/apextooltip.js<|end_filename|>
// APEX Tooltip functions
// Author: <NAME>
// Version: 1.2
// global namespace
var apexTooltip = {
// parse string to boolean
parseBoolean: function(pString) {
var pBoolean;
if (pString.toLowerCase() == 'true') {
pBoolean = true;
}
if (pString.toLowerCase() == 'false') {
pBoolean = false;
}
if (!(pString.toLowerCase() == 'true') && !(pString.toLowerCase() == 'false')) {
pBoolean = undefined;
}
return pBoolean;
},
// helper function to get right text
getText: function(pSource, pText, pItem, pElement) {
var vText;
if (pSource == 'TEXT') {
vText = pText;
} else if (pSource == 'ITEM') {
vText = $v(pItem);
} else if (pSource == 'TITLE') {
vText = $(pElement).attr('title');
}
return vText;
},
// function that gets called from plugin
showTooltip: function() {
// plugin attributes
var daThis = this;
var vElementsArray = daThis.affectedElements;
var vTheme = daThis.action.attribute01;
var vTextSource = daThis.action.attribute11;
var vContent = daThis.action.attribute02;
var vContentItem = daThis.action.attribute12;
var vContentAsHTML = apexTooltip.parseBoolean(daThis.action.attribute03);
var vAnimation = daThis.action.attribute04;
var vPosition = daThis.action.attribute05;
var vDelay = parseInt(daThis.action.attribute06);
var vTrigger = daThis.action.attribute07;
var vMinWidth = parseInt(daThis.action.attribute08);
var vMaxWidth = parseInt(daThis.action.attribute09);
var vLogging = apexTooltip.parseBoolean(daThis.action.attribute10);
var vFinalText;
// Logging
if (vLogging) {
console.log('showTooltip: affectedElements:', vElementsArray);
console.log('showTooltip: Attribute Theme:', vTheme);
console.log('showTooltip: Attribute Content Text Source:', vTextSource);
console.log('showTooltip: Attribute Content:', vContent);
console.log('showTooltip: Attribute Content Item:', vContentItem);
console.log('showTooltip: Attribute Content as HTML:', vContentAsHTML);
console.log('showTooltip: Attribute Animation:', vAnimation);
console.log('showTooltip: Attribute Position:', vPosition);
console.log('showTooltip: Attribute Delay:', vDelay);
console.log('showTooltip: Attribute Trigger:', vTrigger);
console.log('showTooltip: Attribute minWidth:', vMinWidth);
console.log('showTooltip: Attribute maxWidth:', vMaxWidth);
console.log('showTooltip: Attribute Logging:', vLogging);
}
for (var i = 0; i < vElementsArray.length; i++) {
var vAffectedElement = daThis.affectedElements.eq(i);
// Get Text
vFinalText = apexTooltip.getText(vTextSource, vContent, vContentItem, vAffectedElement);
// call tooltipster plugin
$(vAffectedElement).tooltipster({
theme: vTheme,
content: vFinalText,
contentAsHTML: vContentAsHTML,
animation: vAnimation,
side: vPosition,
delay: vDelay,
touchDevices: false,
trigger: vTrigger,
minWidth: vMinWidth,
maxWidth: vMaxWidth,
debug: vLogging,
functionBefore: function(instance, continueTooltip) {
// APEX event
$(vAffectedElement).trigger('apextooltip-show');
// update content Text
vFinalText = apexTooltip.getText(vTextSource, vContent, vContentItem, vAffectedElement);
instance.content(vFinalText);
},
functionAfter: function(instance) {
// APEX event
$(vAffectedElement).trigger('apextooltip-hide');
}
});
}
}
};
| Dani3lSun/apex-plugin-apextooltip |
<|start_filename|>IntegrationTests/bin/benchmark-tests.js<|end_filename|>
const { startWasiTask } = require("../lib");
const { performance } = require("perf_hooks");
global.benchmarkRunner = function (name, body) {
console.log(`Running '${name}' ...`);
const startTime = performance.now();
body(5000);
const endTime = performance.now();
console.log("done " + (endTime - startTime) + " ms");
};
class JSBenchmark {
constructor(title) {
this.title = title;
}
testSuite(name, body) {
benchmarkRunner(`${this.title}/${name}`, (iteration) => {
for (let idx = 0; idx < iteration; idx++) {
body();
}
});
}
}
const serialization = new JSBenchmark("Serialization");
serialization.testSuite("Write JavaScript number directly", () => {
const jsNumber = 42;
const object = global;
for (let idx = 0; idx < 100; idx++) {
object["numberValue" + idx] = jsNumber;
}
});
serialization.testSuite("Write JavaScript string directly", () => {
const jsString = "Hello, world";
const object = global;
for (let idx = 0; idx < 100; idx++) {
object["stringValue" + idx] = jsString;
}
});
startWasiTask("./dist/BenchmarkTests.wasm").catch((err) => {
console.log(err);
});
<|start_filename|>ci/perf-tester/src/index.js<|end_filename|>
/*
Adapted from preactjs/compressed-size-action, which is available under this license:
MIT License
Copyright (c) 2020 Preact
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const { setFailed, startGroup, endGroup, debug } = require("@actions/core");
const { GitHub, context } = require("@actions/github");
const { exec } = require("@actions/exec");
const {
getInput,
runBenchmark,
averageBenchmarks,
toDiff,
diffTable,
toBool,
} = require("./utils.js");
const benchmarkParallel = 2;
const benchmarkSerial = 2;
const runBenchmarks = async () => {
let results = [];
for (let i = 0; i < benchmarkSerial; i++) {
results = results.concat(
await Promise.all(Array(benchmarkParallel).fill().map(runBenchmark))
);
}
return averageBenchmarks(results);
};
async function run(octokit, context, token) {
const { number: pull_number } = context.issue;
const pr = context.payload.pull_request;
try {
debug("pr" + JSON.stringify(pr, null, 2));
} catch (e) {}
if (!pr) {
throw Error(
'Could not retrieve PR information. Only "pull_request" triggered workflows are currently supported.'
);
}
console.log(
`PR #${pull_number} is targetted at ${pr.base.ref} (${pr.base.sha})`
);
const buildScript = getInput("build-script");
startGroup(`[current] Build using '${buildScript}'`);
await exec(buildScript);
endGroup();
startGroup(`[current] Running benchmark`);
const newBenchmarks = await runBenchmarks();
endGroup();
startGroup(`[base] Checkout target branch`);
let baseRef;
try {
baseRef = context.payload.base.ref;
if (!baseRef)
throw Error("missing context.payload.pull_request.base.ref");
await exec(
`git fetch -n origin ${context.payload.pull_request.base.ref}`
);
console.log("successfully fetched base.ref");
} catch (e) {
console.log("fetching base.ref failed", e.message);
try {
await exec(`git fetch -n origin ${pr.base.sha}`);
console.log("successfully fetched base.sha");
} catch (e) {
console.log("fetching base.sha failed", e.message);
try {
await exec(`git fetch -n`);
} catch (e) {
console.log("fetch failed", e.message);
}
}
}
console.log("checking out and building base commit");
try {
if (!baseRef) throw Error("missing context.payload.base.ref");
await exec(`git reset --hard ${baseRef}`);
} catch (e) {
await exec(`git reset --hard ${pr.base.sha}`);
}
endGroup();
startGroup(`[base] Build using '${buildScript}'`);
await exec(buildScript);
endGroup();
startGroup(`[base] Running benchmark`);
const oldBenchmarks = await runBenchmarks();
endGroup();
const diff = toDiff(oldBenchmarks, newBenchmarks);
const markdownDiff = diffTable(diff, {
collapseUnchanged: true,
omitUnchanged: false,
showTotal: true,
minimumChangeThreshold: parseInt(
getInput("minimum-change-threshold"),
10
),
});
let outputRawMarkdown = false;
const commentInfo = {
...context.repo,
issue_number: pull_number,
};
const comment = {
...commentInfo,
body:
markdownDiff +
'\n\n<a href="https://github.com/j-f1/performance-action"><sub>performance-action</sub></a>',
};
if (toBool(getInput("use-check"))) {
if (token) {
const finish = await createCheck(octokit, context);
await finish({
conclusion: "success",
output: {
title: `Compressed Size Action`,
summary: markdownDiff,
},
});
} else {
outputRawMarkdown = true;
}
} else {
startGroup(`Updating stats PR comment`);
let commentId;
try {
const comments = (await octokit.issues.listComments(commentInfo))
.data;
for (let i = comments.length; i--; ) {
const c = comments[i];
if (
c.user.type === "Bot" &&
/<sub>[\s\n]*performance-action/.test(c.body)
) {
commentId = c.id;
break;
}
}
} catch (e) {
console.log("Error checking for previous comments: " + e.message);
}
if (commentId) {
console.log(`Updating previous comment #${commentId}`);
try {
await octokit.issues.updateComment({
...context.repo,
comment_id: commentId,
body: comment.body,
});
} catch (e) {
console.log("Error editing previous comment: " + e.message);
commentId = null;
}
}
// no previous or edit failed
if (!commentId) {
console.log("Creating new comment");
try {
await octokit.issues.createComment(comment);
} catch (e) {
console.log(`Error creating comment: ${e.message}`);
console.log(`Submitting a PR review comment instead...`);
try {
const issue = context.issue || pr;
await octokit.pulls.createReview({
owner: issue.owner,
repo: issue.repo,
pull_number: issue.number,
event: "COMMENT",
body: comment.body,
});
} catch (e) {
console.log("Error creating PR review.");
outputRawMarkdown = true;
}
}
}
endGroup();
}
if (outputRawMarkdown) {
console.log(
`
Error: performance-action was unable to comment on your PR.
This can happen for PR's originating from a fork without write permissions.
You can copy the size table directly into a comment using the markdown below:
\n\n${comment.body}\n\n
`.replace(/^(\t| )+/gm, "")
);
}
console.log("All done!");
}
// create a check and return a function that updates (completes) it
async function createCheck(octokit, context) {
const check = await octokit.checks.create({
...context.repo,
name: "Compressed Size",
head_sha: context.payload.pull_request.head.sha,
status: "in_progress",
});
return async (details) => {
await octokit.checks.update({
...context.repo,
check_run_id: check.data.id,
completed_at: new Date().toISOString(),
status: "completed",
...details,
});
};
}
(async () => {
try {
const token = getInput("repo-token", { required: true });
const octokit = new GitHub(token);
await run(octokit, context, token);
} catch (e) {
setFailed(e.message);
}
})();
<|start_filename|>IntegrationTests/Makefile<|end_filename|>
CONFIGURATION ?= debug
SWIFT_BUILD_FLAGS ?=
FORCE:
TestSuites/.build/$(CONFIGURATION)/%.wasm: FORCE
swift build --package-path TestSuites \
--product $(basename $(notdir $@)) \
--triple wasm32-unknown-wasi \
--configuration $(CONFIGURATION) \
$(SWIFT_BUILD_FLAGS)
dist/%.wasm: TestSuites/.build/$(CONFIGURATION)/%.wasm
mkdir -p dist
cp $< $@
node_modules: package-lock.json
npm ci
.PHONY: build_rt
build_rt: node_modules
cd .. && npm run build
.PHONY: benchmark_setup
benchmark_setup: build_rt dist/BenchmarkTests.wasm
.PHONY: run_benchmark
run_benchmark:
node bin/benchmark-tests.js
.PHONY: benchmark
benchmark: benchmark_setup run_benchmark
.PHONY: primary_test
primary_test: build_rt dist/PrimaryTests.wasm
node bin/primary-tests.js
.PHONY: concurrency_test
concurrency_test: build_rt dist/ConcurrencyTests.wasm
node bin/concurrency-tests.js
.PHONY: test
test: concurrency_test primary_test
<|start_filename|>IntegrationTests/bin/concurrency-tests.js<|end_filename|>
const { startWasiTask } = require("../lib");
startWasiTask("./dist/ConcurrencyTests.wasm").catch((err) => {
console.log(err);
process.exit(1);
});
<|start_filename|>Sources/_CJavaScriptEventLoop/include/_CJavaScriptEventLoop.h<|end_filename|>
#ifndef _CJavaScriptEventLoop_h
#define _CJavaScriptEventLoop_h
#include <stdalign.h>
#include <stdint.h>
#define SWIFT_CC(CC) SWIFT_CC_##CC
#define SWIFT_CC_swift __attribute__((swiftcall))
#define SWIFT_EXPORT_FROM(LIBRARY) __attribute__((__visibility__("default")))
/// A schedulable unit
/// Note that this type layout is a part of public ABI, so we expect this field layout won't break in the future versions.
/// Current implementation refers the `swift-5.5-RELEASE` implementation.
/// https://github.com/apple/swift/blob/swift-5.5-RELEASE/include/swift/ABI/Task.h#L43-L129
/// This definition is used to retrieve priority value of a job. After custom-executor API will be introduced officially,
/// the job priority API will be provided in the Swift world.
typedef __attribute__((aligned(2 * alignof(void *)))) struct {
void *_Nonnull Metadata;
int32_t RefCounts;
void *_Nullable SchedulerPrivate[2];
uint32_t Flags;
} Job;
/// A hook to take over global enqueuing.
typedef SWIFT_CC(swift) void (*swift_task_enqueueGlobal_original)(
Job *_Nonnull job);
SWIFT_EXPORT_FROM(swift_Concurrency)
void *_Nullable swift_task_enqueueGlobal_hook;
/// A hook to take over global enqueuing with delay.
typedef SWIFT_CC(swift) void (*swift_task_enqueueGlobalWithDelay_original)(
unsigned long long delay, Job *_Nonnull job);
SWIFT_EXPORT_FROM(swift_Concurrency)
void *_Nullable swift_task_enqueueGlobalWithDelay_hook;
unsigned long long foo;
/// A hook to take over main executor enqueueing.
typedef SWIFT_CC(swift) void (*swift_task_enqueueMainExecutor_original)(
Job *_Nonnull job);
SWIFT_EXPORT_FROM(swift_Concurrency)
void *_Nullable swift_task_enqueueMainExecutor_hook;
#endif
<|start_filename|>Example/src/index.js<|end_filename|>
import { SwiftRuntime } from "javascript-kit-swift";
import { WASI } from "@wasmer/wasi";
import { WasmFs } from "@wasmer/wasmfs";
const swift = new SwiftRuntime();
// Instantiate a new WASI Instance
const wasmFs = new WasmFs();
// Output stdout and stderr to console
const originalWriteSync = wasmFs.fs.writeSync;
wasmFs.fs.writeSync = (fd, buffer, offset, length, position) => {
const text = new TextDecoder("utf-8").decode(buffer);
// Filter out standalone "\n" added by every `print`, `console.log`
// always adds its own "\n" on top.
if (text !== "\n") {
switch (fd) {
case 1:
console.log(text);
break;
case 2:
console.error(text);
break;
}
}
return originalWriteSync(fd, buffer, offset, length, position);
};
let wasi = new WASI({
args: [],
env: {},
bindings: {
...WASI.defaultBindings,
fs: wasmFs.fs,
},
});
const startWasiTask = async () => {
// Fetch our Wasm File
const response = await fetch("JavaScriptKitExample.wasm");
const responseArrayBuffer = await response.arrayBuffer();
// Instantiate the WebAssembly file
const wasm_bytes = new Uint8Array(responseArrayBuffer).buffer;
let { instance } = await WebAssembly.instantiate(wasm_bytes, {
wasi_snapshot_preview1: wasi.wasiImport,
javascript_kit: swift.importObjects(),
});
swift.setInstance(instance);
// Start the WebAssembly WASI instance!
wasi.start(instance);
};
startWasiTask();
<|start_filename|>IntegrationTests/bin/primary-tests.js<|end_filename|>
global.globalObject1 = {
prop_1: {
nested_prop: 1,
},
prop_2: 2,
prop_3: true,
prop_4: [3, 4, "str_elm_1", null, undefined, 5],
prop_5: {
func1: function () {
return;
},
func2: function () {
return 1;
},
func3: function (n) {
return n * 2;
},
func4: function (a, b, c) {
return a + b + c;
},
func5: function (x) {
return "Hello, " + x;
},
func6: function (c, a, b) {
if (c) {
return a;
} else {
return b;
}
},
},
prop_6: {
call_host_1: () => {
return global.globalObject1.prop_6.host_func_1();
},
},
prop_7: 3.14,
prop_8: [0, , 2, 3, , , 6],
prop_9: {
func1: function () {
throw new Error();
},
func2: function () {
throw "String Error";
},
func3: function () {
throw 3.0
},
},
eval_closure: function (fn) {
return fn(arguments[1])
},
observable_obj: {
set_called: false,
target: new Proxy({
nested: {}
}, {
set(target, key, value) {
global.globalObject1.observable_obj.set_called = true;
target[key] = value;
return true;
}
})
},
};
global.Animal = function (name, age, isCat) {
if (age < 0) {
throw new Error("Invalid age " + age);
}
this.name = name;
this.age = age;
this.bark = () => {
return isCat ? "nyan" : "wan";
};
this.isCat = isCat;
this.getIsCat = function () {
return this.isCat;
};
this.setName = function (name) {
this.name = name;
}
};
const { startWasiTask } = require("../lib");
startWasiTask("./dist/PrimaryTests.wasm").catch((err) => {
console.log(err);
process.exit(1);
});
| yonihemi/JavaScriptKit |
<|start_filename|>loadgen/system_under_test.h<|end_filename|>
/* Copyright 2019 The MLPerf Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
/// \file
/// \brief Defines the SystemUnderTest interface.
#ifndef MLPERF_LOADGEN_SYSTEM_UNDER_TEST_H
#define MLPERF_LOADGEN_SYSTEM_UNDER_TEST_H
#include <string>
#include <vector>
#include "query_sample.h"
namespace mlperf {
/// \addtogroup LoadgenAPI
/// @{
/// \brief The interface a client implements for the loadgen to test.
/// \todo Add hook for an untimed warm up period for the SUT.
/// \todo Add hook for an untimed warm up period for the loadgen logic.
/// \todo Support power hooks for cool-down period before runing performance
/// traffic.
/// \todo Support power hooks for correlating test timeline with power
/// measurment timeline.
class SystemUnderTest {
public:
virtual ~SystemUnderTest() {}
/// \brief A human-readable string for logging purposes.
virtual const std::string& Name() const = 0;
/// \brief Lets the loadgen issue N samples to the SUT.
/// \details The SUT may either a) return immediately and signal completion
/// at a later time on another thread or b) it may block and signal
/// completion on the current stack. The load generator will handle both
/// cases properly.
/// Note: The data for neighboring samples may or may not be contiguous
/// depending on the scenario.
virtual void IssueQuery(const std::vector<QuerySample>& samples) = 0;
/// \brief Called immediately after the last call to IssueQuery
/// in a series is made.
/// \details This doesn't necessarily signify the end of the
/// test since there may be multiple series involved during a test; for
/// example in accuracy mode.
/// Clients can use this to flush any deferred queries immediately, rather
/// than waiting for some timeout.
/// This is especially useful in the server scenario.
virtual void FlushQueries() = 0;
};
/// @}
} // namespace mlperf
#endif // MLPERF_LOADGEN_SYSTEM_UNDER_TEST_H
| pgmpablo157321/inference |
<|start_filename|>subset/bacnet/bacnetTests/src/main/java/FauxDeviceEngine/JSON.java<|end_filename|>
package FauxDeviceEngine;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class JSON {
private String fileName = "";
public JSON(String fileName) {
this.fileName = fileName;
}
public JSONArray read() {
JSONParser jsonParser = new JSONParser();
JSONArray bacnetObjectTypeList = null;
try(FileReader reader = new FileReader(fileName)) {
Object obj = jsonParser.parse(reader);
bacnetObjectTypeList = (JSONArray) obj;
} catch (FileNotFoundException e ) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
return bacnetObjectTypeList;
}
}
<|start_filename|>subset/bacnet/bacnetTests/src/main/java/helper/Csv.java<|end_filename|>
package helper;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class Csv {
private PicsValidator picsValidator = new PicsValidator();
private String csvFile = null;
private String line = "";
private String csvSplitBy = ",";
private Multimap<String, Object> picsMap = ArrayListMultimap.create();
private String[] csvColumnTitle = {
"Bacnet_Object_Type", "Bacnet_Object_Property", "Conformance_Code", "Supported"
};
private boolean passedTest = false;
private String appendixText = "";
public Csv(String csvFile) {
this.csvFile = csvFile;
}
public void readAndValidate(Multimap<String, Map<String, String>> bacnetPointsMap, boolean verboseOutput) {
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] value = line.split(csvSplitBy);
final String objectType = value[0];
final String objectProperty = value[1];
final String conformanceCode = value[3];
final String supported = value[4];
if (!objectType.equals(csvColumnTitle[0])
&& !objectProperty.equals(csvColumnTitle[1])
&& !conformanceCode.equals(csvColumnTitle[2])
&& !supported.equals(csvColumnTitle[3])) {
saveValuesToMap(value);
validateLine(value[0], value[1], value[3], value[4], bacnetPointsMap, verboseOutput);
}
}
setTestResult(picsValidator.getResult());
} catch (IOException e) {
String errorMessage = "CSV file error: " + e.getMessage();
System.err.println(errorMessage);
setTestResult(false);
setTestAppendices(errorMessage);
}
}
private void validateLine(
String bacnetObjectType,
String bacnetObjectProperty,
String conformanceCode,
String supported,
Multimap bacnetPointsMap,
boolean verboseOutput) {
try {
picsValidator.validate(
formatValue(bacnetObjectType),
formatValue(bacnetObjectProperty),
conformanceCode,
supported,
bacnetPointsMap, verboseOutput);
} catch (Exception e) {
System.err.println(
"Error validating property: "
+ e.getMessage()
+ " "
+ bacnetObjectType
+ " "
+ bacnetObjectProperty);
}
}
public boolean getTestResult() {
return this.passedTest;
}
private void setTestResult(boolean result) {
this.passedTest = result;
}
public String getTestAppendices() {
Multimap<String, String> appendicesMap = picsValidator.getResultMap();
for (Map.Entry appendix : appendicesMap.entries()) {
appendixText += String.format("%s %s \n", appendix.getKey(), appendix.getValue());
}
return appendixText + "\n";
}
private void setTestAppendices(String appendix) {
this.appendixText = appendix;
}
private void saveValuesToMap(String[] values) {
String bacnetObjectType = formatValue(values[0]);
String bacnetObjectProperty = values[1];
String conformanceCode = values[3];
String supported = values[4];
Map<String, String[]> bacnetObjectPropertyMap = new HashMap<>();
String[] properties = {conformanceCode, supported};
bacnetObjectPropertyMap.put(bacnetObjectProperty, properties);
picsMap.put(bacnetObjectType, bacnetObjectPropertyMap);
}
private String formatValue(String value) {
if (value.isEmpty() || value.trim().length() == 0) {
return "";
}
String[] bacnetObjectTypes = {
"Analog_Input, Analog_Output",
"Analog_Value",
"Binary_Input",
"Binary_Output",
"Binary_Value",
"Calendar",
"Device",
"Event_Enrollment",
"File",
"Loop",
"Multi-state_Input",
"Multi-state_Value",
"Program",
"Notification",
"Schedule",
"Trend_Log"
};
value = value.replace("Bacnet_", "")
.replace("Analogue", "Analog")
.replace("_", " ");
for (int count = 0; count < bacnetObjectTypes.length; count++) {
String bacnetObjectType = bacnetObjectTypes[count];
if (bacnetObjectType.contains(value)) {
bacnetObjectType = bacnetObjectType.replaceAll("_", " ");
return bacnetObjectType;
}
}
return value;
}
}
<|start_filename|>subset/bacnet/bacnetTests/src/main/java/Main.java<|end_filename|>
public class Main {
public static void main(String[] args) throws Exception {
if (args.length < 4) {
throw new IllegalArgumentException("Usage: bacnetTestId broadcastIp localIp verboseOutput");
}
String bacnetTestId = args[0];
String broadcastIp = args[1];
String localIp = args[2];
boolean verboseOutput = Boolean.parseBoolean(args[3]);
switch (bacnetTestId) {
case "bacnet_VERSION":
new VersionTest(localIp, broadcastIp);
break;
case "bacnet_PICS":
new PicsTest(localIp, broadcastIp, verboseOutput);
break;
default:
throw new IllegalArgumentException("Invalid bacnetTestId.");
}
}
}
<|start_filename|>subset/bacnet/bacnetTests/src/main/java/helper/PicsValidator.java<|end_filename|>
package helper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.util.*;
import java.util.regex.Pattern;
public class PicsValidator {
String read = "R";
String write = "W";
String optional = "O";
String Supported = "TRUE";
String formatProperty = "%-35s%-35s%-15s%-25s";
Multimap<String, String> result = ArrayListMultimap.create();
boolean testPassed = false;
private int count = 0;
public void validate(String bacnetObjectType, String bacnetObjectProperty, String conformanceCode,
String supported, Multimap bacnetPointsMap, boolean verboseOutput) {
Set<String> mapKeySet = bacnetPointsMap.keySet();
ArrayList<String> keys = getMapKeys(mapKeySet, bacnetObjectType);
if (keys.size() == 0 && (conformanceCode.contains(read) || conformanceCode.equals(write))
&& !bacnetObjectProperty.equals("Property List")) {
writeToAppendix(formatProperty, bacnetObjectType, bacnetObjectProperty, conformanceCode,
"FAILED", verboseOutput);
setResult(false);
} else if (keys.size() == 0 && conformanceCode.contains(optional)
&& !bacnetObjectProperty.equals("Property List")) {
writeToAppendix(formatProperty, bacnetObjectType, bacnetObjectProperty, conformanceCode,
"PASSED/WARNING", verboseOutput);
setResult(true);
} else if (keys.size() == 0 && bacnetObjectProperty.equals("Property List")) {
writeToAppendix(formatProperty, bacnetObjectType, bacnetObjectProperty, conformanceCode,
"PASSED", verboseOutput);
setResult(true);
}
for (String key : keys) {
String properties = bacnetPointsMap.get(key).toString();
boolean bacnetObjectPropertyIsFound =
Pattern.compile(Pattern.quote(bacnetObjectProperty), Pattern.CASE_INSENSITIVE)
.matcher(properties).find();
if (!bacnetObjectPropertyIsFound
&& (conformanceCode.contains(read) || conformanceCode.equals(write)) && supported.equals(Supported)
&& !bacnetObjectProperty.equals("Property List")) {
writeToAppendix(formatProperty, bacnetObjectType, bacnetObjectProperty, conformanceCode,
"FAILED", verboseOutput);
setResult(false);
} else if (!bacnetObjectPropertyIsFound && conformanceCode.contains(optional)
&& supported.equals(Supported) && !bacnetObjectProperty.equals("Property List")) {
writeToAppendix(formatProperty, bacnetObjectType, bacnetObjectProperty, conformanceCode,
"PASSED/WARNING", verboseOutput);
setResult(true);
} else if (bacnetObjectPropertyIsFound && supported.equals(Supported)
&& !bacnetObjectProperty.equals("Property List")) {
writeToAppendix(formatProperty, bacnetObjectType, bacnetObjectProperty, conformanceCode,
"PASSED", verboseOutput);
setResult(true);
}
}
}
private void writeToAppendix(String formatProperty, String key, String bacnetObjectProperty, String conformanceCode,
String lineresult, boolean verboseOutput) {
if (!verboseOutput & (lineresult.contains("FAILED") | lineresult.contains("PASSED/WARNING"))) {
String appendix = String.format(formatProperty, key, bacnetObjectProperty,
conformanceCode, lineresult);
this.result.put(key, appendix);
} else if (verboseOutput) {
String appendix = String.format(formatProperty, key, bacnetObjectProperty,
conformanceCode, lineresult);
this.result.put(key, appendix);
}
}
private ArrayList<String> getMapKeys(Set<String> mapKeySet, String bacnetObjectType) {
ArrayList<String> keys = new ArrayList<>();
for (String key : mapKeySet) {
if (key.contains(bacnetObjectType)) {
keys.add(key);
}
}
return keys;
}
private void setResult(boolean propertyValidated) {
if(count == 0) {
this.testPassed = propertyValidated;
} else {
if(!this.testPassed) {
return;
} else { this.testPassed = propertyValidated; }
}
count++;
}
public Multimap<String, String> getResultMap() {
return this.result;
}
public boolean getResult() {
return this.testPassed;
}
}
<|start_filename|>usi/src/main/java/daq/usi/ResponseHandler.java<|end_filename|>
package daq.usi;
public interface ResponseHandler<T> {
void receiveData(T data) throws Exception;
}
<|start_filename|>usi/src/main/java/daq/usi/SwitchController.java<|end_filename|>
package daq.usi;
import grpc.InterfaceResponse;
import grpc.PowerResponse;
import grpc.SwitchActionResponse;
public interface SwitchController {
void getPower(int devicePort, ResponseHandler<PowerResponse> handler) throws Exception;
void getInterface(int devicePort, ResponseHandler<InterfaceResponse> handler)
throws Exception;
void connect(int devicePort, ResponseHandler<SwitchActionResponse> handler)
throws Exception;
void disconnect(int devicePort, ResponseHandler<SwitchActionResponse> handler)
throws Exception;
void start();
}
<|start_filename|>firebase/public/main.js<|end_filename|>
/**
* Simple file to handle test results events from DAQ.
* Uses firebase for data management, and renders straight to HTML.
*/
const ROW_TIMEOUT_SEC = 500;
const display_columns = [];
const display_rows = [];
const row_timestamps = {};
const origin_id = getQueryParam('origin');
const site_name = getQueryParam('site');
const port_id = getQueryParam('port');
const registry_id = getQueryParam('registry');
const device_id = getQueryParam('device');
const run_id = getQueryParam('runid');
const from = getQueryParam('from');
const to = getQueryParam('to');
const data_state = {};
let last_result_time_sec = 0;
let heartbeatTimestamp = 0;
var db;
var activePorts = new Set();
document.addEventListener('DOMContentLoaded', () => {
db = firebase.firestore();
const settings = {
};
db.settings(settings);
});
function appendTestCell(row, column) {
const columnElement = document.createElement('td');
columnElement.setAttribute('label', column);
columnElement.setAttribute('row', row);
columnElement.classList.add('old');
const parent = document.querySelector(`#testgrid table tr[label="${row}"]`)
parent.appendChild(columnElement);
}
function ensureGridColumn(label, content) {
if (display_columns.indexOf(label) < 0) {
display_columns.push(label);
for (row of display_rows) {
appendTestCell(row, label);
}
}
setGridValue('header', label, undefined, content || label);
}
function ensureColumns(columns) {
for (column of columns) {
ensureGridColumn(column);
}
ensureGridColumn('info');
ensureGridColumn('timer');
}
function ensureGridRow(label, content) {
let added = false;
if (display_rows.indexOf(label) < 0) {
display_rows.push(label)
const testTable = document.querySelector("#testgrid table")
const rowElement = document.createElement('tr');
testTable.appendChild(rowElement)
rowElement.setAttribute('label', label)
for (column of display_columns) {
appendTestCell(label, column);
}
}
setGridValue(label, 'row', undefined, content || label);
return added;
}
function setGridValue(row, column, runid, value, append) {
const selector = `#testgrid table tr[label="${row}"] td[label="${column}"]`;
const targetElement = document.querySelector(selector);
if (targetElement) {
const previous = targetElement.getAttribute('runid');
if (!previous || !runid || runid >= previous) {
if (runid) {
targetElement.setAttribute('runid', runid);
}
if (value) {
if (append) {
targetElement.innerHTML += "<br />" + value;
} else {
targetElement.innerHTML = value;
targetElement.setAttribute('status', value);
}
}
}
const rowElement = document.querySelector(`#testgrid table tr[label="${row}"]`);
const rowTime = rowElement.getAttribute('runid');
const rowPrev = rowElement.getAttribute('prev');
updateTimeClass(targetElement, rowTime, rowPrev);
} else {
console.error('Could not find', selector);
}
return targetElement;
}
function setRowClass(row, timeout) {
const rowElement = document.querySelector(`#testgrid table tr[label="${row}"]`);
rowElement.classList.toggle('timeout', timeout);
}
function setRowState(row, new_runid) {
const rowElement = document.querySelector(`#testgrid table tr[label="${row}"]`);
let runid = rowElement.getAttribute('runid') || 0;
let prev = rowElement.getAttribute('prev') || 0;
console.debug('rowstate', row, 'mudgee', new_runid, runid, prev);
if (runid === new_runid) {
return;
} else if (!runid || new_runid > runid) {
rowElement.setAttribute('prev', runid);
rowElement.setAttribute('runid', new_runid);
prev = runid
runid = new_runid
} else if (!prev || new_runid > prev) {
rowElement.setAttribute('prev', new_runid);
prev = new_runid
} else {
return;
}
const allEntries = rowElement.querySelectorAll('td');
allEntries.forEach((entry) => {
updateTimeClass(entry, runid, prev);
});
}
function updateTimeClass(entry, target, prev) {
const value = entry.getAttribute('runid');
if (value === target) {
entry.classList.add('current');
entry.classList.remove('old', 'gone');
} else if (value === prev) {
entry.classList.add('old');
entry.classList.remove('current', 'gone');
} else {
entry.classList.add('gone');
entry.classList.remove('current', 'old');
}
}
function getQueryParam(field) {
var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
var string = reg.exec(window.location.href);
return string ? string[1] : null;
}
function statusUpdate(message, e) {
console.log(message);
if (e) {
console.error(e);
message = message + ' ' + String(e)
}
document.getElementById('status').innerHTML = message;
}
function getResultStatus(result) {
if (result.exception) {
return 'serr';
}
if (result.state) {
return result.state;
}
if (Number(result.code)) {
return 'merr';
}
return '????';
}
function handleFileLinks(row, runid, result) {
const paths = Object.keys(result).filter(key => key.indexOf("_path") >= 0);
if (paths.length) {
const col = result.name;
paths.forEach((path) => {
let name = path.replace("_path", "");
addReportBucket(row, col, runid, result[path], name);
})
}
}
function handleOriginResult(origin, port, runid, test, result) {
if (result.timestamp > last_result_time_sec) {
last_result_time_sec = result.timestamp;
}
if (!row_timestamps[port] || row_timestamps[port] < result.timestamp) {
row_timestamps[port] = result.timestamp;
}
if (test === "terminate") {
row_timestamps[port] = false;
}
const numPort = Number(port.replace('port', ''));
const href = `?origin=${origin}&port=${numPort}`;
ensureGridRow(port, `<a href="${href}">${port}</a>`);
ensureGridColumn(test);
const status = getResultStatus(result);
statusUpdate(`Updating ${port} ${test} run ${runid} with '${status}'.`)
setRowState(port, runid);
setGridValue(port, 'active', runid, activePorts.has(numPort) + "")
const gridElement = setGridValue(port, test, runid, status);
handleFileLinks(port, runid, result);
if (test === 'info') {
makeConfigLink(gridElement, status, port, runid);
}
if (test == 'startup') {
makeActivateLink(gridElement, port);
}
}
function handleFilterResult(origin, site, runid, test, result) {
const id = origin + runid;
if (result.timestamp > last_result_time_sec) {
last_result_time_sec = result.timestamp;
}
if ((!row_timestamps[id] && row_timestamps[id] !== false) || row_timestamps[id] < result.timestamp) {
row_timestamps[id] = result.timestamp;
}
if (test === "terminate") {
row_timestamps[id] = false;
}
ensureGridRow(id, runid);
setGridValue(id, 'origin', runid, origin);
setGridValue(id, 'port', runid, result.port);
setGridValue(id, 'site', runid, site);
ensureGridColumn(test);
const status = getResultStatus(result);
setRowState(id, runid);
const gridElement = setGridValue(id, test, runid, status);
handleFileLinks(id, runid, result);
if (test === 'info') {
makeConfigLink(gridElement, status, id, runid);
}
if (test == 'startup') {
makeActivateLink(gridElement, id);
}
}
function makeConfigLink(element, info, port, runid) {
const parts = info.split('/');
const deviceId = parts[0];
const deviceLink = document.createElement('a');
deviceLink.href = `config.html?origin=${origin_id}&device=${deviceId}&port=${port}&runid=${runid}`;
deviceLink.innerHTML = element.innerHTML;
element.innerHTML = '';
element.appendChild(deviceLink);
}
function activateRun(port) {
console.log('Activate run port', port);
const originDoc = db.collection('origin').doc(origin_id);
const controlDoc = originDoc.collection('control').doc(port).collection('config').doc('definition');
controlDoc.update({
'config.paused': false
});
}
function makeActivateLink(element, port) {
element.onclick = () => activateRun(port)
}
function addReportBucket(row, col, runid, path, name) {
const storage = firebase.app().storage();
if (!name) {
name = path;
}
storage.ref().child(path).getDownloadURL().then((url) => {
setGridValue(row, col, runid, `<a href="${url}">${name}</a>`, true);
}).catch((e) => {
console.error(e);
});
}
function watcherAdd(ref, collection, limit, handler) {
const base = ref.collection(collection);
const target = limit ? limit(base) : base;
target.onSnapshot((snapshot) => {
let delay = 100;
snapshot.docChanges().forEach((change) => {
if (change.type === 'added') {
setTimeout(() => handler(ref.collection(collection).doc(change.doc.id), change.doc.id), delay);
delay = delay + 100;
}
});
}, (e) => console.error(e));
}
function listSites() {
const linkGroup = document.querySelector('#listings .sites');
db.collection('site').get().then((snapshot) => {
snapshot.forEach((site_doc) => {
site = site_doc.id;
const siteLink = document.createElement('a');
siteLink.setAttribute('href', '/?site=' + site);
siteLink.innerHTML = site;
linkGroup.appendChild(siteLink);
linkGroup.appendChild(document.createElement('p'));
});
}).catch((e) => statusUpdate('registry list error', e));
}
function addOrigin(originId) {
db.collection('origin').doc(originId).get().then((result) => {
const linkGroup = document.querySelector('#listings .origins');
const originLink = document.createElement('a');
originLink.setAttribute('href', '/?origin=' + originId);
originLink.innerHTML = originId;
linkGroup.appendChild(originLink);
const originInfo = document.createElement('span');
const version = result.data() && result.data().version;
const updated = result.data() && result.data().updated;
originInfo.innerHTML = ` ${version}, ${updated}`;
linkGroup.appendChild(originInfo);
linkGroup.appendChild(document.createElement('p'));
});
}
function listOrigins() {
db.collection('origin').get().then((snapshot) => {
snapshot.forEach((originDoc) => {
addOrigin(originDoc.id);
});
}).catch((e) => statusUpdate('origin list error', e));
}
function listUsers() {
const link_group = document.querySelector('#listings .users');
db.collection('users').get().then((snapshot) => {
snapshot.forEach((user_doc) => {
const userLink = document.createElement('a');
userLink.innerHTML = user_doc.data().email
link_group.appendChild(userLink);
link_group.appendChild(document.createElement('p'));
});
}).catch((e) => statusUpdate('user list error', e));
}
function dashboardSetup() {
if (registry_id && device_id) {
triggerDevice(db, registry_id, device_id);
} else if (port_id || device_id || site_name || run_id || from || to) {
document.getElementById('filters').classList.add('active');
ensureGridRow('header');
ensureGridColumn('row', 'runid');
ensureGridColumn('origin');
ensureGridColumn('site');
ensureGridColumn('port');
document.getElementById('fromFilter').value = from;
document.getElementById('toFilter').value = to;
document.getElementById('deviceFilter').value = device_id;
document.getElementById('siteFilter').value = site_name;
document.getElementById('originFilter').value = origin_id;
document.getElementById('portFilter').value = port_id;
document.getElementById('runidFilter').value = run_id;
triggerFilter(db);
} else if (origin_id) {
ensureGridRow('header');
ensureGridColumn('row', 'port');
ensureGridColumn('active');
triggerOrigin(db, origin_id);
} else {
document.getElementById('listings').classList.add('active');
listOrigins();
listSites();
listUsers();
}
return origin_id;
}
function applyFilter() {
const filters = {
from: document.getElementById('fromFilter').value,
to: document.getElementById('toFilter').value,
site: document.getElementById('siteFilter').value,
origin: document.getElementById('originFilter').value,
port: document.getElementById('portFilter').value,
device: document.getElementById('deviceFilter').value,
runid: document.getElementById('runidFilter').value
};
const str = Object.keys(filters).map((filter) => {
return filter + "=" + filters[filter];
}).join('&');
document.location = "?" + str;
}
function showActivePorts(message) {
activePorts = new Set(message.ports);
const ports = document.querySelectorAll(`#testgrid table td[label="row"]`);
heartbeatTimestamp = message.timestamp;
ports.forEach((port) => {
const numPort = Number(port.innerText.replace('port', ''));
if (!numPort) {
return;
}
setGridValue("port" + numPort, "active", undefined, activePorts.has(numPort) + "");
if (activePorts.has(numPort) && (!row_timestamps["port" + numPort]
|| Math.floor((Date.now() - row_timestamps["port" + numPort]) / 1000.0) >= ROW_TIMEOUT_SEC)) {
row_timestamps["port" + numPort] = new Date();
const cols = document.querySelectorAll(`#testgrid table tr[label="port${numPort}"] td`);
cols.forEach((entry) => {
if (entry.innerText == port.innerText || entry.getAttribute("label") == "active") {
return;
}
entry.classList.add('old');
entry.classList.remove('current', 'gone');
});
}
});
}
function showMetadata(originId, showActive) {
db.collection('origin').doc(originId).collection('runner').doc('heartbeat').onSnapshot((result) => {
const message = result.data().message;
if (message.timestamp && message.timestamp < heartbeatTimestamp) {
return;
}
message.states && ensureColumns(message.states);
const description = document.querySelector('#description .description');
description.innerHTML = message.description;
description.href = `config.html?origin=${origin_id}`;
document.querySelector('#daq-version').innerHTML = message.version;
document.querySelector('#lsb-version').innerHTML = message.lsb;
document.querySelector('#sys-version').innerHTML = message.uname;
document.querySelector('#daq-versions').classList.add('valid');
if (showActive) {
showActivePorts(message);
}
});
}
function triggerOrigin(db, originId) {
const latest = (ref) => {
return ref.orderBy('updated', 'desc').limit(1);
};
const originRef = db.collection('origin').doc(originId);
showMetadata(originId, true);
watcherAdd(originRef, "port", undefined, (ref, port_id) => {
watcherAdd(ref, "runid", latest, (ref, runid_id) => {
ref = originRef.collection("runid").doc(runid_id);
watcherAdd(ref, "test", undefined, (ref, test_id) => {
ref.onSnapshot((result) => {
// TODO: Handle results going away.
handleOriginResult(originId, port_id, runid_id, test_id, result.data());
});
});
});
});
}
function triggerFilter(db) {
const filters = {
siteName: site_name,
port: Number(port_id),
deviceId: device_id,
from,
to
};
const filtered = (ref) => {
ref = ref.orderBy('updated', "desc");
for (let filter in filters) {
let value = filters[filter];
if (value) {
let op = "==";
if (filter == "to" || filter == "from") {
op = filter == "to" ? "<=" : ">=";
value = value.replace('"', '');
value += (filter == "to" ? "\uf8FF" : "");
filter = "updated";
}
ref = ref.where(filter, op, value);
}
}
// Gonna wait to do pagination.
return ref.limit(100);
};
const processOrigin = (originId) => {
const ref = db.collection('origin').doc(originId);
if (run_id) {
const runIds = run_id.split(',');
runIds.map((runId) => {
const runDoc = db.collection('origin').doc(originId).collection('runid').doc(runId);
runDoc.get().then((doc) => {
const data = doc.data();
const site = data && data.siteName;
const port = data && data.port;
const deviceId = data && data.deviceId;
const updated = data && new Date(data.updated);
if ((filters.siteName && filters.siteName != site)
|| (filters.port && filters.port != port)
|| (filters.deviceId && filters.deviceId != deviceId)
|| (filters.from && new Date(filters.from) > updated)
|| (filters.to && (Number(new Date(filters.to)) + 60 * 24 * 60 * 1000) < updated)) {
return;
}
watcherAdd(runDoc, "test", undefined, (ref, test_id) => {
ref.onSnapshot((result) => {
// TODO: Handle results going away.
handleFilterResult(originId, site, runId, test_id, result.data());
});
});
});
});
} else {
watcherAdd(ref, "runid", filtered, (ref, runid_id) => {
ref.get().then((runDoc) => {
const site = runDoc.data() && runDoc.data().siteName;
watcherAdd(ref, "test", undefined, (ref, test_id) => {
ref.onSnapshot((result) => {
// TODO: Handle results going away.
handleFilterResult(originId, site, runid_id, test_id, result.data());
});
});
});
});
}
};
if (origin_id) {
showMetadata(origin_id);
processOrigin(origin_id);
} else {
db.collection('origin').get().then((collection) => {
const origins = collection.docs;
origins.map((origin, i) => {
if (i == 0) {
showMetadata(origin.id);
}
processOrigin(origin.id);
})
});
}
}
function triggerDevice(db, registry_id, device_id) {
statusUpdate('Setup device trigger ' + device_id);
db
.collection('registry').doc(registry_id)
.collection('device').doc(device_id)
.collection('telemetry').doc('latest')
.onSnapshot((snapshot) => {
statusUpdate('');
const hue = Math.floor(snapshot.data().random * 360);
const hsl = `hsl(${hue}, 80%, 50%)`;
document.body.style.backgroundColor = hsl;
});
}
function interval_updater() {
if (last_result_time_sec) {
const timeDeltaSec = Math.floor(Date.now() / 1000.0 - last_result_time_sec);
document.getElementById('update').innerHTML = `Last update ${timeDeltaSec} sec ago.`
}
for (const row in row_timestamps) {
const lastUpdate = new Date(row_timestamps[row]);
const timeDeltaSec = Math.floor((Date.now() - lastUpdate) / 1000.0);
const selector = `#testgrid table tr[label="${row}"`;
const runid = document.querySelector(selector).getAttribute('runid');
if (row_timestamps[row] === false || timeDeltaSec >= ROW_TIMEOUT_SEC) {
setGridValue(row, 'timer', runid, row_timestamps[row] ? 'Timed Out' : 'Done');
setRowClass(row, true);
} else {
setGridValue(row, 'timer', runid, `${timeDeltaSec}s`);
setRowClass(row, false);
}
}
}
function applySchema(editor, schema_url) {
if (!schema_url) {
return;
}
// Not sure why this is required, but without it the system complains it's not defined??!?!
const refs = {
'http://json-schema.org/draft-07/schema#': true
};
console.log(`Loading editor schema ${schema_url}`);
fetch(schema_url)
.then(response => response.json())
.then(json => editor.setSchema(json, refs))
.catch(rejection => console.log(rejection));
}
function getJsonEditor(container_id, onChange, schema_url) {
const container = document.getElementById(container_id);
const options = {
mode: onChange ? 'code' : 'view',
onChange: onChange
};
const editor = new JSONEditor(container, options);
applySchema(editor, schema_url);
return editor;
}
function setDatedStatus(attribute, value) {
data_state[attribute] = value;
const element = document.getElementById('config_body');
element.classList.toggle('dirty', !!(data_state.dirty > data_state.saved || (data_state.dirty && !data_state.saved)));
element.classList.toggle('saving', data_state.pushed > data_state.saved);
element.classList.toggle('dated', data_state.saved > data_state.updated);
element.classList.toggle('provisional', data_state.provisional);
}
function pushConfigChange(config_editor, config_doc) {
const json = config_editor.get();
const timestamp = new Date().toJSON();
config_doc.update({
'config': json,
'timestamp': timestamp
}).then(() => {
setDatedStatus('pushed', timestamp);
});
}
function setDirtyState() {
setDatedStatus('dirty', new Date().toJSON());
}
function loadEditor(config_doc, element_id, label, onConfigEdit, schema) {
const editor = getJsonEditor(element_id, onConfigEdit, schema);
editor.setName(label);
editor.set(null);
config_doc.onSnapshot((snapshot) => {
const firstUpdate = editor.get() == null;
let snapshot_data = snapshot.data();
snapshot_data && editor.update(snapshot_data.config);
if (firstUpdate && editor.expandAll) {
editor.expandAll();
}
if (onConfigEdit) {
setDatedStatus('saved', snapshot_data && snapshot_data.saved);
} else {
setDatedStatus('updated', snapshot_data && snapshot_data.updated);
const snapshot_config = (snapshot_data && snapshot_data.config && snapshot_data.config.config) || {};
setDatedStatus('provisional', !snapshot_config.run_info);
}
});
return editor;
}
function loadJsonEditors() {
let latest_doc;
let config_doc;
let schema_url;
const subtitle = device_id
? `${origin_id} device ${device_id}`
: `${origin_id} system`;
document.getElementById('title_origin').innerHTML = subtitle;
document.getElementById('dashboard_link').href = `index.html?origin=${origin_id}`
const origin_doc = db.collection('origin').doc(origin_id);
if (device_id) {
config_doc = origin_doc.collection('device').doc(device_id).collection('config').doc('definition');
latest_doc = origin_doc.collection('device').doc(device_id).collection('config').doc('latest');
schema_url = 'schema_device.json';
} else {
config_doc = origin_doc.collection('runner').doc('setup').collection('config').doc('definition');
latest_doc = origin_doc.collection('runner').doc('setup').collection('config').doc('latest');
schema_url = 'schema_system.json';
}
// Prefill module configs from the latest config
Promise.all([latest_doc.get(), config_doc.get()]).then((docs) => {
latest_doc_resolved = docs[0].data();
config_doc_resolved = docs[1].data();
if (!config_doc_resolved) {
config_doc_resolved = {};
}
if ((!config_doc_resolved.config || JSON.stringify(config_doc_resolved.config) == "{}") && latest_doc_resolved.config.config) {
config_doc_resolved.config = { modules: latest_doc_resolved.config.config.modules }
return config_doc.set(config_doc_resolved);
}
}).then(() => {
loadEditor(latest_doc, 'latest_editor', 'latest', null);
const config_editor = loadEditor(config_doc, 'config_editor', 'config', setDirtyState, schema_url);
document.querySelector('#config_body .save_button').onclick = () => pushConfigChange(config_editor, config_doc)
});
}
function authenticated(userData) {
if (!userData) {
statusUpdate('Authentication failed, please sign in.');
return;
}
const perm_doc = db.collection('permissions').doc(userData.uid);
const user_doc = db.collection('users').doc(userData.uid);
const timestamp = new Date().toJSON();
user_doc.set({
name: userData.displayName,
email: userData.email,
updated: timestamp
}).then(function () {
statusUpdate('User info updated');
perm_doc.get().then((doc) => {
if (doc.exists && doc.data().enabled) {
setupUser();
} else {
statusUpdate('User not enabled, contact your system administrator.');
}
});
}).catch((e) => statusUpdate('Error updating user info', e));
}
function setupUser() {
try {
if (document.getElementById('config_editor')) {
loadJsonEditors();
} else {
dashboardSetup();
}
statusUpdate('System initialized.');
setInterval(interval_updater, 1000);
} catch (e) {
statusUpdate('Loading error', e);
}
}
<|start_filename|>subset/connection/mac_oui/src/main/java/Main.java<|end_filename|>
public class Main {
public static void main(String[] args) {
if (args.length != 1) {
throw new IllegalArgumentException("Usage: target_mac");
}
String macAddress = args[0];
System.out.println("Main Started...");
RetrieveList setupTest = new RetrieveList(macAddress);
setupTest.startTest();
}
}
<|start_filename|>subset/bacnet/bacnetTests/src/main/java/FauxDeviceEngine/helper/Device.java<|end_filename|>
package FauxDeviceEngine.helper;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.exception.BACnetServiceException;
import com.serotonin.bacnet4j.obj.BACnetObject;
import com.serotonin.bacnet4j.type.Encodable;
import com.serotonin.bacnet4j.type.enumerated.PropertyIdentifier;
import java.util.Map;
public class Device {
public void addProperty(BACnetObject bacnetObjectType, PropertyIdentifier propertyIdentifier, Encodable encodable) {
try {
bacnetObjectType.setProperty(propertyIdentifier, encodable);
} catch (BACnetServiceException e) {
System.err.println("Error adding bacnet property: " + e.getMessage() + propertyIdentifier.toString());
}
}
public void addObjectType(LocalDevice localDevice, BACnetObject bacnetObject, Map<String, String> map) {
try {
localDevice.addObject(bacnetObject);
} catch (BACnetServiceException e) {
System.err.println("Error adding bacnet object: " + e.getMessage() + " " + map.toString());
}
}
public boolean[] castToArrayBoolean(String string_of_booleans) {
String[] booleans_arr = string_of_booleans.split(" ");
boolean[] array = new boolean[booleans_arr.length];
for (int i = 0; i < booleans_arr.length; i++) {
array[i] = Boolean.parseBoolean(booleans_arr[i]);
}
return array;
}
}
<|start_filename|>subset/bacnet/bacnetTests/src/main/java/helper/BacnetPoints.java<|end_filename|>
package helper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.RemoteDevice;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.type.constructed.ObjectPropertyReference;
import com.serotonin.bacnet4j.type.constructed.SequenceOf;
import com.serotonin.bacnet4j.type.enumerated.ObjectType;
import com.serotonin.bacnet4j.type.enumerated.PropertyIdentifier;
import com.serotonin.bacnet4j.type.primitive.ObjectIdentifier;
import com.serotonin.bacnet4j.util.PropertyReferences;
import com.serotonin.bacnet4j.util.PropertyValues;
import com.serotonin.bacnet4j.util.RequestUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BacnetPoints {
private Multimap<String, Map<String, String>> bacnetPointsMap = ArrayListMultimap.create();
String propertyErrorMessage = "errorClass=Property, errorCode=Unknown property";
public void get(LocalDevice localDevice) throws BACnetException {
for (RemoteDevice remoteDevice : localDevice.getRemoteDevices()) {
RequestUtils.getExtendedDeviceInformation(localDevice, remoteDevice);
@SuppressWarnings("unchecked")
List<ObjectIdentifier> allObjectsIdentifier =
((SequenceOf<ObjectIdentifier>)
RequestUtils.sendReadPropertyAllowNull(
localDevice,
remoteDevice,
remoteDevice.getObjectIdentifier(),
PropertyIdentifier.objectList))
.getValues();
for (ObjectIdentifier objectIdentifier : allObjectsIdentifier) {
try {
PropertyReferences refs = new PropertyReferences();
refs.add(objectIdentifier, PropertyIdentifier.all);
PropertyValues propertyValues =
RequestUtils.readProperties(localDevice, remoteDevice, refs, null);
for (ObjectPropertyReference objectPropertyReference : propertyValues) {
if (!propertyValues
.getNoErrorCheck(objectPropertyReference)
.toString()
.equals(propertyErrorMessage)) {
String bacnetObjectType = objectPropertyReference.getObjectIdentifier().toString();
String bacnetObjectProperty =
objectPropertyReference.getPropertyIdentifier().toString();
String bacnetPropertyValue =
propertyValues.getNoErrorCheck(objectPropertyReference).toString();
Map<String, String> properties = new HashMap<>();
properties.put(bacnetObjectProperty, bacnetPropertyValue);
bacnetPointsMap.put(bacnetObjectType, properties);
}
}
} catch (Exception e) {
System.out.println("Error "+ objectIdentifier + " " + e.getMessage() + "\n");
}
}
}
}
public Multimap<String, Map<String, String>> getBacnetPointsMap() {
return bacnetPointsMap;
}
}
<|start_filename|>subset/bacnet/bacnetTests/src/main/java/FauxDeviceEngine/Analog.java<|end_filename|>
package FauxDeviceEngine;
import FauxDeviceEngine.helper.Device;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.exception.BACnetServiceException;
import com.serotonin.bacnet4j.obj.BACnetObject;
import com.serotonin.bacnet4j.type.Encodable;
import com.serotonin.bacnet4j.type.constructed.*;
import com.serotonin.bacnet4j.type.enumerated.*;
import com.serotonin.bacnet4j.type.primitive.CharacterString;
import com.serotonin.bacnet4j.type.primitive.Real;
import com.serotonin.bacnet4j.type.primitive.UnsignedInteger;
import java.util.Map;
public class Analog {
private float presentValue = 0.0f;
private String objectName = "";
private String deviceType = "";
private float deadband = 0.0f;
private boolean outOfService = false;
private float resolution = 0.0f;
private boolean[] eventEnable = new boolean[3];
private int eventState = 0;
private int objectType = 0;
private int timeDelayNormal = 0;
private float lowLimit = 0;
private boolean[] limitEnable = new boolean[2];
private float covIncrement = 0.0f;
private boolean[] statusFlags = new boolean[4];
private int updateInterval = 0;
private boolean[] ackedTransitions = new boolean[3];
private float highLimit = 0;
private int notifyType = 0;
private boolean eventDetectionEnable = false;
private float minPresValue = 0.0f;
private float maxPresValue = 0.0f;
private int reliability = 0;
private SequenceOf<EventTransitionBits> eventTransitionBits = new SequenceOf<EventTransitionBits>();
private int notificationClass = 0;
private String description = "";
private boolean eventAlgorithmInhibit = false;
private int units = 0;
private String profileName = "";
private float relinquishDefault = 0.0f;
private boolean priorityArray = false;
Device device = new Device();
public Analog(LocalDevice localDevice, BACnetObject bacnetObjectType, Map<String, String>bacnetObjectMap) {
for(Map.Entry<String, String> map : bacnetObjectMap.entrySet()) {
String propertyName = map.getKey();
String propertyValue = map.getValue();
addObjectProperty(bacnetObjectType, propertyName, propertyValue);
}
device.addObjectType(localDevice, bacnetObjectType, bacnetObjectMap);
}
private void addObjectProperty(BACnetObject bacnetObjectType, String objectProperty, String propertyValue) {
Encodable encodable;
switch (objectProperty) {
case "Present_Value":
presentValue = Float.parseFloat(propertyValue);
encodable = new Real(presentValue);
device.addProperty(bacnetObjectType, PropertyIdentifier.presentValue, encodable);
break;
case "Object_Name":
objectName = propertyValue;
encodable = new CharacterString(objectName);
device.addProperty(bacnetObjectType, PropertyIdentifier.objectName, encodable);
break;
case "Device_Type":
deviceType = propertyValue;
encodable = new CharacterString(deviceType);
device.addProperty(bacnetObjectType, PropertyIdentifier.deviceType, encodable);
break;
case "Deadband":
deadband = Float.parseFloat(propertyValue);
encodable = new Real(deadband);
device.addProperty(bacnetObjectType, PropertyIdentifier.deadband, encodable);
break;
case "Out_Of_Service":
outOfService = Boolean.valueOf(propertyValue);
encodable = new com.serotonin.bacnet4j.type.primitive.Boolean(outOfService);
device.addProperty(bacnetObjectType, PropertyIdentifier.outOfService, encodable);
break;
case "Resolution" :
resolution = Float.parseFloat(propertyValue);
encodable = new Real(resolution);
device.addProperty(bacnetObjectType, PropertyIdentifier.resolution, encodable);
break;
case "Event_Enable":
eventEnable = device.castToArrayBoolean(propertyValue);
encodable = new EventTransitionBits(eventEnable[0], eventEnable[1], eventEnable[2]);
device.addProperty(bacnetObjectType, PropertyIdentifier.eventEnable, encodable);
break;
case "Event_State":
eventState = Integer.parseInt(propertyValue);
encodable = new EventState(eventState);
device.addProperty(bacnetObjectType, PropertyIdentifier.eventState, encodable);
break;
case "Object_Type":
objectType = Integer.parseInt(propertyValue);
encodable = new ObjectType(objectType);
device.addProperty(bacnetObjectType, PropertyIdentifier.objectType, encodable);
break;
case "Time_Delay_Normal":
timeDelayNormal = Integer.parseInt(propertyValue);
encodable = new UnsignedInteger(timeDelayNormal);
device.addProperty(bacnetObjectType, PropertyIdentifier.timeDelayNormal, encodable);
break;
case "Low_Limit":
lowLimit = Float.parseFloat(propertyValue);
encodable = new Real(lowLimit);
device.addProperty(bacnetObjectType, PropertyIdentifier.lowLimit, encodable);
break;
case "Limit_Enable":
limitEnable = device.castToArrayBoolean(propertyValue);
encodable = new LimitEnable(limitEnable[0], limitEnable[1]);
device.addProperty(bacnetObjectType, PropertyIdentifier.limitEnable, encodable);
break;
case "Cov_Increment":
covIncrement = Float.parseFloat(propertyValue);
encodable = new Real(covIncrement);
device.addProperty(bacnetObjectType, PropertyIdentifier.covIncrement, encodable);
break;
case "Status_Flags":
statusFlags = device.castToArrayBoolean(propertyValue);
encodable = new StatusFlags(statusFlags[0], statusFlags[1], statusFlags[2], statusFlags[3]);
device.addProperty(bacnetObjectType, PropertyIdentifier.statusFlags, encodable);
break;
case "Update_Interval":
updateInterval = Integer.parseInt(propertyValue);
encodable = new UnsignedInteger(updateInterval);
device.addProperty(bacnetObjectType, PropertyIdentifier.updateInterval, encodable);
break;
case "Acked_Transitions":
ackedTransitions = device.castToArrayBoolean(propertyValue);
encodable = new EventTransitionBits(ackedTransitions[0], ackedTransitions[1], ackedTransitions[2]);
device.addProperty(bacnetObjectType, PropertyIdentifier.ackedTransitions, encodable);
break;
case "High_Limit":
highLimit = Float.parseFloat(propertyValue);
encodable = new Real(highLimit);
device.addProperty(bacnetObjectType, PropertyIdentifier.highLimit, encodable);
break;
case "Notify_Type":
notifyType = Integer.parseInt(propertyValue);
encodable = new NotifyType(notifyType);
device.addProperty(bacnetObjectType, PropertyIdentifier.notifyType, encodable);
break;
case "Event_Detection_Enable":
eventDetectionEnable = Boolean.parseBoolean(propertyValue);
encodable = new com.serotonin.bacnet4j.type.primitive.Boolean(eventDetectionEnable);
device.addProperty(bacnetObjectType, PropertyIdentifier.eventDetectionEnable, encodable);
break;
case "Max_Pres_Value":
maxPresValue = Float.parseFloat(propertyValue);
encodable = new Real(maxPresValue);
device.addProperty(bacnetObjectType, PropertyIdentifier.maxPresValue, encodable);
break;
case "Min_Pres_Value":
minPresValue = Float.parseFloat(propertyValue);
encodable = new Real(minPresValue);
device.addProperty(bacnetObjectType, PropertyIdentifier.minPresValue, encodable);
break;
case "Reliability":
reliability = Integer.parseInt(propertyValue);
encodable = new Reliability(reliability);
device.addProperty(bacnetObjectType, PropertyIdentifier.reliability, encodable);
break;
case "Event_Message_Texts":
if(Boolean.parseBoolean(propertyValue)) {
eventTransitionBits = new SequenceOf<EventTransitionBits>();
encodable = eventTransitionBits;
device.addProperty(bacnetObjectType, PropertyIdentifier.eventMessageTexts, encodable);
}
break;
case "Notification_Class":
notificationClass = Integer.parseInt(propertyValue);
encodable = new UnsignedInteger(notificationClass);
device.addProperty(bacnetObjectType, PropertyIdentifier.notificationClass, encodable);
break;
case "Description":
description = propertyValue;
encodable = new CharacterString(description);
device.addProperty(bacnetObjectType, PropertyIdentifier.description, encodable);
break;
case "Event_Algorithm_Inhibit":
eventAlgorithmInhibit = Boolean.parseBoolean(propertyValue);
encodable = new com.serotonin.bacnet4j.type.primitive.Boolean(eventAlgorithmInhibit);
device.addProperty(bacnetObjectType, PropertyIdentifier.eventAlgorithmInhibit, encodable);
break;
case "Units":
units = Integer.parseInt(propertyValue);
encodable = new EngineeringUnits(units);
device.addProperty(bacnetObjectType, PropertyIdentifier.units, encodable);
break;
case "Profile_Name":
profileName = propertyValue;
encodable = new CharacterString(profileName);
device.addProperty(bacnetObjectType, PropertyIdentifier.profileName, encodable);
break;
case "Relinquish_Default":
relinquishDefault = Float.parseFloat(propertyValue);
encodable = new Real(relinquishDefault);
device.addProperty(bacnetObjectType, PropertyIdentifier.relinquishDefault, encodable);
break;
case "Priority_Array":
priorityArray = Boolean.parseBoolean(propertyValue);
if(priorityArray) {
encodable = new PriorityArray();
device.addProperty(bacnetObjectType, PropertyIdentifier.priorityArray, encodable);
}
break;
default:
throw new IllegalArgumentException(objectProperty + " not found.");
}
}
}
<|start_filename|>subset/bacnet/bacnetTests/src/main/java/helper/BacnetValidation.java<|end_filename|>
package helper;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.RemoteDevice;
import java.util.List;
public class BacnetValidation {
LocalDevice localDevice = null;
public BacnetValidation(LocalDevice localDevice) {
this.localDevice = localDevice;
}
public boolean checkIfBacnetSupported() {
List<RemoteDevice> remoteDevices = localDevice.getRemoteDevices();
if (remoteDevices.size() > 0) {
return true;
}
return false;
}
}
<|start_filename|>subset/bacnet/bacnetTests/src/main/java/helper/Connection.java<|end_filename|>
package helper;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.RemoteDevice;
import com.serotonin.bacnet4j.RemoteObject;
import com.serotonin.bacnet4j.event.DeviceEventListener;
import com.serotonin.bacnet4j.exception.BACnetServiceException;
import com.serotonin.bacnet4j.npdu.ip.IpNetwork;
import com.serotonin.bacnet4j.obj.BACnetObject;
import com.serotonin.bacnet4j.service.confirmed.ReinitializeDeviceRequest.ReinitializedStateOfDevice;
import com.serotonin.bacnet4j.transport.Transport;
import com.serotonin.bacnet4j.type.Encodable;
import com.serotonin.bacnet4j.type.constructed.Choice;
import com.serotonin.bacnet4j.type.constructed.DateTime;
import com.serotonin.bacnet4j.type.constructed.PropertyValue;
import com.serotonin.bacnet4j.type.constructed.SequenceOf;
import com.serotonin.bacnet4j.type.constructed.TimeStamp;
import com.serotonin.bacnet4j.type.enumerated.EventState;
import com.serotonin.bacnet4j.type.enumerated.EventType;
import com.serotonin.bacnet4j.type.enumerated.MessagePriority;
import com.serotonin.bacnet4j.type.enumerated.NotifyType;
import com.serotonin.bacnet4j.type.notificationParameters.NotificationParameters;
import com.serotonin.bacnet4j.type.primitive.Boolean;
import com.serotonin.bacnet4j.type.primitive.CharacterString;
import com.serotonin.bacnet4j.type.primitive.ObjectIdentifier;
import com.serotonin.bacnet4j.type.primitive.UnsignedInteger;
public class Connection {
private LocalDevice localDevice;
private IpNetwork network;
private boolean terminate;
private final int deviceId = (int) Math.floor(Math.random() * 1000.0);
public Connection(String broadcastAddress, int port) throws BACnetServiceException, Exception {
this(broadcastAddress, port, IpNetwork.DEFAULT_BIND_IP);
}
public Connection(String broadcastAddress, int port, String localAddress)
throws BACnetServiceException, Exception {
network = new IpNetwork(broadcastAddress, port, IpNetwork.DEFAULT_BIND_IP, 0, localAddress);
System.out.println("Creating LoopDevice id " + deviceId);
Transport transport = new Transport(network);
transport.setTimeout(1000);
localDevice = new LocalDevice(deviceId, transport);
try {
localDevice
.getEventHandler()
.addListener(
new DeviceEventListener() {
@Override
public void listenerException(Throwable e) {
System.out.println("loopDevice listenerException");
}
@Override
public void iAmReceived(RemoteDevice d) {
System.out.println("loopDevice iAmReceived");
}
@Override
public boolean allowPropertyWrite(BACnetObject obj, PropertyValue pv) {
System.out.println("loopDevice allowPropertyWrite");
return true;
}
@Override
public void propertyWritten(BACnetObject obj, PropertyValue pv) {
System.out.println("loopDevice propertyWritten");
}
@Override
public void iHaveReceived(RemoteDevice d, RemoteObject o) {
System.out.println("loopDevice iHaveReceived");
}
@Override
public void covNotificationReceived(
UnsignedInteger subscriberProcessIdentifier,
RemoteDevice initiatingDevice,
ObjectIdentifier monitoredObjectIdentifier,
UnsignedInteger timeRemaining,
SequenceOf<PropertyValue> listOfValues) {
System.out.println("loopDevice covNotificationReceived");
}
@Override
public void eventNotificationReceived(
UnsignedInteger processIdentifier,
RemoteDevice initiatingDevice,
ObjectIdentifier eventObjectIdentifier,
TimeStamp timeStamp,
UnsignedInteger notificationClass,
UnsignedInteger priority,
EventType eventType,
CharacterString messageText,
NotifyType notifyType,
Boolean ackRequired,
EventState fromState,
EventState toState,
NotificationParameters eventValues) {
System.out.println("loopDevice eventNotificationReceived");
}
@Override
public void textMessageReceived(
RemoteDevice textMessageSourceDevice,
Choice messageClass,
MessagePriority messagePriority,
CharacterString message) {
System.out.println("loopDevice textMessageReceived");
}
@Override
public void privateTransferReceived(
UnsignedInteger vendorId,
UnsignedInteger serviceNumber,
Encodable serviceParameters) {
System.out.println("loopDevice privateTransferReceived");
}
@Override
public void reinitializeDevice(
ReinitializedStateOfDevice reinitializedStateOfDevice) {
System.out.println("loopDevice reinitializeDevice");
}
@Override
public void synchronizeTime(DateTime dateTime, boolean utc) {
System.out.println("loopDevice synchronizeTime");
}
});
localDevice.initialize();
} catch (RuntimeException e) {
System.out.println("Error: " + e.getMessage());
localDevice.terminate();
localDevice = null;
throw e;
}
}
/** @return the terminate */
public boolean isTerminate() {
return terminate;
}
/** @param terminate the terminate to set */
public void doTerminate() {
terminate = true;
localDevice.terminate();
synchronized (this) {
notifyAll();
}
}
/** @return the localDevice */
public LocalDevice getLocalDevice() {
return localDevice;
}
}
<|start_filename|>subset/bacnet/bacnetTests/src/main/java/helper/Report.java<|end_filename|>
package helper;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class Report {
String reportFilename = "tmp/report.txt";
public Report(String reportFilename) {
this.reportFilename = reportFilename;
}
public void writeReport(String report) {
try {
String[] directory = reportFilename.split("/");
File dir = new File(directory[directory.length - 2]);
if (!dir.exists()) {
dir.mkdirs();
}
BufferedWriter writer = new BufferedWriter(new FileWriter(reportFilename));
writer.write(report);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| jcbrough/daq |
<|start_filename|>Makefile<|end_filename|>
INSTALL ?= install
NIXOS_SHELL ?= $(shell nix-build --no-out-link default.nix)/bin/nixos-shell
all:
test:
$(NIXOS_SHELL) examples/vm.nix
test-resources:
$(NIXOS_SHELL) examples/vm-resources.nix
test-forward:
$(NIXOS_SHELL) examples/vm-forward.nix
test-graphics:
$(NIXOS_SHELL) examples/vm-graphics.nix
test-mounts:
$(NIXOS_SHELL) examples/vm-mounts.nix
test-efi:
$(NIXOS_SHELL) examples/vm-efi.nix
install:
$(INSTALL) -D bin/nixos-shell $(DESTDIR)$(PREFIX)/bin/nixos-shell
$(INSTALL) -D share/nixos-shell/nixos-shell.nix $(DESTDIR)$(PREFIX)/share/nixos-shell/nixos-shell.nix
| mkg20001/nixos-shell |
<|start_filename|>clearbit/examples_test.go<|end_filename|>
package clearbit_test
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"time"
"github.com/clearbit/clearbit-go/clearbit"
)
func handleError(err error, resp *http.Response) {
fmt.Printf("%#v\n%s\n", err, resp.Status)
}
func mockClearbitServer() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// mock combined response
if strings.Contains(r.URL.Path, "/v2/combined/find") {
time.Sleep(5 * time.Second)
_, _ = w.Write([]byte(`{
"person": {
"name": {
"fullName": "<NAME>"
}
},
"company": {
"name": "Clearbit"
}
}`))
return
}
// mock person response
if strings.Contains(r.URL.Path, "/v2/people/find") {
time.Sleep(5 * time.Second)
_, _ = w.Write([]byte(`{
"name": {
"fullName": "<NAME>"
}
}`))
return
}
// mock discovery response
if strings.Contains(r.URL.Path, "/v1/companies/search") {
time.Sleep(5 * time.Second)
_, _ = w.Write([]byte(`{
"results": [
{
"domain": "clearbit.com"
}
]
}`))
return
}
// mock company response
if strings.Contains(r.URL.Path, "/v2/companies/find") {
time.Sleep(5 * time.Second)
_, _ = w.Write([]byte(`{
"name": "Clearbit"
}`))
return
}
if strings.Contains(r.URL.Path, "/v1/people/search") {
// mock prospector with roles param response
if _, ok := r.URL.Query()["roles[]"]; ok {
time.Sleep(5 * time.Second)
_, _ = w.Write([]byte(`{
"results": [
{"role": "sales"},
{"role": "sales"},
{"role": "engineering"},
{"role": "engineering"},
{"role": "sales"}
]
}`))
return
}
// mock prospector without roles param response
time.Sleep(5 * time.Second)
_, _ = w.Write([]byte(`{
"results": [
{"email": "<EMAIL>"}
]
}`))
return
}
// mock autocomplete response
if strings.Contains(r.URL.Path, "/v1/companies/suggest") {
time.Sleep(5 * time.Second)
_, _ = w.Write([]byte(`[
{"domain": "clearbit.com"}
]`))
return
}
// mock name to domain response
if strings.Contains(r.URL.Path, "/v1/domains/find") {
time.Sleep(5 * time.Second)
_, _ = w.Write([]byte(`{
"domain": "uber.com"
}`))
return
}
// mock reveal response
if strings.Contains(r.URL.Path, "/v1/companies/find") {
time.Sleep(5 * time.Second)
_, _ = w.Write([]byte(`{
"company": {
"name": "Clearbit"
}
}`))
return
}
// mock risk response
if strings.Contains(r.URL.Path, "/v1/calculate") {
time.Sleep(5 * time.Second)
_, _ = w.Write([]byte(`{
"risk": {
"score": 0
}
}`))
return
}
w.WriteHeader(http.StatusNotFound)
}))
}
var clearbitServer = mockClearbitServer()
func ExampleNewClient_manuallyConfiguringEverything_output() {
client := clearbit.NewClient(
clearbit.WithHTTPClient(&http.Client{}),
clearbit.WithTimeout(20*time.Second),
clearbit.WithBaseURLs(map[string]string{"discovery": clearbitServer.URL}),
)
_, resp, _ := client.Discovery.Search(clearbit.DiscoverySearchParams{
Query: "name:clearbit",
})
fmt.Println(resp.Status)
// Output: 200 OK
}
func ExampleRiskService_Calculate_output() {
client := clearbit.NewClient(clearbit.WithBaseURLs(map[string]string{"risk": clearbitServer.URL}))
results, resp, err := client.Risk.Calculate(clearbit.RiskCalculateParams{
Email: "<EMAIL>",
Name: "<NAME>",
IP: "127.0.0.1",
})
if err == nil {
fmt.Println(results.Risk.Score, resp.Status)
} else {
handleError(err, resp)
}
// Output: 0 200 OK
}
func ExampleRevealService_Find_output() {
client := clearbit.NewClient(clearbit.WithBaseURLs(map[string]string{"reveal": clearbitServer.URL}))
results, resp, err := client.Reveal.Find(clearbit.RevealFindParams{
IP: "172.16.17.32",
})
if err == nil {
fmt.Println(results.Company.Name, resp.Status)
} else {
handleError(err, resp)
}
// Output: Clearbit 200 OK
}
func ExampleAutocompleteService_Suggest_output() {
client := clearbit.NewClient(clearbit.WithBaseURLs(map[string]string{"autocomplete": clearbitServer.URL}))
results, resp, err := client.Autocomplete.Suggest(clearbit.AutocompleteSuggestParams{
Query: "clearbit",
})
if err == nil {
fmt.Println(results[0].Domain, resp.Status)
} else {
handleError(err, resp)
}
// Output: clearbit.com 200 OK
}
func ExampleNameToDomainService_Find_output() {
client := clearbit.NewClient(clearbit.WithBaseURLs(map[string]string{"nameToDomain": clearbitServer.URL}))
result, resp, err := client.NameToDomain.Find(clearbit.NameToDomainFindParams{
Name: "Uber",
})
if err == nil {
fmt.Println(result.Domain, resp.Status)
} else {
handleError(err, resp)
}
// Output: uber.com 200 OK
}
func ExampleProspectorService_Search_output() {
client := clearbit.NewClient(clearbit.WithBaseURLs(map[string]string{"prospector": clearbitServer.URL}))
results, resp, err := client.Prospector.Search(clearbit.ProspectorSearchParams{
Domain: "clearbit.com",
})
if err == nil {
fmt.Println(results.Results[0].Email, resp.Status)
} else {
handleError(err, resp)
}
// Output: <EMAIL> 200 OK
}
func ExampleProspectorService_Search_withRoles_Output() {
client := clearbit.NewClient(clearbit.WithBaseURLs(map[string]string{"prospector": clearbitServer.URL}))
results, resp, err := client.Prospector.Search(clearbit.ProspectorSearchParams{
Domain: "clearbit.com",
Roles: []string{"sales", "engineering"},
})
if err == nil {
fmt.Println(len(results.Results), resp.Status)
} else {
handleError(err, resp)
}
// Output: 5 200 OK
}
func ExampleCompanyService_Find_output() {
client := clearbit.NewClient(clearbit.WithBaseURLs(map[string]string{"company": clearbitServer.URL}))
results, resp, err := client.Company.Find(clearbit.CompanyFindParams{
Domain: "clearbit.com",
})
if err == nil {
fmt.Println(results.Name, resp.Status)
} else {
handleError(err, resp)
}
// Output: Clearbit 200 OK
}
func ExamplePersonService_Find_output() {
client := clearbit.NewClient(clearbit.WithBaseURLs(map[string]string{"person": clearbitServer.URL}))
results, resp, err := client.Person.Find(clearbit.PersonFindParams{
Email: "<EMAIL>",
})
if err == nil {
fmt.Println(results.Name.FullName, resp.Status)
} else {
handleError(err, resp)
}
// Output: <NAME> 200 OK
}
func ExamplePersonService_FindCombined_output() {
client := clearbit.NewClient(clearbit.WithBaseURLs(map[string]string{"person": clearbitServer.URL}))
results, resp, err := client.Person.FindCombined(clearbit.PersonFindParams{
Email: "<EMAIL>",
})
if err == nil {
fmt.Println(results.Person.Name.FullName, results.Company.Name, resp.Status)
} else {
handleError(err, resp)
}
// Output: <NAME> Clearbit 200 OK
}
func ExampleDiscoveryService_Search_output() {
client := clearbit.NewClient(clearbit.WithBaseURLs(map[string]string{"discovery": clearbitServer.URL}))
results, resp, err := client.Discovery.Search(clearbit.DiscoverySearchParams{
Query: "name:clearbit",
})
if err == nil {
fmt.Println(results.Results[0].Domain, resp.Status)
} else {
handleError(err, resp)
}
// Output: clearbit.com 200 OK
}
<|start_filename|>clearbit/errors.go<|end_filename|>
package clearbit
import (
"encoding/json"
"fmt"
)
// apiError represents a Clearbit API Error response
// https://clearbit.com/docs#errors
type apiError struct {
Errors []ErrorDetail `json:"error"`
}
// ErrorDetail represents an individual item in an apiError.
type ErrorDetail struct {
Type string `json:"type"`
Message string `json:"message"`
}
// ErrorDetailWrapper is used for single error
type ErrorDetailWrapper struct {
Error ErrorDetail `json:"error"`
}
// ErrorDetail represents an individual item in an apiError.
func (e apiError) Error() string {
if len(e.Errors) > 0 {
err := e.Errors[0]
return fmt.Sprintf("clearbit: %s %v", err.Type, err.Message)
}
return ""
}
// UnmarshalJSON is used to be able to read dynamic json
//
// This is because sometimes our errors are not arrays of ErrorDetail but a
// single ErrorDetail
func (e *apiError) UnmarshalJSON(b []byte) (err error) {
errorDetail, errors := ErrorDetailWrapper{}, []ErrorDetail{}
if err = json.Unmarshal(b, &errors); err == nil {
e.Errors = errors
return
}
if err = json.Unmarshal(b, &errorDetail); err == nil {
errors = append(errors, errorDetail.Error)
e.Errors = errors
return
}
return err
}
// Empty returns true if empty. Otherwise, at least 1 error message/code is
// present and false is returned.
func (e *apiError) Empty() bool {
return len(e.Errors) == 0
}
// relevantError returns any non-nil http-related error (creating the request,
// getting the response, decoding) if any. If the decoded apiError is non-zero
// the apiError is returned. Otherwise, no errors occurred, returns nil.
func relevantError(httpError error, ae apiError) error {
if httpError != nil {
return httpError
}
if ae.Empty() {
return nil
}
return ae
}
| clearbit/clearbit-go |
<|start_filename|>stdinc/uk/signal.h<|end_filename|>
#pragma once
#define SIGBUS 7
#define SIGSEGV 11
#define SIGPIPE 13
#define NSIG 16
#define SIG_DFL ((void (*)(int)) 0)
#define SIG_IGN ((void (*)(int)) 1)
#define SIG_ERR ((void (*)(int)) -1)
struct sigaction {
void (*sa_handler)(int);
void (*sa_restorer)(void);
};
<|start_filename|>stdinc/sys/utsname.h<|end_filename|>
#pragma once
#include "compiler.h"
#include <uk/utsname.h>
BEGIN_DECLS
int uname(struct utsname *buf);
END_DECLS
<|start_filename|>kernel/ide.cc<|end_filename|>
// Simple PIO-based (non-DMA) IDE driver code.
#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.hh"
#include "amd64.h"
#include "traps.h"
#define IDE_BSY 0x80
#define IDE_DRDY 0x40
#define IDE_DF 0x20
#define IDE_ERR 0x01
#define IDE_CMD_READ 0x20
#define IDE_CMD_WRITE 0x30
#if !MEMIDE && !AHCIIDE
static struct spinlock idelock;
static int havedisk1;
// Wait for IDE disk to become ready.
static int
idewait(int checkerr)
{
int r;
while(((r = inb(0x1f7)) & (IDE_BSY|IDE_DRDY)) != IDE_DRDY)
;
if(checkerr && (r & (IDE_DF|IDE_ERR)) != 0)
return -1;
return 0;
}
void
initdisk(void)
{
idewait(0);
// Check if disk 1 is present
outb(0x1f6, 0xe0 | (1<<4));
for (int i=0; i<1000; i++) {
if (inb(0x1f7) != 0) {
havedisk1 = 1;
break;
}
}
// Switch back to disk 0.
outb(0x1f6, 0xe0 | (0<<4));
}
static void
ide_select(u32 dev, u64 count, u64 offset)
{
assert(offset % 512 == 0);
assert(count > 0);
assert(count % 512 == 0);
assert(count / 512 < 256);
u64 sector = offset / 512;
idewait(0);
outb(0x3f6, 0); // generate interrupt
outb(0x1f2, count / 512); // number of sectors
outb(0x1f3, sector & 0xff);
outb(0x1f4, (sector >> 8) & 0xff);
outb(0x1f5, (sector >> 16) & 0xff);
outb(0x1f6, 0xe0 | (dev<<4) | ((sector>>24)&0x0f));
}
void
ideread(u32 dev, char* data, u64 count, u64 offset)
{
assert(dev == 1);
assert(havedisk1);
scoped_acquire l(&idelock);
ide_select(dev, count, offset);
outb(0x1f7, IDE_CMD_READ);
assert(idewait(1) >= 0);
insl(0x1f0, data, count/4);
}
void
idewrite(u32 dev, const char* data, u64 count, u64 offset)
{
assert(dev == 1);
assert(havedisk1);
scoped_acquire l(&idelock);
ide_select(dev, count, offset);
outb(0x1f7, IDE_CMD_WRITE);
outsl(0x1f0, data, count/4);
assert(idewait(1) >= 0);
}
void
ideintr(void)
{
}
#endif
<|start_filename|>include/cpu.hh<|end_filename|>
#pragma once
#include "mmu.h"
#include <atomic>
#include "spinlock.hh"
#include "spercpu.hh"
using std::atomic;
namespace MMU_SCHEME {
class page_map_cache;
};
// Per-CPU state
struct cpu {
// XXX(Austin) We should move more of this out to static_percpu's.
// The only things that need to live here are the fast-access
// %gs-relative fields at the end (with a little more
// sophistication, we could probably get rid of those, too).
cpuid_t id; // Index into cpus[] below
int ncli; // Depth of pushcli nesting.
int intena; // Were interrupts enabled before pushcli?
struct segdesc gdt[NSEGS]; // x86 global descriptor table
struct taskstate ts; // Used by x86 to find stack for interrupt
struct context *scheduler; // swtch() here to enter scheduler
int timer_printpc;
__mpalign__
atomic<u64> tlbflush_done; // last tlb flush req done on this cpu
atomic<u64> tlb_cr3; // current value of cr3 on this cpu
__padout__;
struct proc *prev; // The previously-running process
atomic<struct proc*> fpu_owner; // The proc with the current FPU state
struct numa_node *node;
hwid_t hwid __mpalign__; // Local APIC ID, accessed by other CPUs
__padout__;
// Cpu-local storage variables; see below and in spercpu.hh
struct cpu *cpu;
struct proc *proc; // The currently-running process.
struct cpu_mem *mem; // The per-core memory metadata
u64 syscallno; // Temporary used by sysentry
void *percpu_base; // Per-CPU memory region base
uint64_t no_sched_count; // sched disable count; high bit means
// yield requested
} __mpalign__;
DECLARE_PERCPU(struct cpu, cpus);
// Per-CPU variables, holding pointers to the
// current cpu and to the current process.
// XXX(sbw) asm labels default to RIP-relative and
// I don't know how to force absolute addressing.
static inline struct cpu *
mycpu(void)
{
u64 val;
__asm volatile("movq %%gs:0, %0" : "=r" (val));
return (struct cpu *)val;
}
static inline struct proc *
myproc(void)
{
u64 val;
__asm volatile("movq %%gs:8, %0" : "=r" (val));
return (struct proc *)val;
}
static inline cpuid_t
myid(void)
{
return mycpu()->id;
}
<|start_filename|>codexinc/atomic_std.h<|end_filename|>
// -*- C++ -*- header.
// Copyright (C) 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file include/atomic
* This is a Standard C++ Library header.
*/
// Based on "C++ Atomic Types and Operations" by <NAME> and <NAME>.
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2427.html
#ifndef _GLIBCXX_ATOMIC
#define _GLIBCXX_ATOMIC 1
#pragma GCC system_header
#include "atomic_base.h"
#include "atomic_2.h"
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
/**
* @addtogroup atomics
* @{
*/
/// atomic_bool
// NB: No operators or fetch-operations for this type.
struct atomic_bool
{
private:
__atomic_base<bool> _M_base;
public:
atomic_bool() = default;
~atomic_bool() = default;
atomic_bool(const atomic_bool&) = delete;
atomic_bool& operator=(const atomic_bool&) = delete;
atomic_bool& operator=(const atomic_bool&) volatile = delete;
constexpr atomic_bool(bool __i) : _M_base(__i) { }
bool
operator=(bool __i)
{ return _M_base.operator=(__i); }
operator bool() const
{ return _M_base.load(); }
operator bool() const volatile
{ return _M_base.load(); }
bool
is_lock_free() const { return _M_base.is_lock_free(); }
bool
is_lock_free() const volatile { return _M_base.is_lock_free(); }
void
store(bool __i, memory_order __m = memory_order_seq_cst)
{ _M_base.store(__i, __m); }
void
store(bool __i, memory_order __m = memory_order_seq_cst) volatile
{ _M_base.store(__i, __m); }
bool
load(memory_order __m = memory_order_seq_cst) const
{ return _M_base.load(__m); }
bool
load(memory_order __m = memory_order_seq_cst) const volatile
{ return _M_base.load(__m); }
bool
exchange(bool __i, memory_order __m = memory_order_seq_cst)
{ return _M_base.exchange(__i, __m); }
bool
exchange(bool __i, memory_order __m = memory_order_seq_cst) volatile
{ return _M_base.exchange(__i, __m); }
bool
compare_exchange_weak(bool& __i1, bool __i2, memory_order __m1,
memory_order __m2)
{ return _M_base.compare_exchange_weak(__i1, __i2, __m1, __m2); }
bool
compare_exchange_weak(bool& __i1, bool __i2, memory_order __m1,
memory_order __m2) volatile
{ return _M_base.compare_exchange_weak(__i1, __i2, __m1, __m2); }
bool
compare_exchange_weak(bool& __i1, bool __i2,
memory_order __m = memory_order_seq_cst)
{ return _M_base.compare_exchange_weak(__i1, __i2, __m); }
bool
compare_exchange_weak(bool& __i1, bool __i2,
memory_order __m = memory_order_seq_cst) volatile
{ return _M_base.compare_exchange_weak(__i1, __i2, __m); }
bool
compare_exchange_strong(bool& __i1, bool __i2, memory_order __m1,
memory_order __m2)
{ return _M_base.compare_exchange_strong(__i1, __i2, __m1, __m2); }
bool
compare_exchange_strong(bool& __i1, bool __i2, memory_order __m1,
memory_order __m2) volatile
{ return _M_base.compare_exchange_strong(__i1, __i2, __m1, __m2); }
bool
compare_exchange_strong(bool& __i1, bool __i2,
memory_order __m = memory_order_seq_cst)
{ return _M_base.compare_exchange_strong(__i1, __i2, __m); }
bool
compare_exchange_strong(bool& __i1, bool __i2,
memory_order __m = memory_order_seq_cst) volatile
{ return _M_base.compare_exchange_strong(__i1, __i2, __m); }
};
/// atomic
/// 29.4.3, Generic atomic type, primary class template.
template<typename _Tp>
struct atomic
{
private:
_Tp _M_i;
public:
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(_Tp __i) : _M_i(__i) { }
operator _Tp() const;
operator _Tp() const volatile;
_Tp
operator=(_Tp __i) { store(__i); return __i; }
_Tp
operator=(_Tp __i) volatile { store(__i); return __i; }
bool
is_lock_free() const;
bool
is_lock_free() const volatile;
void
store(_Tp, memory_order = memory_order_seq_cst);
void
store(_Tp, memory_order = memory_order_seq_cst) volatile;
_Tp
load(memory_order = memory_order_seq_cst) const;
_Tp
load(memory_order = memory_order_seq_cst) const volatile;
_Tp
exchange(_Tp __i, memory_order = memory_order_seq_cst);
_Tp
exchange(_Tp __i, memory_order = memory_order_seq_cst) volatile;
bool
compare_exchange_weak(_Tp&, _Tp, memory_order, memory_order);
bool
compare_exchange_weak(_Tp&, _Tp, memory_order, memory_order) volatile;
bool
compare_exchange_weak(_Tp&, _Tp, memory_order = memory_order_seq_cst);
bool
compare_exchange_weak(_Tp&, _Tp,
memory_order = memory_order_seq_cst) volatile;
bool
compare_exchange_strong(_Tp&, _Tp, memory_order, memory_order);
bool
compare_exchange_strong(_Tp&, _Tp, memory_order, memory_order) volatile;
bool
compare_exchange_strong(_Tp&, _Tp, memory_order = memory_order_seq_cst);
bool
compare_exchange_strong(_Tp&, _Tp,
memory_order = memory_order_seq_cst) volatile;
};
/// Partial specialization for pointer types.
template<typename _Tp>
struct atomic<_Tp*>
{
typedef _Tp* __pointer_type;
typedef __atomic_base<_Tp*> __base_type;
__base_type _M_b;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__pointer_type __p) : _M_b(__p) { }
operator __pointer_type() const
{ return __pointer_type(_M_b); }
operator __pointer_type() const volatile
{ return __pointer_type(_M_b); }
__pointer_type
operator=(__pointer_type __p)
{ return _M_b.operator=(__p); }
__pointer_type
operator=(__pointer_type __p) volatile
{ return _M_b.operator=(__p); }
__pointer_type
operator++(int)
{ return _M_b++; }
__pointer_type
operator++(int) volatile
{ return _M_b++; }
__pointer_type
operator--(int)
{ return _M_b--; }
__pointer_type
operator--(int) volatile
{ return _M_b--; }
__pointer_type
operator++()
{ return ++_M_b; }
__pointer_type
operator++() volatile
{ return ++_M_b; }
__pointer_type
operator--()
{ return --_M_b; }
__pointer_type
operator--() volatile
{ return --_M_b; }
__pointer_type
operator+=(ptrdiff_t __d)
{ return _M_b.operator+=(__d); }
__pointer_type
operator+=(ptrdiff_t __d) volatile
{ return _M_b.operator+=(__d); }
__pointer_type
operator-=(ptrdiff_t __d)
{ return _M_b.operator-=(__d); }
__pointer_type
operator-=(ptrdiff_t __d) volatile
{ return _M_b.operator-=(__d); }
bool
is_lock_free() const
{ return _M_b.is_lock_free(); }
bool
is_lock_free() const volatile
{ return _M_b.is_lock_free(); }
void
store(__pointer_type __p, memory_order __m = memory_order_seq_cst)
{ return _M_b.store(__p, __m); }
void
store(__pointer_type __p,
memory_order __m = memory_order_seq_cst) volatile
{ return _M_b.store(__p, __m); }
__pointer_type
load(memory_order __m = memory_order_seq_cst) const
{ return _M_b.load(__m); }
__pointer_type
load(memory_order __m = memory_order_seq_cst) const volatile
{ return _M_b.load(__m); }
__pointer_type
exchange(__pointer_type __p, memory_order __m = memory_order_seq_cst)
{ return _M_b.exchange(__p, __m); }
__pointer_type
exchange(__pointer_type __p,
memory_order __m = memory_order_seq_cst) volatile
{ return _M_b.exchange(__p, __m); }
bool
compare_exchange_weak(__pointer_type& __p1, __pointer_type __p2,
memory_order __m1, memory_order __m2)
{ return _M_b.compare_exchange_strong(__p1, __p2, __m1, __m2); }
bool
compare_exchange_weak(__pointer_type& __p1, __pointer_type __p2,
memory_order __m1, memory_order __m2) volatile
{ return _M_b.compare_exchange_strong(__p1, __p2, __m1, __m2); }
bool
compare_exchange_weak(__pointer_type& __p1, __pointer_type __p2,
memory_order __m = memory_order_seq_cst)
{
return compare_exchange_weak(__p1, __p2, __m,
__calculate_memory_order(__m));
}
bool
compare_exchange_weak(__pointer_type& __p1, __pointer_type __p2,
memory_order __m = memory_order_seq_cst) volatile
{
return compare_exchange_weak(__p1, __p2, __m,
__calculate_memory_order(__m));
}
bool
compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2,
memory_order __m1, memory_order __m2)
{ return _M_b.compare_exchange_strong(__p1, __p2, __m1, __m2); }
bool
compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2,
memory_order __m1, memory_order __m2) volatile
{ return _M_b.compare_exchange_strong(__p1, __p2, __m1, __m2); }
bool
compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2,
memory_order __m = memory_order_seq_cst)
{
return _M_b.compare_exchange_strong(__p1, __p2, __m,
__calculate_memory_order(__m));
}
bool
compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2,
memory_order __m = memory_order_seq_cst) volatile
{
return _M_b.compare_exchange_strong(__p1, __p2, __m,
__calculate_memory_order(__m));
}
__pointer_type
fetch_add(ptrdiff_t __d, memory_order __m = memory_order_seq_cst)
{ return _M_b.fetch_add(__d, __m); }
__pointer_type
fetch_add(ptrdiff_t __d,
memory_order __m = memory_order_seq_cst) volatile
{ return _M_b.fetch_add(__d, __m); }
__pointer_type
fetch_sub(ptrdiff_t __d, memory_order __m = memory_order_seq_cst)
{ return _M_b.fetch_sub(__d, __m); }
__pointer_type
fetch_sub(ptrdiff_t __d,
memory_order __m = memory_order_seq_cst) volatile
{ return _M_b.fetch_sub(__d, __m); }
};
/// Explicit specialization for bool.
template<>
struct atomic<bool> : public atomic_bool
{
typedef bool __integral_type;
typedef atomic_bool __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for char.
template<>
struct atomic<char> : public atomic_char
{
typedef char __integral_type;
typedef atomic_char __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for signed char.
template<>
struct atomic<signed char> : public atomic_schar
{
typedef signed char __integral_type;
typedef atomic_schar __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for unsigned char.
template<>
struct atomic<unsigned char> : public atomic_uchar
{
typedef unsigned char __integral_type;
typedef atomic_uchar __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for short.
template<>
struct atomic<short> : public atomic_short
{
typedef short __integral_type;
typedef atomic_short __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for unsigned short.
template<>
struct atomic<unsigned short> : public atomic_ushort
{
typedef unsigned short __integral_type;
typedef atomic_ushort __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for int.
template<>
struct atomic<int> : atomic_int
{
typedef int __integral_type;
typedef atomic_int __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for unsigned int.
template<>
struct atomic<unsigned int> : public atomic_uint
{
typedef unsigned int __integral_type;
typedef atomic_uint __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for long.
template<>
struct atomic<long> : public atomic_long
{
typedef long __integral_type;
typedef atomic_long __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for unsigned long.
template<>
struct atomic<unsigned long> : public atomic_ulong
{
typedef unsigned long __integral_type;
typedef atomic_ulong __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for long long.
template<>
struct atomic<long long> : public atomic_llong
{
typedef long long __integral_type;
typedef atomic_llong __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for unsigned long long.
template<>
struct atomic<unsigned long long> : public atomic_ullong
{
typedef unsigned long long __integral_type;
typedef atomic_ullong __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for wchar_t.
template<>
struct atomic<wchar_t> : public atomic_wchar_t
{
typedef wchar_t __integral_type;
typedef atomic_wchar_t __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for char16_t.
template<>
struct atomic<char16_t> : public atomic_char16_t
{
typedef char16_t __integral_type;
typedef atomic_char16_t __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
/// Explicit specialization for char32_t.
template<>
struct atomic<char32_t> : public atomic_char32_t
{
typedef char32_t __integral_type;
typedef atomic_char32_t __base_type;
atomic() = default;
~atomic() = default;
atomic(const atomic&) = delete;
atomic& operator=(const atomic&) = delete;
atomic& operator=(const atomic&) volatile = delete;
constexpr atomic(__integral_type __i) : __base_type(__i) { }
using __base_type::operator __integral_type;
using __base_type::operator=;
};
// Function definitions, atomic_flag operations.
inline bool
atomic_flag_test_and_set_explicit(atomic_flag* __a, memory_order __m)
{ return __a->test_and_set(__m); }
inline bool
atomic_flag_test_and_set_explicit(volatile atomic_flag* __a,
memory_order __m)
{ return __a->test_and_set(__m); }
inline void
atomic_flag_clear_explicit(atomic_flag* __a, memory_order __m)
{ __a->clear(__m); }
inline void
atomic_flag_clear_explicit(volatile atomic_flag* __a, memory_order __m)
{ __a->clear(__m); }
inline bool
atomic_flag_test_and_set(atomic_flag* __a)
{ return atomic_flag_test_and_set_explicit(__a, memory_order_seq_cst); }
inline bool
atomic_flag_test_and_set(volatile atomic_flag* __a)
{ return atomic_flag_test_and_set_explicit(__a, memory_order_seq_cst); }
inline void
atomic_flag_clear(atomic_flag* __a)
{ atomic_flag_clear_explicit(__a, memory_order_seq_cst); }
inline void
atomic_flag_clear(volatile atomic_flag* __a)
{ atomic_flag_clear_explicit(__a, memory_order_seq_cst); }
// Function templates generally applicable to atomic types.
template<typename _ITp>
inline bool
atomic_is_lock_free(const atomic<_ITp>* __a)
{ return __a->is_lock_free(); }
template<typename _ITp>
inline bool
atomic_is_lock_free(const volatile atomic<_ITp>* __a)
{ return __a->is_lock_free(); }
template<typename _ITp>
inline void
atomic_init(atomic<_ITp>* __a, _ITp __i);
template<typename _ITp>
inline void
atomic_init(volatile atomic<_ITp>* __a, _ITp __i);
template<typename _ITp>
inline void
atomic_store_explicit(atomic<_ITp>* __a, _ITp __i, memory_order __m)
{ __a->store(__i, __m); }
template<typename _ITp>
inline void
atomic_store_explicit(volatile atomic<_ITp>* __a, _ITp __i,
memory_order __m)
{ __a->store(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_load_explicit(const atomic<_ITp>* __a, memory_order __m)
{ return __a->load(__m); }
template<typename _ITp>
inline _ITp
atomic_load_explicit(const volatile atomic<_ITp>* __a,
memory_order __m)
{ return __a->load(__m); }
template<typename _ITp>
inline _ITp
atomic_exchange_explicit(atomic<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->exchange(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_exchange_explicit(volatile atomic<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->exchange(__i, __m); }
template<typename _ITp>
inline bool
atomic_compare_exchange_weak_explicit(atomic<_ITp>* __a,
_ITp* __i1, _ITp __i2,
memory_order __m1, memory_order __m2)
{ return __a->compare_exchange_weak(*__i1, __i2, __m1, __m2); }
template<typename _ITp>
inline bool
atomic_compare_exchange_weak_explicit(volatile atomic<_ITp>* __a,
_ITp* __i1, _ITp __i2,
memory_order __m1, memory_order __m2)
{ return __a->compare_exchange_weak(*__i1, __i2, __m1, __m2); }
template<typename _ITp>
inline bool
atomic_compare_exchange_strong_explicit(atomic<_ITp>* __a,
_ITp* __i1, _ITp __i2,
memory_order __m1,
memory_order __m2)
{ return __a->compare_exchange_strong(*__i1, __i2, __m1, __m2); }
template<typename _ITp>
inline bool
atomic_compare_exchange_strong_explicit(volatile atomic<_ITp>* __a,
_ITp* __i1, _ITp __i2,
memory_order __m1,
memory_order __m2)
{ return __a->compare_exchange_strong(*__i1, __i2, __m1, __m2); }
template<typename _ITp>
inline void
atomic_store(atomic<_ITp>* __a, _ITp __i)
{ atomic_store_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline void
atomic_store(volatile atomic<_ITp>* __a, _ITp __i)
{ atomic_store_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_load(const atomic<_ITp>* __a)
{ return atomic_load_explicit(__a, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_load(const volatile atomic<_ITp>* __a)
{ return atomic_load_explicit(__a, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_exchange(atomic<_ITp>* __a, _ITp __i)
{ return atomic_exchange_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_exchange(volatile atomic<_ITp>* __a, _ITp __i)
{ return atomic_exchange_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline bool
atomic_compare_exchange_weak(atomic<_ITp>* __a,
_ITp* __i1, _ITp __i2)
{
return atomic_compare_exchange_weak_explicit(__a, __i1, __i2,
memory_order_seq_cst,
memory_order_seq_cst);
}
template<typename _ITp>
inline bool
atomic_compare_exchange_weak(volatile atomic<_ITp>* __a,
_ITp* __i1, _ITp __i2)
{
return atomic_compare_exchange_weak_explicit(__a, __i1, __i2,
memory_order_seq_cst,
memory_order_seq_cst);
}
template<typename _ITp>
inline bool
atomic_compare_exchange_strong(atomic<_ITp>* __a,
_ITp* __i1, _ITp __i2)
{
return atomic_compare_exchange_strong_explicit(__a, __i1, __i2,
memory_order_seq_cst,
memory_order_seq_cst);
}
template<typename _ITp>
inline bool
atomic_compare_exchange_strong(volatile atomic<_ITp>* __a,
_ITp* __i1, _ITp __i2)
{
return atomic_compare_exchange_strong_explicit(__a, __i1, __i2,
memory_order_seq_cst,
memory_order_seq_cst);
}
// Function templates for atomic_integral operations only, using
// __atomic_base. Template argument should be constricted to
// intergral types as specified in the standard, excluding address
// types.
template<typename _ITp>
inline _ITp
atomic_fetch_add_explicit(__atomic_base<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->fetch_add(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_fetch_add_explicit(volatile __atomic_base<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->fetch_add(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_fetch_sub_explicit(__atomic_base<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->fetch_sub(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_fetch_sub_explicit(volatile __atomic_base<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->fetch_sub(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_fetch_and_explicit(__atomic_base<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->fetch_and(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_fetch_and_explicit(volatile __atomic_base<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->fetch_and(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_fetch_or_explicit(__atomic_base<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->fetch_or(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_fetch_or_explicit(volatile __atomic_base<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->fetch_or(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_fetch_xor_explicit(__atomic_base<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->fetch_xor(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_fetch_xor_explicit(volatile __atomic_base<_ITp>* __a, _ITp __i,
memory_order __m)
{ return __a->fetch_xor(__i, __m); }
template<typename _ITp>
inline _ITp
atomic_fetch_add(__atomic_base<_ITp>* __a, _ITp __i)
{ return atomic_fetch_add_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_fetch_add(volatile __atomic_base<_ITp>* __a, _ITp __i)
{ return atomic_fetch_add_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_fetch_sub(__atomic_base<_ITp>* __a, _ITp __i)
{ return atomic_fetch_sub_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_fetch_sub(volatile __atomic_base<_ITp>* __a, _ITp __i)
{ return atomic_fetch_sub_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_fetch_and(__atomic_base<_ITp>* __a, _ITp __i)
{ return atomic_fetch_and_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_fetch_and(volatile __atomic_base<_ITp>* __a, _ITp __i)
{ return atomic_fetch_and_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_fetch_or(__atomic_base<_ITp>* __a, _ITp __i)
{ return atomic_fetch_or_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_fetch_or(volatile __atomic_base<_ITp>* __a, _ITp __i)
{ return atomic_fetch_or_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_fetch_xor(__atomic_base<_ITp>* __a, _ITp __i)
{ return atomic_fetch_xor_explicit(__a, __i, memory_order_seq_cst); }
template<typename _ITp>
inline _ITp
atomic_fetch_xor(volatile __atomic_base<_ITp>* __a, _ITp __i)
{ return atomic_fetch_xor_explicit(__a, __i, memory_order_seq_cst); }
// Partial specializations for pointers.
template<typename _ITp>
inline _ITp*
atomic_fetch_add_explicit(atomic<_ITp*>* __a, ptrdiff_t __d,
memory_order __m)
{ return __a->fetch_add(__d, __m); }
template<typename _ITp>
inline _ITp*
atomic_fetch_add_explicit(volatile atomic<_ITp*>* __a, ptrdiff_t __d,
memory_order __m)
{ return __a->fetch_add(__d, __m); }
template<typename _ITp>
inline _ITp*
atomic_fetch_add(volatile atomic<_ITp*>* __a, ptrdiff_t __d)
{ return __a->fetch_add(__d); }
template<typename _ITp>
inline _ITp*
atomic_fetch_add(atomic<_ITp*>* __a, ptrdiff_t __d)
{ return __a->fetch_add(__d); }
template<typename _ITp>
inline _ITp*
atomic_fetch_sub_explicit(volatile atomic<_ITp*>* __a,
ptrdiff_t __d, memory_order __m)
{ return __a->fetch_sub(__d, __m); }
template<typename _ITp>
inline _ITp*
atomic_fetch_sub_explicit(atomic<_ITp*>* __a, ptrdiff_t __d,
memory_order __m)
{ return __a->fetch_sub(__d, __m); }
template<typename _ITp>
inline _ITp*
atomic_fetch_sub(volatile atomic<_ITp*>* __a, ptrdiff_t __d)
{ return __a->fetch_sub(__d); }
template<typename _ITp>
inline _ITp*
atomic_fetch_sub(atomic<_ITp*>* __a, ptrdiff_t __d)
{ return __a->fetch_sub(__d); }
// @} group atomics
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
#endif
<|start_filename|>net/string.h<|end_filename|>
void* memset(void*, int, unsigned int);
void* memcpy(void *dst, const void *src, unsigned int n);
void* memset(void*, int, unsigned int);
unsigned int strlen(const char* str);
int memcmp(const void*, const void*, unsigned int);
<|start_filename|>libutil/include/pstream.hh<|end_filename|>
#pragma once
// Extensible, type-safe, usable print streams.
//
// External users of this API should call the print or println methods
// of a print_stream. To specially format numbers, use sfmt or shex.
// To output byte buffers, use sbuf.
//
// Extensions of this API to add printable types should be implemented
// as overloads of to_stream and should call other to_stream
// functions.
//
// Output stream types should be implemented as subclasses of
// print_stream.
// XXX(Austin) The only thing I dislike about this API is that
// formatters aren't higher-order. Usually this is fine, but
// sometimes I want to construct a formatter like zero-padded
// two-digit-wide hex and use it several times. This could be
// accomplished by making formatters functor objects.
#include <cstddef>
#include <cstdint>
#include <initializer_list>
#include <utility>
struct sbuf
{
const char *base;
size_t len;
sbuf(const char *b, size_t l) : base(b), len(l) { }
sbuf(const sbuf &o) = default;
sbuf(sbuf &&o) = default;
};
class print_stream
{
public:
// Write each of the arguments to this stream in order.
template<typename... T>
void print(T&&... args)
{
if (begin_print()) {
_print(std::forward<T>(args)...);
end_print();
}
}
// Like print, but append a newline.
template<typename... T>
void println(T&&... args)
{
if (begin_print()) {
_print(std::forward<T>(args)...);
write('\n');
end_print();
}
}
protected:
// Called when beginning a print call. This should return true to
// allow the print, or false to suppress it. This can also be used
// for locking, but any locking needs to be re-entrant.
virtual bool begin_print()
{
return true;
}
// Called after printing. Always paired with begin_print() when
// begin_print() returns true.
virtual void end_print() { }
virtual void write(char c)
{
write(sbuf(&c, 1));
}
virtual void write(sbuf buf) = 0;
friend void to_stream(print_stream *s, char c);
friend void to_stream(print_stream *s, sbuf b);
private:
template<typename T1, typename... T>
void _print(T1 &&arg1, T&&... rest)
{
to_stream(this, std::forward<T1>(arg1));
_print(std::forward<T>(rest)...);
}
void _print() { }
};
class null_stream : public print_stream
{
protected:
bool begin_print()
{
return false;
}
void write(char c) { }
void write(sbuf buf) { }
};
inline
void to_stream(print_stream *s, char c)
{
s->write(c);
}
inline
void to_stream(print_stream *s, sbuf b)
{
s->write(b);
}
void to_stream(print_stream *s, int v);
void to_stream(print_stream *s, unsigned v);
void to_stream(print_stream *s, long v);
void to_stream(print_stream *s, unsigned long v);
void to_stream(print_stream *s, long long v);
void to_stream(print_stream *s, unsigned long long v);
void to_stream(print_stream *s, const char *str);
void to_stream(print_stream *s, const void *ptr);
class integer_formatter
{
unsigned long long val_;
int width_;
unsigned char base_;
char pad_;
bool neg_;
bool alt_;
friend void to_stream(print_stream *s, const integer_formatter &n);
public:
integer_formatter(unsigned long long v, bool neg)
: val_(v), width_(0), base_(10), pad_(' '), neg_(neg), alt_(false) { }
integer_formatter &width(int width)
{
width_ = width;
return *this;
}
integer_formatter &base(unsigned base)
{
if (base == 0 || base > 16)
base = 10;
base_ = base;
return *this;
}
integer_formatter &pad(char pad = '0')
{
pad_ = pad;
return *this;
}
// Format the number using an alternate form. If base is 8 and the
// number is non-zero, this will prefix the output with "0". If
// base is 16 and the number of non-zero, this will prefix the
// output with "0x".
integer_formatter &alt(bool alt = true)
{
alt_ = alt;
return *this;
}
};
void to_stream(print_stream *s, const integer_formatter &n);
// Format any integral value. The default formatting is equivalent to
// passing the value directly to the print stream, but can be
// manipulated using the methods of integer_formatter.
template<typename T>
integer_formatter sfmt(T v)
{
bool neg = v < 0;
if (neg)
v = -v;
return integer_formatter(v, neg);
}
// Format v in hexadecimal and, if non-zero, preceded by an 0x.
template<typename T>
integer_formatter shex(T v)
{
return sfmt(v).base(16).alt();
}
/**
* Flags pretty-printer.
*
* This decodes a bitmap of flags into symbolic form. Any
* unrecognized bits are included in a trailing hex value.
*/
class sflags
{
public:
/**
* A symbolic flag value.
*/
struct flag
{
const char *name_;
unsigned long long mask_;
unsigned long long test_;
/**
* Construct a flag that's set if <code>(v & test)</code>.
* Generally this is only appropriate for single-bit flags.
*/
constexpr flag(const char *name, unsigned long long test)
: name_(name), mask_(test), test_(test) { }
/**
* Construct a flag that's set if <code>(v & mask) == test</code>.
*/
constexpr flag(const char *name, unsigned long long mask,
unsigned long long test)
: name_(name), mask_(mask), test_(test) { }
};
private:
unsigned long long val_;
std::initializer_list<flag> flags_;
friend void to_stream(print_stream *s, const sflags &f);
public:
/**
* Construct a flags printer that decodes @c v using @c flags. This
* is designed to be used with uniform initialization syntax, e.g.
* <code>sflags(x, {{"X", 1}, {"Y", 2}})</code>.
*/
constexpr sflags(unsigned long long v, std::initializer_list<flag> flags)
: val_(v), flags_(flags) { }
};
void to_stream(print_stream *s, const sflags &f);
/**
* Enum pretty-printer.
*
* This decodes enumerated values into symbol form. Unrecognized
* values are printed as decimal numbers.
*/
class senum
{
public:
/**
* A symbolic enumeration value.
*/
struct enum_value
{
bool next_;
unsigned long long value_;
const char *name_;
/**
* An enumeration whose value is one higher than the previous
* value (or zero if this is the first). This allows for implicit
* conversion so strings can be used directly in an enumeration
* values list.
*/
constexpr enum_value(const char *name)
: next_(true), value_(0), name_(name) { }
/**
* An enumeration with a specific value.
*/
constexpr enum_value(const char *name, unsigned long long value)
: next_(false), value_(value), name_(name) { }
};
private:
unsigned long long val_;
std::initializer_list<enum_value> values_;
friend void to_stream(print_stream *s, const senum &e);
public:
/**
* Construct an enumeration printer that decodes @c v. This is
* designed to be used with uniform initialization syntax, e.g.
* <code>senum(x, {"A", "B", {"D", 3}})</code>.
*/
constexpr senum(unsigned long long v,
std::initializer_list<enum_value> values)
: val_(v), values_(values) { }
};
void to_stream(print_stream *s, const senum &f);
/**
* Hex dump pretty-printer.
*
* The hex dump includes a trailing newline, so this should not be
* used as the last argument to println.
*/
class shexdump
{
const void *base_;
size_t len_;
uintptr_t start_;
friend void to_stream(print_stream *s, const shexdump &f);
public:
/**
* Construct a hex dump printer where the starting offset displayed
* in the dump is base's virtual address.
*/
shexdump(const void *base, size_t len)
: base_(base), len_(len), start_((uintptr_t)base) { }
/**
* Construct a hex dump printer with an explicit starting offset.
*/
constexpr shexdump(const void *base, size_t len, uintptr_t start)
: base_(base), len_(len), start_(start) { }
};
void to_stream(print_stream *s, const shexdump &f);
/**
* Size pretty-printer.
*
* This pretty prints sizes using binary prefixes (KB, MB, etc.) This
* retains two to three significant digits.
*/
class ssize
{
uintptr_t val_;
friend void to_stream(print_stream *s, const ssize &f);
public:
/**
* Construct a size pretty-printed for the given value.
*/
ssize(uintptr_t val) : val_(val) { }
};
void to_stream(print_stream *s, const ssize &f);
<|start_filename|>kernel/sysproc.cc<|end_filename|>
#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "mmu.h"
#include "spinlock.hh"
#include "condvar.hh"
#include "proc.hh"
#include "cpu.hh"
#include "vm.hh"
#include "kmtrace.hh"
#include "futex.h"
#include "version.hh"
#include "filetable.hh"
#include <uk/mman.h>
#include <uk/utsname.h>
#include <uk/unistd.h>
//SYSCALL
int
sys_fork_flags(int flags)
{
clone_flags cflags = clone_flags::CLONE_ALL;
if (flags & FORK_SHARE_VMAP)
cflags |= CLONE_SHARE_VMAP;
if (flags & FORK_SHARE_FD)
cflags |= CLONE_SHARE_FTABLE;
proc *p = doclone(cflags);
if (!p)
return -1;
return p->pid;
}
//SYSCALL {"noret":true}
void
sys_exit(int status)
{
exit(status);
panic("exit() returned");
}
//SYSCALL
int
sys_waitpid(int pid, userptr<int> status, int options)
{
return wait(pid, status);
}
//SYSCALL
int
sys_wait(userptr<int> status)
{
return wait(-1, status);
}
//SYSCALL
int
sys_kill(int pid)
{
return proc::kill(pid);
}
//SYSCALL
int
sys_getpid(void)
{
return myproc()->pid;
}
//SYSCALL
char*
sys_sbrk(int n)
{
uptr addr;
if(myproc()->vmap->sbrk(n, &addr) < 0)
return (char*)-1;
return (char*)addr;
}
//SYSCALL
int
sys_nsleep(u64 nsec)
{
struct spinlock lock("sleep_lock");
struct condvar cv("sleep_cv");
u64 nsecto;
scoped_acquire l(&lock);
nsecto = nsectime()+nsec;
while (nsecto > nsectime()) {
if (myproc()->killed)
return -1;
cv.sleep_to(&lock, nsecto);
}
return 0;
}
// return how many clock tick interrupts have occurred
// since boot.
//SYSCALL
u64
sys_uptime(void)
{
return nsectime();
}
//SYSCALL
void *
sys_mmap(userptr<void> addr, size_t len, int prot, int flags, int fd,
off_t offset)
{
sref<mnode> m;
if (!(prot & (PROT_READ | PROT_WRITE))) {
cprintf("not implemented: !(prot & (PROT_READ | PROT_WRITE))\n");
return MAP_FAILED;
}
if (flags & MAP_ANONYMOUS) {
if (offset)
return MAP_FAILED;
if (flags & MAP_SHARED) {
m = anon_fs->alloc(mnode::types::file).mn();
auto resizer = m->as_file()->write_size();
for (size_t i = 0; i < len; i += PGSIZE) {
void* p = zalloc("MAP_ANON|MAP_SHARED");
if (!p)
throw_bad_alloc();
auto pi = sref<page_info>::transfer(new (page_info::of(p)) page_info());
resizer.resize_append(i + PGSIZE, pi);
}
}
} else {
sref<file> f = myproc()->ftable->getfile(fd);
if (!f)
return MAP_FAILED;
m = f->get_mnode();
if (!m || m->type() != mnode::types::file)
return MAP_FAILED;
}
uptr start = PGROUNDDOWN((uptr)addr);
uptr end = PGROUNDUP((uptr)addr + len);
if ((flags & MAP_FIXED) && start != (uptr)addr)
return MAP_FAILED;
vmdesc desc;
if (!m) {
desc = vmdesc::anon_desc;
} else {
desc = vmdesc(m, start - offset);
}
if (!(prot & PROT_WRITE))
desc.flags &= ~vmdesc::FLAG_WRITE;
if (flags & MAP_SHARED)
desc.flags |= vmdesc::FLAG_SHARED;
if (m && (flags & MAP_PRIVATE))
desc.flags |= vmdesc::FLAG_COW;
uptr r = myproc()->vmap->insert(desc, start, end - start);
return (void*)r;
}
//SYSCALL
int
sys_munmap(userptr<void> addr, size_t len)
{
uptr align_addr = PGROUNDDOWN((uptr)addr);
uptr align_len = PGROUNDUP((uptr)addr + len) - align_addr;
if (myproc()->vmap->remove(align_addr, align_len) < 0)
return -1;
return 0;
}
//SYSCALL
int
sys_madvise(userptr<void> addr, size_t len, int advice)
{
uptr align_addr = PGROUNDDOWN((uptr)addr);
uptr align_len = PGROUNDUP((uptr)addr + len) - align_addr;
switch (advice) {
case MADV_WILLNEED:
if (myproc()->vmap->willneed(align_addr, align_len) < 0)
return -1;
return 0;
case MADV_INVALIDATE_CACHE:
if (myproc()->vmap->invalidate_cache(align_addr, align_len) < 0)
return -1;
return 0;
default:
return -1;
}
}
//SYSCALL
int
sys_mprotect(userptr<void> addr, size_t len, int prot)
{
if ((uptr)addr % PGSIZE)
return -1; // EINVAL
if ((uptr)addr + len >= USERTOP || (uptr)addr + (uptr)len < (uptr)addr)
return -1; // ENOMEM
if (!(prot & (PROT_READ | PROT_WRITE | PROT_EXEC))) {
cprintf("not implemented: PROT_NONE\n");
return -1;
}
uptr align_addr = PGROUNDDOWN((uptr)addr);
uptr align_len = PGROUNDUP((uptr)addr + len) - align_addr;
uint64_t flags = 0;
if (prot & PROT_WRITE)
flags |= vmdesc::FLAG_WRITE;
return myproc()->vmap->mprotect(align_addr, align_len, flags);
}
//SYSCALL
long
sys_pt_pages(void)
{
return myproc()->vmap->internal_pages();
}
//SYSCALL {"noret":true}
void
sys_halt(void)
{
halt();
panic("halt returned");
}
//SYSCALL
long
sys_cpuhz(void)
{
extern u64 cpuhz;
return cpuhz;
}
//SYSCALL
int
sys_setfs(u64 base)
{
proc *p = myproc();
p->user_fs_ = base;
switchvm(p);
return 0;
}
//SYSCALL
int
sys_setaffinity(int cpu)
{
return myproc()->set_cpu_pin(cpu);
}
//SYSCALL
long
sys_futex(const u64* addr, int op, u64 val, u64 timer)
{
futexkey_t key;
if (futexkey(addr, myproc()->vmap.get(), &key) < 0)
return -1;
mt_ascope ascope("%s(%p,%d,%lu,%lu)", __func__, addr, op, val, timer);
switch(op) {
case FUTEX_WAIT:
return futexwait(key, val, timer);
case FUTEX_WAKE:
return futexwake(key, val);
default:
return -1;
}
}
//SYSCALL
long
sys_yield(void)
{
yield();
return 0;
}
//SYSCALL
int
sys_uname(userptr<struct utsname> buf)
{
static struct utsname uts
{
"xv6",
#define xstr(s) str(s)
#define str(s) #s
xstr(XV6_HW),
#undef xstr
#undef str
"",
"",
"x86_64"
};
static bool initialized;
if (!initialized) {
strncpy(uts.version, xv6_version_string, sizeof(uts.version) - 1);
strncpy(uts.release, xv6_release_string, sizeof(uts.release) - 1);
initialized = true;
}
if (!buf.store(&uts))
return -1;
return 0;
}
// XXX(Austin) This is a hack for benchmarking. See vmap::dup_page.
//SYSCALL
int
sys_dup_page(userptr<void> dest, userptr<void> src)
{
return myproc()->vmap->dup_page((uptr)dest, (uptr)src);
}
//SYSCALL
int
sys_sigaction(int signo, userptr<struct sigaction> act, userptr<struct sigaction> oact)
{
if (signo < 0 || signo >= NSIG)
return -1;
if (oact && !oact.store(&myproc()->sig[signo]))
return -1;
if (act && !act.load(&myproc()->sig[signo]))
return -1;
return 0;
}
<|start_filename|>kernel/dev.cc<|end_filename|>
#include "types.h"
#include "kernel.hh"
#include "fs.h"
#include "file.hh"
#include "major.h"
#include "kstats.hh"
extern const char *kconfig;
DEFINE_PERCPU(struct kstats, mykstats, NO_CRITICAL);
static int
kconfigread(mdev*, char *dst, u32 off, u32 n)
{
auto len = strlen(kconfig);
if (off >= len)
return 0;
if (n > len - off)
n = len - off;
memmove(dst, kconfig + off, n);
return n;
}
static int
kstatsread(mdev*, char *dst, u32 off, u32 n)
{
kstats total{};
if (off >= sizeof total)
return 0;
for (size_t i = 0; i < ncpu; ++i)
total += mykstats[i];
if (n > sizeof total - off)
n = sizeof total - off;
memmove(dst, (char*)&total + off, n);
return n;
}
void
initdev(void)
{
devsw[MAJ_KCONFIG].pread = kconfigread;
devsw[MAJ_KSTATS].pread = kstatsread;
}
<|start_filename|>kernel/acpica/source/components/resources/rslist.c<|end_filename|>
/*******************************************************************************
*
* Module Name: rslist - Linked list utilities
*
******************************************************************************/
/******************************************************************************
*
* 1. Copyright Notice
*
* Some or all of this work - Copyright (c) 1999 - 2012, Intel Corp.
* All rights reserved.
*
* 2. License
*
* 2.1. This is your license from Intel Corp. under its intellectual property
* rights. You may have additional license terms from the party that provided
* you this software, covering your right to use that party's intellectual
* property rights.
*
* 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
* copy of the source code appearing in this file ("Covered Code") an
* irrevocable, perpetual, worldwide license under Intel's copyrights in the
* base code distributed originally by Intel ("Original Intel Code") to copy,
* make derivatives, distribute, use and display any portion of the Covered
* Code in any form, with the right to sublicense such rights; and
*
* 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
* license (with the right to sublicense), under only those claims of Intel
* patents that are infringed by the Original Intel Code, to make, use, sell,
* offer to sell, and import the Covered Code and derivative works thereof
* solely to the minimum extent necessary to exercise the above copyright
* license, and in no event shall the patent license extend to any additions
* to or modifications of the Original Intel Code. No other license or right
* is granted directly or by implication, estoppel or otherwise;
*
* The above copyright and patent license is granted only if the following
* conditions are met:
*
* 3. Conditions
*
* 3.1. Redistribution of Source with Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification with rights to further distribute source must include
* the above Copyright Notice, the above License, this list of Conditions,
* and the following Disclaimer and Export Compliance provision. In addition,
* Licensee must cause all Covered Code to which Licensee contributes to
* contain a file documenting the changes Licensee made to create that Covered
* Code and the date of any change. Licensee must include in that file the
* documentation of any changes made by any predecessor Licensee. Licensee
* must include a prominent statement that the modification is derived,
* directly or indirectly, from Original Intel Code.
*
* 3.2. Redistribution of Source with no Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification without rights to further distribute source must
* include the following Disclaimer and Export Compliance provision in the
* documentation and/or other materials provided with distribution. In
* addition, Licensee may not authorize further sublicense of source of any
* portion of the Covered Code, and must include terms to the effect that the
* license from Licensee to its licensee is limited to the intellectual
* property embodied in the software Licensee provides to its licensee, and
* not to intellectual property embodied in modifications its licensee may
* make.
*
* 3.3. Redistribution of Executable. Redistribution in executable form of any
* substantial portion of the Covered Code or modification must reproduce the
* above Copyright Notice, and the following Disclaimer and Export Compliance
* provision in the documentation and/or other materials provided with the
* distribution.
*
* 3.4. Intel retains all right, title, and interest in and to the Original
* Intel Code.
*
* 3.5. Neither the name Intel nor any other trademark owned or controlled by
* Intel shall be used in advertising or otherwise to promote the sale, use or
* other dealings in products derived from or relating to the Covered Code
* without prior written authorization from Intel.
*
* 4. Disclaimer and Export Compliance
*
* 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
* HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
* IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
* INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
* UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
* IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
* OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
* COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
* SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
* CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
* HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
* SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
* LIMITED REMEDY.
*
* 4.3. Licensee shall not export, either directly or indirectly, any of this
* software or system incorporating such software without first obtaining any
* required license or other approval from the U. S. Department of Commerce or
* any other agency or department of the United States Government. In the
* event Licensee exports any such software from the United States or
* re-exports any such software from a foreign destination, Licensee shall
* ensure that the distribution and export/re-export of the software is in
* compliance with all laws, regulations, orders, or other restrictions of the
* U.S. Export Administration Regulations. Licensee agrees that neither it nor
* any of its subsidiaries will export/re-export any technical data, process,
* software, or service, directly or indirectly, to any country for which the
* United States government or any agency thereof requires an export license,
* other governmental approval, or letter of assurance, without first obtaining
* such license, approval or letter.
*
*****************************************************************************/
#define __RSLIST_C__
#include "acpi.h"
#include "accommon.h"
#include "acresrc.h"
#define _COMPONENT ACPI_RESOURCES
ACPI_MODULE_NAME ("rslist")
/*******************************************************************************
*
* FUNCTION: AcpiRsConvertAmlToResources
*
* PARAMETERS: ACPI_WALK_AML_CALLBACK
* ResourcePtr - Pointer to the buffer that will
* contain the output structures
*
* RETURN: Status
*
* DESCRIPTION: Convert an AML resource to an internal representation of the
* resource that is aligned and easier to access.
*
******************************************************************************/
ACPI_STATUS
AcpiRsConvertAmlToResources (
UINT8 *Aml,
UINT32 Length,
UINT32 Offset,
UINT8 ResourceIndex,
void *Context)
{
ACPI_RESOURCE **ResourcePtr = ACPI_CAST_INDIRECT_PTR (
ACPI_RESOURCE, Context);
ACPI_RESOURCE *Resource;
AML_RESOURCE *AmlResource;
ACPI_RSCONVERT_INFO *ConversionTable;
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (RsConvertAmlToResources);
/*
* Check that the input buffer and all subsequent pointers into it
* are aligned on a native word boundary. Most important on IA64
*/
Resource = *ResourcePtr;
if (ACPI_IS_MISALIGNED (Resource))
{
ACPI_WARNING ((AE_INFO,
"Misaligned resource pointer %p", Resource));
}
/* Get the appropriate conversion info table */
AmlResource = ACPI_CAST_PTR (AML_RESOURCE, Aml);
if (AcpiUtGetResourceType (Aml) == ACPI_RESOURCE_NAME_SERIAL_BUS)
{
if (AmlResource->CommonSerialBus.Type > AML_RESOURCE_MAX_SERIALBUSTYPE)
{
ConversionTable = NULL;
}
else
{
/* This is an I2C, SPI, or UART SerialBus descriptor */
ConversionTable =
AcpiGbl_ConvertResourceSerialBusDispatch[
AmlResource->CommonSerialBus.Type];
}
}
else
{
ConversionTable =
AcpiGbl_GetResourceDispatch[ResourceIndex];
}
if (!ConversionTable)
{
ACPI_ERROR ((AE_INFO,
"Invalid/unsupported resource descriptor: Type 0x%2.2X",
ResourceIndex));
return (AE_AML_INVALID_RESOURCE_TYPE);
}
/* Convert the AML byte stream resource to a local resource struct */
Status = AcpiRsConvertAmlToResource (
Resource, AmlResource, ConversionTable);
if (ACPI_FAILURE (Status))
{
ACPI_EXCEPTION ((AE_INFO, Status,
"Could not convert AML resource (Type 0x%X)", *Aml));
return_ACPI_STATUS (Status);
}
ACPI_DEBUG_PRINT ((ACPI_DB_RESOURCES,
"Type %.2X, AmlLength %.2X InternalLength %.2X\n",
AcpiUtGetResourceType (Aml), Length,
Resource->Length));
/* Point to the next structure in the output buffer */
*ResourcePtr = ACPI_NEXT_RESOURCE (Resource);
return_ACPI_STATUS (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiRsConvertResourcesToAml
*
* PARAMETERS: Resource - Pointer to the resource linked list
* AmlSizeNeeded - Calculated size of the byte stream
* needed from calling AcpiRsGetAmlLength()
* The size of the OutputBuffer is
* guaranteed to be >= AmlSizeNeeded
* OutputBuffer - Pointer to the buffer that will
* contain the byte stream
*
* RETURN: Status
*
* DESCRIPTION: Takes the resource linked list and parses it, creating a
* byte stream of resources in the caller's output buffer
*
******************************************************************************/
ACPI_STATUS
AcpiRsConvertResourcesToAml (
ACPI_RESOURCE *Resource,
ACPI_SIZE AmlSizeNeeded,
UINT8 *OutputBuffer)
{
UINT8 *Aml = OutputBuffer;
UINT8 *EndAml = OutputBuffer + AmlSizeNeeded;
ACPI_RSCONVERT_INFO *ConversionTable;
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (RsConvertResourcesToAml);
/* Walk the resource descriptor list, convert each descriptor */
while (Aml < EndAml)
{
/* Validate the (internal) Resource Type */
if (Resource->Type > ACPI_RESOURCE_TYPE_MAX)
{
ACPI_ERROR ((AE_INFO,
"Invalid descriptor type (0x%X) in resource list",
Resource->Type));
return_ACPI_STATUS (AE_BAD_DATA);
}
/* Perform the conversion */
if (Resource->Type == ACPI_RESOURCE_TYPE_SERIAL_BUS)
{
if (Resource->Data.CommonSerialBus.Type > AML_RESOURCE_MAX_SERIALBUSTYPE)
{
ConversionTable = NULL;
}
else
{
/* This is an I2C, SPI, or UART SerialBus descriptor */
ConversionTable = AcpiGbl_ConvertResourceSerialBusDispatch[
Resource->Data.CommonSerialBus.Type];
}
}
else
{
ConversionTable = AcpiGbl_SetResourceDispatch[Resource->Type];
}
if (!ConversionTable)
{
ACPI_ERROR ((AE_INFO,
"Invalid/unsupported resource descriptor: Type 0x%2.2X",
Resource->Type));
return (AE_AML_INVALID_RESOURCE_TYPE);
}
Status = AcpiRsConvertResourceToAml (Resource,
ACPI_CAST_PTR (AML_RESOURCE, Aml),
ConversionTable);
if (ACPI_FAILURE (Status))
{
ACPI_EXCEPTION ((AE_INFO, Status,
"Could not convert resource (type 0x%X) to AML",
Resource->Type));
return_ACPI_STATUS (Status);
}
/* Perform final sanity check on the new AML resource descriptor */
Status = AcpiUtValidateResource (
ACPI_CAST_PTR (AML_RESOURCE, Aml), NULL);
if (ACPI_FAILURE (Status))
{
return_ACPI_STATUS (Status);
}
/* Check for end-of-list, normal exit */
if (Resource->Type == ACPI_RESOURCE_TYPE_END_TAG)
{
/* An End Tag indicates the end of the input Resource Template */
return_ACPI_STATUS (AE_OK);
}
/*
* Extract the total length of the new descriptor and set the
* Aml to point to the next (output) resource descriptor
*/
Aml += AcpiUtGetDescriptorLength (Aml);
/* Point to the next input resource descriptor */
Resource = ACPI_NEXT_RESOURCE (Resource);
}
/* Completed buffer, but did not find an EndTag resource descriptor */
return_ACPI_STATUS (AE_AML_NO_RESOURCE_END_TAG);
}
<|start_filename|>metis/lib/keyvals_array.c<|end_filename|>
#include "pchandler.h"
#include "bsearch.h"
#include "value_helper.h"
#include "bench.h"
#include <string.h>
#include <assert.h>
#ifdef JOS_USER
//#include <inc/compiler.h>
#endif
static key_cmp_t JSHARED_ATTR keycmp = 0;
enum { init_array_size = 8 };
static void
pch_set_util(key_cmp_t keycmp_)
{
keycmp = keycmp_;
}
static void
pch_init(void *coll)
{
memset(coll, 0, sizeof(keyvals_arr_t));
}
static int
keyvals_cmp(const void *k1, const void *k2)
{
keyvals_t *p1 = (keyvals_t *) k1;
keyvals_t *p2 = (keyvals_t *) k2;
return keycmp(p1->key, p2->key);
}
static void
checkfull(keyvals_arr_t * arr)
{
if (arr->alloc_len == 0) {
arr->alloc_len = init_array_size;
arr->arr = malloc(arr->alloc_len * sizeof(keyvals_t));
} else if (arr->len == arr->alloc_len) {
arr->alloc_len *= 2;
assert(arr->arr =
realloc(arr->arr, arr->alloc_len * sizeof(keyvals_t)));
}
}
static void
pch_append_kvs(void *coll, const keyvals_t * kvs)
{
keyvals_arr_t *arr = (keyvals_arr_t *) coll;
checkfull(coll);
arr->arr[arr->len++] = *kvs;
}
static void
pch_insert_kvs(void *coll, const keyvals_t * kvs)
{
keyvals_arr_t *arr = (keyvals_arr_t *) coll;
checkfull(arr);
int bfound = 0;
int dst = bsearch_eq(kvs, arr->arr, arr->len, sizeof(keyvals_t),
keyvals_cmp, &bfound);
assert(!bfound);
if (dst < arr->len)
memmove(&arr->arr[dst + 1], &arr->arr[dst],
sizeof(keyvals_t) * (arr->len - dst));
arr->arr[dst] = *kvs;
arr->len++;
}
static int
pch_insert_kv(void *coll, void *key, void *val, size_t keylen, unsigned hash)
{
keyvals_arr_t *arr = (keyvals_arr_t *) coll;
int bfound = 0;
keyvals_t tmp;
tmp.key = key;
int dst = bsearch_eq(&tmp, arr->arr, arr->len, sizeof(keyvals_t),
keyvals_cmp, &bfound);
if (bfound) {
values_insert(&arr->arr[dst], val);
return 0;
}
// insert the node into the keynode set
checkfull(arr);
if (dst < arr->len)
memmove(&arr->arr[dst + 1], &arr->arr[dst],
sizeof(keyvals_t) * (arr->len - dst));
arr->len++;
arr->arr[dst].alloc_len = 0;
arr->arr[dst].len = 0;
arr->arr[dst].hash = hash;
if (keylen && mrkeycopy)
arr->arr[dst].key = mrkeycopy(key, keylen);
else
arr->arr[dst].key = key;
values_insert(&arr->arr[dst], val);
return 1;
}
static uint64_t
pch_get_len(void *coll)
{
assert(coll);
return ((keyvals_arr_t *) coll)->len;
}
typedef struct {
int next;
} iter_t;
static int
pch_iter_begin(void *coll, void **iter_)
{
if (!coll) {
*iter_ = 0;
return 1;
}
iter_t *iter;
assert(iter = (iter_t *) malloc(sizeof(iter_t)));
iter->next = 0;
*iter_ = iter;
return 0;
}
static int
pch_iter_next_kvs(void *coll, keyvals_t * kvs, void *iter_, int bclear)
{
keyvals_arr_t *arr = (keyvals_arr_t *) coll;
iter_t *iter = (iter_t *) iter_;
if (iter->next == arr->len)
return 1;
*kvs = arr->arr[iter->next];
if (bclear)
memset(&arr->arr[iter->next], 0, sizeof(keyvals_t));
iter->next++;
return 0;
}
static void
pch_iter_end(void *iter)
{
if (iter)
free(iter);
}
static size_t
pch_get_pair_size(void)
{
return sizeof(keyvals_t);
}
static size_t
pch_get_parr_size(void)
{
return sizeof(keyvals_arr_t);
}
static void *
pch_get_arr_elems(void *coll)
{
return ((keyvals_arr_t *) coll)->arr;
}
static void *
pch_get_key(const void *pair)
{
return ((keyvals_t *) pair)->key;
}
static void
pch_set_elems(void *coll, void *elems, int len)
{
keyvals_arr_t *arr = (keyvals_arr_t *) coll;
arr->arr = elems;
arr->len = len;
arr->alloc_len = len;
}
static void
pch_shallow_free(void *coll)
{
assert(coll);
keyvals_arr_t *parr = (keyvals_arr_t *) coll;
if (parr->arr) {
free(parr->arr);
parr->arr = NULL;
parr->len = 0;
}
}
const pc_handler_t hkvsarr = {
.pch_set_util = pch_set_util,
.pch_init = pch_init,
.pch_insert_kv = pch_insert_kv,
.pch_insert_kvs = pch_insert_kvs,
.pch_append_kvs = pch_append_kvs,
.pch_iter_begin = pch_iter_begin,
.pch_iter_next_kvs = pch_iter_next_kvs,
.pch_iter_end = pch_iter_end,
.pch_get_len = pch_get_len,
.pch_get_pair_size = pch_get_pair_size,
.pch_get_parr_size = pch_get_parr_size,
.pch_get_arr_elems = pch_get_arr_elems,
.pch_get_key = pch_get_key,
.pch_set_elems = pch_set_elems,
.pch_shallow_free = pch_shallow_free,
};
<|start_filename|>bin/forktest.cc<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include "amd64.h"
#include "xsys.h"
#if !defined(XV6_USER)
#include <sys/wait.h>
#else
#include "types.h"
#include "user.h"
#endif
int nfork;
#if defined(XV6_USER) && defined(HW_ben)
int get_cpu_order(int thread)
{
const int cpu_order[] = {
// Socket 0
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
// Socket 1
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
// Socket 3
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
// Socket 2
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
// Socket 5
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
// Socket 4
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
// Socket 6
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
// Socket 7
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
};
return cpu_order[thread];
}
#else
int get_cpu_order(int thread)
{
return thread;
}
#endif
void child(int id)
{
// printf("run client %d on cpu %d\n", getpid(), id);
if (setaffinity(get_cpu_order(id)) < 0)
die("setaffinity err");
uint64_t t0 = rdtsc();
for (int i = 0; i < nfork; i++) {
int pid = fork();
if (pid < 0) {
die("fork in child failed\n");
}
if (pid == 0) {
exit(0);
} else {
if (wait(NULL) < 0) {
die("wait in child failed\n");
}
}
}
uint64_t t1 = rdtsc();
printf("client %d ncycles %lu for nfork %d cycles/fork %lu\n", getpid(), t1-t0, nfork, (t1-t0)/nfork);
}
int
main(int argc, char *argv[])
{
int ncore;
if (argc < 3) {
fprintf(stderr, "Usage: %s ncore nfork\n", argv[0]);
exit(-1);
}
ncore = atoi(argv[1]);
nfork = atoi(argv[2]);
uint64_t t0 = rdtsc();
uint64_t usec0 = now_usec();
for (int i = 0; i < ncore; i++) {
int pid = fork();
if (pid < 0) {
die("fork failed");
}
if (pid == 0) {
child(i);
exit(0);
}
}
for (int i = 0; i < ncore; i++) {
wait(NULL);
}
uint64_t t1 = rdtsc();
uint64_t usec1 = now_usec();
printf("%d %f # ncores tput in forks/msec; ncycles %lu nfork %d cycles/fork %lu\n", ncore, 1000.0 * ((double) nfork * ncore)/(usec1-usec0), t1-t0, nfork, (t1-t0)/nfork);
return 0;
}
<|start_filename|>include/cpputil.hh<|end_filename|>
#pragma once
#ifdef XV6_KERNEL
#include "kernel.hh"
#endif
#include <string.h>
#include <type_traits>
#include <utility>
#include <new>
using std::pair;
using std::make_pair;
template<int N>
class strbuf {
public:
char buf_[N];
strbuf() {
if (N > 0)
buf_[0] = '\0';
}
strbuf(const char *s) {
strncpy(buf_, s, N);
}
bool operator==(const strbuf<N> &other) const {
return !strncmp(buf_, other.buf_, N);
}
bool operator!=(const strbuf<N> &other) const {
return !operator==(other);
}
bool operator<(const strbuf<N> &other) const {
return strncmp(buf_, other.buf_, N) < 0;
}
};
#ifdef XV6_KERNEL
namespace std {
struct ostream { int next_width; };
extern ostream cout;
static inline
ostream& operator<<(ostream &s, const char *str) {
if (!str)
str = "(null)";
int len = strlen(str);
cprintf("%s", str);
while (len < s.next_width) {
cprintf(" ");
len++;
}
s.next_width = 0;
return s;
}
static inline
ostream& operator<<(ostream &s, u32 v) {
char buf[32];
snprintf(buf, sizeof(buf), "%d", v);
return s << buf;
}
static inline
ostream& operator<<(ostream &s, u64 v) {
char buf[32];
snprintf(buf, sizeof(buf), "%ld", v);
return s << buf;
}
static inline
ostream& operator<<(ostream &s, ostream& (*xform)(ostream&)) {
return xform(s);
}
static inline ostream& endl(ostream &s) { s << "\n"; return s; }
static inline ostream& left(ostream &s) { return s; }
struct ssetw { int _n; };
static inline ssetw setw(int n) { return { n }; }
static inline
ostream& operator<<(ostream &s, const ssetw &sw) {
s.next_width = sw._n;
return s;
}
}
#endif
/* C++ runtime */
/* Ref: http://sourcery.mentor.com/public/cxx-abi/abi.html */
extern "C" void __cxa_pure_virtual(void);
extern "C" int __cxa_guard_acquire(s64 *guard_object);
extern "C" void __cxa_guard_release(s64 *guard_object);
extern "C" void __cxa_guard_abort(s64 *guard_object);
extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
extern void *__dso_handle;
#define NEW_DELETE_OPS(classname) \
static void* operator new(unsigned long nbytes, \
const std::nothrow_t&) noexcept { \
assert(nbytes == sizeof(classname)); \
return kmalloc(sizeof(classname), #classname); \
} \
\
static void* operator new(unsigned long nbytes) { \
void *p = classname::operator new(nbytes, std::nothrow); \
if (p == nullptr) \
throw_bad_alloc(); \
return p; \
} \
\
static void* operator new(unsigned long nbytes, classname *buf) { \
assert(nbytes == sizeof(classname)); \
return buf; \
} \
\
static void operator delete(void *p, \
const std::nothrow_t&) noexcept { \
kmfree(p, sizeof(classname)); \
} \
\
static void operator delete(void *p) { \
classname::operator delete(p, std::nothrow); \
}
template<class T>
class scoped_cleanup_obj {
private:
T handler_;
bool active_;
public:
scoped_cleanup_obj(const T& h) : handler_(h), active_(true) {};
~scoped_cleanup_obj() { if (active_) handler_(); }
void dismiss() { active_ = false; }
void operator=(const scoped_cleanup_obj&) = delete;
scoped_cleanup_obj(const scoped_cleanup_obj&) = delete;
scoped_cleanup_obj(scoped_cleanup_obj&& other) :
handler_(other.handler_), active_(other.active_) { other.dismiss(); }
};
template<class T>
scoped_cleanup_obj<T>
scoped_cleanup(const T& h)
{
return scoped_cleanup_obj<T>(h);
}
static void inline
throw_bad_alloc()
{
#if EXCEPTIONS
throw std::bad_alloc();
#else
panic("bad alloc");
#endif
}
<|start_filename|>include/fmt.hh<|end_filename|>
void vprintfmt(void (*putch)(int, void*), void *putdat,
const char *fmt, va_list ap);
<|start_filename|>libutil/include/ref.hh<|end_filename|>
#pragma once
#include <cstdint>
#include <type_traits>
#include <utility>
template <class T, typename = void>
class sref {
private:
constexpr explicit sref(T* p) noexcept : ptr_(p) { }
// Allow access to ptr_ from up-conversions
template<typename, typename>
friend class sref;
public:
constexpr sref() noexcept : ptr_(nullptr) { }
// Yes, we need to duplicate the standard and is_convertible
// constructors and assignment methods, even though the
// is_convertible ones logically suffice. If we don't write the
// standard methods, C++ will helpfully give us default
// implementations for them.
sref(const sref &o) : ptr_(o.ptr_) {
if (ptr_)
ptr_->inc();
}
template<typename U, typename = typename
std::enable_if<std::is_convertible<U*, T*>::value>::type>
sref(const sref<U> &o) : ptr_(o.ptr_) {
if (ptr_)
ptr_->inc();
}
sref(sref &&o) noexcept : ptr_(o.ptr_)
{
o.ptr_ = nullptr;
}
template<typename U, typename = typename
std::enable_if<std::is_convertible<U*, T*>::value>::type>
sref(sref<U> &&o) noexcept : ptr_(o.ptr_)
{
o.ptr_ = nullptr;
}
~sref() {
if (ptr_)
ptr_->dec();
}
sref& operator=(const sref& o) {
T *optr = o.ptr_;
if (optr != ptr_) {
if (optr)
optr->inc();
if (ptr_)
ptr_->dec();
ptr_ = optr;
}
return *this;
}
template<typename U, typename = typename
std::enable_if<std::is_convertible<U*, T*>::value>::type>
sref& operator=(const sref<U>& o) {
T *optr = o.ptr_;
if (optr != ptr_) {
if (optr)
optr->inc();
if (ptr_)
ptr_->dec();
ptr_ = optr;
}
return *this;
}
sref& operator=(sref&& o) {
if (ptr_)
ptr_->dec();
ptr_ = o.ptr_;
o.ptr_ = nullptr;
return *this;
}
template<typename U, typename = typename
std::enable_if<std::is_convertible<U*, T*>::value>::type>
sref& operator=(sref<U>&& o) {
if (ptr_)
ptr_->dec();
ptr_ = o.ptr_;
o.ptr_ = nullptr;
return *this;
}
// Transfer ownership of a pointer to this sref. This *does not*
// increment the reference count and is primarily meant for getting
// srefs for freshly allocated objects that have come with an
// implicit reference count of 1.
static constexpr sref transfer(T* p) {
return sref(p);
}
// Transfer ownership of this sref to a pointer, clearing this sref.
// This *does not* decrement the reference count and is meant for
// transitioning an automatic reference to a manual one.
T* transfer_to_ptr() {
T* res = ptr_;
ptr_ = nullptr;
return res;
}
// Create a new reference to a pointer. This *does* increment the
// reference count and is primarily meant for transferring between
// manual pointer-based reference counting and automatic counting.
// The caller must ensure that it is valid to increment the
// reference count (for example, the count is not currently zero).
static sref newref(T* p) {
if (p)
p->inc();
return sref(p);
}
void reset()
{
if (ptr_) {
ptr_->dec();
ptr_ = nullptr;
}
}
bool init(T* p) {
if (ptr_ || !p->tryinc())
return false;
ptr_ = p;
return true;
}
bool operator==(const sref<T>& pr) const { return ptr_ == pr.ptr_; }
bool operator!=(const sref<T>& pr) const { return ptr_ != pr.ptr_; }
bool operator==(T* p) const { return ptr_ == p; }
bool operator!=(T* p) const { return ptr_ != p; }
explicit operator bool() const noexcept { return !!ptr_; }
T * operator->() const noexcept { return ptr_; }
T & operator*() const noexcept { return *ptr_; }
T * get() const noexcept { return ptr_; }
private:
T *ptr_;
};
template<typename T, typename... Args>
sref<T> make_sref(Args&&... args)
{
return sref<T>::transfer(new T(std::forward<Args>(args)...));
}
class referenced {
public:
// Start with 1 reference by default
referenced(uint64_t refcount = 1) { ref_.v = refcount - 1; }
// The number of valid references is:
// ref_.invalid ? 0 : ref_.count+1;
inline void inc() {
asm volatile("lock; incq %0" : "+m" (ref_.v) :: "memory", "cc");
}
// Attempt to increment the reference count, failing if the count is
// currently zero. If there is ever a tryinc from zero, the count
// will remain zero forever after.
inline bool tryinc() {
// If references is 0 (i.e. ref_.count is 0xffffffff) a 32-bit
// increment will increases ref_.count to 0, but ref_.invalid
// will remain unchanged.
asm volatile("lock; incl %0" : "+m" (ref_.count) :: "memory", "cc");
return ref_.invalid == 0;
}
inline void dec() {
unsigned char c;
// If references is 1 (i.e. ref_.v is 0), a 64-bit decrement will
// underflow ref_.invalid to 0xffffffff (and ref_.count to 0xffffffff).
asm volatile("lock; decq %0; sets %1" : "+m" (ref_.v), "=qm" (c)
:: "memory", "cc");
if (c)
onzero();
}
uint64_t get_consistent() const {
return ref_.invalid ? 0 : (ref_.count + 1);
}
protected:
virtual ~referenced() { }
virtual void onzero() { delete this; }
private:
mutable union {
volatile uint64_t v;
struct {
volatile uint32_t count;
volatile uint32_t invalid;
};
} ref_;
};
<|start_filename|>stdinc/xv6/perf.h<|end_filename|>
#pragma once
#include "compiler.h"
BEGIN_DECLS
void perf_stop(void);
void perf_start(u64 selector, u64 period);
END_DECLS
<|start_filename|>bin/spam.h<|end_filename|>
#include <string.h>
#include <unistd.h>
static int isLegit()
{
char buf[1024];
while (read(0, buf, 1024) > 0) {
if (strstr(buf, "SPAM") != NULL) {
return 0;
}
}
return 1;
}
<|start_filename|>include/lockstat.h<|end_filename|>
#include "ilist.hh"
#define LOCKSTAT_MAGIC 0xb4cd79c1b2e46f40ull
#if __cplusplus
#include "gc.hh"
#include "uk/lockstat.h"
struct klockstat : public rcu_freed {
u64 magic;
// LIST_ENTRY(klockstat) link;
ilink<klockstat> link;
struct lockstat s;
klockstat(const char *name);
void do_gc() override { delete this; }
static void* operator new(unsigned long nbytes);
static void operator delete(void *p);
};
#else
struct klockstat;
#endif
<|start_filename|>bin/forkexectree.cc<|end_filename|>
#include "types.h"
#include "user.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NCHILD 2
#define NDEPTH 5
void
forktree(int depth)
{
if (depth == 0) {
printf("%d: forkexectree\n", getpid());
}
if (depth >= NDEPTH)
exit(0);
for (int i = 0; i < NCHILD; i++) {
int pid = fork();
if (pid < 0) {
die("fork error");
}
if (pid == 0) {
depth++;
char depthbuf[16];
snprintf(depthbuf, sizeof(depthbuf), "%d", depth);
const char *av[] = { "forkexectree", depthbuf, 0 };
int r = execv("forkexectree", const_cast<char * const *>(av));
die("forkexectree: exec failed %d", r);
}
}
for (int i = 0; i < NCHILD; i++) {
if (wait(NULL) < 0) {
die("wait stopped early");
}
}
if (wait(NULL) != -1) {
die("wait got too many");
}
if (depth > 0)
exit(0);
printf("%d: forkexectree OK\n", getpid());
// halt();
}
int
main(int ac, char **av)
{
if (ac == 1) {
forktree(0);
} else {
forktree(atoi(av[1]));
}
return 0;
}
<|start_filename|>metis/app/linear_regression.c<|end_filename|>
/* Copyright (c) 2007, Stanford University
* All rights reserved.
*
* 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.
* * Neither the name of Stanford University nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY 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.
*/
#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <sched.h>
#include <time.h>
#include <sys/time.h>
#include "mr-sched.h"
#include "bench.h"
typedef struct {
char x;
char y;
} POINT_T;
enum {
KEY_SX = 0,
KEY_SY,
KEY_SXX,
KEY_SYY,
KEY_SXY,
};
static int
intkeycmp(const void *v1, const void *v2)
{
prof_enterkcmp();
int res;
long int i1 = (long int) v1;
long int i2 = (long int) v2;
if (i1 < i2)
res = 1;
else if (i1 > i2)
res = -1;
else
res = 0;
prof_leavekcmp();
return res;
}
static unsigned int
linear_regression_partition(void *key, int key_size)
{
prof_enterapp();
size_t hash = 5381;
char *str = (char *) &key;
for (int i = 0; i < key_size; i++)
hash = ((hash << 5) + hash) + ((unsigned) str[i]);
prof_leaveapp();
return hash % ((unsigned) (-1));
}
/** sort_map()
* Sorts based on the val output of wordcount
*/
static void
linear_regression_map(split_t * args)
{
assert(args);
POINT_T *data = (POINT_T *) args->data;
assert(data);
prof_enterapp();
long long SX, SXX, SY, SYY, SXY;
SX = SXX = SY = SYY = SXY = 0;
assert(args->length % sizeof(POINT_T) == 0);
for (long i = 0; i < args->length / sizeof(POINT_T); i++) {
//Compute SX, SY, SYY, SXX, SXY
SX += data[i].x;
SXX += data[i].x * data[i].x;
SY += data[i].y;
SYY += data[i].y * data[i].y;
SXY += data[i].x * data[i].y;
}
prof_leaveapp();
mr_map_emit((void *) KEY_SX, (void *) SX, sizeof(void *));
mr_map_emit((void *) KEY_SXX, (void *) SXX, sizeof(void *));
mr_map_emit((void *) KEY_SY, (void *) SY, sizeof(void *));
mr_map_emit((void *) KEY_SYY, (void *) SYY, sizeof(void *));
mr_map_emit((void *) KEY_SXY, (void *) SXY, sizeof(void *));
}
/** linear_regression_reduce()
*
*/
static void
linear_regression_reduce(void *key_in, void **vals_in, size_t vals_len)
{
prof_enterapp();
long long *vals = (long long *) vals_in;
long long sum = 0;
assert(vals);
for (int i = 0; i < vals_len; i++)
sum += (uint64_t) vals[i];
prof_enterapp();
mr_reduce_emit(key_in, (void *) sum);
}
static int
linear_regression_combine(void *key_in, void **vals_in, size_t vals_len)
{
prof_enterapp();
long long *vals = (long long *) vals_in;
long long sum = 0;
assert(vals);
for (int i = 0; i < vals_len; i++)
sum += vals[i];
vals[0] = sum;
prof_leaveapp();
return 1;
}
static inline void
lr_usage(char *prog)
{
printf("usage: %s <filename> [options]\n", prog);
printf("options:\n");
printf(" -p #procs : # of processors to use\n");
printf(" -m #map tasks : # of map tasks (pre-split input before MR)\n");
printf(" -r #reduce tasks : # of reduce tasks\n");
printf(" -l ntops : # of top val. pairs to display\n");
printf(" -q : quiet output (for batch test)\n");
printf(" -d : debug output\n");
}
int
main(int argc, char *argv[])
{
final_data_kv_t final_vals;
int fd;
struct defsplitter_state ps;
char *fdata;
char *fname;
struct stat finfo;
int i;
int nprocs = 0, map_tasks = 0, quiet = 0;
int c;
// Make sure a filename is specified
fname = argv[1];
if (argc < 2) {
lr_usage(argv[0]);
exit(EXIT_FAILURE);
}
while ((c = getopt(argc - 1, argv + 1, "p:m:q")) != -1) {
switch (c) {
case 'p':
nprocs = atoi(optarg);
break;
case 'm':
map_tasks = atoi(optarg);
break;
case 'q':
quiet = 1;
break;
default:
lr_usage(argv[0]);
exit(EXIT_FAILURE);
break;
}
}
// Read in the file
assert((fd = open(fname, O_RDONLY)) >= 0);
// Get the file info (for file length)
assert(fstat(fd, &finfo) == 0);
// Memory map the file
assert((fdata = mmap(0, finfo.st_size + 1,
PROT_READ | PROT_WRITE, MAP_PRIVATE, fd,
0)) != MAP_FAILED);
// Setup scheduler args
mr_param_t mr_param;
memset(&mr_param, 0, sizeof(mr_param_t));
mr_param.nr_cpus = nprocs;
mr_param.map_func = linear_regression_map;
mr_param.app_arg.atype = atype_mapreduce;
mr_param.app_arg.mapreduce.reduce_func = linear_regression_reduce;
mr_param.app_arg.mapreduce.combiner = linear_regression_combine;
memset(&final_vals, 0, sizeof(final_vals));
mr_param.app_arg.mapreduce.results = &final_vals;
defsplitter_init(&ps, fdata, finfo.st_size -
(finfo.st_size % sizeof(POINT_T)), map_tasks,
sizeof(POINT_T));
mr_param.split_func = defsplitter; // Array splitter;
mr_param.split_arg = &ps; // Array to regress
mr_param.part_func = linear_regression_partition;
mr_param.key_cmp = intkeycmp;
//#define PREFETCH
#ifdef PREFETCH
int sum = 0;
for (int i = 0; i < finfo.st_size; i += 4096) {
sum += fdata[i];
}
printf("ignore this %d\n", sum);
#endif
mr_print(!quiet, "Linear regression: running...\n");
assert(mr_run_scheduler(&mr_param) == 0);
mr_print_stats();
long long n;
double a, b, xbar, ybar, r2;
long long SX_ll = 0, SY_ll = 0, SXX_ll = 0, SYY_ll = 0, SXY_ll = 0;
// ADD UP RESULTS
for (i = 0; i < final_vals.length; i++) {
keyval_t *curr = &final_vals.data[i];
switch ((long int) curr->key) {
case KEY_SX:
SX_ll = (long long) curr->val;
break;
case KEY_SY:
SY_ll = (long long) curr->val;
break;
case KEY_SXX:
SXX_ll = (long long) curr->val;
break;
case KEY_SYY:
SYY_ll = (long long) curr->val;
break;
case KEY_SXY:
SXY_ll = (long long) curr->val;
break;
default:
// INVALID KEY
assert(0);
break;
}
}
double SX = (double) SX_ll;
double SY = (double) SY_ll;
double SXX = (double) SXX_ll;
double SYY = (double) SYY_ll;
double SXY = (double) SXY_ll;
n = (long long) finfo.st_size / sizeof(POINT_T);
b = (double) (n * SXY - SX * SY) / (n * SXX - SX * SX);
a = (SY_ll - b * SX_ll) / n;
xbar = (double) SX_ll / n;
ybar = (double) SY_ll / n;
r2 = (double) (n * SXY - SX * SY) * (n * SXY -
SX * SY) / ((n * SXX -
SX * SX) * (n * SYY -
SY * SY));
if (!quiet) {
printf("%2d Linear Regression Results:\n", nprocs);
printf("\ta = %lf\n", a);
printf("\tb = %lf\n", b);
printf("\txbar = %lf\n", xbar);
printf("\tybar = %lf\n", ybar);
printf("\tr2 = %lf\n", r2);
printf("\tSX = %lld\n", SX_ll);
printf("\tSY = %lld\n", SY_ll);
printf("\tSXX = %lld\n", SXX_ll);
printf("\tSYY = %lld\n", SYY_ll);
printf("\tSXY = %lld\n", SXY_ll);
}
free(final_vals.data);
assert(munmap(fdata, finfo.st_size + 1) == 0);
assert(close(fd) == 0);
mr_finalize();
return 0;
}
<|start_filename|>bin/fstest.cc<|end_filename|>
#include <assert.h>
#include <stdio.h>
#include <atomic>
#include <new>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <setjmp.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include "mtrace.h"
#include "fstest.h"
#include "libutil.h"
#include "spinbarrier.hh"
#include "elf.hh"
extern char _end[], __ehdr_start[];
__thread sigjmp_buf pf_jmpbuf;
__thread int pf_active;
class double_barrier {
spin_barrier enter_;
spin_barrier exit_;
public:
double_barrier() : enter_(2), exit_(2) {}
void sync() { enter(); exit(); }
void enter() { enter_.join(); }
void exit() { exit_.join(); }
};
struct testproc {
double_barrier setup;
std::atomic<void (*)(void)> setupf1;
std::atomic<void (*)(void)> setupf2;
testproc(void (*s1)(void), void (*s2)(void)) : setupf1(s1), setupf2(s2) {}
void run() {
setup.enter();
setupf1();
setupf2();
setup.exit();
}
};
struct testfunc {
double_barrier start;
double_barrier stop;
std::atomic<int (*)(void)> func;
std::atomic<int> retval;
testfunc(int (*f)(void)) : func(f) {}
void run() {
#ifndef XV6_USER
errno = 0;
#endif
start.sync();
retval = func();
stop.sync();
}
};
// Ensure entire binary is paged in, to avoid spurious page faults
// during testing
static void
pagein()
{
elfhdr *ehdr = (elfhdr*)__ehdr_start;
assert(ehdr->magic == ELF_MAGIC);
for (size_t i = 0; i < ehdr->phnum; i++) {
proghdr *phdr = (proghdr*)(
(uintptr_t)ehdr + ehdr->phoff + i * ehdr->phentsize);
if (phdr->type == ELF_PROG_LOAD) {
char *ptr = (char*)phdr->vaddr;
while (ptr < (char*)(phdr->vaddr + phdr->memsz)) {
*(volatile char *)ptr;
ptr += 4096;
}
}
}
}
static void*
testfunc_thread(void* arg)
{
pagein();
testfunc* f = (testfunc*) arg;
f->run();
return nullptr;
}
static void
run_test(testproc* tp, testfunc* tf, fstest* t, int first_func, bool do_pin)
{
assert(first_func == 0 || first_func == 1);
if (do_pin)
setaffinity(2);
for (int i = 0; i < 2; i++)
new (&tp[i]) testproc(t->proc[i].setup_proc, t->setup_procfinal);
for (int i = 0; i < 2; i++)
new (&tf[i]) testfunc(t->func[i].call);
t->setup_common();
pid_t pids[2] = { 0, 0 };
for (int p = 0; p < 2; p++) {
int nfunc = 0;
for (int f = 0; f < 2; f++)
if (t->func[f].callproc == p)
nfunc++;
if (nfunc == 0)
continue;
fflush(stdout);
if (do_pin) {
for (int f = 0; f < 2; f++) {
if (t->func[f].callproc == p) {
setaffinity(f+2);
break;
}
}
}
pids[p] = fork();
assert(pids[p] >= 0);
if (pids[p] == 0) {
// Get all text and data structures
pagein();
// Prime the VM system (this must be kept in sync with
// fs_testgen.py)
void *r = mmap((void*)0x12345600000, 4 * 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
if (r == (void*)-1)
setup_error("mmap (fixed)");
munmap(r, 4 * 4096);
r = mmap(0, 4 * 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (r == (void*)-1)
setup_error("mmap (non-fixed)");
munmap(r, 4 * 4096);
// Run setup
tp[p].run();
int ndone = 0;
pthread_t tid[2];
for (int f = 0; f < 2; f++) {
if (t->func[f].callproc == p) {
if (do_pin)
setaffinity(f);
ndone++;
if (ndone == nfunc)
testfunc_thread(&tf[f]);
else
pthread_create(&tid[f], 0, testfunc_thread, (void*) &tf[f]);
}
}
if (nfunc == 2)
pthread_join(tid[0], nullptr);
exit(0);
}
}
for (int p = 0; p < 2; p++) if (pids[p]) tp[p].setup.sync();
t->setup_final();
for (int i = 0; i < 2; i++) tf[i].start.enter();
char mtname[64];
snprintf(mtname, sizeof(mtname), "%s", t->testname);
mtenable_type(mtrace_record_ascope, mtname);
for (int i = 0; i < 2; i++) {
tf[first_func ^ i].start.exit();
tf[first_func ^ i].stop.enter();
}
mtdisable(mtname);
for (int i = 0; i < 2; i++) tf[i].stop.exit();
for (int p = 0; p < 2; p++)
if (pids[p])
assert(waitpid(pids[p], nullptr, 0) >= 0);
t->cleanup();
}
static void
pf_handler(int signo)
{
if (pf_active)
siglongjmp(pf_jmpbuf, signo);
// Let the error happen
signal(signo, SIG_DFL);
}
static bool verbose = false;
static bool check_commutativity = false;
static bool run_threads = false;
static bool check_results = false;
static fstest *cur_test = nullptr;
void
expect_result(const char *varname, long got, long expect)
{
if (!check_results) return;
if (got == expect) return;
auto name = cur_test->testname;
#ifdef XV6_USER
printf("%s: expected %s == %ld, got %ld\n",
name, varname, expect, got);
#else
printf("%s: expected %s == %ld, got %ld (errno %s)\n",
name, varname, expect, got, strerror(errno));
#endif
}
void
expect_errno(int expect)
{
#ifndef XV6_USER
if (!check_results) return;
if (errno == expect) return;
auto name = cur_test->testname;
printf("%s: expected errno == %s, got %s\n",
name, strerror(expect), strerror(errno));
#endif
}
static void
usage(const char* prog)
{
fprintf(stderr, "Usage: %s [-v] [-c] [-t] [-r] [-n NPARTS] [-p THISPART] [min[-max]]\n", prog);
}
int
main(int ac, char** av)
{
uint32_t min = 0;
uint32_t max;
int nparts = -1;
int thispart = -1;
uint32_t ntests = 0;
for (ntests = min; fstests[ntests].testname; ntests++)
;
max = ntests - 1;
for (;;) {
int opt = getopt(ac, av, "vctrp:n:");
if (opt == -1)
break;
switch (opt) {
case 'v':
verbose = true;
break;
case 'c':
check_commutativity = true;
break;
case 't':
run_threads = true;
break;
case 'r':
run_threads = true;
check_results = true;
break;
case 'n':
nparts = atoi(optarg);
break;
case 'p':
thispart = atoi(optarg);
break;
default:
usage(av[0]);
return -1;
}
}
if (optind < ac) {
bool found = false;
for (uint32_t t = 0; t < ntests && !found; t++) {
if (strcmp(av[optind], fstests[t].testname) == 0) {
min = max = t;
found = true;
}
}
if (!found) {
char* dash = strchr(av[optind], '-');
if (!dash) {
min = max = atoi(av[optind]);
} else {
*dash = '\0';
if (av[optind])
min = atoi(av[optind]);
if (*(dash + 1))
max = atoi(dash + 1);
}
}
} else if (nparts >= 0 || thispart >= 0) {
if (nparts < 0 || thispart < 0) {
usage(av[0]);
return -1;
}
uint32_t partsize = (ntests + nparts - 1) /nparts;
min = partsize * thispart;
max = partsize * (thispart + 1) - 1;
}
if (!check_commutativity && !run_threads) {
fprintf(stderr, "Must specify one of -c or -t\n");
usage(av[0]);
return -1;
}
printf("fstest:");
if (verbose)
printf(" verbose");
if (check_commutativity)
printf(" check");
if (run_threads)
printf(" threads");
if (check_results)
printf(" results");
if (min == 0 && max == ntests - 1)
printf(" all");
else if (min == max)
printf(" %d", min);
else
printf(" %d-%d", min, max);
printf("\n");
testproc* tp = (testproc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
assert(tp != MAP_FAILED);
assert(2*sizeof(*tp) <= 4096);
testfunc* tf = (testfunc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
assert(tf != MAP_FAILED);
assert(2*sizeof(*tf) <= 4096);
madvise(0, (size_t) _end, MADV_WILLNEED);
signal(SIGPIPE, SIG_IGN);
signal(SIGBUS, pf_handler);
signal(SIGSEGV, pf_handler);
for (uint32_t t = min; t <= max && t < ntests; t++) {
cur_test = &fstests[t];
if (verbose)
printf("%s (test %d) starting\n", fstests[t].testname, t);
if (check_commutativity) {
run_test(tp, tf, &fstests[t], 0, false);
int ra0 = tf[0].retval;
int ra1 = tf[1].retval;
run_test(tp, tf, &fstests[t], 1, false);
int rb0 = tf[0].retval;
int rb1 = tf[1].retval;
if (ra0 == rb0 && ra1 == rb1) {
if (verbose)
printf("%s: commutes: %s->%d %s->%d\n",
fstests[t].testname,
fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1);
} else {
printf("%s: diverges: %s->%d %s->%d vs %s->%d %s->%d\n",
fstests[t].testname,
fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1,
fstests[t].func[1].callname, rb1, fstests[t].func[0].callname, rb0);
}
}
if (run_threads) {
run_test(tp, tf, &fstests[t], 0, true);
}
}
printf("fstest: done\n");
return 0;
}
<|start_filename|>kernel/acpica/source/tools/acpixtract/Makefile<|end_filename|>
#
# acpixtract - extract binary ACPI tables from acpidump text output
#
# NOTE: This makefile is intended to be used within the native
# ACPICA source tree.
#
#
# Configuration
# Notes:
# gcc should be version 4 or greater, otherwise some of the options
# used will not be recognized.
# Global optimization flags (such as -O2, -Os) are not used, since
# they cause issues on some compilers.
# The _GNU_SOURCE symbol is required for many hosts.
#
PROG = acpixtract
HOST = _LINUX
NOMAN = YES
COMPILE = $(CC) -c $(CFLAGS) $(CWARNINGFLAGS) -o$@ $<
ACPICA_SRC = ../../../source
ACPICA_COMMON = $(ACPICA_SRC)/common
ACPICA_TOOLS = $(ACPICA_SRC)/tools
ACPICA_OSL = $(ACPICA_SRC)/os_specific/service_layers
ACPICA_CORE = $(ACPICA_SRC)/components
ACPICA_INCLUDE = $(ACPICA_SRC)/include
ACPICA_DEBUGGER = $(ACPICA_CORE)/debugger
ACPICA_DISASSEMBLER = $(ACPICA_CORE)/disassembler
ACPICA_DISPATCHER = $(ACPICA_CORE)/dispatcher
ACPICA_EVENTS = $(ACPICA_CORE)/events
ACPICA_EXECUTER = $(ACPICA_CORE)/executer
ACPICA_HARDWARE = $(ACPICA_CORE)/hardware
ACPICA_NAMESPACE = $(ACPICA_CORE)/namespace
ACPICA_PARSER = $(ACPICA_CORE)/parser
ACPICA_RESOURCES = $(ACPICA_CORE)/resources
ACPICA_TABLES = $(ACPICA_CORE)/tables
ACPICA_UTILITIES = $(ACPICA_CORE)/utilities
ACPIXTRACT = $(ACPICA_TOOLS)/acpixtract
INSTALLDIR = /usr/bin
INSTALLPROG = cp --remove-destination $(PROG) $(INSTALLDIR)
ACPICA_HEADERS = \
$(wildcard $(ACPICA_INCLUDE)/*.h) \
$(wildcard $(ACPICA_INCLUDE)/platform/*.h)
#
# Search paths for source files
#
vpath %.c \
$(ACPIXTRACT) \
$(ACPICA_COMMON)
HEADERS = \
$(wildcard $(ACPIXTRACT)/*.h)
OBJECTS = \
acpixtract.o \
axmain.o \
getopt.o
CFLAGS+= \
-D$(HOST) \
-D_GNU_SOURCE \
-DACPI_XTRACT_APP \
-I$(ACPICA_INCLUDE)
CWARNINGFLAGS = \
-ansi \
-Wall \
-Wbad-function-cast \
-Wdeclaration-after-statement \
-Werror \
-Wformat=2 \
-Wmissing-declarations \
-Wmissing-prototypes \
-Wstrict-aliasing=0 \
-Wstrict-prototypes \
-Wswitch-default \
-Wpointer-arith \
-Wundef
#
# gcc 4+ flags
#
CWARNINGFLAGS += \
-Waddress \
-Waggregate-return \
-Wchar-subscripts \
-Wempty-body \
-Wlogical-op \
-Wmissing-declarations \
-Wmissing-field-initializers \
-Wmissing-parameter-type \
-Wnested-externs \
-Wold-style-declaration \
-Wold-style-definition \
-Wredundant-decls \
-Wtype-limits
#
# Rules
#
$(PROG) : $(OBJECTS)
$(CC) $(LDFLAGS) $(OBJECTS) -o $(PROG)
$(COPYPROG)
%.o : %.c $(HEADERS) $(ACPICA_HEADERS)
$(COMPILE)
clean :
rm -f $(PROG) $(PROG).exe $(OBJECTS)
install :
$(INSTALLPROG)
<|start_filename|>stdinc/sys/stat.h<|end_filename|>
#pragma once
#include "compiler.h"
#include <sys/types.h>
#include <uk/stat.h>
#define S_IFCHR (T_DEV << __S_IFMT_SHIFT)
#define S_IFREG (T_FILE << __S_IFMT_SHIFT)
#define S_IFDIR (T_DIR << __S_IFMT_SHIFT)
#define S_IFSOCK (T_SOCKET << __S_IFMT_SHIFT)
#define S_IFIFO (T_FIFO << __S_IFMT_SHIFT)
#define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
#define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
#define S_IRWXU 0700
#define S_IRUSR 0400
#define S_IWUSR 0200
#define S_IXUSR 0100
#define S_IRWXG 070
#define S_IRGRP 040
#define S_IWGRP 020
#define S_IXGRP 010
#define S_IRWXO 07
#define S_IROTH 04
#define S_IWOTH 02
#define S_IXOTH 01
#define S_ISUID 04000
#define S_ISGID 02000
#define S_ISVTX 01000
BEGIN_DECLS
int fstat(int, struct stat *);
int fstatat(int dirfd, const char*, struct stat*);
int mkdir(const char *, mode_t);
int mkdirat(int, const char *, mode_t);
END_DECLS
<|start_filename|>bin/avar.cc<|end_filename|>
// Tests to drive abstract sharing analysis
#include "types.h"
#include "user.h"
#include "mtrace.h"
#include <string.h>
int
main(int ac, char **av)
{
if (ac == 2 && strcmp(av[1], "on") == 0)
mtenable_type(mtrace_record_ascope, "xv6-asharing");
else if (ac == 2 && strcmp(av[1], "onkern") == 0)
mtenable_type(mtrace_record_kernelscope, "xv6-asharing");
else if (ac == 2 && strcmp(av[1], "off") == 0)
mtdisable("xv6-asharing");
else
die("usage: %s on|onkern|off\n", av[0]);
return 0;
}
<|start_filename|>libutil/include/histogram.hh<|end_filename|>
#pragma once
#include <stdio.h>
#include <string.h>
#include <cassert>
#include <cstddef>
#include <cstdint>
template<class T, T Max>
class histogram_log2
{
static constexpr std::size_t
floor_log2_const(T x)
{
return (x == 0) ? (1/x)
: (x == 1) ? 0
: 1 + floor_log2_const(x >> 1);
}
static T
floor_log2(T x)
{
return 8 * sizeof(long long) - __builtin_clzll(x) - 1;
}
T sum_, min_, max_;
T zero_;
T buckets_[floor_log2_const(Max)];
T over_;
enum { NBUCKETS = sizeof(buckets_) / sizeof(buckets_[0]) };
void
get_print_stats(unsigned *lwidth, unsigned *min_bucket,
unsigned *max_bucket) const
{
// Compute the label width. This is fixed, rather than being
// based on used buckets, so that multiple histograms are
// comparable.
char buf[32];
snprintf(buf, sizeof buf, "%llu", (long long unsigned)Max);
*lwidth = strlen(buf);
// Find the minimum used bucket
*min_bucket = 0;
if (!zero_)
for (; *min_bucket < NBUCKETS; ++*min_bucket)
if (buckets_[*min_bucket])
break;
// Find maximum used bucket (plus one, so we always end with a
// zero label)
if (over_) {
*max_bucket = NBUCKETS;
} else {
*max_bucket = 0;
for (std::size_t i = 0; i < NBUCKETS; ++i)
if (buckets_[i])
*max_bucket = i;
if (*max_bucket < NBUCKETS)
++*max_bucket;
}
}
static const char *
get_bar(unsigned width)
{
static const char bar[] = "================================================================================";
unsigned barlen = sizeof(bar) - 1;
assert(width <= barlen);
return &bar[barlen - width];
}
public:
constexpr histogram_log2()
: sum_(0), min_(~0), max_(0), zero_(0), buckets_{}, over_(0)
{
}
histogram_log2 &
operator+=(T val)
{
sum_ += val;
if (val < min_)
min_ = val;
if (val > max_)
max_ = val;
if (val <= 0)
++zero_;
else if (val >= Max)
++over_;
else
++buckets_[floor_log2(val)];
return *this;
}
histogram_log2 &
operator+=(const histogram_log2 &other)
{
sum_ += other.sum_;
if (other.min_ < min_)
min_ = other.min_;
if (other.max_ > max_)
max_ = other.max_;
zero_ += other.zero_;
for (std::size_t i = 0; i < NBUCKETS; ++i)
buckets_[i] += other.buckets_[i];
over_ += other.over_;
return *this;
}
T
sum() const
{
return sum_;
}
T
min() const
{
return min_;
}
T
max() const
{
return max_;
}
T
count() const
{
T res = zero_ + over_;
for (T v : buckets_)
res += v;
return res;
}
T
mean() const
{
return sum_ / count();
}
double
meand() const
{
return sum_ / (double)count();
}
void
print_stats() const
{
if (count() == 0) {
printf("count 0\n");
return;
}
printf("count %llu min %llu mean %llu max %llu\n",
(long long unsigned)count(), (long long unsigned)min(),
(long long unsigned)mean(), (long long unsigned)max());
}
void
print() const
{
unsigned lwidth, min_bucket, max_bucket;
get_print_stats(&lwidth, &min_bucket, &max_bucket);
if (zero_)
printf("%*llu- : %llu\n", lwidth, 0ull, (long long unsigned)zero_);
for (unsigned i = min_bucket; i <= max_bucket; ++i) {
bool last = i == max_bucket;
if (i == NBUCKETS)
printf("%*llu..: %llu\n", lwidth, (long long unsigned)Max,
(long long unsigned)over_);
else
printf("%*llu%s: %llu\n", lwidth, 1ull<<i,
last ? " " : "- ", (long long unsigned)buckets_[i]);
}
}
void
print_bars() const
{
unsigned lwidth, min_bucket, max_bucket;
get_print_stats(&lwidth, &min_bucket, &max_bucket);
unsigned max_count = 0;
for (auto v : buckets_)
if (v > max_count)
max_count = v;
if (max_count == 0) {
printf("%*llu..: \n", lwidth, 0ull);
return;
}
unsigned bar_width = 75 - lwidth;
if (zero_)
printf("%*llu- : %s\n", lwidth, 0ull, get_bar(bar_width * zero_ / max_count));
for (unsigned i = min_bucket; i <= max_bucket; ++i) {
bool last = i == max_bucket;
if (i == NBUCKETS)
printf("%*llu..: %s\n", lwidth, (long long unsigned)Max,
get_bar(bar_width * over_ / max_count));
else
printf("%*llu%s: %s\n", lwidth, 1ull<<i,
last ? " " : "- ",
get_bar(bar_width * buckets_[i] / max_count));
}
}
};
<|start_filename|>stdinc/stdio.h<|end_filename|>
#pragma once
#include <stdarg.h>
#include <sys/stat.h>
BEGIN_DECLS
typedef struct fstream {
int fd;
off_t off;
off_t poff;
struct stat stat;
int err:1;
int eof:1;
int pfill:1;
} FILE;
extern FILE* stdout;
extern FILE* stderr;
int fflush(FILE *stream);
FILE *fdopen(int fd, const char *mode);
int fclose(FILE *fp);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *fp);
int feof(FILE *fp);
int ferror(FILE *fp);
void printf(const char*, ...)
__attribute__((__format__(__printf__, 1, 2)));
void fprintf(FILE*, const char*, ...)
__attribute__((__format__(__printf__, 2, 3)));
void vfprintf(FILE *, const char *fmt, va_list ap);
void snprintf(char *buf, unsigned int n, const char *fmt, ...)
__attribute__((__format__(__printf__, 3, 4)));
void vsnprintf(char *buf, size_t n, const char *fmt, va_list ap);
void dprintf(int, const char*, ...)
__attribute__((__format__(__printf__, 2, 3)));
void vdprintf(int fd, const char *fmt, va_list ap);
/*
* Why does POSIX believe rename() should live in stdio.h? Unclear.
* http://pubs.opengroup.org/onlinepubs/009695399/functions/rename.html
*/
int rename(const char *oldpath, const char *newpath);
END_DECLS
<|start_filename|>libutil/include/enumbitset.hh<|end_filename|>
// Helpers for declaring type-safe enum bit masks
#pragma once
#include <type_traits>
#define ENUM_BITSET_OPS(classname) \
inline constexpr classname \
operator&(classname x, classname y) \
{ \
typedef std::underlying_type<classname>::type int_type; \
return static_cast<classname>( \
static_cast<int_type>(x) & static_cast<int_type>(y)); \
} \
\
inline constexpr classname \
operator|(classname x, classname y) \
{ \
typedef std::underlying_type<classname>::type int_type; \
return static_cast<classname>( \
static_cast<int_type>(x) | static_cast<int_type>(y)); \
} \
\
inline constexpr classname \
operator^(classname x, classname y) \
{ \
typedef std::underlying_type<classname>::type int_type; \
return static_cast<classname>( \
static_cast<int_type>(x) ^ static_cast<int_type>(y)); \
} \
\
inline constexpr classname \
operator~(classname x) \
{ \
typedef std::underlying_type<classname>::type int_type; \
return static_cast<classname>(~static_cast<int_type>(x)); \
} \
\
inline classname& \
operator&=(classname& x, classname y) \
{ \
x = x & y; return x; \
} \
\
inline classname& \
operator|=(classname& x, classname y) \
{ \
x = x | y; return x; \
} \
\
inline classname& \
operator^=(classname& x, classname y) \
{ \
x = x ^ y; return x; \
} \
\
static_assert(true, "semicolon required")
<|start_filename|>libutil/include/rnd.hh<|end_filename|>
#pragma once
#include <stdint.h>
uint64_t rnd();
<|start_filename|>kernel/acpica/source/tools/acpibin/abcompare.c<|end_filename|>
/******************************************************************************
*
* Module Name: abcompare - compare AML files
*
*****************************************************************************/
/******************************************************************************
*
* 1. Copyright Notice
*
* Some or all of this work - Copyright (c) 1999 - 2012, Intel Corp.
* All rights reserved.
*
* 2. License
*
* 2.1. This is your license from Intel Corp. under its intellectual property
* rights. You may have additional license terms from the party that provided
* you this software, covering your right to use that party's intellectual
* property rights.
*
* 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
* copy of the source code appearing in this file ("Covered Code") an
* irrevocable, perpetual, worldwide license under Intel's copyrights in the
* base code distributed originally by Intel ("Original Intel Code") to copy,
* make derivatives, distribute, use and display any portion of the Covered
* Code in any form, with the right to sublicense such rights; and
*
* 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
* license (with the right to sublicense), under only those claims of Intel
* patents that are infringed by the Original Intel Code, to make, use, sell,
* offer to sell, and import the Covered Code and derivative works thereof
* solely to the minimum extent necessary to exercise the above copyright
* license, and in no event shall the patent license extend to any additions
* to or modifications of the Original Intel Code. No other license or right
* is granted directly or by implication, estoppel or otherwise;
*
* The above copyright and patent license is granted only if the following
* conditions are met:
*
* 3. Conditions
*
* 3.1. Redistribution of Source with Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification with rights to further distribute source must include
* the above Copyright Notice, the above License, this list of Conditions,
* and the following Disclaimer and Export Compliance provision. In addition,
* Licensee must cause all Covered Code to which Licensee contributes to
* contain a file documenting the changes Licensee made to create that Covered
* Code and the date of any change. Licensee must include in that file the
* documentation of any changes made by any predecessor Licensee. Licensee
* must include a prominent statement that the modification is derived,
* directly or indirectly, from Original Intel Code.
*
* 3.2. Redistribution of Source with no Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification without rights to further distribute source must
* include the following Disclaimer and Export Compliance provision in the
* documentation and/or other materials provided with distribution. In
* addition, Licensee may not authorize further sublicense of source of any
* portion of the Covered Code, and must include terms to the effect that the
* license from Licensee to its licensee is limited to the intellectual
* property embodied in the software Licensee provides to its licensee, and
* not to intellectual property embodied in modifications its licensee may
* make.
*
* 3.3. Redistribution of Executable. Redistribution in executable form of any
* substantial portion of the Covered Code or modification must reproduce the
* above Copyright Notice, and the following Disclaimer and Export Compliance
* provision in the documentation and/or other materials provided with the
* distribution.
*
* 3.4. Intel retains all right, title, and interest in and to the Original
* Intel Code.
*
* 3.5. Neither the name Intel nor any other trademark owned or controlled by
* Intel shall be used in advertising or otherwise to promote the sale, use or
* other dealings in products derived from or relating to the Covered Code
* without prior written authorization from Intel.
*
* 4. Disclaimer and Export Compliance
*
* 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
* HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
* IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
* INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
* UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
* IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
* OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
* COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
* SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
* CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
* HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
* SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
* LIMITED REMEDY.
*
* 4.3. Licensee shall not export, either directly or indirectly, any of this
* software or system incorporating such software without first obtaining any
* required license or other approval from the U. S. Department of Commerce or
* any other agency or department of the United States Government. In the
* event Licensee exports any such software from the United States or
* re-exports any such software from a foreign destination, Licensee shall
* ensure that the distribution and export/re-export of the software is in
* compliance with all laws, regulations, orders, or other restrictions of the
* U.S. Export Administration Regulations. Licensee agrees that neither it nor
* any of its subsidiaries will export/re-export any technical data, process,
* software, or service, directly or indirectly, to any country for which the
* United States government or any agency thereof requires an export license,
* other governmental approval, or letter of assurance, without first obtaining
* such license, approval or letter.
*
*****************************************************************************/
#include "acpibin.h"
FILE *File1;
FILE *File2;
ACPI_TABLE_HEADER Header1;
ACPI_TABLE_HEADER Header2;
struct stat Gbl_StatBuf;
#define BUFFER_SIZE 256
char Buffer[BUFFER_SIZE];
/* Local prototypes */
static BOOLEAN
AbValidateHeader (
ACPI_TABLE_HEADER *Header);
static UINT8
AcpiTbSumTable (
void *Buffer,
UINT32 Length);
static char *
AbGetFile (
char *Filename,
UINT32 *FileSize);
static void
AbPrintHeaderInfo (
ACPI_TABLE_HEADER *Header);
ACPI_PHYSICAL_ADDRESS
AeLocalGetRootPointer (
void);
/*******************************************************************************
*
* FUNCTION: UtHexCharToValue
*
* PARAMETERS: HexChar - Hex character in Ascii
*
* RETURN: The binary value of the hex character
*
* DESCRIPTION: Perform ascii-to-hex translation
*
******************************************************************************/
static UINT8
UtHexCharToValue (
int HexChar,
UINT8 *OutBinary)
{
if (HexChar >= 0x30 && HexChar <= 0x39)
{
*OutBinary = (UINT8) (HexChar - 0x30);
return (1);
}
else if (HexChar >= 0x41 && HexChar <= 0x46)
{
*OutBinary = (UINT8) (HexChar - 0x37);
return (1);
}
else if (HexChar >= 0x61 && HexChar <= 0x66)
{
*OutBinary = (UINT8) (HexChar - 0x57);
return (1);
}
return (0);
}
static UINT8
AbHexByteToBinary (
char *HexString,
char *OutBinary)
{
UINT8 Local1;
UINT8 Local2;
if (!UtHexCharToValue (HexString[0], &Local1))
{
return (0);
}
if (!UtHexCharToValue (HexString[1], &Local2))
{
return (0);
}
*OutBinary = (UINT8) ((Local1 << 4) | Local2);
return (2);
}
/******************************************************************************
*
* FUNCTION: AbValidateHeader
*
* DESCRIPTION: Check for valid ACPI table header
*
******************************************************************************/
static BOOLEAN
AbValidateHeader (
ACPI_TABLE_HEADER *Header)
{
if (!AcpiUtValidAcpiName (* (UINT32 *) &Header->Signature))
{
printf ("Header signature is invalid\n");
return FALSE;
}
return TRUE;
}
/*******************************************************************************
*
* FUNCTION: AcpiTbSumTable
*
* PARAMETERS: Buffer - Buffer to checksum
* Length - Size of the buffer
*
* RETURNS 8 bit checksum of buffer
*
* DESCRIPTION: Computes an 8 bit checksum of the buffer(length) and returns it.
*
******************************************************************************/
static UINT8
AcpiTbSumTable (
void *Buffer,
UINT32 Length)
{
const UINT8 *limit;
const UINT8 *rover;
UINT8 sum = 0;
if (Buffer && Length)
{
/* Buffer and Length are valid */
limit = (UINT8 *) Buffer + Length;
for (rover = Buffer; rover < limit; rover++)
{
sum = (UINT8) (sum + *rover);
}
}
return (sum);
}
/*******************************************************************************
*
* FUNCTION: AbPrintHeaderInfo
*
* PARAMETERS: Header - An ACPI table header
*
* RETURNS None.
*
* DESCRIPTION: Format and display header contents.
*
******************************************************************************/
static void
AbPrintHeaderInfo (
ACPI_TABLE_HEADER *Header)
{
/* Display header information */
printf ("Signature : %4.4s\n", Header->Signature);
printf ("Length : %8.8X\n", Header->Length);
printf ("Revision : %2.2X\n", Header->Revision);
printf ("Checksum : %2.2X\n", Header->Checksum);
printf ("OEM ID : %6.6s\n", Header->OemId);
printf ("OEM Table ID : %8.8s\n", Header->OemTableId);
printf ("OEM Revision : %8.8X\n", Header->OemRevision);
printf ("ASL Compiler ID : %4.4s\n", Header->AslCompilerId);
printf ("Compiler Revision : %8.8X\n", Header->AslCompilerRevision);
printf ("\n");
}
/******************************************************************************
*
* FUNCTION: AbDisplayHeader
*
* DESCRIPTION: Display an ACPI table header
*
******************************************************************************/
void
AbDisplayHeader (
char *File1Path)
{
UINT32 Actual1;
File1 = fopen (File1Path, "rb");
if (!File1)
{
printf ("Could not open file %s\n", File1Path);
return;
}
Actual1 = fread (&Header1, 1, sizeof (ACPI_TABLE_HEADER), File1);
if (Actual1 < sizeof (ACPI_TABLE_HEADER))
{
printf ("File %s does not contain an ACPI table header\n", File1Path);
return;
}
if (!AbValidateHeader (&Header1))
{
return;
}
AbPrintHeaderInfo (&Header1);
}
/******************************************************************************
*
* FUNCTION: AbComputeChecksum
*
* DESCRIPTION: Compute proper checksum for an ACPI table
*
******************************************************************************/
void
AbComputeChecksum (
char *File1Path)
{
UINT32 Actual1;
ACPI_TABLE_HEADER *Table;
UINT8 Checksum;
File1 = fopen (File1Path, "rb");
if (!File1)
{
printf ("Could not open file %s\n", File1Path);
return;
}
Actual1 = fread (&Header1, 1, sizeof (ACPI_TABLE_HEADER), File1);
if (Actual1 < sizeof (ACPI_TABLE_HEADER))
{
printf ("File %s does not contain an ACPI table header\n", File1Path);
return;
}
if (!AbValidateHeader (&Header1))
{
return;
}
if (!Gbl_TerseMode)
{
AbPrintHeaderInfo (&Header1);
}
/* Allocate a buffer to hold the entire table */
Table = AcpiOsAllocate (Header1.Length);
if (!Table)
{
printf ("could not allocate\n");
return;
}
/* Read the entire table, including header */
fseek (File1, 0, SEEK_SET);
Actual1 = fread (Table, 1, Header1.Length, File1);
if (Actual1 < Header1.Length)
{
printf ("could not read table\n");
return;
}
/* Compute the checksum for the table */
Table->Checksum = 0;
Checksum = (UINT8) (0 - AcpiTbSumTable (Table, Table->Length));
printf ("Computed checksum: 0x%X\n\n", Checksum);
if (Header1.Checksum == Checksum)
{
printf ("Checksum ok in AML file, not updating\n");
return;
}
/* Open the target file for writing, to update checksum */
fclose (File1);
File1 = fopen (File1Path, "r+b");
if (!File1)
{
printf ("Could not open file %s for writing\n", File1Path);
return;
}
/* Set the checksum, write the new header */
Header1.Checksum = Checksum;
Actual1 = fwrite (&Header1, 1, sizeof (ACPI_TABLE_HEADER), File1);
if (Actual1 < sizeof (ACPI_TABLE_HEADER))
{
printf ("Could not write updated table header\n");
return;
}
printf ("Wrote new checksum\n");
return;
}
/******************************************************************************
*
* FUNCTION: AbCompareAmlFiles
*
* DESCRIPTION: Compare two AML files
*
******************************************************************************/
int
AbCompareAmlFiles (
char *File1Path,
char *File2Path)
{
UINT32 Actual1;
UINT32 Actual2;
UINT32 Offset;
UINT8 Char1;
UINT8 Char2;
UINT8 Mismatches = 0;
BOOLEAN HeaderMismatch = FALSE;
File1 = fopen (File1Path, "rb");
if (!File1)
{
printf ("Could not open file %s\n", File1Path);
return -1;
}
File2 = fopen (File2Path, "rb");
if (!File2)
{
printf ("Could not open file %s\n", File2Path);
return -1;
}
/* Read the ACPI header from each file */
Actual1 = fread (&Header1, 1, sizeof (ACPI_TABLE_HEADER), File1);
if (Actual1 < sizeof (ACPI_TABLE_HEADER))
{
printf ("File %s does not contain an ACPI table header\n", File1Path);
return -1;
}
Actual2 = fread (&Header2, 1, sizeof (ACPI_TABLE_HEADER), File2);
if (Actual2 < sizeof (ACPI_TABLE_HEADER))
{
printf ("File %s does not contain an ACPI table header\n", File2Path);
return -1;
}
if ((!AbValidateHeader (&Header1)) ||
(!AbValidateHeader (&Header2)))
{
return -1;
}
/* Table signatures must match */
if (*((UINT32 *) Header1.Signature) != *((UINT32 *) Header2.Signature))
{
printf ("Table signatures do not match\n");
return -1;
}
if (!Gbl_TerseMode)
{
/* Display header information */
AbPrintHeaderInfo (&Header1);
AbPrintHeaderInfo (&Header2);
}
if (memcmp (Header1.Signature, Header2.Signature, sizeof (ACPI_TABLE_HEADER)))
{
printf ("Headers do not match exactly\n");
HeaderMismatch = TRUE;
}
/* Do the byte-by-byte compare */
Actual1 = fread (&Char1, 1, 1, File1);
Actual2 = fread (&Char2, 1, 1, File2);
Offset = sizeof (ACPI_TABLE_HEADER);
while (Actual1 && Actual2)
{
if (Char1 != Char2)
{
printf ("Error - Byte mismatch at offset %8.8X: 0x%2.2X 0x%2.2X\n",
Offset, Char1, Char2);
Mismatches++;
if (Mismatches > 100)
{
printf ("100 Mismatches: Too many mismatches\n");
return -1;
}
}
Offset++;
Actual1 = fread (&Char1, 1, 1, File1);
Actual2 = fread (&Char2, 1, 1, File2);
}
if (Actual1)
{
printf ("Error - file %s is longer than file %s\n", File1Path, File2Path);
Mismatches++;
}
else if (Actual2)
{
printf ("Error - file %s is shorter than file %s\n", File1Path, File2Path);
Mismatches++;
}
else if (!Mismatches)
{
if (HeaderMismatch)
{
printf ("Files compare exactly after header\n");
}
else
{
printf ("Files compare exactly\n");
}
}
printf ("%u Mismatches found\n", Mismatches);
return 0;
}
/******************************************************************************
*
* FUNCTION: AsGetFile
*
* DESCRIPTION: Open a file and read it entirely into a new buffer
*
******************************************************************************/
static char *
AbGetFile (
char *Filename,
UINT32 *FileSize)
{
int FileHandle;
UINT32 Size;
char *Buffer = NULL;
/* Binary mode does not alter CR/LF pairs */
FileHandle = open (Filename, O_BINARY | O_RDONLY);
if (!FileHandle)
{
printf ("Could not open %s\n", Filename);
return NULL;
}
/* Need file size to allocate a buffer */
if (fstat (FileHandle, &Gbl_StatBuf))
{
printf ("Could not get file status for %s\n", Filename);
goto ErrorExit;
}
/* Allocate a buffer for the entire file */
Size = Gbl_StatBuf.st_size;
Buffer = calloc (Size, 1);
if (!Buffer)
{
printf ("Could not allocate buffer of size %u\n", Size);
goto ErrorExit;
}
/* Read the entire file */
Size = read (FileHandle, Buffer, Size);
if (Size == -1)
{
printf ("Could not read the input file %s\n", Filename);
free (Buffer);
Buffer = NULL;
goto ErrorExit;
}
*FileSize = Size;
ErrorExit:
close (FileHandle);
return (Buffer);
}
/******************************************************************************
*
* FUNCTION: AbDumpAmlFile
*
* DESCRIPTION: Dump a binary AML file to a text file
*
******************************************************************************/
int
AbDumpAmlFile (
char *File1Path,
char *File2Path)
{
char *FileBuffer;
UINT32 FileSize = 0;
FILE *FileOutHandle;
/* Get the entire AML file, validate header */
FileBuffer = AbGetFile (File1Path, &FileSize);
printf ("File %s contains 0x%X bytes\n\n", File1Path, FileSize);
FileOutHandle = fopen (File2Path, "wb");
if (!FileOutHandle)
{
printf ("Could not open %s\n", File2Path);
return -1;
}
if (!AbValidateHeader ((ACPI_TABLE_HEADER *) FileBuffer))
{
return -1;
}
/* Convert binary AML to text, using common dump buffer routine */
AcpiGbl_DebugFile = FileOutHandle;
AcpiGbl_DbOutputFlags = ACPI_DB_REDIRECTABLE_OUTPUT;
AcpiOsPrintf ("%4.4s\n", ((ACPI_TABLE_HEADER *) FileBuffer)->Signature);
AcpiDbgLevel = ACPI_UINT32_MAX;
AcpiUtDumpBuffer ((UINT8 *) FileBuffer, FileSize,
DB_BYTE_DISPLAY, ACPI_UINT32_MAX);
return 0;
}
/******************************************************************************
*
* FUNCTION: AbExtractAmlFile
*
* DESCRIPTION: Extract a binary AML file from a text file (as produced by the
* DumpAmlFile procedure or the "acpidmp" table utility.
*
******************************************************************************/
int
AbExtractAmlFile (
char *TableSig,
char *File1Path,
char *File2Path)
{
char *Table;
char Value;
UINT32 i;
FILE *FileHandle;
FILE *FileOutHandle;
UINT32 Count = 0;
int Scanned;
/* Open in/out files. input is in text mode, output is in binary mode */
FileHandle = fopen (File1Path, "rt");
if (!FileHandle)
{
printf ("Could not open %s\n", File1Path);
return -1;
}
FileOutHandle = fopen (File2Path, "w+b");
if (!FileOutHandle)
{
printf ("Could not open %s\n", File2Path);
return -1;
}
/* Force input table sig to uppercase */
AcpiUtStrupr (TableSig);
/* TBD: examine input for ASCII */
/* We have an ascii file, grab one line at a time */
while (fgets (Buffer, BUFFER_SIZE, FileHandle))
{
/* The 4-char ACPI signature appears at the beginning of a line */
if (!strncmp (Buffer, TableSig, 4))
{
printf ("Found table [%4.4s]\n", TableSig);
/*
* Eat all lines in the table, of the form:
* <offset>: <16 bytes of hex data, separated by spaces> <ASCII representation> <newline>
*
* Example:
*
* 02C0: 5F 53 42 5F 4C 4E 4B 44 00 12 13 04 0C FF FF 08 _SB_LNKD........
*
*/
while (fgets (Buffer, BUFFER_SIZE, FileHandle))
{
/* Get past the offset, terminated by a colon */
Table = strchr (Buffer, ':');
if (!Table)
{
/* No colon, all done */
goto Exit;
}
Table += 2; /* Eat the colon + space */
for (i = 0; i < 16; i++)
{
Scanned = AbHexByteToBinary (Table, &Value);
if (!Scanned)
{
goto Exit;
}
Table += 3; /* Go past this hex byte and space */
/* Write the converted (binary) byte */
fwrite (&Value, 1, 1, FileOutHandle);
Count++;
}
}
/* No more lines, EOF, all done */
goto Exit;
}
}
/* Searched entire file, no match to table signature */
printf ("Could not match table signature\n");
fclose (FileHandle);
return -1;
Exit:
printf ("%u (0x%X) bytes written to %s\n", Count, Count, File2Path);
fclose (FileHandle);
fclose (FileOutHandle);
return 0;
}
/******************************************************************************
*
* FUNCTION: Stubs
*
* DESCRIPTION: For linkage
*
******************************************************************************/
ACPI_PHYSICAL_ADDRESS
AeLocalGetRootPointer (
void)
{
return AE_OK;
}
ACPI_THREAD_ID
AcpiOsGetThreadId (
void)
{
return (0xFFFF);
}
ACPI_STATUS
AcpiOsExecute (
ACPI_EXECUTE_TYPE Type,
ACPI_OSD_EXEC_CALLBACK Function,
void *Context)
{
return (AE_SUPPORT);
}
<|start_filename|>include/sampler.h<|end_filename|>
#include <stdint.h>
#include <stdbool.h>
// An event selector
struct perf_selector
{
bool enable : 1;
// Enable precise sampling, if possible. This is incompatible with
// recording stack traces.
bool precise : 1;
// If non-zero, profile load latency by sampling loads that take
// load_latency or more CPU cycles. This is only supported on Intel
// Nehalem or later. If this is set, the value must be at least 4,
// precise must be set, and selector must be
// MEM_INST_RETIRED.LATENCY_ABOVE_THRESHOLD (0x100B), with cmask and
// inv set to 0. See Intel SDM Volume 3 for details on exactly what
// this measures.
// XXX Sandy Bridge changed the required selector.
uint16_t load_latency;
// The event selector code. This is architecture-specific, but
// generally includes an event number, a unit mask, and various
// other flags. Any interrupt flag is ignored.
uint64_t selector;
// If non-zero, record the current instruction pointer every
// 'period' events.
uint64_t period;
};
#define NTRACE 4
struct pmuevent {
u8 idle:1;
u8 ints_disabled:1;
u8 kernel:1;
u32 count;
u64 rip;
uptr trace[NTRACE];
u32 latency, data_source;
u64 load_address;
};
struct logheader {
u64 ncpus;
struct {
u64 offset;
u64 size;
} cpu[];
} __attribute__((packed));
<|start_filename|>net/arch/sys_arch.h<|end_filename|>
#ifndef LWIP_ARCH_SYS_ARCH_H
#define LWIP_ARCH_SYS_ARCH_H
typedef struct proc* sys_thread_t;
typedef u64 sys_prot_t;
typedef struct sys_mbox_impl *sys_mbox_t;
typedef struct semaphore *sys_sem_t;
#define SYS_ARCH_NOWAIT 0xfffffffe
extern void lwip_core_unlock(void);
extern void lwip_core_lock(void);
extern void lwip_core_init(void);
#endif
<|start_filename|>stdinc/uk/gcstat.h<|end_filename|>
struct gc_stat {
u64 ndelay;
u64 lastwake; /* ndelay as of the last GC wakeup */
u64 nfree;
u64 nrun;
u64 ncycles;
u64 nop;
};
<|start_filename|>stdinc/signal.h<|end_filename|>
#pragma once
#include <uk/signal.h>
BEGIN_DECLS
typedef void (*sighandler_t)(int);
sighandler_t signal(int sig, sighandler_t func);
int sigaction(int sig, struct sigaction* act, struct sigaction* oact);
END_DECLS
<|start_filename|>bin/init.cc<|end_filename|>
// init: The initial user-level program
#ifdef XV6_USER
#include "user.h"
#include "major.h"
#endif
#include <fcntl.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
#ifndef XV6_USER
#include <errno.h>
#include <sys/mount.h>
#endif
#include "libutil.h"
static const char *sh_argv[] = { "sh", 0 };
static const char *app_argv[][MAXARG] = {
#ifdef LWIP
{ "telnetd", 0 },
{ "httpd", 0 },
#endif
};
#ifdef XV6_USER
static struct {
const char* name;
int major;
} dev[] = {
{ "/dev/netif", MAJ_NETIF },
{ "/dev/sampler", MAJ_SAMPLER },
{ "/dev/lockstat", MAJ_LOCKSTAT },
{ "/dev/stat", MAJ_STAT },
{ "/dev/cmdline", MAJ_CMDLINE},
{ "/dev/gc", MAJ_GC},
{ "/dev/kconfig", MAJ_KCONFIG},
{ "/dev/kstats", MAJ_KSTATS},
{ "/dev/kmemstats", MAJ_KMEMSTATS},
{ "/dev/mfsstats", MAJ_MFSSTATS},
};
#endif
static int
startone(const char * const *argv)
{
int pid;
pid = fork();
if(pid < 0){
die("init: fork failed");
}
if(pid == 0){
execv(argv[0], const_cast<char * const *>(argv));
die("init: exec %s failed", argv[0]);
}
return pid;
}
static void
runcmdline(void)
{
const char* argv[4] = { "sh", "-c", 0 };
char buf[256];
char* b;
long r;
int fd;
#ifdef XV6_USER
fd = open("/dev/cmdline", O_RDONLY);
#else
fd = open("/proc/cmdline", O_RDONLY);
#endif
if (fd < 0)
return;
r = read(fd, buf, sizeof(buf)-1);
if (r < 0)
return;
buf[r] = 0;
close(fd);
if ((b = strchr(buf, '$'))) {
argv[2] = b+1;
printf("init: Starting %s\n", argv[2]);
startone(argv);
}
}
int
main(void)
{
int pid, wpid;
#ifdef XV6_USER
if(open("console", O_RDWR) < 0){
mknod("console", 1, 1);
open("console", O_RDWR);
}
dup(0); // stdout
dup(0); // stderr
mkdir("dev", 0777);
for (auto &d : dev)
if (mknod(d.name, d.major, 1) < 0)
fprintf(stderr, "init: mknod %s failed\n", d.name);
#else
mkdir("/proc", 0555);
int r = mount("x", "/proc", "proc", 0, "");
if (r < 0)
edie("mount /proc failed");
mkdir("/dev", 0555);
r = mount("x", "/dev", "devtmpfs", 0, "");
if (r < 0) {
fprintf(stderr, "Warning: mount /dev failed: %s\n", strerror (errno));
fprintf(stderr, "(Is CONFIG_DEVTMPFS=y in your kernel configuration?)\n");
}
#endif
for (auto &argv : app_argv)
startone(argv);
time_t now = time(nullptr);
printf("init complete at %s", ctime(&now));
runcmdline();
for(;;){
pid = startone(sh_argv);
while((wpid=wait(NULL)) >= 0 && wpid != pid)
fprintf(stderr, "zombie!\n");
}
return 0;
}
<|start_filename|>kernel/console.cc<|end_filename|>
// Console input and output.
// Input is from the keyboard or serial port.
// Output is written to the screen and serial port.
#include "types.h"
#include "cpu.hh"
#include "kernel.hh"
#include "spinlock.hh"
#include "fs.h"
#include "condvar.hh"
#include "file.hh"
#include "amd64.h"
#include "proc.hh"
#include "traps.h"
#include "lib.h"
#include <stdarg.h>
#include "fmt.hh"
#include "major.h"
#include "apic.hh"
#include "irq.hh"
#include "kstream.hh"
#include "bits.hh"
#define BACKSPACE 0x100
static int panicked = 0;
static struct cons {
int locking;
struct spinlock lock;
struct cpu* holder;
int nesting_count;
constexpr cons()
: locking(0), lock("console", LOCKSTAT_CONSOLE),
holder(nullptr), nesting_count(0) { }
} cons;
static void
consputc(int c)
{
if(panicked){
cli();
for(;;)
;
}
switch(c) {
case BACKSPACE:
uartputc('\b');
uartputc(' ');
uartputc('\b');
break;
case '\n':
uartputc('\r');
// fall through
default:
uartputc(c);
}
cgaputc(c);
}
// Print to the console.
static void
writecons(int c, void *arg)
{
consputc(c);
}
// Print to a buffer.
struct bufstate {
char *p;
char *e;
};
static void
writebuf(int c, void *arg)
{
struct bufstate *bs = (bufstate*) arg;
if (bs->p < bs->e) {
bs->p[0] = c;
bs->p++;
}
}
void
vsnprintf(char *buf, u32 n, const char *fmt, va_list ap)
{
struct bufstate bs = { buf, buf+n-1 };
vprintfmt(writebuf, (void*) &bs, fmt, ap);
bs.p[0] = '\0';
}
void
snprintf(char *buf, u32 n, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, n, fmt, ap);
va_end(ap);
}
void
__cprintf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vprintfmt(writecons, 0, fmt, ap);
va_end(ap);
}
void
cprintf(const char *fmt, ...)
{
va_list ap;
int locking = cons.locking;
if(locking)
acquire(&cons.lock);
va_start(ap, fmt);
vprintfmt(writecons, 0, fmt, ap);
va_end(ap);
if(locking)
release(&cons.lock);
}
void
vcprintf(const char *fmt, va_list ap)
{
int locking = cons.locking;
if(locking)
acquire(&cons.lock);
vprintfmt(writecons, 0, fmt, ap);
if(locking)
release(&cons.lock);
}
void
puts(const char *s)
{
u8 *p, *ep;
p = (u8*)s;
ep = p+strlen(s);
for (; p < ep; p++)
writecons(*p, nullptr);
}
void
printtrace(u64 rbp)
{
uptr pc[10];
getcallerpcs((void*)rbp, pc, NELEM(pc));
for (int i = 0; i < NELEM(pc) && pc[i] != 0; i++)
__cprintf(" %016lx\n", pc[i]);
}
void
printtrap(struct trapframe *tf, bool lock)
{
const char *name = "(no name)";
void *kstack = nullptr;
int pid = 0;
lock_guard<spinlock> l;
if (lock && cons.locking)
l = cons.lock.guard();
if (myproc() != nullptr) {
if (myproc()->name && myproc()->name[0] != 0)
name = myproc()->name;
pid = myproc()->pid;
kstack = myproc()->kstack;
}
__cprintf("trap %lu err 0x%x cpu %u cs %u ds %u ss %u\n"
// Basic machine state
" rip %016lx rsp %016lx rbp %016lx\n"
" cr2 %016lx cr3 %016lx cr4 %016lx\n"
// Function arguments (AMD64 ABI)
" rdi %016lx rsi %016lx rdx %016lx\n"
" rcx %016lx r8 %016lx r9 %016lx\n"
// Everything else
" rax %016lx rbx %016lx r10 %016lx\n"
" r11 %016lx r12 %016lx r13 %016lx\n"
" r14 %016lx r15 %016lx rflags %016lx\n"
// Process state
" proc: name %s pid %u kstack %p\n",
tf->trapno, tf->err, mycpu()->id, tf->cs, tf->ds, tf->ss,
tf->rip, tf->rsp, tf->rbp,
rcr2(), rcr3(), rcr4(),
tf->rdi, tf->rsi, tf->rdx,
tf->rcx, tf->r8, tf->r9,
tf->rax, tf->rbx, tf->r10,
tf->r11, tf->r12, tf->r13,
tf->r14, tf->r15, tf->rflags,
name, pid, kstack);
// Trap decoding
if (tf->trapno == T_PGFLT) {
__cprintf(" page fault: %s %s %016lx from %s mode\n",
tf->err & FEC_PR ?
"protection violation" :
"non-present page",
tf->err & FEC_WR ? "writing" : "reading",
rcr2(),
tf->err & FEC_U ? "user" : "kernel");
}
if (kstack && tf->rsp < (uintptr_t)kstack)
__cprintf(" possible stack overflow\n");
}
void __noret__
kerneltrap(struct trapframe *tf)
{
cli();
acquire(&cons.lock);
__cprintf("kernel ");
printtrap(tf, false);
printtrace(tf->rbp);
panicked = 1;
halt();
for(;;)
;
}
void
panic(const char *fmt, ...)
{
va_list ap;
cli();
acquire(&cons.lock);
__cprintf("cpu%d-%s: panic: ",
mycpu()->id,
myproc() ? myproc()->name : "(unknown)");
va_start(ap, fmt);
vprintfmt(writecons, 0, fmt, ap);
va_end(ap);
__cprintf("\n");
printtrace(rrbp());
panicked = 1;
halt();
for(;;)
;
}
static int
consolewrite(mdev*, const char *buf, u32 n)
{
int i;
acquire(&cons.lock);
for(i = 0; i < n; i++)
consputc(buf[i] & 0xff);
release(&cons.lock);
return n;
}
#define INPUT_BUF 128
struct {
struct spinlock lock;
struct condvar cv;
char buf[INPUT_BUF];
int r; // Read index
int w; // Write index
int e; // Edit index
} input;
#define C(x) ((x)-'@') // Control-x
void
consoleintr(int (*getc)(void))
{
int c;
acquire(&input.lock);
while((c = getc()) >= 0){
switch(c){
case C('P'): // Process listing.
procdumpall();
break;
case C('E'): // Print user-space PCs.
for (u32 i = 0; i < NCPU; i++)
cpus[i].timer_printpc = 1;
break;
case C('T'): // Print user-space PCs and stack traces.
for (u32 i = 0; i < NCPU; i++)
cpus[i].timer_printpc = 2;
break;
case C('U'): // Kill line.
while(input.e != input.w &&
input.buf[(input.e-1) % INPUT_BUF] != '\n'){
input.e--;
consputc(BACKSPACE);
}
break;
case C('H'): case '\x7f': // Backspace
if(input.e != input.w){
input.e--;
consputc(BACKSPACE);
}
break;
case C('F'): // kmem stats
kmemprint(&console);
break;
case C('Y'): // scopedperf stats
// scopedperf::perfsum_base::printall();
// scopedperf::perfsum_base::resetall();
break;
default:
if(c != 0 && input.e-input.r < INPUT_BUF){
c = (c == '\r') ? '\n' : c;
input.buf[input.e++ % INPUT_BUF] = c;
consputc(c);
if(c == '\n' || c == C('D') || input.e == input.r+INPUT_BUF){
input.w = input.e;
input.cv.wake_all();
}
}
break;
}
}
release(&input.lock);
}
static int
consoleread(mdev*, char *dst, u32 n)
{
int target;
int c;
target = n;
acquire(&input.lock);
while(n > 0){
while(input.r == input.w){
if(myproc()->killed){
release(&input.lock);
return -1;
}
input.cv.sleep(&input.lock);
}
c = input.buf[input.r++ % INPUT_BUF];
if(c == C('D')){ // EOF
if(n < target){
// Save ^D for next time, to make sure
// caller gets a 0-byte result.
input.r--;
}
break;
}
*dst++ = c;
--n;
if(c == '\n')
break;
}
release(&input.lock);
return target - n;
}
// Console stream support
void
console_stream::_begin_print()
{
// Acquire cons.lock in a reentrant way. The holder check is
// technically racy, but can't succeed unless this CPU is the
// holder, in which case it's not racy.
if (!cons.locking || cons.holder == mycpu()) {
++cons.nesting_count;
return;
}
acquire(&cons.lock);
cons.holder = mycpu();
cons.nesting_count = 1;
}
void
console_stream::end_print()
{
if (--cons.nesting_count != 0 || !cons.locking)
return;
assert(cons.holder == mycpu());
cons.holder = nullptr;
release(&cons.lock);
}
void
console_stream::write(char c)
{
consputc(c);
}
void
console_stream::write(sbuf buf)
{
for (size_t i = 0; i < buf.len; i++)
consputc(buf.base[i]);
}
bool
panic_stream::begin_print()
{
cli();
console_stream::begin_print();
if (cons.nesting_count == 1) {
print("cpu ", myid(), " (", myproc() ? myproc()->name : "unknown",
") panic: ");
}
return true;
}
void
panic_stream::end_print()
{
if (cons.nesting_count > 1) {
console_stream::end_print();
} else {
printtrace(rrbp());
panicked = 1;
halt();
for(;;);
}
}
console_stream console, swarn;
panic_stream spanic;
console_stream uerr(false);
void
initconsole(void)
{
cons.locking = 1;
devsw[MAJ_CONSOLE].write = consolewrite;
devsw[MAJ_CONSOLE].read = consoleread;
extpic->map_isa_irq(IRQ_KBD).enable();
}
<|start_filename|>metis/app/matrix_mult.c<|end_filename|>
/* Copyright (c) 2007, Stanford University
* All rights reserved.
*
* 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.
* * Neither the name of Stanford University nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY 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.
*/
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
#include <assert.h>
#include <fcntl.h>
#include <ctype.h>
#include <time.h>
#ifndef __WIN__
#include <strings.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sched.h>
#define TCHAR char
#endif
#include "mr-sched.h"
#include "bench.h"
enum { block_based = 1 };
enum { def_block_len = 32 };
static int block_len = def_block_len;
static int nsplits = 0;
typedef struct {
int row_num;
int startrow;
int startcol;
int *matrix_A;
int *matrix_B;
int matrix_len;
int *output;
} mm_data_t;
/* Structure to store the coordinates
and location for each value in the matrix */
typedef struct {
int x_loc;
int y_loc;
int value;
} mm_key_t;
/** myintcmp()
* Comparison Function to compare 2 locations in the matrix
*/
static int
myintcmp(const void *v1, const void *v2)
{
prof_enterkcmp();
mm_key_t *key1 = (mm_key_t *) v1;
mm_key_t *key2 = (mm_key_t *) v2;
int res = 0;
if (key1->x_loc < key2->x_loc)
res = -1;
else if (key1->x_loc > key2->x_loc)
res = 1;
else {
if (key1->y_loc < key2->y_loc)
res = -1;
else if (key1->y_loc > key2->y_loc)
res = 1;
else
res = 0;
}
prof_leavekcmp();
return res;
}
static int
matrixmult_splitter2(void *data_in, split_t * out, int ncores)
{
/* Make a copy of the mm_data structure */
mm_data_t *data = (mm_data_t *) data_in;
mm_data_t *data_out = (mm_data_t *) malloc(sizeof(mm_data_t));
memcpy((char *) data_out, (char *) data, sizeof(mm_data_t));
/* Check whether the various terms exist */
if (nsplits == 0) {
nsplits = ncores * def_nsplits_per_core;
}
uint64_t split_size = data->matrix_len / nsplits;
assert(data->row_num <= data->matrix_len);
printf("Required units is %ld\n", split_size);
/* Reached the end of the matrix */
if (data->row_num >= data->matrix_len) {
fflush(stdout);
free(data_out);
return 0;
}
/* Compute available rows */
int available_rows = data->matrix_len - data->row_num;
out->length = (split_size < available_rows) ? split_size : available_rows;
out->data = data_out;
data->row_num += out->length;
dprintf("Allocated rows is %ld\n", out->length);
return 1;
}
/** matrixmul_map()
* Multiplies the allocated regions of matrix to compute partial sums
*/
static void
matrixmult_map2(split_t * args)
{
int row_count = 0;
int i, j, x_loc, value;
int *a_ptr, *b_ptr;
prof_enterapp();
assert(args);
mm_data_t *data = (mm_data_t *) (args->data);
assert(data);
while (row_count < args->length) {
a_ptr =
data->matrix_A + (data->row_num + row_count) * data->matrix_len;
for (i = 0; i < data->matrix_len; i++) {
b_ptr = data->matrix_B + i;
value = 0;
for (j = 0; j < data->matrix_len; j++) {
value += (a_ptr[j] * (*b_ptr));
b_ptr += data->matrix_len;
}
x_loc = (data->row_num + row_count);
data->output[x_loc * data->matrix_len + i] = value;
fflush(stdout);
}
dprintf("%d Loop\n", data->row_num);
row_count++;
}
printf("Finished Map task %d\n", data->row_num);
fflush(stdout);
prof_leaveapp();
}
/** matrixmul_splitter()
* Assign block_len elements in a row the output matrix
*/
static int
matrixmult_splitter(void *arg, split_t * out, int ncore)
{
/* Make a copy of the mm_data structure */
prof_enterapp();
mm_data_t *data = (mm_data_t *) arg;
mm_data_t *data_out = (mm_data_t *) malloc(sizeof(mm_data_t));
memcpy((char *) data_out, (char *) data, sizeof(mm_data_t));
if (data->startrow >= data->matrix_len) {
fflush(stdout);
free(data_out);
prof_leaveapp();
return 0;
}
/* Compute available rows */
out->data = data_out;
data->startcol += block_len;
if (data->startcol > data->matrix_len) {
data->startrow += block_len;
data->startcol = 0;
}
prof_leaveapp();
return 1;
}
/** matrixmul_map()
* Multiplies the allocated regions of matrix to compute partial sums
*/
void
matrixmult_map(split_t * args)
{
int i, j, k, end_i, end_j, end_k, a, b, c;
prof_enterapp();
assert(args);
mm_data_t *data = (mm_data_t *) (args->data);
assert(data);
dprintf("%d Start Loop \n", data->row_num);
i = data->startrow;
j = data->startcol;
dprintf("do %d %d of %d\n", i, j, data->matrix_len);
for (k = 0; k < data->matrix_len; k += block_len) {
end_i = i + block_len;
end_j = j + block_len;
end_k = k + block_len;
for (a = i; a < end_i && a < data->matrix_len; a++)
for (b = j; b < end_j && b < data->matrix_len; b++)
for (c = k; c < end_k && c < data->matrix_len; c++) {
data->output[data->matrix_len * a + b] +=
(data->matrix_A[data->matrix_len * a + c] *
data->matrix_B[data->matrix_len * c + b]);
}
}
dprintf("Finished Map task %d\n", data->row_num);
fflush(stdout);
prof_leaveapp();
}
static void
mm_usage(char *fn)
{
printf("usage: %s [options]\n", fn);
printf("options:\n");
printf(" -p nprocs : # of processors to use\n");
printf(" -m #map tasks : # of map tasks (pre-split input before MR)\n");
printf(" -q : quiet output (for batch test)\n");
printf(" -l : matrix dimentions. (assume squaure)\n");
}
int
main(int argc, char *argv[])
{
final_data_kv_t mm_vals;
int i, j;
int matrix_len = 0;
int *matrix_A_ptr, *matrix_B_ptr, *fdata_out;
int nprocs = 0, map_tasks = 0;
int quiet = 0;
srand((unsigned) time(NULL));
if (argc < 2) {
mm_usage(argv[0]);
exit(EXIT_FAILURE);
}
int c;
while ((c = getopt(argc, argv, "p:m:ql:")) != -1) {
switch (c) {
case 'p':
assert((nprocs = atoi(optarg)) >= 0);
break;
case 'm':
map_tasks = atoi(optarg);
break;
case 'q':
quiet = 1;
break;
case 'l':
assert((matrix_len = atoi(optarg)) > 0);
break;
default:
mm_usage(argv[0]);
exit(EXIT_FAILURE);
}
}
matrix_A_ptr = malloc(sizeof(int) * matrix_len * matrix_len);
matrix_B_ptr = malloc(sizeof(int) * matrix_len * matrix_len);
fdata_out = malloc(sizeof(int) * matrix_len * matrix_len);
for (i = 0; i < matrix_len; i++) {
for (j = 0; j < matrix_len; j++) {
matrix_A_ptr[i * matrix_len + j] = rand();
matrix_B_ptr[i * matrix_len + j] = rand();
}
}
// Setup splitter args
mm_data_t mm_data;
mm_data.matrix_len = matrix_len;
mm_data.row_num = 0;
mm_data.startrow = 0;
mm_data.startcol = 0;
mm_data.matrix_A = matrix_A_ptr;
mm_data.matrix_B = matrix_B_ptr;
mm_data.output = ((int *) fdata_out);
// Setup scheduler args
mr_param_t mr_param;
memset(&mm_vals, 0, sizeof(mm_vals));
memset(&mr_param, 0, sizeof(mr_param_t));
mr_param.app_arg.atype = atype_maponly;
mr_param.app_arg.maponly.results = &mm_vals;
if (block_based) {
mr_param.split_func = matrixmult_splitter;
mr_param.map_func = matrixmult_map;
nsplits = 0; // split element by element
} else {
mr_param.split_func = matrixmult_splitter2;
mr_param.map_func = matrixmult_map2;
nsplits = map_tasks;
}
mr_param.split_arg = &mm_data;
mr_param.key_cmp = myintcmp;
mr_param.part_func = NULL; // use default
mr_param.nr_cpus = nprocs;
assert(mr_run_scheduler(&mr_param) == 0);
mr_print_stats();
if (!quiet) {
printf("First row of the output matrix:\n");
for (i = 0; i < matrix_len; i++) {
printf("%d\t", fdata_out[i]);
}
printf("\nLast row of the output matrix:\n");
for (i = 0; i < matrix_len; i++) {
printf("%d\t", fdata_out[(matrix_len - 1) * matrix_len + i]);
}
printf("\n");
}
free(mm_vals.data);
mr_finalize();
return 0;
}
<|start_filename|>kernel/acpica/source/tools/acpinames/Makefile<|end_filename|>
#
# acpinames - Load ACPI table and dump namespace. This is a subset
# of the AcpiExec functionality, it is intended to demonstrate
# the configurability of ACPICA.
#
# NOTE: This makefile is intended to be used in the Linux environment,
# with the Linux directory structure. It will not work directly
# on the native ACPICA source tree.
#
#
# Configuration
# Notes:
# gcc should be version 4 or greater, otherwise some of the options
# used will not be recognized.
# Global optimization flags (such as -O2, -Os) are not used, since
# they cause issues on some compilers.
# The _GNU_SOURCE symbol is required for many hosts.
#
PROG = acpinames
HOST = _LINUX
NOMAN = YES
COMPILE = $(CC) -c $(CFLAGS) $(CWARNINGFLAGS) -o$@ $<
ACPICA_SRC = ../../../source
ACPICA_COMMON = $(ACPICA_SRC)/common
ACPICA_TOOLS = $(ACPICA_SRC)/tools
ACPICA_OSL = $(ACPICA_SRC)/os_specific/service_layers
ACPICA_CORE = $(ACPICA_SRC)/components
ACPICA_INCLUDE = $(ACPICA_SRC)/include
ACPICA_DEBUGGER = $(ACPICA_CORE)/debugger
ACPICA_DISASSEMBLER = $(ACPICA_CORE)/disassembler
ACPICA_DISPATCHER = $(ACPICA_CORE)/dispatcher
ACPICA_EVENTS = $(ACPICA_CORE)/events
ACPICA_EXECUTER = $(ACPICA_CORE)/executer
ACPICA_HARDWARE = $(ACPICA_CORE)/hardware
ACPICA_NAMESPACE = $(ACPICA_CORE)/namespace
ACPICA_PARSER = $(ACPICA_CORE)/parser
ACPICA_RESOURCES = $(ACPICA_CORE)/resources
ACPICA_TABLES = $(ACPICA_CORE)/tables
ACPICA_UTILITIES = $(ACPICA_CORE)/utilities
ACPINAMES = $(ACPICA_TOOLS)/acpinames
INSTALLDIR = /usr/bin
INSTALLPROG = cp --remove-destination $(PROG) $(INSTALLDIR)
ACPICA_HEADERS = \
$(wildcard $(ACPICA_INCLUDE)/*.h) \
$(wildcard $(ACPICA_INCLUDE)/platform/*.h)
#
# Search paths for source files
#
vpath %.c \
$(ACPINAMES) \
$(ACPICA_DEBUGGER) \
$(ACPICA_DISPATCHER) \
$(ACPICA_EXECUTER) \
$(ACPICA_NAMESPACE) \
$(ACPICA_PARSER) \
$(ACPICA_TABLES) \
$(ACPICA_UTILITIES) \
$(ACPICA_COMMON) \
$(ACPICA_OSL)
HEADERS = \
$(wildcard $(ACPINAMES)/*.h)
OBJECTS = \
anmain.o \
anstubs.o \
antables.o \
dbfileio.o \
dsfield.o \
dsmthdat.o \
dsobject.o \
dsutils.o \
dswload.o \
dswload2.o \
dswscope.o \
dswstate.o \
excreate.o \
exnames.o \
exresnte.o \
exresolv.o \
exutils.o \
getopt.o \
nsaccess.o \
nsalloc.o \
nsdump.o \
nsinit.o \
nsload.o \
nsnames.o \
nsobject.o \
nsparse.o \
nssearch.o \
nsutils.o \
nswalk.o \
nsxfeval.o \
nsxfname.o \
nsxfobj.o \
osunixxf.o \
psargs.o \
psloop.o \
psopcode.o \
psparse.o \
psscope.o \
pstree.o \
psutils.o \
pswalk.o \
psxface.o \
tbfadt.o \
tbfind.o \
tbinstal.o \
tbutils.o \
tbxface.o \
tbxfroot.o \
utaddress.o \
utalloc.o \
utcache.o \
utdebug.o \
utdecode.o \
utdelete.o \
utglobal.o \
utlock.o \
utmath.o \
utmisc.o \
utmutex.o \
utobject.o \
utstate.o \
utosi.o \
utxferror.o \
utxface.o
CFLAGS+= \
-D$(HOST) \
-D_GNU_SOURCE \
-DACPI_NAMES_APP \
-I$(ACPICA_INCLUDE) \
-I$(ACPINAMES)
CWARNINGFLAGS = \
-ansi \
-Wall \
-Wbad-function-cast \
-Wdeclaration-after-statement \
-Werror \
-Wformat=2 \
-Wmissing-declarations \
-Wmissing-prototypes \
-Wstrict-aliasing=0 \
-Wstrict-prototypes \
-Wswitch-default \
-Wpointer-arith \
-Wundef
#
# gcc 4+ flags
#
CWARNINGFLAGS += \
-Waddress \
-Waggregate-return \
-Wchar-subscripts \
-Wempty-body \
-Wlogical-op \
-Wmissing-declarations \
-Wmissing-field-initializers \
-Wmissing-parameter-type \
-Wnested-externs \
-Wold-style-declaration \
-Wold-style-definition \
-Wredundant-decls \
-Wtype-limits
#
# Rules
#
$(PROG) : $(OBJECTS)
$(CC) $(LDFLAGS) $(OBJECTS) -o $(PROG)
$(COPYPROG)
%.o : %.c $(HEADERS) $(ACPICA_HEADERS)
$(COMPILE)
clean :
rm -f $(PROG) $(PROG).exe $(OBJECTS)
install :
$(INSTALLPROG)
<|start_filename|>libutil/include/libutil.h<|end_filename|>
#pragma once
#include "compiler.h"
#include <stdint.h>
#include <sys/types.h>
BEGIN_DECLS
void die(const char* errstr, ...)
__attribute__((noreturn, __format__(__printf__, 1, 2)));
void edie(const char* errstr, ...)
__attribute__((noreturn, __format__(__printf__, 1, 2)));
size_t xread(int fd, void *buf, size_t n);
void xwrite(int fd, const void *buf, size_t n);
uint64_t now_usec(void);
int setaffinity(int c);
END_DECLS
<|start_filename|>codexinc/atomic_2.h<|end_filename|>
// -*- C++ -*- header.
// Copyright (C) 2008, 2009, 2010, 2011
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file bits/atomic_2.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{atomic}
*/
#ifndef _GLIBCXX_ATOMIC_2_H
#define _GLIBCXX_ATOMIC_2_H 1
#pragma GCC system_header
// XXX: hack
#include "codex.hh"
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
// 2 == __atomic2 == Always lock-free
// Assumed:
// _GLIBCXX_ATOMIC_BUILTINS_1
// _GLIBCXX_ATOMIC_BUILTINS_2
// _GLIBCXX_ATOMIC_BUILTINS_4
// _GLIBCXX_ATOMIC_BUILTINS_8
namespace __atomic2
{
/// atomic_flag
struct atomic_flag : public __atomic_flag_base
{
atomic_flag() = default;
~atomic_flag() = default;
atomic_flag(const atomic_flag&) = delete;
atomic_flag& operator=(const atomic_flag&) = delete;
atomic_flag& operator=(const atomic_flag&) volatile = delete;
// Conversion to ATOMIC_FLAG_INIT.
atomic_flag(bool __i): __atomic_flag_base({ __i }) { }
bool
test_and_set(memory_order __m = memory_order_seq_cst)
{
// Redundant synchronize if built-in for lock is a full barrier.
if (__m != memory_order_acquire && __m != memory_order_acq_rel)
__SYNC_SYNCHRONIZE();
return __SYNC_LOCK_TEST_AND_SET(&_M_i, true);
}
bool
test_and_set(memory_order __m = memory_order_seq_cst) volatile
{
// Redundant synchronize if built-in for lock is a full barrier.
if (__m != memory_order_acquire && __m != memory_order_acq_rel)
__SYNC_SYNCHRONIZE();
return __SYNC_LOCK_TEST_AND_SET(&_M_i, true);
}
void
clear(memory_order __m = memory_order_seq_cst)
{
__glibcxx_assert(__m != memory_order_consume);
__glibcxx_assert(__m != memory_order_acquire);
__glibcxx_assert(__m != memory_order_acq_rel);
__SYNC_LOCK_RELEASE(&_M_i);
if (__m != memory_order_acquire && __m != memory_order_acq_rel)
__SYNC_SYNCHRONIZE();
}
void
clear(memory_order __m = memory_order_seq_cst) volatile
{
__glibcxx_assert(__m != memory_order_consume);
__glibcxx_assert(__m != memory_order_acquire);
__glibcxx_assert(__m != memory_order_acq_rel);
__SYNC_LOCK_RELEASE(&_M_i);
if (__m != memory_order_acquire && __m != memory_order_acq_rel)
__SYNC_SYNCHRONIZE();
}
};
/// Base class for atomic integrals.
//
// For each of the integral types, define atomic_[integral type] struct
//
// atomic_bool bool
// atomic_char char
// atomic_schar signed char
// atomic_uchar unsigned char
// atomic_short short
// atomic_ushort unsigned short
// atomic_int int
// atomic_uint unsigned int
// atomic_long long
// atomic_ulong unsigned long
// atomic_llong long long
// atomic_ullong unsigned long long
// atomic_char16_t char16_t
// atomic_char32_t char32_t
// atomic_wchar_t wchar_t
//
// NB: Assuming _ITp is an integral scalar type that is 1, 2, 4, or
// 8 bytes, since that is what GCC built-in functions for atomic
// memory access expect.
template<typename _ITp>
struct __atomic_base
{
private:
typedef _ITp __int_type;
__int_type _M_i;
public:
__atomic_base() = default;
~__atomic_base() = default;
__atomic_base(const __atomic_base&) = delete;
__atomic_base& operator=(const __atomic_base&) = delete;
__atomic_base& operator=(const __atomic_base&) volatile = delete;
// Requires __int_type convertible to _M_i.
constexpr __atomic_base(__int_type __i): _M_i (__i) { }
operator __int_type() const
{ return load(); }
operator __int_type() const volatile
{ return load(); }
__int_type
operator=(__int_type __i)
{
store(__i);
return __i;
}
__int_type
operator=(__int_type __i) volatile
{
store(__i);
return __i;
}
__int_type
operator++(int)
{ return fetch_add(1); }
__int_type
operator++(int) volatile
{ return fetch_add(1); }
__int_type
operator--(int)
{ return fetch_sub(1); }
__int_type
operator--(int) volatile
{ return fetch_sub(1); }
__int_type
operator++()
{ return __SYNC_ADD_AND_FETCH(&_M_i, __int_type(1)); }
__int_type
operator++() volatile
{ return __SYNC_ADD_AND_FETCH(&_M_i, __int_type(1)); }
__int_type
operator--()
{ return __SYNC_SUB_AND_FETCH(&_M_i, __int_type(1)); }
__int_type
operator--() volatile
{ return __SYNC_SUB_AND_FETCH(&_M_i, __int_type(1)); }
__int_type
operator+=(__int_type __i)
{ return __SYNC_ADD_AND_FETCH(&_M_i, __i); }
__int_type
operator+=(__int_type __i) volatile
{ return __SYNC_ADD_AND_FETCH(&_M_i, __i); }
__int_type
operator-=(__int_type __i)
{ return __SYNC_SUB_AND_FETCH(&_M_i, __i); }
__int_type
operator-=(__int_type __i) volatile
{ return __SYNC_SUB_AND_FETCH(&_M_i, __i); }
__int_type
operator&=(__int_type __i)
{ return __SYNC_AND_AND_FETCH(&_M_i, __i); }
__int_type
operator&=(__int_type __i) volatile
{ return __SYNC_AND_AND_FETCH(&_M_i, __i); }
__int_type
operator|=(__int_type __i)
{ return __SYNC_OR_AND_FETCH(&_M_i, __i); }
__int_type
operator|=(__int_type __i) volatile
{ return __SYNC_OR_AND_FETCH(&_M_i, __i); }
__int_type
operator^=(__int_type __i)
{ return __SYNC_XOR_AND_FETCH(&_M_i, __i); }
__int_type
operator^=(__int_type __i) volatile
{ return __SYNC_XOR_AND_FETCH(&_M_i, __i); }
bool
is_lock_free() const
{ return true; }
bool
is_lock_free() const volatile
{ return true; }
void
store(__int_type __i, memory_order __m = memory_order_seq_cst)
{
__glibcxx_assert(__m != memory_order_acquire);
__glibcxx_assert(__m != memory_order_acq_rel);
__glibcxx_assert(__m != memory_order_consume);
if (__m == memory_order_relaxed)
__STORE_VALUE(&_M_i, __i);
else
{
// write_mem_barrier();
__STORE_VALUE(&_M_i, __i);
if (__m == memory_order_seq_cst)
__SYNC_SYNCHRONIZE();
}
}
void
store(__int_type __i, memory_order __m = memory_order_seq_cst) volatile
{
__glibcxx_assert(__m != memory_order_acquire);
__glibcxx_assert(__m != memory_order_acq_rel);
__glibcxx_assert(__m != memory_order_consume);
if (__m == memory_order_relaxed)
__STORE_VALUE(&_M_i, __i);
else
{
// write_mem_barrier();
__STORE_VALUE(&_M_i, __i);
if (__m == memory_order_seq_cst)
__SYNC_SYNCHRONIZE();
}
}
__int_type
load(memory_order __m = memory_order_seq_cst) const
{
__glibcxx_assert(__m != memory_order_release);
__glibcxx_assert(__m != memory_order_acq_rel);
// __SYNC_SYNCHRONIZE();
__barrier();
__int_type __ret = __LOAD_VALUE(&_M_i);
// __SYNC_SYNCHRONIZE();
__barrier();
return __ret;
}
__int_type
load(memory_order __m = memory_order_seq_cst) const volatile
{
__glibcxx_assert(__m != memory_order_release);
__glibcxx_assert(__m != memory_order_acq_rel);
// __SYNC_SYNCHRONIZE();
__barrier();
__int_type __ret = __LOAD_VALUE(&_M_i);
// __SYNC_SYNCHRONIZE();
__barrier();
return __ret;
}
__int_type
exchange(__int_type __i, memory_order __m = memory_order_seq_cst)
{
// XXX built-in assumes memory_order_acquire.
return __SYNC_LOCK_TEST_AND_SET(&_M_i, __i);
}
__int_type
exchange(__int_type __i, memory_order __m = memory_order_seq_cst) volatile
{
// XXX built-in assumes memory_order_acquire.
return __SYNC_LOCK_TEST_AND_SET(&_M_i, __i);
}
bool
compare_exchange_weak(__int_type& __i1, __int_type __i2,
memory_order __m1, memory_order __m2)
{ return compare_exchange_strong(__i1, __i2, __m1, __m2); }
bool
compare_exchange_weak(__int_type& __i1, __int_type __i2,
memory_order __m1, memory_order __m2) volatile
{ return compare_exchange_strong(__i1, __i2, __m1, __m2); }
bool
compare_exchange_weak(__int_type& __i1, __int_type __i2,
memory_order __m = memory_order_seq_cst)
{
return compare_exchange_weak(__i1, __i2, __m,
__calculate_memory_order(__m));
}
bool
compare_exchange_weak(__int_type& __i1, __int_type __i2,
memory_order __m = memory_order_seq_cst) volatile
{
return compare_exchange_weak(__i1, __i2, __m,
__calculate_memory_order(__m));
}
bool
compare_exchange_strong(__int_type& __i1, __int_type __i2,
memory_order __m1, memory_order __m2)
{
__glibcxx_assert(__m2 != memory_order_release);
__glibcxx_assert(__m2 != memory_order_acq_rel);
__glibcxx_assert(__m2 <= __m1);
__int_type __i1o = __i1;
__int_type __i1n = __SYNC_VAL_COMPARE_AND_SWAP(&_M_i, __i1o, __i2);
// Assume extra stores (of same value) allowed in true case.
__i1 = __i1n;
return __i1o == __i1n;
}
bool
compare_exchange_strong(__int_type& __i1, __int_type __i2,
memory_order __m1, memory_order __m2) volatile
{
__glibcxx_assert(__m2 != memory_order_release);
__glibcxx_assert(__m2 != memory_order_acq_rel);
__glibcxx_assert(__m2 <= __m1);
__int_type __i1o = __i1;
__int_type __i1n = __SYNC_VAL_COMPARE_AND_SWAP(&_M_i, __i1o, __i2);
// Assume extra stores (of same value) allowed in true case.
__i1 = __i1n;
return __i1o == __i1n;
}
bool
compare_exchange_strong(__int_type& __i1, __int_type __i2,
memory_order __m = memory_order_seq_cst)
{
return compare_exchange_strong(__i1, __i2, __m,
__calculate_memory_order(__m));
}
bool
compare_exchange_strong(__int_type& __i1, __int_type __i2,
memory_order __m = memory_order_seq_cst) volatile
{
return compare_exchange_strong(__i1, __i2, __m,
__calculate_memory_order(__m));
}
__int_type
fetch_add(__int_type __i, memory_order __m = memory_order_seq_cst)
{ return __SYNC_FETCH_AND_ADD(&_M_i, __i); }
__int_type
fetch_add(__int_type __i,
memory_order __m = memory_order_seq_cst) volatile
{ return __SYNC_FETCH_AND_ADD(&_M_i, __i); }
__int_type
fetch_sub(__int_type __i, memory_order __m = memory_order_seq_cst)
{ return __SYNC_FETCH_AND_SUB(&_M_i, __i); }
__int_type
fetch_sub(__int_type __i,
memory_order __m = memory_order_seq_cst) volatile
{ return __SYNC_FETCH_AND_SUB(&_M_i, __i); }
__int_type
fetch_and(__int_type __i, memory_order __m = memory_order_seq_cst)
{ return __SYNC_FETCH_AND_AND(&_M_i, __i); }
__int_type
fetch_and(__int_type __i,
memory_order __m = memory_order_seq_cst) volatile
{ return __SYNC_FETCH_AND_AND(&_M_i, __i); }
__int_type
fetch_or(__int_type __i, memory_order __m = memory_order_seq_cst)
{ return __SYNC_FETCH_AND_OR(&_M_i, __i); }
__int_type
fetch_or(__int_type __i,
memory_order __m = memory_order_seq_cst) volatile
{ return __SYNC_FETCH_AND_OR(&_M_i, __i); }
__int_type
fetch_xor(__int_type __i, memory_order __m = memory_order_seq_cst)
{ return __SYNC_FETCH_AND_XOR(&_M_i, __i); }
__int_type
fetch_xor(__int_type __i,
memory_order __m = memory_order_seq_cst) volatile
{ return __SYNC_FETCH_AND_XOR(&_M_i, __i); }
};
/// Partial specialization for pointer types.
template<typename _PTp>
struct __atomic_base<_PTp*>
{
private:
typedef _PTp* __pointer_type;
__pointer_type _M_p;
public:
__atomic_base() = default;
~__atomic_base() = default;
__atomic_base(const __atomic_base&) = delete;
__atomic_base& operator=(const __atomic_base&) = delete;
__atomic_base& operator=(const __atomic_base&) volatile = delete;
// Requires __pointer_type convertible to _M_p.
constexpr __atomic_base(__pointer_type __p): _M_p (__p) { }
operator __pointer_type() const
{ return load(); }
operator __pointer_type() const volatile
{ return load(); }
__pointer_type
operator=(__pointer_type __p)
{
store(__p);
return __p;
}
__pointer_type
operator=(__pointer_type __p) volatile
{
store(__p);
return __p;
}
__pointer_type
operator++(int)
{ return fetch_add(1); }
__pointer_type
operator++(int) volatile
{ return fetch_add(1); }
__pointer_type
operator--(int)
{ return fetch_sub(1); }
__pointer_type
operator--(int) volatile
{ return fetch_sub(1); }
__pointer_type
operator++()
{ return fetch_add(1) + 1; }
__pointer_type
operator++() volatile
{ return fetch_add(1) + 1; }
__pointer_type
operator--()
{ return fetch_sub(1) -1; }
__pointer_type
operator--() volatile
{ return fetch_sub(1) -1; }
__pointer_type
operator+=(ptrdiff_t __d)
{ return fetch_add(__d) + __d; }
__pointer_type
operator+=(ptrdiff_t __d) volatile
{ return fetch_add(__d) + __d; }
__pointer_type
operator-=(ptrdiff_t __d)
{ return fetch_sub(__d) - __d; }
__pointer_type
operator-=(ptrdiff_t __d) volatile
{ return fetch_sub(__d) - __d; }
bool
is_lock_free() const
{ return true; }
bool
is_lock_free() const volatile
{ return true; }
void
store(__pointer_type __p, memory_order __m = memory_order_seq_cst)
{
__glibcxx_assert(__m != memory_order_acquire);
__glibcxx_assert(__m != memory_order_acq_rel);
__glibcxx_assert(__m != memory_order_consume);
if (__m == memory_order_relaxed)
__STORE_VALUE(&_M_p, __p);
else
{
// write_mem_barrier();
__STORE_VALUE(&_M_p, __p);
if (__m == memory_order_seq_cst)
__SYNC_SYNCHRONIZE();
}
}
void
store(__pointer_type __p,
memory_order __m = memory_order_seq_cst) volatile
{
__glibcxx_assert(__m != memory_order_acquire);
__glibcxx_assert(__m != memory_order_acq_rel);
__glibcxx_assert(__m != memory_order_consume);
if (__m == memory_order_relaxed)
__STORE_VALUE(&_M_p, __p);
else
{
// write_mem_barrier();
__STORE_VALUE(&_M_p, __p);
if (__m == memory_order_seq_cst)
__SYNC_SYNCHRONIZE();
}
}
__pointer_type
load(memory_order __m = memory_order_seq_cst) const
{
__glibcxx_assert(__m != memory_order_release);
__glibcxx_assert(__m != memory_order_acq_rel);
// __SYNC_SYNCHRONIZE();
__barrier();
__pointer_type __ret = __LOAD_VALUE(&_M_p);
// __SYNC_SYNCHRONIZE();
__barrier();
return __ret;
}
__pointer_type
load(memory_order __m = memory_order_seq_cst) const volatile
{
__glibcxx_assert(__m != memory_order_release);
__glibcxx_assert(__m != memory_order_acq_rel);
// __SYNC_SYNCHRONIZE();
__barrier();
__pointer_type __ret = __LOAD_VALUE(&_M_p);
// __SYNC_SYNCHRONIZE();
__barrier();
return __ret;
}
__pointer_type
exchange(__pointer_type __p, memory_order __m = memory_order_seq_cst)
{
// XXX built-in assumes memory_order_acquire.
return __SYNC_LOCK_TEST_AND_SET(&_M_p, __p);
}
__pointer_type
exchange(__pointer_type __p,
memory_order __m = memory_order_seq_cst) volatile
{
// XXX built-in assumes memory_order_acquire.
return __SYNC_LOCK_TEST_AND_SET(&_M_p, __p);
}
bool
compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2,
memory_order __m1, memory_order __m2)
{
__glibcxx_assert(__m2 != memory_order_release);
__glibcxx_assert(__m2 != memory_order_acq_rel);
__glibcxx_assert(__m2 <= __m1);
__pointer_type __p1o = __p1;
__pointer_type __p1n = __SYNC_VAL_COMPARE_AND_SWAP(&_M_p, __p1o, __p2);
// Assume extra stores (of same value) allowed in true case.
__p1 = __p1n;
return __p1o == __p1n;
}
bool
compare_exchange_strong(__pointer_type& __p1, __pointer_type __p2,
memory_order __m1, memory_order __m2) volatile
{
__glibcxx_assert(__m2 != memory_order_release);
__glibcxx_assert(__m2 != memory_order_acq_rel);
__glibcxx_assert(__m2 <= __m1);
__pointer_type __p1o = __p1;
__pointer_type __p1n = __SYNC_VAL_COMPARE_AND_SWAP(&_M_p, __p1o, __p2);
// Assume extra stores (of same value) allowed in true case.
__p1 = __p1n;
return __p1o == __p1n;
}
__pointer_type
fetch_add(ptrdiff_t __d, memory_order __m = memory_order_seq_cst)
{ return __SYNC_FETCH_AND_ADD(&_M_p, __d); }
__pointer_type
fetch_add(ptrdiff_t __d,
memory_order __m = memory_order_seq_cst) volatile
{ return __SYNC_FETCH_AND_ADD(&_M_p, __d); }
__pointer_type
fetch_sub(ptrdiff_t __d, memory_order __m = memory_order_seq_cst)
{ return __SYNC_FETCH_AND_SUB(&_M_p, __d); }
__pointer_type
fetch_sub(ptrdiff_t __d,
memory_order __m = memory_order_seq_cst) volatile
{ return __SYNC_FETCH_AND_SUB(&_M_p, __d); }
};
} // namespace __atomic2
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace std
#endif
<|start_filename|>kernel/cga.cc<|end_filename|>
#include "types.h"
#include "kernel.hh"
#include "amd64.h"
#include <string.h>
#define BACKSPACE 0x100
#define CRTPORT 0x3d4
static volatile u16 *crt = (u16*)(KBASE + 0xb8000); // CGA memory
// Black background, (high intensity) white foreground
static int color = ((0 << 4) | 15) << 8;
void
cgaputc(int c)
{
int pos;
// Cursor position: col + 80*row.
outb(CRTPORT, 14);
pos = inb(CRTPORT+1) << 8;
outb(CRTPORT, 15);
pos |= inb(CRTPORT+1);
if(c == '\n')
pos += 80 - pos%80;
else if(c == BACKSPACE){
if(pos > 0) --pos;
} else
crt[pos++] = (c&0xff) | color;
if((pos/80) >= 24){ // Scroll up.
memmove((void *)crt, (void*)(crt+80), sizeof(crt[0])*23*80);
pos -= 80;
memset((void *)(crt+pos), 0, sizeof(crt[0])*(24*80 - pos));
}
outb(CRTPORT, 14);
outb(CRTPORT+1, pos>>8);
outb(CRTPORT, 15);
outb(CRTPORT+1, pos);
crt[pos] = ' ' | 0x0700;
}
void
initcga(void)
{
int i;
for (i = 0; i < 80*25; i++)
crt[i] = 0x0f20;
outb(CRTPORT, 14);
outb(CRTPORT+1, 0);
outb(CRTPORT, 15);
outb(CRTPORT+1, 0);
// Announce that we're here.
for (const char *p=DEBUG?"xv6 DEBUG\n":"xv6\n"; *p; p++)
cgaputc(*p);
}
<|start_filename|>stdinc/uk/time.h<|end_filename|>
#pragma once
typedef int time_t;
struct tm {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year */
int tm_isdst; /* daylight saving time */
};
BEGIN_DECLS
// These math functions are shared by user space and the kernel
struct tm *gmtime_r(const time_t *timep, struct tm *result);
struct tm *localtime_r(const time_t *timep, struct tm *result);
time_t mktime(struct tm *tm);
END_DECLS
<|start_filename|>metis/lib/ibs.c<|end_filename|>
#include <stdio.h>
#include <fcntl.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include "lib/cpumap.h"
#include "lib/ibs.h"
enum { ibs_enabled = 0 };
struct urecord {
/* MSRC001_1034 IBS Op Logical Address Register (IbsRIP) */
uint64_t ibs_op_rip;
/* MSRC001_1035 IBS Op Data Register */
uint64_t ibs_op_data1;
/* MSRC001_1036 IBS Op Data 2 Register */
uint64_t ibs_op_data2;
/* MSRC001_1037 IBS Op Data 3 Register */
uint64_t ibs_op_data3;
/* MSRC001_1038 IBS DC Linear Address Register (IbsDcLinAd) */
uint64_t ibs_dc_linear;
/* MSRC001_1039 IBS DC Physical Address Register (IbsDcPhysAd) */
uint64_t ibs_dc_phys;
char sdp_valid;
char ibs_dc_kmem_cachep_name[32];
uint64_t bp;
void *ibs_dc_kmem_cache_caller;
int ibs_dc_kmem_cache_offset;
unsigned long ts;
} __attribute__ ((__packed__));
#define NUREC 3000
#define PAGE_SIZE 4096
#define NUREC_BYTES (NUREC * sizeof(struct urecord))
#define NUREC_SIZE ((NUREC_BYTES + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))
#define NUREC_PAGES (NUREC_SIZE / PAGE_SIZE)
static __thread uint64_t nsamples = 0;
static __thread uint64_t latency = 0;
static void
writefile(const char *path, const char *str)
{
int fd = open(path, O_WRONLY);
assert(fd >= 0);
assert(write(fd, str, strlen(str)) == strlen(str));
close(fd);
}
static void
readsamples(const char *path)
{
int fd = open(path, O_RDONLY);
assert(fd >= 0);
struct urecord *ur =
(struct urecord *) mmap(0, NUREC_SIZE, PROT_READ, MAP_PRIVATE, fd, 0);
assert(ur != MAP_FAILED);
latency = 0;
for (nsamples = 0; nsamples < NUREC && ur[nsamples].ibs_op_rip;
nsamples++)
latency += ((ur[nsamples].ibs_op_data3 >> 32) & 0xffff);
close(fd);
munmap(ur, NUREC_SIZE);
}
void
ibs_start(int cid)
{
if (!ibs_enabled)
return;
cid = lcpu_to_pcpu[cid];
nsamples = 0;
latency = 0;
char path[512];
char value[20];
// clear samples
snprintf(path, sizeof(path), "/sys/kernel/amd10h-ibs/cpu%d/record", cid);
writefile(path, "0");
// set opdata2
snprintf(path, sizeof(path), "/sys/kernel/amd10h-ibs/cpu%d/opdata2", cid);
// notify the ibs module to record all types of cache refills
writefile(path, "1 2 3");
// set opdata3
snprintf(path, sizeof(path), "/sys/kernel/amd10h-ibs/cpu%d/opdata3", cid);
// track loads only (the latency for stores is not valid)
snprintf(value, sizeof(value), "%x", (1 << 7) | (1 << 0));
writefile(path, value);
// set opdata3pred
snprintf(path, sizeof(path), "/sys/kernel/amd10h-ibs/cpu%d/opdata3pred", cid);
writefile(path, "=");
// set opctl to start
snprintf(path, sizeof(path), "/sys/kernel/amd10h-ibs/cpu%d/opctl", cid);
snprintf(value, sizeof(value), "%x", (0 << 19) | (1 << 17) | 0xffff);
writefile(path, value);
}
void
ibs_stop(int cid)
{
if (!ibs_enabled)
return;
cid = lcpu_to_pcpu[cid];
char path[512];
// set opctl to stop
snprintf(path, sizeof(path), "/sys/kernel/amd10h-ibs/cpu%d/opctl", cid);
writefile(path, "0");
snprintf(path, sizeof(path), "/sys/kernel/amd10h-ibs/cpu%d/record", cid);
readsamples(path);
}
uint64_t
ibs_read_count(int cid)
{
return nsamples;
}
uint64_t
ibs_read_latency(int cid)
{
return latency;
}
<|start_filename|>bin/exechack.cc<|end_filename|>
#include "types.h"
#include "user.h"
#include "mtrace.h"
#include "amd64.h"
#include <stdio.h>
#include <unistd.h>
#define NITERS 100
#define PROCMAX NCPU
#define PROCMIN (NCPU-4)
static void
worker0(void)
{
const char* av[] = { "exechack", "w", 0 };
execv(av[0], const_cast<char * const *>(av));
die("worker exec");
}
static void
worker1(void)
{
exit(0);
}
static void
master(void)
{
u64 pcount = 0;
u64 i = 0;
u64 t0 = rdtsc();
while (i < NITERS) {
while (pcount < PROCMAX) {
int pid;
pid = fork();
if (pid < 0)
die("master fork");
if (pid == 0)
worker0();
pcount++;
}
while (pcount > PROCMIN) {
if (wait(NULL) < 0)
die("master wait");
pcount--;
i++;
}
}
while (pcount) {
wait(NULL);
pcount--;
}
u64 t1 = rdtsc();
printf("%lu\n", (t1-t0)/i);
}
int
main(int ac, char **av)
{
if (ac > 1 && av[1][0] == 'w')
worker1();
master();
return 0;
}
<|start_filename|>kernel/trap.cc<|end_filename|>
#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "amd64.h"
#include "cpu.hh"
#include "traps.h"
#include "spinlock.hh"
#include "condvar.hh"
#include "proc.hh"
#include "kmtrace.hh"
#include "bits.hh"
#include "kalloc.hh"
#include "apic.hh"
#include "irq.hh"
#include "kstream.hh"
#include "hwvm.hh"
#include "refcache.hh"
#include "cpuid.hh"
extern "C" void __uaccess_end(void);
struct intdesc idt[256] __attribute__((aligned(16)));
static char fpu_initial_state[FXSAVE_BYTES];
// boot.S
extern u64 trapentry[];
static struct irq_info
{
irq_handler *handlers;
// True if this IRQ has been allocated to a device
bool in_use;
} irq_info[256 - T_IRQ0];
static void trap(struct trapframe *tf);
u64
sysentry_c(u64 a0, u64 a1, u64 a2, u64 a3, u64 a4, u64 a5, u64 num)
{
if(myproc()->killed) {
mtstart(trap, myproc());
exit(-1);
}
trapframe *tf = (trapframe*) (myproc()->kstack + KSTACKSIZE - sizeof(*tf));
myproc()->tf = tf;
u64 r = syscall(a0, a1, a2, a3, a4, a5, num);
if(myproc()->killed) {
mtstart(trap, myproc());
exit(-1);
}
return r;
}
int
do_pagefault(struct trapframe *tf)
{
uptr addr = rcr2();
if (myproc()->uaccess_) {
if (addr >= USERTOP)
panic("do_pagefault: %lx", addr);
sti();
if(pagefault(myproc()->vmap.get(), addr, tf->err) >= 0){
return 0;
}
console.println("pagefault accessing user address from kernel (addr ",
(void*)addr, " rip ", (void*)tf->rip, ")");
tf->rax = -1;
tf->rip = (u64)__uaccess_end;
return 0;
} else if (tf->err & FEC_U) {
sti();
if(pagefault(myproc()->vmap.get(), addr, tf->err) >= 0){
return 0;
}
uerr.println("pagefault from user for ", shex(addr),
" err ", (int)tf->err);
cli();
}
return -1;
}
static inline void
lapiceoi()
{
lapic->eoi();
}
namespace {
DEFINE_PERCPU(uintptr_t, nmi_lastpc);
DEFINE_PERCPU(int, nmi_swallow);
}
// C/C++ entry point for traps; called by assembly trap stub
extern "C" void
trap_c(struct trapframe *tf)
{
if (tf->trapno == T_NMI) {
// An NMI can come in after popcli() drops ncli to zero and intena
// is 1, but before popcli() checks intena and calls sti. If the
// NMI handler acquires any lock, acquire() will call pushcli(),
// which will set intena to 0, and upon return from the NMI, the
// preempted popcli will observe intena=0 and fail to sti.
int intena_save = mycpu()->intena;
// The only locks that we can acquire during NMI are ones
// we acquire only during NMI.
// NMIs are tricky. On the one hand, they're edge triggered,
// which means we're not guaranteed to get an NMI interrupt for
// every NMI event, so we have to proactively handle all of the
// NMI sources we can. On the other hand, they're also racy,
// since an NMI source may successfully queue an NMI behind an
// existing NMI, but we may detect that source when handling the
// first NMI. Our solution is to detect back-to-back NMIs and
// keep track of how many NMI sources we've handled: as long as
// the number of back-to-back NMIs in a row never exceeds the
// number of NMI sources we've handled across these back-to-back
// NMIs, we're not concerned, even if an individual NMI doesn't
// detect any active sources.
// Is this a back-to-back NMI? If so, we might have handled all
// of the NMI sources already.
bool repeat = (*nmi_lastpc == tf->rip);
*nmi_lastpc = tf->rip;
if (!repeat)
*nmi_swallow = 0;
// Handle NMIs
int handled = 0;
handled += sampintr(tf);
// No lapiceoi because only fixed delivery mode interrupts need to
// be EOI'd (and fixed mode interrupts can't be programmed to
// produce an NMI vector).
if (handled == 0 && !*nmi_swallow)
panic("NMI");
// This NMI accounts for one handled event, so we can swallow up
// to handled - 1 more back-to-back NMIs after this one.
*nmi_swallow += handled - 1;
mycpu()->intena = intena_save;
return;
}
if (tf->trapno == T_DBLFLT)
kerneltrap(tf);
#if MTRACE
if (myproc()->mtrace_stacks.curr >= 0)
mtpause(myproc());
mtstart(trap, myproc());
// XXX mt_ascope ascope("trap:%d", tf->trapno);
#endif
trap(tf);
#if MTRACE
mtstop(myproc());
if (myproc()->mtrace_stacks.curr >= 0)
mtresume(myproc());
#endif
}
static void
trap(struct trapframe *tf)
{
switch(tf->trapno){
case T_IRQ0 + IRQ_TIMER:
kstats::inc(&kstats::sched_tick_count);
// for now, just care about timer interrupts
#if CODEX
codex_magic_action_run_async_event(T_IRQ0 + IRQ_TIMER);
#endif
if (mycpu()->timer_printpc) {
cprintf("cpu%d: proc %s rip %lx rsp %lx cs %x\n",
mycpu()->id,
myproc() ? myproc()->name : "(none)",
tf->rip, tf->rsp, tf->cs);
if (mycpu()->timer_printpc == 2 && tf->rbp > KBASE) {
uptr pc[10];
getcallerpcs((void *) tf->rbp, pc, NELEM(pc));
for (int i = 0; i < 10 && pc[i]; i++)
cprintf("cpu%d: %lx\n", mycpu()->id, pc[i]);
}
mycpu()->timer_printpc = 0;
}
if (mycpu()->id == 0)
timerintr();
refcache::mycache->tick();
lapiceoi();
if (mycpu()->no_sched_count) {
kstats::inc(&kstats::sched_blocked_tick_count);
// Request a yield when no_sched_count is released. We can
// modify this without protection because interrupts are
// disabled.
mycpu()->no_sched_count |= NO_SCHED_COUNT_YIELD_REQUESTED;
return;
}
break;
case T_IRQ0 + IRQ_IDE:
ideintr();
lapiceoi();
piceoi();
break;
case T_IRQ0 + IRQ_IDE+1:
// Bochs generates spurious IDE1 interrupts.
break;
case T_IRQ0 + IRQ_KBD:
kbdintr();
lapiceoi();
piceoi();
break;
case T_IRQ0 + IRQ_COM2:
case T_IRQ0 + IRQ_COM1:
uartintr();
lapiceoi();
piceoi();
break;
case T_IRQ0 + 7:
case T_IRQ0 + IRQ_SPURIOUS:
cprintf("cpu%d: spurious interrupt at %x:%lx\n",
mycpu()->id, tf->cs, tf->rip);
// [Intel SDM 10.9 Spurious Interrupt] The spurious interrupt
// vector handler should return without an EOI.
//lapiceoi();
break;
case T_IRQ0 + IRQ_ERROR:
cprintf("cpu%d: lapic error?\n", mycpu()->id);
lapiceoi();
break;
case T_TLBFLUSH: {
lapiceoi();
mmu::shootdown::on_ipi();
break;
}
case T_SAMPCONF:
lapiceoi();
sampconf();
break;
case T_IPICALL: {
extern void on_ipicall();
lapiceoi();
on_ipicall();
break;
}
case T_DEVICE: {
// Clear "task switched" flag to enable floating-point
// instructions. sched will set this again when it switches
// tasks.
clts();
// Save current FPU state
// XXX(Austin) This process could exit and free its fpu_state, but
// scoped_gc_epoch breaks if I use it here.
// XXX(Austin) Do I need to FWAIT first?
struct proc *fpu_owner = mycpu()->fpu_owner;
if (fpu_owner) {
assert(fpu_owner->fpu_state);
fxsave(fpu_owner->fpu_state);
}
// Lazily allocate myproc's FPU state
if (!myproc()->fpu_state) {
myproc()->fpu_state = kmalloc(FXSAVE_BYTES, "(fxsave)");
if (!myproc()->fpu_state) {
console.println("out of memory allocating fxsave region");
myproc()->killed = 1;
break;
}
memmove(myproc()->fpu_state, &fpu_initial_state, FXSAVE_BYTES);
}
// Restore myproc's FPU state
fxrstor(myproc()->fpu_state);
mycpu()->fpu_owner = myproc();
break;
}
default:
if (tf->trapno >= T_IRQ0 && irq_info[tf->trapno - T_IRQ0].handlers) {
for (auto h = irq_info[tf->trapno - T_IRQ0].handlers; h; h = h->next)
h->handle_irq();
lapiceoi();
piceoi();
return;
}
if (tf->trapno == T_PGFLT) {
if (do_pagefault(tf) == 0)
return;
// XXX distinguish between SIGSEGV and SIGBUS?
if (myproc()->deliver_signal(SIGSEGV))
return;
}
if (myproc() == 0 || (tf->cs&3) == 0)
kerneltrap(tf);
// In user space, assume process misbehaved.
uerr.println("pid ", myproc()->pid, ' ', myproc()->name,
": trap ", (u64)tf->trapno, " err ", (u32)tf->err,
" on cpu ", myid(), " rip ", shex(tf->rip),
" rsp ", shex(tf->rsp), " addr ", shex(rcr2()),
"--kill proc");
myproc()->killed = 1;
}
// Force process exit if it has been killed and is in user space.
// (If it is still executing in the kernel, let it keep running
// until it gets to the regular system call return.)
if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)
exit(-1);
// Force process to give up CPU on clock tick.
// If interrupts were on while locks held, would need to check nlock.
if(myproc() && myproc()->get_state() == RUNNING &&
(tf->trapno == T_IRQ0+IRQ_TIMER || myproc()->yield_)) {
yield();
}
// Check if the process has been killed since we yielded
if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)
exit(-1);
}
void
inittrap(void)
{
u64 entry;
u8 bits;
int i;
bits = INT_P | SEG_INTR64; // present, interrupt gate
for(i=0; i<256; i++) {
entry = trapentry[i];
idt[i] = INTDESC(KCSEG, entry, bits);
}
// Conservatively reserve all legacy IRQs. This might cause us to
// not be able to configure a device.
for (int i = 0; i < 16; ++i)
irq_info[i].in_use = true;
// Also reserve the spurious vector
irq_info[IRQ_SPURIOUS].in_use = true;
// And reserve interrupt 255 (Intel SDM Vol. 3 suggests this can't
// be used for MSI).
irq_info[255 - T_IRQ0].in_use = true;
}
void
initfpu(void)
{
// Allow ourselves to use FPU instructions. We'll clear this before
// we schedule anything.
lcr0(rcr0() & ~(CR0_TS | CR0_EM));
// Initialize FPU, ignoring pending FP exceptions
fninit();
// Don't generate interrupts for any SSE exceptions
ldmxcsr(0x1f80);
// Stash away the initial FPU state to use as each process' initial
// FPU state
if (myid() == 0)
fxsave(&fpu_initial_state);
}
void
initmsr(void)
{
// XXX Where should this code live?
#if defined(DISABLE_PREFETCH_STREAM)
#define CONTROL_PREFETCH_STREAM 1
#else
#define CONTROL_PREFETCH_STREAM 0
#define DISABLE_PREFETCH_STREAM 0
#endif
#if defined(DISABLE_PREFETCH_ADJ)
#define CONTROL_PREFETCH_ADJ 1
#else
#define CONTROL_PREFETCH_ADJ 0
#define DISABLE_PREFETCH_ADJ 0
#endif
if (CONTROL_PREFETCH_STREAM || CONTROL_PREFETCH_ADJ) {
// Is the MISC_FEATURE_CONTROL MSR valid?
auto m = cpuid::model();
if (!(cpuid::vendor_is_intel() && m.family == 6 &&
(m.model == 0x1a || m.model == 0x1e || m.model == 0x1f || // Nehalem
m.model == 0x25 || m.model == 0x2c || // Westmere
m.model == 0x2e || // Nehalem-EX
m.model == 0x2f))) // Westmere-EX
panic("Cannot control hardware prefetcher for this CPU model");
uint64_t mfc = readmsr(MSR_INTEL_MISC_FEATURE_CONTROL);
if (DISABLE_PREFETCH_STREAM)
mfc |= MSR_INTEL_MISC_FEATURE_CONTROL_DISABLE_MLC_STREAMER;
else if (CONTROL_PREFETCH_STREAM)
mfc &= ~MSR_INTEL_MISC_FEATURE_CONTROL_DISABLE_MLC_STREAMER;
if (DISABLE_PREFETCH_ADJ)
mfc |= MSR_INTEL_MISC_FEATURE_CONTROL_DISABLE_MLC_SPATIAL;
else if (CONTROL_PREFETCH_ADJ)
mfc &= ~MSR_INTEL_MISC_FEATURE_CONTROL_DISABLE_MLC_SPATIAL;
writemsr(MSR_INTEL_MISC_FEATURE_CONTROL, mfc);
if (myid() == 0) {
if (CONTROL_PREFETCH_STREAM)
cprintf("msr: MLC stream prefetcher %s\n",
DISABLE_PREFETCH_STREAM ? "disabled" : "enabled");
if (CONTROL_PREFETCH_ADJ)
cprintf("msr: Adjacent cache line prefetcher %s\n",
DISABLE_PREFETCH_ADJ ? "disabled" : "enabled");
}
// XXX There are also the DCU prefetchers. ben's BIOS doesn't
// disable these when I set "Hardware prefetcher" to disable, so
// I'm not convinced the bits are right.
}
}
void
initnmi(void)
{
void *nmistackbase = kalloc("kstack", KSTACKSIZE);
mycpu()->ts.ist[1] = (u64) nmistackbase + KSTACKSIZE;
if (mycpu()->id == 0)
idt[T_NMI].ist = 1;
}
void
initdblflt(void)
{
void *dfaultstackbase = kalloc("kstack", KSTACKSIZE);
mycpu()->ts.ist[2] = (uintptr_t)dfaultstackbase + KSTACKSIZE;
if (mycpu()->id == 0)
idt[T_DBLFLT].ist = 2;
}
void
initseg(struct cpu *c)
{
volatile struct desctr dtr;
dtr.limit = sizeof(idt) - 1;
dtr.base = (u64)idt;
lidt((void *)&dtr.limit);
// Load per-CPU GDT
memmove(c->gdt, bootgdt, sizeof(bootgdt));
dtr.limit = sizeof(c->gdt) - 1;
dtr.base = (u64)c->gdt;
lgdt((void *)&dtr.limit);
// When executing a syscall instruction the CPU sets the SS selector
// to (star >> 32) + 8 and the CS selector to (star >> 32).
// When executing a sysret instruction the CPU sets the SS selector
// to (star >> 48) + 8 and the CS selector to (star >> 48) + 16.
u64 star = ((((u64)UCSEG|0x3) - 16)<<48)|((u64)KCSEG<<32);
writemsr(MSR_STAR, star);
writemsr(MSR_LSTAR, (u64)&sysentry);
writemsr(MSR_SFMASK, FL_TF | FL_IF);
}
// Pushcli/popcli are like cli/sti except that they are matched:
// it takes two popcli to undo two pushcli. Also, if interrupts
// are off, then pushcli, popcli leaves them off.
void
pushcli(void)
{
u64 rflags;
rflags = readrflags();
cli();
if(mycpu()->ncli++ == 0)
mycpu()->intena = rflags & FL_IF;
}
void
popcli(void)
{
if(readrflags()&FL_IF)
panic("popcli - interruptible");
if(--mycpu()->ncli < 0)
panic("popcli");
if(mycpu()->ncli == 0 && mycpu()->intena)
sti();
}
// Record the current call stack in pcs[] by following the %rbp chain.
void
getcallerpcs(void *v, uptr pcs[], int n)
{
uintptr_t rbp;
int i;
rbp = (uintptr_t)v;
for(i = 0; i < n; i++){
// Read saved %rip
uintptr_t saved_rip;
if (safe_read_vm(&saved_rip, rbp + sizeof(uintptr_t), sizeof(saved_rip)) !=
sizeof(saved_rip))
break;
// Subtract 1 so it points to the call instruction
pcs[i] = saved_rip - 1;
// Read saved %rbp
if (safe_read_vm(&rbp, rbp, sizeof(rbp)) != sizeof(rbp))
break;
}
for(; i < n; i++)
pcs[i] = 0;
}
bool
irq::reserve(const int *accept_gsi, size_t num_accept)
{
assert(!valid());
int gsi = -1;
if (accept_gsi) {
for (size_t i = 0; i < num_accept; ++i) {
if (!irq_info[accept_gsi[i]].in_use) {
gsi = accept_gsi[i];
break;
}
}
} else {
// Find a free GSI. Start from the top because system-assigned
// GSI's tend to be low.
for (int try_gsi = sizeof(irq_info) / sizeof(irq_info[0]) - 1; try_gsi >= 0;
--try_gsi) {
if (!irq_info[try_gsi].in_use) {
gsi = try_gsi;
break;
}
}
}
if (gsi == -1)
// XXX Level-triggered, active-low interrupts can share an IRQ line
return false;
irq_info[gsi].in_use = true;
this->gsi = gsi;
vector = T_IRQ0 + gsi;
return true;
}
void
irq::register_handler(irq_handler *handler)
{
assert(valid());
assert(vector == gsi + T_IRQ0);
handler->next = irq_info[gsi].handlers;
irq_info[gsi].handlers = handler;
}
void
to_stream(class print_stream *s, const struct irq &irq)
{
if (irq.valid()) {
s->print("IRQ ", irq.gsi);
if (irq.level_triggered)
s->print(irq.active_low ? " (level low)" : " (level high)");
else
s->print(irq.active_low ? " (falling edge)" : " (rising edge)");
} else {
s->print("invalid IRQ");
}
}
void
scoped_critical::release_yield()
{
kstats::inc(&kstats::sched_delayed_tick_count);
// Clear the yield request and yield
modify_no_sched_count(-NO_SCHED_COUNT_YIELD_REQUESTED);
// Below here is racy, strictly speaking, but that's okay.
yield();
}
bool
check_critical(critical_mask mask)
{
if (mask == NO_CRITICAL)
return true;
bool safe = !(readrflags() & FL_IF);
if (mask & NO_INT)
return safe;
safe = safe || mycpu()->no_sched_count;
if (mask & NO_SCHED)
return safe;
safe = safe || myproc()->cpu_pin;
if (mask & NO_MIGRATE)
return safe;
return false;
}
<|start_filename|>include/ahcireg.hh<|end_filename|>
#pragma once
/*
* Originally from HiStar kern/dev/ahcireg.h
*/
#include "satareg.hh"
struct ahci_reg_global {
u32 cap; /* host capabilities */
u32 ghc; /* global host control */
u32 is; /* interrupt status */
u32 pi; /* ports implemented */
u32 vs; /* version */
u32 ccc_ctl; /* command completion coalescing control */
u32 ccc_ports; /* command completion coalescing ports */
u32 em_loc; /* enclosure management location */
u32 em_ctl; /* enclosure management control */
u32 cap2; /* extended host capabilities */
u32 bohc; /* BIOS/OS handoff control and status */
};
#define AHCI_GHC_AE (1 << 31)
#define AHCI_GHC_IE (1 << 1)
#define AHCI_GHC_HR (1 << 0)
struct ahci_reg_port {
u64 clb; /* command list base address */
u64 fb; /* FIS base address */
u32 is; /* interrupt status */
u32 ie; /* interrupt enable */
u32 cmd; /* command and status */
u32 reserved;
u32 tfd; /* task file data */
u32 sig; /* signature */
u32 ssts; /* sata phy status: SStatus */
u32 sctl; /* sata phy control: SControl */
u32 serr; /* sata phy error: SError */
u32 sact; /* sata phy active: SActive */
u32 ci; /* command issue */
u32 sntf; /* sata phy notification: SNotify */
u32 fbs; /* FIS-based switching control */
};
#define AHCI_PORT_CMD_ST (1 << 0) /* start */
#define AHCI_PORT_CMD_SUD (1 << 1) /* spin-up device */
#define AHCI_PORT_CMD_POD (1 << 2) /* power on device */
#define AHCI_PORT_CMD_FRE (1 << 4) /* FIS receive enable */
#define AHCI_PORT_CMD_FR (1 << 14) /* FIS receive running */
#define AHCI_PORT_CMD_CR (1 << 15) /* command list running */
#define AHCI_PORT_CMD_ACTIVE (1 << 28) /* ICC active */
#define AHCI_PORT_TFD_ERR(tfd) (((tfd) >> 8) & 0xff)
#define AHCI_PORT_TFD_STAT(tfd) (((tfd) >> 0) & 0xff)
#define AHCI_PORT_SCTL_RESET 0x01
#define AHCI_PORT_INTR_DHRE (1 << 0)
struct ahci_reg {
union {
struct ahci_reg_global g;
char __pad[0x100];
};
struct {
union {
struct ahci_reg_port p;
char __pad[0x80];
};
} port[32];
};
struct ahci_recv_fis {
u8 dsfis[0x20]; /* DMA setup FIS */
u8 psfis[0x20]; /* PIO setup FIS */
sata_fis_reg reg; /* D2H register FIS */
u8 __pad[0x4];
u8 sdbfis[0x8]; /* set device bits FIS */
u8 ufis[0x40]; /* unknown FIS */
u8 reserved[0x60];
};
struct ahci_cmd_header {
u16 flags;
u16 prdtl;
u32 prdbc;
u64 ctba;
u64 reserved0;
u64 reserved1;
};
#define AHCI_CMD_FLAGS_WRITE (1 << 6)
#define AHCI_CMD_FLAGS_CFL_MASK 0x1f /* command FIS len, in DWs */
struct ahci_prd {
u64 dba;
u32 reserved;
u32 dbc; /* one less than #bytes */
};
struct ahci_cmd_table {
u8 cfis[0x40]; /* command FIS */
u8 acmd[0x10]; /* ATAPI command */
u8 reserved[0x30];
ahci_prd prdt[DISK_REQMAX / PGSIZE + 1];
};
<|start_filename|>include/lb.hh<|end_filename|>
#pragma once
#define NCPU_PER_SOCKET (NCPU/NSOCKET)
#include "rnd.hh"
#include "percpu.hh"
template<int N>
struct random_permutation {
public:
random_permutation() : i_(0) {
assert(N <= 256);
for (int i = 0; i < N; i++)
x_[i] = i;
}
void reset() {
i_ = 0;
}
int next() {
#if CODEX
int r = rnd() % (N - i_);
#else
int r = rdtsc() % (N - i_);
#endif
std::swap(x_[i_], x_[r]);
return x_[i_++];
}
private:
char x_[N];
int i_;
};
// For wrapping into <percpu>, which maybe important to avoid false sharing
struct persocket {
random_permutation<NCPU_PER_SOCKET-1> perm;
};
struct othersocket {
random_permutation<NCPU-NCPU_PER_SOCKET> perm;
};
template<class Pool>
class balance_pool {
public:
balance_pool(u64 max) : balance_max_(max) {}
bool balanced() const {
Pool* thispool = (Pool*) this;
u64 c = thispool->balance_count();
return c != 0 && c != balance_max_;
}
void balance_with(Pool* otherpool) {
Pool* thispool = (Pool*) this;
u64 thisbal = thispool->balance_count();
u64 otherbal = otherpool->balance_count();
if (thisbal < otherbal) {
otherpool->balance_move_to(thispool);
} else if (otherbal > thisbal) {
thispool->balance_move_to(otherpool);
}
}
private:
u64 balance_max_;
};
template<class PoolDir, class Pool>
class balancer {
public:
balancer(const PoolDir* bd) : bd_(bd) {}
~balancer() {}
void balance() {
int myid = mycpu()->id;
Pool* thispool = bd_->balance_get(myid);
if (!thispool)
return;
u64 sock_first_core = (myid / NCPU_PER_SOCKET) * NCPU_PER_SOCKET;
u64 sock_myoff = myid % NCPU_PER_SOCKET;
rpsock_->perm.reset();
for (int i = 0; i < NCPU_PER_SOCKET-1; i++) {
int bal_id = sock_first_core +
((sock_myoff + 1 + rpsock_->perm.next()) % NCPU_PER_SOCKET);
Pool* otherpool = bd_->balance_get(bal_id);
if (otherpool && (thispool != otherpool)) {
thispool->balance_with(otherpool);
if (thispool->balanced())
return;
}
}
rpother_->perm.reset();
for (int i = 0; i < NCPU-NCPU_PER_SOCKET; i++) {
int bal_id = (sock_first_core + NCPU_PER_SOCKET +
rpother_->perm.next()) % NCPU;
Pool* otherpool = bd_->balance_get(bal_id);
if (otherpool && (thispool != otherpool)) {
thispool->balance_with(otherpool);
if (thispool->balanced())
break;
}
}
}
private:
const PoolDir* const bd_;
percpu<persocket,NO_CRITICAL> rpsock_;
percpu<othersocket,NO_CRITICAL> rpother_;
};
<|start_filename|>include/codex.hh<|end_filename|>
#pragma once
// Helpers for codex
// XXX: do a better job of sharing the common defines
// between the xv6 codebase and the qemu codebase
#define ALWAYS_INLINE __attribute__((always_inline))
#if CODEX && !defined(XV6_USER)
#define __SYNC_FETCH_AND_ADD __codex_sync_fetch_and_add
#define __SYNC_FETCH_AND_SUB __codex_sync_fetch_and_sub
#define __SYNC_FETCH_AND_OR __codex_sync_fetch_and_or
#define __SYNC_FETCH_AND_AND __codex_sync_fetch_and_and
#define __SYNC_FETCH_AND_XOR __codex_sync_fetch_and_xor
#define __SYNC_FETCH_AND_NAND __codex_sync_fetch_and_nand
#define __SYNC_ADD_AND_FETCH __codex_sync_add_and_fetch
#define __SYNC_SUB_AND_FETCH __codex_sync_sub_and_fetch
#define __SYNC_OR_AND_FETCH __codex_sync_or_and_fetch
#define __SYNC_AND_AND_FETCH __codex_sync_and_and_fetch
#define __SYNC_XOR_AND_FETCH __codex_sync_xor_and_fetch
#define __SYNC_NAND_AND_FETCH __codex_sync_nand_and_fetch
#define __SYNC_BOOL_COMPARE_AND_SWAP __codex_sync_bool_compare_and_swap
#define __SYNC_VAL_COMPARE_AND_SWAP __codex_sync_val_compare_and_swap
#define __SYNC_SYNCHRONIZE __codex_sync_synchronize
#define __SYNC_LOCK_TEST_AND_SET __codex_sync_lock_test_and_set
#define __SYNC_LOCK_RELEASE __codex_sync_lock_release
#define __STORE_VALUE __codex_store_value
#define __LOAD_VALUE __codex_load_value
#else
#define __SYNC_FETCH_AND_ADD __sync_fetch_and_add
#define __SYNC_FETCH_AND_SUB __sync_fetch_and_sub
#define __SYNC_FETCH_AND_OR __sync_fetch_and_or
#define __SYNC_FETCH_AND_AND __sync_fetch_and_and
#define __SYNC_FETCH_AND_XOR __sync_fetch_and_xor
#define __SYNC_FETCH_AND_NAND __sync_fetch_and_nand
#define __SYNC_ADD_AND_FETCH __sync_add_and_fetch
#define __SYNC_SUB_AND_FETCH __sync_sub_and_fetch
#define __SYNC_OR_AND_FETCH __sync_or_and_fetch
#define __SYNC_AND_AND_FETCH __sync_and_and_fetch
#define __SYNC_XOR_AND_FETCH __sync_xor_and_fetch
#define __SYNC_NAND_AND_FETCH __sync_nand_and_fetch
#define __SYNC_BOOL_COMPARE_AND_SWAP __sync_bool_compare_and_swap
#define __SYNC_VAL_COMPARE_AND_SWAP __sync_val_compare_and_swap
#define __SYNC_SYNCHRONIZE __sync_synchronize
#define __SYNC_LOCK_TEST_AND_SET __sync_lock_test_and_set
#define __SYNC_LOCK_RELEASE __sync_lock_release
#define __STORE_VALUE __store_value
#define __LOAD_VALUE __load_value
template <typename T> inline ALWAYS_INLINE void
__store_value(T *ptr, T value)
{
*ptr = value;
}
template <typename T> inline ALWAYS_INLINE void
__store_value(volatile T *ptr, T value)
{
*ptr = value;
}
template <typename T> inline ALWAYS_INLINE T
__load_value(const T *ptr)
{
return *ptr;
}
template <typename T> inline ALWAYS_INLINE T
__load_value(volatile const T *ptr)
{
return *ptr;
}
#endif
#if !defined(XV6_USER)
#include <assert.h>
#include <stdint.h>
class codex {
public:
static unsigned int current_tid(void);
static inline ALWAYS_INLINE bool
in_atomic_section(void)
{
return g_atomic_section;
}
static inline void
on_atomic_section_completion(void);
struct atomic_section {
atomic_section(bool enabled)
: enabled(enabled)
{
if (enabled)
++g_atomic_section;
}
~atomic_section()
{
if (enabled) {
assert(g_atomic_section);
if (!--g_atomic_section)
on_atomic_section_completion();
}
}
// no copy/moving
atomic_section(const atomic_section &) = delete;
atomic_section &operator=(const atomic_section &) = delete;
atomic_section(atomic_section &&) = delete;
const bool enabled;
};
// XXX: make private
static bool g_codex_trace_start;
static unsigned int g_atomic_section;
};
/**
* modelled after mtrace:
* https://github.com/stephentu/qemu-tsx/blob/tsx/mtrace-magic.h
*/
static inline ALWAYS_INLINE void
codex_magic(uint64_t ax, uint64_t bx,
uint64_t cx, uint64_t dx,
uint64_t si, uint64_t di)
{
#if CODEX
if (codex::g_codex_trace_start) {
// 0x0F 0x04 is an un-used x86 opcode, according to
// http://ref.x86asm.net/geek64.html
__asm __volatile(".byte 0x0F\n"
".byte 0x04\n"
:
: "a" (ax), "b" (bx),
"c" (cx), "d" (dx),
"S" (si), "D" (di));
}
#else
// no-op
#endif
}
enum class codex_call_type {
TRACE_START = 0,
TRACE_END,
ACTION_RUN,
};
// copied from gen/protocol.h
enum class action_type
{
R = 0x1,
W = 0x2,
RW = 0x3,
ACQUIRE = 0x10,
ACQUIRED = 0x11,
RELEASE = 0x12,
THREAD_CREATE = 0x20,
THREAD_DESTROY = 0x21,
THREAD_JOIN = 0x22,
THREAD_ENABLE = 0x23,
THREAD_DISABLE = 0x24,
THREAD_WAKE = 0x25,
NOP = 0x30,
LOG = 0x40,
ANNO_STATE = 0x50,
ANNO_CRIT_BEGIN = 0x55,
ANNO_CRIT_END = 0x56,
ASYNC_EVENT = 0x60,
};
enum action_flags
{
ACTION_FLAG_REPLAY = 0x1,
ACTION_FLAG_ATOMIC = 0x2,
ACTION_FLAG_AVOID_RESCHED_THD = 0x4,
};
typedef uint16_t tid_t;
static inline ALWAYS_INLINE uint64_t
codex_encode_action_with_flags(enum action_type type)
{
// action type in lower 32-bits, flags in upper 32-bits
unsigned long flags = 0;
if (codex::in_atomic_section())
flags |= ACTION_FLAG_ATOMIC;
return (flags << 32) | (unsigned long) type;
}
static inline ALWAYS_INLINE void
codex_trace_start(void)
{
assert(!codex::g_codex_trace_start);
codex::g_codex_trace_start = true; // must come before codex_magic()
codex_magic(
(uint64_t) codex_call_type::TRACE_START,
(uint64_t) codex::current_tid(),
0, 0, 0, 0);
}
static inline ALWAYS_INLINE void
codex_trace_end(void)
{
assert(codex::g_codex_trace_start);
codex_magic(
(uint64_t) codex_call_type::TRACE_END,
(uint64_t) codex::current_tid(),
0, 0, 0, 0);
codex::g_codex_trace_start = false; // must come after
}
// GCC __sync_* definitions from:
// http://gcc.gnu.org/onlinedocs/gcc-4.1.1/gcc/Atomic-Builtins.html
//
// we provide __codex_sync variants
//
// the __codex_sync variants should not be called unles CODEX is true
template <typename T> inline ALWAYS_INLINE void
codex_magic_action_run_rw(T *addr, T oldval, T newval)
{
if (codex::g_codex_trace_start)
codex_magic(
(uint64_t) codex_call_type::ACTION_RUN,
(uint64_t) codex::current_tid(),
codex_encode_action_with_flags(action_type::RW),
(uint64_t) addr,
(uint64_t) oldval,
(uint64_t) newval);
}
template <typename T> inline ALWAYS_INLINE void
codex_magic_action_run_rw(volatile T *addr, T oldval, T newval)
{
codex_magic_action_run_rw((T *) addr, oldval, newval);
}
template <typename T> inline ALWAYS_INLINE void
codex_magic_action_run_read(const T *addr, T readval)
{
if (codex::g_codex_trace_start)
codex_magic(
(uint64_t) codex_call_type::ACTION_RUN,
(uint64_t) codex::current_tid(),
codex_encode_action_with_flags(action_type::R),
(uint64_t) addr,
(uint64_t) readval,
(uint64_t) readval);
}
template <typename T> inline ALWAYS_INLINE void
codex_magic_action_run_read(const volatile T *addr, T readval)
{
codex_magic_action_run_read((const T *) addr, readval);
}
template <typename T> inline ALWAYS_INLINE void
codex_magic_action_run_write(T *addr, T oldval, T writeval)
{
if (codex::g_codex_trace_start)
codex_magic(
(uint64_t) codex_call_type::ACTION_RUN,
(uint64_t) codex::current_tid(),
codex_encode_action_with_flags(action_type::W),
(uint64_t) addr,
(uint64_t) oldval,
(uint64_t) writeval);
}
template <typename T> inline ALWAYS_INLINE void
codex_magic_action_run_write(volatile T *addr, T oldval, T writeval)
{
codex_magic_action_run_write((T *) addr, oldval, writeval);
}
inline ALWAYS_INLINE void
codex_magic_action_run_acquire(intptr_t lock, bool acquired)
{
if (codex::g_codex_trace_start)
codex_magic(
(uint64_t) codex_call_type::ACTION_RUN,
(uint64_t) codex::current_tid(),
codex_encode_action_with_flags(acquired ? action_type::ACQUIRED : action_type::ACQUIRE),
(uint64_t) lock,
0, 0);
}
inline ALWAYS_INLINE void
codex_magic_action_run_release(intptr_t lock)
{
if (codex::g_codex_trace_start)
codex_magic(
(uint64_t) codex_call_type::ACTION_RUN,
(uint64_t) codex::current_tid(),
codex_encode_action_with_flags(action_type::RELEASE),
(uint64_t) lock,
0, 0);
}
inline ALWAYS_INLINE void
codex_magic_action_run_thread_create(tid_t tid)
{
if (codex::g_codex_trace_start)
codex_magic(
(uint64_t) codex_call_type::ACTION_RUN,
(uint64_t) codex::current_tid(),
codex_encode_action_with_flags(action_type::THREAD_CREATE),
(uint64_t) tid,
0, 0);
}
inline ALWAYS_INLINE void
codex_magic_action_run_async_event(uint32_t intno)
{
if (codex::g_codex_trace_start)
codex_magic(
(uint64_t) codex_call_type::ACTION_RUN,
(uint64_t) codex::current_tid(),
codex_encode_action_with_flags(action_type::ASYNC_EVENT),
(uint64_t) intno,
0, 0);
}
inline ALWAYS_INLINE void
codex_magic_action_run_nop(void)
{
if (codex::g_codex_trace_start)
codex_magic(
(uint64_t) codex_call_type::ACTION_RUN,
(uint64_t) codex::current_tid(),
codex_encode_action_with_flags(action_type::NOP),
0, 0, 0);
}
void
codex::on_atomic_section_completion(void)
{
assert(!in_atomic_section());
codex_magic_action_run_nop();
}
template <typename T> inline ALWAYS_INLINE void
__codex_store_value(T *ptr, T value)
{
auto before = value;
auto after = (*ptr = value);
codex_magic_action_run_write(ptr, before, after);
}
template <typename T> inline ALWAYS_INLINE void
__codex_store_value(volatile T *ptr, T value)
{
auto before = value;
auto after = (*ptr = value);
codex_magic_action_run_write(ptr, before, after);
}
template <typename T> inline ALWAYS_INLINE T
__codex_load_value(const T *ptr)
{
auto ret = *ptr;
codex_magic_action_run_read(ptr, ret);
return ret;
}
template <typename T> inline ALWAYS_INLINE T
__codex_load_value(volatile const T *ptr)
{
auto ret = *ptr;
codex_magic_action_run_read(ptr, ret);
return ret;
}
#define __CODEX_IMPL_FETCH_AND_OP(ptr, value, op) \
auto before = *ptr; \
auto ret = __sync_fetch_and_ ## op(ptr, value); \
auto after = *ptr; \
codex_magic_action_run_rw(ptr, before, after); \
return ret;
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_add(T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, add);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_sub(T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, sub);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_or(T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, or);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_and(T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, and);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_xor(T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, xor);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_nand(T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, nand);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_add(volatile T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, add);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_sub(volatile T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, sub);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_or(volatile T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, or);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_and(volatile T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, and);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_xor(volatile T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, xor);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_fetch_and_nand(volatile T *ptr, T value)
{
__CODEX_IMPL_FETCH_AND_OP(ptr, value, nand);
}
#define __CODEX_IMPL_OP_AND_FETCH(ptr, value, op) \
auto before = *ptr; \
auto ret = __sync_ ## op ## _and_fetch(ptr, value); \
auto after = *ptr; \
codex_magic_action_run_rw(ptr, before, after); \
return ret;
template <typename T> inline ALWAYS_INLINE T
__codex_sync_add_and_fetch(T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, add);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_sub_and_fetch(T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, sub);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_or_and_fetch(T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, or);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_and_and_fetch(T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, and);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_xor_and_fetch(T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, xor);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_nand_and_fetch(T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, nand);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_add_and_fetch(volatile T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, add);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_sub_and_fetch(volatile T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, sub);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_or_and_fetch(volatile T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, or);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_and_and_fetch(volatile T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, and);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_xor_and_fetch(volatile T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, xor);
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_nand_and_fetch(volatile T *ptr, T value)
{
__CODEX_IMPL_OP_AND_FETCH(ptr, value, nand);
}
template <typename T> inline ALWAYS_INLINE bool
__codex_sync_bool_compare_and_swap(T *ptr, T oldval, T newval)
{
auto before = *ptr;
auto ret = __sync_bool_compare_and_swap(ptr, oldval, newval);
auto after = *ptr;
codex_magic_action_run_rw(ptr, before, after);
return ret;
}
template <typename T> inline ALWAYS_INLINE bool
__codex_sync_bool_compare_and_swap(volatile T *ptr, T oldval, T newval)
{
auto before = *ptr;
auto ret = __sync_bool_compare_and_swap(ptr, oldval, newval);
auto after = *ptr;
codex_magic_action_run_rw(ptr, before, after);
return ret;
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_val_compare_and_swap(T *ptr, T oldval, T newval)
{
auto ret = *ptr;
__codex_sync_bool_compare_and_swap(ptr, oldval, newval);
return ret;
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_val_compare_and_swap(volatile T *ptr, T oldval, T newval)
{
auto ret = *ptr;
__codex_sync_bool_compare_and_swap(ptr, oldval, newval);
return ret;
}
inline ALWAYS_INLINE void
__codex_sync_synchronize()
{
// XXX: do something for codex
__sync_synchronize();
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_lock_test_and_set(T *ptr, T value)
{
auto before = *ptr;
auto ret = __sync_lock_test_and_set(ptr, value);
codex_magic_action_run_rw(ptr, before, ret);
return ret;
}
template <typename T> inline ALWAYS_INLINE T
__codex_sync_lock_test_and_set(volatile T *ptr, T value)
{
auto before = *ptr;
auto ret = __sync_lock_test_and_set(ptr, value);
codex_magic_action_run_rw(ptr, before, ret);
return ret;
}
template <typename T> inline ALWAYS_INLINE void
__codex_sync_lock_release(T *ptr)
{
auto before = *ptr;
__sync_lock_release(ptr);
auto after = *ptr;
codex_magic_action_run_rw(ptr, before, after);
}
template <typename T> inline ALWAYS_INLINE void
__codex_sync_lock_release(volatile T *ptr)
{
auto before = *ptr;
__sync_lock_release(ptr);
auto after = *ptr;
codex_magic_action_run_rw(ptr, before, after);
}
#undef __CODEX_IMPL_FETCH_AND_OP
#undef __CODEX_IMPL_OP_AND_FETCH
#endif /* !defined(XV6_USER) */
<|start_filename|>include/acpica-xv6.h<|end_filename|>
// ACPICA platform definitions for xv6
#pragma once
#include <stdarg.h>
#include <stdint.h>
#include "platform/acgcc.h"
#if defined(__ia64__) || defined(__x86_64__)
#define ACPI_MACHINE_WIDTH 64
#else
#define ACPI_MACHINE_WIDTH 32
#endif
#define COMPILER_DEPENDENT_INT64 int64_t
#define COMPILER_DEPENDENT_UINT64 uint64_t
// No matter what, don't use ACPICA's va_list! It's subtly wrong, and
// ACPICA will silently swap it in if it thinks it doesn't have
// va_list. This should be defined by stdarg.h, but be extra certain.
#ifndef va_arg
#error No va_arg
#endif
// Use ACPICA's built-in cache
#define ACPI_USE_LOCAL_CACHE
// Don't use a special mutex type
#define ACPI_MUTEX_TYPE ACPI_BINARY_SEMAPHORE
// Use xv6 spinlocks. Unfortunately, these have to be heap-allocated
// because acpica expects a copyable handle.
struct spinlock;
#define ACPI_SPINLOCK struct spinlock *
// Use xv6 semaphores.
struct semaphore;
#define ACPI_SEMAPHORE struct semaphore *
<|start_filename|>libutil/include/pmcdb.hh<|end_filename|>
#pragma once
#include <stdint.h>
uint64_t pmcdb_parse_selector(const char *str);
<|start_filename|>stdinc/uk/unistd.h<|end_filename|>
// User/kernel shared unistd definitions
#pragma once
// xv6 fork flags
#define FORK_SHARE_VMAP (1<<0)
#define FORK_SHARE_FD (1<<1)
// xv6 fstatx flags
enum stat_flags {
STAT_NO_FLAGS = 0,
STAT_OMIT_NLINK = 1<<0
};
// lseek flags
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
<|start_filename|>lib/getopt.cc<|end_filename|>
#include "types.h"
#include "user.h"
#include <string.h>
#include <unistd.h>
char *optarg;
int optind = 1;
int
getopt(int argc, char* const argv[], const char *optstring)
{
static char UNKNOWN_OPTION[] = { '?', '\0' };
size_t optIndex;
size_t optLen;
while (optind < argc) {
if (!argv[optind]) {
optind++;
continue;
}
if (argv[optind][0] != '-' || argv[optind][1] == 0 || argv[optind][2] != 0)
return -1;
optIndex = 0;
optLen = strlen(optstring);
for (optIndex = 0; optIndex < optLen; optIndex++) {
char c = optstring[optIndex];
if (!(((c > 'a' - 1) && (c < 'z' + 1)) || ((c > 'A' - 1) && (c < 'Z' + 1))))
continue;
if (argv[optind][1] == c) {
if (optIndex + 1 < optLen && optstring[optIndex + 1] == ':') {
if (optind + 1 < argc) {
optind++;
optarg = argv[optind];
} else {
optarg = UNKNOWN_OPTION;
}
optind++;
return c;
}
optind++;
return c;
}
}
optarg = UNKNOWN_OPTION;
optind++;
continue;
}
return -1;
}
<|start_filename|>bin/maptest.cc<|end_filename|>
#include "types.h"
#include "user.h"
#include "mtrace.h"
#include "amd64.h"
#include "uspinlock.h"
#include "pthread.h"
#include <stdio.h>
#include <sys/mman.h>
static volatile char *p;
static struct uspinlock l;
static volatile int state;
static void
spin(void)
{
volatile int i;
for (i = 0; i < 10000; i++)
;
}
void*
thr(void*)
{
for (;;) {
acquire(&l);
if (state == 1) {
p[0] = 'x';
p[4096] = 'y';
state = 2;
}
if (state == 3) {
state = 4;
printf("about to access after unmap\n");
release(&l);
p[0] = 'X';
p[4096] = 'Y';
acquire(&l);
printf("still alive after unmap write\n");
exit(0);
}
release(&l);
spin();
}
}
int
main(void)
{
p = (char *) 0x80000;
if (mmap((void *) p, 8192, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) < 0) {
die("map failed");
}
pthread_t tid;
pthread_create(&tid, 0, thr, 0);
acquire(&l);
state = 1;
while (state != 2) {
release(&l);
spin();
acquire(&l);
}
if (p[0] != 'x' || p[4096] != 'y') {
die("mismatch");
}
printf("shm ok\n");
if (munmap((void *) p, 8192) < 0) {
die("unmap failed\n");
}
state = 3;
printf("waiting for unmap access\n");
while (state != 4) {
release(&l);
spin();
acquire(&l);
}
printf("maptest done\n");
return 0;
}
<|start_filename|>attic/xdu.cc<|end_filename|>
#if defined(LINUX)
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stddef.h>
#include <errno.h>
typedef uint64_t u64;
#include "wq.hh"
#include "reducer.hh"
#include "user/dirit.hh"
#include "user/util.h"
#define BSIZ 256
#define perf_stop() do { } while(0)
#define perf_start(x, y) do { } while (0)
#else // assume xv6
#include "types.h"
#include "user.h"
#include "lib.h"
#include "fs.h"
#include "uspinlock.h"
#include "wq.hh"
#include "dirit.hh"
#include "percpu.hh"
#include "reducer.hh"
#define stderr 2
#define BSIZ (DIRSIZ+1)
#endif
#include <fcntl.h>
#include <sys/stat.h>
static const bool silent = (DEBUG == 0);
static size_t
du(int fd)
{
struct stat st;
if (fstat(fd, &st) < 0) {
fprintf(stderr, "du: cannot stat\n");
close(fd);
return 0;
}
reducer_opadd<size_t> size(st.st_size);
if (S_ISDIR(st.st_mode)) {
dirit di(fd);
wq_for<dirit>(di,
[](dirit &i)->bool { return !i.end(); },
[&size, &fd](const char *name)->void
{
if (!strcmp(name, ".") || !strcmp(name, ".."))
return;
int nfd = openat(fd, name, 0);
if (nfd >= 0)
size += du(nfd); // should go into work queue
});
} else {
close(fd);
}
return size.get_value();
}
int
main(int ac, char **av)
{
size_t s;
if (ac < 2)
die("usage: %s nworkers", av[0]);
wq_maxworkers = atoi(av[1])-1;
initwq();
perf_start(PERF_SELECTOR, PERF_PERIOD);
s = du(open(".", 0));
perf_stop();
if (!silent) {
printf("%ld\n", s);
wq_dump();
}
return 0;
}
<|start_filename|>kernel/acpica/generate/unix/acpibin/Makefile<|end_filename|>
#
# acpibin - Binary ACPI table utility
#
#
# Note: This makefile is intended to be used from within the native
# ACPICA directory structure, from under generate/unix. It specifically
# places all object files in a generate/unix subdirectory, not within
# the various ACPICA source directories. This prevents collisions
# between different compilations of the same source file with different
# compile options, and prevents pollution of the source code.
#
include ../Makefile.config
PROG = $(OBJDIR)/acpibin
#
# Search paths for source files
#
vpath %.c \
$(ACPIBIN) \
$(ACPICA_UTILITIES) \
$(ACPICA_COMMON) \
$(ACPICA_OSL)
HEADERS = \
$(wildcard $(ACPIBIN)/*.h)
OBJECTS = \
$(OBJDIR)/abcompare.o \
$(OBJDIR)/abmain.o \
$(OBJDIR)/utalloc.o \
$(OBJDIR)/utcache.o \
$(OBJDIR)/utdebug.o \
$(OBJDIR)/utdecode.o \
$(OBJDIR)/utglobal.o \
$(OBJDIR)/utlock.o \
$(OBJDIR)/utmath.o \
$(OBJDIR)/utmisc.o \
$(OBJDIR)/utmutex.o \
$(OBJDIR)/utstate.o \
$(OBJDIR)/utxferror.o \
$(OBJDIR)/osunixxf.o \
$(OBJDIR)/getopt.o
#
# Flags specific to acpibin
#
CFLAGS+= \
-DACPI_BIN_APP \
-I$(ACPIBIN)
#
# Rules
#
$(PROG) : $(OBJECTS)
$(CC) $(LDFLAGS) $(OBJECTS) -o $(PROG)
$(COPYPROG)
$(OBJDIR)/%.o : %.c $(HEADERS) $(ACPICA_HEADERS)
$(COMPILE)
clean :
rm -f $(PROG) $(PROG).exe $(OBJECTS)
install :
$(INSTALLPROG)
<|start_filename|>kernel/asmdefines.cc<|end_filename|>
#include "types.h"
#include "kernel.hh"
#include "spinlock.hh"
#include "amd64.h"
#include "condvar.hh"
#include "proc.hh"
#include "cpu.hh"
#define DEFINE(sym, val) \
asm volatile ("\n#define " #sym " remove%0 " : : "i" (val))
void
asmdefines(void)
{
DEFINE(PROC_KSTACK_OFFSET, __offsetof(struct proc, kstack));
DEFINE(TF_CS, __offsetof(struct trapframe, cs));
DEFINE(PROC_UACCESS, __offsetof(struct proc, uaccess_));
DEFINE(TRAPFRAME_SIZE, sizeof(trapframe));
}
<|start_filename|>include/memlayout.h<|end_filename|>
// The kernel controls the address space above 0xFFFF800000000000.
// Everything above KGLOBAL is identical in every address space.
#define KGLOBAL KVMALLOC
// [KVMALLOC, KVMALLOCEND) is used for dynamic kernel virtual mappings
// of vmalloc'd memory.
#define KVMALLOC 0xFFFFF00000000000ull
#define KVMALLOCEND 0xFFFFF10000000000ull // 1 TB
// Physical memory is direct-mapped from KBASE to KBASEEND in initpg.
#define KBASE 0xFFFFFF0000000000ull
#define KBASEEND 0xFFFFFF5000000000ull // 320GB
// The kernel is linked to run from virtual address KCODE+2MB. boot.S
// sets up a direct mapping at KCODE to KCODE+1GB. This is necessary
// in addition to KBASE because we compile with -mcmodel=kernel, which
// assumes the kernel text and symbols are linked in the top 2GB of
// memory.
#define KCODE 0xFFFFFFFFC0000000ull
#define USERTOP 0x0000800000000000ull
<|start_filename|>lib/fmt.cc<|end_filename|>
#include "types.h"
#include <stdarg.h>
#include "fmt.hh"
#include "lib.h"
extern "C" unsigned int strlen(const char*);
//
// Print a number (base <= 16) in reverse order,
// using specified putch function and associated pointer putdat.
//
static void
printnum (void (*putch) (int, void *), void *putdat,
unsigned long long num, unsigned base, int width, int padc,
bool upper)
{
// recursion a bad idea here
char buf[68], *x;
const char *digits = upper ? "0123456789ABCDEF" : "0123456789abcdef";
for (x = buf; num; num /= base)
*x++ = digits[num % base];
if (x == buf)
*x++ = '0';
if (padc != '-')
for (; width > x - buf; width--)
putch (padc, putdat);
for (; x > buf; width--)
putch (*--x, putdat);
if (padc == '-')
for (; width > 0; width--)
putch (' ', putdat);
}
// Get an unsigned int of various possible sizes from a varargs list,
// depending on the lflag parameter.
//
// These cannot be functions without autoconf-like glue, unfortunately.
// gcc-3.4.5 on x86_64 passes va_list by reference, and doesn't like the
// type (va_list*), and gcc-3.4.6 on i386 passes va_list by value, and
// does handle the type (va_list*).
//
// [http://www.opengroup.org/onlinepubs/009695399/basedefs/stdarg.h.html]
// The object ap may be passed as an argument to another function;
// if that function invokes the va_arg() macro with parameter ap,
// the value of ap in the calling function is unspecified and shall
// be passed to the va_end() macro prior to any further reference to ap.
#define getuint(ap, lflag) \
({ \
long long __v; \
if (lflag >= 2) \
__v = va_arg (ap, unsigned long long); \
else if (lflag) \
__v = va_arg (ap, unsigned long); \
else \
__v = va_arg (ap, unsigned int); \
__v; \
})
// Same as getuint but signed - can't use getuint
// because of sign extension
#define getint(ap, lflag) \
({ \
long long __v; \
if (lflag >= 2) \
__v = va_arg (ap, long long); \
else if (lflag) \
__v = va_arg (ap, long); \
else \
__v = va_arg (ap, int); \
__v; \
})
void
vprintfmt(void (*putch)(int, void*), void *putdat,
const char *fmt, va_list ap)
{
register const char *p;
register int ch;
unsigned long long num;
int base, lflag, width, precision, altflag;
char padc;
bool upper;
while (1) {
while ((ch = *(unsigned char *) fmt++) != '%') {
if (ch == '\0')
return;
putch(ch, putdat);
}
// Process a %-escape sequence
padc = ' ';
width = -1;
precision = -1;
lflag = 0;
altflag = 0;
upper = false;
reswitch:
switch (ch = *(unsigned char *) fmt++) {
// flag to pad on the right
case '-':
padc = '-';
goto reswitch;
// flag to pad with 0's instead of spaces
case '0':
padc = '0';
goto reswitch;
// width field
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
for (precision = 0;; ++fmt) {
precision = precision * 10 + ch - '0';
ch = *fmt;
if (ch < '0' || ch > '9')
break;
}
goto process_precision;
case '*':
precision = va_arg (ap, int);
goto process_precision;
case '.':
if (width < 0)
width = 0;
goto reswitch;
case '#':
altflag = 1;
goto reswitch;
process_precision:
if (width < 0)
width = precision, precision = -1;
goto reswitch;
// long flag (doubled for long long)
case 'l':
lflag++;
goto reswitch;
// size_t
case 'z':
if (sizeof(size_t) == sizeof(long))
lflag = 1;
else if (sizeof(size_t) == sizeof(long long))
lflag = 2;
else
lflag = 0;
goto reswitch;
// character
case 'c':
putch (va_arg (ap, int), putdat);
break;
// string
case 's':
if ((p = va_arg (ap, char *)) == nullptr)
p = "(null)";
if (width > 0 && padc != '-')
for (width -= strlen (p); width > 0; width--)
putch (padc, putdat);
for (; (ch = *p++) != '\0' && (precision < 0 || --precision >= 0);
width--)
if (altflag && (ch < ' ' || ch > '~'))
putch ('?', putdat);
else
putch (ch, putdat);
for (; width > 0; width--)
putch (' ', putdat);
break;
// binary
case 'b':
num = getint (ap, lflag);
base = 2;
goto number;
// (signed) decimal
case 'd':
num = getint (ap, lflag);
if ((long long) num < 0) {
putch ('-', putdat);
num = -(long long) num;
}
base = 10;
goto number;
// unsigned decimal
case 'u':
num = getuint (ap, lflag);
base = 10;
goto number;
// (unsigned) octal
case 'o':
num = getuint (ap, lflag);
base = 8;
if (altflag && num)
putch ('0', putdat);
goto number;
// pointer
case 'p':
putch ('0', putdat);
putch ('x', putdat);
num = (unsigned long long)
(uptr) va_arg (ap, void *);
base = 16;
goto number;
// (unsigned) hexadecimal
case 'X':
upper = true;
case 'x':
num = getuint (ap, lflag);
base = 16;
if (altflag && num) {
putch ('0', putdat);
putch ('x', putdat);
}
number:
printnum (putch, putdat, num, base, MAX(width, 0), padc, upper);
break;
#ifndef XV6_KERNEL
case 'f': {
double dnum;
if (precision == -1)
precision = 6;
dnum = va_arg (ap, double);
if (dnum < 0) {
putch ('-', putdat);
dnum = -dnum;
}
printnum (putch, putdat, (unsigned long long)dnum, 10, 0, padc, false);
if (precision) {
putch('.', putdat);
dnum -= (unsigned long long)dnum;
while (--precision) {
dnum *= 10;
putch("0123456789"[(unsigned)dnum], putdat);
dnum -= (unsigned)dnum;
}
}
break;
}
#endif
// unrecognized escape sequence - just print it literally
default:
putch ('%', putdat);
while (lflag-- > 0)
putch ('l', putdat);
/* FALLTHROUGH */
// escaped '%' character
case '%':
putch (ch, putdat);
}
}
}
<|start_filename|>net/arch/cc.h<|end_filename|>
#ifndef LWIP_ARCH_CC_H
#define LWIP_ARCH_CC_H
#include "types.h"
void lwip_cprintf(const char*, ...) __attribute__((format(printf, 1, 2)));
void lwip_panic(const char*, ...) __noret__ __attribute__((format(printf, 1, 2)));
typedef u32 u32_t;
typedef s32 s32_t;
typedef u64 u64_t;
typedef s64 s64_t;
typedef u16 u16_t;
typedef s16 s16_t;
typedef u8 u8_t;
typedef s8 s8_t;
typedef uptr mem_ptr_t;
#define PACK_STRUCT_FIELD(x) x
#define PACK_STRUCT_STRUCT __attribute__((packed))
#define PACK_STRUCT_BEGIN
#define PACK_STRUCT_END
#define S16_F "d"
#define U16_F "u"
#define X16_F "x"
#define S32_F "d"
#define U32_F "u"
#define X32_F "x"
#define LWIP_PLATFORM_DIAG(x) lwip_cprintf x
#define LWIP_PLATFORM_ASSERT(x) lwip_panic(x)
#ifndef BYTE_ORDER
#define BYTE_ORDER LITTLE_ENDIAN
#endif
// We define our own htonx so we can use them in userspace without
// compiling any lwIP .cc files (otherwise we must compile core/def.c).
#define LWIP_PLATFORM_BYTESWAP 1
static inline u16_t
LWIP_PLATFORM_HTONS(u16_t n)
{
return ((n & 0xff) << 8) | ((n & 0xff00) >> 8);
}
static inline u32_t
LWIP_PLATFORM_HTONL(u32_t n)
{
return ((n & 0xff) << 24) |
((n & 0xff00) << 8) |
((n & 0xff0000UL) >> 8) |
((n & 0xff000000UL) >> 24);
}
#endif
<|start_filename|>lib/umalloc.cc<|end_filename|>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#ifndef XV6_USER
#include <linux/unistd.h> // __NR_gettid
#endif
#include <memory>
#include <new>
#include <utility>
#include "bit_spinlock.hh"
#include "radix_array.hh"
#include "log2.hh"
// This allocator strongly weighs its own scalability over other forms
// of efficiency. In particular, when memory is freed via a given
// thread, only that thread can then reuse that memory. Also, after a
// page is carved up in to sub-page regions, it can never be used for
// any other size class (allocations that involve a page or more of
// memory can be re-partitioned, however). It also never returns
// memory to the system.
// == Overall architecture ==
//
// Throughout this allocator, it uses "size classes", which are simply
// the ceil(log2(bytes)) of an allocation. That is, each allocation
// gets rounded up to the nearest power of two.
//
// The allocator has three levels:
//
// A *linear allocator* allocates memory linearly from per-core pools
// that area allocated min_map_bytes at a time. This allocator never
// reuses memory. This is used exclusively to allocate nodes for the
// large allocator's radix array.
//
// A *large allocator* allocates memory for objects whose size class
// is larger than half-a-page (where only one object will fit on a
// page). It maintains per-core per-size-class free lists. Each free
// region starts on a page boundary and is an exact multiple of the
// page size. The allocator finds the smallest sufficient size class
// with a free region and returns that. However, if an allocated
// object is smaller than its size class, the allocator will release
// unused pages at the end of the allocated region (splitting the page
// run in to smaller size-class-sized regions), so allocated regions
// are never more than (PGSIZE-1) bytes larger than the requested
// size, even though size classes are exponential.
//
// To free pages, the large allocator maintains a radix array of
// metadata, indexed by page. For each allocated region, this marks
// it as allocated. For each free region, this marks which thread has
// the region on its free list. In both cases, it marks the head and
// the rest of the region differently so regions can be identified.
// When an object is freed to the large allocator, its size is
// computed using the radix array and it is merged with adjacent free
// pages that belong to the same thread (also using the radix array).
// This could result in an arbitrary size region, so it is split in to
// the largest size classes possible.
//
// Finally, a *small allocator* handles allocations for size classes
// half-a-page and smaller (where multiple objects will fit on one
// page). Like the large allocation, this allocator maintains
// per-core per-size-class free lists; however, the small allocator
// does no splitting or merging. If the free list for an allocation
// is empty, it obtains a page from the large allocator, carves it up
// in to equal size regions, and stores the size class at the
// beginning of the page. As a result, there is no per-object space
// overhead; only per-page overhead. Freeing an object simply checks
// the page header to find the object's size class and adds it to the
// appropriate free list.
//
// malloc determines whether to use the large allocator or the small
// allocator based on the requested object size. free determines
// which allocator to free back to using the pointer's alignment: if
// it is page-aligned it must have come from the large allocator;
// otherwise it must have come from the small allocator.
// Uncomment to enable additional debugging.
//#define UMALLOC_DEBUG
// Uncomment to enable debug prints.
//#define pdebug printf
#define pdebug if (0) printf
// If non-zero, enable merging of adjacent page-and-up free ranges.
// If there seems to be a bug, disabling this is the place to start.
enum { DO_MERGE = 1 };
namespace {
enum { PGSIZE = 4096 };
// Must be >= 4096 and a valid size class
size_t min_map_bytes = 256 * 1024;
pid_t gettid()
{
#if defined(XV6_USER)
return getpid();
#else
return syscall(__NR_gettid);
#endif
}
// Assert that ptr looks like a valid pointer.
void check_ptr(void *ptr)
{
assert(ptr < (void*)0x800000000000);
}
//
// Block lists
//
class block_list
{
public:
struct block
{
struct block *next, **pprev;
#ifdef UMALLOC_DEBUG
size_t size_class;
#endif
};
private:
block *head;
// Blarg. If I delete these, GCC fails on any thread-local
// variables with "X is thread-local and so cannot be dynamically
// initialized". So hide them the old-fashioned way.
block_list(const block_list&) = default;
block_list(block_list&&) = default;
block_list &operator=(const block_list &) = delete;
block_list &operator=(block_list &&) = delete;
public:
// NOTE: block_list is used in __thread globals, which means it
// must have a default constructor. Since this is the *only*
// place it's used, the global will take care of zeroing head.
block_list() = default;
~block_list() = default;
operator bool() const
{
return !!head;
}
// Add ptr to this block list. size_class is used only for
// debugging.
void push(void *ptr, size_t size_class)
{
block *b = static_cast<block*>(ptr);
b->pprev = &head;
b->next = head;
#ifdef UMALLOC_DEBUG
if (size_class >= 12)
assert((uintptr_t)ptr % PGSIZE == 0);
b->size_class = size_class;
if (head)
assert(size_class == head->size_class);
#endif
if (head)
head->pprev = &b->next;
head = b;
check_ptr(head);
}
// Pop a block from this list. size_class is used only for
// debugging.
void *pop(size_t size_class)
{
assert(head);
block *b = head;
#ifdef UMALLOC_DEBUG
assert(b->size_class == size_class);
#endif
check_ptr(head->next);
assert(head->pprev == &head);
head = head->next;
if (head) {
#ifdef UMALLOC_DEBUG
assert(head->size_class == size_class);
#endif
head->pprev = &head;
}
return b;
}
// Remove ptr from whatever block list it's on.
static void remove(void *ptr)
{
block *b = static_cast<block*>(ptr);
check_ptr(b->next);
if (b->next) {
assert(b->next->pprev == &b->next);
b->next->pprev = b->pprev;
}
*b->pprev = b->next;
}
};
//
// Size classes
//
// XXX This has an internal fragmentation of 100%. We could easily
// get it down to 50% by using the top *two* most significant bits,
// for example. OTOH, the large allocator only rounds up to PGSIZE,
// so this would only really matter for small allocations.
// At this many bytes, the size class will be one page large
enum { LARGE_THRESHOLD = 2049 };
// Compute the size class of a byte size.
size_t size_to_class(size_t bytes)
{
return ceil_log2(bytes);
}
// Return the maximum number of bytes that can be stored in an
// object with the given size class.
size_t class_max_size(size_t sc)
{
return 1ull << sc;
}
// Return the largest size class that would fit in bytes.
size_t size_fit_class(size_t bytes)
{
return floor_log2(bytes);
}
//
// Linear allocator (used for pages radix array)
//
__thread char *linear_pos, *linear_end;
template<typename T>
class linear_allocator
{
public:
typedef std::size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template <class U> struct rebind { typedef linear_allocator<U> other; };
linear_allocator() = default;
linear_allocator(const linear_allocator&) = default;
template<class U> linear_allocator(const linear_allocator<U>&) noexcept { }
pointer address(reference x) const noexcept
{
return std::addressof(x);
}
const_pointer address(const_reference x) const noexcept
{
return std::addressof(x);
}
template<class U, class... Args>
void construct(U* p, Args&&... args)
{
::new((void *)p) U(std::forward<Args>(args)...);
}
template <class U>
void destroy(U* p)
{
p->~U();
}
T* allocate(std::size_t n, const void *hint = 0)
{
size_t bytes = n * sizeof(T);
if (!linear_pos || linear_end - linear_pos < bytes) {
// Get more memory
void *p = mmap(0, min_map_bytes, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED)
throw std::bad_alloc();
linear_pos = (char*)p;
linear_end = linear_pos + min_map_bytes;
}
T *p = static_cast<T*>(static_cast<void*>(linear_pos));
linear_pos += bytes;
return p;
}
void deallocate(T* p, std::size_t n)
{
}
std::size_t max_size() const noexcept
{
return min_map_bytes;
}
// ZAllocator interface
T* default_allocate()
{
static_assert(std::has_trivial_default_constructor<T>::value,
"T does not have a trivial default constructor");
return allocate(1);
}
};
//
// Large allocator (size classes one page large and up)
//
enum { MAX_LARGE_CLASS = 48 };
enum
{
UNMAPPED = 0,
ALLOCATED_HEAD = 1,
ALLOCATED_REST = -1
};
struct page_info
{
// * For unmapped pages, UNMAPPED.
// * For the first page of a free run, the thread ID that owns the
// run.
// * For the non-first page of a free run, the negative thread ID
// that owns the run.
// * For allocated pages, the first page of the allocation is
// ALLOCATED_HEAD and the rest are ALLOCATED_REST.
pid_t owner;
// XXX The information about free pages could be written on the
// pages themselves, rather than requiring lots of space in a
// radix tree. There could be races with checking the data, so
// we'd have to double-check the radix state. But that would
// reduce this to two bits per page, which could be packed much
// more efficiently (we could even use a straight 16GB mapping).
page_info() = default;
explicit page_info(pid_t owner) : owner(owner) { }
dummy_bit_spinlock get_lock()
{
return dummy_bit_spinlock();
}
bool is_set() const
{
return owner != 0;
}
};
// Page free lists indexed by size class. The smaller size classes
// are unused.
__thread block_list free_runs[MAX_LARGE_CLASS];
// Page info radix array. The +1 on the size is a lame way to avoid
// having to constantly check our iterators against pages.end().
radix_array<page_info, (1ULL<<47)/PGSIZE + 1, 4096,
linear_allocator<page_info> > pages;
// Convert page pointer to pages index
size_t idx(void *ptr)
{
uintptr_t x = reinterpret_cast<uintptr_t>(ptr);
assert(x % PGSIZE == 0);
return x / PGSIZE;
}
// Convert pages index to page pointer
void *idx_to_ptr(size_t idx)
{
return reinterpret_cast<void*>(idx * PGSIZE);
}
// Add a free run of size bytes starting at run. The run must not
// be on any free list or contained within any run on any free list.
void add_free_run(void *run, size_t bytes)
{
assert(bytes >= PGSIZE);
assert(bytes % PGSIZE == 0);
pid_t tid = gettid();
void *end = (char*)run + bytes;
auto it = pages.find(idx(run));
// Divide the run up in to size-class-sized pieces
while (run < end) {
size_t fsc = size_fit_class((char*)end - (char*)run);
size_t fbytes = class_max_size(fsc);
pdebug("adding free run %p class %zu\n", run, fsc);
free_runs[fsc].push(run, fsc);
auto nextit = it + fbytes / PGSIZE;
// Mark pages as free to this thread
pages.fill(it++, page_info(tid));
if (it != nextit) {
pages.fill(it, nextit, page_info(-tid));
it = nextit;
}
run = (char*)run + fbytes;
assert((uintptr_t)run % PGSIZE == 0);
assert(idx(run) == it.index());
}
}
// Allocate bytes from run, which is of size class sc. run must not
// be on any free list.
void *alloc_from_run(void *run, size_t sc, size_t bytes)
{
pdebug("alloc_large %zu bytes from run %zu => %p\n", bytes, sc, run);
// If we only used part of run, put the rest back on a free list
size_t used_pages = (bytes + PGSIZE - 1) / PGSIZE;
size_t have_pages = class_max_size(sc) / PGSIZE;
assert(class_max_size(sc) % PGSIZE == 0);
assert(have_pages >= used_pages);
if (have_pages > used_pages) {
// It's possible we could merge this in to following runs to
// create larger runs, but we don't bother
add_free_run((char*)run + used_pages * PGSIZE,
(have_pages - used_pages) * PGSIZE);
}
// Mark pages allocated
auto start = pages.find(idx(run));
pages.fill(start, page_info(ALLOCATED_HEAD));
if (used_pages > 1)
pages.fill(start + 1, start + used_pages, page_info(ALLOCATED_REST));
return run;
}
// Allocate bytes bytes from the large allocator.
void *alloc_large(size_t bytes)
{
assert(bytes >= LARGE_THRESHOLD);
size_t sc = size_to_class(bytes);
// Find a free run of at least this size class
for (size_t i = sc; i < MAX_LARGE_CLASS; ++i)
if (free_runs[i])
return alloc_from_run(free_runs[i].pop(i), i, bytes);
// Can't satisfy request. Get more pages from the system.
size_t map_bytes = class_max_size(sc);
size_t map_sc = sc;
if (map_bytes < min_map_bytes) {
map_bytes = min_map_bytes;
map_sc = size_to_class(map_bytes);
assert(class_max_size(map_sc) == map_bytes);
}
void *run = mmap(0, map_bytes, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
if (run == MAP_FAILED)
return nullptr;
pdebug("alloc_large mapped %p for class %zu\n", run, map_sc);
// Allocate from the new run
return alloc_from_run(run, map_sc, bytes);
}
// Free the memory at ptr to the large allocator.
void free_large(void *ptr)
{
pid_t tid = gettid();
// Find length of run at start
auto start = pages.find(idx(ptr));
if (!start.is_set())
throw std::runtime_error("Free of non-mapped memory");
if (start->owner != ALLOCATED_HEAD) {
if (start->owner == ALLOCATED_REST)
throw std::runtime_error("Free in the middle of a block");
else
throw std::runtime_error("Double free");
}
auto end = start;
for (++end; end.is_set() && end->owner == ALLOCATED_REST; ++end)
;
// Find preceding runs to merge and remove the from free lists
auto pre = start;
if (DO_MERGE) {
for (--pre; pre.is_set(); --pre) {
if (pre->owner == tid) {
// This is the beginning of a run we can merge with
block_list::remove(idx_to_ptr(pre.index()));
} else if (pre->owner != -tid) {
// We can't merge with this
break;
}
}
++pre;
}
// Find following runs to merge and remove the from free lists
auto post = end;
if (DO_MERGE) {
for (; post.is_set(); ++post) {
if (post->owner == tid) {
block_list::remove(idx_to_ptr(post.index()));
} else if (post->owner != -tid) {
break;
}
}
}
// Add (possibly expanded) run to free list
// XXX Because we add the largest size class first when adding a
// run, this may re-create lots of runs we just absorbed. There
// should be a way to avoid this.
pdebug("free_large %p of %lu pages (expanded %p %lu pages)\n",
ptr, end - start, idx_to_ptr(pre.index()), post - pre);
add_free_run(idx_to_ptr(pre.index()), (post - pre) * PGSIZE);
}
// Get the allocated size of the large allocation at ptr.
size_t get_size_large(void *ptr)
{
// XXX Deduplicate with code in free
auto start = pages.find(idx(ptr));
auto end = start;
for (++end; end.is_set() && end->owner == ALLOCATED_REST; ++end)
;
return (end - start) * PGSIZE;
}
//
// Small allocator (size classes less than a page)
//
// XXX This never frees pages back to the large allocator, so once a
// page has been reserved for a size class, it will stay that size
// class forever.
// Fragment free lists by size class (ceil(log2(bytes))). Fragments
// must be at least sizeof(block_list::block), so the smaller
// classes are unused.
__thread block_list free_fragments[13];
// Header for pages owned by the small allocator. Following this
// header, a page is divided into equal-size fragments.
struct page_hdr
{
uintptr_t magic;
size_t size_class;
};
enum { PAGE_HDR_MAGIC = 0x2065c977e3516564 };
// Allocate bytes bytes from the small allocator
void *alloc_small(size_t bytes)
{
assert(bytes < LARGE_THRESHOLD);
// Fragments must be at least as big as block_list::block.
if (bytes < sizeof(block_list::block))
bytes = sizeof(block_list::block);
// Check for a free fragment
size_t sc = size_to_class(bytes);
if (!free_fragments[sc]) {
// There are no free fragments of this size. Get a page from
// the large allocator and chop it up.
void *page = alloc_large(PGSIZE);
if (!page)
return nullptr;
page_hdr *hdr = static_cast<page_hdr*>(page);
hdr->magic = PAGE_HDR_MAGIC;
hdr->size_class = sc;
size_t sbytes = class_max_size(sc);
// Make sure fragments are always 16-byte aligned. (This could
// be less aligned for smaller size classes, but there are no
// smaller size classes.)
char *fragment = (char*)page + 16;
assert(sizeof(page_hdr) <= 16);
char *last = (char*)page + PGSIZE - sbytes;
int i = 0;
for (; fragment <= last; fragment += sbytes, ++i)
free_fragments[sc].push(fragment, sc);
pdebug("alloc_small growing class %zu by %d objects\n", sc, i);
}
void *ptr = free_fragments[sc].pop(sc);
pdebug("alloc_small %zu bytes from class %zu => %p\n", bytes, sc, ptr);
return ptr;
}
// Free the memory at ptr to the small allocator.
void free_small(void *ptr)
{
// Round ptr to the page start to get the page metadata
page_hdr *hdr = (page_hdr*)(((uintptr_t)ptr) & ~(PGSIZE-1));
if (hdr->magic != PAGE_HDR_MAGIC)
throw std::runtime_error("Bad free or corrupted page magic");
pdebug("free_small %p to class %zu\n", ptr, hdr->size_class);
free_fragments[hdr->size_class].push(ptr, hdr->size_class);
}
// Get the allocated size of the small allocation at ptr.
size_t get_size_small(void *ptr)
{
page_hdr *hdr = (page_hdr*)(((uintptr_t)ptr) & ~(PGSIZE-1));
if (hdr->magic != PAGE_HDR_MAGIC)
throw std::runtime_error("Bad free or corrupted page magic");
return class_max_size(hdr->size_class);
}
}
extern "C" void *
malloc(size_t size)
{
if (size < LARGE_THRESHOLD)
return alloc_small(size);
return alloc_large(size);
}
extern "C" void
free(void *ptr)
{
if (!ptr)
return;
uintptr_t x = reinterpret_cast<uintptr_t>(ptr);
if (x % PGSIZE == 0) {
// This memory came from the large allocator
free_large(ptr);
} else {
// This memory came from the small allocator
free_small(ptr);
}
}
extern "C" void*
calloc(size_t a, size_t b)
{
size_t n = a * b;
if (n / a != b)
return 0;
void* p = malloc(n);
if (p)
memset(p, 0, n);
return p;
}
extern "C" void*
realloc(void* ap, size_t nbytes)
{
// XXX If this is a large allocation, we might be able to take over
// the following pages directly.
size_t cur_size;
uintptr_t x = reinterpret_cast<uintptr_t>(ap);
if (x % PGSIZE == 0) {
cur_size = get_size_large(ap);
} else {
cur_size = get_size_small(ap);
}
if (nbytes <= cur_size)
return ap;
void *n = malloc(nbytes);
if (!n)
return nullptr;
if (ap) {
memcpy(n, ap, cur_size);
free(ap);
}
return n;
}
extern "C" void
malloc_set_alloc_unit(size_t bytes)
{
if (bytes < 4096)
bytes = 4096;
min_map_bytes = class_max_size(size_to_class(bytes));
}
extern "C" void
malloc_show_state()
{
auto it = pages.begin(), end = pages.end();
while (it < end) {
if (!it.is_set()) {
it += it.base_span();
continue;
}
auto it2 = it;
while (it2.is_set() && it2->owner == it->owner)
it2 += it2.base_span();
printf("%p-%p %d\n", idx_to_ptr(it.index()),
(char*)idx_to_ptr(it2.index())-1,
it->owner);
it = it2;
}
}
<|start_filename|>kernel/cmdline.cc<|end_filename|>
#include "types.h"
#include "kernel.hh"
#include "mmu.h"
#include "amd64.h"
#include "spinlock.hh"
#include "condvar.hh"
#include "fs.h"
#include "file.hh"
#include "major.h"
extern char cmdline[];
static int
cmdlineread(mdev*, char *dst, u32 off, u32 n)
{
u32 cc;
if (off >= strlen(cmdline))
return 0;
cc = MIN(n, strlen(cmdline)-off);
memcpy(dst, &cmdline[off], cc);
return cc;
}
void
initcmdline(void)
{
if (VERBOSE)
cprintf("cmdline: %s\n", cmdline);
devsw[MAJ_CMDLINE].pread = cmdlineread;
}
<|start_filename|>include/mfs.hh<|end_filename|>
#pragma once
#include "mnode.hh"
extern u64 root_inum;
extern mfs* root_fs;
extern mfs* anon_fs;
sref<mnode> namei(sref<mnode> cwd, const char* path);
sref<mnode> nameiparent(sref<mnode> cwd, const char* path, strbuf<DIRSIZ>* buf);
s64 readi(sref<mnode> m, char* buf, u64 start, u64 nbytes);
s64 writei(sref<mnode> m, const char* buf, u64 start, u64 nbytes,
mfile::resizer* resize = nullptr);
class print_stream;
void mfsprint(print_stream *s);
<|start_filename|>kernel/hwvm.cc<|end_filename|>
#include "types.h"
#include "amd64.h"
#include "mmu.h"
#include "cpu.hh"
#include "kernel.hh"
#include "bits.hh"
#include "spinlock.hh"
#include "kalloc.hh"
#include "condvar.hh"
#include "proc.hh"
#include "vm.hh"
#include "apic.hh"
#include "kstream.hh"
#include "ipi.hh"
#include "kstats.hh"
#include "cpuid.hh"
#include "vmalloc.hh"
using namespace std;
// Ensure tlbflush_req lives on a cache line by itself since we hit
// this from all cores in batched_shootdown mode.
static atomic<u64> tlbflush_req __mpalign__;
static __padout__ __attribute__((used));
DEFINE_PERCPU(const MMU_SCHEME::page_map_cache*, cur_page_map_cache);
static const char *levelnames[] = {
"PT", "PD", "PDP", "PML4"
};
// One level in an x86-64 page table, typically the top level. Many
// of the methods of pgmap assume they are being invoked on a
// top-level PML4.
struct pgmap {
enum {
// Page table levels
L_PT = 0,
L_PD = 1,
L_PDPT = 2,
L_PML4 = 3,
// By the size of an entry on that level
L_4K = L_PT,
L_2M = L_PD,
L_1G = L_PDPT,
L_512G = L_PML4,
// Semantic names
L_PGSIZE = L_4K,
};
private:
std::atomic<pme_t> e[PGSIZE / sizeof(pme_t)];
void free(int level, int end = 512, bool release = true)
{
if (level != 0) {
for (int i = 0; i < end; i++) {
pme_t entry = e[i].load(memory_order_relaxed);
if (entry & PTE_P)
((pgmap*) p2v(PTE_ADDR(entry)))->free(level - 1);
}
}
if (release)
kfree(this);
}
u64 internal_pages(int level, int end = 512) const
{
u64 count = 1;
if (level != 0) {
for (int i = 0; i < end; i++) {
pme_t entry = e[i].load(memory_order_relaxed);
if (entry & PTE_P)
count += ((pgmap*) p2v(PTE_ADDR(entry)))->internal_pages(level - 1);
}
}
return count;
}
public:
~pgmap()
{
// Don't free kernel portion of the pml4 and don't kfree this
// page, since operator delete will do that.
free(L_PML4, PX(L_PML4, KGLOBAL), false);
}
// Delete'ing a ::pgmap also frees all sub-pgmaps (except those
// shared with kpml4), but does not free any non-page structure
// pages pointed to by the page table. Note that there is no
// operator new; the only way to get a new ::pgmap is kclone().
static void operator delete(void *p)
{
kfree(p);
}
// Allocate and return a new pgmap the clones the kernel part of
// this pgmap.
pgmap *kclone() const
{
pgmap *pml4 = (pgmap*)kalloc("PML4");
if (!pml4)
throw_bad_alloc();
size_t k = PX(L_PML4, KGLOBAL);
memset(&pml4->e[0], 0, 8*k);
memmove(&pml4->e[k], &e[k], 8*(512-k));
return pml4;
}
// Make this page table active on this CPU.
void switch_to()
{
auto nreq = tlbflush_req.load();
u64 cr3 = v2p(this);
lcr3(cr3);
mycpu()->tlbflush_done = nreq;
mycpu()->tlb_cr3 = cr3;
}
u64 internal_pages() const
{
return internal_pages(L_PML4, PX(L_PML4, KGLOBAL));
}
// An iterator that references the page structure entry on a fixed
// level of the page structure tree for some virtual address.
// Moving the iterator changes the virtual address, but not the
// level.
class iterator
{
struct pgmap *pml4;
uintptr_t va;
// The target pgmap level of this iterator.
int level;
// The actual level resolve() was able to reach. If <tt>reached
// > level<tt> then @c cur will be null. If <tt>reached ==
// level</tt>, then @c cur will be non-null.
int reached;
// The pgmap containing @c va on level @c level. As long as the
// iterator moves within this pgmap, we don't have to re-walk the
// page structure tree.
struct pgmap *cur;
friend struct pgmap;
iterator(struct pgmap *pml4, uintptr_t va, int level)
: pml4(pml4), va(va), level(level)
{
resolve();
}
// Walk the page table structure to find @c va at @c level and set
// @c cur. If @c create is zero and the path to @c va does not
// exist, sets @c cur to nullptr. Otherwise, the path will be
// created with the flags @c create.
void resolve(pme_t create = 0)
{
cur = pml4;
for (reached = L_PML4; reached > level; reached--) {
atomic<pme_t> *entryp = &cur->e[PX(reached, va)];
pme_t entry = entryp->load(memory_order_relaxed);
retry:
if (entry & PTE_P) {
cur = (pgmap*) p2v(PTE_ADDR(entry));
} else if (!create) {
cur = nullptr;
break;
} else {
// XXX(Austin) Could use zalloc except during really early
// boot (really, zalloc shouldn't crash during early boot).
pgmap *next = (pgmap*) kalloc(levelnames[reached - 1]);
if (!next)
throw_bad_alloc();
memset(next, 0, sizeof *next);
if (!atomic_compare_exchange_weak(
entryp, &entry, v2p(next) | create)) {
// The above call updated entry with the current value in
// entryp, so retry after the entry load.
kfree(next);
goto retry;
}
cur = next;
}
}
}
public:
// Default constructor
constexpr iterator() : pml4(nullptr), va(0), level(0), reached(0),
cur(nullptr) { }
// Return the page structure level this iterator is traversing.
int get_level() const
{
return level;
}
// Return the pgmap containing the entry returned by operator*.
// exists() must be true.
pgmap *get_pgmap() const
{
return cur;
}
// Return the virtual address this iterator current points to.
uintptr_t index() const
{
return va;
}
// Return the "span" over which the entry this iterator refers to
// will remain the same. That is, if exists() is false, then it
// will be false for at least [index(), index()+span()).
// Otherwise, &*it will be the same for [index(), index()+span()).
uintptr_t span() const
{
// Calculate the beginning of the next entry on level 'reached'
uintptr_t next = (va | ((1ull << PXSHIFT(reached)) - 1)) + 1;
return next - va;
}
// Create this entry if it doesn't already exist. Any created
// directory entries will have flags <tt>flags|PTE_P|PTE_W</tt>.
// After this, exists() will be true (though is_set() will only be
// set if is_set() was already true).
iterator &create(pme_t flags)
{
if (!cur)
resolve(flags | PTE_P | PTE_W);
return *this;
}
// Return true if this entry can be retrieved and set. The entry
// itself might not be marked present.
bool exists() const
{
return cur;
}
// Return true if this entry both exists and is marked present.
bool is_set() const
{
return cur && ((*this)->load(memory_order_relaxed) & PTE_P);
}
// Return a reference to the current page structure entry. This
// operation is only legal if exists() is true.
atomic<pme_t> &operator*() const
{
return cur->e[PX(level, va)];
}
atomic<pme_t> *operator->() const
{
return &cur->e[PX(level, va)];
}
// Increment the iterator by @c x.
iterator &operator+=(uintptr_t x)
{
uintptr_t prev = va;
va += x;
if ((va >> PXSHIFT(level + 1)) != (prev >> PXSHIFT(level + 1))) {
// The bottom level changed. Re-resolve.
resolve();
}
return *this;
}
};
// Return an iterator pointing to @c va at page structure level @c
// level, where level 0 is the page table.
iterator find(uintptr_t va, int level = L_PGSIZE)
{
return iterator(this, va, level);
}
};
static_assert(sizeof(pgmap) == PGSIZE, "!(sizeof(pgmap) == PGSIZE)");
extern pgmap kpml4;
static atomic<uintptr_t> kvmallocpos;
// Create a direct mapping starting at PA 0 to VA KBASE up to
// KBASEEND. This augments the KCODE mapping created by the
// bootloader. Perform per-core control register set up.
void
initpg(void)
{
static bool kpml4_initialized;
if (!kpml4_initialized) {
kpml4_initialized = true;
int level = pgmap::L_2M;
pgmap::iterator it;
// Can we use 1GB mappings?
if (cpuid::features().page1GB) {
level = pgmap::L_1G;
// Redo KCODE mapping with a 1GB page
*kpml4.find(KCODE, level).create(0) = PTE_W | PTE_P | PTE_PS | PTE_G;
lcr3(rcr3());
}
// Create direct map region
for (auto it = kpml4.find(KBASE, level); it.index() < KBASEEND;
it += it.span()) {
paddr pa = it.index() - KBASE;
*it.create(0) = pa | PTE_W | PTE_P | PTE_PS | PTE_NX | PTE_G;
}
assert(!kpml4.find(KBASEEND, level).is_set());
// Create KVMALLOC area. This doesn't map anything at this point;
// it only fills in PML4 entries that can later be shared with all
// other page tables.
for (auto it = kpml4.find(KVMALLOC, pgmap::L_PDPT); it.index() < KVMALLOCEND;
it += it.span()) {
it.create(0);
assert(!it.is_set());
}
kvmallocpos = KVMALLOC;
}
// Enable global pages. This has to happen on every core.
lcr4(rcr4() | CR4_PGE);
}
// Clean up mappings that were only required during early boot.
void
cleanuppg(void)
{
// Remove 1GB identity mapping
*kpml4.find(0, pgmap::L_PML4) = 0;
lcr3(rcr3());
}
size_t
safe_read_hw(void *dst, uintptr_t src, size_t n)
{
scoped_cli cli;
struct mypgmap
{
pme_t e[PGSIZE / sizeof(pme_t)];
} *pml4 = (struct mypgmap*)p2v(rcr3());
for (size_t i = 0; i < n; ++i) {
uintptr_t va = src + i;
void *obj = pml4;
int level;
for (level = pgmap::L_PML4; ; level--) {
pme_t entry = ((mypgmap*)obj)->e[PX(level, va)];
if (!(entry & PTE_P))
return i;
obj = p2v(PTE_ADDR(entry));
if (level == 0 || (entry & PTE_PS))
break;
}
((char*)dst)[i] = ((char*)obj)[va % (1ull << PXSHIFT(level))];
}
return n;
}
// Switch TSS and h/w page table to correspond to process p.
void
switchvm(struct proc *p)
{
scoped_cli cli;
u64 base = (u64) &mycpu()->ts;
mycpu()->gdt[TSSSEG>>3] = (struct segdesc)
SEGDESC(base, (sizeof(mycpu()->ts)-1), SEG_P|SEG_TSS64A);
mycpu()->gdt[(TSSSEG>>3)+1] = (struct segdesc) SEGDESCHI(base);
mycpu()->ts.rsp[0] = (u64) myproc()->kstack + KSTACKSIZE;
mycpu()->ts.iomba = (u16)__offsetof(struct taskstate, iopb);
ltr(TSSSEG);
if (*cur_page_map_cache)
(*cur_page_map_cache)->switch_from();
// XXX(Austin) This puts the TLB tracking logic in pgmap, which is
// probably the wrong place.
if (p->vmap) {
p->vmap->cache.switch_to();
*cur_page_map_cache = &p->vmap->cache;
} else {
kpml4.switch_to();
*cur_page_map_cache = nullptr;
}
writefs(UDSEG);
writemsr(MSR_FS_BASE, p->user_fs_);
}
// Set up CPU's kernel segment descriptors.
// Run once at boot time on each CPU.
void
inittls(struct cpu *c)
{
// Initialize cpu-local storage.
writegs(KDSEG);
writemsr(MSR_GS_BASE, (u64)&c->cpu);
writemsr(MSR_GS_KERNBASE, (u64)&c->cpu);
c->cpu = c;
c->proc = nullptr;
}
// Allocate 'bytes' bytes in the KVMALLOC area, surrounded by at least
// 'guard' bytes of unmapped memory. This memory must be freed with
// vmalloc_free.
void *
vmalloc_raw(size_t bytes, size_t guard, const char *name)
{
if (kvmallocpos == 0)
panic("vmalloc called before initpg");
bytes = PGROUNDUP(bytes);
guard = PGROUNDUP(guard);
// Ensure there is always some guard space. vmalloc_free depends on
// this.
if (guard < PGSIZE)
guard = PGSIZE;
uintptr_t base = guard + kvmallocpos.fetch_add(bytes + guard * 2);
if (base + bytes + guard >= KVMALLOCEND)
// Egads, we ran out of KVMALLOC space?! Ideally, we would
// recycle KVMALLOC space and perform a TLB shootdown, but other
// things will surely break long before this does.
panic("vmalloc: out of KVMALLOC space (recycling not implemented)");
for (auto it = kpml4.find(base); it.index() < base + bytes; it += it.span()) {
void *page = kalloc(name);
if (!page)
throw_bad_alloc();
*it.create(0) = v2p(page) | PTE_P | PTE_W | PTE_G;
}
mtlabel(mtrace_label_heap, (void*)base, bytes, name, strlen(name));
return (void*)base;
}
// Free vmalloc'd memory at ptr. Note that this *lazily* unmaps this
// area from KVMALLOC space, so this area may remain effectively
// mapped until some indeterminate point in the future.
void
vmalloc_free(void *ptr)
{
if ((uintptr_t)ptr % PGSIZE)
panic("vmalloc_free: ptr %p is not page-aligned", ptr);
if ((uintptr_t)ptr < KVMALLOC || (uintptr_t)ptr >= KVMALLOCEND)
panic("vmalloc_free: ptr %p is not in KVMALLOC space", ptr);
// Free and unmap until we reach the guard space.
for (auto it = kpml4.find((uintptr_t)ptr); it.is_set(); it += it.span()) {
kfree(p2v(PTE_ADDR(*it)));
*it = 0;
}
mtunlabel(mtrace_label_heap, ptr);
// XXX Should release unused page table pages. This requires a
// global TLB shootdown, so we should only do it in large-ish
// batches.
}
void
batched_shootdown::perform() const
{
if (!need_shootdown)
return;
u64 myreq = ++tlbflush_req;
u64 cr3 = rcr3();
// the caller may not hold any spinlock, because other CPUs might
// be spinning waiting for that spinlock, with interrupts disabled,
// so we will deadlock waiting for their TLB flush..
assert(mycpu()->ncli == 0);
kstats::inc(&kstats::tlb_shootdown_count);
kstats::timer timer(&kstats::tlb_shootdown_cycles);
for (int i = 0; i < ncpu; i++) {
if (cpus[i].tlb_cr3 == cr3 && cpus[i].tlbflush_done < myreq) {
lapic->send_tlbflush(&cpus[i]);
kstats::inc(&kstats::tlb_shootdown_targets);
}
}
for (int i = 0; i < ncpu; i++)
while (cpus[i].tlb_cr3 == cr3 && cpus[i].tlbflush_done < myreq)
/* spin */ ;
}
void
batched_shootdown::on_ipi()
{
pushcli();
u64 nreq = tlbflush_req.load();
lcr3(rcr3());
mycpu()->tlbflush_done = nreq;
popcli();
}
void
core_tracking_shootdown::cache_tracker::track_switch_to() const
{
active_cores.atomic_set(myid());
// Ensure that reads from the cache cannot move up before the tracker
// update, and that the tracker update does not move down after the
// cache reads.
std::atomic_thread_fence(std::memory_order_acq_rel);
}
void
core_tracking_shootdown::cache_tracker::track_switch_from() const
{
active_cores.atomic_reset(myid());
// No need for a fence; worst case, we just get an extra shootdown.
}
void
core_tracking_shootdown::clear_tlb() const
{
if (end_ > start_ && end_ - start_ > 4 * PGSIZE) {
lcr3(rcr3());
} else {
for (uintptr_t va = start_; va < end_; va += PGSIZE)
invlpg((void*) va);
}
}
void
core_tracking_shootdown::perform() const
{
if (!t_ || start_ >= end_)
return;
// Ensure that cache invalidations happen before reading the tracker;
// see also cache_tracker::track_switch_to().
std::atomic_thread_fence(std::memory_order_acq_rel);
bitset<NCPU> targets = t_->active_cores;
{
scoped_cli cli;
if (targets[myid()]) {
clear_tlb();
targets.reset(myid());
}
}
if (targets.count() == 0)
return;
kstats::inc(&kstats::tlb_shootdown_count);
kstats::inc(&kstats::tlb_shootdown_targets, targets.count());
kstats::timer timer(&kstats::tlb_shootdown_cycles);
run_on_cpus(targets, [this]() { clear_tlb(); });
}
namespace mmu_shared_page_table {
page_map_cache::page_map_cache() : pml4(kpml4.kclone())
{
if (!pml4) {
swarn.println("setupkvm out of memory\n");
throw_bad_alloc();
}
}
page_map_cache::~page_map_cache()
{
delete pml4;
}
void
page_map_cache::__insert(uintptr_t va, pme_t pte)
{
pml4->find(va).create(PTE_U)->store(pte, memory_order_relaxed);
}
void
page_map_cache::__invalidate(
uintptr_t start, uintptr_t len, shootdown *sd)
{
sd->set_cache_tracker(this);
for (auto it = pml4->find(start); it.index() < start + len;
it += it.span()) {
if (it.is_set()) {
it->store(0, memory_order_relaxed);
sd->add_range(it.index(), it.index() + it.span());
}
}
}
void
page_map_cache::switch_to() const
{
track_switch_to();
pml4->switch_to();
}
u64
page_map_cache::internal_pages() const
{
return pml4->internal_pages();
}
}
namespace mmu_per_core_page_table {
page_map_cache::~page_map_cache()
{
for (size_t i = 0; i < ncpu; ++i) {
delete pml4[i];
}
}
void
page_map_cache::insert(uintptr_t va, page_tracker *t, pme_t pte)
{
scoped_cli cli;
auto mypml4 = *pml4;
assert(mypml4);
mypml4->find(va).create(PTE_U)->store(pte, memory_order_relaxed);
t->tracker_cores.set(myid());
}
void
page_map_cache::switch_to() const
{
auto &mypml4 = *pml4;
if (!mypml4)
mypml4 = kpml4.kclone();
mypml4->switch_to();
}
u64
page_map_cache::internal_pages() const
{
u64 count = 0;
for (int i = 0; i < ncpu; i++) {
pgmap* pm = pml4[i];
if (!pm)
continue;
count += pm->internal_pages();
}
return count;
}
void
page_map_cache::clear(uintptr_t start, uintptr_t end)
{
// Are we the current page_map_cache on this core? (Depending on
// MMU_SCHEME, *cur_page_map_cache may not be this type of
// page_map_cache, but if it isn't, we'll never take this code
// path.)
bool current =
(reinterpret_cast<const page_map_cache*>(*cur_page_map_cache) == this);
pgmap *mypml4 = *pml4;
// If we're clearing this CPU's page map cache, then we must have
// inserted something into it previously. (Note that this may
// not hold if we start tracking shootdowns conservatively.)
assert(mypml4);
for (auto it = mypml4->find(start); it.index() < end; it += it.span()) {
if (it.is_set()) {
it->store(0, memory_order_relaxed);
if (current)
invlpg((void*)it.index());
}
}
}
void
shootdown::perform() const
{
// XXX Alternatively, we could reach into the per-core page tables
// directly from invalidate. Then it would be able to zero them
// directly and gather PTE_P bits (instead of using a separate
// tracker), but it would probably require more communication.
if (targets.none())
return;
assert(start < end && end <= USERTOP);
kstats::inc(&kstats::tlb_shootdown_count);
kstats::inc(&kstats::tlb_shootdown_targets, targets.count());
kstats::timer timer(&kstats::tlb_shootdown_cycles);
run_on_cpus(targets, [this]() {
cache->clear(start, end);
});
}
}
<|start_filename|>lib/rand.cc<|end_filename|>
#include <stdlib.h>
#include "amd64.h"
void
srand(unsigned int seed)
{
}
int
rand(void)
{
return rdtsc();
}
<|start_filename|>stdinc/inttypes.h<|end_filename|>
#pragma once
#include <stdint.h>
// In freestanding mode, we don't get __WORDSIZE. This is how
// bits/wordsize.h figures it out.
#ifndef __WORDSIZE
# if defined __x86_64__ && !defined __ILP32__
# define __WORDSIZE 64
# else
# define __WORDSIZE 32
# endif
#endif
#if __WORDSIZE == 64
# define __PRI64_PREFIX "l"
# define __PRIPTR_PREFIX "l"
#elif __WORDSIZE == 32
# define __PRI64_PREFIX "ll"
# define __PRIPTR_PREFIX
#else
# error Unexpected __WORDSIZE
#endif
#define PRIu32 "u"
#define PRIu64 __PRI64_PREFIX "u"
#define PRId32 "d"
#define PRId64 __PRI64_PREFIX "d"
<|start_filename|>bin/mailfilter.cc<|end_filename|>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "libutil.h"
#include "amd64.h"
#include "xsys.h"
#include "spam.h"
// To build on Linux:
// make HW=linux
int
main (int argc, char *argv[])
{
int r = isLegit();
exit(r);
}
<|start_filename|>include/sperf.hh<|end_filename|>
#pragma once
#include "cpputil.hh"
#include "scopedperf.hh"
extern scopedperf::ctrgroup_chain<scopedperf::tsc_ctr> perfgroup;
<|start_filename|>kernel/acpica/source/compiler/dttable.c<|end_filename|>
/******************************************************************************
*
* Module Name: dttable.c - handling for specific ACPI tables
*
*****************************************************************************/
/******************************************************************************
*
* 1. Copyright Notice
*
* Some or all of this work - Copyright (c) 1999 - 2012, Intel Corp.
* All rights reserved.
*
* 2. License
*
* 2.1. This is your license from Intel Corp. under its intellectual property
* rights. You may have additional license terms from the party that provided
* you this software, covering your right to use that party's intellectual
* property rights.
*
* 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
* copy of the source code appearing in this file ("Covered Code") an
* irrevocable, perpetual, worldwide license under Intel's copyrights in the
* base code distributed originally by Intel ("Original Intel Code") to copy,
* make derivatives, distribute, use and display any portion of the Covered
* Code in any form, with the right to sublicense such rights; and
*
* 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
* license (with the right to sublicense), under only those claims of Intel
* patents that are infringed by the Original Intel Code, to make, use, sell,
* offer to sell, and import the Covered Code and derivative works thereof
* solely to the minimum extent necessary to exercise the above copyright
* license, and in no event shall the patent license extend to any additions
* to or modifications of the Original Intel Code. No other license or right
* is granted directly or by implication, estoppel or otherwise;
*
* The above copyright and patent license is granted only if the following
* conditions are met:
*
* 3. Conditions
*
* 3.1. Redistribution of Source with Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification with rights to further distribute source must include
* the above Copyright Notice, the above License, this list of Conditions,
* and the following Disclaimer and Export Compliance provision. In addition,
* Licensee must cause all Covered Code to which Licensee contributes to
* contain a file documenting the changes Licensee made to create that Covered
* Code and the date of any change. Licensee must include in that file the
* documentation of any changes made by any predecessor Licensee. Licensee
* must include a prominent statement that the modification is derived,
* directly or indirectly, from Original Intel Code.
*
* 3.2. Redistribution of Source with no Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification without rights to further distribute source must
* include the following Disclaimer and Export Compliance provision in the
* documentation and/or other materials provided with distribution. In
* addition, Licensee may not authorize further sublicense of source of any
* portion of the Covered Code, and must include terms to the effect that the
* license from Licensee to its licensee is limited to the intellectual
* property embodied in the software Licensee provides to its licensee, and
* not to intellectual property embodied in modifications its licensee may
* make.
*
* 3.3. Redistribution of Executable. Redistribution in executable form of any
* substantial portion of the Covered Code or modification must reproduce the
* above Copyright Notice, and the following Disclaimer and Export Compliance
* provision in the documentation and/or other materials provided with the
* distribution.
*
* 3.4. Intel retains all right, title, and interest in and to the Original
* Intel Code.
*
* 3.5. Neither the name Intel nor any other trademark owned or controlled by
* Intel shall be used in advertising or otherwise to promote the sale, use or
* other dealings in products derived from or relating to the Covered Code
* without prior written authorization from Intel.
*
* 4. Disclaimer and Export Compliance
*
* 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
* HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
* IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
* INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
* UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
* IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
* OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
* COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
* SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
* CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
* HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
* SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
* LIMITED REMEDY.
*
* 4.3. Licensee shall not export, either directly or indirectly, any of this
* software or system incorporating such software without first obtaining any
* required license or other approval from the U. S. Department of Commerce or
* any other agency or department of the United States Government. In the
* event Licensee exports any such software from the United States or
* re-exports any such software from a foreign destination, Licensee shall
* ensure that the distribution and export/re-export of the software is in
* compliance with all laws, regulations, orders, or other restrictions of the
* U.S. Export Administration Regulations. Licensee agrees that neither it nor
* any of its subsidiaries will export/re-export any technical data, process,
* software, or service, directly or indirectly, to any country for which the
* United States government or any agency thereof requires an export license,
* other governmental approval, or letter of assurance, without first obtaining
* such license, approval or letter.
*
*****************************************************************************/
#define __DTTABLE_C__
/* Compile all complex data tables */
#include "aslcompiler.h"
#include "dtcompiler.h"
#define _COMPONENT DT_COMPILER
ACPI_MODULE_NAME ("dttable")
/* TBD: merge these into dmtbinfo.c? */
static ACPI_DMTABLE_INFO TableInfoAsfAddress[] =
{
{ACPI_DMT_BUFFER, 0, "Addresses", 0},
{ACPI_DMT_EXIT, 0, NULL, 0}
};
static ACPI_DMTABLE_INFO TableInfoDmarPciPath[] =
{
{ACPI_DMT_PCI_PATH, 0, "PCI Path", 0},
{ACPI_DMT_EXIT, 0, NULL, 0}
};
/* TBD: move to acmacros.h */
#define ACPI_SUB_PTR(t, a, b) \
ACPI_CAST_PTR (t, (ACPI_CAST_PTR (UINT8, (a)) - (ACPI_SIZE)(b)))
/* Local prototypes */
static ACPI_STATUS
DtCompileTwoSubtables (
void **List,
ACPI_DMTABLE_INFO *TableInfo1,
ACPI_DMTABLE_INFO *TableInfo2);
/******************************************************************************
*
* FUNCTION: DtCompileTwoSubtables
*
* PARAMETERS: List - Current field list pointer
* TableInfo1 - Info table 1
* TableInfo1 - Info table 2
*
* RETURN: Status
*
* DESCRIPTION: Compile tables with a header and one or more same subtables.
* Include CPEP, EINJ, ERST, MCFG, MSCT, WDAT
*
*****************************************************************************/
static ACPI_STATUS
DtCompileTwoSubtables (
void **List,
ACPI_DMTABLE_INFO *TableInfo1,
ACPI_DMTABLE_INFO *TableInfo2)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
Status = DtCompileTable (PFieldList, TableInfo1, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
while (*PFieldList)
{
Status = DtCompileTable (PFieldList, TableInfo2, &Subtable, FALSE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileFacs
*
* PARAMETERS: PFieldList - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile FACS.
*
*****************************************************************************/
ACPI_STATUS
DtCompileFacs (
DT_FIELD **PFieldList)
{
DT_SUBTABLE *Subtable;
UINT8 *ReservedBuffer;
ACPI_STATUS Status;
UINT32 ReservedSize;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoFacs,
&Gbl_RootTable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
/* Large FACS reserved area at the end of the table */
ReservedSize = (UINT32) sizeof (((ACPI_TABLE_FACS *) NULL)->Reserved1);
ReservedBuffer = UtLocalCalloc (ReservedSize);
DtCreateSubtable (ReservedBuffer, ReservedSize, &Subtable);
ACPI_FREE (ReservedBuffer);
DtInsertSubtable (Gbl_RootTable, Subtable);
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileRsdp
*
* PARAMETERS: PFieldList - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile RSDP.
*
*****************************************************************************/
ACPI_STATUS
DtCompileRsdp (
DT_FIELD **PFieldList)
{
DT_SUBTABLE *Subtable;
ACPI_TABLE_RSDP *Rsdp;
ACPI_RSDP_EXTENSION *RsdpExtension;
ACPI_STATUS Status;
/* Compile the "common" RSDP (ACPI 1.0) */
Status = DtCompileTable (PFieldList, AcpiDmTableInfoRsdp1,
&Gbl_RootTable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
Rsdp = ACPI_CAST_PTR (ACPI_TABLE_RSDP, Gbl_RootTable->Buffer);
DtSetTableChecksum (&Rsdp->Checksum);
if (Rsdp->Revision > 0)
{
/* Compile the "extended" part of the RSDP as a subtable */
Status = DtCompileTable (PFieldList, AcpiDmTableInfoRsdp2,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (Gbl_RootTable, Subtable);
/* Set length and extended checksum for entire RSDP */
RsdpExtension = ACPI_CAST_PTR (ACPI_RSDP_EXTENSION, Subtable->Buffer);
RsdpExtension->Length = Gbl_RootTable->Length + Subtable->Length;
DtSetTableChecksum (&RsdpExtension->ExtendedChecksum);
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileAsf
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile ASF!.
*
*****************************************************************************/
ACPI_STATUS
DtCompileAsf (
void **List)
{
ACPI_ASF_INFO *AsfTable;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
ACPI_DMTABLE_INFO *InfoTable;
ACPI_DMTABLE_INFO *DataInfoTable = NULL;
UINT32 DataCount = 0;
ACPI_STATUS Status;
UINT32 i;
DT_FIELD **PFieldList = (DT_FIELD **) List;
DT_FIELD *SubtableStart;
while (*PFieldList)
{
SubtableStart = *PFieldList;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoAsfHdr,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
AsfTable = ACPI_CAST_PTR (ACPI_ASF_INFO, Subtable->Buffer);
switch (AsfTable->Header.Type & 0x7F) /* Mask off top bit */
{
case ACPI_ASF_TYPE_INFO:
InfoTable = AcpiDmTableInfoAsf0;
break;
case ACPI_ASF_TYPE_ALERT:
InfoTable = AcpiDmTableInfoAsf1;
break;
case ACPI_ASF_TYPE_CONTROL:
InfoTable = AcpiDmTableInfoAsf2;
break;
case ACPI_ASF_TYPE_BOOT:
InfoTable = AcpiDmTableInfoAsf3;
break;
case ACPI_ASF_TYPE_ADDRESS:
InfoTable = AcpiDmTableInfoAsf4;
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "ASF!");
return (AE_ERROR);
}
Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
switch (AsfTable->Header.Type & 0x7F) /* Mask off top bit */
{
case ACPI_ASF_TYPE_INFO:
DataInfoTable = NULL;
break;
case ACPI_ASF_TYPE_ALERT:
DataInfoTable = AcpiDmTableInfoAsf1a;
DataCount = ACPI_CAST_PTR (ACPI_ASF_ALERT,
ACPI_SUB_PTR (UINT8, Subtable->Buffer,
sizeof (ACPI_ASF_HEADER)))->Alerts;
break;
case ACPI_ASF_TYPE_CONTROL:
DataInfoTable = AcpiDmTableInfoAsf2a;
DataCount = ACPI_CAST_PTR (ACPI_ASF_REMOTE,
ACPI_SUB_PTR (UINT8, Subtable->Buffer,
sizeof (ACPI_ASF_HEADER)))->Controls;
break;
case ACPI_ASF_TYPE_BOOT:
DataInfoTable = NULL;
break;
case ACPI_ASF_TYPE_ADDRESS:
DataInfoTable = TableInfoAsfAddress;
DataCount = ACPI_CAST_PTR (ACPI_ASF_ADDRESS,
ACPI_SUB_PTR (UINT8, Subtable->Buffer,
sizeof (ACPI_ASF_HEADER)))->Devices;
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "ASF!");
return (AE_ERROR);
}
if (DataInfoTable)
{
switch (AsfTable->Header.Type & 0x7F)
{
case ACPI_ASF_TYPE_ADDRESS:
while (DataCount > 0)
{
Status = DtCompileTable (PFieldList, DataInfoTable,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
DataCount = DataCount - Subtable->Length;
}
break;
default:
for (i = 0; i < DataCount; i++)
{
Status = DtCompileTable (PFieldList, DataInfoTable,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
}
break;
}
}
DtPopSubtable ();
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileCpep
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile CPEP.
*
*****************************************************************************/
ACPI_STATUS
DtCompileCpep (
void **List)
{
ACPI_STATUS Status;
Status = DtCompileTwoSubtables (List,
AcpiDmTableInfoCpep, AcpiDmTableInfoCpep0);
return (Status);
}
/******************************************************************************
*
* FUNCTION: DtCompileDmar
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile DMAR.
*
*****************************************************************************/
ACPI_STATUS
DtCompileDmar (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
DT_FIELD *SubtableStart;
ACPI_DMTABLE_INFO *InfoTable;
ACPI_DMAR_HEADER *DmarHeader;
UINT8 *ReservedBuffer;
UINT32 ReservedSize;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoDmar, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
/* DMAR Reserved area */
ReservedSize = (UINT32) sizeof (((ACPI_TABLE_DMAR *) NULL)->Reserved);
ReservedBuffer = UtLocalCalloc (ReservedSize);
DtCreateSubtable (ReservedBuffer, ReservedSize, &Subtable);
ACPI_FREE (ReservedBuffer);
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
while (*PFieldList)
{
/* DMAR Header */
SubtableStart = *PFieldList;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoDmarHdr,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
DmarHeader = ACPI_CAST_PTR (ACPI_DMAR_HEADER, Subtable->Buffer);
switch (DmarHeader->Type)
{
case ACPI_DMAR_TYPE_HARDWARE_UNIT:
InfoTable = AcpiDmTableInfoDmar0;
break;
case ACPI_DMAR_TYPE_RESERVED_MEMORY:
InfoTable = AcpiDmTableInfoDmar1;
break;
case ACPI_DMAR_TYPE_ATSR:
InfoTable = AcpiDmTableInfoDmar2;
break;
case ACPI_DMAR_HARDWARE_AFFINITY:
InfoTable = AcpiDmTableInfoDmar3;
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "DMAR");
return (AE_ERROR);
}
/* DMAR Subtable */
Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
/* Optional Device Scope subtables */
while (*PFieldList)
{
Status = DtCompileTable (PFieldList, AcpiDmTableInfoDmarScope,
&Subtable, FALSE);
if (Status == AE_NOT_FOUND)
{
break;
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
/* Optional PCI Paths */
while (*PFieldList)
{
Status = DtCompileTable (PFieldList, TableInfoDmarPciPath,
&Subtable, FALSE);
if (Status == AE_NOT_FOUND)
{
DtPopSubtable ();
break;
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
}
}
DtPopSubtable ();
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileEinj
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile EINJ.
*
*****************************************************************************/
ACPI_STATUS
DtCompileEinj (
void **List)
{
ACPI_STATUS Status;
Status = DtCompileTwoSubtables (List,
AcpiDmTableInfoEinj, AcpiDmTableInfoEinj0);
return (Status);
}
/******************************************************************************
*
* FUNCTION: DtCompileErst
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile ERST.
*
*****************************************************************************/
ACPI_STATUS
DtCompileErst (
void **List)
{
ACPI_STATUS Status;
Status = DtCompileTwoSubtables (List,
AcpiDmTableInfoErst, AcpiDmTableInfoEinj0);
return (Status);
}
/******************************************************************************
*
* FUNCTION: DtCompileFadt
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile FADT.
*
*****************************************************************************/
ACPI_STATUS
DtCompileFadt (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
ACPI_TABLE_HEADER *Table;
UINT8 Revision;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoFadt1,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
Table = ACPI_CAST_PTR (ACPI_TABLE_HEADER, ParentTable->Buffer);
Revision = Table->Revision;
if (Revision == 2)
{
Status = DtCompileTable (PFieldList, AcpiDmTableInfoFadt2,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
}
else if (Revision >= 2)
{
Status = DtCompileTable (PFieldList, AcpiDmTableInfoFadt3,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
if (Revision >= 5)
{
Status = DtCompileTable (PFieldList, AcpiDmTableInfoFadt5,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
}
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileFpdt
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile FPDT.
*
*****************************************************************************/
ACPI_STATUS
DtCompileFpdt (
void **List)
{
ACPI_STATUS Status;
ACPI_FPDT_HEADER *FpdtHeader;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
ACPI_DMTABLE_INFO *InfoTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
DT_FIELD *SubtableStart;
while (*PFieldList)
{
SubtableStart = *PFieldList;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoFpdtHdr,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
FpdtHeader = ACPI_CAST_PTR (ACPI_FPDT_HEADER, Subtable->Buffer);
switch (FpdtHeader->Type)
{
case ACPI_FPDT_TYPE_BOOT:
InfoTable = AcpiDmTableInfoFpdt0;
break;
case ACPI_FPDT_TYPE_S3PERF:
InfoTable = AcpiDmTableInfoFpdt1;
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "FPDT");
return (AE_ERROR);
break;
}
Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPopSubtable ();
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileHest
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile HEST.
*
*****************************************************************************/
ACPI_STATUS
DtCompileHest (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
DT_FIELD *SubtableStart;
ACPI_DMTABLE_INFO *InfoTable;
UINT16 Type;
UINT32 BankCount;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoHest,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
while (*PFieldList)
{
/* Get subtable type */
SubtableStart = *PFieldList;
DtCompileInteger ((UINT8 *) &Type, *PFieldList, 2, 0);
switch (Type)
{
case ACPI_HEST_TYPE_IA32_CHECK:
InfoTable = AcpiDmTableInfoHest0;
break;
case ACPI_HEST_TYPE_IA32_CORRECTED_CHECK:
InfoTable = AcpiDmTableInfoHest1;
break;
case ACPI_HEST_TYPE_IA32_NMI:
InfoTable = AcpiDmTableInfoHest2;
break;
case ACPI_HEST_TYPE_AER_ROOT_PORT:
InfoTable = AcpiDmTableInfoHest6;
break;
case ACPI_HEST_TYPE_AER_ENDPOINT:
InfoTable = AcpiDmTableInfoHest7;
break;
case ACPI_HEST_TYPE_AER_BRIDGE:
InfoTable = AcpiDmTableInfoHest8;
break;
case ACPI_HEST_TYPE_GENERIC_ERROR:
InfoTable = AcpiDmTableInfoHest9;
break;
default:
/* Cannot continue on unknown type */
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "HEST");
return (AE_ERROR);
}
Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
/*
* Additional subtable data - IA32 Error Bank(s)
*/
BankCount = 0;
switch (Type)
{
case ACPI_HEST_TYPE_IA32_CHECK:
BankCount = (ACPI_CAST_PTR (ACPI_HEST_IA_MACHINE_CHECK,
Subtable->Buffer))->NumHardwareBanks;
break;
case ACPI_HEST_TYPE_IA32_CORRECTED_CHECK:
BankCount = (ACPI_CAST_PTR (ACPI_HEST_IA_CORRECTED,
Subtable->Buffer))->NumHardwareBanks;
break;
default:
break;
}
while (BankCount)
{
Status = DtCompileTable (PFieldList, AcpiDmTableInfoHestBank,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
BankCount--;
}
}
return AE_OK;
}
/******************************************************************************
*
* FUNCTION: DtCompileIvrs
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile IVRS.
*
*****************************************************************************/
ACPI_STATUS
DtCompileIvrs (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
DT_FIELD *SubtableStart;
ACPI_DMTABLE_INFO *InfoTable;
ACPI_IVRS_HEADER *IvrsHeader;
UINT8 EntryType;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoIvrs,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
while (*PFieldList)
{
SubtableStart = *PFieldList;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoIvrsHdr,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
IvrsHeader = ACPI_CAST_PTR (ACPI_IVRS_HEADER, Subtable->Buffer);
switch (IvrsHeader->Type)
{
case ACPI_IVRS_TYPE_HARDWARE:
InfoTable = AcpiDmTableInfoIvrs0;
break;
case ACPI_IVRS_TYPE_MEMORY1:
case ACPI_IVRS_TYPE_MEMORY2:
case ACPI_IVRS_TYPE_MEMORY3:
InfoTable = AcpiDmTableInfoIvrs1;
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "IVRS");
return (AE_ERROR);
}
Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
if (IvrsHeader->Type == ACPI_IVRS_TYPE_HARDWARE)
{
while (*PFieldList &&
!ACPI_STRCMP ((*PFieldList)->Name, "Entry Type"))
{
SubtableStart = *PFieldList;
DtCompileInteger (&EntryType, *PFieldList, 1, 0);
switch (EntryType)
{
/* 4-byte device entries */
case ACPI_IVRS_TYPE_PAD4:
case ACPI_IVRS_TYPE_ALL:
case ACPI_IVRS_TYPE_SELECT:
case ACPI_IVRS_TYPE_START:
case ACPI_IVRS_TYPE_END:
InfoTable = AcpiDmTableInfoIvrs4;
break;
/* 8-byte entries, type A */
case ACPI_IVRS_TYPE_ALIAS_SELECT:
case ACPI_IVRS_TYPE_ALIAS_START:
InfoTable = AcpiDmTableInfoIvrs8a;
break;
/* 8-byte entries, type B */
case ACPI_IVRS_TYPE_PAD8:
case ACPI_IVRS_TYPE_EXT_SELECT:
case ACPI_IVRS_TYPE_EXT_START:
InfoTable = AcpiDmTableInfoIvrs8b;
break;
/* 8-byte entries, type C */
case ACPI_IVRS_TYPE_SPECIAL:
InfoTable = AcpiDmTableInfoIvrs8c;
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart,
"IVRS Device Entry");
return (AE_ERROR);
}
Status = DtCompileTable (PFieldList, InfoTable,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
}
}
DtPopSubtable ();
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileMadt
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile MADT.
*
*****************************************************************************/
ACPI_STATUS
DtCompileMadt (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
DT_FIELD *SubtableStart;
ACPI_SUBTABLE_HEADER *MadtHeader;
ACPI_DMTABLE_INFO *InfoTable;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoMadt,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
while (*PFieldList)
{
SubtableStart = *PFieldList;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoMadtHdr,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
MadtHeader = ACPI_CAST_PTR (ACPI_SUBTABLE_HEADER, Subtable->Buffer);
switch (MadtHeader->Type)
{
case ACPI_MADT_TYPE_LOCAL_APIC:
InfoTable = AcpiDmTableInfoMadt0;
break;
case ACPI_MADT_TYPE_IO_APIC:
InfoTable = AcpiDmTableInfoMadt1;
break;
case ACPI_MADT_TYPE_INTERRUPT_OVERRIDE:
InfoTable = AcpiDmTableInfoMadt2;
break;
case ACPI_MADT_TYPE_NMI_SOURCE:
InfoTable = AcpiDmTableInfoMadt3;
break;
case ACPI_MADT_TYPE_LOCAL_APIC_NMI:
InfoTable = AcpiDmTableInfoMadt4;
break;
case ACPI_MADT_TYPE_LOCAL_APIC_OVERRIDE:
InfoTable = AcpiDmTableInfoMadt5;
break;
case ACPI_MADT_TYPE_IO_SAPIC:
InfoTable = AcpiDmTableInfoMadt6;
break;
case ACPI_MADT_TYPE_LOCAL_SAPIC:
InfoTable = AcpiDmTableInfoMadt7;
break;
case ACPI_MADT_TYPE_INTERRUPT_SOURCE:
InfoTable = AcpiDmTableInfoMadt8;
break;
case ACPI_MADT_TYPE_LOCAL_X2APIC:
InfoTable = AcpiDmTableInfoMadt9;
break;
case ACPI_MADT_TYPE_LOCAL_X2APIC_NMI:
InfoTable = AcpiDmTableInfoMadt10;
break;
case ACPI_MADT_TYPE_GENERIC_INTERRUPT:
InfoTable = AcpiDmTableInfoMadt11;
break;
case ACPI_MADT_TYPE_GENERIC_DISTRIBUTOR:
InfoTable = AcpiDmTableInfoMadt12;
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "MADT");
return (AE_ERROR);
}
Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPopSubtable ();
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileMcfg
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile MCFG.
*
*****************************************************************************/
ACPI_STATUS
DtCompileMcfg (
void **List)
{
ACPI_STATUS Status;
Status = DtCompileTwoSubtables (List,
AcpiDmTableInfoMcfg, AcpiDmTableInfoMcfg0);
return (Status);
}
/******************************************************************************
*
* FUNCTION: DtCompileMpst
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile MPST.
*
*****************************************************************************/
ACPI_STATUS
DtCompileMpst (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
ACPI_MPST_CHANNEL *MpstChannelInfo;
ACPI_MPST_POWER_NODE *MpstPowerNode;
ACPI_MPST_DATA_HDR *MpstDataHeader;
UINT16 SubtableCount;
UINT8 PowerStateCount;
UINT8 ComponentCount;
/* Main table */
Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
MpstChannelInfo = ACPI_CAST_PTR (ACPI_MPST_CHANNEL, Subtable->Buffer);
SubtableCount = MpstChannelInfo->PowerNodeCount;
while (*PFieldList && SubtableCount)
{
/* Subtable: Memory Power Node(s) */
Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst0,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
MpstPowerNode = ACPI_CAST_PTR (ACPI_MPST_POWER_NODE, Subtable->Buffer);
PowerStateCount = MpstPowerNode->NumPowerStates;
ComponentCount = MpstPowerNode->NumPhysicalComponents;
ParentTable = DtPeekSubtable ();
/* Sub-subtables - Memory Power State Structure(s) */
while (*PFieldList && PowerStateCount)
{
Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst0A,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
PowerStateCount--;
}
/* Sub-subtables - Physical Component ID Structure(s) */
while (*PFieldList && ComponentCount)
{
Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst0B,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
ComponentCount--;
}
SubtableCount--;
DtPopSubtable ();
}
/* Subtable: Count of Memory Power State Characteristic structures */
DtPopSubtable ();
Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst1, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
MpstDataHeader = ACPI_CAST_PTR (ACPI_MPST_DATA_HDR, Subtable->Buffer);
SubtableCount = MpstDataHeader->CharacteristicsCount;
ParentTable = DtPeekSubtable ();
/* Subtable: Memory Power State Characteristics structure(s) */
while (*PFieldList && SubtableCount)
{
Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst2,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
SubtableCount--;
}
DtPopSubtable ();
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileMsct
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile MSCT.
*
*****************************************************************************/
ACPI_STATUS
DtCompileMsct (
void **List)
{
ACPI_STATUS Status;
Status = DtCompileTwoSubtables (List,
AcpiDmTableInfoMsct, AcpiDmTableInfoMsct0);
return (Status);
}
/******************************************************************************
*
* FUNCTION: DtCompilePmtt
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile PMTT.
*
*****************************************************************************/
ACPI_STATUS
DtCompilePmtt (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
DT_FIELD *SubtableStart;
ACPI_PMTT_HEADER *PmttHeader;
ACPI_PMTT_CONTROLLER *PmttController;
UINT16 DomainCount;
UINT8 PrevType = ACPI_PMTT_TYPE_SOCKET;
/* Main table */
Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmtt, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
while (*PFieldList)
{
SubtableStart = *PFieldList;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmttHdr,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
PmttHeader = ACPI_CAST_PTR (ACPI_PMTT_HEADER, Subtable->Buffer);
while (PrevType >= PmttHeader->Type)
{
DtPopSubtable ();
if (PrevType == ACPI_PMTT_TYPE_SOCKET)
{
break;
}
PrevType--;
}
PrevType = PmttHeader->Type;
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
switch (PmttHeader->Type)
{
case ACPI_PMTT_TYPE_SOCKET:
/* Subtable: Socket Structure */
Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmtt0,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
break;
case ACPI_PMTT_TYPE_CONTROLLER:
/* Subtable: Memory Controller Structure */
Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmtt1,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
PmttController = ACPI_CAST_PTR (ACPI_PMTT_CONTROLLER,
(Subtable->Buffer - sizeof (ACPI_PMTT_HEADER)));
DomainCount = PmttController->DomainCount;
while (DomainCount)
{
Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmtt1a,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtInsertSubtable (ParentTable, Subtable);
DomainCount--;
}
break;
case ACPI_PMTT_TYPE_DIMM:
/* Subtable: Physical Component Structure */
Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmtt2,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "PMTT");
return (AE_ERROR);
}
}
return (Status);
}
/******************************************************************************
*
* FUNCTION: DtCompileRsdt
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile RSDT.
*
*****************************************************************************/
ACPI_STATUS
DtCompileRsdt (
void **List)
{
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD *FieldList = *(DT_FIELD **) List;
UINT32 Address;
ParentTable = DtPeekSubtable ();
while (FieldList)
{
DtCompileInteger ((UINT8 *) &Address, FieldList, 4, DT_NON_ZERO);
DtCreateSubtable ((UINT8 *) &Address, 4, &Subtable);
DtInsertSubtable (ParentTable, Subtable);
FieldList = FieldList->Next;
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileS3pt
*
* PARAMETERS: PFieldList - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile S3PT (Pointed to by FPDT)
*
*****************************************************************************/
ACPI_STATUS
DtCompileS3pt (
DT_FIELD **PFieldList)
{
ACPI_STATUS Status;
ACPI_S3PT_HEADER *S3ptHeader;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
ACPI_DMTABLE_INFO *InfoTable;
DT_FIELD *SubtableStart;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoS3pt,
&Gbl_RootTable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DtPushSubtable (Gbl_RootTable);
while (*PFieldList)
{
SubtableStart = *PFieldList;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoS3ptHdr,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
S3ptHeader = ACPI_CAST_PTR (ACPI_S3PT_HEADER, Subtable->Buffer);
switch (S3ptHeader->Type)
{
case ACPI_S3PT_TYPE_RESUME:
InfoTable = AcpiDmTableInfoS3pt0;
break;
case ACPI_S3PT_TYPE_SUSPEND:
InfoTable = AcpiDmTableInfoS3pt1;
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "S3PT");
return (AE_ERROR);
}
Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPopSubtable ();
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileSlic
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile SLIC.
*
*****************************************************************************/
ACPI_STATUS
DtCompileSlic (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
DT_FIELD *SubtableStart;
ACPI_SLIC_HEADER *SlicHeader;
ACPI_DMTABLE_INFO *InfoTable;
while (*PFieldList)
{
SubtableStart = *PFieldList;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoSlicHdr,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
SlicHeader = ACPI_CAST_PTR (ACPI_SLIC_HEADER, Subtable->Buffer);
switch (SlicHeader->Type)
{
case ACPI_SLIC_TYPE_PUBLIC_KEY:
InfoTable = AcpiDmTableInfoSlic0;
break;
case ACPI_SLIC_TYPE_WINDOWS_MARKER:
InfoTable = AcpiDmTableInfoSlic1;
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "SLIC");
return (AE_ERROR);
}
Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPopSubtable ();
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileSlit
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile SLIT.
*
*****************************************************************************/
ACPI_STATUS
DtCompileSlit (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
DT_FIELD *FieldList;
UINT32 Localities;
UINT8 *LocalityBuffer;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoSlit,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
Localities = *ACPI_CAST_PTR (UINT32, Subtable->Buffer);
LocalityBuffer = UtLocalCalloc (Localities);
/* Compile each locality buffer */
FieldList = *PFieldList;
while (FieldList)
{
DtCompileBuffer (LocalityBuffer,
FieldList->Value, FieldList, Localities);
DtCreateSubtable (LocalityBuffer, Localities, &Subtable);
DtInsertSubtable (ParentTable, Subtable);
FieldList = FieldList->Next;
}
ACPI_FREE (LocalityBuffer);
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileSrat
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile SRAT.
*
*****************************************************************************/
ACPI_STATUS
DtCompileSrat (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
DT_FIELD *SubtableStart;
ACPI_SUBTABLE_HEADER *SratHeader;
ACPI_DMTABLE_INFO *InfoTable;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoSrat,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
while (*PFieldList)
{
SubtableStart = *PFieldList;
Status = DtCompileTable (PFieldList, AcpiDmTableInfoSratHdr,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPushSubtable (Subtable);
SratHeader = ACPI_CAST_PTR (ACPI_SUBTABLE_HEADER, Subtable->Buffer);
switch (SratHeader->Type)
{
case ACPI_SRAT_TYPE_CPU_AFFINITY:
InfoTable = AcpiDmTableInfoSrat0;
break;
case ACPI_SRAT_TYPE_MEMORY_AFFINITY:
InfoTable = AcpiDmTableInfoSrat1;
break;
case ACPI_SRAT_TYPE_X2APIC_CPU_AFFINITY:
InfoTable = AcpiDmTableInfoSrat2;
break;
default:
DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "SRAT");
return (AE_ERROR);
}
Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
DtPopSubtable ();
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtGetGenericTableInfo
*
* PARAMETERS: Name - Generic type name
*
* RETURN: Info entry
*
* DESCRIPTION: Obtain table info for a generic name entry
*
*****************************************************************************/
ACPI_DMTABLE_INFO *
DtGetGenericTableInfo (
char *Name)
{
ACPI_DMTABLE_INFO *Info;
UINT32 i;
if (!Name)
{
return (NULL);
}
/* Search info table for name match */
for (i = 0; ; i++)
{
Info = AcpiDmTableInfoGeneric[i];
if (Info->Opcode == ACPI_DMT_EXIT)
{
Info = NULL;
break;
}
/* Use caseless compare for generic keywords */
if (!AcpiUtStricmp (Name, Info->Name))
{
break;
}
}
return (Info);
}
/******************************************************************************
*
* FUNCTION: DtCompileUefi
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile UEFI.
*
*****************************************************************************/
ACPI_STATUS
DtCompileUefi (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
UINT16 *DataOffset;
/* Compile the predefined portion of the UEFI table */
Status = DtCompileTable (PFieldList, AcpiDmTableInfoUefi,
&Subtable, TRUE);
if (ACPI_FAILURE (Status))
{
return (Status);
}
DataOffset = (UINT16 *) (Subtable->Buffer + 16);
*DataOffset = sizeof (ACPI_TABLE_UEFI);
ParentTable = DtPeekSubtable ();
DtInsertSubtable (ParentTable, Subtable);
/*
* Compile the "generic" portion of the UEFI table. This
* part of the table is not predefined and any of the generic
* operators may be used.
*/
DtCompileGeneric ((void **) PFieldList);
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileWdat
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile WDAT.
*
*****************************************************************************/
ACPI_STATUS
DtCompileWdat (
void **List)
{
ACPI_STATUS Status;
Status = DtCompileTwoSubtables (List,
AcpiDmTableInfoWdat, AcpiDmTableInfoWdat0);
return (Status);
}
/******************************************************************************
*
* FUNCTION: DtCompileXsdt
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile XSDT.
*
*****************************************************************************/
ACPI_STATUS
DtCompileXsdt (
void **List)
{
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD *FieldList = *(DT_FIELD **) List;
UINT64 Address;
ParentTable = DtPeekSubtable ();
while (FieldList)
{
DtCompileInteger ((UINT8 *) &Address, FieldList, 8, DT_NON_ZERO);
DtCreateSubtable ((UINT8 *) &Address, 8, &Subtable);
DtInsertSubtable (ParentTable, Subtable);
FieldList = FieldList->Next;
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: DtCompileGeneric
*
* PARAMETERS: List - Current field list pointer
*
* RETURN: Status
*
* DESCRIPTION: Compile generic unknown table.
*
*****************************************************************************/
ACPI_STATUS
DtCompileGeneric (
void **List)
{
ACPI_STATUS Status;
DT_SUBTABLE *Subtable;
DT_SUBTABLE *ParentTable;
DT_FIELD **PFieldList = (DT_FIELD **) List;
ACPI_DMTABLE_INFO *Info;
ParentTable = DtPeekSubtable ();
/*
* Compile the "generic" portion of the table. This
* part of the table is not predefined and any of the generic
* operators may be used.
*/
/* Find any and all labels in the entire generic portion */
DtDetectAllLabels (*PFieldList);
/* Now we can actually compile the parse tree */
while (*PFieldList)
{
Info = DtGetGenericTableInfo ((*PFieldList)->Name);
if (!Info)
{
sprintf (MsgBuffer, "Generic data type \"%s\" not found",
(*PFieldList)->Name);
DtNameError (ASL_ERROR, ASL_MSG_INVALID_FIELD_NAME,
(*PFieldList), MsgBuffer);
*PFieldList = (*PFieldList)->Next;
continue;
}
Status = DtCompileTable (PFieldList, Info,
&Subtable, TRUE);
if (ACPI_SUCCESS (Status))
{
DtInsertSubtable (ParentTable, Subtable);
}
else
{
*PFieldList = (*PFieldList)->Next;
if (Status == AE_NOT_FOUND)
{
sprintf (MsgBuffer, "Generic data type \"%s\" not found",
(*PFieldList)->Name);
DtNameError (ASL_ERROR, ASL_MSG_INVALID_FIELD_NAME,
(*PFieldList), MsgBuffer);
}
}
}
return (AE_OK);
}
<|start_filename|>bin/time.cc<|end_filename|>
#include "types.h"
#include "user.h"
#include "amd64.h"
#include <stdio.h>
#include <unistd.h>
#include <vector>
int
main(int ac, char * const av[])
{
if (ac <= 1)
die("usage: %s command...", av[0]);
u64 t0 = rdtsc();
int pid = fork();
if (pid < 0) {
die("time: fork failed");
}
if (pid == 0) {
std::vector<const char *> args(av + 1, av + ac);
args.push_back(nullptr);
execv(args[0], const_cast<char * const *>(args.data()));
die("time: exec failed");
}
wait(NULL);
u64 t1 = rdtsc();
printf("%lu cycles\n", t1-t0);
return 0;
}
<|start_filename|>kernel/xapic.cc<|end_filename|>
// The local APIC manages internal (non-I/O) interrupts.
// See Chapter 8 & Appendix C of Intel processor manual volume 3.
#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "traps.h"
#include "bits.hh"
#include "cpu.hh"
#include "apic.hh"
#include "kstream.hh"
#include "bitset.hh"
#include "critical.hh"
#include "cpuid.hh"
static console_stream verbose(true);
// Local APIC registers, divided by 4 for use as uint[] indices.
#define ID (0x0020/4) // ID
#define VER (0x0030/4) // Version
#define TPR (0x0080/4) // Task Priority
#define PPR (0x00A0/4) // Processor Priority
#define EOI (0x00B0/4) // EOI
#define LDR (0x00D0/4) // Logical Destination
#define SVR (0x00F0/4) // Spurious Interrupt Vector
#define ENABLE 0x00000100 // Unit Enable
#define ISR (0x0100/4) // In-service register
#define ISR_NR 0x8
#define TMR (0x0180/4) // Trigger mode register
#define IRR (0x0200/4) // Interrupt request register
#define ESR (0x0280/4) // Error Status
#define CMCI (0x02f0/4) // CMCI LVT
#define ICRLO (0x0300/4) // Interrupt Command
#define INIT 0x00000500 // INIT/RESET
#define STARTUP 0x00000600 // Startup IPI
#define DELIVS 0x00001000 // Delivery status
#define ASSERT 0x00004000 // Assert interrupt (vs deassert)
#define DEASSERT 0x00000000
#define LEVEL 0x00008000 // Level triggered
#define BCAST 0x00080000 // Send to all APICs, including self.
#define FIXED 0x00000000
#define ICRHI (0x0310/4) // Interrupt Command [63:32]
#define TIMER (0x0320/4) // Local Vector Table 0 (TIMER)
#define X1 0x0000000B // divide counts by 1
#define PERIODIC 0x00020000 // Periodic
#define THERM (0x0330/4) // Thermal sensor LVT
#define PCINT (0x0340/4) // Performance Counter LVT
#define LINT0 (0x0350/4) // Local Vector Table 1 (LINT0)
#define LINT1 (0x0360/4) // Local Vector Table 2 (LINT1)
#define ERROR (0x0370/4) // Local Vector Table 3 (ERROR)
#define MASKED 0x00010000 // Interrupt masked
#define MT_NMI 0x00000400 // NMI message type
#define MT_FIX 0x00000000 // Fixed message type
#define TICR (0x0380/4) // Timer Initial Count
#define TCCR (0x0390/4) // Timer Current Count
#define TDCR (0x03E0/4) // Timer Divide Configuration
#define IO_RTC 0x70
static volatile u32 *xapic;
static u64 xapichz;
class xapic_lapic : public abstract_lapic
{
public:
void init();
void cpu_init() override;
hwid_t id() override;
void eoi() override;
void send_ipi(struct cpu *c, int ino) override;
void mask_pc(bool mask) override;
void start_ap(struct cpu *c, u32 addr) override;
void dump() override;
private:
void dumpall();
};
static void
xapicw(u32 index, u32 value)
{
xapic[index] = value;
xapic[ID]; // wait for write to finish, by reading
}
static u32
xapicr(u32 off)
{
return xapic[off];
}
static int
xapicwait()
{
int i = 100000;
while ((xapicr(ICRLO) & DELIVS) != 0) {
nop_pause();
i--;
if (i == 0) {
cprintf("xapicwait: wedged?\n");
return -1;
}
}
return 0;
}
void
xapic_lapic::init()
{
u64 apic_base = readmsr(MSR_APIC_BAR);
// Sanity check
if (!(apic_base & APIC_BAR_XAPIC_EN))
panic("xapic_lapic::init xAPIC not enabled");
xapic = (u32*)p2v(apic_base & ~0xffful);
}
void
xapic_lapic::cpu_init()
{
u64 count;
verbose.println("xapic: Initializing LAPIC (CPU ", myid(), ")");
// Enable local APIC, do not suppress EOI broadcast, set spurious
// interrupt vector.
xapicw(SVR, ENABLE | (T_IRQ0 + IRQ_SPURIOUS));
if (xapichz == 0) {
// Measure the TICR frequency
xapicw(TDCR, X1);
xapicw(TICR, 0xffffffff);
u64 ccr0 = xapicr(TCCR);
microdelay(10 * 1000); // 1/100th of a second
u64 ccr1 = xapicr(TCCR);
xapichz = 100 * (ccr0 - ccr1);
}
count = (QUANTUM*xapichz) / 1000;
if (count > 0xffffffff)
panic("initxapic: QUANTUM too large");
// The timer repeatedly counts down at bus frequency
// from xapic[TICR] and then issues an interrupt.
xapicw(TDCR, X1);
xapicw(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER));
xapicw(TICR, count);
// Disable logical interrupt lines.
xapicw(LINT0, MASKED);
xapicw(LINT1, MASKED);
// Disable performance counter overflow interrupts
// on machines that provide that interrupt entry.
if(((xapic[VER]>>16) & 0xFF) >= 4)
mask_pc(false);
// Map error interrupt to IRQ_ERROR.
xapicw(ERROR, T_IRQ0 + IRQ_ERROR);
// Clear error status register (requires back-to-back writes).
xapicw(ESR, 0);
xapicw(ESR, 0);
// Ack any outstanding interrupts.
xapicw(EOI, 0);
// Send an Init Level De-Assert to synchronise arbitration ID's.
xapicw(ICRHI, 0);
xapicw(ICRLO, BCAST | INIT | LEVEL);
while(xapic[ICRLO] & DELIVS)
;
// Enable interrupts on the APIC (but not on the processor).
xapicw(TPR, 0);
}
void
xapic_lapic::mask_pc(bool mask)
{
xapicw(PCINT, mask ? MASKED : MT_NMI);
}
hwid_t
xapic_lapic::id()
{
if (readrflags() & FL_IF) {
cli();
panic("xapic_lapic::id() called from %p with interrupts enabled\n",
__builtin_return_address(0));
}
return HWID(xapic[ID]>>24);
}
// Acknowledge interrupt.
void
xapic_lapic::eoi()
{
xapicw(EOI, 0);
}
// Send IPI
void
xapic_lapic::send_ipi(struct cpu *c, int ino)
{
pushcli();
xapicw(ICRHI, c->hwid.num << 24);
xapicw(ICRLO, FIXED | DEASSERT | ino);
if (xapicwait() < 0)
panic("xapic_lapic::send_ipi: xapicwait failure");
popcli();
}
// Start additional processor running bootstrap code at addr.
// See Appendix B of MultiProcessor Specification.
void
xapic_lapic::start_ap(struct cpu *c, u32 addr)
{
int i;
// "Universal startup algorithm."
// Send INIT (level-triggered) interrupt to reset other CPU.
xapicw(ICRHI, c->hwid.num<<24);
xapicw(ICRLO, INIT | LEVEL | ASSERT);
xapicwait();
microdelay(10000);
xapicw(ICRLO, INIT | LEVEL);
xapicwait();
microdelay(10000); // should be 10ms, but too slow in Bochs!
// Send startup IPI (twice!) to enter bootstrap code.
// Regular hardware is supposed to only accept a STARTUP
// when it is in the halted state due to an INIT. So the second
// should be ignored, but it is part of the official Intel algorithm.
// Bochs complains about the second one. Too bad for Bochs.
for(i = 0; i < 2; i++){
xapicw(ICRHI, c->hwid.num<<24);
xapicw(ICRLO, STARTUP | (addr>>12));
microdelay(200);
}
}
void
xapic_lapic::dump()
{
bitset<256> isr, irr, tmr;
scoped_cli cli;
for (int word = 0; word < ISR_NR; ++word) {
isr.setword(word * 32, xapicr(ISR + word * 4));
irr.setword(word * 32, xapicr(IRR + word * 4));
tmr.setword(word * 32, xapicr(TMR + word * 4));
}
if (isr.any() || irr.any() || tmr.any())
// Fixed-mode interrupt vectors that are awaiting EOI (ISR), that
// are pending delivery (IRR), and are level-triggered and will
// trigger an IOAPIC EOI when acknowledged (TMR).
console.println("LAPIC INT ISR ", isr, " IRR ", irr, " TMR ", tmr);
}
void
xapic_lapic::dumpall()
{
scoped_cli cli;
console.println("LAPIC CPU ", myid());
#define SHOW(reg) console.println(" " #reg "\t", shex(xapicr(reg)).width(10).pad())
SHOW(ID);
SHOW(VER);
SHOW(TPR);
SHOW(PPR);
SHOW(LDR);
SHOW(SVR);
SHOW(ESR);
SHOW(CMCI);
console.println(" ICR\t", shex(xapicr(ICRLO) | ((u64)xapicr(ICRHI) << 32)).
width(18).pad());
SHOW(TIMER);
SHOW(THERM);
SHOW(PCINT);
SHOW(LINT0);
SHOW(LINT1);
SHOW(ERROR);
SHOW(TICR);
SHOW(TCCR);
SHOW(TDCR);
#undef SHOW
}
bool
initlapic_xapic(void)
{
if (!cpuid::features().apic)
return false;
verbose.println("xapic: Using xAPIC LAPIC");
static xapic_lapic apic;
apic.init();
lapic = &apic;
return true;
}
<|start_filename|>kernel/user.cc<|end_filename|>
#include "types.h"
#include "kernel.hh"
#include "mmu.h"
#include "amd64.h"
#include "spinlock.hh"
#include "condvar.hh"
#include "proc.hh"
#include "cpu.hh"
#include "bits.hh"
#include "vm.hh"
#include "filetable.hh"
#define INIT_START 0x1000
extern struct proc *bootproc;
// Set up first user process.
void
inituser(void)
{
struct proc *p;
extern u8 _initcode_start[];
extern u64 _initcode_size;
p = proc::alloc();
p->ftable = filetable::alloc();
if (p->ftable == nullptr)
panic("userinit: new filetable");
bootproc = p;
if((p->vmap = vmap::alloc()) == 0)
panic("userinit: out of vmaps?");
if(p->vmap->insert(vmdesc::anon_desc, INIT_START,
PGROUNDUP(_initcode_size)) < 0)
panic("inituser: vmap::insert");
if(p->vmap->copyout(INIT_START, _initcode_start, _initcode_size) < 0)
panic("userinit: copyout");
memset(p->tf, 0, sizeof(*p->tf));
p->tf->cs = UCSEG | 0x3;
p->tf->ds = UDSEG | 0x3;
p->tf->ss = p->tf->ds;
p->tf->rflags = FL_IF;
p->tf->rsp = PGSIZE;
p->tf->rip = INIT_START; // beginning of initcode.S
p->data_cpuid = myid();
safestrcpy(p->name, "initcode", sizeof(p->name));
p->cwd.reset(); // forkret will fix in the process's context
acquire(&p->lock);
addrun(p);
release(&p->lock);
}
<|start_filename|>stdinc/sys/types.h<|end_filename|>
#pragma once
// Partial implementation of IEEE Std 1003.1-2008
#include <stddef.h>
#include <stdint.h>
typedef ptrdiff_t ssize_t;
typedef ssize_t off_t;
typedef uint64_t dev_t;
typedef uint64_t ino_t;
typedef short nlink_t;
typedef short mode_t;
typedef int pid_t;
typedef int time_t;
typedef int suseconds_t;
<|start_filename|>include/lockwrap.hh<|end_filename|>
#pragma once
#include "seqlock.hh"
template<typename T>
class ptr_wrap
{
public:
ptr_wrap(T* ptr) : ptr_(ptr) {}
T* operator->() const {
return ptr_;
}
T& operator*() const {
return *ptr_;
}
private:
T* ptr_;
};
template<typename T>
class seq_reader
{
public:
seq_reader(const T* v, const seqcount<u32>* seq) {
for (;;) {
auto r = seq->read_begin();
state_ = *v;
if (!r.need_retry())
return;
}
}
const T* operator->() const {
return &state_;
}
const T& operator*() const {
return state_;
}
private:
T state_;
};
class seq_writer
{
public:
seq_writer(seqcount<u32>* seq) : w_(seq->write_begin()) {}
seq_writer() {}
private:
seqcount<u32>::writer w_;
};
<|start_filename|>stdinc/strings.h<|end_filename|>
#pragma once
#include "compiler.h"
#include <string.h>
static inline void
bzero(void* s, size_t n)
{
memset(s, 0, n);
}
BEGIN_DECLS
int strcasecmp(const char *s1, const char *s2);
END_DECLS
<|start_filename|>bin/disktest.cc<|end_filename|>
#include <stdio.h>
#include "sysstubs.h"
int
main(int argc, char *argv[])
{
disktest();
return 0;
}
<|start_filename|>kernel/uart.cc<|end_filename|>
// Intel 8250 serial port (UART).
// http://en.wikibooks.org/wiki/Serial_Programming/8250_UART_Programming
#include "types.h"
#include "kernel.hh"
#include "amd64.h"
#include "traps.h"
#include "apic.hh"
#include "irq.hh"
#define COM2 0x2f8
#define COM1 0x3f8
#define COM_IN_RECEIVE 0 // DLAB = 0, in
#define COM_OUT_TRANSMIT 0 // DLAB = 0, out
#define COM_INT_EN 1 // DLAB = 0
# define COM_INT_RECEIVE 0x01
# define COM_INT_TRANSMIT 0x02
# define COM_INT_LINE 0x04
# define COM_INT_MODEM 0x08
#define COM_DIVISOR_LSB 0 // DLAB = 1
#define COM_DIVISOR_MSB 1 // DLAB = 1
#define COM_IN_IIR 2
# define COM_IN_IIR_NOT_PENDING 0x01
# define COM_IN_IIR_ID_MASK 0x0E
#define COM_OUT_FIFO_CTL 2
# define COM_OUT_FIFO_ENABLE 0x01
# define COM_OUT_FIFO_RECV_RESET 0x02
# define COM_OUT_FIFO_XMIT_RESET 0x04
# define COM_OUT_FIFO_DMA 0x08
# define COM_OUT_FIFO_TRIGGER_MASK 0xC0
# define COM_OUT_FIFO_TRIGGER_1 (0<<6)
# define COM_OUT_FIFO_TRIGGER_4 (1<<6)
# define COM_OUT_FIFO_TRIGGER_8 (2<<6)
# define COM_OUT_FIFO_TRIGGER_14 (3<<6)
#define COM_LINE_CTL 3
# define COM_LINE_LEN_MASK 0x03
# define COM_LINE_LEN_5 0
# define COM_LINE_LEN_6 1
# define COM_LINE_LEN_7 2
# define COM_LINE_LEN_8 3
# define COM_LINE_STOP_BITS 0x04
# define COM_LINE_PARITY 0x08
# define COM_LINE_EVEN_PARITY 0x10
# define COM_LINE_STICK_PARITY 0x20
# define COM_LINE_BREAK_CTL 0x40
# define COM_LINE_DLAB 0x80
#define COM_MODEM_CTL 4
#define COM_LINE_STATUS 5
# define COM_LINE_DATA_READY 0x01
# define COM_LINE_OVERRUN_ERR 0x02
# define COM_LINE_PARITY_ERR 0x04
# define COM_LINE_FRAMING_ERR 0x08
# define COM_LINE_BREAK 0x10
# define COM_LINE_XMIT_HOLDING 0x20
# define COM_LINE_XMIT_EMPTY 0x40
# define COM_LINE_FIFO_ERR 0x80
#define COM_MODEM_STATUS 6
#define COM_SCRATCH 7
static int com;
static int irq_com;
static int uart; // is there a uart?
void
uartputc(char c)
{
int i;
if (!uart)
return;
for (i = 0; i < 128 && !(inb(com+COM_LINE_STATUS) & COM_LINE_XMIT_HOLDING);
i++)
microdelay(10);
#ifdef UART_SEND_DELAY_USEC
microdelay(UART_SEND_DELAY_USEC);
#endif
outb(com+COM_OUT_TRANSMIT, c);
#ifdef UART_SEND_DELAY_USEC
microdelay(UART_SEND_DELAY_USEC);
#endif
}
static int
uartgetc(void)
{
if (!uart)
return -1;
if (!(inb(com+COM_LINE_STATUS) & COM_LINE_DATA_READY))
return -1;
return inb(com+COM_IN_RECEIVE);
}
void
uartintr(void)
{
consoleintr(uartgetc);
}
void
inituart(void)
{
static struct {
int com;
int irq;
} conf[] = {
// Try COM2 (aka ttyS1) first, because it usually does SOL for IPMI.
{ COM2, IRQ_COM2 },
// Still try COM1 (aka ttyS0), because it is what QEMU emulates.
{ COM1, IRQ_COM1 },
};
int i;
#if defined(UART_BAUD)
int baud = UART_BAUD;
#else
int baud = 19200;
#endif
for (i = 0; i < 2; i++) {
com = conf[i].com;
irq_com = conf[i].irq;
// Turn off the FIFO
outb(com+COM_OUT_FIFO_CTL, 0);
// 19200 baud
outb(com+COM_LINE_CTL, COM_LINE_DLAB); // Unlock divisor
outb(com+COM_DIVISOR_LSB, 115200/baud);
outb(com+COM_DIVISOR_MSB, 0);
// 8 bits, one stop bit, no parity
outb(com+COM_LINE_CTL, COM_LINE_LEN_8); // Lock divisor, 8 data bits.
outb(com+COM_INT_EN, COM_INT_RECEIVE); // Enable receive interrupts.
// Data terminal ready
outb(com+COM_MODEM_CTL, 0x0);
// If status is 0xFF, no serial port.
if(inb(com+COM_LINE_STATUS) != 0xFF)
break;
}
if (i == 2)
return;
uart = 1;
// Clean up the serial console (beginning of line, erase down)
for (const char *p="\r\x1b[J"; *p; p++)
uartputc(*p);
// Announce that we're here.
for (const char *p=DEBUG?"xv6 DEBUG\n":"xv6\n"; *p; p++)
uartputc(*p);
}
void
inituartcons(void)
{
// Acknowledge pre-existing interrupt conditions;
// enable interrupts.
extpic->map_isa_irq(irq_com).enable();
inb(com+COM_IN_IIR);
inb(com+COM_IN_RECEIVE);
}
| manyabu/sv6 |
<|start_filename|>live-filters.lua<|end_filename|>
-- live-filters.lua
--
-- add, remove and toggle ffmpeg filters during mpv video playback
--
-- see default keybindings at end of file
--
-- based on <NAME>'s code for mpv-repl, a graphical REPL for mpv input commands (https://github.com/rossy/mpv-repl)
-- with some modified functions from <NAME>'s mpv-scripts (https://github.com/occivink/mpv-scripts)
--
-- MIT License
-- Copyright 2018 <NAME>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
-- to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-- IN THE SOFTWARE.
local utils = require 'mp.utils'
local options = require 'mp.options'
local assdraw = require 'mp.assdraw'
-- Default options
local opts = {
font = 'monospace',
['font-size'] = 16,
scale = 2,
}
options.read_options(opts)
function detect_platform()
local o = {}
-- Kind of a dumb way of detecting the platform but whatever
if mp.get_property_native('options/vo-mmcss-profile', o) ~= o then
return 'windows'
elseif mp.get_property_native('options/macos-force-dedicated-gpu', o) ~= o then
return 'macos'
end
return 'linux'
end
-- Pick a better default font for Windows and macOS
local platform = detect_platform()
if platform == 'windows' then
opts.font = 'Consolas'
elseif platform == 'macos' then
opts.font = 'Menlo'
end
function copy(obj, seen)
if type(obj) ~= 'table' then return obj end
if seen and seen[obj] then return seen[obj] end
local s = seen or {}
local res = setmetatable({}, getmetatable(obj))
s[obj] = res
for k, v in pairs(obj) do res[copy(k, s)] = copy(v, s) end
return res
end
-- List of ffmpeg video filters for automcompletion in REPL
-- Note: Not all ffmpeg filters are compatible with mpv. Depending on your hardware, some more intensive filters like "reverse"
-- are likekly to cause mpv to crash when applied in the middle of a video
local vfx_list = {
"alphamerge", "ass", "atadenoise", "avgblur", "bbox", "bench", "bitplanenoise", "blackdetect", "blackframe", "blend",
"boxblur", "bwdif", "chromakey", "ciescope", "codecview", "colorbalance", "colorchannelmixer", "colorkey", "colorlevels",
"colormatrix", "colorspace", "convolution", "convolve", "copy", "cover_rect", "crop", "cropdetect", "curves", "datascope",
"dctdnoiz", "deband", "deflate", "deflicker", "deinterlace_vaapi", "dejudder", "delogo", "deshake", "despill", "detelecine",
"dilation", "displace", "doubleweave", "drawbox", "drawgraph", "drawgrid", "drawtext", "edgedetect", "elbg", "eq", "erosion",
"fade", "fftfilt", "field", "fieldhint", "fieldorder", "find_rect", "floodfill", "format", "fps", "framepack", "framerate",
"framestep", "fspp", "gblur", "geq", "gradfun", "haldclut", "hflip", "histeq", "histogram", "hqdn3d", "hqx", "hue",
"hwdownload", "hwmap", "hwupload", "hwupload_cuda", "hysteresis", "idet", "il", "inflate", "interlace", "kerndeint",
"lenscorrection", "limiter", "loop", "lumakey", "lut", "lut2", "lut3d", "lutrgb", "lutyuv", "maskedclamp", "maskedmerge",
"mcdeint", "mestimate", "metadata", "midequalizer", "minterpolate", "mpdecimate", "negate", "nlmeans", "nnedi", "noformat",
"noise", "normalize", "null", "oscilloscope", "overlay", "owdenoise", "pad", "palettegen", "paletteuse", "perms", "perspective", "phase",
"pixdesctest", "pixscope", "pp", "pp7", "prewitt", "pseudocolor", "psnr", "pullup", "qp", "random", "readeia608", "readvitc",
"realtime", "remap", "removegrain", "removelogo", "repeatfields", "reverse", "roberts", "rotate", "sab", "scale", "scale_vaapi",
"scale2ref", "selectivecolor", "sendcmd", "separatefields", "setdar", "setfield", "setpts", "setsar", "settb", "showinfo",
"showpalette", "shuffleframes", "shuffleplanes", "sidedata", "signalstats", "smartblur", "sobel", "spp", "ssim", "stereo3d",
"subtitles", "super2xsai", "swaprect", "swapuv", "tblend", "telecine", "threshold", "thumbnail", "tile", "tinterlace", "tlut2",
"tonemap", "transpose", "trim", "unsharp", "uspp", "vaguedenoiser", "vectorscope", "vflip", "vignette", "vmafmotion", "w3fdif",
"waveform", "weave", "xbr", "yadif", "zmq", "zoompan", "fifo",
--frei0r filters require that your version of ffmpeg is built with frei0r library support
"frei0r=3dflippo", "frei0r=B", "frei0r=G", "frei0r=IIRblur", "frei0r=R", "frei0r=alpha0ps", "frei0r=alphagrad",
"frei0r=alphaspot", "frei0r=balanc0r", "frei0r=baltan", "frei0r=bgsubtract0r", "frei0r=bluescreen0r", "frei0r=brightness",
"frei0r=bw0r", "frei0r=c0rners", "frei0r=cairogradient", "frei0r=cairoimagegrid", "frei0r=cartoon", "frei0r=cluster",
"frei0r=colgate", "frei0r=coloradj_RGB", "frei0r=colordistance", "frei0r=colorhalftone", "frei0r=colorize",
"frei0r=colortap", "frei0r=contrast0r", "frei0r=curves", "frei0r=d90stairsteppingfix", "frei0r=defish0r",
"frei0r=delay0r", "frei0r=delaygrab", "frei0r=distort0r", "frei0r=dither", "frei0r=edgeglow", "frei0r=emboss",
"frei0r=equaliz0r", "frei0r=facebl0r", "frei0r=facedetect", "frei0r=flippo", "frei0r=gamma", "frei0r=glitch0r",
"frei0r=glow", "frei0r=hqdn3d", "frei0r=hueshift0r", "frei0r=invert0r", "frei0r=keyspillm0pup", "frei0r=lenscorrection",
"frei0r=letterb0xed", "frei0r=levels", "frei0r=lightgraffiti", "frei0r=luminance", "frei0r=mask0mate", "frei0r=medians",
"frei0r=ndvi", "frei0r=nervous", "frei0r=nosync0r", "frei0r=pixeliz0r", "frei0r=posterize", "frei0r=pr0be",
"frei0r=pr0file", "frei0r=primaries", "frei0r=rgbnoise", "frei0r=rgbparade", "frei0r=rgbsplit0r", "frei0r=saturat0r",
"frei0r=scale0tilt", "frei0r=scanline0r", "frei0r=select0r", "frei0r=sharpness", "frei0r=sigmoidaltransfer", "frei0r=sobel",
"frei0r=softglow", "frei0r=sopsat", "frei0r=spillsupress", "frei0r=squareblur", "frei0r=tehroxx0r", "frei0r=three_point_balance",
"frei0r=threelay0r", "frei0r=threshold0r", "frei0r=timeout", "frei0r=tint0r", "frei0r=transparency", "frei0r=twolay0r",
"frei0r=vectorscope", "frei0r=vignette",
}
-- ENTER SHORTCUTS FOR COMPLEX COMMANDS HERE...
local saved_cmds = {
mirrortop="\"lavfi=[[vid1]split[main][tmp];[tmp]crop=iw:ih/2:0:0,vflip[flip];[main][flip]overlay=0:H/2[vo]]\"",
mirrorbottom="\"lavfi=[[vid1]split[main][tmp];[tmp]crop=iw:ih/2:0:ih/2,vflip[flip];[main][flip]overlay[vo]]\"",
mirrorleft="\"lavfi=[[vid1]split[main][tmp];[tmp]crop=iw/2:ih:0:0,hflip[flip];[main][flip]overlay=W/2[vo]]\"",
mirrorright="\"lavfi=[[vid1]split[main][tmp];[tmp]crop=iw/2:ih:iw/2:0,hflip[flip];[main][flip]overlay[vo]]\"",
hstack="\"lavfi=[[vid1]split[v1][v2];[v1][v2]hstack[t]]\"",
vstack="\"lavfi=[[vid1]split[v1][v2];[v1][v2]vstack[t]]\"",
}
local prop_list = mp.get_property_native('property-list')
for _, opt in ipairs(mp.get_property_native('options')) do
prop_list[#prop_list + 1] = 'options/' .. opt
prop_list[#prop_list + 1] = 'file-local-options/' .. opt
prop_list[#prop_list + 1] = 'option-info/' .. opt
end
local repl_active = false
local insert_mode = false
local line = ''
local cursor = 1
local history = {}
local history_pos = 1
local log_ring = {}
-- Escape a string for verbatim display on the OSD
function ass_escape(str)
-- There is no escape for '\' in ASS (I think?) but '\' is used verbatim if
-- it isn't followed by a recognised character, so add a zero-width
-- non-breaking space
str = str:gsub('\\', '\\\239\187\191')
str = str:gsub('{', '\\{')
str = str:gsub('}', '\\}')
-- Precede newlines with a ZWNBSP to prevent ASS's weird collapsing of
-- consecutive newlines
str = str:gsub('\n', '\239\187\191\\N')
return str
end
-- Render the REPL and console as an ASS OSD
function update()
local screenx, screeny, aspect = mp.get_osd_size()
screenx = screenx / opts.scale
screeny = screeny / opts.scale
-- Clear the OSD if the REPL is not active
if not repl_active then
mp.set_osd_ass(screenx, screeny, '')
return
end
local ass = assdraw.ass_new()
local style = '{\\r' ..
'\\1a&H00&\\3a&H00&\\4a&H99&' ..
'\\1c&Heeeeee&\\3c&H111111&\\4c&H000000&' ..
'\\fn' .. opts.font .. '\\fs' .. opts['font-size'] ..
'\\bord2\\xshad0\\yshad1\\fsp0\\q1}'
-- Create the cursor glyph as an ASS drawing. ASS will draw the cursor
-- inline with the surrounding text, but it sets the advance to the width
-- of the drawing. So the cursor doesn't affect layout too much, make it as
-- thin as possible and make it appear to be 1px wide by giving it 0.5px
-- horizontal borders.
local cheight = opts['font-size'] * 8
local cglyph = '{\\r' ..
'\\1a&H44&\\3a&H44&\\4a&H99&' ..
'\\1c&Heeeeee&\\3c&Heeeeee&\\4c&H000000&' ..
'\\xbord0.5\\ybord0\\xshad0\\yshad1\\p4\\pbo24}' ..
'm 0 0 l 1 0 l 1 ' .. cheight .. ' l 0 ' .. cheight ..
'{\\p0}'
local before_cur = ass_escape(line:sub(1, cursor - 1))
local after_cur = ass_escape(line:sub(cursor))
-- Render log messages as ASS. This will render at most screeny / font-size
-- messages.
local log_ass = ''
local log_messages = #log_ring
local log_max_lines = math.ceil(screeny / opts['font-size'])
if log_max_lines < log_messages then
log_messages = log_max_lines
end
for i = #log_ring - log_messages + 1, #log_ring do
log_ass = log_ass .. style .. log_ring[i].style .. ass_escape(log_ring[i].text)
end
ass:new_event()
ass:an(1)
ass:pos(2, screeny - 2)
ass:append(log_ass .. '\\N')
ass:append(style .. '> ' .. before_cur)
ass:append(cglyph)
ass:append(style .. after_cur)
-- Redraw the cursor with the REPL text invisible. This will make the
-- cursor appear in front of the text.
ass:new_event()
ass:an(1)
ass:pos(2, screeny - 2)
ass:append(style .. '{\\alpha&HFF&}> ' .. before_cur)
ass:append(cglyph)
ass:append(style .. '{\\alpha&HFF&}' .. after_cur)
mp.set_osd_ass(screenx, screeny, ass.text)
end
-- Set the REPL visibility (`, Esc)
function set_active(active)
if active == repl_active then return end
if active then
repl_active = true
insert_mode = false
mp.enable_key_bindings('repl-input', 'allow-hide-cursor+allow-vo-dragging')
else
repl_active = false
mp.disable_key_bindings('repl-input')
end
update()
end
-- Show the repl if hidden and replace its contents with 'text'
-- (script-message-to repl type)
function show_and_type(text)
text = text or ''
-- Save the line currently being edited, just in case
if line ~= text and line ~= '' and history[#history] ~= line then
history[#history + 1] = line
end
line = text
cursor = line:len() + 1
history_pos = #history + 1
insert_mode = false
if repl_active then
update()
else
set_active(true)
end
end
-- Naive helper function to find the next UTF-8 character in 'str' after 'pos'
-- by skipping continuation bytes. Assumes 'str' contains valid UTF-8.
function next_utf8(str, pos)
if pos > str:len() then return pos end
repeat
pos = pos + 1
until pos > str:len() or str:byte(pos) < 0x80 or str:byte(pos) > 0xbf
return pos
end
-- As above, but finds the previous UTF-8 charcter in 'str' before 'pos'
function prev_utf8(str, pos)
if pos <= 1 then return pos end
repeat
pos = pos - 1
until pos <= 1 or str:byte(pos) < 0x80 or str:byte(pos) > 0xbf
return pos
end
-- Insert a character at the current cursor position (' '-'~', Shift+Enter)
function handle_char_input(c)
if insert_mode then
line = line:sub(1, cursor - 1) .. c .. line:sub(next_utf8(line, cursor))
else
line = line:sub(1, cursor - 1) .. c .. line:sub(cursor)
end
cursor = cursor + 1
update()
end
-- Remove the character behind the cursor (Backspace)
function handle_backspace()
if cursor <= 1 then return end
local prev = prev_utf8(line, cursor)
line = line:sub(1, prev - 1) .. line:sub(cursor)
cursor = prev
update()
end
-- Remove the character in front of the cursor (Del)
function handle_del()
if cursor > line:len() then return end
line = line:sub(1, cursor - 1) .. line:sub(next_utf8(line, cursor))
update()
end
-- Toggle insert mode (Ins)
function handle_ins()
insert_mode = not insert_mode
end
-- Move the cursor to the next character (Right)
function next_char(amount)
cursor = next_utf8(line, cursor)
update()
end
-- Move the cursor to the previous character (Left)
function prev_char(amount)
cursor = prev_utf8(line, cursor)
update()
end
-- Clear the current line (Ctrl+C)
function clear()
line = ''
cursor = 1
insert_mode = false
history_pos = #history + 1
update()
end
-- Close the REPL if the current line is empty, otherwise do nothing (Ctrl+D)
function maybe_exit()
if line == '' then
set_active(false)
end
end
-- Run the current command and clear the line (Enter)
function handle_enter()
if line == '' then
return
end
if history[#history] ~= line then
history[#history + 1] = line
end
-- See if text is a saved command (overwrites any actual filters which has the same name)
if saved_cmds[line] ~= nil then
line=saved_cmds[line]
end
mp.command('vf add '..line)
clear()
end
function handle_alt_enter()
if line == '' then
return
end
if history[#history] ~= line then
history[#history + 1] = line
end
mp.command('vf set '..line)
clear()
end
-- Go to the specified position in the command history
function go_history(new_pos)
local old_pos = history_pos
history_pos = new_pos
-- Restrict the position to a legal value
if history_pos > #history + 1 then
history_pos = #history + 1
elseif history_pos < 1 then
history_pos = 1
end
-- Do nothing if the history position didn't actually change
if history_pos == old_pos then
return
end
-- If the user was editing a non-history line, save it as the last history
-- entry. This makes it much less frustrating to accidentally hit Up/Down
-- while editing a line.
if old_pos == #history + 1 and line ~= '' and history[#history] ~= line then
history[#history + 1] = line
end
-- Now show the history line (or a blank line for #history + 1)
if history_pos <= #history then
line = history[history_pos]
else
line = ''
end
cursor = line:len() + 1
insert_mode = false
update()
end
-- Go to the specified relative position in the command history (Up, Down)
function move_history(amount)
go_history(history_pos + amount)
end
-- Go to the first command in the command history (PgUp)
function handle_pgup()
go_history(1)
end
-- Stop browsing history and start editing a blank line (PgDown)
function handle_pgdown()
go_history(#history + 1)
end
-- Move to the start of the current word, or if already at the start, the start
-- of the previous word. (Ctrl+Left)
function prev_word()
-- This is basically the same as next_word() but backwards, so reverse the
-- string in order to do a "backwards" find. This wouldn't be as annoying
-- to do if Lua didn't insist on 1-based indexing.
cursor = line:len() - select(2, line:reverse():find('%s*[^%s]*', line:len() - cursor + 2)) + 1
update()
end
-- Move to the end of the current word, or if already at the end, the end of
-- the next word. (Ctrl+Right)
function next_word()
cursor = select(2, line:find('%s*[^%s]*', cursor)) + 1
update()
end
-- List of tab-completions:
-- pattern: A Lua pattern used in string:find. Should return the start and
-- end positions of the word to be completed in the first and second
-- capture groups (using the empty parenthesis notation "()")
-- list: A list of candidate completion values.
-- append: An extra string to be appended to the end of a successful
-- completion. It is only appended if 'list' contains exactly one
-- match.
local completers = {
{ pattern = '^%s*()[%w_-]+()$', list = vfx_list, append = '' },
}
-- Use 'list' to find possible tab-completions for 'part.' Returns the longest
-- common prefix of all the matching list items and a flag that indicates
-- whether the match was unique or not.
function complete_match(part, list)
local completion = nil
local full_match = false
for _, candidate in ipairs(list) do
--print(candidate)
if candidate:sub(1, part:len()) == part then
if completion and completion ~= candidate then
local prefix_len = part:len()
while completion:sub(1, prefix_len + 1)
== candidate:sub(1, prefix_len + 1) do
prefix_len = prefix_len + 1
end
completion = candidate:sub(1, prefix_len)
full_match = false
else
completion = candidate
full_match = true
end
end
end
return completion, full_match
end
-- Complete the option or property at the cursor (TAB)
function complete()
local before_cur = line:sub(1, cursor - 1)
local after_cur = line:sub(cursor)
-- Try the first completer that works
for _, completer in ipairs(completers) do
local _, _, s, e = before_cur:find(completer.pattern)
local s = 1
--print(s)
--[[if not s then
-- Multiple input commands can be separated by semicolons, so all
-- completions that are anchored at the start of the string with
-- '^' can start from a semicolon as well. Replace ^ with ; and try
-- to match again.
_, _, s, e = before_cur:find(completer.pattern:gsub('^^', ';'))
end--]]
if s then
-- If the completer's pattern found a word, check the completer's
-- list for possible completions
local part = before_cur:sub(s, e)
local c, full = complete_match(part, completer.list)
if c then
-- If there was only one full match from the list, add
-- completer.append to the final string. This is normally a
-- space or a quotation mark followed by a space.
if full and completer.append then
c = c .. completer.append
end
-- Insert the completion and update
before_cur = before_cur:sub(1, s - 1) .. c
cursor = before_cur:len() + 1
line = before_cur .. after_cur
update()
return
end
end
end
end
-- Move the cursor to the beginning of the line (HOME)
function go_home()
cursor = 1
update()
end
-- Move the cursor to the end of the line (END)
function go_end()
cursor = line:len() + 1
update()
end
-- Delete from the cursor to the end of the word (Ctrl+W)
function del_word()
local before_cur = line:sub(1, cursor - 1)
local after_cur = line:sub(cursor)
before_cur = before_cur:gsub('[^%s]+%s*$', '', 1)
line = before_cur .. after_cur
cursor = before_cur:len() + 1
update()
end
-- Delete from the cursor to the end of the line (Ctrl+K)
function del_to_eol()
line = line:sub(1, cursor - 1)
update()
end
-- Delete from the cursor back to the start of the line (Ctrl+U)
function del_to_start()
line = line:sub(cursor)
cursor = 1
update()
end
-- Returns a string of UTF-8 text from the clipboard (or the primary selection)
function get_clipboard(clip)
if platform == 'linux' then
local res = utils.subprocess({
args = { 'xclip', '-selection', clip and 'clipboard' or 'primary', '-out' },
playback_only = false,
})
if not res.error then
return res.stdout
end
elseif platform == 'windows' then
local res = utils.subprocess({
args = { 'powershell', '-NoProfile', '-Command', [[& {
Trap {
Write-Error -ErrorRecord $_
Exit 1
}
$clip = ""
if (Get-Command "Get-Clipboard" -errorAction SilentlyContinue) {
$clip = Get-Clipboard -Raw -Format Text -TextFormatType UnicodeText
} else {
Add-Type -AssemblyName PresentationCore
$clip = [Windows.Clipboard]::GetText()
}
$clip = $clip -Replace "`r",""
$u8clip = [System.Text.Encoding]::UTF8.GetBytes($clip)
[Console]::OpenStandardOutput().Write($u8clip, 0, $u8clip.Length)
}]] },
playback_only = false,
})
if not res.error then
return res.stdout
end
elseif platform == 'macos' then
local res = utils.subprocess({
args = { 'pbpaste' },
playback_only = false,
})
if not res.error then
return res.stdout
end
end
return ''
end
-- Paste text from the window-system's clipboard. 'clip' determines whether the
-- clipboard or the primary selection buffer is used (on X11 only.)
function paste(clip)
local text = get_clipboard(clip)
local before_cur = line:sub(1, cursor - 1)
local after_cur = line:sub(cursor)
line = before_cur .. text .. after_cur
cursor = cursor + text:len()
update()
end
-- The REPL has pretty specific requirements for key bindings that aren't
-- really satisified by any of mpv's helper methods, since they must be in
-- their own input section, but they must also raise events on key-repeat.
-- Hence, this function manually creates an input section and puts a list of
-- bindings in it.
function add_repl_bindings(bindings)
local cfg = ''
for i, binding in ipairs(bindings) do
local key = binding[1]
local fn = binding[2]
local name = '__repl_binding_' .. i
mp.add_key_binding(nil, name, fn, 'repeatable')
cfg = cfg .. key .. ' script-binding ' .. mp.script_name .. '/' ..
name .. '\n'
end
mp.commandv('define-section', 'repl-input', cfg, 'force')
end
-- Mapping from characters to mpv key names
local binding_name_map = {
[' '] = 'SPACE',
['#'] = 'SHARP',
}
-- List of input bindings. This is a weird mashup between common GUI text-input
-- bindings and readline bindings.
local bindings = {
{ 'esc', function() set_active(false) end },
{ 'enter', handle_enter },
{ 'alt+enter', handle_alt_enter },
{ 'shift+enter', function() handle_char_input('\n') end },
{ 'bs', handle_backspace },
{ 'shift+bs', handle_backspace },
{ 'del', handle_del },
{ 'shift+del', handle_del },
{ 'ins', handle_ins },
{ 'shift+ins', function() paste(false) end },
{ 'mouse_btn1', function() paste(false) end },
{ 'left', function() prev_char() end },
{ 'right', function() next_char() end },
{ 'up', function() move_history(-1) end },
{ 'axis_up', function() move_history(-1) end },
{ 'mouse_btn3', function() move_history(-1) end },
{ 'down', function() move_history(1) end },
{ 'axis_down', function() move_history(1) end },
{ 'mouse_btn4', function() move_history(1) end },
{ 'axis_left', function() end },
{ 'axis_right', function() end },
{ 'ctrl+left', prev_word },
{ 'ctrl+right', next_word },
{ 'tab', complete },
{ 'home', go_home },
{ 'end', go_end },
{ 'pgup', handle_pgup },
{ 'pgdwn', handle_pgdown },
{ 'ctrl+c', clear },
{ 'ctrl+d', maybe_exit },
{ 'ctrl+k', del_to_eol },
{ 'ctrl+u', del_to_start },
{ 'ctrl+v', function() paste(true) end },
{ 'meta+v', function() paste(true) end },
{ 'ctrl+w', del_word },
}
-- Add bindings for all the printable US-ASCII characters from ' ' to '~'
-- inclusive. Note, this is a pretty hacky way to do text input. mpv's input
-- system was designed for single-key key bindings rather than text input, so
-- things like dead-keys and non-ASCII input won't work. This is probably okay
-- though, since all mpv's commands and properties can be represented in ASCII.
for b = (' '):byte(), ('~'):byte() do
local c = string.char(b)
local binding = binding_name_map[c] or c
bindings[#bindings + 1] = {binding, function() handle_char_input(c) end}
end
add_repl_bindings(bindings)
-- Add a script-message to show the REPL and fill it with the provided text
mp.register_script_message('type', function(text)
show_and_type(text)
end)
-- Redraw the REPL when the OSD size changes. This is needed because the
-- PlayRes of the OSD will need to be adjusted.
mp.observe_property('osd-width', 'native', update)
mp.observe_property('osd-height', 'native', update)
-- Watch for log-messages and print them in the REPL console
mp.enable_messages('info')
--functions for removing/toggling filters
local filters_undo_stack = {}
function toggle()
local vf_table = mp.get_property_native("vf")
if #vf_table == 0 then
if #filters_undo_stack == 0 then
return
end
for i = 1, #filters_undo_stack do
print(i)
vf_table[#vf_table + 1] = filters_undo_stack[#filters_undo_stack + 1 -i]
end
filters_undo_stack = {}
mp.set_property_native("vf", vf_table)
return
end
for i = 1, #vf_table do
print(i..'!')
filters_undo_stack[#filters_undo_stack + 1] = vf_table[#vf_table + 1 - i]
end
mp.set_property_native("vf", {})
end
function remove_last_filter()
local vf_table = mp.get_property_native("vf")
if #vf_table == 0 then
return
end
filters_undo_stack[#filters_undo_stack + 1] = vf_table[#vf_table]
vf_table[#vf_table] = nil
mp.set_property_native("vf", vf_table)
end
function undo_filter_removal()
if #filters_undo_stack == 0 then
return
end
local vf_table = mp.get_property_native("vf")
vf_table[#vf_table + 1] = filters_undo_stack[#filters_undo_stack]
filters_undo_stack[#filters_undo_stack] = nil
mp.set_property_native("vf", vf_table)
end
function clear_filters()
local vf_table = mp.get_property_native("vf")
if #vf_table == 0 then
return
end
for i = 1, #vf_table do
filters_undo_stack[#filters_undo_stack + 1] = vf_table[#vf_table + 1 - i]
end
mp.set_property_native("vf", {})
end
mp.add_key_binding('`', 'repl-enable', function()
set_active(true)
end)
mp.add_key_binding('ctrl+x', "toggle-filter", toggle)
mp.add_key_binding('ctrl+shift+x', "clear-filters", clear_filters)
mp.add_key_binding('ctrl+z', "remove-last-filter", remove_last_filter)
mp.add_key_binding('ctrl+shift+z', "undo-filter-removal", undo_filter_removal) | hdb/mpv-live-filters |
<|start_filename|>Makefile<|end_filename|>
build-app:
shards build --link-flags="-rpath @executable_path/../Frameworks -L`pwd`/vendor"
cp ./bin/MyCocoaApplication ./build/MyCocoaApplication.app/Contents/MacOS/
cp ./vendor/Frameworks/libui.A.dylib ./build/MyCocoaApplication.app/Contents/Frameworks/
run: build-app
#open ./build/MyCocoaApplication.app
./build/MyCocoaApplication.app/Contents/MacOS/MyCocoaApplication
package:
shards build --release --link-flags="-rpath @executable_path/../Frameworks -L`pwd`/vendor"
cp ./bin/MyCocoaApplication ./build/MyCocoaApplication.app/Contents/MacOS/
cp ./vendor/Frameworks/libui.A.dylib ./build/MyCocoaApplication.app/Contents/Frameworks/
inspect:
otool -L ./bin/app
validate:
otool -L ./bin/app | grep local | Iainmon/Cocoa.cr |
<|start_filename|>src/App.js<|end_filename|>
import React, { Component } from 'react'
import axios from 'axios'
import './bootstrap.css'
import './App.css'
const formAPI = '/.netlify/functions/signup'
export default class App extends Component {
state = {
loading: false,
success: false,
error: false
}
handleSubmit = (event, data) => {
event.preventDefault()
const email = this.email.value
if (!email) {
alert('Please email your email')
}
this.setState({
loading: true
})
formHandler(email).then(() => {
this.setState({
success: true,
loading: false
})
}).catch((e) => {
this.setState({
error: true,
loading: false
})
})
}
renderForm() {
const { success, loading } = this.state
const buttonText = (loading) ? '...' : 'Notify Me'
const handler = (loading) ? noOp : this.handleSubmit
/* if they submitted the form, show thanks */
if (success) {
return (
<div>
<h2>Thanks for signing up!</h2>
</div>
)
}
return (
<form onSubmit={handler}>
<input
type="email"
name="email"
className="sign-up"
ref={input => this.email = input}
placeholder="Enter your email address..."
required
/>
<button className="btn btn-lg btn-green sign-up-button" type="submit">
{buttonText}
</button>
</form>
)
}
render() {
return (
<div className="App">
<div className="landing-page">
<div className='backdrop'></div>
<div className='container'>
<div className="row centered">
<h3 className="logo aligncenter">
Netlify functions landing page example
</h3>
<h1>
Sign up to get notified<br/>when we launch!
</h1>
<div className="col-md-6 col-md-offset-3 mt">
{this.renderForm()}
</div>
</div>
<div className="row">
<div className="continue">
<i className="ion-chevron-down"></i>
</div>
</div>
</div>
</div>
</div>
)
}
}
function formHandler(email) {
const data = {
email: email
}
return axios({
method: 'post',
url: formAPI,
data: data,
})
}
function noOp() {
console.log('submission in progress')
} | tobilg/netlify-functions-landingpage |
<|start_filename|>app/src/main/java/com/adapty/example/promopush/YourFirebaseMessagingService.kt<|end_filename|>
package com.adapty.example.promopush
/**
* Setup Firebase Cloud Messaging (https://firebase.google.com/docs/cloud-messaging/android/client),
* add your google-services.json and uncomment this section
*
* Don't forget to declare the service in your AndroidManifest.xml
*/
//import com.adapty.Adapty
//import com.google.firebase.messaging.FirebaseMessagingService
//import com.google.firebase.messaging.RemoteMessage
//
//class YourFirebaseMessagingService : FirebaseMessagingService() {
//
// private val pushHandler: YourAdaptyPushHandler by lazy {
// YourAdaptyPushHandler(this)
// }
//
// override fun onNewToken(p0: String) {
// super.onNewToken(p0)
// Adapty.refreshPushToken(p0)
// }
//
// override fun onMessageReceived(p0: RemoteMessage) {
// super.onMessageReceived(p0)
// if (!pushHandler.handleNotification(p0.data)) {
// /*
// here is your logic for other notifications
// that haven't been handled by Adapty
// */
// }
// }
//}
<|start_filename|>app/src/main/java/com/adapty/example/MainActivity.kt<|end_filename|>
package com.adapty.example
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.adapty.Adapty
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
addFragment(MainFragment.newInstance(), false)
}
handleIntent(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleIntent(intent)
}
private fun handleIntent(intent: Intent) {
if (Adapty.handlePromoIntent(intent) { promo, error ->
//your logic for callback
}
) {
//your logic for the case user did click on promo notification,
//for example show loading indicator
} else {
//your logic for other cases
}
}
fun addFragment(fragment: Fragment, addToBackStack: Boolean) {
supportFragmentManager
.beginTransaction()
.add(R.id.container, fragment)
.apply { if (addToBackStack) this.addToBackStack(null) }
.commit()
}
} | ditansu/AdaptySDK-Android |
<|start_filename|>app/src/test/java/me/hufman/androidautoidrive/NavTriggerTest.kt<|end_filename|>
package me.hufman.androidautoidrive
import android.location.Address
import com.nhaarman.mockito_kotlin.*
import me.hufman.androidautoidrive.carapp.navigation.AddressSearcher
import me.hufman.androidautoidrive.carapp.navigation.NavigationParser
import me.hufman.androidautoidrive.carapp.navigation.NavigationTriggerApp
import me.hufman.androidautoidrive.carapp.navigation.URLRedirector
import io.bimmergestalt.idriveconnectkit.rhmi.RHMIAction
import io.bimmergestalt.idriveconnectkit.rhmi.RHMIApplicationConcrete
import io.bimmergestalt.idriveconnectkit.rhmi.RHMIEvent
import io.bimmergestalt.idriveconnectkit.rhmi.RHMIModel
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
class NavTriggerTest {
lateinit var addressSearcher: AddressSearcher
var redirector = mock<URLRedirector>()
lateinit var parser: NavigationParser
@Before
fun setUp() {
addressSearcher = mock()
parser = NavigationParser(addressSearcher, redirector)
}
@Test
fun testParseUrl() {
assertNull(parser.parseUrl("smtp:lol"))
}
@Test
fun testParseGeo() {
val invalid = "geo:abc"
val incorrect = parser.parseUrl(invalid)
assertNull(incorrect)
val geo = "geo:37.786971,+-122.399677+;u=35"
val parsed = parser.parseUrl(geo)
assertEquals(";;;;;;;450816123.84535134;-1460285026.4199002;", parsed)
val geoQuery = "geo:0,0?q=37.330593+,-121.859425"
val parsedQuery = parser.parseUrl(geoQuery)
assertEquals(";;;;;;;445371322.2239593;-1453839569.0017943;", parsedQuery)
val geoLabel = "geo:0,0?q=37.330593,-121.859425%28Main+Street%29"
val parsedLabel = parser.parseUrl(geoLabel)
assertEquals(";;;;;;;445371322.2239593;-1453839569.0017943;Main Street", parsedLabel)
val geoSpaceLabel = "geo:0,0?q=37.330593,-121.859425+%28Main+Street%29"
val parsedSpaceLabel = parser.parseUrl(geoSpaceLabel)
assertEquals(";;;;;;;445371322.2239593;-1453839569.0017943;Main Street", parsedSpaceLabel)
val geoWhiteSpaceLabel = "geo:0,0?q=37.330593,-121.859425 (Main Street)"
val parsedWhiteSpaceLabel = parser.parseUrl(geoWhiteSpaceLabel)
assertEquals(";;;;;;;445371322.2239593;-1453839569.0017943;Main Street", parsedWhiteSpaceLabel)
// free form query
val addressResult = mock<Address> {
on { latitude } doReturn 37.7773
on { longitude } doReturn -122.41
on { thoroughfare } doReturn "1970 Naglee Ave"
on { locality } doReturn "San Jose, CA"
on { postalCode } doReturn "95126"
on { countryCode } doReturn "US"
}
whenever(addressSearcher.search(any())) doReturn addressResult
val correctAnswer = ";;Naglee Ave;1970;95126;San Jose, CA;US;450700744.3211838;-1460408184.6070554;"
val geoAddress = "geo:0,0?q=1970+Naglee+Ave+San+Jose,+CA+95126"
val addressParsed = parser.parseUrl(geoAddress)
assertEquals(correctAnswer, addressParsed)
val geoWhitespaceAddress = "geo:0,0?q=1970 Naglee Ave San Jose, CA 95126"
val addressWhitespaceParsed = parser.parseUrl(geoWhitespaceAddress)
assertEquals(correctAnswer, addressWhitespaceParsed)
// unknown address
whenever(addressSearcher.search(any())) doReturn null
val empty = parser.parseUrl("geo:0,0?q=")
assertNull(empty)
val unknown = parser.parseUrl("geo:0,0?q=missingLocation")
assertNull(unknown)
}
@Test
fun testParsePlusCode() {
val invalid = parser.parseUrl("https://plus.codes/849QJQ5+XX")
assertNull(invalid)
val parsed = parser.parseUrl("http://plus.codes/849VQJQ5+XX")
assertEquals(";;;;;;;450851515.5689004;-1460170320.9669886;", parsed)
val invalidShort = parser.parseUrl("https://plus.codes/QJQ5+XX")
assertNull(invalidShort)
val cantParseShort = parser.parseUrl("https://plus.codes/QJQ5+XX,San%20Francisco")
assertNull(cantParseShort)
val googleOlc = parser.parseUrl("https://www.google.com/maps/dir//849VQJQ5+XX")
assertEquals(";;;;;;;450851515.5689004;-1460170320.9669886;", googleOlc)
val addressResult = mock<Address> {
on { latitude } doReturn 37.7773
on { longitude } doReturn -122.41
}
whenever(addressSearcher.search(eq("San Francisco"))) doReturn addressResult
val canParseShort = parser.parseUrl("https://plus.codes/QJQ5+XX,San%20Francisco")
assertEquals(";;;;;;;450851515.5689004;-1460170320.9669886;", canParseShort)
val googleShortOlc = parser.parseUrl("https://www.google.com/maps/dir//QJQ5+XX%20San%20Francisco")
assertEquals(";;;;;;;450851515.5689004;-1460170320.9669886;", googleShortOlc)
}
@Test
fun testParseGoogle() {
val zanotto = "http://maps.google.com/maps?q=1970+Naglee+Ave+San+Jose,+CA+95126;&ie=UTF8&hl=en&hq=&ll=37.335378,-121.931098&spn=0,359.967062"
assertEquals(";;;;;;;445428409.4975754;-1454694661.1986356;1970 Naglee Ave San Jose, CA 95126 ", parser.parseUrl(zanotto))
val officialExample = "https://www.google.com/maps/search/?api=1&query=47.5951518+,-122.3316393"
assertEquals(";;;;;;;567832278.7054589;-1459473305.041403;", parser.parseUrl(officialExample))
val officialDirExample = "https://www.google.com/maps/dir/?api=1&destination=47.5951518,+-122.3316393"
assertEquals(";;;;;;;567832278.7054589;-1459473305.041403;", parser.parseUrl(officialDirExample))
val dirPath = "https://www.google.com/maps/dir/Current+Location/47.5951518+,-122.3316393"
assertEquals(";;;;;;;567832278.7054589;-1459473305.041403;", parser.parseUrl(dirPath))
val intentUrl = "google.navigation:q=47.5951518,-122.3316393"
assertEquals(";;;;;;;567832278.7054589;-1459473305.041403;", parser.parseUrl(intentUrl))
// more formats from https://stackoverflow.com/questions/2660201/
val pathPlace = "http://maps.google.com/maps/place/%3Cname%3E/@47.5951518+,-122.3316393,15z"
assertEquals(";;;;;;;567832278.7054589;-1459473305.041403;<name>", parser.parseUrl(pathPlace))
val searchPath = "https://www.google.com/maps/search/47.5951518,-122.3316393"
assertEquals(";;;;;;;567832278.7054589;-1459473305.041403;", parser.parseUrl(searchPath))
val locQuery = "http://maps.google.co.uk/maps?q=loc:+47.5951518,-122.3316393&z=15"
assertEquals(";;;;;;;567832278.7054589;-1459473305.041403;", parser.parseUrl(locQuery))
val zanottoQuery = "http://maps.google.com/?q=1970+Naglee+Ave+San+Jose,+CA+95126;&ie=UTF8&hl=en&hq=&ll=37.335378,-121.931098&spn=0,359.967062"
assertEquals(";;;;;;;445428409.4975754;-1454694661.1986356;1970 Naglee Ave San Jose, CA 95126 ", parser.parseUrl(zanottoQuery))
val llQuery = "https://maps.google.de/maps?q=47.5951518,-122.3316393&z=17&t=k"
assertEquals(";;;;;;;567832278.7054589;-1459473305.041403;", parser.parseUrl(llQuery))
}
@Test
fun testParseGoogleQueries() {
// without a valid address searcher
val emptyAddress = "http://maps.google.com/maps?q=1970+Naglee+Ave+San+Jose,+CA+95126&ie=UTF8"
assertNull(parser.parseUrl(emptyAddress))
val emptyUrl = "google.navigation:q=1970+Naglee+Ave+San+Jose,+CA+95126"
assertNull(parser.parseUrl(emptyUrl))
val addressResult = mock<Address> {
on { latitude } doReturn 37.7773
on { longitude } doReturn -122.41
on { thoroughfare } doReturn "1970 Naglee Ave"
on { locality } doReturn "San Jose, CA"
on { postalCode } doReturn "95126"
on { countryCode } doReturn "US"
}
whenever(addressSearcher.search(eq("1970 Naglee Ave San Jose, CA 95126"))) doReturn addressResult
val correctAnswer = ";;Naglee Ave;1970;95126;San Jose, CA;US;450700744.3211838;-1460408184.6070554;"
val zanotto = "http://maps.google.com/maps?q=1970+Naglee+Ave+San+Jose,+CA+95126&ie=UTF8"
assertEquals(correctAnswer, parser.parseUrl(zanotto))
val zanottoQuery = "http://maps.google.com/?q=1970+Naglee+Ave+San+Jose,+CA+95126"
assertEquals(correctAnswer, parser.parseUrl(zanottoQuery))
val officialExample = "https://www.google.com/maps/search/?api=1&query=1970+Naglee+Ave+San+Jose,+CA+95126&query_place_id=unknown"
assertEquals(correctAnswer, parser.parseUrl(officialExample))
val officialDirExample = "https://www.google.com/maps/dir/?api=1&destination=1970+Naglee+Ave+San+Jose,+CA+95126&travelmode=driving"
assertEquals(correctAnswer, parser.parseUrl(officialDirExample))
val intentUrl = "google.navigation:q=1970+Naglee+Ave+San+Jose,+CA+95126&mode=d"
assertEquals(correctAnswer, parser.parseUrl(intentUrl))
val daddr = "http://maps.google.com/maps?saddr=1970+Naglee+Ave+San+Jose,+CA+95126&daddr=1970%20Naglee%20Ave%20San%20Jose,%20CA%2095126"
assertEquals(correctAnswer, parser.parseUrl(daddr))
val pathDirQuery = "https://www.google.com/maps/dir//1970%20Naglee%20Ave%20San%20Jose,%20CA%2095126"
assertEquals(correctAnswer, parser.parseUrl(pathDirQuery))
val pathPlaceQuery = "https://www.google.com/maps/place/1970%20Naglee%20Ave%20San%20Jose,%20CA%2095126"
assertEquals(correctAnswer, parser.parseUrl(pathPlaceQuery))
val pathSearchQuery = "https://www.google.com/maps/search/1970%20Naglee%20Ave%20San%20Jose,%20CA%2095126"
assertEquals(correctAnswer, parser.parseUrl(pathSearchQuery))
}
@Test
fun testGoogleRedirect() {
// handle a maps.app.goo.gl redirect
whenever(redirector.tryRedirect("https://maps.app.goo.gl/test")) doReturn "https://maps.google.de/maps?q=47.5951518,-122.3316393&z=17&t=k"
whenever(redirector.tryRedirect("https://goo.gl/maps/test")) doReturn "https://maps.google.de/maps?q=47.5951518,-122.3316393&z=17&t=k"
val mapsShortener = "https://maps.app.goo.gl/test"
assertEquals(";;;;;;;567832278.7054589;-1459473305.041403;", parser.parseUrl(mapsShortener))
val googShortener = "https://goo.gl/maps/test"
assertEquals(";;;;;;;567832278.7054589;-1459473305.041403;", parser.parseUrl(googShortener))
// redirects to an unknown location
val otherwise = "https://somewhere.com/test"
assertEquals(null, parser.parseUrl(otherwise))
}
@Test
fun testNavTrigger() {
val app = RHMIApplicationConcrete()
val navModel = RHMIModel.RaDataModel(app, 550)
val navAction = RHMIAction.LinkAction(app, 563)
navAction.linkModel = navModel.id
navAction.actionType = "navigate"
val navEvent = RHMIEvent.ActionEvent(app, 3)
navEvent.action = navAction.id
app.models[navModel.id] = navModel
app.actions[navAction.id] = navAction
app.events[navEvent.id] = navEvent
val trigger = NavigationTriggerApp(app)
trigger.triggerNavigation("Test")
assertEquals("Test", navModel.value)
assertTrue(app.triggeredEvents.containsKey(navEvent.id))
}
}
<|start_filename|>app/src/main/java/me/hufman/androidautoidrive/carapp/InputState.kt<|end_filename|>
package me.hufman.androidautoidrive.carapp
import android.util.Log
import io.bimmergestalt.idriveconnectkit.rhmi.*
/** Handles letter entry from the car's input widget */
abstract class InputState<T:Any>(val state: RHMIState) {
var input = ""
var suggestions: MutableList<T> = ArrayList()
val inputComponent = state.componentsList.filterIsInstance<RHMIComponent.Input>().first()
companion object {
const val TAG = "InputState"
fun fits(state: RHMIState): Boolean {
return state.componentsList.size == 1 &&
state.componentsList[0] is RHMIComponent.Input
}
}
init {
// show any suggestions right when it shows up
state.focusCallback = FocusCallback { focus ->
if (focus) {
onEntry(input)
}
}
inputComponent.getAction()?.asRAAction()?.rhmiActionCallback = RHMIActionSpellerCallback { letter ->
Log.i(TAG, "Received speller input $letter")
onInput(letter)
}
inputComponent.getSuggestAction()?.asRAAction()?.rhmiActionCallback = RHMIActionListCallback { index ->
val suggestion = suggestions.getOrNull(index)
if (suggestion == null) {
Log.w(TAG, "Car selected input suggestion $index which was not found in the list of suggestions")
} else {
onSelect(suggestion, index)
}
}
inputComponent.getResultAction()?.asRAAction()?.rhmiActionCallback = RHMIActionButtonCallback {
onOk()
}
inputComponent.getResultModel()?.asRaDataModel()?.value = ""
inputComponent.getSuggestModel()?.setValue(RHMIModel.RaListModel.RHMIListConcrete(1),0,0, 0)
}
/**
* Called when the ok button is clicked. Does nothing by default.
*/
open fun onOk() {
}
open fun sendSuggestions(newSuggestions: List<T>) {
synchronized(this) {
suggestions.clear()
suggestions.addAll(newSuggestions)
}
val outputListModel = inputComponent.getSuggestModel() ?: return
val outputList = RHMIModel.RaListModel.RHMIListConcrete(1)
newSuggestions.forEach { outputList.addRow(arrayOf(convertRow(it))) }
outputListModel.setValue(outputList, 0, outputList.height, outputList.height)
}
fun onInput(letter: String) {
when (letter) {
"delall" -> input = ""
"del" -> input = input.dropLast(1)
else -> input += letter
}
inputComponent.getResultModel()?.asRaDataModel()?.value = input
onEntry(input)
}
/**
* After a user inputs a letter, or a vocal word, or a delete command
* This callback is called with the new complete input string
* This callback should call sendSuggestions() to update the list of suggestions
*/
abstract fun onEntry(input: String)
/**
* This callback is called when the user selects a suggestion
*/
abstract fun onSelect(item: T, index: Int)
/**
* This function converts a suggestion item to a displayable text string
*/
open fun convertRow(row: T): String {
return row.toString()
}
}
<|start_filename|>app/src/test/java/me/hufman/androidautoidrive/FullImageViewTest.kt<|end_filename|>
package me.hufman.androidautoidrive
import com.nhaarman.mockito_kotlin.*
import io.bimmergestalt.idriveconnectkit.GenericRHMIDimensions
import me.hufman.androidautoidrive.carapp.*
import me.hufman.androidautoidrive.carapp.maps.MapAppMode
import me.hufman.androidautoidrive.utils.removeFirst
import io.bimmergestalt.idriveconnectkit.rhmi.RHMIApplicationConcrete
import io.bimmergestalt.idriveconnectkit.rhmi.RHMIProperty
import io.bimmergestalt.idriveconnectkit.rhmi.RHMIState
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import java.util.*
class FullImageViewTest {
private lateinit var fullImageState: RHMIState
private lateinit var carApp: RHMIApplicationConcrete
@Before
fun setUp() {
val widgetStream = this.javaClass.classLoader!!.getResourceAsStream("ui_description_onlineservices_v2.xml")
this.carApp = RHMIApplicationConcrete()
this.carApp.loadFromXML(widgetStream?.readBytes() as ByteArray)
val unclaimedStates = LinkedList(carApp.states.values)
this.fullImageState = unclaimedStates.removeFirst { FullImageView.fits(it) }
}
@Test
fun testInitialize() {
val appSettings = MockAppSettings()
appSettings[AppSettings.KEYS.MAP_WIDESCREEN] = "false"
val fullImageConfig = MapAppMode(GenericRHMIDimensions(1280, 480), appSettings)
val fullImageView = FullImageView(this.fullImageState, "Map", fullImageConfig, mock(), mock())
fullImageView.initWidgets()
assertEquals(703, fullImageView.imageComponent.properties[RHMIProperty.PropertyId.WIDTH.id]?.value)
assertEquals(480, fullImageView.imageComponent.properties[RHMIProperty.PropertyId.HEIGHT.id]?.value)
appSettings[AppSettings.KEYS.MAP_WIDESCREEN] = "true"
fullImageView.initWidgets()
assertEquals(1211, fullImageView.imageComponent.properties[RHMIProperty.PropertyId.WIDTH.id]?.value)
assertEquals(480, fullImageView.imageComponent.properties[RHMIProperty.PropertyId.HEIGHT.id]?.value)
}
@Test
fun testInteraction() {
val appSettings = MockAppSettings()
appSettings[AppSettings.KEYS.MAP_INVERT_SCROLL] = "false"
val fullImageConfig = MapAppMode(GenericRHMIDimensions(1280, 480), appSettings)
val mockInteraction = mock<FullImageInteraction> {
on { getClickState() } doReturn RHMIState.PlainState(carApp, 99)
}
val fullImageView = FullImageView(this.fullImageState, "Map", fullImageConfig, mockInteraction, mock())
fullImageView.initWidgets()
// handle a bookmark click
fullImageView.inputList.getAction()?.asRAAction()?.rhmiActionCallback?.onActionEvent(mapOf(1.toByte() to 3, 43.toByte() to 2))
assertEquals(fullImageState.id, carApp.triggeredEvents[6]?.get(0))
verify(mockInteraction, never()).click()
// navigate up
fullImageView.inputList.getSelectAction()?.asRAAction()?.rhmiActionCallback?.onActionEvent(mapOf(1.toByte() to 2))
verify(mockInteraction).navigateUp()
// it should reset the focus back to the middle of the list
assertEquals("Reset scroll back to neutral" , 3, carApp.triggeredEvents[6]?.get(41))
assertEquals("Reset scroll back to neutral" , fullImageView.inputList.id, carApp.triggeredEvents[6]?.get(0))
// navigate down
fullImageView.inputList.getSelectAction()?.asRAAction()?.rhmiActionCallback?.onActionEvent(mapOf(1.toByte() to 4))
verify(mockInteraction).navigateUp()
// it should reset the focus back to the middle of the list
assertEquals("Reset scroll back to neutral" , 3, carApp.triggeredEvents[6]?.get(41))
assertEquals("Reset scroll back to neutral" , fullImageView.inputList.id, carApp.triggeredEvents[6]?.get(0))
// try inverted mode
appSettings[AppSettings.KEYS.MAP_INVERT_SCROLL] = "true"
fullImageView.inputList.getSelectAction()?.asRAAction()?.rhmiActionCallback?.onActionEvent(mapOf(1.toByte() to 2))
verify(mockInteraction, times(2)).navigateDown() // inverted
// try to click
fullImageView.inputList.getAction()?.asRAAction()?.rhmiActionCallback?.onActionEvent(mapOf(1.toByte() to 3))
assertEquals(99, carApp.triggeredEvents[6]?.get(0))
verify(mockInteraction).getClickState()
verify(mockInteraction).click()
}
}
<|start_filename|>app/src/main/java/me/hufman/androidautoidrive/phoneui/fragments/MapsPageFragment.kt<|end_filename|>
package me.hufman.androidautoidrive.phoneui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import me.hufman.androidautoidrive.databinding.MapPageSettingsBinding
import me.hufman.androidautoidrive.phoneui.controllers.MapsPageController
import me.hufman.androidautoidrive.phoneui.controllers.PermissionsController
import me.hufman.androidautoidrive.phoneui.viewmodels.MapSettingsModel
import me.hufman.androidautoidrive.phoneui.viewmodels.PermissionsModel
import me.hufman.androidautoidrive.phoneui.viewmodels.viewModels
class MapsPageFragment: Fragment() {
val mapSettingsModel by viewModels<MapSettingsModel> { MapSettingsModel.Factory(requireContext().applicationContext) }
val permissionsModel by viewModels<PermissionsModel> { PermissionsModel.Factory(requireContext().applicationContext) }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val permissionsController by lazy { PermissionsController(requireActivity()) }
val mapsPageController by lazy { MapsPageController(mapSettingsModel, permissionsModel, permissionsController) }
val binding = MapPageSettingsBinding.inflate(inflater, container, false)
binding.lifecycleOwner = viewLifecycleOwner
binding.settings = mapSettingsModel
binding.controller = mapsPageController
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// clear the checkbox if we don't yet have location permission
permissionsModel.hasLocationPermission.observe(viewLifecycleOwner) {
if (!it) {
mapSettingsModel.mapEnabled.setValue(false)
}
}
}
override fun onResume() {
super.onResume()
// update the model, used in the controller to know to show the prompt
permissionsModel.update()
}
}
<|start_filename|>app/src/nomap/java/me/hufman/androidautoidrive/MapService.kt<|end_filename|>
package me.hufman.androidautoidrive
import android.content.Context
import me.hufman.androidautoidrive.carapp.maps.MapAppMode
import io.bimmergestalt.idriveconnectkit.android.IDriveConnectionStatus
import io.bimmergestalt.idriveconnectkit.android.security.SecurityAccess
class MapService(val context: Context, val iDriveConnectionStatus: IDriveConnectionStatus, val securityAccess: SecurityAccess, val mapAppMode: MapAppMode) {
fun start(): Boolean {
return false
}
fun stop() {
}
}
<|start_filename|>app/src/main/java/me/hufman/androidautoidrive/phoneui/controllers/MapsPageController.kt<|end_filename|>
package me.hufman.androidautoidrive.phoneui.controllers
import me.hufman.androidautoidrive.phoneui.viewmodels.MapSettingsModel
import me.hufman.androidautoidrive.phoneui.viewmodels.PermissionsModel
class MapsPageController(val mapSettingsModel: MapSettingsModel,
val permissionsModel: PermissionsModel,
val permissionsController: PermissionsController) {
fun onChangedSwitchGMaps(isChecked: Boolean) {
mapSettingsModel.mapEnabled.setValue(isChecked)
if (isChecked) {
// make sure we have permissions to show current location
if (permissionsModel.hasLocationPermission.value != true) {
permissionsController.promptLocation()
}
}
}
}
<|start_filename|>app/src/main/java/me/hufman/androidautoidrive/NotificationService.kt<|end_filename|>
package me.hufman.androidautoidrive
import android.content.Context
import android.content.Intent
import android.provider.Settings
import android.util.Log
import io.bimmergestalt.idriveconnectkit.android.CarAppAssetResources
import io.bimmergestalt.idriveconnectkit.android.IDriveConnectionStatus
import io.bimmergestalt.idriveconnectkit.android.security.SecurityAccess
import me.hufman.androidautoidrive.carapp.notifications.ID5StatusbarApp
import me.hufman.androidautoidrive.carapp.notifications.NotificationSettings
import me.hufman.androidautoidrive.carapp.notifications.PhoneNotifications
import me.hufman.androidautoidrive.carapp.notifications.ReadoutApp
import me.hufman.androidautoidrive.connections.BtStatus
import me.hufman.androidautoidrive.notifications.AudioPlayer
import me.hufman.androidautoidrive.notifications.CarNotificationControllerIntent
import me.hufman.androidautoidrive.notifications.NotificationListenerServiceImpl
import me.hufman.androidautoidrive.utils.GraphicsHelpersAndroid
class NotificationService(val context: Context, val iDriveConnectionStatus: IDriveConnectionStatus, val securityAccess: SecurityAccess, val carInformationObserver: CarInformationObserver) {
var threadNotifications: CarThread? = null
var carappNotifications: PhoneNotifications? = null
var carappStatusbar: ID5StatusbarApp? = null
var carappReadout: ReadoutApp? = null
var running = false
fun start(): Boolean {
if (AppSettings[AppSettings.KEYS.ENABLED_NOTIFICATIONS].toBoolean()) {
running = true
synchronized(this) {
if (carInformationObserver.capabilities.isNotEmpty() && threadNotifications?.isAlive != true) {
threadNotifications = CarThread("Notifications") {
Log.i(MainService.TAG, "Starting notifications app")
val handler = threadNotifications?.handler
if (handler == null) {
Log.e(MainService.TAG, "CarThread Handler is null?")
}
val notificationSettings = NotificationSettings(carInformationObserver.capabilities, BtStatus(context) {}, MutableAppSettingsReceiver(context, handler))
notificationSettings.notificationListenerConnected = Settings.Secure.getString(context.contentResolver, "enabled_notification_listeners")?.contains(context.packageName) == true
notificationSettings.btStatus.register()
carappNotifications = PhoneNotifications(iDriveConnectionStatus, securityAccess,
CarAppAssetResources(context, "basecoreOnlineServices"),
PhoneAppResourcesAndroid(context),
GraphicsHelpersAndroid(),
CarNotificationControllerIntent(context),
AudioPlayer(context),
notificationSettings)
if (handler != null) {
carappNotifications?.onCreate(context, handler)
}
// request an initial draw
context.sendBroadcast(Intent(NotificationListenerServiceImpl.INTENT_REQUEST_DATA))
handler?.post {
if (running) {
// start up the readout app
// using a handler to automatically handle shutting down during init
val carappReadout = ReadoutApp(iDriveConnectionStatus, securityAccess,
CarAppAssetResources(context, "news"))
carappNotifications?.readoutInteractions?.readoutController = carappReadout.readoutController
this.carappReadout = carappReadout
}
}
handler?.post {
val id4 = carInformationObserver.capabilities["hmi.type"]?.contains("ID4")
if (running && id4 == false) {
// start up the id5 statusbar app
// using a handler to automatically handle shutting down during init
val carappStatusbar = ID5StatusbarApp(iDriveConnectionStatus, securityAccess,
CarAppWidgetAssetResources(context, "bmwone"), GraphicsHelpersAndroid())
// main app should use this for popup access
carappNotifications?.viewPopup = carappStatusbar.popupView
// main app should use this for statusbar access
carappNotifications?.statusbarController?.controller = carappStatusbar.statusbarController
// the statusbar can trigger the main app
carappNotifications?.showNotificationController?.also {
carappStatusbar.showNotificationController = it
}
this.carappStatusbar = carappStatusbar
println("Finished initializing id5 statusbar")
}
}
}
threadNotifications?.start()
}
}
return true
} else { // we should not run the service
if (threadNotifications != null) {
Log.i(MainService.TAG, "Notifications app needs to be shut down...")
stop()
}
return false
}
}
fun stop() {
running = false
// unregister in the main thread
// when the car disconnects, the threadNotifications handler shuts down
try {
carappNotifications?.notificationSettings?.btStatus?.unregister()
carappNotifications?.onDestroy(context)
} catch (e: Exception) {
Log.w(TAG, "Encountered an exception while shutting down", e)
}
// post cleanup actions to the thread to run after initialization finishes
// if the car is already disconnected, this Handler loop will have crashed
threadNotifications?.post {
carappNotifications?.onDestroy(context)
carappNotifications?.disconnect()
carappNotifications = null
carappReadout?.disconnect()
carappReadout = null
carappStatusbar?.disconnect()
carappStatusbar = null
threadNotifications?.quit()
threadNotifications = null
// if we started up again during shutdown
if (running) {
start()
}
}
}
}
<|start_filename|>app/src/test/java/me/hufman/androidautoidrive/phoneui/ConnectionStatusModelTest.kt<|end_filename|>
package me.hufman.androidautoidrive.phoneui
import android.content.Context
import android.content.res.Resources
import android.util.TypedValue
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.nhaarman.mockito_kotlin.*
import kotlinx.coroutines.delay
import me.hufman.androidautoidrive.CarInformation
import me.hufman.androidautoidrive.ChassisCode
import me.hufman.androidautoidrive.R
import me.hufman.androidautoidrive.TestCoroutineRule
import me.hufman.androidautoidrive.connections.CarConnectionDebugging
import me.hufman.androidautoidrive.phoneui.viewmodels.ConnectionStatusModel
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.mockito.ArgumentMatchers.anyInt
class ConnectionStatusModelTest {
@Rule
@JvmField
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Rule
@JvmField
val testCoroutineRule = TestCoroutineRule()
@Suppress("DEPRECATION")
val resources: Resources = mock {
on {getColor(any())} doAnswer {context.getColor(it.arguments[0] as Int)}
on {getColor(any(), any())} doAnswer {context.getColor(it.arguments[0] as Int)}
on {getDrawable(any())} doAnswer{context.getDrawable(it.arguments[0] as Int)}
on {getValue(anyInt(), any(), any())} doAnswer { (it.arguments[1] as TypedValue).resourceId = it.arguments[0] as Int }
}
val context: Context = mock {
on {getString(any())} doReturn ""
on {getString(any(), any())} doReturn ""
on {resources} doReturn resources
}
@Test
fun testDisconnected() {
val connection = mock<CarConnectionDebugging>()
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(false, model.isBtConnected.value)
assertEquals(false, model.isUsbConnected.value)
assertEquals(false, model.isBclReady.value)
assertEquals("", model.bclTransport.value)
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.connectionStatusWaiting))
assertEquals("", context.run(model.carConnectionHint.value!!))
}
@Test
fun testBtConnected() {
val connection = mock<CarConnectionDebugging> {
on {isBTConnected} doReturn true
on {isA2dpConnected} doReturn false
on {isSPPAvailable} doReturn false
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(true, model.isBtConnected.value)
assertEquals(false, model.isA2dpConnected.value)
assertEquals(false, model.isSppAvailable.value)
assertEquals(false, model.isUsbConnected.value)
assertEquals(false, model.isBclReady.value)
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.connectionStatusWaiting))
assertEquals("", context.run(model.carConnectionHint.value!!))
}
@Test
fun testBtA2dpConnected() {
val connection = mock<CarConnectionDebugging> {
on {isBTConnected} doReturn true
on {isA2dpConnected} doReturn true
on {isSPPAvailable} doReturn false
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(true, model.isBtConnected.value)
assertEquals(true, model.isA2dpConnected.value)
assertEquals(false, model.isSppAvailable.value)
assertEquals(false, model.isUsbConnected.value)
assertEquals(false, model.isBclReady.value)
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.connectionStatusWaiting))
assertEquals("", context.run(model.carConnectionHint.value!!))
}
@Test
fun testBtSppConnected() {
val connection = mock<CarConnectionDebugging> {
on {isBTConnected} doReturn true
on {isA2dpConnected} doReturn true
on {isSPPAvailable} doReturn true
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(true, model.isBtConnected.value)
assertEquals(true, model.isA2dpConnected.value)
assertEquals(true, model.isSppAvailable.value)
assertEquals(false, model.isUsbConnected.value)
assertEquals(true, model.isBclReady.value)
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.txt_setup_bcl_waiting))
assertEquals("", context.run(model.carConnectionHint.value!!))
}
@Test
fun testUsbConnectedCharging() {
val connection = mock<CarConnectionDebugging> {
on {isUsbConnected} doReturn true
on {isUsbTransferConnected} doReturn false
on {isUsbAccessoryConnected} doReturn false
on {isBMWConnectedInstalled} doReturn true
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(false, model.isBtConnected.value)
assertEquals(true, model.isUsbConnected.value)
assertEquals(true, model.isUsbCharging.value)
assertEquals(false, model.isUsbTransfer.value)
assertEquals(false, model.isUsbAccessory.value)
assertEquals(false, model.isBclReady.value)
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.connectionStatusWaiting))
context.run(model.carConnectionHint.value!!)
verify(context).getString(eq(R.string.txt_setup_enable_usbmtp))
}
@Test
fun testUsbConnectedTransfer() {
val connection = mock<CarConnectionDebugging> {
on {deviceName} doReturn "Test"
on {isUsbConnected} doReturn true
on {isUsbTransferConnected} doReturn true
on {isUsbAccessoryConnected} doReturn false
on {isBMWConnectedInstalled} doReturn true
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(false, model.isBtConnected.value)
assertEquals(true, model.isUsbConnected.value)
assertEquals(false, model.isUsbCharging.value)
assertEquals(true, model.isUsbTransfer.value)
assertEquals(false, model.isUsbAccessory.value)
assertEquals(false, model.isBclReady.value)
context.run(model.hintUsbAccessory.value!!)
verify(context).getString(eq(R.string.txt_setup_enable_usbacc), eq("Test"))
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.connectionStatusWaiting))
context.run(model.carConnectionHint.value!!)
verify(context, times(2)).getString(eq(R.string.txt_setup_enable_usbacc), eq("Test"))
}
@Test
fun testUsbConnectedAccessory() {
val connection = mock<CarConnectionDebugging> {
on {isUsbConnected} doReturn true
on {isUsbTransferConnected} doReturn false
on {isUsbAccessoryConnected} doReturn true
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(false, model.isBtConnected.value)
assertEquals(true, model.isUsbConnected.value)
assertEquals(false, model.isUsbCharging.value)
assertEquals(false, model.isUsbTransfer.value)
assertEquals(true, model.isUsbAccessory.value)
assertEquals(true, model.isBclReady.value)
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.txt_setup_bcl_waiting))
assertEquals("", context.run(model.carConnectionHint.value!!))
}
@Test
fun testBclDisconnected() = testCoroutineRule.runBlockingTest {
val connection = mock<CarConnectionDebugging> {
on {isBMWConnectedInstalled} doReturn true // usb is supported
on {isBTConnected} doReturn true
on {isSPPAvailable} doReturn true
on {isBCLConnecting} doReturn false
on {isBCLConnected} doReturn false
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(true, model.isBtConnected.value)
assertEquals(false, model.isUsbConnected.value)
assertEquals(true, model.isBclReady.value)
assertEquals(true, model.isBclDisconnected.value)
assertEquals(false, model.isBclConnecting.value)
assertEquals(false, model.isBclConnected.value)
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.txt_setup_bcl_waiting))
assertEquals("", context.run(model.carConnectionHint.value!!))
// empty hint
assertEquals("", context.run(model.hintBclDisconnected.value!!))
delay(10500L)
// flips to show a hint after a timeout
context.run(model.hintBclDisconnected.value!!)
verify(context).getString(eq(R.string.txt_setup_enable_bclspp_usb))
// main connection status shows the hint too
context.run(model.carConnectionText.value!!)
verify(context, times(2)).getString(eq(R.string.txt_setup_bcl_waiting))
context.run(model.carConnectionHint.value!!)
verify(context, times(2)).getString(eq(R.string.txt_setup_enable_bclspp_usb))
}
@Test
fun testBclDisconnectedBMWMine() = testCoroutineRule.runBlockingTest {
val connection = mock<CarConnectionDebugging> {
on {isBMWConnectedInstalled} doReturn false // usb is not supported
on {isBTConnected} doReturn true
on {isSPPAvailable} doReturn true
on {isBCLConnecting} doReturn false
on {isBCLConnected} doReturn false
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(true, model.isBtConnected.value)
assertEquals(false, model.isUsbConnected.value)
assertEquals(true, model.isBclReady.value)
assertEquals(true, model.isBclDisconnected.value)
assertEquals(false, model.isBclConnecting.value)
assertEquals(false, model.isBclConnected.value)
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.txt_setup_bcl_waiting))
assertEquals("", context.run(model.carConnectionHint.value!!))
// empty hint
assertEquals("", context.run(model.hintBclDisconnected.value!!))
delay(10500L)
// flips to show a hint after a timeout
context.run(model.hintBclDisconnected.value!!)
verify(context).getString(eq(R.string.txt_setup_enable_bclspp_usb))
// main connection status shows the hint too
context.run(model.carConnectionText.value!!)
verify(context, times(2)).getString(eq(R.string.txt_setup_bcl_waiting))
context.run(model.carConnectionHint.value!!)
verify(context, times(2)).getString(eq(R.string.txt_setup_enable_bclspp_usb))
}
@Test
fun testBclConnecting() {
val connection = mock<CarConnectionDebugging> {
on {isBTConnected} doReturn true
on {isSPPAvailable} doReturn true
on {isBCLConnecting} doReturn true
on {isBCLConnected} doReturn false
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(true, model.isBtConnected.value)
assertEquals(false, model.isUsbConnected.value)
assertEquals(true, model.isBclReady.value)
assertEquals(false, model.isBclDisconnected.value)
assertEquals(true, model.isBclConnecting.value)
assertEquals(false, model.isBclConnected.value)
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.txt_setup_bcl_connecting))
assertEquals("", context.run(model.carConnectionHint.value!!))
}
@Test
fun testBclStuck() {
val connection = mock<CarConnectionDebugging> {
on {deviceName} doReturn "Test"
on {isBTConnected} doReturn true
on {isSPPAvailable} doReturn true
on {isBCLConnecting} doReturn true
on {isBCLStuck} doReturn true
on {isBCLConnected} doReturn false
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(true, model.isBtConnected.value)
assertEquals(false, model.isUsbConnected.value)
assertEquals(true, model.isBclReady.value)
assertEquals(false, model.isBclDisconnected.value)
assertEquals(true, model.isBclConnecting.value)
assertEquals(true, model.isBclStuck.value)
assertEquals(false, model.isBclConnected.value)
context.run(model.hintBclMode.value!!)
verify(context).getString(eq(R.string.txt_setup_enable_bcl_mode), eq("Test"))
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.txt_setup_bcl_connecting))
context.run(model.carConnectionHint.value!!)
verify(context, times(2)).getString(eq(R.string.txt_setup_enable_bcl_mode), eq("Test"))
// not actually displayed, but the value is generic
context.run(model.bclModeText.value!!)
verify(context).getString(eq(R.string.txt_setup_bcl_connected))
}
@Test
fun testBclConnected() {
val connection = mock<CarConnectionDebugging> {
on {isBTConnected} doReturn true
on {isSPPAvailable} doReturn true
on {isBCLConnecting} doReturn true // stays true even while Connected
on {isBCLConnected} doReturn true
on {bclTransport} doReturn "BT"
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(true, model.isBtConnected.value)
assertEquals(false, model.isUsbConnected.value)
assertEquals(true, model.isBclReady.value)
assertEquals(false, model.isBclDisconnected.value)
assertEquals(false, model.isBclConnecting.value)
assertEquals(true, model.isBclConnected.value)
assertEquals("BT", model.bclTransport.value)
context.run(model.bclModeText.value!!)
verify(context).getString(eq(R.string.txt_setup_bcl_connected_transport), eq("BT"))
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.txt_setup_bcl_connecting))
}
@Test
fun testConnectedNoSecurity() {
val connection = mock<CarConnectionDebugging> {
on {isConnectedSecurityConnecting} doReturn true
on {isConnectedSecurityConnected} doReturn false
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.connectionStatusWaiting))
context.run(model.carConnectionColor.value!!)
verify(context).getColor(R.color.connectionWaiting)
// within the time limit, don't show red if done connecting
whenever(connection.isConnectedSecurityConnecting) doReturn false
model.update()
context.run(model.carConnectionText.value!!)
verify(context, times(2)).getString(eq(R.string.connectionStatusWaiting))
context.run(model.carConnectionColor.value!!)
verify(context, times(2)).getColor(R.color.connectionWaiting)
// still Connecting, don't show red
Thread.sleep(2500)
whenever(connection.isConnectedSecurityConnecting) doReturn true
model.update()
context.run(model.carConnectionText.value!!)
verify(context, times(3)).getString(eq(R.string.connectionStatusWaiting))
context.run(model.carConnectionColor.value!!)
verify(context, times(3)).getColor(R.color.connectionWaiting)
// done connecting
whenever(connection.isConnectedSecurityConnecting) doReturn false
model.update()
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.connectionStatusMissingConnectedApp))
context.run(model.carConnectionColor.value!!)
verify(context).getColor(R.color.connectionError)
}
@Test
fun testConnectedNoBrand() {
val connection = mock<CarConnectionDebugging> {
on {isConnectedSecurityConnected} doReturn true
on {isBCLConnected} doReturn true
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.txt_setup_bcl_connecting))
assertEquals("", context.run(model.carConnectionHint.value!!))
context.run(model.carConnectionColor.value!!)
verify(context).getColor(R.color.connectionWaiting)
context.run(model.carLogo.value!!)
verify(context, never()).getDrawable(R.drawable.logo_bmw)
verify(context, never()).getDrawable(R.drawable.logo_mini)
}
@Test
fun testConnectedBMWBrand() {
val connection = mock<CarConnectionDebugging>{
on {isConnectedSecurityConnected} doReturn true
on {isBCLConnected} doReturn true
on {carBrand} doReturn "BMW"
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.connectionStatusConnected), eq("BMW"))
assertEquals("", context.run(model.carConnectionHint.value!!))
context.run(model.carConnectionColor.value!!)
verify(context).getColor(R.color.connectionConnected)
context.run(model.carLogo.value!!)
verify(context).getDrawable(R.drawable.logo_bmw)
}
@Test
fun testConnectedMiniBrand() {
val connection = mock<CarConnectionDebugging>{
on {isConnectedSecurityConnected} doReturn true
on {isBCLConnected} doReturn true
on {carBrand} doReturn "Mini"
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.connectionStatusConnected), eq("MINI"))
assertEquals("", context.run(model.carConnectionHint.value!!))
context.run(model.carConnectionColor.value!!)
verify(context).getColor(R.color.connectionConnected)
context.run(model.carLogo.value!!)
verify(context).getDrawable(R.drawable.logo_mini)
}
@Test
fun testDisconnectedBrand() {
val connection = mock<CarConnectionDebugging>{
on {isConnectedSecurityConnected} doReturn true
on {isBCLConnected} doReturn false // we've disconnected after a previous branded connection
on {carBrand} doReturn "Mini"
}
val carInfo = mock<CarInformation>()
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals("", context.run(model.carConnectionText.value!!))
assertEquals("", context.run(model.carConnectionHint.value!!))
context.run(model.carConnectionColor.value!!)
verify(context).getColor(R.color.connectionWaiting)
assertEquals(null, context.run(model.carLogo.value!!))
}
@Test
fun testChassisCode() {
val carCapabilities = mapOf(
"vehicle.type" to "F56"
)
val connection = mock<CarConnectionDebugging>{
on {isConnectedSecurityConnected} doReturn true
on {isBCLConnected} doReturn true
on {carBrand} doReturn "Mini"
}
val carInfo = mock<CarInformation> {
on {capabilities} doReturn carCapabilities
}
val model = ConnectionStatusModel(connection, carInfo).apply { update() }
assertEquals(false, model.isBtConnected.value)
assertEquals(false, model.isUsbConnected.value)
assertEquals(true, model.isBclReady.value)
assertEquals(ChassisCode.F56, model.carChassisCode.value)
context.run(model.carConnectionText.value!!)
verify(context).getString(eq(R.string.connectionStatusConnected), eq(ChassisCode.F56.toString()))
assertEquals("", context.run(model.carConnectionHint.value!!))
context.run(model.carConnectionColor.value!!)
verify(context).getColor(R.color.connectionConnected)
}
} | ntruchsess/AndroidAutoIdrive |
<|start_filename|>middleware/.yalc/@semapps/ldp/services/container/actions/clear.js<|end_filename|>
module.exports = {
visibility: 'public',
params: {
containerUri: { type: 'string' },
webId: { type: 'string', optional: true }
},
async handler(ctx) {
let { containerUri, webId } = ctx.params;
// Matches container with or without trailing slash
containerUri = containerUri.replace(/\/+$/, '');
return await ctx.call('triplestore.update', {
query: `
PREFIX as: <https://www.w3.org/ns/activitystreams#>
PREFIX ldp: <http://www.w3.org/ns/ldp#>
DELETE {
?container ldp:contains ?s1 .
?s1 ?p1 ?o1 .
}
WHERE {
FILTER(?container IN (<${containerUri}>, <${containerUri + '/'}>)) .
?container ldp:contains ?s1 .
OPTIONAL { ?s1 ?p1 ?o1 . }
}
`,
webId
});
}
};
<|start_filename|>middleware/.yalc/@semapps/auth/LocalConnector.js<|end_filename|>
const { Strategy } = require('passport-local');
const Connector = require('./Connector');
const { MIME_TYPES } = require('@semapps/mime-types');
class LocalConnector extends Connector {
constructor(settings) {
super('local', settings || {});
}
async initialize() {
this.localStrategy = new Strategy(
{
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // We want to have access to req below
},
(req, email, password, done) => {
req.$ctx
.call('auth.account.verify', { email, password })
.then(({ webId }) =>
req.$ctx.call('ldp.resource.get', {
resourceUri: webId,
accept: MIME_TYPES.JSON,
webId: 'system'
})
)
.then(userData => {
req.$ctx.emit('auth.connected', { webId: userData.id, profileData: userData });
done(null, { ...userData, webId: userData.id });
})
.catch(e => {
console.error(e);
done(null, false);
});
}
);
this.passport.use(this.localStrategy);
}
login() {
return async (req, res) => {
const middlewares = [
this.passport.authenticate(this.passportId, {
session: false
}),
this.generateToken.bind(this),
this.sendToken.bind(this)
];
await this.runMiddlewares(middlewares, req, res);
};
}
signup() {
return async (req, res) => {
const middlewares = [this.createAccount.bind(this), this.generateToken.bind(this), this.sendToken.bind(this)];
await this.runMiddlewares(middlewares, req, res);
};
}
createAccount(req, res, next) {
const { email, password, ...profileData } = req.$params;
req.$ctx
.call('auth.account.findByEmail', { email })
.then(webId => {
if (!webId) {
return req.$ctx.call('webid.create', profileData);
} else {
throw new Error('email.already.exists');
}
})
.then(webId =>
req.$ctx.call('ldp.resource.get', {
resourceUri: webId,
accept: MIME_TYPES.JSON,
webId: 'system'
})
)
.then(userData => {
req.user = userData;
req.user.webId = userData.id;
req.user.newUser = true;
return req.$ctx.call('auth.account.create', {
email,
password,
webId: userData.id
});
})
.then(accountData => {
req.$ctx.emit('auth.registered', { webId: accountData['semapps:webId'], profileData, accountData });
next();
})
.catch(e => this.sendError(res, e.message));
}
sendToken(req, res, next) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ token: req.user.token, newUser: req.user.newUser }));
next();
}
sendError(res, message, statusCode = 400) {
res.writeHead(statusCode, message);
res.end();
}
}
module.exports = LocalConnector;
<|start_filename|>middleware/.yalc/@semapps/ldp/services/container/defaultOptions.js<|end_filename|>
module.exports = {
accept: 'text/turtle',
jsonContext: null,
queryDepth: 0,
dereference: [],
newResourcesPermissions: webId => {
switch (webId) {
case 'anon':
return {
anon: {
read: true,
write: true
}
};
case 'system':
return {
anon: {
read: true
},
anyUser: {
read: true,
write: true
}
};
default:
return {
anon: {
read: true
},
anyUser: {
read: true
},
user: {
uri: webId,
read: true,
write: true,
control: true
}
};
}
}
};
<|start_filename|>middleware/.yalc/@semapps/ldp/services/container/actions/getOptions.js<|end_filename|>
const { getContainerFromUri } = require('../../../utils');
module.exports = {
visibility: 'public',
params: {
uri: { type: 'string' }
},
async handler(ctx) {
const { uri } = ctx.params;
const containerOptions =
// Try to find a matching container
this.settings.containers.find(container => this.getContainerUri(container) === uri) ||
// If no container was found, assume the URI passed is a resource
this.settings.containers.find(container => this.getContainerUri(container) === getContainerFromUri(uri)) ||
{};
return { ...this.settings.defaultOptions, ...containerOptions };
}
};
<|start_filename|>middleware/.yalc/@semapps/auth/services/jwt.js<|end_filename|>
const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
module.exports = {
name: 'auth.jwt',
settings: {
jwtPath: null
},
async created() {
const privateKeyPath = path.resolve(this.settings.jwtPath, 'jwtRS256.key');
const publicKeyPath = path.resolve(this.settings.jwtPath, 'jwtRS256.key.pub');
if (!fs.existsSync(privateKeyPath) && !fs.existsSync(publicKeyPath)) {
console.log('JWT keypair not found, generating...');
await this.actions.generateKeyPair({ privateKeyPath, publicKeyPath });
}
this.privateKey = fs.readFileSync(privateKeyPath);
this.publicKey = fs.readFileSync(publicKeyPath);
},
actions: {
generateKeyPair(ctx) {
const { privateKeyPath, publicKeyPath } = ctx.params;
return new Promise((resolve, reject) => {
crypto.generateKeyPair(
'rsa',
{
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
},
(err, publicKey, privateKey) => {
if (err) {
reject(err);
} else {
fs.writeFile(privateKeyPath, privateKey, err => {
if (err) {
reject(err);
} else {
fs.writeFile(publicKeyPath, publicKey, err => {
if (err) {
reject(err);
} else {
resolve({ privateKey, publicKey });
}
});
}
});
}
}
);
});
},
async generateToken(ctx) {
const { payload } = ctx.params;
return jwt.sign(payload, this.privateKey, { algorithm: 'RS256' });
},
async verifyToken(ctx) {
const { token } = ctx.params;
try {
return jwt.verify(token, this.publicKey, { algorithms: ['RS256'] });
} catch (err) {
return false;
}
}
}
};
<|start_filename|>middleware/.yalc/@semapps/ldp/mixins/document-tagger.js<|end_filename|>
module.exports = {
settings: {
documentPredicates: {
created: 'http://purl.org/dc/terms/created',
updated: 'http://purl.org/dc/terms/modified',
creator: 'http://purl.org/dc/terms/creator'
}
},
actions: {
async tagCreatedResource(ctx) {
const { resourceUri, webId } = ctx.params;
const now = new Date();
let triples = [];
triples.push(
`<${resourceUri}> <${
this.settings.documentPredicates.created
}> "${now.toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime> .`
);
triples.push(
`<${resourceUri}> <${
this.settings.documentPredicates.updated
}> "${now.toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime> .`
);
if (webId && webId.startsWith('http'))
triples.push(`<${resourceUri}> <${this.settings.documentPredicates.creator}> <${webId}> .`);
await ctx.call('triplestore.insert', {
resource: triples.join('\n'),
webId: 'system'
});
},
async tagUpdatedResource(ctx) {
const { resourceUri } = ctx.params;
const now = new Date();
await ctx.call('triplestore.update', {
query: `
DELETE { <${resourceUri}> <${this.settings.documentPredicates.updated}> ?updated }
INSERT { <${resourceUri}> <${
this.settings.documentPredicates.updated
}> "${now.toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime> }
WHERE { <${resourceUri}> <${this.settings.documentPredicates.updated}> ?updated }
`,
webId: 'system'
});
}
},
events: {
async 'ldp.resource.created'(ctx) {
const { resourceUri, webId } = ctx.params;
this.actions.tagCreatedResource({ resourceUri, webId }, { parentCtx: ctx });
},
async 'ldp.resource.updated'(ctx) {
const { resourceUri } = ctx.params;
this.actions.tagUpdatedResource({ resourceUri }, { parentCtx: ctx });
}
}
};
<|start_filename|>middleware/.yalc/@semapps/auth/services/account.js<|end_filename|>
const bcrypt = require('bcrypt');
const { MIME_TYPES } = require('@semapps/mime-types');
module.exports = {
name: 'auth.account',
settings: {
containerUri: null
},
dependencies: ['ldp', 'triplestore'],
actions: {
async create(ctx) {
const { email, password, webId } = ctx.params;
const hashedPassword = await this.hashPassword(password);
const accountUri = await ctx.call('ldp.resource.post', {
containerUri: this.settings.containerUri,
resource: {
'@context': {
semapps: 'http://semapps.org/ns/core#'
},
'@type': 'semapps:Account',
'semapps:email': email,
'semapps:password': hashedPassword,
'semapps:webId': webId
},
contentType: MIME_TYPES.JSON,
webId
});
return await ctx.call('ldp.resource.get', {
resourceUri: accountUri,
accept: MIME_TYPES.JSON,
webId
});
},
async verify(ctx) {
const { email, password } = ctx.params;
const results = await ctx.call('triplestore.query', {
query: `
PREFIX semapps: <http://semapps.org/ns/core#>
PREFIX ldp: <http://www.w3.org/ns/ldp#>
SELECT ?accountUri ?passwordHash ?webId
WHERE {
<${this.settings.containerUri}> ldp:contains ?accountUri .
?accountUri semapps:email '${email}' .
?accountUri semapps:password ?passwordHash .
?accountUri semapps:webId ?webId .
}
`,
accept: MIME_TYPES.JSON,
webId: 'system'
});
if (results.length > 0) {
const passwordMatch = await this.comparePassword(password, results[0].passwordHash.value);
if (passwordMatch) {
return { accountUri: results[0].accountUri.value, webId: results[0].webId.value };
} else {
throw new Error('account.not-found');
}
} else {
throw new Error('account.not-found');
}
},
async findByEmail(ctx) {
const { email } = ctx.params;
const results = await ctx.call('triplestore.query', {
query: `
PREFIX semapps: <http://semapps.org/ns/core#>
PREFIX ldp: <http://www.w3.org/ns/ldp#>
SELECT ?accountUri ?webId
WHERE {
<${this.settings.containerUri}> ldp:contains ?accountUri .
?accountUri semapps:email '${email}' .
?accountUri semapps:webId ?webId .
}
`,
accept: MIME_TYPES.JSON,
webId: 'system'
});
return results.length > 0 ? results[0].webId.value : null;
},
async findByWebId(ctx) {
const { webId } = ctx.params;
const results = await ctx.call('triplestore.query', {
query: `
PREFIX semapps: <http://semapps.org/ns/core#>
PREFIX ldp: <http://www.w3.org/ns/ldp#>
SELECT ?accountUri
WHERE {
<${this.settings.containerUri}> ldp:contains ?accountUri .
?accountUri semapps:webId "${webId}" .
}
`,
accept: MIME_TYPES.JSON,
webId: 'system'
});
return results.length > 0 ? results[0].accountUri.value : null;
}
},
methods: {
async hashPassword(password) {
return new Promise((resolve, reject) => {
bcrypt.hash(password, 10, (err, hash) => {
if (err) {
reject(err);
} else {
resolve(hash);
}
});
});
},
async comparePassword(password, hash) {
return new Promise(resolve => {
bcrypt.compare(password, hash, (err, res) => {
if (res === true) {
resolve(true);
} else {
resolve(false);
}
});
});
}
}
};
<|start_filename|>middleware/.yalc/@semapps/ldp/index.js<|end_filename|>
const utils = require('./utils');
module.exports = {
LdpService: require('./service'),
LdpContainerService: require('./services/container'),
LdpResourceService: require('./services/resource'),
ResourcesWatcherBot: require('./bots/resources-watcher'),
DocumentTaggerMixin: require('./mixins/document-tagger'),
TripleStoreAdapter: require('./adapter'),
getContainerRoutes: require('./routes/getContainerRoutes'),
...utils
};
<|start_filename|>middleware/.yalc/@semapps/auth/index.js<|end_filename|>
module.exports = {
AuthService: require('./services/auth'),
AuthAccountService: require('./services/account'),
AuthJWTService: require('./services/jwt'),
Connector: require('./Connector'),
CasConnector: require('./CasConnector'),
LocalConnector: require('./LocalConnector'),
OidcConnector: require('./OidcConnector')
};
<|start_filename|>middleware/.yalc/@semapps/ldp/bots/resources-watcher.js<|end_filename|>
const { getContainerFromUri } = require('../utils');
module.exports = {
name: 'resources-watcher',
settings: {
containerUri: null
},
methods: {
created(resourceUri, newData) {
// This method can be implemented
},
updated(resourceUri, newData, oldData) {
// This method can be implemented
},
deleted(resourceUri, oldData) {
// This method can be implemented
},
isMatching(resourceUri) {
return getContainerFromUri(resourceUri) === this.settings.containerUri;
}
},
events: {
async 'ldp.resource.created'(ctx) {
const { resourceUri, newData } = ctx.params;
if (this.isMatching(resourceUri)) {
this.created(resourceUri, newData);
}
},
async 'ldp.resource.updated'(ctx) {
const { resourceUri, newData, oldData } = ctx.params;
if (this.isMatching(resourceUri)) {
this.updated(resourceUri, newData, oldData);
}
},
async 'ldp.resource.deleted'(ctx) {
const { resourceUri, oldData } = ctx.params;
if (this.isMatching(resourceUri)) {
this.updated(resourceUri, oldData);
}
}
}
};
<|start_filename|>middleware/.yalc/@semapps/ldp/services/container/actions/attach.js<|end_filename|>
module.exports = {
visibility: 'public',
params: {
containerUri: { type: 'string' },
resourceUri: { type: 'string' },
webId: {
type: 'string',
optional: true
}
},
async handler(ctx) {
const { containerUri, resourceUri } = ctx.params;
let { webId } = ctx.params;
webId = webId || ctx.meta.webId || 'anon';
const resourceExists = await ctx.call('ldp.resource.exist', { resourceUri }, { meta: { webId } });
if (!resourceExists) {
const childContainerExists = await this.actions.exist(
{ containerUri: resourceUri },
{ parentCtx: ctx, meta: { webId } }
);
if (!childContainerExists) {
throw new Error('Cannot attach non-existing resource or container: ' + resourceUri);
}
}
const containerExists = await this.actions.exist({ containerUri }, { parentCtx: ctx, meta: { webId } });
if (!containerExists) throw new Error('Cannot attach to a non-existing container: ' + containerUri);
await ctx.call('triplestore.insert', {
resource: `<${containerUri}> <http://www.w3.org/ns/ldp#contains> <${resourceUri}>`,
webId
});
ctx.emit('ldp.container.attached', {
containerUri,
resourceUri
});
}
};
| data-players/AUrba |
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmNegateExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import org.elm.lang.core.psi.ElmAtomTag
import org.elm.lang.core.psi.ElmExpressionTag
import org.elm.lang.core.psi.ElmPsiElementImpl
/**
* A negated expression (one with a leading `-` operator)
*
* e.g. `-3`
*/
class ElmNegateExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmAtomTag {
/** The negated expression. In a well-formed program, this will never be null. */
val expression: ElmExpressionTag? get() = findChildByClass(ElmExpressionTag::class.java)
}
<|start_filename|>src/main/kotlin/org/elm/ide/wordSelection/ElmDeclAnnotationSelectionHandler.kt<|end_filename|>
package org.elm.ide.wordSelection
import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.elements.ElmTypeAnnotation
import org.elm.lang.core.psi.elements.ElmValueDeclaration
import org.elm.lang.core.psi.parentOfType
/**
* Adjusts the 'extend selection' behavior for [ElmValueDeclaration] and [ElmTypeAnnotation] so that they
* mutually extend the selection to include the other.
*/
class ElmDeclAnnotationSelectionHandler : ExtendWordSelectionHandlerBase() {
/*
The plugin mechanism for refining the default 'extend selection' behavior is poor.
Based on tracing the code, here is my understanding of how the internal logic works:
It all starts in `SelectWordHandler.doExecute`. Starting with the element at the caret,
it creates a selection range that just covers the caret position itself. And it defines
an initial minimum range which spans the entire document. It then asks each registered
`ExtendWordSelectionHandler` plugin extension point if it can select the thing and if so,
to return a list of text ranges describing what it would like to select.
Each candidate range is then checked to see if:
(a) it would expand the current selection range
(b) it is smaller than any candidate range seen so far
If both conditions pass, the remaining candidates are ignored and IntelliJ will select
the text in the editor described by the candidate that succeeded. Otherwise, the algorithm
will walk the Psi tree upwards until it finds a larger selection.
In terms of how this affects plugin authors, it appears that the following guidelines
should be followed:
(1) if you want to return a *larger* selection than would normally be returned for
the given element, then you must call `ExtendWordSelectionHandlerBase.expandToWholeLine`
with your desired range and return the resulting list of ranges. I have no idea why
this is, but it appears to work.
(2) if you want to return a *smaller* selection than would normally be returned for
the given element, then you can just return the desired range directly.
*/
override fun canSelect(e: PsiElement): Boolean =
e is ElmValueDeclaration || e is ElmTypeAnnotation
override fun select(e: PsiElement, editorText: CharSequence, cursorOffset: Int, editor: Editor): List<TextRange>? {
when (e) {
is ElmValueDeclaration -> {
// extend the selection so that it also includes the preceding type annotation
val typeAnnotation = e.typeAnnotation ?: return null
val range = TextRange(typeAnnotation.textRange.startOffset, e.textRange.endOffset)
return expandToWholeLine(editorText, range)
}
is ElmTypeAnnotation -> {
// extend the selection so that it also includes the function body
val targetDecl = e.reference.resolve() ?: return null
val valueDecl = targetDecl.parentOfType<ElmValueDeclaration>()!!
val range = TextRange(e.textRange.startOffset, valueDecl.textRange.endOffset)
return expandToWholeLine(editorText, range)
}
else -> return null
}
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmAsClause.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.ElmStubbedNamedElementImpl
import org.elm.lang.core.psi.ElmTypes.UPPER_CASE_IDENTIFIER
import org.elm.lang.core.psi.IdentifierCase.UPPER
import org.elm.lang.core.stubs.ElmAsClauseStub
/**
* Introduces an alias name for the imported module.
*
* e.g. the 'as U' in 'import Data.User as U'
*/
class ElmAsClause : ElmStubbedNamedElementImpl<ElmAsClauseStub> {
constructor(node: ASTNode) :
super(node, UPPER)
constructor(stub: ElmAsClauseStub, stubType: IStubElementType<*, *>) :
super(stub, stubType, UPPER)
val upperCaseIdentifier: PsiElement
get() = findNotNullChildByType(UPPER_CASE_IDENTIFIER)
}
<|start_filename|>src/main/kotlin/org/elm/ide/ElmPairedBraceMatcher.kt<|end_filename|>
package org.elm.ide
import com.intellij.lang.BracePair
import com.intellij.lang.PairedBraceMatcher
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType.WHITE_SPACE
import com.intellij.psi.tree.IElementType
import org.elm.lang.core.psi.ElmTypes.*
private val bracePairs = arrayOf(
BracePair(LEFT_BRACE, RIGHT_BRACE, true),
BracePair(LEFT_PARENTHESIS, RIGHT_PARENTHESIS, false),
BracePair(LEFT_SQUARE_BRACKET, RIGHT_SQUARE_BRACKET, true))
class ElmPairedBraceMatcher : PairedBraceMatcher {
override fun getCodeConstructStart(file: PsiFile?, openingBraceOffset: Int) =
// TODO [kl] re-visit this later. the default is adequate for now.
openingBraceOffset
override fun getPairs() =
bracePairs
override fun isPairedBracesAllowedBeforeType(lbraceType: IElementType, contextType: IElementType?) =
when (contextType) {
null -> true
TAB -> true
NEWLINE -> true
WHITE_SPACE -> true
else -> false
}
}
<|start_filename|>src/test/kotlin/org/elm/lang/core/stubs/ElmStubAccessTest.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elm.lang.core.stubs
import com.intellij.openapi.util.Iconable
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.PsiFileImpl
import com.intellij.psi.stubs.StubElement
import com.intellij.testFramework.LoggedErrorProcessor
import org.apache.log4j.Logger
import org.elm.lang.ElmTestBase
import org.elm.lang.core.psi.ElmNamedElement
import org.elm.lang.core.psi.ElmPsiElement
import java.util.ArrayDeque
import java.util.HashMap
class ElmStubAccessTest : ElmTestBase() {
override val dataPath = "org/elm/lang/core/stubs/fixtures"
override fun setUp() {
super.setUp()
myFixture.copyDirectoryToProject(".", "src")
}
fun `test presentation does not need ast`() {
processStubsWithoutAstAccess<ElmNamedElement> { element ->
element.getIcon(0)
element.getIcon(Iconable.ICON_FLAG_VISIBILITY)
element.name
element.presentation?.let {
it.locationString
it.presentableText
it.getIcon(false)
}
}
}
fun `test getting reference does not need ast`() {
processStubsWithoutAstAccess<ElmPsiElement> { it.reference }
}
fun `test parent works correctly for stubbed elements`() {
val parentsByStub: MutableMap<PsiElement, PsiElement> = HashMap()
try {
LoggedErrorProcessor.setNewInstance(object : LoggedErrorProcessor() {
override fun processError(message: String?, t: Throwable?, details: Array<out String>?, logger: Logger) {
logger.info(message, t)
throw AssertionError(message)
}
})
processStubsWithoutAstAccess<ElmPsiElement> {
val parent = try {
it.parent
} catch (e: AssertionError) {
null
}
if (parent != null) {
parentsByStub += it to it.parent
}
}
} finally {
LoggedErrorProcessor.restoreDefaultProcessor()
}
checkAstNotLoaded(VirtualFileFilter.NONE)
for ((element, stubParent) in parentsByStub) {
element.node // force AST loading
check(element.parent == stubParent) {
"parentByStub returned wrong result for $element\n${element.text}"
}
}
}
private inline fun <reified T : PsiElement> processStubsWithoutAstAccess(block: (T) -> Unit) {
checkAstNotLoaded(VirtualFileFilter.ALL)
val work = ArrayDeque<StubElement<*>>()
VfsUtilCore.visitChildrenRecursively(myFixture.findFileInTempDir("src"), object : VirtualFileVisitor<Void>() {
override fun visitFileEx(file: VirtualFile): Result {
if (!file.isDirectory) {
work.push((psiManager.findFile(file) as PsiFileImpl).stub!!)
}
return CONTINUE
}
})
var processed = 0
var visited = 0
while (work.isNotEmpty()) {
val stub = work.pop()
val psi = stub.psi
visited += 1
if (psi is T) {
block(psi)
processed += 1
}
work += stub.childrenStubs
}
check(visited > 10)
check(processed > 0)
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/parser/manual/TupleOrParenExprParser.kt<|end_filename|>
package org.elm.lang.core.parser.manual
import com.intellij.lang.PsiBuilder
import com.intellij.lang.parser.GeneratedParserUtilBase.*
import com.intellij.psi.tree.IElementType
import org.elm.lang.core.psi.ElmTypes.*
/*
Ideally we could define something like this in GrammarKit, but it doesn't parse
the way we want due to some weird interaction with GrammarKit's left-recursive
expression parser system (extends/collapse).
TupleOrParenOrFieldAccessExpr ::=
LEFT_PARENTHESIS Expression (FieldAccessUpper | ParenUpper | TupleUpper)
{ pin = 1 }
upper FieldAccessUpper ::=
RIGHT_PARENTHESIS FieldAccessSegment+
{ elementType = FieldAccessExpr }
upper ParenUpper ::=
RIGHT_PARENTHESIS
{ elementType = ParenthesizedExpr }
upper TupleUpper ::=
(COMMA Expression)+ RIGHT_PARENTHESIS
{ elementType = TupleExpr }
*/
// TODO expand parser to also parse `FieldAccess` expressions that start with a parenthesized expr
class TupleOrParenExprParser(
private val exprParser: Parser
) : Parser {
override fun parse(b: PsiBuilder, level: Int): Boolean {
val tupleOrParens: PsiBuilder.Marker = enter_section_(b, level, _NONE_)
if (!consumeTokenSmart(b, LEFT_PARENTHESIS)) {
exit_section_(b, level, tupleOrParens, null, false, false, null)
return false
}
// Due to how our parse rules are ordered, it is safe to pin
// as soon as we see a left parenthesis. Whether we choose to treat
// this as a parenthesized expr or a tuple expr is arbitrary.
// I have chosen to treat it as a paren expr until we see a comma.
fun commit(type: IElementType, success: Boolean): Boolean {
exit_section_(b, level, tupleOrParens, type, success, /*pinned*/ true, null)
return true
}
if (!exprParser.parse(b, level)) {
return commit(PARENTHESIZED_EXPR, success = false)
}
if (consumeTokenSmart(b, RIGHT_PARENTHESIS)) {
return commit(PARENTHESIZED_EXPR, success = true)
}
// If this is actually a tuple expression, there should be a comma right here.
if (!consumeToken(b, COMMA)) {
return commit(PARENTHESIZED_EXPR, success = false)
}
// Now that we've seen a comma, we definitely are parsing a tuple, so
// if there are any parse errors beyond this point, we will commit
// it as a tuple expr (rather than a paren expr).
if (!exprParser.parse(b, level)) {
return commit(TUPLE_EXPR, success = false)
}
// parse any remaining commas followed by expressions until closing parenthesis
while (!nextTokenIs(b, RIGHT_PARENTHESIS)) {
// parse: comma followed by expression
if (!consumeToken(b, COMMA)) {
return commit(TUPLE_EXPR, success = false)
}
if (!exprParser.parse(b, level)) {
return commit(TUPLE_EXPR, success = false)
}
}
if (!consumeTokenSmart(b, RIGHT_PARENTHESIS)) {
return commit(TUPLE_EXPR, success = false)
}
return commit(TUPLE_EXPR, success = true)
}
}
<|start_filename|>src/main/kotlin/org/elm/ide/intentions/AnnotationBasedGeneratorIntention.kt<|end_filename|>
package org.elm.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import org.elm.lang.core.imports.ImportAdder
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmTypeAnnotation
import org.elm.lang.core.psi.endOffset
import org.elm.lang.core.psi.parentOfType
import org.elm.lang.core.psi.startOffset
import org.elm.lang.core.types.Ty
import org.elm.lang.core.types.typeExpressionInference
import org.elm.openapiext.runWriteCommandAction
import org.elm.utils.getIndent
abstract class AnnotationBasedGeneratorIntention : ElmAtCaretIntentionActionBase<AnnotationBasedGeneratorIntention.Context>() {
data class Context(val file: ElmFile, val ty: Ty, val name: String, val startOffset: Int, val endOffset: Int)
override fun getFamilyName() = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val file = element.containingFile as? ElmFile ?: return null
val typeAnnotation = element.parentOfType<ElmTypeAnnotation>()
?: return null
if (typeAnnotation.reference.resolve() != null) {
// the target declaration already exists; nothing to do
return null
}
val ty = typeAnnotation.typeExpressionInference()?.ty ?: return null
val root = getRootIfApplicable(ty) ?: return null
return Context(file, root, typeAnnotation.referenceName, typeAnnotation.startOffset, typeAnnotation.endOffset)
}
/** If the intention applies to the type of this annotation, return the [Ty] to use as [Context.ty]. */
abstract fun getRootIfApplicable(annotationTy: Ty): Ty?
/** The code generator for this intention*/
abstract fun generator(context: Context): TyFunctionGenerator
override fun invoke(project: Project, editor: Editor, context: Context) {
val generator = generator(context)
val indent = editor.getIndent(context.startOffset)
val (generatedCode, imports) = generator.run()
val code = generatedCode.replace(Regex("\n(?![\r\n])"), "\n$indent")
project.runWriteCommandAction {
editor.document.insertString(context.endOffset, "$indent$code")
if (imports.isNotEmpty()) {
// Commit the string changes so we can work with the new PSI
PsiDocumentManager.getInstance(context.file.project).commitDocument(editor.document)
for (import in imports) {
ImportAdder.addImport(import, context.file, import.nameToBeExposed.isEmpty())
}
}
}
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/IfElse.elm<|end_filename|>
f1 = if a then 1 else 2
f2 = if a then 1 else if b then 2 else 3
f2 = if a then 1 else if b then 2 else if c then 3 else 4
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmImportClause.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.ElmNamedElement
import org.elm.lang.core.psi.ElmStubbedElement
import org.elm.lang.core.psi.stubDirectChildrenOfType
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReferenceCached
import org.elm.lang.core.stubs.ElmPlaceholderStub
import org.elm.lang.core.stubs.index.ElmModulesIndex
/**
* An import declaration at the top of the module.
*
* e.g. 'import Data.User exposing (User, name, age)'
*
* Role:
* - refers to the module from which values and types should be imported
* - possibly introduces an alias name for the module
* - expose individual values and types from the module
*/
class ElmImportClause : ElmStubbedElement<ElmPlaceholderStub>, ElmReferenceElement {
constructor(node: ASTNode) :
super(node)
constructor(stub: ElmPlaceholderStub, stubType: IStubElementType<*, *>) :
super(stub, stubType)
val moduleQID: ElmUpperCaseQID
get() = stubDirectChildrenOfType<ElmUpperCaseQID>().single()
val asClause: ElmAsClause?
get() = stubDirectChildrenOfType<ElmAsClause>().singleOrNull()
val exposingList: ElmExposingList?
get() = stubDirectChildrenOfType<ElmExposingList>().singleOrNull()
val exposesAll: Boolean
get() = exposingList?.exposesAll ?: false
override val referenceNameElement: PsiElement
get() = moduleQID
override val referenceName: String
get() = moduleQID.fullName // stub-safe
override fun getReference() =
object : ElmReferenceCached<ElmImportClause>(this) {
override fun resolveInner(): ElmNamedElement? =
ElmModulesIndex.get(moduleQID.fullName, elmFile)
override fun getVariants(): Array<ElmNamedElement> =
ElmModulesIndex.getAll(elmFile).toTypedArray()
}
}
<|start_filename|>src/main/kotlin/org/elm/ide/color/ElmColorSettingsPage.kt<|end_filename|>
package org.elm.ide.color
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import org.elm.ide.highlight.ElmSyntaxHighlighter
import org.elm.ide.icons.ElmIcons
class ElmColorSettingsPage : ColorSettingsPage {
private val ATTRS = ElmColor.values().map { it.attributesDescriptor }.toTypedArray()
override fun getDisplayName() =
"Elm"
override fun getIcon() =
ElmIcons.FILE
override fun getAttributeDescriptors() =
ATTRS
override fun getColorDescriptors(): Array<ColorDescriptor> =
ColorDescriptor.EMPTY_ARRAY
override fun getHighlighter() =
ElmSyntaxHighlighter()
override fun getAdditionalHighlightingTagToDescriptorMap() =
// special tags in [demoText] for semantic highlighting
mapOf(
"type" to ElmColor.TYPE_EXPR,
"variant" to ElmColor.UNION_VARIANT,
"accessor" to ElmColor.RECORD_FIELD_ACCESSOR,
"field" to ElmColor.RECORD_FIELD,
"func_decl" to ElmColor.DEFINITION_NAME
).mapValues { it.value.textAttributesKey }
override fun getDemoText() =
demoCodeText
}
private const val demoCodeText = """
module Todo exposing (..)
import Html exposing (div, h1, ul, li, text)
-- a single line comment
type alias Model =
{ <field>page</field> : <type>Int</type>
, <field>title</field> : <type>String</type>
, <field>stepper</field> : <type>Int</type> -> <type>Int</type>
}
type Msg <type>a</type>
= <variant>ModeA</variant>
| <variant>ModeB</variant> <type>Maybe a</type>
<func_decl>update</func_decl> : <type>Msg</type> -> <type>Model</type> -> ( <type>Model</type>, <type>Cmd Msg</type> )
<func_decl>update</func_decl> msg model =
case msg of
<variant>ModeA</variant> ->
{ model
| <field>page</field> = 0
, <field>title</field> = "Mode A"
, <field>stepper</field> = (\k -> k + 1)
}
! []
<func_decl>view</func_decl> : <type>Model</type> -> <type>Html.Html Msg</type>
<func_decl>view</func_decl> model =
let
<func_decl>itemify</func_decl> label =
li [] [ text label ]
in
div []
[ h1 [] [ text "Chapter One" ]
, ul []
(List.map <accessor>.value</accessor> model.<field>items</field>)
]
"""
<|start_filename|>src/main/kotlin/org/elm/ide/refactoring/ElmRenamePsiElementProcessor.kt<|end_filename|>
package org.elm.ide.refactoring
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.refactoring.rename.RenamePsiFileProcessor
import org.elm.lang.core.psi.elements.ElmModuleDeclaration
/**
* When renaming an Elm module, always treat it as if the user were renaming the file.
*
* See https://intellij-support.jetbrains.com/hc/en-us/community/posts/206760415-Renaming-files-in-IDE
* and [ElmRenamePsiFileProcessor].
*/
class ElmRenamePsiElementProcessor : RenamePsiFileProcessor() {
override fun canProcessElement(element: PsiElement) =
element is ElmModuleDeclaration
override fun substituteElementToRename(element: PsiElement, editor: Editor?): PsiElement? {
return when (element) {
is ElmModuleDeclaration -> element.elmFile
else -> element
}
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/Shaders.elm<|end_filename|>
shader =
[glsl|
1 | 2
<|start_filename|>src/main/kotlin/org/elm/ide/inspections/ElmInspectionSuppressor.kt<|end_filename|>
package org.elm.ide.inspections
import com.intellij.codeInsight.daemon.impl.actions.AbstractBatchSuppressByNoInspectionCommentFix
import com.intellij.codeInspection.InspectionSuppressor
import com.intellij.codeInspection.SuppressQuickFix
import com.intellij.codeInspection.SuppressionUtil
import com.intellij.codeInspection.SuppressionUtilCore
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.elm.lang.core.ElmLanguage
import org.elm.lang.core.psi.*
import org.elm.lang.core.psi.ElmTypes.VIRTUAL_END_DECL
import org.elm.lang.core.psi.elements.ElmTypeAnnotation
import org.elm.lang.core.psi.elements.ElmValueDeclaration
class ElmInspectionSuppressor : InspectionSuppressor {
companion object {
private val SUPPRESS_REGEX = Regex("--" + SuppressionUtil.COMMON_SUPPRESS_REGEXP)
}
override fun getSuppressActions(element: PsiElement?, toolId: String): Array<out SuppressQuickFix> = arrayOf(
SuppressInspectionFix(toolId),
SuppressInspectionFix(SuppressionUtil.ALL)
)
override fun isSuppressedFor(element: PsiElement, toolId: String): Boolean =
element.ancestors.filterIsInstance<ElmPsiElement>().firstOrNull { it.isTopLevel }
?.isSuppressedByComment(toolId)
?: false
private fun ElmPsiElement.isSuppressedByComment(toolId: String): Boolean {
return prevSiblings.takeWhile {
it is PsiWhiteSpace ||
it is PsiComment ||
it.elementType == VIRTUAL_END_DECL ||
this is ElmValueDeclaration && it is ElmTypeAnnotation
}.filterIsInstance<PsiComment>().any { comment ->
val match = SUPPRESS_REGEX.matchEntire(comment.text)
match != null && SuppressionUtil.isInspectionToolIdMentioned(match.groupValues[1], toolId)
}
}
private class SuppressInspectionFix(
id: String
) : AbstractBatchSuppressByNoInspectionCommentFix(id, /* replaceOthers = */ id == SuppressionUtil.ALL) {
init {
text = when (id) {
SuppressionUtil.ALL -> "Suppress all inspections for declaration"
else -> "Suppress for declaration with comment"
}
}
override fun getContainer(context: PsiElement?): PsiElement? {
if (context == null) return null
return context.ancestors.filterIsInstance<ElmPsiElement>().firstOrNull { it.isTopLevel }
}
override fun createSuppression(project: Project, element: PsiElement, container: PsiElement) {
val anchor = (container as? ElmValueDeclaration)?.typeAnnotation ?: container
val text = SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME + " " + myID
val comment = SuppressionUtil.createComment(project, text + "\n", ElmLanguage)
val parent = anchor.parent
parent.addBefore(comment, anchor)
parent.addBefore(ElmPsiFactory(element.project).createWhitespace("\n"), anchor)
}
}
}
<|start_filename|>src/test/kotlin/org/elm/ide/wordSelection/ElmExtendSelectionTestBase.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elm.ide.wordSelection
import com.intellij.codeInsight.editorActions.SelectWordHandler
import com.intellij.ide.DataManager
import org.elm.lang.ElmTestBase
abstract class ElmExtendSelectionTestBase : ElmTestBase() {
fun doTest(before: String, vararg after: String) {
myFixture.configureByText("main.elm", before)
val action = SelectWordHandler(null)
val dataContext = DataManager.getInstance().getDataContext(myFixture.editor.component)
for (text in after) {
action.execute(myFixture.editor, null, dataContext)
myFixture.checkResult(text, false)
}
}
fun doTestWithTrimmedMargins(before: String, vararg after: String) {
doTest(before.trimMargin(), *after.map { it.trimMargin() }.toTypedArray())
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmCharConstantExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import org.elm.lang.core.psi.ElmConstantTag
import org.elm.lang.core.psi.ElmPsiElementImpl
/** A literal char. e.g. `'x'` or `'\u{0042}'` */
class ElmCharConstantExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmConstantTag
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmIfElseExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.elm.lang.core.psi.ElmAtomTag
import org.elm.lang.core.psi.ElmExpressionTag
import org.elm.lang.core.psi.ElmPsiElementImpl
import org.elm.lang.core.psi.ElmTypes
/**
* An if-else expression, possible with one or more else-if branches.
*
* e.g.
* - `if True then 1 else 2`
* - `if False then 1 else if True then 2 else 3`
*/
class ElmIfElseExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmAtomTag {
/**
* In a well-formed program, will contain an odd number of expressions, with at least three.
*/
val expressionList: List<ElmExpressionTag>
get() = PsiTreeUtil.getChildrenOfTypeAsList(this, ElmExpressionTag::class.java)
/** The `if` keywords. This will never be empty. */
val ifKeywords : List<PsiElement> get() = findChildrenByType(ElmTypes.IF)
/** The `then` keywords. In a well formed program, this will be the same size as [ifKeywords] */
val thenKeywords : List<PsiElement> get() = findChildrenByType(ElmTypes.THEN)
/** The `else` keywords. In a well formed program, this will be the same size as [ifKeywords] */
val elseKeywords : List<PsiElement> get() = findChildrenByType(ElmTypes.ELSE)
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/Tuples.elm<|end_filename|>
magicNumber = 42
f1 = (mag
f2 = (magicNumber,
f3 = (magicNumber, m
f4 = (magicNumber, )
magicWord = "please"
<|start_filename|>src/test/kotlin/org/elm/ide/docs/ElmDocumentationProviderTest.kt<|end_filename|>
package org.elm.ide.docs
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.psi.PsiElement
import com.intellij.testFramework.UsefulTestCase.assertSameLines
import org.elm.lang.ElmTestBase
import org.intellij.lang.annotations.Language
import org.junit.Test
import org.junit.Assert.*
abstract class ElmDocumentationProviderTest : ElmTestBase() {
protected inline fun doTest(
@Language("Elm") code: String,
@Language("Html") expected: String,
block: ElmDocumentationProvider.(PsiElement, PsiElement?) -> String?
) {
InlineFile(code)
val (originalElement, _, offset) = findElementWithDataAndOffsetInEditor<PsiElement>()
val element = DocumentationManager.getInstance(project)
.findTargetElement(myFixture.editor, offset, myFixture.file, originalElement)!!
val actual = ElmDocumentationProvider().block(element, originalElement)?.trim()!!
assertSameLines(expected.trimIndent(), actual)
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/lexer/ElmLayoutLexer.kt<|end_filename|>
package org.elm.lang.core.lexer
import com.intellij.lexer.Lexer
import com.intellij.lexer.LexerBase
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.intellij.util.text.CharArrayCharSequence
import org.elm.lang.core.lexer.State.*
import org.elm.lang.core.psi.ELM_COMMENTS
import org.elm.lang.core.psi.ElmTypes
import org.elm.lang.core.psi.ElmTypes.*
import java.util.LinkedList
import kotlin.collections.ArrayList
/**
* This is the main lexer. It wraps the underlying lexer generated by Flex
* to synthesize special tokens based on whitespace-sensitive layout rules
* in the Elm language. This makes it possible to write a traditional parser
* using GrammarKit.
*
* @see ElmIncrementalLexer
*/
class ElmLayoutLexer(private val lexer: Lexer) : LexerBase() {
private lateinit var tokens: ArrayList<Token>
private var currentTokenIndex = 0
private val currentToken: Token
get() = tokens[currentTokenIndex]
@Deprecated("")
fun start(buffer: CharArray, startOffset: Int, endOffset: Int, initialState: Int) {
start(CharArrayCharSequence(*buffer), startOffset, endOffset, initialState)
}
override fun start(buffer: CharSequence, startOffset: Int, endOffset: Int, initialState: Int) {
require(startOffset == 0) { "does not support incremental lexing: startOffset must be 0" }
require(initialState == 0) { "does not support incremental lexing: initialState must be 0" }
// Start the incremental lexer
lexer.start(buffer, startOffset, endOffset, initialState)
tokens = doLayout(lexer)
currentTokenIndex = 0
}
override fun getState() = lexer.state
override fun getBufferSequence() = lexer.bufferSequence
override fun getBufferEnd() = lexer.bufferEnd
override fun getTokenType() = currentToken.elementType
override fun getTokenStart() = currentToken.start
override fun getTokenEnd() = currentToken.end
override fun advance() {
if (currentToken.isEOF)
return
currentTokenIndex++
}
}
private fun slurpTokens(lexer: Lexer): MutableList<Token> {
val tokens = ArrayList<Token>()
var line = Line()
var currentColumn = 0
while (true) {
val token = Token(lexer.tokenType, lexer.tokenStart, lexer.tokenEnd, currentColumn, line)
tokens.add(token)
if (line.columnWhereCodeStarts == null && token.isCode) {
line.columnWhereCodeStarts = currentColumn
}
currentColumn += token.end - token.start
if (token.isEOF) {
break
} else if (token.elementType == NEWLINE) {
line = Line()
currentColumn = 0
}
lexer.advance()
}
return tokens
}
private enum class State {
/** The start state. Do not perform layout until we get to the first real line of code
*/
START,
/** Waiting for the first line of code inside a let/in or case/of in order to open a new section. */
WAITING_FOR_SECTION_START,
/**
* Looking to emit virtual delimiters between declarations at the same indent level
* and closing out sections when appropriate.
*/
NORMAL
}
private fun doLayout(lexer: Lexer): ArrayList<Token> {
val tokens = slurpTokens(lexer)
// initial state
var i = 0
var state = START
val indentStack = IndentStack()
indentStack.push(0) // top-level is an implicit section
while (true) {
val token = tokens[i]
when (state) {
START -> {
if (token.isCode && token.column == 0) {
state = NORMAL
}
}
WAITING_FOR_SECTION_START -> {
if (token.isCode && token.column > indentStack.peek()) {
tokens.add(i, virtualToken(VIRTUAL_OPEN_SECTION, tokens[i - 1]))
i++
state = NORMAL
indentStack.push(token.column)
} else if (token.isFirstSignificantTokenOnLine() && token.column <= indentStack.peek()) {
// The Elm program is malformed: most likely because the new section is empty
// (the user is still editing the text) or they did not indent the section.
// The empty section case is a common workflow, so we must handle it by bailing
// out of section building and re-process the token in the 'NORMAL' state.
// If, instead, the problem is that the user did not indent the text,
// tough luck (although we may want to handle this better in the future).
state = NORMAL
i--
}
}
NORMAL -> {
if (SECTION_CREATING_KEYWORDS.contains(token.elementType)) {
state = WAITING_FOR_SECTION_START
} else if (token.isFirstSignificantTokenOnLine()) {
var insertAt = i
// We want to insert virtual tokens immediately after the newline that follows
// the last code token. This is important so that:
//
// (1) trailing spaces at the end of the declaration are part of the declaration
// (2) top-level comments that follow the declaration are NOT part of the declaration
//
// Note that a virtual token has to appear after a whitespace token, since the real token
// is combined with the virtual token during parsing (their text ranges overlap).
loop@ for (k in (i - 1) downTo 1) {
if (tokens[k].isCode) {
for (m in (k + 1) until (i + 1)) {
if (tokens[m].elementType == NEWLINE) {
insertAt = m + 1
break@loop
}
}
}
}
val precedingToken = tokens[insertAt - 1]
while (token.column <= indentStack.peek()) {
if (token.column == indentStack.peek()) {
tokens.add(insertAt, virtualToken(VIRTUAL_END_DECL, precedingToken))
i++
break
} else if (token.column < indentStack.peek()) {
tokens.add(insertAt, virtualToken(VIRTUAL_END_SECTION, precedingToken))
i++
insertAt++
indentStack.pop()
}
}
} else if (isSingleLineLetIn(i, tokens)) {
tokens.add(i, virtualToken(VIRTUAL_END_SECTION, tokens[i - 1]))
i++
indentStack.pop()
}
}
}
i++
if (i >= tokens.size)
break
}
return ArrayList(tokens)
}
private fun isSingleLineLetIn(index: Int, tokens: List<Token>): Boolean {
/*
Elm allows for a let/in expression on a single line:
e.g. ```foo = let x = 0 in x + 1```
I don't know why you would ever do this, but some people do:
https://github.com/klazuka/intellij-elm/issues/20#issuecomment-374843581
If we didn't have special handling for it, the `let` section wouldn't
get closed-out until a subsequent line with less indent, which would be wrong.
*/
val token = tokens[index]
if (token.elementType != ElmTypes.IN)
return false
val thisLine = token.line
var i = index
do {
val t = tokens[i--]
if (t.elementType == ElmTypes.LET)
return true
} while (t.line == thisLine && i in 0 until tokens.size)
return false
}
/**
* In a well-formed program, there would be no way to underflow the indent stack,
* but this lexer will be asked to lex malformed/partial Elm programs, so we need
* to guard against trying to use the stack when it's empty.
*/
private class IndentStack : LinkedList<Int>() {
override fun peek(): Int {
return if (super.isEmpty()) -1 else super.peek()
}
override fun pop(): Int {
return if (super.isEmpty()) -1 else super.pop()
}
}
private fun virtualToken(elementType: IElementType, precedesToken: Token): Token {
return Token(
elementType = elementType,
start = precedesToken.start,
end = precedesToken.start, // yes, this is intentional
column = precedesToken.column,
line = precedesToken.line)
}
private val NON_CODE_TOKENS = TokenSet.orSet(TokenSet.create(TokenType.WHITE_SPACE, TAB, NEWLINE), ELM_COMMENTS)
private val SECTION_CREATING_KEYWORDS = TokenSet.create(LET, OF)
private class Line(var columnWhereCodeStarts: Int? = null)
private class Token(val elementType: IElementType?,
val start: Int,
val end: Int,
val column: Int,
val line: Line) {
override fun toString() =
"${elementType.toString()} ($start, $end)"
val isEOF: Boolean
get() = elementType == null
val isCode: Boolean
get() = !NON_CODE_TOKENS.contains(elementType) && !isEOF
fun isFirstSignificantTokenOnLine() =
isCode && column == line.columnWhereCodeStarts
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/TypeAnnotation.elm<|end_filename|>
update : Msg -> Foo.Model -> (Foo.Model, Cmd Msg)
map : (a -> b) -> List a -> List b
titleOfThing : { a | title : String } -> String
second : (a, b) -> b
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/NegateExpression.elm<|end_filename|>
foo = -
<|start_filename|>src/main/kotlin/org/elm/lang/core/stubs/ElmPlaceholderStub.kt<|end_filename|>
package org.elm.lang.core.stubs
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.*
import org.elm.lang.core.psi.ElmPsiElement
import org.elm.lang.core.resolve.ElmReferenceElement
/**
* The placeholder stub is used for any stub element which does not need to store additional data.
* It's only purpose is to decrease boilerplate for elements whose only reason they exist as a
* stub is to hold stub children.
*
* @see ElmPlaceholderRefStub
*/
class ElmPlaceholderStub(
parent: StubElement<*>?,
elementType: IStubElementType<*, *>
) : StubBase<ElmPsiElement>(parent, elementType) {
class Type<T : ElmPsiElement>(
name: String,
private val ctor: (ElmPlaceholderStub, IStubElementType<*, *>) -> T
) : ElmStubElementType<ElmPlaceholderStub, T>(name) {
override fun shouldCreateStub(node: ASTNode) =
createStubIfParentIsStub(node)
override fun serialize(stub: ElmPlaceholderStub, dataStream: StubOutputStream) {
// nothing extra to write
}
override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) =
ElmPlaceholderStub(parentStub, this) // nothing extra to read
override fun createPsi(stub: ElmPlaceholderStub) =
ctor(stub, this)
override fun createStub(psi: T, parentStub: StubElement<*>?) =
ElmPlaceholderStub(parentStub, this)
override fun indexStub(stub: ElmPlaceholderStub, sink: IndexSink) {
// no-op
}
}
}
/**
* Like [ElmPlaceholderStub] but for the common-case where the stub needs to also
* hold its reference name.
*
* @see ElmPlaceholderStub
*/
class ElmPlaceholderRefStub(
parent: StubElement<*>?,
elementType: IStubElementType<*, *>,
val refName: String
) : StubBase<ElmReferenceElement>(parent, elementType) {
class Type<T : ElmReferenceElement>(
name: String,
private val ctor: (ElmPlaceholderRefStub, IStubElementType<*, *>) -> T
) : ElmStubElementType<ElmPlaceholderRefStub, T>(name) {
override fun shouldCreateStub(node: ASTNode) =
createStubIfParentIsStub(node)
override fun serialize(stub: ElmPlaceholderRefStub, dataStream: StubOutputStream) {
with(dataStream) {
writeName(stub.refName)
}
}
override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?) =
ElmPlaceholderRefStub(parentStub, this,
dataStream.readNameString()!!)
override fun createPsi(stub: ElmPlaceholderRefStub) =
ctor(stub, this)
override fun createStub(psi: T, parentStub: StubElement<*>?) =
ElmPlaceholderRefStub(parentStub, this, psi.referenceName)
override fun indexStub(stub: ElmPlaceholderRefStub, sink: IndexSink) {
// no-op
}
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/stubs/fixtures/Foo.elm<|end_filename|>
module Foo exposing (..)
type alias Foo =
{ n : Int }
z : Foo
z = { n = 42 }
bar = "bar"
type Baz = A String | B
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmTupleType.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.*
import org.elm.lang.core.stubs.ElmPlaceholderStub
/**
* A type expression for a tuple
*
* e.g. `(Int, String)` in a type declaration or annotation
*/
class ElmTupleType : ElmStubbedElement<ElmPlaceholderStub>,
ElmUnionVariantParameterTag, ElmTypeRefArgumentTag, ElmTypeExpressionSegmentTag {
constructor(node: ASTNode) :
super(node)
constructor(stub: ElmPlaceholderStub, stubType: IStubElementType<*, *>) :
super(stub, stubType)
val typeExpressionList: List<ElmTypeExpression>
get() = stubDirectChildrenOfType()
val unitExpr: ElmUnitExpr?
get() = stubDirectChildrenOfType<ElmUnitExpr>().singleOrNull()
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmTuplePattern.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.util.PsiTreeUtil
import org.elm.lang.core.psi.*
/**
* Pattern matching on the components of a tuple
*
* e.g. `(x, y)` in the function `scalePoint (x, y) s = (x * s, y * s)`
*/
class ElmTuplePattern(node: ASTNode) : ElmPsiElementImpl(node), ElmFunctionParamTag,
ElmPatternChildTag, ElmUnionPatternChildTag {
val patternList: List<ElmPattern>
get() = PsiTreeUtil.getChildrenOfTypeAsList(this, ElmPattern::class.java)
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmFieldType.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.ElmStubbedNamedElementImpl
import org.elm.lang.core.psi.ElmTypes.LOWER_CASE_IDENTIFIER
import org.elm.lang.core.psi.IdentifierCase.LOWER
import org.elm.lang.core.psi.stubDirectChildrenOfType
import org.elm.lang.core.stubs.ElmFieldTypeStub
/**
* The definition of a record field's type.
*
* e.g. `name : String` in the record definition `type alias Person = { name : String }`
*/
class ElmFieldType : ElmStubbedNamedElementImpl<ElmFieldTypeStub> {
constructor(node: ASTNode) :
super(node, LOWER)
constructor(stub: ElmFieldTypeStub, stubType: IStubElementType<*, *>) :
super(stub, stubType, LOWER)
/**
* The name of a field in a record literal type definition
*/
val lowerCaseIdentifier: PsiElement
get() = findNotNullChildByType(LOWER_CASE_IDENTIFIER)
/**
* The definition of the type of the field.
*/
val typeExpression: ElmTypeExpression
get() = stubDirectChildrenOfType<ElmTypeExpression>().single()
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmAnonymousFunctionExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.util.PsiTreeUtil
import org.elm.lang.core.psi.*
/**
* A lambda expression
*
* e.g. `\x -> x + 1`
*/
class ElmAnonymousFunctionExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmAtomTag, ElmFunctionCallTargetTag {
/** Zero-or-more parameters to the lambda expression */
val patternList: List<ElmPattern>
get() = PsiTreeUtil.getChildrenOfTypeAsList(this, ElmPattern::class.java)
/** The body expression */
val expression: ElmExpressionTag
get() = findNotNullChildByClass(ElmExpressionTag::class.java)
/** Named elements introduced by pattern destructuring in the parameter list */
val namedParameters: List<ElmNameDeclarationPatternTag>
get() = patternList.flatMap {
PsiTreeUtil.collectElementsOfType(it, ElmNameDeclarationPatternTag::class.java)
}
}
<|start_filename|>src/main/kotlin/org/elm/openapiext/ui.kt<|end_filename|>
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*
* Originally from intellij-rust
*/
package org.elm.openapiext
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.ui.TextComponentAccessor
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.Disposer
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.components.JBCheckBox
import com.intellij.util.Alarm
import javax.swing.event.DocumentEvent
import kotlin.reflect.KProperty
class UiDebouncer(
private val parentDisposable: Disposable,
private val delayMillis: Int = 200
) {
private val alarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, parentDisposable)
/**
* @param onUiThread: callback to be executed in EDT with **any** modality state.
* Use it only for UI updates
*/
fun <T> run(onPooledThread: () -> T, onUiThread: (T) -> Unit) {
if (Disposer.isDisposed(parentDisposable)) return
alarm.cancelAllRequests()
alarm.addRequest({
val r = onPooledThread()
ApplicationManager.getApplication().invokeLater({
if (!Disposer.isDisposed(parentDisposable)) {
onUiThread(r)
}
}, ModalityState.any())
}, delayMillis)
}
}
fun fileSystemPathTextField(
disposable: Disposable,
title: String,
fileDescriptor: FileChooserDescriptor,
onTextChanged: () -> Unit = {}
): TextFieldWithBrowseButton {
val component = TextFieldWithBrowseButton(null, disposable)
component.addBrowseFolderListener(title, null, null, fileDescriptor, TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT)
component.childComponent.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
onTextChanged()
}
})
return component
}
class CheckboxDelegate(private val checkbox: JBCheckBox) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): Boolean {
return checkbox.isSelected
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) {
checkbox.isSelected = value
}
}
<|start_filename|>src/test/kotlin/org/elm/ide/refactoring/ElmImportOptimizerTest.kt<|end_filename|>
package org.elm.ide.refactoring
import org.elm.lang.ElmTestBase
import org.intellij.lang.annotations.Language
class ElmImportOptimizerTest : ElmTestBase() {
fun `test do nothing if no imports at all`() =
doTest(
"""
--@ Main.elm
main = ()
--^
--@ Foo.elm
module Foo exposing (..)
foo = 42
""",
"""
main = ()
--^
""")
fun `test removes unused imports`() =
doTest(
"""
--@ Main.elm
import Bar
import Foo
import Quux exposing (quux)
main = Bar.bar + Quux.quux
--^
--@ Foo.elm
module Foo exposing (..)
foo = 1
--@ Bar.elm
module Bar exposing (..)
bar = 2
--@ Quux.elm
module Quux exposing (..)
quux = 3
""",
"""
import Bar
import Quux
main = Bar.bar + Quux.quux
--^
""")
/*
For more detailed tests related to DETECTING unused imports, see [ElmUnusedImportInspectionTest]
*/
private fun doTest(@Language("Elm") before: String, @Language("Elm") after: String) {
configureByFileTree(before)
myFixture.performEditorAction("OptimizeImports")
myFixture.checkResult(after.trimStart())
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/FieldAccessors.elm<|end_filename|>
f1 x = x.
f2 x = x.bar.
f3 x = Foo.bar.
p1 x = (foo x).
p2 x = (foo x).bar.
r1 = {x=2}.
r2 = {x={y=2}}.x.
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/ModulesEffect.elm<|end_filename|>
effect module Time where { subscription = MySub } exposing (now)
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/basic/fixtures/Strings.elm<|end_filename|>
""
" "
"a"
"\u{1F648}"
"""single line multi line"""
"""multi
line"""
""""""""
"""
"""
"""
"\"""
"""
"""
\
"""
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmExposedValue.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.ElmExposedItemTag
import org.elm.lang.core.psi.ElmStubbedElement
import org.elm.lang.core.psi.ElmTypes.LOWER_CASE_IDENTIFIER
import org.elm.lang.core.psi.parentOfType
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReference
import org.elm.lang.core.resolve.reference.ExposedValueImportReference
import org.elm.lang.core.resolve.reference.ExposedValueModuleReference
import org.elm.lang.core.stubs.ElmPlaceholderRefStub
/**
* A value or function exposed via an import clause's `exposing` list.
*
* e.g. `bar` in `import Foo exposing (bar)`
*/
class ElmExposedValue : ElmStubbedElement<ElmPlaceholderRefStub>, ElmReferenceElement, ElmExposedItemTag {
constructor(node: ASTNode) :
super(node)
constructor(stub: ElmPlaceholderRefStub, stubType: IStubElementType<*, *>) :
super(stub, stubType)
val lowerCaseIdentifier: PsiElement
get() = findNotNullChildByType(LOWER_CASE_IDENTIFIER)
override val referenceNameElement: PsiElement
get() = lowerCaseIdentifier
override val referenceName: String
get() = stub?.refName ?: referenceNameElement.text
override fun getReference(): ElmReference =
if (parentOfType<ElmModuleDeclaration>() != null)
ExposedValueModuleReference(this)
else
ExposedValueImportReference(this)
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/TypeAliasDecl.elm<|end_filename|>
type alias Blah [garbage]
type alias Blah = if 0 then 1 else 2
type alias Blah = String 42
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmGlslCodeExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiLanguageInjectionHost
import org.elm.ide.injection.GlslEscaper
import org.elm.lang.core.psi.ElmAtomTag
import org.elm.lang.core.psi.ElmPsiElementImpl
import org.elm.lang.core.psi.ElmPsiFactory
import org.elm.lang.core.psi.ElmTypes
class ElmGlslCodeExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmAtomTag, PsiLanguageInjectionHost {
val content: List<PsiElement> get() = findChildrenByType(ElmTypes.GLSL_CODE_CONTENT)
override fun updateText(text: String): PsiLanguageInjectionHost {
val expr = ElmPsiFactory(project).createGlslExpr(text)
node.replaceAllChildrenToChildrenOf(expr.node)
return this
}
override fun createLiteralTextEscaper() = GlslEscaper(this)
override fun isValidHost(): Boolean = true
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmListPattern.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import org.elm.lang.core.psi.*
/**
* A list pattern.
*
* e.g. `[a, (b, c)]`
*/
class ElmListPattern(node: ASTNode) : ElmPsiElementImpl(node), ElmFunctionParamTag,
ElmPatternChildTag, ElmUnionPatternChildTag {
/** The patterns that are part of the list. May be empty. */
val parts: Sequence<ElmPatternChildTag> get() = directChildren.filterIsInstance<ElmPatternChildTag>()
}
<|start_filename|>src/main/kotlin/org/elm/utils/EditorUtils.kt<|end_filename|>
package org.elm.utils
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.util.DocumentUtil
/**
* Calculates indent of the line containing [offset]
* @return Whitespaces at the beginning of the line
*/
fun Document.getIndent(offset: Int): String = DocumentUtil.getIndent(this, offset).toString()
/**
* Calculates indent of the line containing [offset]
* @return Whitespaces at the beginning of the line
*/
fun Editor.getIndent(offset: Int): String = document.getIndent(offset)
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmRecordBaseIdentifier.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.ElmStubbedElement
import org.elm.lang.core.psi.ElmTypes.LOWER_CASE_IDENTIFIER
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReference
import org.elm.lang.core.resolve.reference.LexicalValueReference
import org.elm.lang.core.resolve.reference.TypeVariableReference
import org.elm.lang.core.stubs.ElmPlaceholderRefStub
/**
* This can occur in 2 different contexts:
*
* - In a record literal update expression, the name of an existing record which is to be updated.
* - e.g. the first instance of person in `{ person | age = person.age + 1 }`
* - in this case, the identifier acts as reference to a name in the lexical scope
*
* - In an extension record type expression, the base record type variable
* - e.g. the `a` immediately before the pipe character in `type alias User a = { a | name : String }
* - e.g. the `a` in `foo : { a | name : String } -> String`
* - in this case, the identifier acts as a type variable which may or may not resolve
* (the type alias example above will resolve, but the function parameter example will not resolve)
*
*/
class ElmRecordBaseIdentifier : ElmStubbedElement<ElmPlaceholderRefStub>, ElmReferenceElement {
constructor(node: ASTNode) :
super(node)
constructor(stub: ElmPlaceholderRefStub, stubType: IStubElementType<*, *>) :
super(stub, stubType)
override val referenceNameElement: PsiElement
get() = findNotNullChildByType(LOWER_CASE_IDENTIFIER)
override val referenceName: String
get() = stub?.refName ?: referenceNameElement.text
override fun getReference(): ElmReference = references.first()
override fun getReferences(): Array<ElmReference> {
return when (parent) {
is ElmRecordType -> arrayOf(TypeVariableReference(this))
is ElmRecordExpr -> arrayOf(LexicalValueReference(this))
else -> emptyArray()
}
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/DottedExpressions.elm<|end_filename|>
f1 x = bar x
f2 x = Foo.bar
f3 x = Quux
f4 x = Foo.Quux
f5 x = Foo.Bar.baz
f5 x = Foo.Bar.Baz
f6 x = foo.bar
f7 x = foo.bar.baz.quux
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmRecordType.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.*
import org.elm.lang.core.stubs.ElmPlaceholderStub
/**
* A record type definition
*
* e.g. { name : String, age : Int }
*/
class ElmRecordType : ElmStubbedElement<ElmPlaceholderStub>,
ElmUnionVariantParameterTag, ElmTypeRefArgumentTag, ElmTypeExpressionSegmentTag {
constructor(node: ASTNode) :
super(node)
constructor(stub: ElmPlaceholderStub, stubType: IStubElementType<*, *>) :
super(stub, stubType)
/**
* The type variable representing a generic record which this
* definition extends.
*
* e.g. entity in `{ entity | vx : Float, vy: Float }`
*/
val baseTypeIdentifier: ElmRecordBaseIdentifier?
get() = stubDirectChildrenOfType<ElmRecordBaseIdentifier>().singleOrNull()
/**
* The definition of the fields which comprise the record proper.
*/
val fieldTypeList: List<ElmFieldType>
get() = stubDirectChildrenOfType()
}
<|start_filename|>src/test/kotlin/org/elm/lang/core/resolve/ElmLayeredImportResolveTest.kt<|end_filename|>
package org.elm.lang.core.resolve
class ElmLayeredImportResolveTest : ElmResolveTestBase() {
/**
* Layered imports are imports where multiple modules are imported using the same alias.
*/
fun `test layered import using first import`() = stubOnlyResolve(
"""
--@ main.elm
import Foo as F
import FooExtra as F
main = F.bar
--^Foo.elm
--@ Foo.elm
module Foo exposing (..)
bar = 42
--@ FooExtra.elm
module FooExtra exposing (..)
quux = 99
""")
fun `test layered import using second import`() = stubOnlyResolve(
"""
--@ main.elm
import Foo as F
import FooExtra as F
main = F.quux
--^FooExtra.elm
--@ Foo.elm
module Foo exposing (..)
bar = 42
--@ FooExtra.elm
module FooExtra exposing (..)
quux = 99
""")
}
<|start_filename|>src/test/kotlin/org/elm/ide/inspections/inference/TypeInferenceInspectionPartialProgramTest.kt<|end_filename|>
package org.elm.ide.inspections.inference
import org.elm.ide.inspections.ElmInspectionsTestBase
import org.elm.ide.inspections.ElmTypeInferenceInspection
class TypeInferenceInspectionPartialProgramTest : ElmInspectionsTestBase(ElmTypeInferenceInspection()) {
override fun getProjectDescriptor() = ElmWithStdlibDescriptor
fun `test nested function without in branch`() = checkByText("""
main =
let
foo : ()
foo =
<error descr="Type mismatch.Required: ()Found: Float">1.0</error><EOLError descr="VIRTUAL_END_DECL or VIRTUAL_END_SECTION expected"></EOLError>
""")
fun `test in expression without let branches`() = checkByText("""
main : ()
main =
let
foo<EOLError descr="COLON, EQ, LEFT_BRACE, LEFT_PARENTHESIS, LEFT_SQUARE_BRACKET, LOWER_CASE_IDENTIFIER, NUMBER_LITERAL, OPEN_CHAR, OPEN_QUOTE or UNDERSCORE expected"></EOLError>
in
<error descr="Type mismatch.Required: ()Found: Float">1.0</error>
""")
fun `test in expression with reference to error decl`() = checkByText("""
main : ()
main =
let
foo =<error descr="<expr> expected, got '...'"> </error>...
in
foo
""")
fun `test parenthesized in expression with reference to error decl`() = checkByText("""
main : ()
main =
(let
foo =<error descr="<expr> expected, got '...'"> </error>...
in
foo)
""")
fun `test let decl with forward reference to error decl`() = checkByText("""
main : ()
main =
let
foo : ()
foo =
bar
bar =<EOLError descr="<expr> expected, got '...'"></EOLError>
...
in
foo
""")
fun `test let decl with backward reference to error decl`() = checkByText("""
main : ()
main =
let
bar =<EOLError descr="<expr> expected, got '...'"></EOLError>
...
foo : ()
foo =
bar
in
foo
""")
fun `test case with no branches`() = checkByText("""
main : ()
main =
case ()<EOLError descr="<expr>, OF or OPERATOR_IDENTIFIER expected"></EOLError>
""")
fun `test case branches with case error`() = checkByText("""
main : ()
main =
case<error descr="<expr> expected, got 'of'"> </error> of
1 -> <error descr="Type mismatch.Required: ()Found: String">""</error>
_ -> <error descr="Type mismatch.Required: ()Found: number">1</error>
""")
fun `test case branch with pattern error`() = checkByText("""
main : ()
main =
case () of
a<error descr="'::', ARROW or AS expected, got '.'">.</error> -> a
""")
}
<|start_filename|>src/test/kotlin/org/elm/ide/typing/ElmTypingTestBase.kt<|end_filename|>
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*
* Originally from intellij-rust
*/
package org.elm.ide.typing
import org.elm.lang.ElmTestBase
import org.intellij.lang.annotations.Language
abstract class ElmTypingTestBase : ElmTestBase() {
protected fun doTest(c: Char = '\n') = checkByFile {
myFixture.type(c)
}
protected fun doTestByText(@Language("Elm") before: String,
@Language("Elm") after: String,
c: Char = '\n') =
checkByText(before.trimIndent(), after.trimIndent()) {
myFixture.type(c)
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/LetIn.elm<|end_filename|>
f1 = let
f2 = let
x
f3 = let
x =
f4 = let
x = 0
f5 = let
x = 0
in
f6 = let
x = 0
in
f7 = let
x = import Garbage
y = 1
in
y
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/Basics.elm<|end_filename|>
module Main exposing (main)
import Task
main =
text f
f = "hello world"
<|start_filename|>src/test/kotlin/org/elm/ide/inspections/inference/TypeInferenceStubAccessTest.kt<|end_filename|>
package org.elm.ide.inspections.inference
import com.intellij.openapi.vfs.VirtualFileFilter
import org.elm.fileTreeFromText
import org.elm.lang.ElmTestBase
import org.elm.lang.core.psi.ElmPsiElement
import org.elm.lang.core.psi.descendantsOfType
import org.elm.lang.core.psi.elements.ElmTypeAliasDeclaration
import org.elm.lang.core.psi.elements.ElmValueDeclaration
import org.elm.lang.core.psi.elements.ElmValueExpr
import org.elm.lang.core.types.findInference
import org.elm.lang.core.types.findTy
import org.elm.lang.core.types.renderedText
import org.elm.lang.core.types.typeExpressionInference
import org.intellij.lang.annotations.Language
class TypeInferenceStubAccessTest : ElmTestBase() {
/*
Type inference should use stubs as much as possible.
These tests are kinda weird because you need to setup strange situations
in the imported file in order to exercise the type inference code completely
over a stub-backed Psi tree. Most of these tests have been discovered by running
IntelliJ with debug logging enabled for "#com.intellij.psi.impl.source.PsiFileImpl"
and looking for unexpected "Loaded text for file" log messages when opening files
and running type inference. Then set a breakpoint where that log message is
emitted to check the callstack and create a test that recreates the scenario.
It's tedious and lame, but it works.
Ideally type inference could operate 100% using stubs. But this is only feasible
when functions have type annotations, in which case we do not need to peek into
the body of the function.
So in the rare case where the user calls an unannotated function from a different
module, the other module's stubs will be converted to full-AST-backed. The only
other option is to return `TyUnknown` in such cases, but we have chosen to avoid
the false negative.
*/
fun `test infer basic value expr across modules`() = stubOnlyTypeInfer<ElmValueExpr>(
"""
--@ Main.elm
import Foo
f : Foo.Bar -> ()
f x = x
--^Bar
--@ Foo.elm
module Foo exposing (..)
type alias Bar = ()
""")
fun `test infer function across modules with type annotation`() = stubOnlyTypeInfer<ElmValueExpr>(
"""
--@ Main.elm
import Foo exposing (foo)
f = foo
--^()
--@ Foo.elm
module Foo exposing (..)
foo : ()
foo = ()
""")
fun `test infer function across modules where type does not exist`() = stubOnlyTypeInfer<ElmValueExpr>(
"""
--@ Main.elm
import Foo exposing (foo)
f = foo
--^unknown
--@ Foo.elm
module Foo exposing (..)
foo : DoesNotExist
foo = 42
""")
fun `test infer record field across modules`() = stubOnlyTypeInfer<ElmValueExpr>(
"""
--@ Main.elm
import Foo
f : Foo.Bar -> ()
f { y } = y
--^()
--@ Foo.elm
module Foo exposing (..)
type alias Bar =
{ y : () }
""")
fun `test infer type expr across modules`() = stubOnlyTypeInfer<ElmTypeAliasDeclaration>(
"""
--@ Main.elm
import Foo exposing (Bar)
type alias Thing = Bar
--^Thing
--@ Foo.elm
module Foo exposing (..)
type alias Bar = ()
""")
fun `test infer union type with type variable expr`() = stubOnlyTypeInfer<ElmTypeAliasDeclaration>(
"""
--@ Main.elm
import Foo exposing (Bar)
type alias Thing = Bar ()
--^Thing
--@ Foo.elm
module Foo exposing (..)
type Bar a = Bar a
""")
fun `test infer with union type variable reference`() = stubOnlyTypeInfer<ElmValueExpr>(
"""
--@ Main.elm
import Foo exposing (..)
f = g
--^()
g = foo () 0
--@ Foo.elm
module Foo exposing (..)
foo : a -> b -> a
foo x y = x
""")
fun `test infer type via exposed import`() = stubOnlyTypeInfer<ElmTypeAliasDeclaration>(
"""
--@ Main.elm
import Foo exposing (Foo)
type alias Thing = Foo
--^Thing
--@ Foo.elm
module Foo exposing (..)
import Bar exposing (Bar)
type alias Foo = Bar
--@ Bar.elm
module Bar exposing (..)
type alias Bar = ()
""")
fun `test infer qualified type expr in other file`() = stubOnlyTypeInfer<ElmTypeAliasDeclaration>(
"""
--@ Main.elm
import Foo exposing (Foo)
type alias Thing = Foo
--^Thing
--@ Foo.elm
module Foo exposing (..)
import Bar
type alias Foo = Bar.Bar
--@ Bar.elm
module Bar exposing (..)
type alias Bar = ()
""")
fun `test infer func that destructures union type parameter`() = stubOnlyTypeInfer<ElmValueExpr>(
"""
--@ Main.elm
import Foo exposing (..)
f = g
--^()
g = foo (Foo ())
--@ Foo.elm
module Foo exposing (..)
type Foo = Foo ()
foo : Foo -> ()
foo (Foo x) = x
""")
fun `test infer infix operator`() = stubOnlyTypeInfer<ElmValueExpr>(
"""
--@ Main.elm
import Foo exposing ((**))
f = g
--^()
g = () ** ()
--@ Foo.elm
module Foo exposing (..)
infix left 7 (**) = foo
foo : a -> b -> a
foo x y = x
""")
fun `test infer port annotation`() = stubOnlyTypeInfer<ElmValueExpr>(
"""
--@ Main.elm
import Foo exposing (foo)
f = foo
--^()
--@ Foo.elm
port module Foo exposing (..)
port foo : ()
""")
fun `test infer function with extensible record param`() = stubOnlyTypeInfer<ElmValueExpr>(
"""
--@ Main.elm
import Foo exposing (foo)
f = g
--^()
g = foo { id = 0, name = () }
--@ Foo.elm
module Foo exposing (..)
foo : { a | name : () } -> ()
foo { name } = name
""")
private inline fun <reified T : ElmPsiElement> stubOnlyTypeInfer(@Language("Elm") code: String) {
val testProject = fileTreeFromText(code)
.createAndOpenFileWithCaretMarker()
checkAstNotLoaded(VirtualFileFilter { file ->
!file.path.endsWith(testProject.fileWithCaret)
})
checkExpectedType<T>()
checkNoInferenceErrors()
}
private inline fun <reified T : ElmPsiElement> checkExpectedType() {
val (expr, expectedType) = findElementAndDataInEditor<T>()
// TODO [kl] Find a better way to get the ty for any ElmPsiElement.
val ty = when (expr) {
is ElmValueExpr -> expr.findTy()
is ElmTypeAliasDeclaration -> expr.typeExpressionInference().value
else -> error("not handled")
}
val renderedText = ty?.renderedText()
check(renderedText == expectedType) {
"Type mismatch. Expected: $expectedType, found: $renderedText ($ty)"
}
}
private fun checkNoInferenceErrors() {
val diagnostics = myFixture.file.descendantsOfType<ElmValueDeclaration>()
.flatMap { it.findInference()?.diagnostics ?: emptyList() }
if (diagnostics.isNotEmpty()) {
error(
diagnostics.joinToString("\n", "Program failed to type check: \n") {
"\t${it.message}"
}
)
}
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/ModuleDecl0.elm<|end_filename|>
module Foo exp
bar = 42
<|start_filename|>src/test/resources/org/elm/ide/folding/fixtures/record_type.elm<|end_filename|>
{ foo : Foo
, bar : Bar Int
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/FieldAccessors.elm<|end_filename|>
f1 x = x.bar
f2 x = x.bar.baz
f3 x = Foo.bar.baz
p1 x = (foo x).bar
p2 x = (foo x).bar.baz
r1 = {x=2}.x
r2 = {x={y=2}}.x.y
<|start_filename|>src/main/kotlin/org/elm/lang/core/completion/ElmPlatformPatterns.kt<|end_filename|>
package org.elm.lang.core.completion
import com.intellij.patterns.*
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ProcessingContext
inline fun <reified I : PsiElement> psiElement(): PsiElementPattern.Capture<I> {
return PlatformPatterns.psiElement(I::class.java)
}
/**
* Similar with [TreeElementPattern.afterSiblingSkipping]
* but it uses [PsiElement.getPrevSibling] to get previous sibling elements
* instead of [PsiElement.getChildren].
*/
fun <T : PsiElement, Self : PsiElementPattern<T, Self>> PsiElementPattern<T, Self>.withPrevSiblingSkipping(
skip: ElementPattern<out T>,
pattern: ElementPattern<out T>
): Self = with("withPrevSiblingSkipping") {
val sibling = it.leftSiblings.dropWhile { skip.accepts(it) }
.firstOrNull() ?: return@with false
pattern.accepts(sibling)
}
private fun <T, Self : ObjectPattern<T, Self>> ObjectPattern<T, Self>.with(name: String, cond: (T) -> Boolean): Self =
with(object : PatternCondition<T>(name) {
override fun accepts(t: T, context: ProcessingContext?): Boolean = cond(t)
})
val PsiElement.leftLeaves: Sequence<PsiElement> get() = generateSequence(this, PsiTreeUtil::prevLeaf).drop(1)
val PsiElement.rightSiblings: Sequence<PsiElement> get() = generateSequence(this.nextSibling) { it.nextSibling }
val PsiElement.leftSiblings: Sequence<PsiElement> get() = generateSequence(this.prevSibling) { it.prevSibling }
<|start_filename|>src/main/kotlin/org/elm/ide/injection/GlslEscaper.kt<|end_filename|>
package org.elm.ide.injection
import com.intellij.openapi.util.TextRange
import com.intellij.psi.LiteralTextEscaper
import org.elm.lang.core.psi.elements.ElmGlslCodeExpr
// GLSL blocks don't require any escaping, so this is a passthrough
class GlslEscaper(host: ElmGlslCodeExpr) : LiteralTextEscaper<ElmGlslCodeExpr>(host) {
override fun isOneLine(): Boolean = false
override fun getOffsetInHost(offsetInDecoded: Int, rangeInsideHost: TextRange): Int {
return rangeInsideHost.startOffset + offsetInDecoded
}
override fun decode(rangeInsideHost: TextRange, outChars: StringBuilder): Boolean {
outChars.append(rangeInsideHost.substring(myHost.text))
return true
}
}
<|start_filename|>src/main/kotlin/org/elm/ide/utils/SearchByOffset.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elm.ide.utils
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import org.elm.lang.core.psi.*
/**
* Find an [ElmExpressionTag] element at [offset], being smart about whether
* we look to the left or the right of the caret offset.
*/
fun findExpressionAtCaret(file: ElmFile, offset: Int): ElmExpressionTag? {
val expr = file.expressionAtOffset(offset)
val exprBefore = file.expressionAtOffset(offset - 1)
return when {
expr == null -> exprBefore
exprBefore == null -> expr
PsiTreeUtil.isAncestor(expr, exprBefore, false) -> exprBefore
else -> expr
}
}
private fun ElmFile.expressionAtOffset(offset: Int): ElmExpressionTag? =
findElementAt(offset)?.parentOfType(strict = false)
/**
* Finds top-most [ElmExpressionTag] within selected range.
*/
fun findExpressionInRange(file: PsiFile, startOffset: Int, endOffset: Int): ElmExpressionTag? {
val (element1, element2) = file.getElementRange(startOffset, endOffset) ?: return null
// Get common expression parent.
var parent = PsiTreeUtil.findCommonParent(element1, element2) ?: return null
parent = parent.parentOfType<ElmExpressionTag>(strict = false) ?: return null
// If our parent's deepest first child is element1 and deepest last - element 2,
// then it is completely within selection, so this is our sought expression.
if (element1 == PsiTreeUtil.getDeepestFirst(parent) && element2 == PsiTreeUtil.getDeepestLast(element2)) {
return parent
}
return null
}
/**
* Finds two edge leaf PSI elements within given range.
*/
fun PsiFile.getElementRange(startOffset: Int, endOffset: Int): Pair<PsiElement, PsiElement>? {
val element1 = findElementAtIgnoreWhitespaceBefore(startOffset) ?: return null
val element2 = findElementAtIgnoreWhitespaceAfter(endOffset - 1) ?: return null
// Elements have crossed (for instance when selection was inside single whitespace block)
if (element1.startOffset >= element2.endOffset) return null
return element1 to element2
}
/**
* Finds a leaf PSI element at the specified offset from the start of the text range of this node.
* If found element is whitespace, returns its next non-whitespace sibling.
*/
fun PsiFile.findElementAtIgnoreWhitespaceBefore(offset: Int): PsiElement? {
val element = findElementAt(offset)
if (element is PsiWhiteSpace) {
return findElementAt(element.getTextRange().endOffset)
}
return element
}
/**
* Finds a leaf PSI element at the specified offset from the start of the text range of this node.
* If found element is whitespace, returns its previous non-whitespace sibling.
*/
fun PsiFile.findElementAtIgnoreWhitespaceAfter(offset: Int): PsiElement? {
val element = findElementAt(offset)
if (element is PsiWhiteSpace) {
return findElementAt(element.getTextRange().startOffset - 1)
}
return element
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmListExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.util.PsiTreeUtil
import org.elm.lang.core.psi.ElmAtomTag
import org.elm.lang.core.psi.ElmExpressionTag
import org.elm.lang.core.psi.ElmPsiElementImpl
class ElmListExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmAtomTag {
val expressionList: List<ElmExpressionTag>
get() = PsiTreeUtil.getChildrenOfTypeAsList(this, ElmExpressionTag::class.java)
}
<|start_filename|>src/main/kotlin/org/elm/ide/intentions/MakeAnnotationIntention.kt<|end_filename|>
package org.elm.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.elements.ElmFunctionDeclarationLeft
import org.elm.lang.core.psi.elements.ElmValueDeclaration
import org.elm.lang.core.psi.parentOfType
import org.elm.lang.core.psi.startOffset
import org.elm.lang.core.types.Ty
import org.elm.lang.core.types.findTy
import org.elm.lang.core.types.renderedText
import org.elm.openapiext.runWriteCommandAction
import org.elm.utils.getIndent
class MakeAnnotationIntention : ElmAtCaretIntentionActionBase<MakeAnnotationIntention.Context>() {
data class Context(val fdl: ElmFunctionDeclarationLeft, val valueDeclaration: ElmValueDeclaration, val ty: Ty)
override fun getText() = "Add type annotation"
override fun getFamilyName() = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val fdl = element.parentOfType<ElmFunctionDeclarationLeft>()
?: return null
val declaration = fdl.parentOfType<ElmValueDeclaration>()
?: return null
if (declaration.typeAnnotation != null) {
// the target annotation already exists; nothing needs to be done
return null
}
val ty = declaration.findTy() ?: return null
return Context(fdl, declaration, ty)
}
override fun invoke(project: Project, editor: Editor, context: Context) {
val (fdl, valueDeclaration, ty) = context
val indent = editor.getIndent(valueDeclaration.startOffset)
val code = "${fdl.name} : ${ty.renderedText(elmFile = fdl.elmFile).replace("→", "->")}\n$indent"
project.runWriteCommandAction {
editor.document.insertString(valueDeclaration.startOffset, code)
}
}
}
<|start_filename|>src/test/kotlin/org/elm/lang/core/completion/ElmCompletionTestBase.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elm.lang.core.completion
import com.intellij.codeInsight.lookup.LookupElement
import org.elm.fileTreeFromText
import org.elm.hasCaretMarker
import org.elm.lang.ElmTestBase
import org.intellij.lang.annotations.Language
abstract class ElmCompletionTestBase: ElmTestBase() {
protected fun doSingleCompletion(@Language("Elm") before: String, @Language("Elm") after: String) {
check(hasCaretMarker(before) && hasCaretMarker(after)) {
"Please add `{-caret-}` marker"
}
checkByText(before, after) { executeSoloCompletion() }
}
protected fun doSingleCompletionMultiFile(@Language("Elm") before: String, @Language("Elm") after: String) {
fileTreeFromText(before).createAndOpenFileWithCaretMarker()
executeSoloCompletion()
myFixture.checkResult(replaceCaretMarker(after.trimIndent()))
}
protected fun checkContainsCompletion(text: String, @Language("Elm") code: String) {
InlineFile(code).withCaret()
val variants = myFixture.completeBasic()
when {
variants == null -> {
// IntelliJ returns null if there was only one completion possible. In which case, all we need
// to do is verify that the completion that it performed was the one that was expected.
// Unfortunately that's a bit hard to express, so we will just do something sloppy and make sure
// that the expected text got inserted somewhere. What could possibly go wrong? ;-)
val fullText = myFixture.editor.document.text
check(fullText.contains(text)) {
"Expected completions that contain $text, but it actually completed as something else:\n$fullText"
}
}
variants.isEmpty() ->
error("Expected completions that contain $text, but got no completions at all")
variants.none { it.lookupString == text } ->
error("Expected completions that contain $text, but got ${variants.toList()}")
}
}
protected fun checkNoCompletion(@Language("Elm") code: String) {
InlineFile(code).withCaret()
noCompletionCheck()
}
protected fun checkNoCompletionWithMultiFile(@Language("Elm") code: String) {
fileTreeFromText(code).createAndOpenFileWithCaretMarker()
noCompletionCheck()
}
private fun noCompletionCheck() {
val variants = myFixture.completeBasic()
checkNotNull(variants) {
val element = myFixture.file.findElementAt(myFixture.caretOffset - 1)
"Expected zero completions, but one completion was auto inserted: `${element?.text}`."
}
check(variants.isEmpty()) {
"Expected zero completions, got ${variants.size}."
}
}
protected fun executeSoloCompletion() {
val variants = myFixture.completeBasic()
if (variants != null) {
if (variants.size == 1) {
// for cases like `frob{-caret-}nicate()`,
// completion won't be selected automatically.
myFixture.type('\n')
return
}
fun LookupElement.debug(): String = "$lookupString ($psiElement)"
error("Expected a single completion, but got ${variants.size}\n"
+ variants.joinToString("\n") { it.debug() })
}
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/TypeDecl.elm<|end_filename|>
type User { xyz }
type User = if 0 then 1 else 2
type User [garbage]
type User = A | bogus_identifier | C
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmInfixDeclaration.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.*
import org.elm.lang.core.stubs.ElmInfixDeclarationStub
/**
* A top-level declaration that describes the associativity and the precedence
* of a binary operator.
*
* For example, `infix right 5 (++) = append` means that the operator `++` has right associativity
* at precedence level of 5.
*
* As of Elm 0.19, these are now restricted to packages owned by elm-lang (and elm-explorations?)
*/
class ElmInfixDeclaration : ElmStubbedNamedElementImpl<ElmInfixDeclarationStub>, ElmExposableTag {
constructor(node: ASTNode) :
super(node, IdentifierCase.OPERATOR)
constructor(stub: ElmInfixDeclarationStub, stubType: IStubElementType<*, *>) :
super(stub, stubType, IdentifierCase.OPERATOR)
val operatorIdentifier: PsiElement
get() = findNotNullChildByType(ElmTypes.OPERATOR_IDENTIFIER)
val precedenceElement: PsiElement
get() = findNotNullChildByType(ElmTypes.NUMBER_LITERAL)
val precedence: Int?
get() = stub?.precedence ?: precedenceElement.text.toIntOrNull()
val associativityElement: PsiElement
get() = findNotNullChildByType(ElmTypes.LOWER_CASE_IDENTIFIER)
val associativity: OperatorAssociativity
get() = when (stub?.associativity ?: associativityElement.text) {
"left" -> OperatorAssociativity.LEFT
"right" -> OperatorAssociativity.RIGHT
else -> OperatorAssociativity.NON
}
/**
* A ref to the function which implements the infix operator.
*
* This will be non-null in a well-formed program.
*/
val funcRef: ElmInfixFuncRef?
get() = stubDirectChildrenOfType<ElmInfixFuncRef>().singleOrNull()
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/Import.elm<|end_filename|>
import A exp
import B exposing
import C exposing (
import D exposing (blah
import E exposing (blah,
import F exposing (blah, quux
import G expo
foo = 42
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/ModuleDecl1.elm<|end_filename|>
module Foo exposing
bar = 42
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/basic/fixtures/DocComments.elm<|end_filename|>
{-| #1
-}
{-| #2 -}
{-| #3
blah blah blah
more stuff
-}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/IfElse.elm<|end_filename|>
f1 = if
f2 = if x
f3 = if x then
type alias Garbage
else
42
f4 = if x then 42
else type alias Garbage = String
<|start_filename|>src/test/resources/org/elm/ide/folding/fixtures/record.elm<|end_filename|>
foo<fold text=' = ...'>=
<fold text='{...}'>{ bar = "bar"
, baz = "baz"
}</fold></fold>
<|start_filename|>src/main/kotlin/org/elm/utils/future.kt<|end_filename|>
package org.elm.utils
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import java.util.concurrent.CancellationException
import java.util.concurrent.CompletableFuture
/**
* Run [fn] on a pooled background thread and show IntelliJ's indeterminate progress bar while it's running.
*
* @param project The IntelliJ project
* @param progressTitle The text to be shown with the progress bar
* @param fn The work to be performed in the background
* @return A future providing the result of [fn]
*/
fun <T> runAsyncTask(project: Project, progressTitle: String, fn: () -> T): CompletableFuture<T> {
val fut = CompletableFuture<T>()
ProgressManager.getInstance().run(
object : Task.Backgroundable(project, progressTitle) {
// NOTE: At first I thought that you should override [onThrowable] to make the future complete
// exceptionally, but when I did that, the exceptions were still escaping to the top-level.
// So now I just catch the exceptions myself within `run`.
override fun run(indicator: ProgressIndicator) {
try {
fut.complete(fn())
} catch (e: ProcessCanceledException) {
throw e // ProgressManager needs to be able to see these
} catch (e: Throwable) {
fut.completeExceptionally(e)
}
}
override fun onCancel() {
// TODO [kl] make sure that this is working correctly with IntelliJ cancellation
fut.completeExceptionally(CancellationException())
super.onCancel()
}
})
return fut
}
/**
* Join on the completion of all futures in the list.
*/
fun <T> List<CompletableFuture<T>>.joinAll(): CompletableFuture<List<T>> =
CompletableFuture.allOf(*this.toTypedArray()).thenApply { map { it.join() } }
/**
* Handle an error, ignoring successful result.
*/
fun <T> CompletableFuture<T>.handleError(fn: (error: Throwable) -> Unit): CompletableFuture<Unit> =
handle { _, error -> fn(error) }
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/Comments.elm<|end_filename|>
-- this is a line comment
n = 42 -- this is also a line comment
{- this is a block comment.
It can span multiple lines
-}
foo = 42
{- block comments can also be on a single line -}
bar = 99
{- block comments can be
{- nested -}
like this
-}
baz = 0
{-| this is a doc comment.
It can span multiple lines
-}
foo2 = 42
{-| doc comments can also be on a single line -}
bar2 = 99
{-| doc comments can contain block comments
{- nested -}
and everything is still ok
-}
baz2 = 0
<|start_filename|>src/test/resources/compiler_json_reports/error.json<|end_filename|>
{
"type": "error",
"path": "src/Helper.elm",
"title": "UNNAMED MODULE",
"message": [
"The `Helper` module must start with a line like this:\n\n ",
{
"bold": false,
"underline": false,
"color": "yellow",
"string": "module Helper exposing (..)"
},
"\n\nTry adding that as the first line of your file!\n\n",
{
"bold": false,
"underline": true,
"color": null,
"string": "Note"
},
": It is best to replace (..) with an explicit list of types and functions\nyou want to expose. If you know a value is only used WITHIN this module, it is\nextra easy to refactor. This kind of information is great, especially as your\nproject grows!"
]
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmCaseOfBranch.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.elm.lang.core.psi.ElmExpressionTag
import org.elm.lang.core.psi.ElmNameDeclarationPatternTag
import org.elm.lang.core.psi.ElmPsiElementImpl
import org.elm.lang.core.psi.ElmTypes
/**
* A pattern-matching branch in a case-of expression.
*/
class ElmCaseOfBranch(node: ASTNode) : ElmPsiElementImpl(node) {
/**
* The pattern on the left-hand-side of the branch.
*/
val pattern: ElmPattern
get() = findNotNullChildByClass(ElmPattern::class.java)
/**
* The body expression on the right-hand-side of the branch.
*
* In a well-formed program, this will be non-null.
*/
val expression: ElmExpressionTag?
get() = findChildByClass(ElmExpressionTag::class.java)
/**
* Named elements introduced by pattern destructuring on the left-hand side of the branch.
*/
val destructuredNames: List<ElmNameDeclarationPatternTag>
get() = PsiTreeUtil.collectElementsOfType(pattern, ElmNameDeclarationPatternTag::class.java).toList()
/** The `->` element. In a well formed program, this will not return null */
val arrow: PsiElement? get() = findChildByType(ElmTypes.ARROW)
}
<|start_filename|>src/test/kotlin/org/elm/ide/inspections/inference/TypeDeclarationInspectionTest.kt<|end_filename|>
package org.elm.ide.inspections.inference
import org.elm.ide.inspections.ElmInspectionsTestBase
import org.elm.ide.inspections.ElmTypeDeclarationInspection
class TypeDeclarationInspectionTest : ElmInspectionsTestBase(ElmTypeDeclarationInspection()) {
/*
The self-recursion tests are ignored because starting in IntelliJ 2019.1,
`getParameterizedCachedValue` is always creating a new value rather than reusing the cache...
This was an intentional change made by JetBrains so that `CachedValue` no longer
caches recursive calls. See:
https://github.com/JetBrains/intellij-community/commit/33c645167507788cdd6e026c7a7bb86938e65e6d
We relied on this behavior to report the error, so now our only choice is to fork the code
restoring the original behavior or to just settle for a false negative. We have chosen the latter.
fun `test bad self-recursion in type alias`() = checkByText("""
<error descr="Infinite recursion">type alias A = A</error>
""")
fun `test bad mutual self-recursion in type alias`() = checkByText("""
<error descr="Infinite recursion">type alias A = B</error>
type alias B = A
""")
*/
fun `test good recursion in through union`() = checkByText("""
type alias Alias = { value : Union }
type Union = Variant Alias
""")
// https://github.com/klazuka/intellij-elm/issues/188
fun `test allowed recursion through two aliases`() = checkByText("""
type Foo = Foo Alias1
type alias Alias1 = Alias2
type alias Alias2 = { foo : Foo }
""")
fun `test too few arguments to type`() = checkByText("""
type Foo a b = Bar
main : <error descr="The type expects 2 arguments, but it got 1 instead.">Foo ()</error>
main = Bar
""")
fun `test correct number of arguments to type`() = checkByText("""
type Foo a b = Bar
main : Foo () ()
main = Bar
""")
fun `test too many arguments to type`() = checkByText("""
type Foo a b = Bar
main : <error descr="The type expects 2 arguments, but it got 3 instead.">Foo () () ()</error>
main = Bar
""")
fun `test too many arguments to type in union variant`() = checkByText("""
type Foo a b = Bar
type Baz = Qux (<error descr="The type expects 2 arguments, but it got 3 instead.">Foo () () ()</error>)
""")
fun `test no arguments to type`() = checkByText("""
type Foo a b = Bar
main : <error descr="The type expects 2 arguments, but it got 0 instead.">Foo</error>
main = Bar
""")
// List uses a separate code path, so we need tests for it
fun `test too many arguments to List`() = checkByText("""
main : <error descr="The type expects 1 argument, but it got 2 instead.">List () ()</error>
main = []
""")
fun `test correct number of arguments to List`() = checkByText("""
main : List ()
main = []
""")
fun `test too few arguments to List`() = checkByText("""
main : <error descr="The type expects 1 argument, but it got 0 instead.">List</error>
main = []
""")
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/ModuleDecl4.elm<|end_filename|>
module Foo exposing (foo, 99, bar)
bar = 42
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/ModulesQualifiedName.elm<|end_filename|>
module Foo.Bar exposing (..)
<|start_filename|>src/main/kotlin/org/elm/workspace/compiler/ElmJsonReport.kt<|end_filename|>
package org.elm.workspace.compiler
import com.google.gson.Gson
// The Elm compiler emits HTTP URLs with angle brackets around them
private val urlPattern = Regex("""<((http|https)://.*?)>""")
fun elmJsonToCompilerMessages(json: String): List<ElmError> {
val report = Gson().fromJson(json, Report::class.java) ?: error("failed to parse JSON report from elm")
return when (report) {
is Report.General -> {
listOf(ElmError(
title = report.title,
html = chunksToHtml(report.message),
location = report.path?.let { ElmLocation(path = it, moduleName = null, region = null) })
)
}
is Report.Specific -> {
report.errors.flatMap { error ->
error.problems.map { problem ->
ElmError(
title = problem.title,
html = chunksToHtml(problem.message),
location = ElmLocation(
path = error.path,
moduleName = error.name,
region = problem.region)
)
}
}
}
}
}
private fun chunksToHtml(chunks: List<Chunk>): String =
chunks.joinToString("",
prefix = "<html><body style=\"font-family: monospace; font-weight: bold\">",
postfix = "</body></html>"
) { chunkToHtml(it) }
private fun chunkToHtml(chunk: Chunk): String =
when (chunk) {
is Chunk.Unstyled -> toHtmlSpan("color: #4F9DA6", chunk.string)
is Chunk.Styled -> with(StringBuilder()) {
if (chunk.bold) append("font-weight: bold;")
if (chunk.underline) append("text-decoration: underline;")
append("color: ${chunk.color.adjustForDisplay()};")
toHtmlSpan(this, chunk.string)
}
}
private fun toHtmlSpan(style: CharSequence, text: String) =
"""<span style="$style">${text.convertWhitespaceToHtml().createHyperlinks()}</span>"""
private fun String.createHyperlinks(): String =
urlPattern.replace(this) { result ->
val url = result.groupValues[1]
"<a href=\"$url\">$url</a>"
}
/**
* The Elm compiler emits the text where the whitespace is already formatted to line up
* using a fixed-width font. But HTML does its own thing with whitespace. We could use a
* `<pre>` element, but then we wouldn't be able to do the color highlights and other
* formatting tricks.
*
* The best solution would be to use the "white-space: pre" CSS rule, but the UI widget
* that we use to render the HTML, [javax.swing.JTextPane], does not support it
* (as best I can tell).
*
* So we will instead manually convert the whitespace so that it renders correctly.
*/
private fun String.convertWhitespaceToHtml() =
replace(" ", " ").replace("\n", "<br>")
/**
* Adjust the Elm compiler's colors to make it look good
*/
private fun String?.adjustForDisplay(): String =
when (this) {
"yellow" -> "#FACF5A"
"red" -> "#FF5959"
null -> "white" // Elm compiler uses null to indicate default foreground color? who knows!
else -> this
}
<|start_filename|>src/main/kotlin/org/elm/ide/refactoring/extractExpressionUI.kt<|end_filename|>
package org.elm.ide.refactoring
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.Pass
import com.intellij.refactoring.IntroduceTargetChooser
import org.elm.lang.core.psi.ElmExpressionTag
import org.elm.openapiext.isUnitTestMode
import org.jetbrains.annotations.TestOnly
fun showExpressionChooser(
editor: Editor,
exprs: List<ElmExpressionTag>,
callback: (ElmExpressionTag) -> Unit
) {
if (isUnitTestMode) {
callback(MOCK!!.chooseTarget(exprs))
} else {
IntroduceTargetChooser.showChooser(editor, exprs, callback.asPass) { it.text }
}
}
private val <T> ((T) -> Unit).asPass: Pass<T>
get() = object : Pass<T>() {
override fun pass(t: T) = this@asPass(t)
}
interface ExtractExpressionUi {
fun chooseTarget(exprs: List<ElmExpressionTag>): ElmExpressionTag
}
private var MOCK: ExtractExpressionUi? = null
@TestOnly
fun withMockTargetExpressionChooser(mock: ExtractExpressionUi, f: () -> Unit) {
MOCK = mock
try {
f()
} finally {
MOCK = null
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmTypeExpression.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.*
import org.elm.lang.core.stubs.ElmPlaceholderStub
/**
* A type expression.
*
* e.g.
*
* - `Float`
* - `Maybe a`
* - `Int -> String`
* - `a -> (a -> {a: String})`
*/
class ElmTypeExpression : ElmStubbedElement<ElmPlaceholderStub>,
ElmUnionVariantParameterTag, ElmTypeRefArgumentTag, ElmTypeExpressionSegmentTag {
constructor(node: ASTNode) :
super(node)
constructor(stub: ElmPlaceholderStub, stubType: IStubElementType<*, *>) :
super(stub, stubType)
/**
* All segments of the type expression.
*
* The segments will be in source order. If this element is not a function, there will be one segment in
* well-formed programs. For functions, there will be one segment per function argument, plus the return type.
*
* e.g. `Int` and `String` in `Int -> String`
*/
val allSegments: List<ElmTypeExpressionSegmentTag>
get() = stubDirectChildrenOfType()
val allTypeVariablesRecursively: Collection<ElmTypeVariable>
get() = stubDescendantsOfTypeStrict()
}
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/basic/fixtures/LineComments.elm<|end_filename|>
-- #1
foo = 0 -- #2
-- #3
<|start_filename|>src/main/kotlin/org/elm/lang/core/parser/manual/MinusWithoutTrailingWhitespaceParser.kt<|end_filename|>
package org.elm.lang.core.parser.manual
import com.intellij.lang.PsiBuilder
import com.intellij.lang.parser.GeneratedParserUtilBase
import com.intellij.lang.parser.GeneratedParserUtilBase.parseTokens
import com.intellij.lang.parser.GeneratedParserUtilBase.recursion_guard_
import com.intellij.psi.TokenType
import org.elm.lang.core.psi.ElmTypes.OPERATOR_IDENTIFIER
/**
* Parses a `-` token iif it is not followed by whitespace.
*
* Does not emit any markers
*/
object MinusWithoutTrailingWhitespaceParser : GeneratedParserUtilBase.Parser {
override fun parse(builder: PsiBuilder, level: Int): Boolean {
if (!recursion_guard_(builder, level, "minus_without_ws")
|| builder.tokenText != "-"
|| builder.rawLookup(1) === TokenType.WHITE_SPACE) {
return false
}
return parseTokens(builder, 0, OPERATOR_IDENTIFIER)
}
}
<|start_filename|>src/test/kotlin/org/elmPerformanceTests/ElmRealProjectAnalysisTest.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elmPerformanceTests
import com.intellij.codeInspection.ex.InspectionToolRegistrar
import org.elm.ide.inspections.ElmLocalInspection
import org.elm.lang.core.ElmFileType
import org.elm.lang.core.psi.ElmFile
import org.elm.openapiext.toPsiFile
import org.junit.ComparisonFailure
import java.lang.reflect.Field
/**
* Smoke-test the plugin by evaluating it against a variety of real-world Elm projects.
* Assuming that the projects you are testing are well-formed, these tests will detect
* any false-positive errors caused by bugs in:
*
* - the parser
* - the unresolved reference inspector
* - the type checker
*/
class ElmRealProjectAnalysisTest : ElmRealProjectTestBase() {
fun `test analyze elm-css`() = doTest(ELM_CSS)
fun `test analyze elm-dev-tools`() = doTest(DEV_TOOLS)
fun `test analyze elm-json-tree-view`() = doTest(JSON_TREE_VIEW)
fun `test analyze elm-list-extra`() = doTest(LIST_EXTRA)
fun `test analyze elm-physics`() = doTest(ELM_PHYSICS)
fun `test analyze elm-spa-example`() = doTest(SPA)
private fun doTest(info: RealProjectInfo, failOnFirstFileWithErrors: Boolean = false) {
val inspections = InspectionToolRegistrar.getInstance().createTools()
.map { it.tool }
.filterIsInstance<ElmLocalInspection>()
myFixture.enableInspections(*inspections.toTypedArray())
println("Opening the project")
val base = openRealProject(info) ?: return
println("Collecting files to analyze")
val filesToCheck = base.findDescendants {
it.fileType == ElmFileType && run {
val file = it.toPsiFile(project)
file is ElmFile && file.elmProject != null
}
}
if (failOnFirstFileWithErrors) {
println("Analyzing...")
myFixture.testHighlightingAllFiles(
/* checkWarnings = */ false,
/* checkInfos = */ false,
/* checkWeakWarnings = */ false,
*filesToCheck.toTypedArray()
)
} else {
val exceptions = filesToCheck.mapNotNull { file ->
val path = file.path.substring(base.path.length + 1)
println("Analyzing $path")
try {
myFixture.testHighlighting(
/* checkWarnings = */ false,
/* checkInfos = */ false,
/* checkWeakWarnings = */ false,
file
)
null
} catch (e: ComparisonFailure) {
e to path
}
}
if (exceptions.isNotEmpty()) {
error("Error annotations found:\n\n" + exceptions.joinToString("\n\n") { (e, path) ->
"$path:\n${e.detailMessage}"
})
}
}
}
}
private val THROWABLE_DETAILED_MESSAGE_FIELD: Field = run {
val field = Throwable::class.java.getDeclaredField("detailMessage")
field.isAccessible = true
field
}
/**
* Retrieves original value of detailMessage field of [Throwable] class.
* It is needed because [ComparisonFailure] overrides [Throwable.message]
* method so we can't get the original value without reflection
*/
private val Throwable.detailMessage: CharSequence
get() = THROWABLE_DETAILED_MESSAGE_FIELD.get(this) as CharSequence
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/CaseFollowedByTopLevelDecl.elm<|end_filename|>
f x =
case x of
0 -> 0
_ -> 1
g = 42
<|start_filename|>src/main/kotlin/org/elm/lang/core/stubs/index/ElmNamedElementIndex.kt<|end_filename|>
package org.elm.lang.core.stubs.index
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StringStubIndexExtension
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey
import org.elm.lang.core.psi.ElmNamedElement
import org.elm.lang.core.stubs.ElmFileStub
/**
* An index of all Elm named things across the entire IntelliJ project.
*
* IMPORTANT: See [ElmLookup] for an alternative API that properly
* handles visibility of named things based on the Elm project which
* wants to access it.
*
*/
class ElmNamedElementIndex : StringStubIndexExtension<ElmNamedElement>() {
override fun getVersion() =
ElmFileStub.Type.stubVersion
override fun getKey(): StubIndexKey<String, ElmNamedElement> =
KEY
companion object {
val KEY: StubIndexKey<String, ElmNamedElement> =
StubIndexKey.createIndexKey("org.elm.lang.core.stubs.index.ElmNamedElementIndex")
/**
* Find all [ElmNamedElement]s whose name matches [name] in [scope].
*/
fun find(name: String, project: Project, scope: GlobalSearchScope): Collection<ElmNamedElement> =
StubIndex.getElements(KEY, name, project, scope, ElmNamedElement::class.java)
/**
* Get the name of every element stored in this index.
*/
fun getAllNames(project: Project): Collection<String> =
StubIndex.getInstance().getAllKeys(KEY, project)
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/CaseOfComments.elm<|end_filename|>
f =
case 1 of
_ ->
2
{-| comment -}
g = 3
<|start_filename|>src/main/kotlin/org/elm/ide/inspections/ElmDiagnosticBasedInspection.kt<|end_filename|>
package org.elm.ide.inspections
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import org.elm.lang.core.diagnostics.ElmDiagnostic
import org.elm.lang.core.psi.ElmPsiElement
abstract class ElmDiagnosticBasedInspection : ElmLocalInspection() {
final override fun visitElement(element: ElmPsiElement, holder: ProblemsHolder, isOnTheFly: Boolean) {
for (diagnostic in getElementDiagnostics(element)) {
holder.registerProblem(holder.manager.createProblemDescriptor(
diagnostic.element,
diagnostic.endElement ?: diagnostic.element,
"<html>${diagnostic.message}</html>",
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
holder.isOnTheFly
))
}
}
abstract fun getElementDiagnostics(element: ElmPsiElement): Iterable<ElmDiagnostic>
}
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/EmptyModule.elm<|end_filename|>
module Foo exposing (..)
<|start_filename|>src/main/kotlin/org/elm/ide/usages/ElmImportFilteringRule.kt<|end_filename|>
package org.elm.ide.usages
import com.intellij.usages.Usage
import com.intellij.usages.UsageTarget
import com.intellij.usages.rules.ImportFilteringRule
import com.intellij.usages.rules.PsiElementUsage
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmImportClause
import org.elm.lang.core.psi.elements.ElmModuleDeclaration
import org.elm.lang.core.psi.elements.ElmTypeAnnotation
import org.elm.lang.core.psi.parentOfType
/**
* A filtering rule that allows you exclude imports from actions such as "find usages"
*/
class ElmImportFilteringRule : ImportFilteringRule() {
override fun isVisible(usage: Usage, targets: Array<UsageTarget>): Boolean {
val element = (usage as? PsiElementUsage)?.element
return element?.containingFile !is ElmFile
|| (element.parentOfType<ElmImportClause>() == null
&& element.parentOfType<ElmModuleDeclaration>() == null
&& element !is ElmTypeAnnotation)
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/parser/manual/DotWithoutWhitespaceParser.kt<|end_filename|>
package org.elm.lang.core.parser.manual
import com.intellij.lang.PsiBuilder
import com.intellij.lang.parser.GeneratedParserUtilBase
import com.intellij.lang.parser.GeneratedParserUtilBase.*
import com.intellij.psi.TokenType
import org.elm.lang.core.psi.ElmTypes.*
/**
* Parses a `.` token, optionally forbidding whitespace on one or both sides.
*
* Does not emit any markers
*/
class DotWithoutWhitespaceParser(private val allowLeadingWs:Boolean,
private val allowTrailingWs:Boolean) : GeneratedParserUtilBase.Parser {
override fun parse(builder: PsiBuilder, level: Int): Boolean {
if (!recursion_guard_(builder, level, "dot_without_ws")
|| (!allowLeadingWs && builder.rawLookup(-1) === TokenType.WHITE_SPACE)
|| builder.rawLookup(0) !== DOT
|| (!allowTrailingWs && builder.rawLookup(1) === TokenType.WHITE_SPACE)) {
return false
}
return parseTokens(builder, 0, DOT)
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/ModuleDecl2.elm<|end_filename|>
module Foo exposing (
bar = 42
<|start_filename|>src/main/kotlin/org/elm/ide/navigation/ElmGoToSymbolContributor.kt<|end_filename|>
package org.elm.ide.navigation
import com.intellij.navigation.ChooseByNameContributor
import com.intellij.navigation.NavigationItem
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import org.elm.lang.core.stubs.index.ElmNamedElementIndex
class ElmGoToSymbolContributor : ChooseByNameContributor {
override fun getNames(project: Project?, includeNonProjectItems: Boolean): Array<out String> {
project ?: return emptyArray()
return ElmNamedElementIndex.getAllNames(project).toTypedArray()
}
override fun getItemsByName(name: String?,
pattern: String?,
project: Project?,
includeNonProjectItems: Boolean): Array<out NavigationItem> {
if (project == null || name == null)
return emptyArray()
val scope = if (includeNonProjectItems)
GlobalSearchScope.allScope(project)
else
GlobalSearchScope.projectScope(project)
return ElmNamedElementIndex.find(name, project, scope)
.toTypedArray<NavigationItem>()
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/TypeAnnotations.elm<|end_filename|>
f : if 0 then 1 else 2
f = 42
port doSomething : [garbage]
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmRecordExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.util.PsiTreeUtil
import org.elm.lang.core.psi.ElmAtomTag
import org.elm.lang.core.psi.ElmFieldAccessTargetTag
import org.elm.lang.core.psi.ElmPsiElementImpl
/**
* A record literal value
*
* e.g. { name = "George", age = 42 }
*/
class ElmRecordExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmAtomTag, ElmFieldAccessTargetTag {
/**
* The name of the existing record which is to be updated, or null
* if this record literal is constructing a completely new value.
*
* e.g. person in `{ person | age = person.age + 1 }`
*/
val baseRecordIdentifier: ElmRecordBaseIdentifier?
get() = findChildByClass(ElmRecordBaseIdentifier::class.java)
/**
* The fields to set in the new record.
*/
val fieldList: List<ElmField>
get() = PsiTreeUtil.getChildrenOfTypeAsList(this, ElmField::class.java)
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/stubs/ElmStubElementType.kt<|end_filename|>
package org.elm.lang.core.stubs
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.tree.IStubFileElementType
import org.elm.lang.core.ElmLanguage
import org.elm.lang.core.psi.ElmPsiElement
abstract class ElmStubElementType<StubT : StubElement<*>, PsiT : ElmPsiElement>(
debugName: String
) : IStubElementType<StubT, PsiT>(debugName, ElmLanguage) {
final override fun getExternalId() =
"elm.${super.toString()}"
protected fun createStubIfParentIsStub(node: ASTNode): Boolean {
val parent = node.treeParent
val parentType = parent.elementType
return (parentType is IStubElementType<*, *> && parentType.shouldCreateStub(parent)) ||
parentType is IStubFileElementType<*>
}
}
<|start_filename|>src/test/kotlin/org/elm/lang/core/lexer/ElmLexerTestCaseBase.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elm.lang.core.lexer
import com.intellij.lexer.Lexer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.testFramework.LexerTestCase
import com.intellij.testFramework.UsefulTestCase
import org.elm.lang.ElmTestCase
import org.elm.lang.pathToGoldTestFile
import org.elm.lang.pathToSourceTestFile
import org.jetbrains.annotations.NonNls
import java.io.IOException
abstract class ElmLexerTestCaseBase : LexerTestCase(), ElmTestCase {
override fun getDirPath(): String = throw UnsupportedOperationException()
// NOTE(matkad): this is basically a copy-paste of doFileTest.
// The only difference is that encoding is set to utf-8
protected fun doTest(lexer: Lexer = createLexer()) {
val filePath = pathToSourceTestFile(getTestName(false))
var text = ""
try {
val fileText = FileUtil.loadFile(filePath.toFile(), CharsetToolkit.UTF8)
text = StringUtil.convertLineSeparators(if (shouldTrim()) fileText.trim() else fileText)
} catch (e: IOException) {
fail("can't load file " + filePath + ": " + e.message)
}
doTest(text, null, lexer)
}
override fun doTest(@NonNls text: String, expected: String?, lexer: Lexer) {
val result = printTokens(text, 0, lexer)
if (expected != null) {
UsefulTestCase.assertSameLines(expected, result)
} else {
UsefulTestCase.assertSameLinesWithFile(pathToGoldTestFile(getTestName(false)).toFile().canonicalPath, result)
}
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/Types.elm<|end_filename|>
type alias Foo = String
type alias Bar = Int
type Quux = Q Bool
type Frob = Widget
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/LetInSingleLineBug2.elm<|end_filename|>
module Foo exposing (in
-- see https://github.com/klazuka/intellij-elm/issues/271
<|start_filename|>src/test/resources/org/elm/ide/folding/fixtures/type_declaration.elm<|end_filename|>
type Foo a<fold text=' = ...'>
= Bar
| Baz a
| Qux Foo a</fold>
<|start_filename|>src/test/kotlin/org/elm/lang/core/parser/ElmParsingTestCaseBase.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elm.lang.core.parser
import com.intellij.lang.LanguageBraceMatching
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiFile
import com.intellij.testFramework.ParsingTestCase
import org.elm.ide.ElmPairedBraceMatcher
import org.elm.lang.ElmTestCase
import org.elm.lang.core.ElmFileType
import org.elm.lang.core.ElmLanguage
import org.jetbrains.annotations.NonNls
val relativeFixtures = "org/elm/lang/core/parser/fixtures/"
abstract class ElmParsingTestCaseBase(@NonNls dataPath: String)
: ParsingTestCase(relativeFixtures + dataPath, ElmFileType.EXTENSION, false, ElmParserDefinition())
, ElmTestCase {
override fun getTestDataPath() =
ElmTestCase.testResourcesPath
protected fun hasError(file: PsiFile): Boolean {
var hasErrors = false
file.accept(object : PsiElementVisitor() {
override fun visitElement(element: PsiElement?) {
if (element is PsiErrorElement) {
hasErrors = true
return
}
element!!.acceptChildren(this)
}
})
return hasErrors
}
override fun setUp() {
super.setUp()
// register the brace-matcher because GrammarKit uses it during error recovery
addExplicitExtension(LanguageBraceMatching.INSTANCE, ElmLanguage, ElmPairedBraceMatcher())
}
}
<|start_filename|>src/main/kotlin/org/elm/ide/intentions/MakeEncoderIntention.kt<|end_filename|>
package org.elm.ide.intentions
import org.elm.lang.core.lookup.ElmLookup
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmTypeDeclaration
import org.elm.lang.core.types.*
class MakeEncoderIntention : AnnotationBasedGeneratorIntention() {
override fun getText() = "Generate Encoder"
override fun getRootIfApplicable(annotationTy: Ty): Ty? {
if (annotationTy !is TyFunction) return null
val param = annotationTy.parameters.singleOrNull() ?: return null
val ret = annotationTy.ret as? TyUnion ?: return null
if (ret.module != "Json.Encode" || ret.name != "Value") return null
return param
}
override fun generator(context: Context): TyFunctionGenerator {
return EncoderGenerator(context.file, context.ty, context.name)
}
}
private class EncoderGenerator(
file: ElmFile,
root: Ty,
private val functionName: String
) : TyFunctionGenerator(file, root) {
/** Counter used to prevent name collision of generated functions */
private var i = 1
override fun generateCode(): String {
// run gen on the root to kick off generation
val genBody = gen(root)
val rootFunc = funcsByTy[root]
funcsByTy.remove(root)
val param = rootFunc?.paramName ?: root.renderParam()
val body = rootFunc?.body ?: " $genBody $param"
return buildString {
append("\n$functionName $param =\n")
append(body)
for (f in funcsByTy.values) {
append("\n\n\n")
append("-- TODO: double-check generated code\n")
append("${f.name} : ${f.qualifier}${f.paramTy.renderedText()} -> ${qual("Value")}\n")
append("${f.name} ${f.paramName} =\n")
append(f.body)
}
}
}
/** Return a unary callable expression that will encode [ty] */
private fun gen(ty: Ty): String = when (ty) {
is TyRecord -> generateRecord(ty)
is TyUnion -> generateUnion(ty)
is TyVar -> "(\\_ -> Debug.todo \"Can't generate encoders for type variables\")"
is TyTuple -> generateTuple(ty)
is TyUnit -> "(\\_ -> ${qual("null")})"
is TyFunction, TyInProgressBinding, is MutableTyRecord, is TyUnknown -> {
"(\\_ -> Debug.todo \"Can't generate encoder for type ${ty.renderedText()}\")"
}
}
private fun generateUnion(ty: TyUnion): String = when {
ty.isTyInt -> qual("int")
ty.isTyFloat -> qual("float")
ty.isTyBool -> qual("bool")
ty.isTyString -> qual("string")
ty.isTyChar -> "(${qual("String", "fromChar")} >> ${qual("string")})"
ty.isTyList -> existing(ty) ?: "${qual("list")} ${gen(ty.parameters[0])}"
ty.module == "Set" && ty.name == "Set" -> existing(ty) ?: "${qual("set")} ${gen(ty.parameters[0])}"
ty.module == "Array" && ty.name == "Array" -> existing(ty)
?: "${qual("array")} ${gen(ty.parameters[0])}"
ty.module == "Maybe" && ty.name == "Maybe" -> generateMaybe(ty)
ty.module == "Dict" && ty.name == "Dict" -> generateDict(ty)
else -> generateUnionFunc(ty)
}
private fun generateUnionFunc(ty: TyUnion): String {
val cached = existing(ty) ?: funcsByTy[ty]?.name
if (cached != null) return cached
val renderedTy = ty.renderParam()
val decl: ElmTypeDeclaration? = ElmLookup.findFirstByNameAndModule(ty.name, ty.module, file)
val (param, body) = if (decl == null) {
renderedTy to "Debug.todo \"Can't generate encoder for ${ty.name}\""
} else {
unionsToExpose += ty.toRef()
val variants = decl.variantInference().value
val patternsAndExprs = variants.map { (variant, params) ->
val pattern = (listOf(variant) + params.map { it.renderParam() }).joinToString(" ")
val expr = when (params.size) {
0 -> "${qual("string")} \"$variant\""
1 -> "${gen(params[0])} ${params[0].renderParam()}"
else -> "Debug.todo \"Cannot generate encoder for variant with multiple parameters\""
}
pattern to expr
}
if (variants.size == 1) {
// For a single variant, we can pattern match it in the function parameter
"(${patternsAndExprs[0].first})" to " ${patternsAndExprs[0].second}"
} else {
// Otherwise we have to use a case expression
renderedTy to patternsAndExprs.joinToString("\n\n", prefix = " case $renderedTy of\n") { (pattern, expr) ->
"""
| $pattern ->
| $expr
""".trimMargin()
}
}
}
val name = "encode${ty.alias?.let { funcNames[it.toRef()] } ?: ty.name}"
val func = GeneratedFunction(name = name, paramTy = ty, paramName = param, body = body, qualifier = qualifierFor(ty.toRef()))
funcsByTy[ty] = func
return name
}
private fun generateRecord(ty: TyRecord): String {
val cached = ty.alias?.let { existing(ty) } ?: funcsByTy[ty]?.name
if (cached != null) return cached
val name = "encode${ty.alias?.let { funcNames[it.toRef()] } ?: "Record${i++}"}"
val param = ty.renderParam()
val qualifier = ty.alias?.let { qualifierFor(it.toRef()) } ?: ""
val body = buildString {
append(" ${qual("object")} <|\n [ ")
ty.fields.entries.joinTo(this, separator = "\n , ") { (k, v) ->
"( \"$k\", ${gen(v)} $param.$k )"
}
append("\n ]")
}
val func = GeneratedFunction(name = name, paramTy = ty, paramName = param, body = body, qualifier = qualifier)
funcsByTy[ty] = func
return name
}
private fun generateDict(ty: TyUnion): String {
val k = ty.parameters[0]
return if (k !is TyUnion || !k.isTyString) {
"(\\_ -> Debug.todo \"Can't generate encoder for Dict with non-String keys\")"
} else {
"(${qual("Dict", "toList")} >> ${qual("List", "map")} (\\( k, v ) -> ( k, ${gen(ty.parameters[1])} v )) >> ${qual("object")})"
}
}
private fun generateTuple(ty: TyTuple): String {
return if (ty.types.size == 2) {
"(\\( a, b ) -> ${qual("list")} identity [ ${gen(ty.types[0])} a, ${gen(ty.types[1])} b ])"
} else {
"(\\( a, b, c ) -> ${qual("list")} identity [ ${gen(ty.types[0])} a, ${gen(ty.types[1])} b, ${gen(ty.types[2])} c ])"
}
}
private fun generateMaybe(ty: TyUnion): String {
return existing(ty) ?: run {
"(${qual("Maybe", "map")} ${gen(ty.parameters[0])} >> ${qual("Maybe", "withDefault")} ${qual("null")})"
}
}
override fun isExistingFunction(needle: Ty, function: Ty): Boolean {
return function.run {
this is TyFunction &&
parameters == listOf(needle) &&
ret is TyUnion &&
ret.module == "Json.Encode" &&
ret.name == "Value"
}
}
private fun qual(name: String) = qual("Json.Encode", name)
}
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/LetInSingleLineBug.elm<|end_filename|>
-- ok
i = let x = 320 in x
-- invalid syntax, but still should not crash the layout lexer
-- https://github.com/klazuka/intellij-elm/issues/20#issuecomment-374843581
boom = [in, in, in]
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmTypeAliasDeclaration.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.elm.ide.icons.ElmIcons
import org.elm.lang.core.psi.*
import org.elm.lang.core.psi.ElmTypes.UPPER_CASE_IDENTIFIER
import org.elm.lang.core.stubs.ElmTypeAliasDeclarationStub
/**
* Declares a type alias
*
* e.g. `type alias User = { name : String, age : Int }`
*
*/
class ElmTypeAliasDeclaration : ElmStubbedNamedElementImpl<ElmTypeAliasDeclarationStub>,
ElmDocTarget, ElmExposableTag {
constructor(node: ASTNode) :
super(node, IdentifierCase.UPPER)
constructor(stub: ElmTypeAliasDeclarationStub, stubType: IStubElementType<*, *>) :
super(stub, stubType, IdentifierCase.UPPER)
override fun getIcon(flags: Int) =
ElmIcons.TYPE_ALIAS
/** The new name (alias) which will hereafter refer to [typeExpression] */
val upperCaseIdentifier: PsiElement
get() = findNotNullChildByType(UPPER_CASE_IDENTIFIER)
/** Zero-or-more type variables which may appear in [typeExpression] */
val lowerTypeNameList: List<ElmLowerTypeName>
get() = stubDirectChildrenOfType()
/**
* The type which is being aliased
*
* In a well-formed program, this will be non-null.
*/
val typeExpression: ElmTypeExpression?
get() = stubDirectChildrenOfType<ElmTypeExpression>().singleOrNull()
/** `true` if the alias is exclusively a record */
val isRecordAlias: Boolean
get() = typeExpression?.allSegments?.firstOrNull() as? ElmRecordType != null
}
<|start_filename|>src/main/kotlin/org/elm/ide/inspections/ElmTypeInferenceInspection.kt<|end_filename|>
package org.elm.ide.inspections
import org.elm.lang.core.diagnostics.ElmDiagnostic
import org.elm.lang.core.psi.ElmPsiElement
import org.elm.lang.core.psi.elements.ElmValueDeclaration
import org.elm.lang.core.psi.isTopLevel
import org.elm.lang.core.types.findInference
class ElmTypeInferenceInspection : ElmDiagnosticBasedInspection() {
override fun getElementDiagnostics(element: ElmPsiElement): Iterable<ElmDiagnostic> {
// nested declarations are taken care of in the parent inference
if (element is ElmValueDeclaration && element.isTopLevel) {
val inference = element.findInference() ?: return emptyList()
return inference.diagnostics
}
return emptyList()
}
}
<|start_filename|>src/test/kotlin/org/elm/lang/core/types/BinaryExprTreeTest.kt<|end_filename|>
package org.elm.lang.core.types
import org.elm.lang.core.psi.OperatorAssociativity
import org.elm.lang.core.psi.OperatorAssociativity.*
import org.elm.lang.core.types.BinaryExprTree.Binary
import org.elm.lang.core.types.BinaryExprTree.Operand
import org.junit.Assert.assertEquals
import org.junit.Test
class BinaryExprTreeTest {
private fun ops(vararg p: Pair<Int, OperatorAssociativity>): Map<String, OperatorPrecedence> {
return p.withIndex().associate { (i, it) ->
"${it.second}-$i" to OperatorPrecedence(it.first, it.second)
}
}
@Test
fun `no operators`() {
val expression = listOf(1)
val actual = BinaryExprTree.parse(expression, emptyMap())
assertEquals(Operand(1), actual)
}
@Test
fun `single operator`() {
val ops = ops(1 to NON)
val op = ops.entries.single().key
val expression = listOf("1", op, "2")
val actual = BinaryExprTree.parse(expression, ops)
assertEquals(Binary(Operand("1"), op, Operand("2")), actual)
}
@Test
fun `left assoc`() {
val ops = ops(1 to LEFT, 1 to LEFT)
val (op1, op2) = ops.keys.toList()
val expression = listOf("1", op1, "2", op2, "3")
val actual = BinaryExprTree.parse(expression, ops)
val expected = Binary(
Binary(Operand("1"), op1, Operand("2")),
op2,
Operand("3"))
assertEquals(expected, actual)
}
@Test
fun `right assoc`() {
val ops = ops(1 to RIGHT, 1 to RIGHT)
val (op1, op2) = ops.keys.toList()
val expression = listOf("1", op1, "2", op2, "3")
val actual = BinaryExprTree.parse(expression, ops)
val expected = Binary(
Operand("1"), op1, Binary(Operand("2"),
op2,
Operand(("3"))))
assertEquals(expected, actual)
}
@Test
fun `high precedence first`() {
val ops = ops(2 to LEFT, 1 to LEFT)
val (op1, op2) = ops.keys.toList()
val expression = listOf("1", op1, "2", op2, "3")
val actual = BinaryExprTree.parse(expression, ops)
val expected = Binary(
Binary(Operand("1"), op1, Operand("2")),
op2,
Operand("3"))
assertEquals(expected, actual)
}
@Test
fun `high precedence last`() {
val ops = ops(1 to LEFT, 2 to LEFT)
val (op1, op2) = ops.keys.toList()
val expression = listOf("1", op1, "2", op2, "3")
val actual = BinaryExprTree.parse(expression, ops)
val expected = Binary(
Operand("1"),
op1,
Binary(Operand("2"), op2, Operand(("3"))))
assertEquals(expected, actual)
}
@Test
fun `left assoc with non assoc`() {
val ops = ops(2 to NON, 1 to LEFT, 2 to NON)
val (op1, op2, op3) = ops.keys.toList()
val expression = listOf("1", op1, "2", op2, "3", op3, "4")
val actual = BinaryExprTree.parse(expression, ops)
val expected = Binary(
Binary(Operand("1"), op1, Operand("2")),
op2,
Binary(Operand("3"), op3, Operand("4")))
assertEquals(expected, actual)
}
@Test
fun `right assoc with non assoc`() {
val ops = ops(2 to NON, 1 to RIGHT, 2 to NON)
val (op1, op2, op3) = ops.keys.toList()
val expression = listOf("1", op1, "2", op2, "3", op3, "4")
val actual = BinaryExprTree.parse(expression, ops)
val expected = Binary(
Binary(Operand("1"), op1, Operand("2")),
op2,
Binary(Operand("3"), op3, Operand("4")))
assertEquals(expected, actual)
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmLetInExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.util.PsiTreeUtil
import org.elm.lang.core.psi.*
/**
* A let-in expression
*
* For example:
* ```
* let
* x = 320
* y = 480
* in
* x + y
* ```
*/
class ElmLetInExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmAtomTag {
/**
* The local declaration bindings.
*
* In a well-formed program, there will be at least one element.
*/
val valueDeclarationList: List<ElmValueDeclaration>
get() = PsiTreeUtil.getChildrenOfTypeAsList(this, ElmValueDeclaration::class.java)
/**
* The body expression.
*
* In a well-formed program, this will be non-null
*/
val expression: ElmExpressionTag?
get() = findChildByClass(ElmExpressionTag::class.java)
/** The `let` element. In a well formed program, this will not return null */
val letKeyword: PsiElement get() = findNotNullChildByType(ElmTypes.LET)
/** The `in` element. In a well formed program, this will not return null */
val inKeyword: PsiElement?
get() = findChildByType(ElmTypes.IN) ?:
// If there's no valueDeclarationList, the in keyword is enclosed in an error element
(lastChild as? PsiErrorElement)?.firstChild?.takeIf { it.elementType == ElmTypes.IN }
}
<|start_filename|>src/test/kotlin/org/elm/lang/core/resolve/ElmMiscResolveTest.kt<|end_filename|>
package org.elm.lang.core.resolve
/**
* Miscellaneous tests related to the reference-resolve system
*/
class ElmMiscResolveTest : ElmResolveTestBase() {
fun `test top-level value ref`() = checkByCode(
"""
magicNumber = 42
--X
f = magicNumber + 1
--^
""")
// LET-IN EXPRESSIONS
fun `test simple value declared by let-in`() = checkByCode(
"""
f x =
let y = 42
--X
in x + y
--^
""")
fun `test let-in should honor lexical scope in body expr`() = checkByCode(
"""
foo =
let
bar y = 0
in y
--^unresolved
""")
fun `test let-in should honor lexical scope in sibling decl`() = checkByCode(
"""
foo =
let
bar y = 0
quux = y
--^unresolved
in
quux
""")
// LAMBDAS (ANONYMOUS FUNCTIONS)
fun `test lambda parameter ref`() = checkByCode(
"""
f = \x -> x
--X --^
""")
fun `test lambda parameter nested`() = checkByCode(
"""
f = \x -> (\() -> x)
--X --^
""")
fun `test lambda parameter nested and should not resolve`() = checkByCode(
"""
f = \() -> x (\x -> ())
--^unresolved
""")
fun `test lambda parameter destructured record field ref`() = checkByCode(
"""
f = \{x} -> x
--X --^
""")
fun `test lambda parameter destructured tuple ref`() = checkByCode(
"""
f = \(x,y) -> x
--X --^
""")
fun `test lambda parameter destructured with alias`() = checkByCode(
"""
f = \((x,y) as point) -> point
--X --^
""")
// PORTS
fun `test port ref`() = checkByCode(
"""
port module Ports exposing (..)
port foo : String -> Cmd msg
--X
update msg model = (model, foo "blah")
--^
""")
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/diagnostics/ElmDiagnostic.kt<|end_filename|>
package org.elm.lang.core.diagnostics
import com.intellij.psi.PsiElement
import org.elm.lang.core.types.*
sealed class ElmDiagnostic(val element: PsiElement, val endElement: PsiElement? = null) {
abstract val message: String
}
class ArgumentCountError(
element: PsiElement,
endElement: PsiElement,
private val actual: Int,
private val expected: Int,
private val isType: Boolean = false
) : ElmDiagnostic(element, endElement) {
override val message: String
get() =
if (expected == 0 && !isType) "This value is not a function, but it was given $actual ${pl(actual, "argument")}."
else "The ${if (isType) "type" else "function"} expects $expected ${pl(expected, "argument")}, but it got $actual instead."
}
class ParameterCountError(
element: PsiElement,
endElement: PsiElement,
private val actual: Int,
private val expected: Int
) : ElmDiagnostic(element, endElement) {
override val message: String
get() =
"The function expects $expected ${pl(expected, "parameter")}, but it got $actual instead."
}
class RedefinitionError(
element: PsiElement
) : ElmDiagnostic(element) {
override val message: String
get() = "Conflicting name declaration"
}
class PartialPatternError(
element: PsiElement
) : ElmDiagnostic(element) {
override val message: String
get() = "Pattern does not cover all possibilities"
}
class BadRecursionError(
element: PsiElement
) : ElmDiagnostic(element) {
override val message: String
get() = "Infinite recursion"
}
class CyclicDefinitionError(
element: PsiElement
) : ElmDiagnostic(element) {
override val message: String
get() = "Value cannot be defined in terms of itself"
}
class InfiniteTypeError(
element: PsiElement
) : ElmDiagnostic(element) {
override val message: String
get() = "Infinite self-referential type"
}
class RecordFieldError(
element: PsiElement,
private val name: String
) : ElmDiagnostic(element) {
override val message: String
get() = "Record does not have field '$name'"
}
class RecordBaseIdError(
element: PsiElement,
private val actual: Ty
) : ElmDiagnostic(element) {
override val message: String
get() {
val expectedRendered = actual.renderedText()
return "Type must be a record.<br>Found: $expectedRendered"
}
}
class FieldAccessOnNonRecordError(
element: PsiElement,
private val actual: Ty
) : ElmDiagnostic(element) {
override val message: String
get() {
val expectedRendered = actual.renderedText()
return "Value is not a record, cannot access fields.<br>Type: $expectedRendered"
}
}
class NonAssociativeOperatorError(
element: PsiElement,
private val operator: PsiElement
) : ElmDiagnostic(element) {
override val message: String
get() {
return "Operator (${operator.text}) is not associative, and so cannot be chained"
}
}
class TypeMismatchError(
element: PsiElement,
private val actual: Ty,
private val expected: Ty,
endElement: PsiElement? = null,
private val patternBinding: Boolean = false,
private val recordDiff: RecordDiff? = null
) : ElmDiagnostic(element, endElement) {
override val message: String
get() {
var expectedRendered = expected.renderedText()
var foundRendered = actual.renderedText()
if (expectedRendered == foundRendered || tysAreAmbiguousUnions(actual, expected)) {
expectedRendered = expected.renderedText(linkify = false, withModule = true)
foundRendered = actual.renderedText(linkify = false, withModule = true)
}
val message = if (patternBinding) {
"Invalid pattern." +
"<br>Required type: $expectedRendered" +
"<br>Pattern type: $foundRendered"
} else {
"Type mismatch." +
"<br>Required: $expectedRendered" +
"<br>Found: $foundRendered"
}
return message + (recordDiff?.let { renderRecordDiff(it) } ?: "")
}
private fun tysAreAmbiguousUnions(l: Ty, r: Ty): Boolean {
return l is TyUnion && r is TyUnion
&& l.name == r.name
&& l.module != r.module
}
private fun renderRecordDiff(recordDiff: RecordDiff) = buildString {
if (recordDiff.extra.isNotEmpty()) {
append("<br>Extra fields: ")
append(TyRecord(fields = recordDiff.extra).renderedText())
}
if (recordDiff.missing.isNotEmpty()) {
append("<br>Missing fields: ")
append(TyRecord(fields = recordDiff.missing).renderedText())
}
if (recordDiff.mismatched.isNotEmpty()) {
append("<br>Mismatched fields: ")
for ((k, v) in recordDiff.mismatched) {
append("<br> Field ").append(k).append(":")
append("<br> Required: ")
append(v.second.renderedText())
append("<br> Found: ")
append(v.first.renderedText())
}
}
}
}
class TypeArgumentCountError(
element: PsiElement,
private val actual: Int,
private val expected: Int
) : ElmDiagnostic(element, null) {
override val message: String
get() =
"The type expects $expected ${pl(expected, "argument")}, but it got $actual instead."
}
private fun pl(n: Int, singular: String, plural: String = singular + "s") = if (n == 1) singular else plural
<|start_filename|>src/test/resources/org/elm/ide/folding/fixtures/doc_comment.elm<|end_filename|>
<fold text='{-| first line ...-}'>{-| first line
second line
-}</fold>
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/TypeAlias.elm<|end_filename|>
type alias Person =
{ name : String
, age : Int
, occupation : (String, String)
}
type alias Updater = Person -> Person
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/ElmElementType.kt<|end_filename|>
package org.elm.lang.core.psi
import com.intellij.psi.tree.IElementType
import org.elm.lang.core.ElmLanguage
/** type of intermediate PSI tree nodes */
class ElmElementType(debugName: String) : IElementType(debugName, ElmLanguage)
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/CaseOfPartial.elm<|end_filename|>
x = case
y = case x
z = case x of
f = 99
<|start_filename|>src/main/kotlin/org/elm/workspace/compiler/ElmMakeTypes.kt<|end_filename|>
package org.elm.workspace.compiler
import com.google.gson.*
import com.google.gson.annotations.JsonAdapter
import java.lang.reflect.Type
// ELM COMPILER DTO TYPES
// Naming based on https://package.elm-lang.org/packages/elm/project-metadata-utils/latest/Elm-Error
private val gson = Gson()
@JsonAdapter(ReportDeserializer::class)
sealed class Report {
data class General(
val path: String?,
val title: String,
val message: List<Chunk>
) : Report()
data class Specific(
val errors: List<BadModuleError>
) : Report()
}
class ReportDeserializer : JsonDeserializer<Report> {
override fun deserialize(element: JsonElement, typeOf: Type, context: JsonDeserializationContext): Report {
if (!element.isJsonObject) throw JsonParseException("Expected a report object")
val obj = element.asJsonObject
val reportType = obj["type"].asString
return when (reportType) {
"error" -> gson.fromJson(obj, Report.General::class.java)
"compile-errors" -> gson.fromJson(obj, Report.Specific::class.java)
else -> error("Unexpected Elm compiler report type '$reportType'")
}
}
}
data class BadModuleError(
val path: String,
val name: String,
val problems: List<Problem>
)
data class Problem(
val title: String,
val region: Region,
val message: List<Chunk>
)
data class Region(val start: Start, val end: End)
data class Start(val line: Int, val column: Int)
data class End(val line: Int, val column: Int)
@JsonAdapter(ChunkDeserializer::class)
sealed class Chunk {
data class Unstyled(val string: String) : Chunk()
data class Styled(val bold: Boolean, val underline: Boolean, val color: String, val string: String) : Chunk()
}
class ChunkDeserializer : JsonDeserializer<Chunk> {
override fun deserialize(element: JsonElement, typeOf: Type, context: JsonDeserializationContext): Chunk =
when {
element.isJsonObject -> gson.fromJson(element, Chunk.Styled::class.java)
element.isJsonPrimitive -> Chunk.Unstyled(element.asString)
else -> throw JsonParseException("Expected a simple string or a rich-text chunk")
}
}
// ElmCompilerPanel UI types
data class ElmError(
val html: String,
val title: String,
val location: ElmLocation?
)
data class ElmLocation(val path: String,
val moduleName: String?,
val region: Region?
)
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/Comments.elm<|end_filename|>
-- 1
module Library exposing (foo, bar)
--2
import Task
--3
--4
foo = 0
bar = 0
--5
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/ListLiterals.elm<|end_filename|>
magicNumber = 42
f1 = [
f3 = [magicNumber,
f4 = [magicNumber, m
f5 = [,]
f6 = [magicNumber, ]
magicWord = "please"
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/ModuleDecl3.elm<|end_filename|>
module Foo exposing (foo,
bar = 42
<|start_filename|>src/test/kotlin/org/elm/ide/annotator/ElmAnnotatorTestBase.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elm.ide.annotator
import org.elm.lang.ElmTestBase
import org.intellij.lang.annotations.Language
abstract class ElmAnnotatorTestBase : ElmTestBase() {
override val dataPath: String
get() = "org/elm/ide/annotator/fixtures"
protected fun doTest(vararg additionalFilenames: String) {
myFixture.testHighlighting(fileName, *additionalFilenames)
}
protected fun checkInfo(@Language("Elm") text: String) {
myFixture.configureByText("main.elm", text)
myFixture.testHighlighting(false, true, false)
}
protected fun checkWarnings(@Language("Elm") text: String) {
myFixture.configureByText("main.elm", text)
myFixture.testHighlighting(true, false, true)
}
protected fun checkErrors(@Language("Elm") text: String) {
myFixture.configureByText("main.elm", text)
myFixture.testHighlighting(false, false, false)
}
protected fun checkQuickFix(
fixName: String,
@Language("Elm") before: String,
@Language("Elm") after: String
) = checkByText(before, after) { applyQuickFix(fixName) }
}
<|start_filename|>src/test/kotlin/org/elm/lang/ElmTestCase.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elm.lang
import org.elm.lang.core.ElmFileType
import java.nio.file.Paths
interface ElmTestCase {
companion object {
val testResourcesPath = "src/test/resources"
}
/**
* The relative path to the test fixture data within the Test Resources root.
*
* This is the key data that [LightPlatformCodeInsightFixtureTestCase] needs
* to be able to find the location of your test fixtures, and it *MUST* be
* overridden by IntelliJ plugins. Unfortunately, the method is not abstract
* so we can't rely on the compiler to verify that we have overridden it, so
* we instead add it to this interface, thereby forcing the client to provide
* an override.
*/
fun getTestDataPath(): String
}
/**
* Path to the source text file which is the input to the test.
*/
fun ElmTestCase.pathToSourceTestFile(name: String) =
Paths.get("${ElmTestCase.testResourcesPath}/${getTestDataPath()}/$name.${ElmFileType.EXTENSION}")
/**
* Path to the 'gold' reference file which is the expected output of the test.
*/
fun ElmTestCase.pathToGoldTestFile(name: String) =
Paths.get("${ElmTestCase.testResourcesPath}/${getTestDataPath()}/$name.txt")
<|start_filename|>src/main/kotlin/org/elm/ide/typing/ElmQuoteHandler.kt<|end_filename|>
package org.elm.ide.typing
import com.intellij.codeInsight.editorActions.MultiCharQuoteHandler
import com.intellij.codeInsight.editorActions.QuoteHandler
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.highlighter.HighlighterIterator
import org.elm.lang.core.psi.ElmTypes.*
// A QuoteHandler is called while the user is typing to control quote matching functionality
// A MultiCharQuoteHandler adds the ability to match quotes that are more than one character long.
class ElmQuoteHandler : QuoteHandler, MultiCharQuoteHandler {
// If this returns true, the editor will move the carat one character right instead of inserting the typed
// character
override fun isClosingQuote(iterator: HighlighterIterator, offset: Int): Boolean {
return when (iterator.tokenType) {
CLOSE_QUOTE, CLOSE_CHAR -> true
else -> false
}
}
// If this returns true, the editor will insert a copy of the typed character after the carat
override fun isOpeningQuote(iterator: HighlighterIterator, offset: Int): Boolean {
return when (iterator.tokenType) {
OPEN_QUOTE, OPEN_CHAR -> offset == iterator.start
else -> false
}
}
// If this returns false, the editor won't insert a closing quote
override fun hasNonClosedLiteral(editor: Editor, iterator: HighlighterIterator, offset: Int): Boolean {
return true
}
// If this returns true, and the carat is immediately after an odd number of backslashes, the
// editor won't perform the isOpeningQuote or isClosingQuote behavior. The character will just be typed normally.
override fun isInsideLiteral(iterator: HighlighterIterator): Boolean {
return when (iterator.tokenType) {
REGULAR_STRING_PART, STRING_ESCAPE, INVALID_STRING_ESCAPE, OPEN_QUOTE, CLOSE_QUOTE -> true
else -> false
}
}
// Part of MultiCharQuoteHandler. If this returns non-null, it will be inserted after the carat.
// This takes precedence over the isOpeningQuote behavior, but if it returns null,
// isOpeningQuote will still be called.
override fun getClosingQuote(iterator: HighlighterIterator, offset: Int): CharSequence? {
return if (isOpeningTripleQuote(iterator, offset)) "\"\"\""
else null
}
private fun isOpeningTripleQuote(iterator: HighlighterIterator, offset: Int): Boolean {
val text = iterator.document.text
val tokenType = iterator.tokenType
return offset >= 3
&& text[offset - 1] == '"'
&& text[offset - 2] == '"'
&& text[offset - 3] == '"'
&& (tokenType == REGULAR_STRING_PART && offset == iterator.start // middle of file
|| tokenType == OPEN_QUOTE && offset == iterator.start + 3) // end of file
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmLowerTypeName.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.ElmStubbedNamedElementImpl
import org.elm.lang.core.psi.IdentifierCase.LOWER
import org.elm.lang.core.stubs.ElmLowerTypeNameStub
class ElmLowerTypeName : ElmStubbedNamedElementImpl<ElmLowerTypeNameStub> {
constructor(node: ASTNode) :
super(node, LOWER)
constructor(stub: ElmLowerTypeNameStub, stubType: IStubElementType<*, *>) :
super(stub, stubType, LOWER)
}
<|start_filename|>src/main/kotlin/org/elm/ide/highlight/ElmSyntaxHighlighterFactory.kt<|end_filename|>
package org.elm.ide.highlight
import com.intellij.openapi.fileTypes.SingleLazyInstanceSyntaxHighlighterFactory
import com.intellij.openapi.fileTypes.SyntaxHighlighter
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
class ElmSyntaxHighlighterFactory : SingleLazyInstanceSyntaxHighlighterFactory() {
override fun createHighlighter(): SyntaxHighlighter = ElmSyntaxHighlighter()
}
<|start_filename|>src/test/kotlin/org/elm/TestClientLocation.kt<|end_filename|>
package org.elm
import com.intellij.openapi.project.Project
import org.elm.lang.core.lookup.ClientLocation
import org.elm.workspace.ElmProject
/**
* A [ClientLocation] for testing purposes
*/
data class TestClientLocation(
override val intellijProject: Project,
override val elmProject: ElmProject?,
override val isInTestsDirectory: Boolean = false
) : ClientLocation
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/TypeAnnotations.elm<|end_filename|>
f : Int -> Int
f x = x
g : Int
g = 42
port p : String -> Cmd msg
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/Records.elm<|end_filename|>
type alias Point =
{ x : Int
, y : Int
}
p =
{ x = 0
, y = 0
}
emptyRecord =
{}
makePair : { a | x : Int, y : Int } -> (Int, Int)
makePair { x, y } =
( x, y )
input = { x = \() -> () }
valueRef = { foo = input.x (), bar = () }
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmFieldAccessorFunctionExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.*
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReference
import org.elm.lang.core.resolve.reference.RecordFieldReference
import org.elm.lang.core.types.Ty
import org.elm.lang.core.types.TyFunction
import org.elm.lang.core.types.findTy
/**
* A function expression that will access a field in a record.
*
* e.g. `.x` in `List.map .x [{x=1}]`
*/
class ElmFieldAccessorFunctionExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmReferenceElement, ElmFunctionCallTargetTag, ElmAtomTag {
/** The name of the field being accessed */
val identifier: PsiElement
get() = findNotNullChildByType(ElmTypes.LOWER_CASE_IDENTIFIER)
override val referenceNameElement: PsiElement
get() = identifier
override val referenceName: String
get() = identifier.text
override fun getReference(): ElmReference {
return object : RecordFieldReference<ElmFieldAccessorFunctionExpr>(this@ElmFieldAccessorFunctionExpr) {
override fun getTy(): Ty? = (element.findTy() as? TyFunction)?.parameters?.singleOrNull()
}
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmOperator.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.ElmBinOpPartTag
import org.elm.lang.core.psi.ElmPsiElementImpl
import org.elm.lang.core.psi.ElmTypes.OPERATOR_IDENTIFIER
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.SimpleOperatorReference
/**
* A binary operator used in an expression
*
* e.g. `x + y`
*/
class ElmOperator(node: ASTNode) : ElmPsiElementImpl(node), ElmReferenceElement, ElmBinOpPartTag {
val operator: PsiElement
get() = findNotNullChildByType(OPERATOR_IDENTIFIER)
override val referenceNameElement: PsiElement
get() = operator
override val referenceName: String
get() = referenceNameElement.text
override fun getReference() =
SimpleOperatorReference(this)
}
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/CaseOf.elm<|end_filename|>
f = case x of
0 -> "zero"
_ -> "other"
g = case f x of
"zero" -> 0
_ -> case x of
0 -> 1
_ -> 42
h = case f x of
"other" ->
case x of
0 -> 1
_ -> 42
"zero" -> 0
_ ->
99
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/Records.elm<|end_filename|>
type alias P = {
type alias Q = { x :
type alias R = { x : Int
type alias S = { x : Int,
p = {
t = { x
q = { x =
r = { x = 0 ,
s = { x = 0 , y
sentinel = 42
<|start_filename|>src/main/kotlin/org/elm/ide/refactoring/ElmRefactoringSupportProvider.kt<|end_filename|>
package org.elm.ide.refactoring
import com.intellij.lang.refactoring.RefactoringSupportProvider
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringActionHandler
class ElmRefactoringSupportProvider : RefactoringSupportProvider() {
override fun isMemberInplaceRenameAvailable(element: PsiElement, context: PsiElement?): Boolean {
// TODO [kl] eventually we will want to be more selective
return true
}
override fun getIntroduceVariableHandler(): RefactoringActionHandler? {
return ElmIntroduceVariableHandler()
}
}
<|start_filename|>src/test/kotlin/org/elm/ide/hints/ElmExpressionTypeProviderTest.kt<|end_filename|>
package org.elm.ide.hints
import junit.framework.TestCase
import org.elm.lang.ElmTestBase
import org.elm.lang.core.psi.ElmPsiElement
import org.intellij.lang.annotations.Language
class ElmExpressionTypeProviderTest : ElmTestBase() {
fun `test binary operator`() {
checkChoices("""
foo a b = a
infix left 0 (~~) = foo
x = ()
y = x ~~ ()
--^
""", listOf("x", "x ~~ ()"))
}
fun `test parenthesized expressions are not provided as a separate, redundant choice`() {
checkChoices("""
foo a b = a
infix left 0 (~~) = foo
x0 = ()
x1 = ()
x2 = ()
y = x0 ~~ (x1 ~~ x2)
--^
""", listOf("x1", "x1 ~~ x2", "x0 ~~ (x1 ~~ x2)"))
}
fun `test function call`() {
checkChoices("""
f x = x
y = ()
z = f (f y)
--^
""", listOf("y", "f y", "f (f y)"))
}
fun `test lists`() {
checkChoices("""
x = ()
y = [x, x]
--^
""", listOf("x", "[x, x]"))
}
fun `test records`() {
checkChoices("""
x = ()
y = { foo = x }
--^
""", listOf("x", "{ foo = x }"))
}
fun `test record field access`() {
checkChoices("""
type alias Foo = { x: { y: () } }
f : Foo -> ()
f foo = foo.x.y
--^
""", listOf("foo", "foo.x", "foo.x.y"))
}
private fun checkChoices(@Language("Elm") str: String, choices: List<String>) {
val provider = ElmExpressionTypeProvider()
InlineFile(str)
val elem = findElementInEditor<ElmPsiElement>()
TestCase.assertEquals(choices, provider.getExpressionsAt(elem).map { it.text })
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/OperatorAssociativity.kt<|end_filename|>
package org.elm.lang.core.psi
enum class OperatorAssociativity { LEFT, RIGHT, NON }
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmUnitExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.*
import org.elm.lang.core.stubs.ElmPlaceholderStub
class ElmUnitExpr : ElmStubbedElement<ElmPlaceholderStub>,
ElmAtomTag, ElmFunctionParamTag, ElmPatternChildTag, ElmUnionPatternChildTag {
constructor(node: ASTNode) :
super(node)
constructor(stub: ElmPlaceholderStub, stubType: IStubElementType<*, *>) :
super(stub, stubType)
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/resolve/reference/QualifiedReference.kt<|end_filename|>
package org.elm.lang.core.resolve.reference
/**
* A reference which is qualified by a module name (or an imported module's alias)
*
* @property qualifierPrefix the module name or alias (e.g. `Foo` in `Foo.bar`)
* @property nameWithoutQualifier the bare, unqualified name (e.g. `bar` in `Foo.bar`)
*/
interface QualifiedReference : ElmReference {
val qualifierPrefix: String
val nameWithoutQualifier: String
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/ValueDecl.elm<|end_filename|>
f1 =
f2 = type Blah
f3 42 = ,
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmInfixFuncRef.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.ElmStubbedElement
import org.elm.lang.core.psi.ElmTypes.LOWER_CASE_IDENTIFIER
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReference
import org.elm.lang.core.resolve.reference.LocalTopLevelValueReference
import org.elm.lang.core.stubs.ElmPlaceholderRefStub
/**
* A reference to the function that implements an infix operator.
*/
class ElmInfixFuncRef : ElmStubbedElement<ElmPlaceholderRefStub>, ElmReferenceElement {
constructor(node: ASTNode) :
super(node)
constructor(stub: ElmPlaceholderRefStub, stubType: IStubElementType<*, *>) :
super(stub, stubType)
override val referenceNameElement: PsiElement
get() = findNotNullChildByType(LOWER_CASE_IDENTIFIER)
override val referenceName: String
get() = stub?.refName ?: referenceNameElement.text
override fun getReference(): ElmReference =
LocalTopLevelValueReference(this)
}
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/basic/fixtures/Types.elm<|end_filename|>
type Foo = Foo
type alias Normal = ()
type alias Spacey = ()
-- `alias` can be used in other contexts (https://github.com/klazuka/intellij-elm/issues/378)
x = { alias = "secret" }
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmNumberConstantExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import org.elm.lang.core.psi.ElmConstantTag
import org.elm.lang.core.psi.ElmPsiElementImpl
/** A literal number. e.g. `-123` or `1.23` */
class ElmNumberConstantExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmConstantTag {
val isFloat get() = text.contains('.')
}
<|start_filename|>src/test/resources/org/elm/ide/folding/fixtures/type_alias.elm<|end_filename|>
type alias Foo a b<fold text=' = ...'> =
Int -> Int -> Int</fold>
<|start_filename|>src/test/kotlin/org/elm/ide/docs/ElmQuickDocumentationTest.kt<|end_filename|>
package org.elm.ide.docs
import org.intellij.lang.annotations.Language
class ElmQuickDocumentationTest : ElmDocumentationProviderTest() {
override fun getProjectDescriptor() = ElmWithStdlibDescriptor
fun `test variable declaration`() = doTest(
"""
foo = 0
--^
""",
"""
<div class='definition'><pre><b>foo</b> : number
<b>foo</b></pre></div>
""")
fun `test unary function`() = doTest(
"""
foo bar = bar
--^
""",
"""
<div class='definition'><pre><b>foo</b> : a → a
<b>foo</b> bar</pre></div>
""")
fun `test binary function with line comment`() = doTest(
"""
--- this shouldn't be included
foo bar baz = bar baz
--^
""",
"""
<div class='definition'><pre><b>foo</b> : (b → a) → b → a
<b>foo</b> bar baz</pre></div>
""")
fun `test binary function with as`() = doTest(
"""
foo (bar as baz) qux = bar
--^
""",
"""
<div class='definition'><pre><b>foo</b> : a → b → a
<b>foo</b> (bar as baz) qux</pre></div>
""")
fun `test unannotated function`() = doTest(
"""
foo a = ((), "", a + 1)
main = foo
--^
""",
"""
<div class='definition'><pre><b>foo</b> : number → ((), <a href="psi_element://String">String</a>, number)
<b>foo</b> a</pre></div>
""")
fun `test var with later constraints`() = doTest(
"""
foo a =
let
b = a
--^
c = a ++ ""
in
a
""",
"""
<div class='definition'><pre><i>parameter</i> a : <a href="psi_element://String">String</a>
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test function with doc comment`() = doTest(
"""
{-| this should be included. -}
foo bar baz = bar baz
--^
""",
"""
<div class='definition'><pre><b>foo</b> : (b → a) → b → a
<b>foo</b> bar baz</pre></div>
<div class='content'><p>this should be included.</p></div>
""")
fun `test function with type annotation`() = doTest(
"""
foo : Int -> Int -> Int
foo bar baz = bar
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a>
<b>foo</b> bar baz</pre></div>
""")
fun `test function with type annotation with nested types`() = doTest(
"""
foo : List (List a) -> ()
foo bar = ()
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://List">List</a> (<a href="psi_element://List">List</a> a) → ()
<b>foo</b> bar</pre></div>
""")
fun `test function with type annotation and parameterized alias`() = doTest(
"""
type alias A a = {x: a, y: ()}
main : A ()
main = {x = (), y = ()}
--^
""",
"""
<div class='definition'><pre><b>main</b> : <a href="psi_element://A">A</a> ()
<b>main</b></pre></div>
""")
fun `test nested function with type annotation`() = doTest(
"""
main a =
let
foo : Int -> Int -> Int
foo bar baz = a
in
foo
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a>
<b>foo</b> bar baz</pre></div>
""")
fun `test function in let`() = doTest(
"""
foo a =
let
bar b = b + 1
--^
in
a
""",
"""
<div class='definition'><pre><b>bar</b> : number → number
<b>bar</b> b</pre></div>
""")
fun `test function with qualified type annotation`() = doTest(
"""
import Json.Decode
foo : Json.Decode.Decoder ()
foo = Json.Decode.succeed ()
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Decoder">Decoder</a> ()
<b>foo</b></pre></div>
""")
fun `test function with type and docs`() = doTest(
"""
{-| foo some ints together -}
foo : Int -> Int -> Int
foo bar baz = bar baz
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a>
<b>foo</b> bar baz</pre></div>
<div class='content'><p>foo some ints together</p></div>
""")
fun `test function in module`() = doTest(
"""
module Foo.Bar exposing (foo)
foo bar = bar
--^
""",
"""
<div class='definition'><pre><b>foo</b> : a → a
<b>foo</b> bar<i> defined in </i>Foo.Bar</pre></div>
""")
fun `test doc comments with markdown`() = doTest(
"""
{-| Map some `Int`s together,
producing another `Int`
# Example
bar = 1
baz = 2
foo bar baz
*For more information*, see [this][link] before
deciding if this is what you want.
[link]: https://example.com/
-}
foo : Int -> Int -> Int
foo bar baz =
--^
bar baz
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a> → <a href="psi_element://Int">Int</a>
<b>foo</b> bar baz</pre></div>
<div class='content'><p>Map some <code>Int</code>s together,
producing another <code>Int</code></p><h2>Example</h2><pre><code>bar = 1
baz = 2
foo bar baz
</code></pre><p><em>For more information</em>, see <a href="https://example.com/">this</a> before
deciding if this is what you want.</p></div>
""")
fun `test type declaration`() = doTest(
"""
type Foo = Bar
--^
""",
"""
<div class='definition'><pre><b>type</b> Foo</pre></div>
<table class='sections'><tr><td valign='top' class='section'><p>Variants:</td><td valign='top'><p>
<p><code>Bar</code></td></table>
""")
fun `test type declaration in module`() = doTest(
"""
module Foo.Bar exposing (Foo)
type Foo = Bar
--^
""",
"""
<div class='definition'><pre><b>type</b> Foo<i> defined in </i>Foo.Bar</pre></div>
<table class='sections'><tr><td valign='top' class='section'><p>Variants:</td><td valign='top'><p>
<p><code>Bar</code></td></table>
""")
fun `test type declaration with docs`() = doTest(
"""
{-| included *docs* -}
type Foo = Bar
--^
""",
"""
<div class='definition'><pre><b>type</b> Foo</pre></div>
<div class='content'><p>included <em>docs</em></p></div>
<table class='sections'><tr><td valign='top' class='section'><p>Variants:</td><td valign='top'><p>
<p><code>Bar</code></td></table>
""")
fun `test type declaration with multiple variants`() = doTest(
"""
{-| included *docs* -}
type Foo
--^
= Bar
| Baz Foo
| Qux (List a) a
| Lorem { ipsum: Int }
""",
"""
<div class='definition'><pre><b>type</b> Foo</pre></div>
<div class='content'><p>included <em>docs</em></p></div>
<table class='sections'><tr><td valign='top' class='section'><p>Variants:</td><td valign='top'><p>
<p><code>Bar</code>
<p><code>Baz</code> <a href="psi_element://Foo">Foo</a>
<p><code>Qux</code> (<a href="psi_element://List">List</a> a) a
<p><code>Lorem</code> { ipsum : <a href="psi_element://Int">Int</a> }</td></table>
""")
fun `test union variant with parameters`() = doTest(
"""
type Foo a = Bar | Baz a (List Int) Int
--^
""",
"""
<div class='definition'><pre><i>variant</i> Baz a (<a href="psi_element://List">List</a> <a href="psi_element://Int">Int</a>) <a href="psi_element://Int">Int</a><i> of type </i><a href="psi_element://Foo">Foo</a></pre></div>
""")
fun `test union variant without parameters`() = doTest(
"""
type Foo a = Bar | Baz a Foo
--^
""",
"""
<div class='definition'><pre><i>variant</i> Bar<i> of type </i><a href="psi_element://Foo">Foo</a></pre></div>
""")
fun `test type alias`() = doTest(
"""
type alias Foo = Int
--^
""",
"""
<div class='definition'><pre><b>type alias</b> Foo</pre></div>
""")
fun `test type alias in module`() = doTest(
"""
module Foo.Bar exposing (Foo)
type alias Foo = Int
--^
""",
"""
<div class='definition'><pre><b>type alias</b> Foo<i> defined in </i>Foo.Bar</pre></div>
""")
fun `test type alias with docs`() = doTest(
"""
{-| included *docs* -}
type alias Foo = Int
--^
""",
"""
<div class='definition'><pre><b>type alias</b> Foo</pre></div>
<div class='content'><p>included <em>docs</em></p></div>
""")
fun `test type alias empty record`() = doTest(
"""
type alias Foo = { }
--^
""",
"""
<div class='definition'><pre><b>type alias</b> Foo</pre></div>
""")
fun `test type alias record with fields`() = doTest(
"""
type alias Foo = { a: Int, b: String }
--^
""",
"""
<div class='definition'><pre><b>type alias</b> Foo</pre></div>
<table class='sections'><tr><td valign='top' class='section'><p>Fields:</td><td valign='top'><p>
<p><code>a</code> : <a href="psi_element://Int">Int</a>
<p><code>b</code> : <a href="psi_element://String">String</a></td></table>
""")
fun `test module`() = doTest(
"""
module Main exposing (main)
--^
main = ()
""",
"""
<div class='definition'><pre><i>module</i> Main</pre></div>
""")
// This test is kludgy: since a line comment before a doc comment will cause the doc comment to fail to attach to
// the module element, we need to put the line comment inside the doc comment.
fun `test module with docstring`() = doTest(
"""
module Main exposing (main)
{-| --^
Module docs
# Header
@docs main, foo, Bar
# Helpers
@docs main, foo,
Bar, Baz
-}
main = ()
foo = ()
type alias Bar = ()
type Baz = Baz
""",
"""
<div class='definition'><pre><i>module</i> Main</pre></div>
<div class='content'><p>--^</p><p>Module docs</p><h2>Header</h2><a href="psi_element://main">main</a>, <a href="psi_element://foo">foo</a>, <a href="psi_element://Bar">Bar</a><h2>Helpers</h2><a href="psi_element://main">main</a>, <a href="psi_element://foo">foo</a>, <a href="psi_element://Bar">Bar</a>, <a href="psi_element://Baz">Baz</a></div>
""")
fun `test function parameter`() = doTest(
"""
foo bar = ()
--^
""",
"""
<div class='definition'><pre><i>parameter</i> bar : a
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test function parameter with primitive type annotation`() = doTest(
"""
type Int = Int
foo : Int -> Int
foo bar = bar
--^
""",
"""
<div class='definition'><pre><i>parameter</i> bar : <a href="psi_element://Int">Int</a>
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test function parameter with nested parametric type annotation`() = doTest(
"""
type Foo a = Bar
foo : Foo (Foo a) -> Foo (Foo a)
foo bar = bar
--^
""",
"""
<div class='definition'><pre><i>parameter</i> bar : <a href="psi_element://Foo">Foo</a> (<a href="psi_element://Foo">Foo</a> a)
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test function parameter with parenthesized type annotation`() = doTest(
"""
type Int = Int
foo : ((Int)) -> Int
foo ((bar)) = bar
--^
""",
"""
<div class='definition'><pre><i>parameter</i> bar : <a href="psi_element://Int">Int</a>
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test function parameter with nested tuple type annotation`() = doTest(
"""
type Int = Int
type String = String
type Float = Float
foo : (Int, (String, Float)) -> String
foo (_, (bar, _)) = bar
--^
""",
"""
<div class='definition'><pre><i>parameter</i> bar : <a href="psi_element://String">String</a>
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
// The value now resolves to the field inside the annotation, which we don't have a ty for.
// fun `test function parameter with record type annotation`() = doTest(
// """
//type Int = Int
//type Float = Float
//foo : {x: Int, y: Float} -> Float
//foo {x, y} = y
// --^
//""",
// """
//<div class='definition'><pre><i>parameter</i> y : <a href="psi_element://Float">Float</a>
//<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
//""")
fun `test function parameter with record type and as annotation`() = doTest(
"""
type Int = Int
type Float = Float
foo : {x: Int, y: Float} -> {x: Int, y: Float}
foo ({x, y} as z) = z
--^
""",
"""
<div class='definition'><pre><i>parameter</i> z : { x : <a href="psi_element://Int">Int</a>, y : <a href="psi_element://Float">Float</a> }
<i>of function </i><a href="psi_element://foo">foo</a></pre></div>
""")
fun `test aliased types`() = doTest(
"""
type alias T1 t = ()
type alias T2 u = T1 t
foo : T1 a -> T2 b
foo a = a
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://T1">T1</a> t → <a href="psi_element://T2">T2</a> u
<b>foo</b> a</pre></div>
""")
fun `test alias to unresolved type`() = doTest(
"""
type alias Html msg = VirtualDom.Node msg
foo : Html msg -> Html msg
foo a = a
--^
""",
"""
<div class='definition'><pre><b>foo</b> : <a href="psi_element://Html">Html</a> msg → <a href="psi_element://Html">Html</a> msg
<b>foo</b> a</pre></div>
""")
fun `test operator`() = doTest(
"""
{-| included *docs* -}
foo : number -> number -> number
foo a b = a
infix left 6 (~~) = foo
bar = 11 ~~ 11
--^
""",
"""
<div class='definition'><pre><b>foo</b> : number → number → number
<b>foo</b> a b</pre></div>
<div class='content'><p>included <em>docs</em></p></div>
""")
private fun doTest(@Language("Elm") code: String, @Language("Html") expected: String) =
doTest(code, expected, ElmDocumentationProvider::generateDoc)
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/resolve/reference/ElmReferenceCached.kt<|end_filename|>
package org.elm.lang.core.resolve.reference
import com.intellij.psi.impl.source.resolve.ResolveCache
import org.elm.lang.core.psi.ElmNamedElement
import org.elm.lang.core.resolve.ElmReferenceElement
/**
* A reference that will resolve to at most one element. The resolve result is cached.
*/
abstract class ElmReferenceCached<T : ElmReferenceElement>(element: T)
: ElmReference, ElmReferenceBase<T>(element) {
abstract fun resolveInner(): ElmNamedElement?
final override fun multiResolve(): List<ElmNamedElement> {
return ResolveCache.getInstance(element.project)
.resolveWithCaching(this, Resolver, true, false)
?.let { listOf(it) }.orEmpty()
}
private object Resolver : ResolveCache.AbstractResolver<ElmReferenceCached<*>, ElmNamedElement?> {
override fun resolve(ref: ElmReferenceCached<*>, incompleteCode: Boolean): ElmNamedElement? {
return ref.resolveInner()
}
}
}
<|start_filename|>src/test/kotlin/org/elmPerformanceTests/ElmRealProjectTestBase.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elmPerformanceTests
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.vfs.*
import com.intellij.util.ui.UIUtil
import org.elm.openapiext.fullyRefreshDirectory
import org.elm.workspace.ElmWorkspaceTestBase
import org.elm.workspace.elmWorkspace
abstract class ElmRealProjectTestBase : ElmWorkspaceTestBase() {
protected fun openRealProject(info: RealProjectInfo): VirtualFile? {
val base = openRealProject("testData/${info.path}", info.exclude)
if (base == null) {
val name = info.name
println("SKIP $name: git clone ${info.gitUrl} testData/$name")
return null
}
return base
}
private fun openRealProject(path: String, exclude: List<String> = emptyList()): VirtualFile? {
val projectDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(path)
?: return null
fun isAppropriate(file: VirtualFile): Boolean {
val relativePath = file.path.substring(projectDir.path.length + 1)
// 1. Ignore excluded files
if (exclude.any { relativePath.startsWith(it) }) return false
// 2. Ignore hidden files
if (file.name.startsWith(".")) return false
// Otherwise, analyse it
return true
}
runWriteAction {
fullyRefreshDirectoryInUnitTests(projectDir)
VfsUtil.copyDirectory(this, projectDir, elmWorkspaceDirectory, ::isAppropriate)
fullyRefreshDirectoryInUnitTests(elmWorkspaceDirectory)
}
project.elmWorkspace.asyncDiscoverAndRefresh()
UIUtil.dispatchAllInvocationEvents()
return elmWorkspaceDirectory
}
class RealProjectInfo(
val name: String,
val path: String,
val gitUrl: String,
val exclude: List<String> = emptyList()
)
companion object {
val SPA = RealProjectInfo("elm-spa-example", "elm-spa-example", "https://github.com/rtfeldman/elm-spa-example")
val ELM_CSS = RealProjectInfo("elm-css", "elm-css", "https://github.com/rtfeldman/elm-css", exclude = listOf("src/DEPRECATED", "tests"))
val ELM_PHYSICS = RealProjectInfo("elm-physics", "elm-physics", "https://github.com/w0rm/elm-physics")
val LIST_EXTRA = RealProjectInfo("elm-list-extra", "elm-list-extra", "https://github.com/elm-community/list-extra")
val JSON_TREE_VIEW = RealProjectInfo("elm-json-tree-view", "elm-json-tree-view", "https://github.com/klazuka/elm-json-tree-view")
val DEV_TOOLS = RealProjectInfo("elm-dev-tools", "elm-dev-tools", "https://github.com/opvasger/elm-dev-tools")
}
}
fun VirtualFile.findDescendants(filter: (VirtualFile) -> Boolean): ArrayList<VirtualFile> {
val result = ArrayList<VirtualFile>()
VfsUtilCore.visitChildrenRecursively(this,
object : VirtualFileVisitor<ArrayList<VirtualFile>>() {
override fun visitFile(file: VirtualFile): Boolean {
if (!file.isDirectory && filter(file)) result.add(file)
return true
}
})
return result
}
fun fullyRefreshDirectoryInUnitTests(directory: VirtualFile) {
// It's very weird, but real refresh occurs only if
// we touch file names. At least in the test environment
VfsUtilCore.iterateChildrenRecursively(directory, null) { it.name; true }
fullyRefreshDirectory(directory)
}
<|start_filename|>src/main/kotlin/org/elm/openapiext/Result.kt<|end_filename|>
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*
* Originally from intellij-rust
*
*/
package org.elm.openapiext
sealed class Result<out T> {
class Ok<out T>(val value: T) : Result<T>()
class Err<out T>(val reason: String) : Result<T>()
fun orNull(): T? {
return when (this) {
is Ok -> this.value
is Err -> null
}
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/Shaders.elm<|end_filename|>
shader =
[glsl|
precision mediump float;
uniform float shade;
varying vec3 vcolor;
void main () {
gl_FragColor = shade * vec4(vcolor, 1.0);
}
|]
<|start_filename|>src/test/resources/org/elm/lang/core/stubs/fixtures/Main.elm<|end_filename|>
module Main exposing (main)
import Foo exposing (Foo, bar, Baz(A,B))
i : Foo
i = Foo.z.n
main =
let
a = A
x = bar
in
a x
<|start_filename|>src/test/kotlin/org/elm/ide/inspections/ElmInspectionSuppressorTest.kt<|end_filename|>
package org.elm.ide.inspections
class ElmInspectionSuppressorTest : ElmInspectionsTestBase(ElmUnusedSymbolInspection()) {
fun testWithoutSuppression() = checkByText("""
type T = T ()
<warning>f</warning> = g
g : T -> () -> ()
g t <warning>x</warning> =
case t of
T <warning>u</warning> -> ()
""")
fun testSuppression() = checkByText("""
type T = T ()
-- noinspection ElmUnusedSymbol
f = g
-- noinspection ElmUnusedSymbol
g : T -> () -> ()
g t x =
case t of
T u -> ()
""")
}
<|start_filename|>src/main/kotlin/org/elm/ide/toolwindow/ElmToolWindowFactory.kt<|end_filename|>
package org.elm.ide.toolwindow
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
/**
* Boilerplate to connect tool window content to IntelliJ.
*/
class ElmToolWindowFactory : ToolWindowFactory {
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
with(toolWindow.contentManager) {
addContent(factory.createContent(ElmWorkspacePanel(project), "Projects", true))
}
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/stubs/ElmNamedStub.kt<|end_filename|>
package org.elm.lang.core.stubs
interface ElmNamedStub {
val name: String
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/UnionTypeDeclaration.elm<|end_filename|>
type Msg
= Dismiss
| Show (Int, String)
type Configurator model
= Init (() -> model)
| Apply model Int (model -> Int -> model)
| Configure { foo: Bool, bar: List model }
<|start_filename|>src/main/kotlin/org/elm/ide/spelling/ElmSpellCheckingStrategy.kt<|end_filename|>
package org.elm.ide.spelling
import com.intellij.psi.PsiElement
import com.intellij.spellchecker.inspections.PlainTextSplitter
import com.intellij.spellchecker.tokenizer.SpellcheckingStrategy
import com.intellij.spellchecker.tokenizer.TokenizerBase
import org.elm.lang.core.ElmLanguage
import org.elm.lang.core.psi.ElmTypes
import org.elm.lang.core.psi.elementType
class ElmSpellCheckingStrategy : SpellcheckingStrategy() {
override fun isMyContext(element: PsiElement) =
element.language.`is`(ElmLanguage)
override fun getTokenizer(element: PsiElement?) =
if (element?.elementType == ElmTypes.REGULAR_STRING_PART)
ELM_STRING_TOKENIZER
else
super.getTokenizer(element)
}
val ELM_STRING_TOKENIZER =
TokenizerBase<PsiElement>(PlainTextSplitter.getInstance())
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmPattern.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.*
class ElmPattern(node: ASTNode) : ElmPsiElementImpl(node), ElmFunctionParamTag, ElmPatternChildTag, ElmUnionPatternChildTag, ElmValueAssigneeTag {
/**
* The actual type of this pattern.
*
* If this patten is wrapped in parenthesis, the child will be another [ElmPattern]
*/
val child: ElmPatternChildTag
get() = findNotNullChildByClass(ElmPatternChildTag::class.java)
/**
* The name after the `as` that this pattern is bound to.
*
* e.g. `record` in `({field} as record)`
*/
val patternAs: ElmLowerPattern?
get() {
val asToken = findChildByType<PsiElement>(ElmTypes.AS) ?: return null
return asToken.nextSiblings.filterIsInstance<ElmLowerPattern>().firstOrNull()
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/Strings.elm<|end_filename|>
a="bar
b="baz"
c="""
qux
"""
d=["one
,"two"
]
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/basic/fixtures/Chars.elm<|end_filename|>
'a'
'\\'
'\u{1F648}'
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/LetInPartial.elm<|end_filename|>
a = let
b = let
b2
c = let
c2 =
d = let
d2 = a
e = let
e2 = a
in
<|start_filename|>src/test/resources/org/elm/ide/folding/fixtures/case_of.elm<|end_filename|>
main<fold text=' = ...'> =
case a of<fold text='...'>
() -><fold text='...'>
()</fold>
() -><fold text='...'>
()</fold></fold></fold>
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/CaseOf.elm<|end_filename|>
f x =
case x of
Just xx ->
xx
Nothing ->
0
Foo Bar baz ->
baz
g x y =
case (x,y) of
(0, 0) ->
"origin"
(0, y2) ->
"x-axis"
(x2, 0) ->
"y-axis"
_ ->
"somewhere else"
h list =
case list of
[] -> 1
(single :: []) :: [] -> 2
[first, second] -> 3
_ :: b -> 4
i record =
case record of
{x,y} -> ()
<|start_filename|>src/test/kotlin/org/elm/lang/core/resolve/ElmRecordFieldResolveTest.kt<|end_filename|>
package org.elm.lang.core.resolve
class ElmRecordFieldResolveTest : ElmResolveTestBase() {
fun `test simple field access`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R -> ()
main r = r.field
--^
""")
fun `test chained field access at end of chain`() = checkByCode(
"""
type alias S = { nested : () }
--X
type alias R = { field : S }
main : R -> ()
main r = r.field.nested
--^
""")
fun `test chained field access at middle of chain`() = checkByCode(
"""
type alias S = { nested : () }
type alias R = { field : S }
--X
main : R -> ()
main r = r.field.nested
--^
""")
fun `test simple field accessor function`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R -> ()
main r =
.field r
--^
""")
fun `test field access on return value inside unannotated function`() = checkByCode(
"""
type alias R = { field : () }
--X
r : () -> R
r unit = { field = unit }
main = (r ()).field
--^
""")
fun `test field access to parameterized record`() = checkByCode(
"""
type alias R a = { field : a }
--X
main : R () -> ()
main r = r.field
--^
""")
fun `test field access to field in record parameter`() = checkByCode(
"""
type alias R a = { a | field : () }
type alias S = { s : R { field2 : () } }
--X
main : S -> ()
main r = r.s.field2
--^
""")
fun `test field access to nested parameterized record`() = checkByCode(
"""
type alias S = { nested : () }
--X
type alias R a = { field : a }
main : R S -> ()
main r = r.field.nested
--^
""")
fun `test field access in lambda call`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R -> ()
main r = (\rr -> rr.field) r
--^
""")
fun `test record update`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R -> R
main r = { r | field = ()}
--^
""")
fun `test record update access`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R -> ()
main r = { r | field = () }.field
--^
""")
fun `test field access of variant param`() = checkByCode(
"""
type T = T { field : () }
--X
main : T -> ()
main t =
case t of
T record ->
record.field
--^
""")
fun `test record value in function call`() = checkByCode(
"""
type alias R = { field : () }
--X
func : R -> ()
func _ = ()
main : ()
main = func { field = () }
--^
""")
fun `test record value in forward pipeline`() = checkByCode(
"""
infix left 0 (|>) = apR
apR : a -> (a -> b) -> b
apR x f = f x
type alias R = { field : () }
--X
func : R -> ()
func _ = ()
main : ()
main = { field = () } |> func
--^
""")
fun `test record value in backward pipeline`() = checkByCode(
"""
infix right 0 (<|) = apL
apL : (a -> b) -> a -> b
apL f x =
f x
type alias R = { field : () }
--X
func : R -> ()
func _ = ()
main : ()
main = func <| { field = () }
--^
""")
fun `test record value returned from function`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R
main = { field = () }
--^
""")
fun `test record value returned from lambda`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R
main = (\_ -> { field = () }) 1
--^
""")
fun `test nested decl field access`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R -> ()
main r =
let
nest = r.field
--^
in
nest
""")
fun `test nested decl mapper`() = checkByCode(
"""
type alias R = { field : () }
--X
type Box a = Box a
map : (a -> b) -> Box a -> Box b
map f (Box a) = Box (f a)
main : Box R -> Box R
main box =
let
f r = { r | field = () }
--^
in
map f box
""")
fun `test multi resolve`() = checkMultiResolve(
"""
type alias R = { field : () }
type alias S = { field : () }
first : () -> () -> ()
first a _ = a
main : R -> S -> ()
main r s =
let
nest t = t.field
--^
in
first (nest r) (nest s)
""")
fun `test ref to destructuring in function parameter`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R -> ()
main { field } = field
--^
""")
fun `test value ref through destructuring in function parameter`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R -> ()
main { field } = field
--^
""")
fun `test ref through destructuring in case`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R -> ()
main r =
case r of
{ field } -> field
--^
""")
fun `test ref to destructuring in case`() = checkByCode(
"""
type alias R = { field : () }
--X
main : R -> ()
main r =
case r of
{ field } -> field
--^
""")
fun `test repeated reference in list 1`() = checkByCode(
"""
type alias R = { field : () }
--X
main : List R
main =
[ { field = () }
--^
]
""")
fun `test repeated reference in list 2`() = checkByCode(
"""
type alias R = { field : () }
--X
main : List R
main =
[ { field = () }
, { field = () }
--^
]
""")
fun `test repeated reference in list 3`() = checkByCode(
"""
type alias R = { field : () }
--X
main : List R
main =
[ { field = () }
, { field = () }
, { field = () }
--^
]
""")
fun `test nested extension aliases with funcion in type variable passed through another variable via forward pipeline`() = checkByCode(
"""
infix left 0 (|>) = apR
apR : a -> (a -> b) -> b
apR x f = f x
type alias R = { field : () }
--X
type alias Outer r = { r : Type (r -> r) }
type Type a = Type a
foo : Outer r -> Outer r
foo r = r
main : Outer R
main =
{ r = Type (\r -> { r | field = () }) } |> foo
--^
""")
}
<|start_filename|>src/main/kotlin/org/elm/ide/typing/ElmBackspaceHandler.kt<|end_filename|>
package org.elm.ide.typing
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.psi.PsiFile
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmStringConstantExpr
// A BackspaceHandlerDelegate is called during character deletion.
// We use this to delete triple quotes, since the QuoteHandler can only delete single characters.
class ElmBackspaceHandler : BackspaceHandlerDelegate() {
private var rangeMarker: RangeMarker? = null
// Called when a character is about to be deleted. There's no return value, so you can't affect behavior
// here.
override fun beforeCharDeleted(c: Char, file: PsiFile, editor: Editor) {
rangeMarker = null
// If we didn't insert the matching quote, don't do anything
if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_QUOTE) return
if (file !is ElmFile) return
val offset = editor.caretModel.offset
val psiElement = file.findElementAt(offset) ?: return
// We need to save the element range now, because the PSI will be changed by the time charDeleted is
// called
val parent = psiElement.parent ?: return
if (parent is ElmStringConstantExpr
&& parent.text == "\"\"\"\"\"\""
&& editor.caretModel.offset == parent.textOffset + 3) {
rangeMarker = editor.document.createRangeMarker(parent.textRange)
}
}
// Called immediately after a character is deleted. If this returns true, no automatic quote or brace
// deletion will happen.
override fun charDeleted(c: Char, file: PsiFile, editor: Editor): Boolean {
// The range marker is automatically adjusted with the deleted character, so we can just delete the
// whole thing.
rangeMarker?.let {
editor.document.deleteString(it.startOffset, it.endOffset)
rangeMarker = null
return true
}
return false
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/Header.elm<|end_filename|>
module Foo
exposing
( f
, g
, h)
import Regex
import Task
exposing
( map
, map2
, map3
)
f = "hello world"
g = 42
h = 99
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmCaseOfExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.util.PsiTreeUtil
import org.elm.lang.core.psi.ElmAtomTag
import org.elm.lang.core.psi.ElmExpressionTag
import org.elm.lang.core.psi.ElmPsiElementImpl
/**
* A pattern-matching expression.
*
* e.g. `case x of
* Just y -> y
* Nothing -> 0`
*/
class ElmCaseOfExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmAtomTag {
/**
* The expression which the case-of performs pattern matching against.
*
* In a well-formed program, this will be non-null.
*/
val expression: ElmExpressionTag?
get() = findChildByClass(ElmExpressionTag::class.java)
/**
* The pattern-matching branches.
*
* In a well-formed program, there will be at least one branch.
*/
val branches: List<ElmCaseOfBranch>
get() = PsiTreeUtil.getChildrenOfTypeAsList(this, ElmCaseOfBranch::class.java)
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmTypeVariable.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.*
import org.elm.lang.core.psi.IdentifierCase.LOWER
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.TypeVariableReference
import org.elm.lang.core.stubs.ElmTypeVariableStub
/**
* Holds a lower-case identifier within a type expression which
* gives the type variable in a parametric type.
*
* e.g. the 'a' in `map : (a -> b) -> List a -> List b`
* e.g. the last `a` in `type Foo a = Bar a`
*/
class ElmTypeVariable : ElmStubbedNamedElementImpl<ElmTypeVariableStub>,
ElmReferenceElement, ElmUnionVariantParameterTag, ElmTypeRefArgumentTag, ElmTypeExpressionSegmentTag {
constructor(node: ASTNode) :
super(node, LOWER)
constructor(stub: ElmTypeVariableStub, stubType: IStubElementType<*, *>) :
super(stub, stubType, LOWER)
val identifier: PsiElement
get() = findNotNullChildByType(ElmTypes.LOWER_CASE_IDENTIFIER)
override val referenceNameElement: PsiElement
get() = identifier
override val referenceName: String
get() = name // equivalent to `referenceNameElement.text` but this checks stub first
override fun getReference() = TypeVariableReference(this)
// type variables can only be referenced within the declaration they're declared in, and, in the
// case of function annotations, from annotations of nested functions
override fun getUseScope(): SearchScope {
return LocalSearchScope(elmFile)
}
}
<|start_filename|>src/main/kotlin/org/elm/ide/refactoring/ElmImportOptimizer.kt<|end_filename|>
package org.elm.ide.refactoring
import com.intellij.lang.ImportOptimizer
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import org.elm.ide.inspections.ImportVisitor
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmImportClause
import org.elm.lang.core.psi.elements.removeItem
import org.elm.lang.core.psi.parentOfType
import org.elm.lang.core.psi.prevSiblings
import org.elm.lang.core.resolve.scope.ModuleScope
class ElmImportOptimizer: ImportOptimizer {
override fun supports(file: PsiFile?) =
file is ElmFile
override fun processFile(file: PsiFile): Runnable {
if (file !is ElmFile) error("expected an Elm File!")
// Pre-compute the unused elements prior to performing the
// actual edits in the Runnable on the UI thread.
val visitor = ImportVisitor(ModuleScope.getImportDecls(file))
file.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitElement(element: PsiElement) {
element.accept(visitor)
super.visitElement(element)
}
})
return Runnable {
val documentManager = PsiDocumentManager.getInstance(file.project)
val document = documentManager.getDocument(file)
if (document != null) {
documentManager.commitDocument(document)
}
execute(visitor)
}
}
private fun execute(visitor: ImportVisitor) {
for (unusedImport in visitor.unusedImports) {
val prevNewline = unusedImport.prevSiblings.firstOrNull { it.textContains('\n') }
if (prevNewline == null) unusedImport.delete()
else unusedImport.parent.deleteChildRange(prevNewline, unusedImport)
}
for (item in visitor.unusedExposedItems) {
val exposingList = item.parentOfType<ElmImportClause>()?.exposingList ?: continue
if (exposingList.allExposedItems.size <= 1) exposingList.delete()
else exposingList.removeItem(item)
}
for (alias in visitor.unusedModuleAliases) {
val parent = alias.parentOfType<ElmImportClause>() ?: continue
// Delete the alias and the preceding whitespace
parent.deleteChildRange(parent.moduleQID.nextSibling, alias)
}
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmConsPattern.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import org.elm.lang.core.psi.ElmPatternChildTag
import org.elm.lang.core.psi.ElmPsiElementImpl
import org.elm.lang.core.psi.directChildren
/**
* A list cons pattern.
*
* e.g. `1 :: [2, 3]`
*/
class ElmConsPattern(node: ASTNode) : ElmPsiElementImpl(node), ElmPatternChildTag {
/**
* The patterns that are consed together.
*
* Note that an [ElmConsPattern] cannot be one of the parts, although it may contain one nested in a [ElmPattern].
*
* e.g. the pattern `(a :: [2]) :: [[3]]` will have parts `(a :: [2])` and `[[3]]`, with the first being an
* [ElmPattern].
*/
val parts: Sequence<ElmPatternChildTag> get() = directChildren.filterIsInstance<ElmPatternChildTag>()
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/ElementTags.kt<|end_filename|>
package org.elm.lang.core.psi
import org.elm.lang.core.psi.elements.*
/**
* An element that is at least one of [ElmUnionVariantParameterTag], [ElmTypeExpressionSegmentTag],
* or [ElmTypeRefArgumentTag].
*
* No elements implement this directly.
*/
interface ElmTypeSignatureDeclarationTag: ElmPsiElement
/** An element that can appear in the parameter list of an [ElmUnionVariant] */
interface ElmUnionVariantParameterTag : ElmTypeSignatureDeclarationTag
/** An Elm expression; either a chain of binary operators, a function call, or an atom */
interface ElmExpressionTag : ElmPsiElement
/** An element that can occur on its own or as an argument to a function or operator */
interface ElmAtomTag : ElmExpressionTag, ElmOperandTag
/** An element that can occur as an argument to an operator */
interface ElmOperandTag : ElmPsiElement, ElmBinOpPartTag
/** An element that can occur in a binary operator expression */
interface ElmBinOpPartTag : ElmPsiElement
/** An element that can be the parameter of an [ElmFunctionDeclarationLeft], [ElmAnonymousFunctionExpr], or [ElmCaseOfBranch] */
interface ElmNameDeclarationPatternTag : ElmNameIdentifierOwner
/** A function being called as the child of a [ElmFunctionCallExpr] */
interface ElmFunctionCallTargetTag : ElmAtomTag
/** An element that is either an [ElmFunctionParamTag], a [ElmPatternChildTag], or both. No elements implement this directly. */
interface ElmFunctionParamOrPatternChildTag : ElmPsiElement
/** An element that can be a top-level parameter to a [ElmFunctionDeclarationLeft] or [ElmOperatorDeclarationLeft] */
interface ElmFunctionParamTag : ElmFunctionParamOrPatternChildTag
/** An element that can be the direct child of an [ElmPattern] */
interface ElmPatternChildTag : ElmFunctionParamOrPatternChildTag
/** A pattern that can appear as the argument list of a UnionPattern */
interface ElmUnionPatternChildTag : ElmPsiElement
/** An element that can be a parameter of an [ElmTypeExpression]*/
interface ElmTypeExpressionSegmentTag : ElmTypeSignatureDeclarationTag
/** An element that can be an argument to an [ElmTypeRef] */
interface ElmTypeRefArgumentTag : ElmTypeSignatureDeclarationTag
/** A value literal. Either a number, string, or char. */
interface ElmConstantTag : ElmAtomTag, ElmFunctionParamTag, ElmPatternChildTag, ElmUnionPatternChildTag
/** An element which can be the target of a field access expression. */
interface ElmFieldAccessTargetTag : ElmPsiElement
/** An element which can occur in a module or import's exposing list */
interface ElmExposedItemTag : ElmPsiElement
/** A named declaration which can be exposed by a module */
interface ElmExposableTag : ElmPsiElement, ElmNameIdentifierOwner
/** The element on the left side of the `=` in a value declaration */
interface ElmValueAssigneeTag : ElmPsiElement
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/Literals.elm<|end_filename|>
f = 0.1
i = 0
l = 12345678901234567890
i = -10
f = 00002340000.00002340000
c = 'd'
c = '\n'
s = ""
s = "test"
-- a string containing newlines
s = """
2nd line
3rd line
"""
-- a docstring
s = """
s = ""
s = "s"
"\"""
"""
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/ElmPsiManager.kt<|end_filename|>
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*
* Originally from intellij-rust
*/
package org.elm.lang.core.psi
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.psi.*
import com.intellij.psi.PsiTreeChangeEvent.PROP_WRITABLE
import com.intellij.psi.impl.PsiTreeChangeEventImpl
import com.intellij.psi.util.PsiModificationTracker
import org.elm.lang.core.ElmFileType
import org.elm.lang.core.psi.elements.ElmFunctionDeclarationLeft
class ElmPsiManager(val project: Project) : ProjectComponent {
/**
* A modification tracker that is incremented on PSI changes that can affect non-local references or inference.
*
* It is incremented whenever a non-whitespace, non-comment change is made to the PSI of an Elm
* file outside of function bodies.
*/
val modificationTracker = SimpleModificationTracker()
override fun projectOpened() {
PsiManager.getInstance(project).addPsiTreeChangeListener(CacheInvalidator())
}
inner class CacheInvalidator : PsiTreeChangeAdapter() {
override fun beforeChildRemoval(event: PsiTreeChangeEvent) = onPsiChange(event, event.child)
override fun beforeChildReplacement(event: PsiTreeChangeEvent) = onPsiChange(event, event.oldChild)
override fun beforeChildMovement(event: PsiTreeChangeEvent) = onPsiChange(event, event.child)
override fun childReplaced(event: PsiTreeChangeEvent) = onPsiChange(event, event.newChild)
override fun childAdded(event: PsiTreeChangeEvent) = onPsiChange(event, event.child)
override fun childMoved(event: PsiTreeChangeEvent) = onPsiChange(event, event.child)
override fun childrenChanged(event: PsiTreeChangeEvent) {
// `GenericChange` event means that "something changed in the file" and sends
// after all events for concrete PSI changes in a file.
// We handle more concrete events and so should ignore the generic event.
if (event !is PsiTreeChangeEventImpl || !event.isGenericChange) onPsiChange(event, event.parent)
}
override fun propertyChanged(event: PsiTreeChangeEvent) {
if (event.propertyName != PROP_WRITABLE && event.element != null) {
onPsiChange(event, event.element)
}
}
private fun onPsiChange(event: PsiTreeChangeEvent, element: PsiElement) {
// If the file is null, then this is an event about VFS changes
val file = event.file
if (file == null && (element is ElmFile || element is PsiDirectory)) {
modificationTracker.incModificationCount()
return
}
if (file?.fileType != ElmFileType) return
if (element is PsiComment || element is PsiWhiteSpace) return
updateModificationCount(element)
}
private fun updateModificationCount(element: PsiElement) {
// If something is changed inside an annotated function, we will only increment the
// function local modification counter. Otherwise, we will increment the global
// modification counter.
val owner = element.outermostDeclaration(strict = false)
if (owner?.typeAnnotation == null ||
// Invalidate globally if we change the name of a top level declaration
(owner.assignee as? ElmFunctionDeclarationLeft)?.lowerCaseIdentifier == element) {
modificationTracker.incModificationCount()
} else {
owner.modificationTracker.incModificationCount()
}
}
}
}
private val Project.elmPsiManager: ElmPsiManager
get() = getComponent(ElmPsiManager::class.java)
/** @see ElmPsiManager.modificationTracker */
val Project.modificationTracker: SimpleModificationTracker
get() = elmPsiManager.modificationTracker
/**
* Return [ElmPsiManager.modificationTracker], or [PsiModificationTracker.MODIFICATION_COUNT] if
* this element is in a language injection.
*/
val ElmPsiElement.globalModificationTracker: Any
get() = elmFile.globalModificationTracker
val ElmFile.globalModificationTracker: Any
get() = when (virtualFile) {
// If the element is in a language injection (e.g. a Kotlin string literal with Elm
// injected, like we use in this project's tests), then we are never notified of PSI
// change events in the injected code; we have to invalidate the cache after any PSI
// change in the project.
is VirtualFileWindow -> PsiModificationTracker.MODIFICATION_COUNT
else -> project.modificationTracker
}
<|start_filename|>src/test/resources/org/elm/ide/folding/fixtures/imports.elm<|end_filename|>
import <fold text='...'>Foo
import Bar</fold>
<|start_filename|>src/main/kotlin/org/elm/lang/core/resolve/ElmReferenceElement.kt<|end_filename|>
package org.elm.lang.core.resolve
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.ElmPsiElement
import org.elm.lang.core.resolve.reference.ElmReference
interface ElmReferenceElement : ElmPsiElement {
val referenceNameElement: PsiElement
val referenceName: String
override fun getReference(): ElmReference
override fun getReferences(): Array<ElmReference>
}
<|start_filename|>src/main/kotlin/org/elm/ide/inspections/ElmTypeDeclarationInspection.kt<|end_filename|>
package org.elm.ide.inspections
import org.elm.lang.core.diagnostics.ElmDiagnostic
import org.elm.lang.core.psi.ElmPsiElement
import org.elm.lang.core.psi.elements.ElmTypeAliasDeclaration
import org.elm.lang.core.psi.elements.ElmTypeAnnotation
import org.elm.lang.core.psi.elements.ElmTypeDeclaration
import org.elm.lang.core.types.typeExpressionInference
import org.elm.lang.core.types.variantInference
class ElmTypeDeclarationInspection : ElmDiagnosticBasedInspection() {
override fun getElementDiagnostics(element: ElmPsiElement): Iterable<ElmDiagnostic> {
return when (element) {
is ElmTypeDeclaration -> element.typeExpressionInference().diagnostics + element.variantInference().diagnostics
is ElmTypeAliasDeclaration -> element.typeExpressionInference().diagnostics
is ElmTypeAnnotation -> element.typeExpressionInference()?.diagnostics ?: emptyList()
else -> emptyList()
}
}
}
<|start_filename|>src/main/kotlin/org/elm/ide/injection/ElmGlslInjector.kt<|end_filename|>
package org.elm.ide.injection
import com.intellij.lang.Language
import com.intellij.lang.injection.MultiHostInjector
import com.intellij.lang.injection.MultiHostRegistrar
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.elements.ElmGlslCodeExpr
class ElmGlslInjector : MultiHostInjector {
override fun elementsToInjectIn(): List<Class<out PsiElement>> {
return listOf(ElmGlslCodeExpr::class.java)
}
override fun getLanguagesToInject(registrar: MultiHostRegistrar, context: PsiElement) {
if (!context.isValid || context !is ElmGlslCodeExpr) return
val language = Language.findInstancesByMimeType("x-shader/x-fragment").firstOrNull() ?: return
val range = TextRange(7, context.textLength - 2)
registrar.startInjecting(language)
.addPlace(null, null, context, range)
.doneInjecting()
}
}
<|start_filename|>src/test/kotlin/org/elm/ide/search/ElmFindUsagesProviderTest.kt<|end_filename|>
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 <NAME>, <NAME>, <NAME> and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elm.ide.search
import com.intellij.psi.PsiElement
import org.elm.lang.ElmTestBase
import org.elm.lang.core.psi.ElmNamedElement
import org.intellij.lang.annotations.Language
class ElmFindUsagesProviderTest: ElmTestBase() {
fun `test function parameter usage`() = doTestByText(
"""
foo x =
--^
let
a = x -- : foobar
in
x -- : foobar
""")
fun `test binary operator usage`() = doTestByText(
"""
power a b = List.product (List.repeat b a)
infix right 5 (**) = power
--^
foo = 2 ** 3 -- : foobar
bar = (**) 2 -- : foobar
""")
private fun doTestByText(@Language("Elm") code: String) {
InlineFile(code)
val source = findElementInEditor<ElmNamedElement>()
val actual = markersActual(source)
val expected = markersFrom(code)
assertEquals(expected.joinToString(COMPARE_SEPARATOR), actual.joinToString(COMPARE_SEPARATOR))
}
private fun markersActual(source: ElmNamedElement) =
myFixture.findUsages(source)
.filter { it.element != null }
// TODO [kl] implement a UsageTypeProvider and replace "foobar" with the expected usage type
// both here and in the test cases themselves.
// .map { Pair(it.element?.line ?: -1, RsUsageTypeProvider.getUsageType(it.element).toString()) }
.map { Pair(it.element?.line ?: -1, "foobar") }
private fun markersFrom(text: String) =
text.split('\n')
.withIndex()
.filter { it.value.contains(MARKER) }
.map { Pair(it.index, it.value.substring(it.value.indexOf(MARKER) + MARKER.length).trim()) }
private companion object {
val MARKER = "-- : "
val COMPARE_SEPARATOR = " | "
}
val PsiElement.line: Int? get() = containingFile.viewProvider.document?.getLineNumber(textRange.startOffset)
}
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/layout/fixtures/WhitespaceHandling.elm<|end_filename|>
-- Virtual end decl tokens should be placed at the end of line, AFTER the newline.
-- This is important for ElmParameterInfoHandler and other things that need to look
-- at the context of the caret when the caret is on a space character.
x = f
y = f
z = f -- a comment that belongs to the value decl
-- this should stand on its own
a = f 0
<|start_filename|>src/main/kotlin/org/elm/utils/MyDirectoryIndex.kt<|end_filename|>
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Ported from IntelliJ's LightDirectoryIndex.java
*
* I ported this initially because I ran into a weird issue with
* LightDirectoryIndex where lookup was failing in IntelliJ Ultimate,
* but not when building & running the plugin as a developer. So I
* copied it over to add some debug logging, and it magically started
* working. I have no clue why this appears to have fixed it, but such
* is life...
*/
package org.elm.utils
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileTypes.FileTypeEvent
import com.intellij.openapi.fileTypes.FileTypeListener
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.VirtualFileWithId
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.Consumer
import com.intellij.util.containers.ContainerUtil
private val log = logger<MyDirectoryIndex<*>>()
class MyDirectoryIndex<T>(parentDisposable: Disposable,
private val myDefValue: T,
private val myInitializer: Consumer<MyDirectoryIndex<T>>) {
private val myInfoCache = ContainerUtil.createConcurrentIntObjectMap<T>()
init {
resetIndex()
val connection = ApplicationManager.getApplication().messageBus.connect(parentDisposable)
connection.subscribe(FileTypeManager.TOPIC, object : FileTypeListener {
override fun fileTypesChanged(event: FileTypeEvent) {
resetIndex()
}
})
connection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
for (event in events) {
val file = event.file
if (file == null || file.isDirectory) {
resetIndex()
break
}
}
}
})
}
fun resetIndex() {
myInfoCache.clear()
myInitializer.consume(this)
}
fun putInfo(file: VirtualFile?, value: T) {
if (file !is VirtualFileWithId) return
cacheInfo(file, value)
}
fun getInfoForFile(file: VirtualFile?): T {
if (file !is VirtualFileWithId) return myDefValue
val dir: VirtualFile
dir = if (!file.isDirectory) {
val info = getCachedInfo(file)
if (info != null) {
return info
}
file.parent
} else {
file
}
var count = 0
var root: VirtualFile? = dir
while (root != null) {
if (++count > 1000) {
throw IllegalStateException("Possible loop in tree, started at " + dir.name)
}
val info = getCachedInfo(root)
if (info != null) {
if (dir != root) {
cacheInfos(dir, root, info)
}
return info
}
root = root.parent
}
return cacheInfos(dir, null, myDefValue)
}
private fun cacheInfos(virtualFile: VirtualFile?, stopAt: VirtualFile?, info: T): T {
var dir = virtualFile
while (dir != null) {
cacheInfo(dir, info)
if (dir == stopAt) {
break
}
dir = dir.parent
}
return info
}
private fun cacheInfo(file: VirtualFile, info: T) {
val id = (file as VirtualFileWithId).id
if (log.isDebugEnabled) {
val thing = if (info == myDefValue) "sentinel" else info.toString()
log.debug("Putting $thing for $file using id $id")
}
myInfoCache.put(id, info)
}
private fun getCachedInfo(file: VirtualFile): T? {
val id = (file as VirtualFileWithId).id
val info = myInfoCache.get(id)
if (log.isDebugEnabled) {
val thing = if (info == myDefValue) "sentinel" else info.toString()
log.debug("Got $thing for $file using id $id")
}
return info
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmParenthesizedExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import org.elm.lang.core.psi.*
/**
* An Elm expression wrapped in parentheses
*
* e.g. `(42)`
*/
class ElmParenthesizedExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmAtomTag, ElmFunctionCallTargetTag, ElmFieldAccessTargetTag {
/** In a well-formed program, this will never be null. */
val expression: ElmExpressionTag? get() = findChildByClass(ElmExpressionTag::class.java)
}
<|start_filename|>src/main/kotlin/org/elm/ide/search/ElmFindUsagesProvider.kt<|end_filename|>
package org.elm.ide.search
import com.intellij.lang.cacheBuilder.DefaultWordsScanner
import com.intellij.lang.cacheBuilder.WordsScanner
import com.intellij.lang.findUsages.FindUsagesProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
import org.elm.lang.core.lexer.ElmIncrementalLexer
import org.elm.lang.core.psi.ELM_COMMENTS
import org.elm.lang.core.psi.ELM_IDENTIFIERS
import org.elm.lang.core.psi.ElmNamedElement
import org.elm.lang.core.psi.ElmTypes.OPERATOR_IDENTIFIER
import org.elm.lang.core.psi.ElmTypes.REGULAR_STRING_PART
import org.elm.lang.core.psi.elements.*
import org.elm.lang.core.psi.tokenSetOf
class ElmFindUsagesProvider : FindUsagesProvider {
override fun getWordsScanner(): WordsScanner? {
return DefaultWordsScanner(
ElmIncrementalLexer(),
ELM_IDENTIFIERS,
ELM_COMMENTS,
tokenSetOf(REGULAR_STRING_PART),
TokenSet.EMPTY,
tokenSetOf(OPERATOR_IDENTIFIER))
}
override fun canFindUsagesFor(psiElement: PsiElement) =
psiElement is ElmNamedElement
override fun getType(element: PsiElement): String {
// TODO [kl] handle more cases
return when (element) {
is ElmModuleDeclaration -> "Module"
is ElmAsClause -> "Aliased Module Import"
is ElmFunctionDeclarationLeft -> "Value/Function Declaration"
is ElmInfixDeclaration -> "Infix Operator Declaration"
is ElmTypeAliasDeclaration -> "Type Alias"
is ElmTypeDeclaration -> "Union Type"
is ElmUnionVariant -> "Union Variant"
is ElmLowerPattern -> "Value Binding"
is ElmPortAnnotation -> "Port Annotation"
is ElmFieldType -> "Record Field"
else -> "unknown type for $element"
}
}
// TODO [kl] this doesn't appear to do anything?
override fun getDescriptiveName(element: PsiElement) =
when (element) {
is ElmNamedElement -> element.name ?: "unknown"
else -> "unknown descriptive name for $element"
}
override fun getNodeText(element: PsiElement, useFullName: Boolean) =
when (element) {
is ElmNamedElement -> element.name ?: "unknown"
else -> "unknown node text for $element"
}
override fun getHelpId(psiElement: PsiElement) =
null
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmFieldAccessExpr.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.ElmAtomTag
import org.elm.lang.core.psi.ElmFieldAccessTargetTag
import org.elm.lang.core.psi.ElmFunctionCallTargetTag
import org.elm.lang.core.psi.ElmPsiElementImpl
import org.elm.lang.core.psi.ElmTypes.LOWER_CASE_IDENTIFIER
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReference
import org.elm.lang.core.resolve.reference.RecordFieldReference
/**
* Accessing a field on a record.
*
* EXAMPLES: The following expressions each access a record field called `name`:
* ```
* user.name
* model.currentUser.name
* (defaultUser "George").name
* { user = { name = "George" } }.name
* ```
*/
class ElmFieldAccessExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmReferenceElement, ElmAtomTag, ElmFunctionCallTargetTag, ElmFieldAccessTargetTag {
/** An expression which evaluates to a record value whose field we want to access */
val targetExpr: ElmFieldAccessTargetTag
get() = findNotNullChildByClass(ElmFieldAccessTargetTag::class.java)
/** The name of the record field to read */
val lowerCaseIdentifier: PsiElement
get() = findNotNullChildByType(LOWER_CASE_IDENTIFIER)
override val referenceNameElement: PsiElement
get() = lowerCaseIdentifier
override val referenceName: String
get() = lowerCaseIdentifier.text
override fun getReference(): ElmReference {
return RecordFieldReference.fromElement(this) { it.targetExpr }
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/psi/elements/ElmTypeRef.kt<|end_filename|>
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.*
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReference
import org.elm.lang.core.resolve.reference.ModuleNameQualifierReference
import org.elm.lang.core.resolve.reference.QualifiedTypeReference
import org.elm.lang.core.resolve.reference.SimpleTypeReference
import org.elm.lang.core.stubs.ElmPlaceholderStub
/**
* A type expression which references an [ElmTypeAliasDeclaration] or an [ElmTypeDeclaration].
*
* It may have one or more type arguments, which are each a type expression.
*
* e.g.
* - `String`
* - `List a`
* - `List { x : Int }`
* - `Task.Task Http.Error String`
*/
class ElmTypeRef : ElmStubbedElement<ElmPlaceholderStub>,
ElmReferenceElement, ElmTypeExpressionSegmentTag, ElmTypeRefArgumentTag, ElmUnionVariantParameterTag {
constructor(node: ASTNode) :
super(node)
constructor(stub: ElmPlaceholderStub, stubType: IStubElementType<*, *>) :
super(stub, stubType)
val upperCaseQID: ElmUpperCaseQID
get() = stubDirectChildrenOfType<ElmUpperCaseQID>().single()
/**
* All arguments to the type, if there are any.
*
* The elements will be in source order.
*/
val allArguments: List<ElmTypeRefArgumentTag>
get() = stubDirectChildrenOfType()
override val referenceNameElement: PsiElement
get() = upperCaseQID.upperCaseIdentifierList.last()
override val referenceName: String
get() = upperCaseQID.refName // stub-safe
override fun getReference(): ElmReference =
references.first()
override fun getReferences(): Array<ElmReference> {
val qualifierPrefix = upperCaseQID.qualifierPrefix // stub-safe
return if (qualifierPrefix != "") {
arrayOf(QualifiedTypeReference(this, qualifierPrefix),
ModuleNameQualifierReference(this, upperCaseQID, qualifierPrefix))
} else {
arrayOf(SimpleTypeReference(this))
}
}
}
<|start_filename|>src/test/kotlin/org/elm/workspace/VersionTest.kt<|end_filename|>
package org.elm.workspace
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
class VersionTest {
@Test
fun `version compare`() {
assertTrue(v(1, 0, 0) < v(2, 0, 0))
assertTrue(v(2, 0, 0) > v(1, 0, 0))
assertTrue(v(1, 0, 0) == v(1, 0, 0))
assertTrue(v(0, 1, 0) < v(0, 2, 0))
assertTrue(v(0, 2, 0) > v(0, 1, 0))
assertTrue(v(0, 1, 0) == v(0, 1, 0))
assertTrue(v(0, 0, 1) < v(0, 0, 2))
assertTrue(v(0, 0, 2) > v(0, 0, 1))
assertTrue(v(0, 0, 1) == v(0, 0, 1))
}
@Test
fun `version compare takes into account pre-release info`() {
// based on example ordering from the SemVer spec
val versionsInOrder = listOf(
"1.0.0-alpha.1",
"1.0.0-alpha.beta",
"1.0.0-beta",
"1.0.0-beta.2",
"1.0.0-beta.11",
"1.0.0-rc.1",
"1.0.0"
)
versionsInOrder.zipWithNext { a: String, b: String ->
assertTrue("$a < $b") {
Version.parse(a) < Version.parse(b)
}
}
}
@Test
fun `version compare ignores build metadata`() {
assertTrue(Version.parse("1.0.0+foo").compareTo(Version.parse("1.0.0+bar")) == 0)
}
@Test
fun `version toString is dotted form`() {
assertEquals("1.2.3", v(1, 2, 3).toString())
}
@Test
fun `version toString includes pre-release info if available`() {
assertEquals("1.2.3-rc1", Version(1, 2, 3, preReleaseFields = listOf("rc1")).toString())
}
@Test
fun `parse works on good input`() {
Version.parse("1.2.3")
}
@Test
fun `parse ignores junk around the version number`() {
assertEquals(Version.parse("foo 1.2.3 bar"), Version(1, 2, 3))
}
@Test
fun `parses pre-release version info`() {
assertEquals(
Version.parse("1.2.3-alpha"),
Version(1, 2, 3, preReleaseFields = listOf("alpha")))
}
@Test
fun `parses build metadata`() {
assertEquals(
Version.parse("1.2.3+99999"),
Version(1, 2, 3, buildFields = listOf("99999")))
}
@Test
fun `parses pre-release version info AND build metadata`() {
assertEquals(
Version.parse("1.2.3-alpha+99999"),
Version(1, 2, 3, preReleaseFields = listOf("alpha"), buildFields = listOf("99999")))
}
@Test
fun `toString emits the dotted version number without any adornment`() {
assertEquals("1.2.3", Version.parse("1.2.3").toString())
}
@Test(expected = ParseException::class)
fun `parse throws on bad input`() {
Version.parse("bogus.version.number")
}
@Test
fun `parseOrNull does not throw on bad input`() {
assertNull(Version.parseOrNull("bogus.version.number"))
}
private fun v(x: Int, y: Int, z: Int) =
Version(x, y, z)
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/partial/CaseOf.elm<|end_filename|>
f1 = case
f2 = case x
f3 = case x of
f4 = case x of
type alias Garbage = String
f5 = case x of
Just y
f6 = case x of
Just y -> type alias Garbage
Nothing -> 42
<|start_filename|>src/main/kotlin/org/elm/lang/core/types/DisjointSet.kt<|end_filename|>
package org.elm.lang.core.types
/**
* A map of [TyVar] to [Ty] that optimizes retrieval of chains of references
*
* https://en.wikipedia.org/wiki/Disjoint-set_data_structure
*/
class DisjointSet {
private val map = mutableMapOf<TyVar, Ty>()
operator fun set(key: TyVar, value: Ty) {
map[key] = value
}
operator fun get(ty: Ty): Ty {
if (ty !is TyVar) return ty
var node: TyVar = ty
var parent = map[node]
// use Tarjan's algorithm for path compression to keep access near constant time
while (parent is TyVar) {
val grandparent = map[parent] ?: return parent
map[node] = grandparent
node = parent
parent = grandparent
}
return parent ?: node
}
operator fun contains(ty: TyVar): Boolean = ty in map
fun isEmpty(): Boolean = map.isEmpty()
fun asMap(): Map<TyVar, Ty> = map
}
<|start_filename|>src/main/kotlin/org/elm/workspace/ElmDetachProjectAction.kt<|end_filename|>
package org.elm.workspace
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataKey
class ElmDetachProjectAction : AnAction() {
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = e.project != null && e.associatedElmProject != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val elmProject = e.associatedElmProject ?: return
project.elmWorkspace.detachElmProject(elmProject.manifestPath)
}
private val AnActionEvent.associatedElmProject: ElmProject?
get() = dataContext.getData(DATA_KEY)
companion object {
val DATA_KEY = DataKey.create<ElmProject>("ELM_PROJECT_TO_DETACH")
}
}
<|start_filename|>src/test/resources/org/elm/ide/folding/fixtures/module.elm<|end_filename|>
module Mod exposing
(<fold text='...'> foo
, bar
</fold>)
-- some comments
import <fold text='...'>Basics exposing (..)
import Maybe
import Maybe exposing ( Maybe(Just,Nothing) )
import Native.List</fold>
<|start_filename|>src/test/resources/org/elm/lang/core/lexer/basic/fixtures/Numbers.elm<|end_filename|>
1
111
-111
1.0
111.0
-111.0
100e3
-100e3
100.0e3
-100.0e3
100e-3
-100e-3
100.0e-3
-100.0e-3
<|start_filename|>src/test/kotlin/org/elm/ide/spelling/ElmSpellCheckerTest.kt<|end_filename|>
package org.elm.ide.spelling
import com.intellij.spellchecker.inspections.SpellCheckingInspection
import org.elm.lang.ElmTestBase
import org.intellij.lang.annotations.Language
class ElmSpellCheckerTest : ElmTestBase() {
fun testNamedElement() = doTest(
"""<TYPO descr="Typo: In word 'wodlr'">wodlr</TYPO> = 42""")
fun testComments() = doTest(
"""-- Hello, <TYPO descr="Typo: In word 'Wodrl'">Wodrl</TYPO>!""")
fun testStringLiterals() = doTest(
"""x = "<TYPO descr="Typo: In word 'Wodlr'">Wodlr</TYPO>" """)
fun testCommentsSuppressed() = doTest(
"-- Hello, Wodrl!",
processComments = false)
fun testStringLiteralsSuppressed() = doTest(
"""x = "Hello, Wodlr!" """,
processLiterals = false)
private fun doTest(@Language("Elm") text: String, processComments: Boolean = true, processLiterals: Boolean = true) {
val inspection = SpellCheckingInspection()
inspection.processLiterals = processLiterals
inspection.processComments = processComments
myFixture.configureByText("main.elm", text)
myFixture.enableInspections(inspection)
myFixture.testHighlighting(false, false, true, "main.elm")
}
}
<|start_filename|>src/main/kotlin/org/elm/lang/core/lexer/ElmIncrementalLexer.kt<|end_filename|>
package org.elm.lang.core.lexer
import com.intellij.lexer.FlexAdapter
/**
* A raw lexer over the lexer generated by Flex. The purpose of this
* lexer is to provide basic lexing (no special whitespace logic).
* It can be used in places where a state-less (incremental) lexer is
* needed by IntelliJ (syntax highlighting), and it can be used as the
* foundation for a stateful lexer.
*
* @see ElmLayoutLexer
*/
class ElmIncrementalLexer : FlexAdapter(_ElmLexer())
<|start_filename|>src/test/resources/org/elm/ide/folding/fixtures/let_in.elm<|end_filename|>
main<fold text=' = ...'> =
let<fold text='...'>
foo<fold text=' = ...'> = ()</fold>
</fold>in<fold text='...'>
foo</fold></fold>
<|start_filename|>src/test/kotlin/org/elm/ide/docs/ElmResolveLinkTest.kt<|end_filename|>
package org.elm.ide.docs
import com.intellij.psi.PsiManager
import org.elm.lang.ElmTestBase
import org.elm.lang.core.psi.ElmNamedElement
import org.intellij.lang.annotations.Language
class ElmResolveLinkTest : ElmTestBase(){
fun `test type`() = doTest(
"""
type Foo = Bar
--X
foo : Foo
foo = 0
--^
""", "Foo")
fun `test type alias`() = doTest(
"""
type alias Foo = Int
--X
foo : Foo
foo = 0
--^
""", "Foo")
private fun doTest(@Language("Elm") code: String, link: String) {
InlineFile(code)
val context = findElementInEditor<ElmNamedElement>("^")
val expectedElement = findElementInEditor<ElmNamedElement>("X")
val actualElement = ElmDocumentationProvider()
.getDocumentationElementForLink(PsiManager.getInstance(project), link, context)
assertEquals(expectedElement, actualElement)
}
}
<|start_filename|>src/main/kotlin/org/elm/ide/inspections/import/MakeDeclarationFix.kt<|end_filename|>
package org.elm.ide.inspections.import
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.codeInsight.template.impl.TextExpression
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.elm.lang.core.psi.*
import org.elm.lang.core.psi.elements.ElmTypeAnnotation
import org.elm.lang.core.types.TyFunction
import org.elm.lang.core.types.renderParam
import org.elm.lang.core.types.typeExpressionInference
import org.elm.utils.getIndent
class MakeDeclarationFix(element: ElmPsiElement) : LocalQuickFixAndIntentionActionOnPsiElement(element) {
data class Context(val typeAnnotation: ElmTypeAnnotation)
override fun getText() = "Create"
override fun getFamilyName() = text
public override fun isAvailable(): Boolean {
return super.isAvailable() && findApplicableContext() != null
}
private fun findApplicableContext(): Context? {
val element = startElement as? ElmPsiElement ?: return null
val typeAnnotation = element.parentOfType<ElmTypeAnnotation>(strict = false)
?: return null
if (typeAnnotation.reference.resolve() != null) {
// the target declaration already exists; nothing needs to be done
return null
}
return Context(typeAnnotation)
}
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) {
if (file !is ElmFile || editor == null) return
val context = findApplicableContext() ?: return
WriteCommandAction.writeCommandAction(project).run<Throwable> {
generateDecl(project, editor, context)
}
}
private fun generateDecl(project: Project, editor: Editor, context: Context) {
val typeAnnotation = context.typeAnnotation
val factory = ElmPsiFactory(project)
// Insert a newline at the end of this line
val anchor = typeAnnotation.nextLeaves
.takeWhile { !it.text.contains('\n') }
.lastOrNull() ?: typeAnnotation
val indent = editor.getIndent(typeAnnotation.startOffset)
typeAnnotation.parent.addAfter(factory.createWhitespace("\n$indent"), anchor)
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
// Move the caret down to the line that we just created
editor.caretModel.moveCaretRelatively(0, 1, false, false, false)
// Insert the Live Template
val template = generateTemplate(project, context)
TemplateManager.getInstance(project).startTemplate(editor, template)
}
private fun generateTemplate(project: Project, context: Context): Template {
val templateManager = TemplateManager.getInstance(project)
val template = templateManager.createTemplate("", "")
template.isToReformat = false
val typeAnnotation = context.typeAnnotation
val name = typeAnnotation.referenceName
template.addTextSegment("$name ")
val ty = typeAnnotation.typeExpressionInference()?.ty
val args: List<String> = when (ty) {
is TyFunction -> ty.parameters.map { it.renderParam() }
else -> emptyList()
}
for (arg in args) {
template.addVariable(TextExpression(arg), true)
template.addTextSegment(" ")
}
template.addTextSegment("=\n ")
template.addEndVariable()
return template
}
}
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/FieldAccessorFunction.elm<|end_filename|>
allCredentials users =
List.map .credentials users
<|start_filename|>src/test/resources/org/elm/lang/core/parser/fixtures/complete/ValueQID.elm<|end_filename|>
f = List.length []
<|start_filename|>src/main/kotlin/org/elm/ide/hints/ElmExpressionTypeProvider.kt<|end_filename|>
package org.elm.ide.hints
import com.intellij.lang.ExpressionTypeProvider
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.ElmPsiElement
import org.elm.lang.core.psi.ancestors
import org.elm.lang.core.psi.elements.ElmParenthesizedExpr
import org.elm.lang.core.types.findInference
import org.elm.lang.core.types.findTy
import org.elm.lang.core.types.renderedText
/**
* Provides the text for the "Expression Type" command, which is typically bound to `Ctrl+Shift+P` or `Cmd+Shift+P`
*/
class ElmExpressionTypeProvider : ExpressionTypeProvider<PsiElement>() {
override fun getErrorHint() = "Type is unknown"
override fun getInformationHint(element: PsiElement): String {
val ty = (element as? ElmPsiElement)?.findTy() ?: return errorHint
return StringUtil.escapeXmlEntities(ty.renderedText())
}
override fun getExpressionsAt(elementAt: PsiElement): List<PsiElement> {
val expressionTypes = elementAt.findInference()?.expressionTypes ?: return emptyList()
return elementAt.ancestors.takeWhile { it !is ElmFile }
.filter { it in expressionTypes && it !is ElmParenthesizedExpr }
.toList()
}
}
| AleksandrSl/intellij-elm |
<|start_filename|>test/unit-test/framework/mock_securechip.c<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <setjmp.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <cmocka.h>
#include <securechip/securechip.h>
#include <stdio.h>
#include <string.h>
#include <wally_crypto.h>
static uint32_t _u2f_counter;
bool securechip_update_keys(void)
{
return true;
}
int securechip_kdf(securechip_slot_t slot, const uint8_t* msg, size_t len, uint8_t* kdf_out)
{
check_expected(slot);
check_expected(msg);
// wally_sha256(msg, len, kdf_out, 32);
memcpy(kdf_out, (const uint8_t*)mock(), 32);
return 0;
}
bool securechip_u2f_counter_set(uint32_t counter)
{
_u2f_counter = counter;
return true;
}
bool securechip_u2f_counter_inc(uint32_t* counter)
{
*counter = _u2f_counter++;
return true;
}
bool securechip_ecc_unsafe_sign(const uint8_t* priv_key, const uint8_t* msg, uint8_t* sig)
{
return false;
}
bool securechip_ecc_generate_public_key(uint8_t* priv_key, uint8_t* pub_key)
{
return false;
}
bool securechip_attestation_sign(const uint8_t* msg, uint8_t* signature_out)
{
return false;
}
bool securechip_monotonic_increments_remaining(uint32_t* remaining_out)
{
return false;
}
bool securechip_model(securechip_model_t* model_out)
{
return false;
}
<|start_filename|>src/qtouch/qtouch.h<|end_filename|>
/*============================================================================
Filename : touch.h
Project : QTouch Modular Library
Purpose : configuation macros for touch library
This file is part of QTouch Modular Library Release 5.1 example application.
Important Note: This file was created using the QTouch Configurator within
Atmel Start and then patched.
Usage License: Refer license.h file for license information
Support: Visit http://www.microchip.com/support/hottopics.aspx
to create MySupport case.
------------------------------------------------------------------------------
Copyright (c) 2017 Microchip. All rights reserved.
------------------------------------------------------------------------------
============================================================================*/
#ifndef TOUCH_H
#define TOUCH_H
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/*----------------------------------------------------------------------------
* include files
*----------------------------------------------------------------------------*/
#include "touch_api_ptc.h"
/**********************************************************/
/******************* Acquisition controls *****************/
/**********************************************************/
/* Defines the Measurement Time in milli seconds.
* Range: 1 to 255.
* Default value: 20.
*/
#define DEF_TOUCH_MEASUREMENT_PERIOD_MS 20
/* Defines the Type of sensor
* Default value: NODE_MUTUAL.
*/
#define DEF_SENSOR_TYPE NODE_SELFCAP
/* Set sensor calibration mode for charge share delay ,Prescaler or series resistor.
* Range: CAL_AUTO_TUNE_NONE / CAL_AUTO_TUNE_RSEL / CAL_AUTO_TUNE_PRSC / CAL_AUTO_TUNE_CSD
* Default value: CAL_AUTO_TUNE_NONE.
*/
#define DEF_PTC_CAL_OPTION CAL_AUTO_TUNE_NONE
/* Defines the interrupt priority for the PTC. Set low priority to PTC interrupt for applications
* having interrupt time constraints. Range: 0 to 2 Default: 2 (Lowest Priority)
*/
#define DEF_PTC_INTERRUPT_PRIORITY 2
/* Calibration option to ensure full charge transfer */
/* Bits 7:0 = XX | TT SELECT_TAU | X | CAL_OPTION */
#define DEF_PTC_TAU_TARGET CAL_CHRG_5TAU
#define DEF_PTC_CAL_AUTO_TUNE \
(uint8_t)((DEF_PTC_TAU_TARGET << CAL_CHRG_TIME_POS) | DEF_PTC_CAL_OPTION)
/* Set default bootup acquisition frequency.
* Range: FREQ_SEL_0 - FREQ_SEL_15 , FREQ_SEL_SPREAD
* Default value: FREQ_SEL_0.
*/
#define DEF_SEL_FREQ_INIT FREQ_SEL_8
/*----------------------------------------------------------------------------
* defines
*----------------------------------------------------------------------------*/
/**********************************************************/
/***************** Node Params ******************/
/**********************************************************/
/* Acquisition Set 1 */
/* Defines the number of sensor nodes in the acquisition set
* Range: 1 to 65535.
* Default value: 1
*/
#define DEF_NUM_CHANNELS (8)
/* Defines node parameter setting
* {X-line, Y-line, Charge Share Delay, NODE_RSEL_PRSC(series resistor, prescaler), NODE_G(Analog
* Gain , Digital Gain), filter level}
*/
// Slider 1 buttons
#define NODE_0_PARAMS \
{ \
X_NONE, Y_LINE(26), 0, NODE_RSEL_PRSC(RSEL_VAL_20, PRSC_DIV_SEL_1), \
NODE_GAIN(GAIN_4, GAIN_4), FILTER_LEVEL_512 \
}
#define NODE_1_PARAMS \
{ \
X_NONE, Y_LINE(27), 0, NODE_RSEL_PRSC(RSEL_VAL_20, PRSC_DIV_SEL_1), \
NODE_GAIN(GAIN_4, GAIN_4), FILTER_LEVEL_512 \
}
#define NODE_2_PARAMS \
{ \
X_NONE, Y_LINE(28), 0, NODE_RSEL_PRSC(RSEL_VAL_20, PRSC_DIV_SEL_1), \
NODE_GAIN(GAIN_4, GAIN_4), FILTER_LEVEL_512 \
}
#define NODE_3_PARAMS \
{ \
X_NONE, Y_LINE(29), 0, NODE_RSEL_PRSC(RSEL_VAL_20, PRSC_DIV_SEL_1), \
NODE_GAIN(GAIN_4, GAIN_4), FILTER_LEVEL_512 \
}
// Slider 0 buttons
#define NODE_4_PARAMS \
{ \
X_NONE, Y_LINE(30), 0, NODE_RSEL_PRSC(RSEL_VAL_20, PRSC_DIV_SEL_1), \
NODE_GAIN(GAIN_4, GAIN_4), FILTER_LEVEL_512 \
}
#define NODE_5_PARAMS \
{ \
X_NONE, Y_LINE(31), 0, NODE_RSEL_PRSC(RSEL_VAL_20, PRSC_DIV_SEL_1), \
NODE_GAIN(GAIN_4, GAIN_4), FILTER_LEVEL_512 \
}
#define NODE_6_PARAMS \
{ \
X_NONE, Y_LINE(20), 0, NODE_RSEL_PRSC(RSEL_VAL_20, PRSC_DIV_SEL_1), \
NODE_GAIN(GAIN_4, GAIN_4), FILTER_LEVEL_512 \
}
#define NODE_7_PARAMS \
{ \
X_NONE, Y_LINE(21), 0, NODE_RSEL_PRSC(RSEL_VAL_20, PRSC_DIV_SEL_1), \
NODE_GAIN(GAIN_4, GAIN_4), FILTER_LEVEL_512 \
}
/**********************************************************/
/***************** Key Params ******************/
/**********************************************************/
/* Defines the number of key sensors
* Range: 1 to 65535.
* Default value: 1
*/
#define DEF_NUM_SENSORS (DEF_NUM_CHANNELS)
/* Defines Key Sensor setting
* {Sensor Threshold, Sensor Hysterisis, Sensor AKS}
*/
// 0..3 higher Slider left to right 4..7 lower Slider right to left
#define KEY_0_PARAMS \
{ \
16, HYST_50, NO_AKS_GROUP \
}
#define KEY_1_PARAMS \
{ \
16, HYST_50, NO_AKS_GROUP \
}
#define KEY_2_PARAMS \
{ \
16, HYST_50, NO_AKS_GROUP \
}
#define KEY_3_PARAMS \
{ \
16, HYST_50, NO_AKS_GROUP \
}
#define KEY_4_PARAMS \
{ \
16, HYST_50, NO_AKS_GROUP \
}
#define KEY_5_PARAMS \
{ \
16, HYST_50, NO_AKS_GROUP \
}
#define KEY_6_PARAMS \
{ \
16, HYST_50, NO_AKS_GROUP \
}
#define KEY_7_PARAMS \
{ \
16, HYST_50, NO_AKS_GROUP \
}
/* De-bounce counter for additional measurements to confirm touch detection
* Range: 0 to 255.
* Default value: 4.
*/
#define DEF_TOUCH_DET_INT 0
/* De-bounce counter for additional measurements to confirm away from touch signal
* to initiate Away from touch re-calibration.
* Range: 0 to 255.
* Default value: 5.
*/
#define DEF_ANTI_TCH_DET_INT 0
/* Threshold beyond with automatic sensor recalibration is initiated.
* Range: RECAL_100/ RECAL_50 / RECAL_25 / RECAL_12_5 / RECAL_6_25 / MAX_RECAL
* Default value: RECAL_100.
*/
#define DEF_ANTI_TCH_RECAL_THRSHLD RECAL_50
/* Rate at which sensor reference value is adjusted towards sensor signal value
* when signal value is greater than reference.
* Units: 200ms
* Range: 0-255
* Default value: 20u = 4 seconds.
*/
#define DEF_TCH_DRIFT_RATE 20
/* Rate at which sensor reference value is adjusted towards sensor signal value
* when signal value is less than reference.
* Units: 200ms
* Range: 0-255
* Default value: 5u = 1 second.
*/
#define DEF_ANTI_TCH_DRIFT_RATE 5
/* Time to restrict drift on all sensor when one or more sensors are activated.
* Units: 200ms
* Range: 0-255
* Default value: 20u = 4 seconds.
*/
#define DEF_DRIFT_HOLD_TIME 20
/* Set mode for additional sensor measurements based on touch activity.
* Range: REBURST_NONE / REBURST_UNRESOLVED / REBURST_ALL
* Default value: REBURST_UNRESOLVED
*/
#define DEF_REBURST_MODE REBURST_ALL
/* Sensor maximum ON duration upon touch.
* Range: 0-255
* Default value: 0
*/
#define DEF_MAX_ON_DURATION 0
/*
* The count that the reference value must be above the measured value to
* allow the force calibrate procedure to overwrite the reference to the
* current measured value.
*/
#define KEY_FORCE_CALIBRATE_THRESHOLD 10
/**********************************************************/
/***************** Slider/Wheel Parameters ****************/
/**********************************************************/
/*
* Do not use qtouch scroller module. The button readings need
* a custom post-filter to reduce noise. The output of the custom
* filter is then fed into a custom scroller implementation.
* This allows low noise button readings while keeping
* fast responsiveness.
*/
#define DEF_NUM_SCROLLERS 2 // Number of scrollers (sliders or wheels)
#define DEF_SCROLLER_NUM_CHANNELS 4 // Number of channels per scroller
#define DEF_SCROLLER_OFFSET_0 4 // Index of first button in scroller
#define DEF_SCROLLER_OFFSET_1 0 // Index of first button in scroller
#define DEF_SCROLLER_RESOLUTION 256 // Scroller resolution in bits
#define DEF_SCROLLER_DET_THRESHOLD 25 // Scroller detect threshold
#define DEF_SCROLLER_TOUCH_THRESHOLD 25 // Scroller active threshold
#define DEF_SCROLLER_UNTOUCH_THRESHOLD 20 // Scroller active threshold
#define DEF_SCROLLER_DEADBAND 13 // 13 bits = 5% of 256-bit range
#define DEF_SCROLLER_NUM_PREV_POS \
4 // Number of previous scroller positions to remember; used in a simple filter
#define DEF_SCROLLER_OFF \
0xFFFF // Marker for indicating scroller reading does not exceed detection threshold
#define DEF_SENSOR_EDGE_WEIGHT \
0.15 // Percent added weight to edge sensors, which are physically smaller
#define DEF_SENSOR_NUM_PREV_POS \
4 // Number of previous sensor positions to remember; used in a simple filter
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // TOUCH_C
<|start_filename|>test/unit-test/test_app_btc_multisig.c<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
#include <cmocka.h>
#include <btc_util.h>
#include <apps/btc/btc.h>
#include <apps/btc/btc_common.h>
#include <keystore.h>
#include <memory/memory.h>
#include <util.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <wally_bip32.h>
const char* _multisig_name = "foo";
bool __wrap_memory_multisig_get_by_hash(const uint8_t* hash, char* name_out)
{
snprintf(name_out, MEMORY_MULTISIG_NAME_MAX_LEN, "%s", _multisig_name);
return true;
}
bool __wrap_apps_btc_confirm_multisig_basic(
const char* title,
const app_btc_coin_params_t* params,
const char* name,
const BTCScriptConfig_Multisig* multisig,
bool verify_xpubs)
{
assert_string_equal(title, "Receive to");
check_expected(params->coin);
assert_string_equal(name, _multisig_name);
check_expected(multisig);
return true;
}
static uint8_t _mock_seed[32] = {
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
};
// sudden tenant fault inject concert weather maid people chunk youth stumble grit
static uint8_t _mock_bip39_seed[64] =
"\x5a\x11\x5b\xcd\xbe\x0f\xe1\x70\x0e\x60\x95\x74\xf3\x57\xb0\x8d\xca\x37\x15\xb0\x35\xe6\xc7"
"\x76\x77\x0a\xc7\xa0\xab\x2e\x2f\xea\x84\x0b\xa2\x76\x35\x06\xfa\x9c\x39\xde\x4d\xef\x27\xf6"
"\xf8\xeb\xce\x36\x37\x02\xe9\x83\xe5\x49\xbd\x7d\xef\x14\xa0\x31\xbf\xdd";
typedef struct {
BTCCoin coin;
BTCScriptConfig_Multisig_ScriptType script_type;
uint32_t threshold;
size_t xpubs_count;
const char* xpubs[20];
size_t our_xpub_index;
const char* out;
const uint32_t keypath[6];
const size_t keypath_len;
} testcase_t;
static testcase_t _tests[] = {
/** P2WSH **/
{
.coin = BTCCoin_BTC,
.threshold = 1,
.xpubs_count = 2,
.xpubs =
{
"<KEY>"
"<KEY>",
"<KEY>"
"<KEY>",
},
.our_xpub_index = 1,
.out = "bc1q2fhgukymf0caaqrhfxrdju4wm94wwrch2ukntl5fuc0faz8zm49q0h6ss8",
.keypath =
{
48 + BIP32_INITIAL_HARDENED_CHILD,
0 + BIP32_INITIAL_HARDENED_CHILD,
0 + BIP32_INITIAL_HARDENED_CHILD,
2 + BIP32_INITIAL_HARDENED_CHILD,
1,
2,
},
.keypath_len = 6,
},
{
.coin = BTCCoin_TBTC,
.threshold = 1,
.xpubs_count = 2,
.xpubs =
{
"<KEY>"
"<KEY>",
"<KEY>"
"<KEY>",
},
.our_xpub_index = 0,
.out = "<KEY>",
.keypath =
{
48 + BIP32_INITIAL_HARDENED_CHILD,
1 + BIP32_INITIAL_HARDENED_CHILD,
0 + BIP32_INITIAL_HARDENED_CHILD,
2 + BIP32_INITIAL_HARDENED_CHILD,
1,
2,
},
.keypath_len = 6,
},
{
.coin = BTCCoin_TBTC,
.threshold = 7,
.xpubs_count = 15,
.xpubs =
{
// clang-format off
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
// clang-format on
},
.our_xpub_index = 14,
.out = "tb1qndz49j0arp8g6jc8vcrgf9ugrsw96a0j5d7vqcun6jev6rlv47jsv99y5m",
.keypath =
{
48 + BIP32_INITIAL_HARDENED_CHILD,
1 + BIP32_INITIAL_HARDENED_CHILD,
0 + BIP32_INITIAL_HARDENED_CHILD,
2 + BIP32_INITIAL_HARDENED_CHILD,
1,
2,
},
.keypath_len = 6,
},
/** P2SH **/
{
.coin = BTCCoin_BTC,
.script_type = BTCScriptConfig_Multisig_ScriptType_P2WSH_P2SH,
.threshold = 2,
.xpubs_count = 2,
.xpubs =
{
"<KEY>"
"<KEY>",
"<KEY>"
"<KEY>",
},
.our_xpub_index = 1,
.out = "<KEY>",
.keypath =
{
48 + BIP32_INITIAL_HARDENED_CHILD,
0 + BIP32_INITIAL_HARDENED_CHILD,
0 + BIP32_INITIAL_HARDENED_CHILD,
1 + BIP32_INITIAL_HARDENED_CHILD,
1,
0,
},
.keypath_len = 6,
},
/** P2SH Nunchuk keypath **/
{
.coin = BTCCoin_BTC,
.script_type = BTCScriptConfig_Multisig_ScriptType_P2WSH_P2SH,
.threshold = 2,
.xpubs_count = 2,
.xpubs =
{
"<KEY>"
"<KEY>",
"<KEY>"
"<KEY>",
},
.our_xpub_index = 1,
.out = "<KEY>",
.keypath =
{
48 + BIP32_INITIAL_HARDENED_CHILD,
0 + BIP32_INITIAL_HARDENED_CHILD,
0 + BIP32_INITIAL_HARDENED_CHILD,
1,
0,
},
.keypath_len = 5,
},
};
static void _test_app_btc_address_multisig(void** state)
{
mock_state(_mock_seed, _mock_bip39_seed);
for (size_t test_case_index = 0; test_case_index < sizeof(_tests) / sizeof(testcase_t);
test_case_index++) {
const testcase_t* test_case = &_tests[test_case_index];
BTCScriptConfig_Multisig multisig = {
.threshold = test_case->threshold,
.xpubs_count = test_case->xpubs_count,
.our_xpub_index = test_case->our_xpub_index,
.script_type = test_case->script_type,
};
for (size_t xpub_idx = 0; xpub_idx < test_case->xpubs_count; xpub_idx++) {
multisig.xpubs[xpub_idx] = btc_util_parse_xpub(test_case->xpubs[xpub_idx]);
}
char out[XPUB_ENCODED_LEN] = {0};
expect_value(__wrap_apps_btc_confirm_multisig_basic, params->coin, test_case->coin);
expect_memory(
__wrap_apps_btc_confirm_multisig_basic, multisig, &multisig, sizeof(multisig));
bool result = app_btc_address_multisig(
test_case->coin,
&multisig,
test_case->keypath,
test_case->keypath_len,
out,
sizeof(out),
false);
assert_int_equal(APP_BTC_OK, result);
assert_string_equal(out, test_case->out);
}
}
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(_test_app_btc_address_multisig),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
<|start_filename|>src/usb/usb_processing.c<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "usb_processing.h"
#include "platform_config.h"
#include "u2f/u2f_packet.h"
#include "usb_frame.h"
#include "usb_packet.h"
#include <hardfault.h>
#if !defined(BOOTLOADER)
#include <hww.h>
#ifndef TESTING
#include <hal_timer.h>
extern struct timer_descriptor TIMER_0;
#endif
#endif
#include <queue.h>
#include <stdlib.h>
#include <string.h>
#include <u2f.h>
#include <util.h>
/**
* Amount of time to wait before an outstanding operation times out
* (if the client is closed).
*/
#define USB_OUTSTANDING_OP_TIMEOUT_MS (500)
#define USB_TIMER_TICK_PERIOD_MS (100)
#define USB_OUTSTANDING_OP_TIMEOUT_TICKS (USB_OUTSTANDING_OP_TIMEOUT_MS / USB_TIMER_TICK_PERIOD_MS)
struct usb_processing {
CMD_Callback* registered_cmds;
uint32_t registered_cmds_len;
/* Whether the content of in_packet is a new, complete incoming packet. */
bool has_packet;
struct queue* (*out_queue)(void);
void (*send)(void);
usb_frame_formatter_t format_frame;
/**
* Function to call when a message has been received,
* but there is no registered API set to manage it.
*/
void (*manage_invalid_endpoint)(struct queue* queue, uint32_t cid);
#if !defined(BOOTLOADER)
/**
* Function to call when a message has been received,
* but the stack cannot process it because the device
* is busy processing another request.
*/
void (*create_blocked_req_error)(Packet* out_packet, const Packet* in_packet);
/**
* Function to call to forcefully abort any operation
* that is keeping the USB stack busy.
*/
void (*force_operation_abort)(void);
/**
* Function to call in order to know whether the given
* request can be passed to the stack, while the stack
* is blocked.
*/
bool (*can_request_unblock)(const Packet* in_packet);
/**
* Callback to forcefully abort any operation processing
* on this stack.
*/
void (*abort_outstanding_op)(void);
#endif
};
/**
* Keeps track of the internal state of the USB processing stack.
*/
typedef struct {
/**
* FUTURE: this can be removed and packets can be queued when
* hww workflows are independent from the USB processing layer.
*
* At that point, we can just use the usb_processing.has_packet flags to make
* sure that we don't drop packets, send FRAME_ERR_CHANNEL_BUSY when layer-1
* is busy (i.e. we are in the process of buffering a frame) and continuously accept
* frames from both stacks (so we don't send FRAME_ERR_CHANNEL_BUSY improperly when
* it's the user interface that is busy, and not the USB port).
*
* For now this is impossible as the UI being busy keeps the USB port busy as well...
*/
volatile bool in_packet_queued;
/**
* Contains the USB packet that is currently being processed.
* This is only valid if in_packet_queued is true.
* It is shared between all stacks (as we only process one packet at the time,
* and send out FRAME_ERR_CHANNEL_BUSY if we are still processing the buffered one
* and a new one arrives).
*/
Packet in_packet;
#if !defined(BOOTLOADER)
/**
* Pointer to the context that has locked the USB stack while
* handling a blocking request.
*/
struct usb_processing* blocking_ctx;
/**
* Timeout counter. This is increased every 100ms by a timer,
* and is reset to 0 every time a new packet is send to one of the
* underlying stacks. When the timeout counter becomes greater then
* USB_OUTSTANDING_OP_TIMEOUT_TICKS, any outstanding operation is aborted
* and the USB stack is forcefully unlocked.
*/
uint16_t timeout_counter;
#endif
} usb_processing_state_t;
static usb_processing_state_t _usb_state = {0};
/**
* Responds with data of a certain length.
* @param[in] packet The packet to be sent.
*/
static queue_error_t _enqueue_frames(struct usb_processing* ctx, const Packet* out_packet)
{
return ctx->format_frame(
out_packet->cmd, out_packet->data_addr, out_packet->len, out_packet->cid, ctx->out_queue());
}
/**
* Builds a packet from the passed state.
* @param[in] in_state The packet is loaded from the state.
*/
static void _build_packet(const uint8_t* buf, size_t length, uint8_t cmd, uint32_t cid)
{
memcpy(_usb_state.in_packet.data_addr, buf, MIN(USB_DATA_MAX_LEN, length));
_usb_state.in_packet.len = length;
_usb_state.in_packet.cmd = cmd;
_usb_state.in_packet.cid = cid;
}
/**
* Prepares an outgoing packet.
*/
static void _prepare_out_packet(const Packet* in_packet, Packet* out_packet)
{
memset(out_packet->data_addr, 0, sizeof(out_packet->data_addr));
out_packet->len = 0;
out_packet->cmd = in_packet->cmd;
out_packet->cid = in_packet->cid;
}
/**
* Register a command callback that is executed when a USB frame with
* a specific cmd id is received.
*/
void usb_processing_register_cmds(
struct usb_processing* ctx,
const CMD_Callback* cmd_callbacks,
int num_cmds)
{
if (ctx->registered_cmds == NULL) {
ctx->registered_cmds = malloc(num_cmds * sizeof(CMD_Callback));
if (!ctx->registered_cmds) {
Abort("Error: malloc usb commands");
}
memcpy(ctx->registered_cmds, cmd_callbacks, num_cmds * sizeof(CMD_Callback));
} else {
size_t old_size = ctx->registered_cmds_len * sizeof(CMD_Callback);
size_t added_size = num_cmds * sizeof(CMD_Callback);
size_t new_size = old_size + added_size;
CMD_Callback* new_registered_cmds = (CMD_Callback*)realloc(ctx->registered_cmds, new_size);
if (new_registered_cmds == NULL) {
free(ctx->registered_cmds);
Abort("Error: realloc usb commands");
}
ctx->registered_cmds = new_registered_cmds;
memcpy(ctx->registered_cmds + ctx->registered_cmds_len, cmd_callbacks, added_size);
}
ctx->registered_cmds_len += num_cmds;
}
/**
* Request to process a complete incoming USB packet.
*/
bool usb_processing_enqueue(
struct usb_processing* ctx,
const uint8_t* buf,
size_t length,
uint8_t cmd,
uint32_t cid)
{
if (_usb_state.in_packet_queued) {
/* We already have a buffered packet. */
return false;
}
_build_packet(buf, length, cmd, cid);
_usb_state.in_packet_queued = true;
ctx->has_packet = true;
return true;
}
void usb_processing_set_send(struct usb_processing* ctx, void (*send)(void))
{
ctx->send = send;
}
/**
* Marks any buffered RX packet as fully processed.
* This frees the RX buffer so that it's possible to
* receive further packets.
*/
static void _usb_processing_drop_received(struct usb_processing* ctx)
{
// Mark the packet as processed.
if (ctx->has_packet) {
ctx->has_packet = false;
util_zero(&_usb_state.in_packet, sizeof(_usb_state.in_packet));
}
_usb_state.in_packet_queued = false;
}
/**
* Executes a packet, making it go through the registered callbacks
* for the given context.
*
* @param ctx USB stack that should execute the packet.
* @param in_packet Packet to execute.
*/
static void _usb_execute_packet(struct usb_processing* ctx, const Packet* in_packet)
{
bool cmd_valid = false;
for (uint32_t i = 0; i < ctx->registered_cmds_len; i++) {
if (in_packet->cmd == ctx->registered_cmds[i].cmd) {
cmd_valid = true;
// process_cmd calls commander(...) or U2F functions.
Packet out_packet;
_prepare_out_packet(in_packet, &out_packet);
ctx->registered_cmds[i].process_cmd(in_packet, &out_packet, USB_DATA_MAX_LEN);
_enqueue_frames(ctx, (const Packet*)&out_packet);
break;
}
}
if (!cmd_valid) {
ctx->manage_invalid_endpoint(ctx->out_queue(), _usb_state.in_packet.cid);
}
}
#if !defined(BOOTLOADER)
/**
* Processes an incoming packet. If the packet cannot be processed,
* send an error response.
*
* @param ctx USB stack that received the packet.
* @param in_packet Packet to process.
*/
static void _usb_arbitrate_packet(struct usb_processing* ctx, const Packet* in_packet)
{
bool can_go_through = true;
/*
* If we're busy on another request, check if this
* request matches.
*/
if (_usb_state.blocking_ctx) {
if (ctx == _usb_state.blocking_ctx) {
/* Ask the lock owner to check if it will accept this request. */
can_go_through = ctx->can_request_unblock(in_packet);
} else {
can_go_through = false;
}
}
if (!can_go_through) {
/* The receiving state should send back an error */
Packet out_packet;
_prepare_out_packet(in_packet, &out_packet);
ctx->create_blocked_req_error(&out_packet, in_packet);
_enqueue_frames(ctx, &out_packet);
} else {
_usb_execute_packet(ctx, in_packet);
/* New packet processed: reset the watchdog timeout. */
_usb_state.timeout_counter = 0;
}
}
#endif
/**
* Check if packets are buffered; if yes, process and pop them.
* @param ctx USB stack to process.
*/
static void _usb_consume_incoming_packets(struct usb_processing* ctx)
{
if (!ctx->has_packet) {
return;
}
/*
* The bootloader is not allowed to execute any blocking request.
* Remove all the arbitration logic.
*/
#if !defined(BOOTLOADER)
_usb_arbitrate_packet(ctx, &_usb_state.in_packet);
#else
_usb_execute_packet(ctx, &_usb_state.in_packet);
#endif
_usb_processing_drop_received(ctx);
}
#if !defined(BOOTLOADER)
/**
* Check if the lock timer has expired for this context.
* If it has, call the abort_outstanding_op function and unlock
* the USB stack.
*
* @param ctx Context to check.
*/
static void _check_lock_timeout(struct usb_processing* ctx)
{
if (_usb_state.blocking_ctx != ctx) {
return;
}
if (_usb_state.timeout_counter > USB_OUTSTANDING_OP_TIMEOUT_TICKS) {
if (!ctx->abort_outstanding_op) {
Abort("abort_outstanding_op is NULL.");
}
ctx->abort_outstanding_op();
usb_processing_unlock();
}
}
#endif
void usb_processing_process(struct usb_processing* ctx)
{
#if APP_U2F == 1
uint32_t timeout_cid;
// If there are any timeouts, send them first
while (u2f_packet_timeout_get(&timeout_cid)) {
u2f_packet_timeout(timeout_cid);
usb_processing_u2f()->send();
}
#endif
_usb_consume_incoming_packets(ctx);
/*
* If USB sends are not enabled (yet), send will be NULL.
* Otherwise, we can call it now to flush outstanding writes.
*/
if (ctx->send != NULL) {
ctx->send();
}
#if !defined(BOOTLOADER)
/*
* If we've been locked for too much time, it's time
* to forcefully close the offending operation.
*/
_check_lock_timeout(ctx);
#endif
}
#if APP_U2F == 1
struct usb_processing* usb_processing_u2f(void)
{
static struct usb_processing usb_processing;
return &usb_processing;
}
#endif
struct usb_processing* usb_processing_hww(void)
{
static struct usb_processing usb_processing;
return &usb_processing;
}
#if !defined(BOOTLOADER) && !defined(TESTING)
/**
* Callback invoked every 100ms from interrupt space.
*
* Increments the realtime counter (until it saturates).
*/
static void _timer_cb(const struct timer_task* const timer_task)
{
(void)timer_task;
if (_usb_state.timeout_counter != (uint16_t)-1) {
_usb_state.timeout_counter++;
}
}
static void _register_timer(void)
{
static struct timer_task Timer_task;
Timer_task.interval = USB_TIMER_TICK_PERIOD_MS;
Timer_task.cb = _timer_cb;
Timer_task.mode = TIMER_TASK_REPEAT;
timer_stop(&TIMER_0);
timer_add_task(&TIMER_0, &Timer_task);
timer_start(&TIMER_0);
}
#endif
void usb_processing_init(void)
{
#if APP_U2F == 1
usb_processing_u2f()->out_queue = queue_u2f_queue;
queue_init(queue_u2f_queue(), USB_REPORT_SIZE);
usb_processing_u2f()->format_frame = usb_frame_reply;
usb_processing_u2f()->has_packet = false;
usb_processing_u2f()->manage_invalid_endpoint = u2f_invalid_endpoint;
usb_processing_u2f()->can_request_unblock = u2f_blocking_request_can_go_through;
usb_processing_u2f()->create_blocked_req_error = u2f_blocked_req_error;
usb_processing_u2f()->abort_outstanding_op = u2f_abort_outstanding_op;
#endif
usb_processing_hww()->out_queue = queue_hww_queue;
#if !defined(BOOTLOADER)
usb_processing_hww()->can_request_unblock = hww_blocking_request_can_go_through;
usb_processing_hww()->create_blocked_req_error = hww_blocked_req_error;
usb_processing_hww()->abort_outstanding_op = hww_abort_outstanding_op;
#endif
queue_init(queue_hww_queue(), USB_REPORT_SIZE);
usb_processing_hww()->format_frame = usb_frame_reply;
usb_processing_hww()->manage_invalid_endpoint = usb_invalid_endpoint;
usb_processing_hww()->has_packet = false;
#if !defined(BOOTLOADER) && !defined(TESTING)
_register_timer();
#endif
}
#if !defined(BOOTLOADER)
void usb_processing_lock(struct usb_processing* ctx)
{
if (_usb_state.blocking_ctx) {
Abort("Tried to lock the USB stack while locked.");
}
_usb_state.blocking_ctx = ctx;
}
void usb_processing_timeout_reset(void)
{
_usb_state.timeout_counter = 0;
}
void usb_processing_unlock(void)
{
if (!_usb_state.blocking_ctx) {
Abort("Tried to unlock the USB stack while not locked.");
}
_usb_state.blocking_ctx = NULL;
}
#endif
<|start_filename|>test/unit-test/test_sd.c<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
#include <cmocka.h>
#include <sd.h>
static void _test_sd_write_read(void** state)
{
assert_true(sd_format());
uint8_t data[4] = "data";
assert_false(sd_write_bin("test.pdf", NULL, NULL, 0, false));
assert_false(sd_write_bin("test.pdf", NULL, data, 0, false));
assert_false(sd_write_bin("", NULL, data, sizeof(data), false));
assert_false(sd_write_bin(NULL, NULL, data, sizeof(data), false));
assert_true(sd_write_bin("test.pdf", NULL, data, sizeof(data), false));
uint8_t read[100] = {0};
size_t readlen;
assert_true(sd_load_bin("test.pdf", NULL, read, &readlen));
assert_int_equal(readlen, 4);
assert_memory_equal(read, data, readlen);
}
int main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(_test_sd_write_read),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
<|start_filename|>src/platform/platform_init.c<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "platform_init.h"
#include <driver_init.h>
#include <ui/oled/oled.h>
#if !defined(BOOTLOADER)
#include "sd_mmc/sd_mmc_start.h"
#endif
extern void initialise_monitor_handles(void);
void platform_init(void)
{
#if defined(SEMIHOSTING)
initialise_monitor_handles();
#endif
oled_init();
#if !defined(BOOTLOADER)
sd_mmc_start();
#endif
}
<|start_filename|>src/platform/driver_init.h<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// THIS IS A GENERATED FILE, MODIFY AS LITTLE AS POSSIBLE
#ifndef _DRIVER_INIT_H_
#define _DRIVER_INIT_H_
#include "CryptoLib_Headers_pb.h"
#include <hal_atomic.h>
#include <hal_delay.h>
#include <hal_flash.h>
#include <hal_i2c_m_sync.h>
#include <hal_init.h>
#include <hal_io.h>
#include <hal_mci_sync.h>
#include <hal_pac.h>
#include <hal_rand_sync.h>
#include <hal_sha_sync.h>
#include <hal_sleep.h>
#include <hal_timer.h>
#include <hal_usb_device.h>
#include <hpl_rtc_base.h>
#include <sd_mmc.h>
#include <spi_lite.h>
#include <utils.h>
#include "platform_config.h"
#include <bitbox02_pins.h>
#define SHA256_DIGEST_LENGTH 32
extern struct timer_descriptor TIMER_0;
extern struct i2c_m_sync_desc I2C_0;
extern struct mci_sync_desc MCI_0;
extern struct aes_sync_descriptor CRYPTOGRAPHY_0;
extern struct sha_sync_descriptor HASH_ALGORITHM_0;
extern struct flash_descriptor FLASH_0;
extern struct rand_sync_desc RAND_0;
extern PPUKCL_PARAM pvPUKCLParam;
extern PUKCL_PARAM PUKCLParam;
/**
* Close peripheral interfaces
*/
void system_close_interfaces(void);
/**
* Perform system initialization, initialize pins and clocks for
* peripherals
*/
void system_init(void);
/**
* Close peripheral interfaces
*/
void bootloader_close_interfaces(void);
/**
* Perform system initialization, initialize pins and clocks for
* peripherals
*/
void bootloader_init(void);
#endif
<|start_filename|>test/unit-test/framework/mock_diskio.c<|end_filename|>
// Copyright 2021 Shift Crypto AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdint.h>
#include <string.h>
// Must be included before diskio.h, see http://elm-chan.org/fsw/ff/bd/?show=3626
#include <ff.h>
#include <diskio.h>
// This file is the disk middleware for use in tests, replacing sdmmc_diskio.c used in the firmware
// to write to microSD cards.
//
// It writes and reads from RAM instead of to a card or disk so that unit tests can exercise all
// sd-card related functionality.
// 100mb with 512 bytes per sector
#define SECTOR_SIZE 512
#define SECTOR_COUNT 204800
static uint8_t _data[SECTOR_SIZE * SECTOR_COUNT] = {0};
DSTATUS disk_initialize(uint8_t drv)
{
(void)drv;
return 0;
}
DSTATUS disk_status(uint8_t drv)
{
(void)drv;
return 0;
}
DRESULT disk_read(BYTE pdrv, BYTE* buff, LBA_t sector, UINT count)
{
(void)pdrv;
for (UINT i = 0; i < count; i++) {
memcpy(&buff[SECTOR_SIZE * i], &_data[SECTOR_SIZE * sector + SECTOR_SIZE * i], SECTOR_SIZE);
}
return RES_OK;
}
DRESULT disk_write(BYTE pdrv, const BYTE* buff, LBA_t sector, UINT count)
{
for (UINT i = 0; i < count; i++) {
memcpy(&_data[SECTOR_SIZE * sector + SECTOR_SIZE * i], &buff[SECTOR_SIZE * i], SECTOR_SIZE);
}
return RES_OK;
}
DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void* buff)
{
(void)pdrv;
switch (cmd) {
case CTRL_SYNC:
// Already synced (RAM).
return RES_OK;
case GET_BLOCK_SIZE:
*(DWORD*)buff = 1;
return RES_OK;
case GET_SECTOR_SIZE:
*(LBA_t*)buff = SECTOR_SIZE;
return RES_OK;
case GET_SECTOR_COUNT:
*(LBA_t*)buff = SECTOR_COUNT;
return RES_OK;
default:
return RES_PARERR;
}
}
<|start_filename|>src/ui/oled/oled.c<|end_filename|>
/**
* \file
*
* \brief SSD1306 OLED display controller driver.
*
* Copyright (c) 2013-2015 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
/*
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// BitBox02 controller SH1107:
// The actual size of the GDDR is something like 128x128. But our display only uses the middle 64
// columns. The start column is 32 and end column is 95.
#include "oled.h"
#include <driver_init.h>
#include <hardfault.h>
#include <screen.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <ui/ugui/ugui.h>
#define OLED_CMD_SET_LOW_COL(column) (0x00 | ((column)&0x0F))
#define OLED_CMD_SET_HIGH_COL(column) (0x10 | (((column) >> 4) & 0x0F))
#define OLED_CMD_SET_MEMORY_ADDRESSING_MODE 0x20
#define OLED_CMD_SET_COLUMN_ADDRESS 0x21
#define OLED_CMD_SET_PAGE_ADDRESS 0x22
#define OLED_CMD_SET_START_LINE(line) (0x40 | (line))
#define OLED_CMD_SET_CONTRAST_CONTROL_FOR_BANK0 0x81
#define OLED_CMD_SET_CHARGE_PUMP_SETTING 0x8D
#define OLED_CMD_SET_SEGMENT_RE_MAP_COL0_SEG0 0xA0
#define OLED_CMD_SET_SEGMENT_RE_MAP_COL127_SEG0 0xA1
#define OLED_CMD_ENTIRE_DISPLAY_AND_GDDRAM_ON 0xA4
#define OLED_CMD_ENTIRE_DISPLAY_ON 0xA5
#define OLED_CMD_SET_NORMAL_DISPLAY 0xA6
#define OLED_CMD_SET_INVERSE_DISPLAY 0xA7
#define OLED_CMD_SET_MULTIPLEX_RATIO 0xA8
#define OLED_CMD_SET_DISPLAY_ON 0xAF
#define OLED_CMD_SET_DISPLAY_OFF 0xAE
#define OLED_CMD_SET_PAGE_START_ADDRESS(page) \
(0xB0 | ((page)&0x0f)) // changed to 0x0f for SH1107 (128x64) OLED
#define OLED_CMD_SET_COM_OUTPUT_SCAN_UP 0xC0
#define OLED_CMD_SET_COM_OUTPUT_SCAN_DOWN 0xC8
#define OLED_CMD_SET_DISPLAY_OFFSET 0xD3
#define OLED_CMD_SET_DISPLAY_CLOCK_DIVIDE_RATIO 0xD5
#define OLED_CMD_SET_PRE_CHARGE_PERIOD 0xD9
#define OLED_CMD_SET_COM_PINS 0xDA
#define OLED_CMD_SET_VCOMH_DESELECT_LEVEL 0xDB
#define OLED_CMD_NOP 0xE3
#define OLED_CMD_SCROLL_H_RIGHT 0x26
#define OLED_CMD_SCROLL_H_LEFT 0x27
#define OLED_CMD_CONTINUOUS_SCROLL_V_AND_H_RIGHT 0x29
#define OLED_CMD_CONTINUOUS_SCROLL_V_AND_H_LEFT 0x2A
#define OLED_CMD_DEACTIVATE_SCROLL 0x2E
#define OLED_CMD_ACTIVATE_SCROLL 0x2F
#define OLED_CMD_SET_VERTICAL_SCROLL_AREA 0xA3
static bool _frame_buffer_updated = false;
static uint8_t _frame_buffer[128 * 8];
enum _interface_t {
INTERFACE_COMMAND,
INTERFACE_DATA,
};
static volatile bool _enabled = false;
/**
* Write to serial interface
* @param [in] interface which interface to talk to.
* @param [in] buf the bytes to write (must be at least buf_len long)
* @param [in] buf_len the number of bytes to write
*/
static inline void _write(enum _interface_t interface, const uint8_t* buf, size_t buf_len)
{
uint8_t cmd = interface == INTERFACE_COMMAND ? 0 : 1;
gpio_set_pin_level(PIN_OLED_CMD, cmd);
gpio_set_pin_level(PIN_OLED_CS, 0);
// It is safe to cast from const here because "write_block" only reads from buf
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
SPI_0_write_block((void*)buf, buf_len);
#pragma GCC diagnostic pop
gpio_set_pin_level(PIN_OLED_CS, 1);
}
static inline void _write_data(const uint8_t* buf, size_t buf_len)
{
_write(INTERFACE_DATA, buf, buf_len);
}
static inline void _write_cmd(uint8_t command)
{
const uint8_t buf[] = {command};
_write(INTERFACE_COMMAND, buf, sizeof(buf));
}
static inline void _write_cmd_with_param(uint8_t command, uint8_t value)
{
const uint8_t buf[] = {command, value};
_write(INTERFACE_COMMAND, buf, sizeof(buf));
}
// Vertical addressing mode
#define ADDRESSING_MODE 0x21
#define SEGMENT_REMAP OLED_CMD_SET_SEGMENT_RE_MAP_COL127_SEG0
#define DISPLAY_OFFSET 0x60
#define DISPLAY_OFFSET_MIRRORED 0x20
#define PRE_CHARGE_PERIOD 0x22
void oled_init(void)
{
if (_enabled) {
return;
}
// DC-DC OFF
gpio_set_pin_level(PIN_OLED_ON, 0);
delay_us(5);
// Hard reset OLED display controller
gpio_set_pin_level(PIN_OLED_RES, 0);
delay_us(5);
gpio_set_pin_level(PIN_OLED_RES, 1);
delay_us(5);
// Initialize
_write_cmd(OLED_CMD_SET_DISPLAY_OFF);
// Set brightness (0x00..=0xff)
_write_cmd_with_param(OLED_CMD_SET_CONTRAST_CONTROL_FOR_BANK0, 0xff);
_write_cmd(ADDRESSING_MODE);
_write_cmd(SEGMENT_REMAP);
_write_cmd(OLED_CMD_SET_COM_OUTPUT_SCAN_UP);
// Set normal display (not inverted)
_write_cmd(OLED_CMD_SET_NORMAL_DISPLAY);
// We only activate the 64 lines we use (0x3f == 64 Multiplex ratio)
_write_cmd_with_param(OLED_CMD_SET_MULTIPLEX_RATIO, 0x3f);
// Shift the columns by 96 when display is in non-mirrored orientation
_write_cmd_with_param(OLED_CMD_SET_DISPLAY_OFFSET, DISPLAY_OFFSET);
// Set clock frequency and divisor
// Upper 4 bits are freqency, lower 4 bits are divisor
_write_cmd_with_param(OLED_CMD_SET_DISPLAY_CLOCK_DIVIDE_RATIO, 0xf0);
// Set precharge and discharge
// Upper 4 bits are dis-charge, lower 4 bits are pre-charge
_write_cmd_with_param(OLED_CMD_SET_PRE_CHARGE_PERIOD, PRE_CHARGE_PERIOD);
_write_cmd_with_param(OLED_CMD_SET_VCOMH_DESELECT_LEVEL, 0x35);
// TODO(nc): Find in other docs (bitbox02 only?)
// built-in DC-DC enable (8a:disable; 8b:enable)
_write_cmd_with_param(0xad, 0x8a);
_write_cmd(OLED_CMD_ENTIRE_DISPLAY_AND_GDDRAM_ON);
oled_clear_buffer();
oled_send_buffer();
_write_cmd(OLED_CMD_SET_DISPLAY_ON);
delay_ms(100);
// DC-DC ON
gpio_set_pin_level(PIN_OLED_ON, 1);
_enabled = true;
}
void oled_send_buffer(void)
{
/* The SH1107 Segment/Common driver specifies that there are 16 pages per column
* In total we should be writing 64*128 pixels. 8 bits per page, 16 pages per column and 64
* columns */
for (size_t i = 0; i < 64; i++) {
_write_cmd(OLED_CMD_SET_LOW_COL(i));
_write_cmd(OLED_CMD_SET_HIGH_COL(i));
_write_data(&_frame_buffer[i * 16], 16);
}
}
void oled_clear_buffer(void)
{
memset(_frame_buffer, 0, sizeof(_frame_buffer));
}
void oled_mirror(bool mirror)
{
if (mirror) {
_write_cmd(OLED_CMD_SET_SEGMENT_RE_MAP_COL0_SEG0);
_write_cmd(OLED_CMD_SET_COM_OUTPUT_SCAN_DOWN);
// Shift the columns by 32 when display is in mirrored orientation
_write_cmd_with_param(OLED_CMD_SET_DISPLAY_OFFSET, DISPLAY_OFFSET_MIRRORED);
} else {
_write_cmd(OLED_CMD_SET_SEGMENT_RE_MAP_COL127_SEG0);
_write_cmd(OLED_CMD_SET_COM_OUTPUT_SCAN_UP);
_write_cmd_with_param(OLED_CMD_SET_DISPLAY_OFFSET, DISPLAY_OFFSET);
}
}
void oled_set_pixel(uint16_t x, uint16_t y, uint8_t c)
{
/* pixels can be accessed via buf[y*16+x/8] >> x%8 */
uint32_t p;
if (x > 127) return;
if (y > 63) return;
p = y * 16;
p += x / 8;
if (c) {
_frame_buffer[p] |= 1 << (x % 8);
} else {
_frame_buffer[p] &= ~(1 << (x % 8));
}
_frame_buffer_updated = true;
}
void oled_off(void)
{
if (!_enabled) {
return;
}
_write_cmd(OLED_CMD_SET_DISPLAY_OFF);
// OFF VCC
gpio_set_pin_level(PIN_OLED_ON, 0);
_enabled = false;
}
void oled_set_brightness(uint8_t value)
{
_write_cmd_with_param(OLED_CMD_SET_CONTRAST_CONTROL_FOR_BANK0, value);
}
<|start_filename|>src/qtouch/qtouch.c<|end_filename|>
/*============================================================================
Filename : touch.c
Project : QTouch Modular Library
Purpose : Provides Initialization, Processing and ISR handler of touch library,
Simple API functions to get/set the key touch parameters from/to the
touch library data structures
This file is part of QTouch Modular Library Release 5.1 example application.
Important Note: This file was created using the QTouch Configurator within
Atmel Start and then patched.
Usage License: Refer license.h file for license information
Support: Visit http://www.microchip.com/support/hottopics.aspx
to create MySupport case.
------------------------------------------------------------------------------
Copyright (c) 2017 Microchip. All rights reserved.
------------------------------------------------------------------------------
============================================================================*/
#ifndef TOUCH_C
#define TOUCH_C
/*----------------------------------------------------------------------------
* include files
*----------------------------------------------------------------------------*/
#include "qtouch.h"
#include "license.h"
#include "touch_api_ptc.h"
#include "util.h"
#include <driver_init.h>
#include <platform_config.h>
/*----------------------------------------------------------------------------
* prototypes
*----------------------------------------------------------------------------*/
/*! \brief configure binding layer config parameter
*/
static void build_qtm_config(qtm_control_t* qtm);
/*! \brief configure keys, wheels and sliders.
*/
static touch_ret_t touch_sensors_config(void);
/*! \brief Init complete callback function prototype.
*/
static void init_complete_callback(void);
/*! \brief Touch measure complete callback function example prototype.
*/
static void qtm_measure_complete_callback(void);
/*! \brief Touch post process complete callback function prototype.
*/
static void qtm_post_process_complete(void);
/*! \brief Touch Error callback function prototype.
*/
static void qtm_error_callback(uint8_t err);
/*! \brief Calculate scroller positions based on custom filter.
*/
static void qtouch_process_scroller_positions(void);
/*----------------------------------------------------------------------------
* Global Variables
*----------------------------------------------------------------------------*/
/* Binding layer control */
qtm_control_t qtm_control;
qtm_control_t* p_qtm_control;
qtm_state_t qstate;
/* Measurement Done Touch Flag */
volatile uint8_t measurement_done_touch = 0;
/* Error Handling */
uint8_t module_error_code = 0;
/* Acquisition module internal data - Size to largest acquisition set */
uint16_t touch_acq_signals_raw[DEF_NUM_CHANNELS];
/* Acquisition set 1 - General settings */
qtm_acq_node_group_config_t ptc_qtlib_acq_gen1 = {DEF_NUM_CHANNELS,
DEF_SENSOR_TYPE,
DEF_PTC_CAL_AUTO_TUNE,
DEF_SEL_FREQ_INIT,
DEF_PTC_INTERRUPT_PRIORITY};
/* Node status, signal, calibration values */
qtm_acq_node_data_t ptc_qtlib_node_stat1[DEF_NUM_CHANNELS];
/* Node configurations */
qtm_acq_samd51_node_config_t ptc_seq_node_cfg1[DEF_NUM_CHANNELS] = {NODE_0_PARAMS,
NODE_1_PARAMS,
NODE_2_PARAMS,
NODE_3_PARAMS,
NODE_4_PARAMS,
NODE_5_PARAMS,
NODE_6_PARAMS,
NODE_7_PARAMS};
/* Container */
qtm_acquisition_control_t qtlib_acq_set1 = {&ptc_qtlib_acq_gen1,
&ptc_seq_node_cfg1[0],
&ptc_qtlib_node_stat1[0]};
/* Stores recent unfiltered scroller positions for custom filter */
__extension__ static uint16_t scroller_previous_position[][DEF_SCROLLER_NUM_PREV_POS] = {
[0 ...(DEF_NUM_SCROLLERS - 1)][0 ...(DEF_SCROLLER_NUM_PREV_POS - 1)] = 0};
/* Current scroller position consisting of a moving-average of preceding positions for custom filter
*/
__extension__ static uint16_t scroller_position[] = {[0 ...(DEF_NUM_SCROLLERS - 1)] = 0};
/* Whether or not scroller reading exceeds threshold for custom filter */
__extension__ static bool scroller_active[DEF_NUM_SCROLLERS] = {[0 ...(DEF_NUM_SCROLLERS - 1)] = 0};
/**********************************************************/
/*********************** Keys Module **********************/
/**********************************************************/
/* Keys set 1 - General settings */
qtm_touch_key_group_config_t qtlib_key_grp_config_set1 = {DEF_NUM_SENSORS,
DEF_TOUCH_DET_INT,
DEF_MAX_ON_DURATION,
DEF_ANTI_TCH_DET_INT,
DEF_ANTI_TCH_RECAL_THRSHLD,
DEF_TCH_DRIFT_RATE,
DEF_ANTI_TCH_DRIFT_RATE,
DEF_DRIFT_HOLD_TIME,
DEF_REBURST_MODE};
qtm_touch_key_group_data_t qtlib_key_grp_data_set1;
/* Key data */
qtm_touch_key_data_t qtlib_key_data_set1[DEF_NUM_SENSORS];
/* Key Configurations */
qtm_touch_key_config_t qtlib_key_configs_set1[DEF_NUM_SENSORS] = {KEY_0_PARAMS,
KEY_1_PARAMS,
KEY_2_PARAMS,
KEY_3_PARAMS,
KEY_4_PARAMS,
KEY_5_PARAMS,
KEY_6_PARAMS,
KEY_7_PARAMS};
/* Container */
qtm_touch_key_control_t qtlib_key_set1 = {&qtlib_key_grp_data_set1,
&qtlib_key_grp_config_set1,
&qtlib_key_data_set1[0],
&qtlib_key_configs_set1[0]};
/**********************************************************/
/***************** Scroller Module ********************/
/**********************************************************/
/*
* Do not use qtouch scroller module. The button readings need
* a custom post-filter to reduce noise. The output of the custom
* filter is then fed into a custom scroller implementation.
* This allows low noise button readings while keeping
* fast responsiveness.
*/
/**********************************************************/
/**************** Binding Layer Module ******************/
/**********************************************************/
#define LIB_MODULES_INIT_LIST \
{ \
(module_init_t) & qtm_ptc_init_acquisition_module, null \
}
#define LIB_MODULES_PROC_LIST \
{ \
(module_proc_t) & qtm_key_sensors_process, null \
}
#define LIB_INIT_DATA_MODELS_LIST \
{ \
(void*)&qtlib_acq_set1, null \
}
#define LIB_DATA_MODELS_PROC_LIST \
{ \
(void*)&qtlib_key_set1, null \
}
#define LIB_MODULES_ACQ_ENGINES_LIST \
{ \
(module_acq_t) & qtm_ptc_start_measurement_seq, null \
}
#define LIB_MODULES_ACQ_ENGINES_LIST_DM \
{ \
(void*)&qtlib_acq_set1, null \
}
/* QTM run time options */
module_init_t library_modules_init[] = LIB_MODULES_INIT_LIST;
module_proc_t library_modules_proc[] = LIB_MODULES_PROC_LIST;
module_arg_t library_module_init_data_models[] = LIB_INIT_DATA_MODELS_LIST;
module_acq_t library_modules_acq_engines[] = LIB_MODULES_ACQ_ENGINES_LIST;
module_arg_t library_module_acq_engine_data_model[] = LIB_MODULES_ACQ_ENGINES_LIST_DM;
module_arg_t library_module_proc_data_model[] = LIB_DATA_MODELS_PROC_LIST;
/*----------------------------------------------------------------------------
* function definitions
*----------------------------------------------------------------------------*/
/*============================================================================
static void build_qtm_config(qtm_control_t *qtm)
------------------------------------------------------------------------------
Purpose: Initialization of binding layer module
Input : Pointer of binding layer container data structure
Output : none
Notes :
============================================================================*/
static void build_qtm_config(qtm_control_t* qtm)
{
/* Initialise the Flags by clearing them */
qtm->binding_layer_flags = 0x00U;
/*!< List of function pointers to acquisition sets */
qtm->library_modules_init = library_modules_init;
/*!< List of function pointers to post processing modules */
qtm->library_modules_proc = library_modules_proc;
/*!< List of Acquisition Engines (Acq Modules one per AcqSet */
qtm->library_modules_acq = library_modules_acq_engines;
/*!< Data Model for Acquisition modules */
qtm->library_module_init_data_model = library_module_init_data_models;
/*!< Data Model for post processing modules */
qtm->library_module_proc_data_model = library_module_proc_data_model;
/*!< Data model for inline module processes */
qtm->library_modules_acq_dm = library_module_acq_engine_data_model;
/*!< Post porcessing pointer */
qtm->qtm_acq_pp = qtm_acquisition_process;
/* Register Binding layer callbacks */
qtm->qtm_init_complete_callback = init_complete_callback;
qtm->qtm_error_callback = qtm_error_callback;
qtm->qtm_measure_complete_callback = qtm_measure_complete_callback;
qtm->qtm_pre_process_callback = null;
qtm->qtm_post_process_callback = qtm_post_process_complete;
}
/*============================================================================
static touch_ret_t touch_sensors_config(void)
------------------------------------------------------------------------------
Purpose: Initialization of touch key sensors
Input : none
Output : none
Notes :
============================================================================*/
/* Touch sensors config - assign nodes to buttons / wheels / sliders / surfaces / water level / etc
*/
static touch_ret_t touch_sensors_config(void)
{
uint16_t sensor_nodes;
touch_ret_t touch_ret = TOUCH_SUCCESS;
/* Init pointers to DMA sequence memory */
qtm_ptc_qtlib_assign_signal_memory(&touch_acq_signals_raw[0]);
/* Initialize sensor nodes */
for (sensor_nodes = 0U; sensor_nodes < DEF_NUM_CHANNELS; sensor_nodes++) {
/* Enable each node for measurement and mark for calibration */
qtm_enable_sensor_node(&qtlib_acq_set1, sensor_nodes);
qtm_calibrate_sensor_node(&qtlib_acq_set1, sensor_nodes);
}
/* Enable sensor keys and assign nodes */
for (sensor_nodes = 0U; sensor_nodes < DEF_NUM_CHANNELS; sensor_nodes++) {
qtm_init_sensor_key(&qtlib_key_set1, sensor_nodes, &ptc_qtlib_node_stat1[sensor_nodes]);
}
return (touch_ret);
}
/*
* Force calibrate
*
* Call this function when the user "probably" isn't touching the device to reset all the
* calibration values. It will only reset inputs that are not considered to be in "touched" states
*/
void qtouch_force_calibrate(void)
{
qtm_touch_key_data_t* key;
for (uint16_t i = 0U; i < DEF_NUM_CHANNELS; i++) {
key = &qtlib_key_data_set1[i];
uint16_t value = key->node_data_struct_ptr->node_acq_signals;
uint16_t reference = key->channel_reference;
int32_t diff = (int32_t)reference - (int32_t)value;
if (!(key->sensor_state & KEY_TOUCHED_MASK) && diff > KEY_FORCE_CALIBRATE_THRESHOLD) {
key->channel_reference = key->node_data_struct_ptr->node_acq_signals;
}
}
}
/*============================================================================
static void init_complete_callback(void)
------------------------------------------------------------------------------
Purpose: Callback function from binding layer called after the completion of
acquisition module initialization.
Input : none
Output : none
Notes :
============================================================================*/
static void init_complete_callback(void)
{
/* Configure touch sensors with Application specific settings */
touch_sensors_config();
}
/*============================================================================
static void qtm_measure_complete_callback( void )
------------------------------------------------------------------------------
Purpose: Callback function from binding layer called after the completion of
measurement cycle. This function sets the post processing request
flag to trigger the post processing.
Input : none
Output : none
Notes :
============================================================================*/
static void qtm_measure_complete_callback(void)
{
qtm_control.binding_layer_flags |= (1 << node_pp_request);
}
/*============================================================================
static void qtm_post_process_complete(void)
------------------------------------------------------------------------------
Purpose: Callback function from binding layer called after the completion of
post processing. This function sets the reburst flag based on the
key sensor group status, calls the datastreamer output function to
display the module data.
Input : none
Output : none
Notes :
============================================================================*/
static void qtm_post_process_complete(void)
{
{
// This block is a workaround for a rare touch issue.
//
// After boot, reburst is required until the sensors are calibrated (see reburst_request
// below). Afterwards, they are calibrated and the sensor signal and reference values can be
// used to figure out touch gestures.
//
// Normally, calibration finishes quickly (tests showed in about 12 loop iterations).
// Afterwards, reference and signal values are non-zero. In very rare cases, a sensor can
// have a reference value of 0 until it is physically touched, meaning that touch is
// required to finish calibration. This could be due to a hardware or production quirk. In
// this case, reburst would be requested until that sensor is touched, and gesture detection
// would not start until then. In this csae, a user could not interact with the device at
// all until they first touched the faulty sensor.
//
// As a workaround for this, if we have sensors with a zero reference value of 0 after 30
// iterations, we assume that all other sensors are calibrated and allow gesture detection
// and user interaction. When the user then touches the weird sensor with a zero reference
// value in normal use of the device, it too would be calibrated and start working normally.
static int counter = 0;
if (counter == 30 && !measurement_done_touch) {
for (uint16_t i = 0; i < DEF_NUM_SENSORS; i++) {
if (qtouch_get_sensor_node_reference(i) == 0) {
measurement_done_touch = 1;
break;
}
}
}
counter++;
}
if ((0U != (qtlib_key_set1.qtm_touch_key_group_data->qtm_keys_status & 0x80U))) {
p_qtm_control->binding_layer_flags |= (1U << reburst_request);
} else {
measurement_done_touch = 1;
}
if (measurement_done_touch) {
qtouch_process_scroller_positions(); // Run the custom filter
}
}
/*============================================================================
static void qtm_error_callback(uint8_t error)
------------------------------------------------------------------------------
Purpose: Callback function from binding layer called after the completion of
post processing. This function is called only when there is error.
Input : error code
Output : decoded module error code
Notes :
Error Handling supported by Binding layer module:
Acquisition Module Error codes: 0x8<error code>
0x81 - Qtm init
0x82 - start acq
0x83 - cal sensors
0x84 - cal hardware
Post processing Modules error codes: 0x4<process_id>
0x40, 0x41, 0x42, ...
process_id is the sequence of process IDs listed in #define LIB_MODULES_PROC_LIST macro.
Process IDs start from zero and maximum is 15
Examples:
0x40 -> error in post processing module 1
0x42 -> error in post processing module 3
Derived Module_error_codes:
Acquisition module error =1
post processing module1 error = 2
post processing module2 error = 3
... and so on
============================================================================*/
static void qtm_error_callback(uint8_t err)
{
module_error_code = 0;
if (err & 0x80) {
module_error_code = 1;
} else if (err & 0x40) {
module_error_code = (err & 0x0F) + 2;
}
}
/*============================================================================
void qtouch_init(void)
------------------------------------------------------------------------------
Purpose: Initialization of touch library. PTC, timer, binding layer and
datastreamer modules are initialized in this function.
Input : none
Output : none
Notes :
============================================================================*/
void qtouch_init(void)
{
qtouch_timer_config();
build_qtm_config(&qtm_control);
qtm_binding_layer_init(&qtm_control);
/* get a pointer to the binding layer control */
p_qtm_control = qmt_get_binding_layer_ptr();
}
/*============================================================================
void qtouch_process(void)
------------------------------------------------------------------------------
Purpose: Main processing function of touch library. This function initiates the
acquisition, calls post processing after the acquistion complete and
sets the flag for next measurement based on the sensor status.
Input : none
Output : none
Notes :
============================================================================*/
void qtouch_process(void)
{
touch_ret_t touch_ret;
/* check the time_to_measure_touch flag for Touch Acquisition */
if (p_qtm_control->binding_layer_flags & (1U << time_to_measure_touch)) {
/* Do the acquisition */
touch_ret = qtm_lib_start_acquisition(0);
/* if the Acquistion request was successful then clear the request flag */
if (TOUCH_SUCCESS == touch_ret) {
/* Clear the Measure request flag */
p_qtm_control->binding_layer_flags &= (uint8_t) ~(1U << time_to_measure_touch);
}
}
/* check the flag for node level post processing */
if (p_qtm_control->binding_layer_flags & (1U << node_pp_request)) {
/* Run Acquisition moudle level post pocessing*/
touch_ret = qtm_lib_acq_process();
/* Check the return value */
if (TOUCH_SUCCESS == touch_ret) {
/* Returned with success: Start module level post processing */
qtm_lib_post_process();
} else {
/* Acq module Eror Detected: Issue an Acq module common error code 0x80 */
qtm_error_callback(0x80);
}
/* Reset the flags for node_level_post_processing */
p_qtm_control->binding_layer_flags &= (uint8_t) ~(1U << node_pp_request);
if (p_qtm_control->binding_layer_flags & (1U << reburst_request)) {
p_qtm_control->binding_layer_flags |= (1U << time_to_measure_touch);
p_qtm_control->binding_layer_flags &= ~(1U << reburst_request);
}
}
}
/*============================================================================
void qtouch_timer_handler(void)
------------------------------------------------------------------------------
Purpose: This function updates the time elapsed to the touch key module to
synchronize the internal time counts used by the module.
Input : none
Output : none
Notes :
============================================================================*/
void qtouch_timer_handler(void)
{
/* Count complete - Measure touch sensors */
qtm_control.binding_layer_flags |= (1U << time_to_measure_touch);
qtm_update_qtlib_timer(DEF_TOUCH_MEASUREMENT_PERIOD_MS);
}
static void qtouch_timer_task_cb(const struct timer_task* const timer_task)
{
(void)timer_task;
qtouch_timer_handler();
}
void qtouch_timer_config(void)
{
static struct timer_task Timer_task;
Timer_task.interval = DEF_TOUCH_MEASUREMENT_PERIOD_MS;
Timer_task.cb = qtouch_timer_task_cb;
Timer_task.mode = TIMER_TASK_REPEAT;
timer_add_task(&TIMER_0, &Timer_task);
timer_start(&TIMER_0);
}
uint16_t qtouch_get_sensor_node_signal(uint16_t sensor_node)
{
return (ptc_qtlib_node_stat1[sensor_node].node_acq_signals);
}
uint16_t qtouch_get_sensor_node_reference(uint16_t sensor_node)
{
return (qtlib_key_data_set1[sensor_node].channel_reference);
}
uint16_t qtouch_get_sensor_cc_val(uint16_t sensor_node)
{
return (ptc_qtlib_node_stat1[sensor_node].node_comp_caps);
}
uint8_t qtouch_get_sensor_state(uint16_t sensor_node)
{
return (qtlib_key_set1.qtm_touch_key_data[sensor_node].sensor_state);
}
/* Holds preceding unfiltered scroller positions */
static uint16_t sensor_previous_filtered_reading[DEF_NUM_SENSORS][DEF_SENSOR_NUM_PREV_POS] = {0};
/* Custom sensor signal filter. */
uint16_t qtouch_get_sensor_node_signal_filtered(uint16_t sensor_node)
{
// Filter the sensor signal.
//
// Smooth it out and saturate it so that values never go beyond 50.
// This helps to mitigate 'jumpy' channels that exist at higher sensor readings when
// in noisy environments.
//
uint16_t X;
uint16_t sensor_raw = qtouch_get_sensor_node_signal(sensor_node);
uint16_t sensor_reference = qtouch_get_sensor_node_reference(sensor_node);
if (sensor_reference == 0) {
// If a sensor reference is 0, it means that the sensor is not yet calibrated (or dead).
// The signal can be high anyway, which makes it look like the sensor is being touched when
// it isn't.
return 0;
}
X = sensor_raw < sensor_reference ? 0 : sensor_raw - sensor_reference;
// Add more weight to edge buttons because they are physically smaller (smaller readings).
if ((sensor_node == DEF_SCROLLER_OFFSET_0) || (sensor_node == DEF_SCROLLER_OFFSET_1) ||
(sensor_node == DEF_SCROLLER_OFFSET_0 + DEF_SCROLLER_NUM_CHANNELS - 1) ||
(sensor_node == DEF_SCROLLER_OFFSET_1 + DEF_SCROLLER_NUM_CHANNELS - 1)) {
X = X * (1 + DEF_SENSOR_EDGE_WEIGHT);
}
// Saturate out-of-range readings.
X = (X > 50) ? 50 : X;
// Calculate sensor readout using a moving average
// The moving average wieghts previous N readings twice current reading
uint16_t moving_average_cummulative_weight = 1; // Add one for current reading calculated above
uint16_t X_ave = X;
for (size_t j = 0; j < DEF_SENSOR_NUM_PREV_POS; j++) {
moving_average_cummulative_weight += 2;
X_ave += sensor_previous_filtered_reading[sensor_node][j] * 2;
}
X_ave = X_ave / moving_average_cummulative_weight;
// Update recorded previous positions
for (size_t j = 0; j < DEF_SENSOR_NUM_PREV_POS - 1; j++) {
sensor_previous_filtered_reading[sensor_node][j] =
sensor_previous_filtered_reading[sensor_node][j + 1];
}
sensor_previous_filtered_reading[sensor_node][DEF_SENSOR_NUM_PREV_POS - 1] = X;
return X_ave;
}
bool qtouch_is_scroller_active(uint16_t scroller)
{
return scroller_active[scroller];
}
uint16_t qtouch_get_scroller_position(uint16_t sensor_node)
{
return scroller_position[sensor_node];
}
void qtouch_process_scroller_positions(void)
{
for (uint8_t scroller = 0; scroller < DEF_NUM_SCROLLERS; scroller++) {
uint8_t i, j;
uint16_t sum = 0;
uint16_t max_sensor_reading = 0;
uint16_t weighted_sum = 0;
uint16_t sensor_location[DEF_SCROLLER_NUM_CHANNELS] = {
1, // Offset by `1` because a `0` location cannot be weight-averaged
DEF_SCROLLER_RESOLUTION / 3,
DEF_SCROLLER_RESOLUTION / 3 * 2,
DEF_SCROLLER_RESOLUTION};
// Read filterd data and weight by sensor physical location
for (i = 0; i < DEF_SCROLLER_NUM_CHANNELS; i++) {
uint16_t value;
value = qtouch_get_sensor_node_signal_filtered(
i + (scroller ? DEF_SCROLLER_OFFSET_1 : DEF_SCROLLER_OFFSET_0));
sum += value;
weighted_sum += value * sensor_location[i];
max_sensor_reading = (value > max_sensor_reading) ? value : max_sensor_reading;
}
// Compensate for deadband (i.e. when only a single edge button gives a reading and
// neighbors do not)
uint16_t scaled_value = weighted_sum / sum;
scaled_value =
(scaled_value < DEF_SCROLLER_DEADBAND) ? DEF_SCROLLER_DEADBAND : (weighted_sum / sum);
scaled_value = (scaled_value > (DEF_SCROLLER_RESOLUTION - DEF_SCROLLER_DEADBAND))
? (DEF_SCROLLER_RESOLUTION - DEF_SCROLLER_DEADBAND)
: scaled_value;
scaled_value = ((scaled_value - DEF_SCROLLER_DEADBAND) * (DEF_SCROLLER_RESOLUTION - 1)) /
(DEF_SCROLLER_RESOLUTION - 2 * DEF_SCROLLER_DEADBAND);
// Calculate scroller position using a moving average
// The moving average wieghts previous N readings twice current reading
if (sum >= DEF_SCROLLER_DET_THRESHOLD) {
uint16_t moving_average_cummulative_weight = 0;
scroller_position[scroller] = 0;
for (j = 0; j < DEF_SCROLLER_NUM_PREV_POS; j++) {
if (scroller_previous_position[scroller][j] != DEF_SCROLLER_OFF) {
moving_average_cummulative_weight += 2;
scroller_position[scroller] += scroller_previous_position[scroller][j] * 2;
}
}
scroller_position[scroller] +=
scaled_value; // Most recent signal is half weight of others to help avoid bounce
// when finger is released
scroller_position[scroller] =
scroller_position[scroller] / (moving_average_cummulative_weight + 1);
}
// Update recorded previous positions and scroller active state
for (j = 0; j < DEF_SCROLLER_NUM_PREV_POS - 1; j++) {
scroller_previous_position[scroller][j] = scroller_previous_position[scroller][j + 1];
}
if (sum >= DEF_SCROLLER_DET_THRESHOLD) {
scroller_previous_position[scroller][DEF_SCROLLER_NUM_PREV_POS - 1] = scaled_value;
} else {
scroller_previous_position[scroller][DEF_SCROLLER_NUM_PREV_POS - 1] = DEF_SCROLLER_OFF;
}
// Use the maximum value of all sensor readings as an estimate of pressure.
// Put a threshold on this to detect whether we're touching or not.
if (max_sensor_reading >= DEF_SCROLLER_TOUCH_THRESHOLD) {
scroller_active[scroller] = true;
} else if (max_sensor_reading <= DEF_SCROLLER_UNTOUCH_THRESHOLD) {
scroller_active[scroller] = false;
}
}
}
/*============================================================================
ISR(ADC0_RESRDY_vect)
------------------------------------------------------------------------------
Purpose: ADC EOC Interrupt - Call PTC handler or application
Input : none
Output : none
Notes : none
============================================================================*/
void ADC0_1_Handler(void)
{
CRITICAL_SECTION_ENTER()
ADC0->INTFLAG.reg |= 1U;
qtm_samd51_ptc_handler();
CRITICAL_SECTION_LEAVE()
}
#endif /* TOUCH_C */
<|start_filename|>src/apps/btc/btc_sign_validate.c<|end_filename|>
// Copyright 2020 Shift Crypto AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "btc_sign_validate.h"
#include "btc_common.h"
#include "btc_params.h"
#include "confirm_multisig.h"
#include <memory/memory.h>
app_btc_result_t app_btc_sign_validate_init_script_configs(
BTCCoin coin,
const BTCScriptConfigWithKeypath* script_configs,
size_t script_configs_count)
{
const app_btc_coin_params_t* coin_params = app_btc_params_get(coin);
if (coin_params == NULL) {
return APP_BTC_ERR_INVALID_INPUT;
}
if (script_configs_count == 0) {
return APP_BTC_ERR_INVALID_INPUT;
}
// If there are multiple script configs, only SimpleType (single sig, no additional inputs)
// configs are allowed, so e.g. mixing p2wpkh and pw2wpkh-p2sh is okay, but mixing p2wpkh with
// multisig-pw2sh is not.
// We get multisig out of the way first.
bool is_multisig = script_configs_count == 1 &&
script_configs[0].script_config.which_config == BTCScriptConfig_multisig_tag;
if (is_multisig) {
const BTCScriptConfigWithKeypath* script_config = &script_configs[0];
const BTCScriptConfig_Multisig* multisig = &script_config->script_config.config.multisig;
if (!btc_common_multisig_is_valid(
multisig,
script_config->keypath,
script_config->keypath_count,
coin_params->bip44_coin)) {
return APP_BTC_ERR_INVALID_INPUT;
}
char multisig_registered_name[MEMORY_MULTISIG_NAME_MAX_LEN] = {0};
if (!btc_common_multisig_name(
coin,
multisig,
script_config->keypath,
script_config->keypath_count,
multisig_registered_name)) {
// Not previously registered -> fail.
return APP_BTC_ERR_INVALID_INPUT;
}
if (!apps_btc_confirm_multisig_basic(
"Spend from", coin_params, multisig_registered_name, multisig)) {
return APP_BTC_ERR_USER_ABORT;
}
return APP_BTC_OK;
}
for (size_t i = 0; i < script_configs_count; i++) {
const BTCScriptConfigWithKeypath* script_config = &script_configs[i];
// Only allow simple single sig configs here.
if (script_config->script_config.which_config != BTCScriptConfig_simple_type_tag) {
return APP_BTC_ERR_INVALID_INPUT;
}
if (!btc_common_is_valid_keypath_account_simple(
script_config->script_config.config.simple_type,
script_config->keypath,
script_config->keypath_count,
coin_params->bip44_coin)) {
return APP_BTC_ERR_INVALID_INPUT;
}
// Check that the bip44 account is the same for all. While we allow mixing input types
// (bip44 purpose), we do not allow mixing accounts.
if (script_config->keypath[2] != script_configs[0].keypath[2]) {
return APP_BTC_ERR_INVALID_INPUT;
}
}
return APP_BTC_OK;
}
<|start_filename|>src/hardfault.h<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _HARDFAULT_H_
#define _HARDFAULT_H_
#ifdef TESTING
#include <stdio.h>
void Dummy_Handler(void);
void HardFault_Handler(void) __attribute__((weak));
#endif
// Abort is for manual calls to stop execution, providing a message for
// debugging.
__attribute__((noreturn)) void Abort(const char* msg);
// Abort is for manual calls to stop execution, providing a message for debugging. It also sets
// autoenter to true, making sure that the device boots into the bootloader after reconnecting it.
// This should be called for any Abort during firmware startup, so a firmware update can be
// applied. Otherwise, if there is an Abort() during startup, there would no way to reboot into the
// bootloader and the device would be bricked.
__attribute__((noreturn)) void AbortAutoenter(const char* msg);
#endif
<|start_filename|>src/apps/eth/eth_sighash.c<|end_filename|>
#include "eth_sighash.h"
#include <hardfault.h>
#include <util.h>
#include <rust/rust.h>
// https://github.com/ethereum/wiki/wiki/RLP
// If ctx is NULL, we skip the hashing.
// If encoded_len_out is NULL, we skip counting the bytes.
// If encoded_len_out is not NULL, we add to it, so it has to be initialized to 0 before the first
// call.
static void _hash_header(
void* ctx,
uint8_t small_tag,
uint8_t large_tag,
pb_size_t len,
uint32_t* encoded_len_out)
{
if (sizeof(len) != 2) {
Abort("_hash_header: unexpected size");
}
// According to the RLP spec., buffer headers are encoded differently for lengths below and
// above 55 (for >55, length of length is encoded).
if (len <= 55) {
if (ctx != NULL) {
uint8_t byte = small_tag + len;
rust_keccak256_update(ctx, &byte, 1);
}
if (encoded_len_out != NULL) {
*encoded_len_out += 1;
}
} else if (len <= 0xff) {
if (ctx != NULL) {
uint8_t encoding[2] = {large_tag + 1, len};
rust_keccak256_update(ctx, encoding, sizeof(encoding));
}
if (encoded_len_out != NULL) {
*encoded_len_out += 2;
}
} else {
if (ctx != NULL) {
uint8_t byte = large_tag + 2;
rust_keccak256_update(ctx, &byte, 1);
// big endian serialization of 2-bytes `len`.
rust_keccak256_update(ctx, (const uint8_t*)&len + 1, 1);
rust_keccak256_update(ctx, (const uint8_t*)&len, 1);
}
if (encoded_len_out != NULL) {
*encoded_len_out += 3;
}
}
}
// https://github.com/ethereum/wiki/wiki/RLP
// If ctx is NULL, we skip the hashing.
// If encoded_len_out is NULL, we skip counting the bytes.
// If encoded_len_out is not NULL, we add to it, so it has to be initialized to 0 before the first
// call.
static void _hash_element(void* ctx, const uint8_t* bytes, pb_size_t len, uint32_t* encoded_len_out)
{
if (sizeof(len) != 2) {
Abort("_hash_element: unexpected size");
}
// hash header
if (len != 1 || bytes[0] > 0x7f) {
_hash_header(ctx, 0x80, 0xb7, len, encoded_len_out);
}
if (ctx != NULL) {
// hash bytes
rust_keccak256_update(ctx, bytes, len);
}
if (encoded_len_out != NULL) {
*encoded_len_out += len;
}
}
bool app_eth_sighash(eth_sighash_params_t params, uint8_t* sighash_out)
{
// We hash [nonce, gas price, gas limit, recipient, value, data], RLP encoded.
// The list length prefix is (0xc0 + length of the encoding of all elements).
// 1) calculate length
uint32_t encoded_length = 0;
_hash_element(NULL, params.nonce.data, params.nonce.len, &encoded_length);
_hash_element(NULL, params.gas_price.data, params.gas_price.len, &encoded_length);
_hash_element(NULL, params.gas_limit.data, params.gas_limit.len, &encoded_length);
_hash_element(NULL, params.recipient.data, params.recipient.len, &encoded_length);
_hash_element(NULL, params.value.data, params.value.len, &encoded_length);
_hash_element(NULL, params.data.data, params.data.len, &encoded_length);
encoded_length += 3; // EIP155 part, see below.
if (encoded_length > 0xffff) {
// Don't support bigger than this for now.
return false;
}
// 2) hash len and encoded tx elements
void* ctx = rust_keccak256_new();
_hash_header(ctx, 0xc0, 0xf7, (pb_size_t)encoded_length, NULL);
_hash_element(ctx, params.nonce.data, params.nonce.len, NULL);
_hash_element(ctx, params.gas_price.data, params.gas_price.len, NULL);
_hash_element(ctx, params.gas_limit.data, params.gas_limit.len, NULL);
_hash_element(ctx, params.recipient.data, params.recipient.len, NULL);
_hash_element(ctx, params.value.data, params.value.len, NULL);
_hash_element(ctx, params.data.data, params.data.len, NULL);
{ // EIP155
if (params.chain_id == 0 || params.chain_id > 0x7f) {
Abort("chain id encoding error");
}
// encodes <chainID><0><0>
uint8_t eip155_part[3] = {params.chain_id, 0x80, 0x80};
rust_keccak256_update(ctx, eip155_part, sizeof(eip155_part));
}
rust_keccak256_finish(&ctx, sighash_out);
return true;
}
<|start_filename|>src/workflow/workflow.h<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _WORKFLOW_H_
#define _WORKFLOW_H_
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <compiler_util.h>
/**
* Typedef for a callback to be executed when a workflow is finishing.
* This can be used by the parent workflow to obtain information about
* the executed workflow's result.
*/
typedef void (*workflow_cb_t)(void*);
/**
* Descriptor for a workflow to be run.
*/
typedef struct _workflow_t {
/* Starts the workflow */
void (*init)(struct _workflow_t*);
/* Stops the workflow and destroys the related resources. */
void (*cleanup)(struct _workflow_t*);
/* Private data (depends on the workflow type) */
void* data;
/* Size of the allocated data. */
size_t data_size;
/* Function to get run at every cycle */
void (*spin)(struct _workflow_t*);
} workflow_t;
#endif
<|start_filename|>src/apps/btc/btc_common.c<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdio.h>
#include <stdlib.h>
#include "btc_common.h"
#include <apps/common/bip32.h>
#include <hardfault.h>
#include <keystore.h>
#include <memory/memory.h>
#include <rust/rust.h>
#include <util.h>
#include <wally_address.h>
#define MULTISIG_P2WSH_MAX_SIGNERS 15
bool btc_common_is_valid_keypath_account_simple(
BTCScriptConfig_SimpleType script_type,
const uint32_t* keypath,
const size_t keypath_len,
const uint32_t expected_coin)
{
return rust_bitcoin_keypath_validate_account_simple(
keypath, keypath_len, expected_coin, script_type);
}
bool btc_common_is_valid_keypath_address_simple(
BTCScriptConfig_SimpleType script_type,
const uint32_t* keypath,
const size_t keypath_len,
const uint32_t expected_coin)
{
return rust_bitcoin_keypath_validate_address_simple(
keypath, keypath_len, expected_coin, script_type);
}
bool btc_common_is_valid_keypath_address_multisig(
BTCScriptConfig_Multisig_ScriptType script_type,
const uint32_t* keypath,
const size_t keypath_len,
const uint32_t expected_coin)
{
return rust_bitcoin_keypath_validate_address_multisig(
keypath, keypath_len, expected_coin, script_type);
}
bool btc_common_outputhash_from_pubkeyhash(
BTCScriptConfig_SimpleType script_type,
const uint8_t* pubkey_hash,
uint8_t* output_hash,
size_t* output_hash_size)
{
switch (script_type) {
case BTCScriptConfig_SimpleType_P2WPKH:
memcpy(output_hash, pubkey_hash, HASH160_LEN);
*output_hash_size = HASH160_LEN;
break;
case BTCScriptConfig_SimpleType_P2WPKH_P2SH: {
uint8_t script[WALLY_SCRIPTPUBKEY_P2WPKH_LEN] = {0};
size_t written = 0;
if (wally_witness_program_from_bytes(
pubkey_hash, HASH160_LEN, 0, script, sizeof(script), &written) != WALLY_OK) {
return false;
}
if (written != WALLY_SCRIPTPUBKEY_P2WPKH_LEN) {
return false;
}
if (wally_hash160(script, sizeof(script), output_hash, HASH160_LEN) != WALLY_OK) {
return false;
}
*output_hash_size = HASH160_LEN;
break;
}
default:
return false;
}
return true;
}
bool btc_common_sighash_script_from_pubkeyhash(
BTCScriptConfig_SimpleType script_type,
const uint8_t* pubkey_hash,
uint8_t* script,
size_t* script_size)
{
size_t size_in = *script_size;
switch (script_type) {
case BTCScriptConfig_SimpleType_P2WPKH_P2SH:
case BTCScriptConfig_SimpleType_P2WPKH:
script[0] = 0x19; // 25 byte data push
if (wally_scriptpubkey_p2pkh_from_bytes(
pubkey_hash, HASH160_LEN, 0, script + 1, size_in - 1, script_size) != WALLY_OK) {
return false;
}
*script_size = *script_size + 1;
return true;
default:
return false;
}
}
BTCOutputType btc_common_determine_output_type(BTCScriptConfig_SimpleType script_type)
{
switch (script_type) {
case BTCScriptConfig_SimpleType_P2WPKH_P2SH:
return BTCOutputType_P2SH;
case BTCScriptConfig_SimpleType_P2WPKH:
return BTCOutputType_P2WPKH;
default:
return BTCOutputType_UNKNOWN;
}
}
BTCOutputType btc_common_determine_output_type_multisig(const BTCScriptConfig_Multisig* multisig)
{
switch (multisig->script_type) {
case BTCScriptConfig_Multisig_ScriptType_P2WSH:
return BTCOutputType_P2WSH;
case BTCScriptConfig_Multisig_ScriptType_P2WSH_P2SH:
return BTCOutputType_P2SH;
default:
return BTCOutputType_UNKNOWN;
}
}
/**
* @param[in] version base58 check version, e.g. 0x05 for the "3" prefix.
* @param[in] hash hash160 hash of pubkey or script, to bebase58Check encoded.
* @param[out] out will contain the resulting address.
* @param[in] out_len size allocation of `out`.
* @return true on success, false on failure.
*/
static bool _encode_base58_address(uint8_t version, const uint8_t* hash, char* out, size_t out_len)
{
uint8_t vhash[1 + HASH160_LEN] = {0};
vhash[0] = version;
memcpy(vhash + 1, hash, HASH160_LEN);
char* address_string = NULL;
if (wally_base58_from_bytes(vhash, sizeof(vhash), BASE58_FLAG_CHECKSUM, &address_string) !=
WALLY_OK) {
return false;
}
int sprintf_result = snprintf(out, out_len, "%s", address_string);
wally_free_string(address_string);
return sprintf_result >= 0 && sprintf_result < (int)out_len;
}
bool btc_common_address_from_outputhash(
const app_btc_coin_params_t* params,
BTCOutputType output_type,
const uint8_t* hash,
size_t hash_size,
char* out,
size_t out_len)
{
switch (output_type) {
case BTCOutputType_P2PKH:
if (hash_size != HASH160_LEN) {
return false;
}
return _encode_base58_address(params->base58_version_p2pkh, hash, out, out_len);
case BTCOutputType_P2SH:
if (hash_size != HASH160_LEN) {
return false;
}
return _encode_base58_address(params->base58_version_p2sh, hash, out, out_len);
case BTCOutputType_P2WPKH:
case BTCOutputType_P2WSH: {
uint8_t script[WALLY_SCRIPTPUBKEY_P2WSH_LEN] = {0};
size_t written = 0;
if (wally_witness_program_from_bytes(
hash, hash_size, 0, script, sizeof(script), &written) != WALLY_OK) {
return false;
}
char* address_string = NULL;
if (wally_addr_segwit_from_bytes(script, written, params->bech32_hrp, 0, &address_string) !=
WALLY_OK) {
return false;
}
int sprintf_result = snprintf(out, out_len, "%s", address_string);
wally_free_string(address_string);
return sprintf_result >= 0 && sprintf_result < (int)out_len;
}
default:
return false;
}
return true;
}
bool btc_common_pkscript_from_outputhash(
BTCOutputType output_type,
const uint8_t* hash,
size_t hash_size,
uint8_t* pk_script,
size_t* pk_script_len)
{
if (!hash || !pk_script || !pk_script_len) {
return false;
}
size_t len = *pk_script_len;
switch (output_type) {
case BTCOutputType_P2PKH:
if (hash_size != HASH160_LEN) {
return false;
}
return wally_scriptpubkey_p2pkh_from_bytes(
hash, hash_size, 0, pk_script, len, pk_script_len) == WALLY_OK;
case BTCOutputType_P2SH:
if (hash_size != HASH160_LEN) {
return false;
}
return wally_scriptpubkey_p2sh_from_bytes(
hash, hash_size, 0, pk_script, len, pk_script_len) == WALLY_OK;
case BTCOutputType_P2WPKH:
case BTCOutputType_P2WSH:
return wally_witness_program_from_bytes(
hash, hash_size, 0, pk_script, len, pk_script_len) == WALLY_OK;
default:
return false;
}
return true;
}
bool btc_common_pkscript_from_multisig(
const BTCScriptConfig_Multisig* multisig,
uint32_t keypath_change,
uint32_t keypath_address,
uint8_t* script_out,
size_t* script_out_size)
{
uint8_t pubkeys[MULTISIG_P2WSH_MAX_SIGNERS * EC_PUBLIC_KEY_LEN];
for (size_t index = 0; index < multisig->xpubs_count; index++) {
const XPub* xpub_in = &multisig->xpubs[index];
struct ext_key xpub = {0};
if (!apps_common_bip32_xpub_from_protobuf(xpub_in, &xpub)) {
return false;
}
struct ext_key derived_cosigner_xpub = {0};
const uint32_t keypath[2] = {keypath_change, keypath_address};
if (bip32_key_from_parent_path(
&xpub, keypath, 2, BIP32_FLAG_KEY_PUBLIC, &derived_cosigner_xpub) != WALLY_OK) {
return false;
}
memcpy(
&pubkeys[index * EC_PUBLIC_KEY_LEN], derived_cosigner_xpub.pub_key, EC_PUBLIC_KEY_LEN);
}
size_t written;
if (wally_scriptpubkey_multisig_from_bytes(
pubkeys,
multisig->xpubs_count * EC_PUBLIC_KEY_LEN,
multisig->threshold,
WALLY_SCRIPT_MULTISIG_SORTED,
script_out,
*script_out_size,
&written) != WALLY_OK) {
return false;
}
if (written > *script_out_size) {
// Double check since the function above sets written to script_len if the buffer was too
// short.
return false;
}
*script_out_size = written;
return true;
}
bool btc_common_outputhash_from_multisig(
const BTCScriptConfig_Multisig* multisig,
uint32_t keypath_change,
uint32_t keypath_address,
uint8_t* output_hash,
size_t* output_hash_size)
{
uint8_t script[700] = {0};
size_t written = sizeof(script);
if (!btc_common_pkscript_from_multisig(
multisig, keypath_change, keypath_address, script, &written)) {
return false;
}
// TODO: double check that the witness script must be <= 10,000 bytes /
// 201 opCounts (consensus rule), resp. 3,600 bytes (standardness rule).
// See https://bitcoincore.org/en/segwit_wallet_dev/.
// Note that the witness script has an additional varint prefix.
switch (multisig->script_type) {
case BTCScriptConfig_Multisig_ScriptType_P2WSH:
*output_hash_size = SHA256_LEN;
return wally_sha256(script, written, output_hash, SHA256_LEN) == WALLY_OK;
case BTCScriptConfig_Multisig_ScriptType_P2WSH_P2SH: {
// script_sha256 contains the hash of the multisig redeem script as used in a P2WSH output.
uint8_t script_sha256[SHA256_LEN] = {0};
if (wally_sha256(script, written, script_sha256, sizeof(script_sha256)) != WALLY_OK) {
return false;
}
// create the p2wsh output.
uint8_t p2wsh_pkscript[WALLY_SCRIPTPUBKEY_P2WSH_LEN] = {0};
if (wally_witness_program_from_bytes(
script_sha256,
sizeof(script_sha256),
0,
p2wsh_pkscript,
sizeof(p2wsh_pkscript),
&written) != WALLY_OK) {
return false;
}
// hash the output script according to p2sh.
*output_hash_size = HASH160_LEN;
return wally_hash160(p2wsh_pkscript, written, output_hash, HASH160_LEN) == WALLY_OK;
}
default:
return false;
};
}
USE_RESULT bool btc_common_multisig_is_valid(
const BTCScriptConfig_Multisig* multisig,
const uint32_t* keypath,
size_t keypath_len,
uint32_t expected_coin)
{
if (multisig->xpubs_count < 2 || multisig->xpubs_count > MULTISIG_P2WSH_MAX_SIGNERS) {
return false;
}
if (multisig->threshold == 0 || multisig->threshold > multisig->xpubs_count) {
return false;
}
if (multisig->our_xpub_index >= multisig->xpubs_count) {
return false;
}
if (!rust_bitcoin_keypath_validate_account_multisig(
keypath, keypath_len, expected_coin, multisig->script_type)) {
return false;
}
struct ext_key our_xpub __attribute__((__cleanup__(keystore_zero_xkey))) = {0};
if (!keystore_get_xpub(keypath, keypath_len, &our_xpub)) {
return false;
}
const XPub* maybe_our_xpub_in = &multisig->xpubs[multisig->our_xpub_index];
struct ext_key maybe_our_xpub = {0};
if (!apps_common_bip32_xpub_from_protobuf(maybe_our_xpub_in, &maybe_our_xpub)) {
return false;
}
if (!apps_common_bip32_xpubs_equal(&our_xpub, &maybe_our_xpub)) {
return false;
}
// Check for duplicates.
for (size_t i = 0; i < multisig->xpubs_count; i++) {
struct ext_key xpub_i = {0};
if (!apps_common_bip32_xpub_from_protobuf(&multisig->xpubs[i], &xpub_i)) {
return false;
}
for (size_t j = i + 1; j < multisig->xpubs_count; j++) {
struct ext_key xpub_j = {0};
if (!apps_common_bip32_xpub_from_protobuf(&multisig->xpubs[j], &xpub_j)) {
return false;
}
if (apps_common_bip32_xpubs_equal(&xpub_i, &xpub_j)) {
return false;
}
}
}
return true;
}
// serialized_out must be of size BIP32_SERIALIZED_LEN.
static bool _serialize_xpub(const XPub* xpub, uint8_t* serialized_out)
{
struct ext_key wally_xpub __attribute__((__cleanup__(keystore_zero_xkey))) = {0};
if (!apps_common_bip32_xpub_from_protobuf(xpub, &wally_xpub)) {
return false;
}
return bip32_key_serialize(
&wally_xpub, BIP32_FLAG_KEY_PUBLIC, serialized_out, BIP32_SERIALIZED_LEN) ==
WALLY_OK;
}
static int _xpubs_sort_comp(const void* elem1, const void* elem2)
{
const uint8_t* xpub1 = (const uint8_t*)elem1;
const uint8_t* xpub2 = (const uint8_t*)elem2;
// Sort by xpub serialization, ignoring the version bytes.
return memcmp(xpub1 + 4, xpub2 + 4, BIP32_SERIALIZED_LEN - 4);
}
static bool _multisig_hash(
BTCCoin coin,
const BTCScriptConfig_Multisig* multisig,
bool sort_xpubs,
const uint32_t* keypath,
size_t keypath_len,
uint8_t* hash_out)
{
void* ctx __attribute__((__cleanup__(rust_sha256_free))) = rust_sha256_new();
{ // 1. coin
uint8_t byte;
switch (coin) {
case BTCCoin_BTC:
byte = 0x00;
break;
case BTCCoin_TBTC:
byte = 0x01;
break;
case BTCCoin_LTC:
byte = 0x02;
break;
case BTCCoin_TLTC:
byte = 0x03;
break;
default:
return false;
}
rust_sha256_update(ctx, &byte, 1);
}
{ // 2. script config type
uint8_t byte;
switch (multisig->script_type) {
case BTCScriptConfig_Multisig_ScriptType_P2WSH:
byte = 0x00;
break;
case BTCScriptConfig_Multisig_ScriptType_P2WSH_P2SH:
byte = 0x01;
break;
default:
return false;
}
rust_sha256_update(ctx, &byte, 1);
}
{ // 3. threshold
// assumes little endian environment
rust_sha256_update(ctx, &multisig->threshold, sizeof(multisig->threshold));
}
{ // 4. num xpubs
uint32_t num = multisig->xpubs_count; // cast to fixed size
// assumes little endian environment
rust_sha256_update(ctx, &num, sizeof(num));
}
{ // 5. xpubs
uint8_t xpubs_serialized[sizeof(multisig->xpubs) / sizeof(*multisig->xpubs)]
[BIP32_SERIALIZED_LEN] = {0};
for (size_t i = 0; i < multisig->xpubs_count; i++) {
if (!_serialize_xpub(&multisig->xpubs[i], xpubs_serialized[i])) {
return false;
}
}
if (sort_xpubs) {
qsort(
xpubs_serialized,
multisig->xpubs_count,
sizeof(*xpubs_serialized),
_xpubs_sort_comp);
}
for (size_t i = 0; i < multisig->xpubs_count; i++) {
// Drop the first xpub version, which are the 4 first bytes. They are determined by the
// above `BIP32_FLAG_KEY_PUBLIC` flag and do not add anything, as the xpub version is
// chosen ad-hoc depending on the context it is used in.
rust_sha256_update(ctx, xpubs_serialized[i] + 4, BIP32_SERIALIZED_LEN - 4);
}
}
{ // 6. keypath len
uint32_t len = keypath_len; // cast to fixed size
rust_sha256_update(ctx, &len, sizeof(len));
}
{ // 7. keypath
for (size_t i = 0; i < keypath_len; i++) {
rust_sha256_update(ctx, &keypath[i], sizeof(keypath[i]));
}
}
rust_sha256_finish(&ctx, hash_out);
return true;
}
bool btc_common_multisig_hash_unsorted(
BTCCoin coin,
const BTCScriptConfig_Multisig* multisig,
const uint32_t* keypath,
size_t keypath_len,
uint8_t* hash_out)
{
return _multisig_hash(coin, multisig, false, keypath, keypath_len, hash_out);
}
bool btc_common_multisig_hash_sorted(
BTCCoin coin,
const BTCScriptConfig_Multisig* multisig,
const uint32_t* keypath,
size_t keypath_len,
uint8_t* hash_out)
{
return _multisig_hash(coin, multisig, true, keypath, keypath_len, hash_out);
}
bool btc_common_multisig_name(
BTCCoin coin,
const BTCScriptConfig_Multisig* multisig,
const uint32_t* keypath,
size_t keypath_len,
char* name_out)
{
uint8_t hash[SHA256_LEN] = {0};
// First try using sorted xpubs (the default registration since v9.3.0).
if (!btc_common_multisig_hash_sorted(coin, multisig, keypath, keypath_len, hash)) {
return false;
}
if (memory_multisig_get_by_hash(hash, name_out)) {
return true;
}
// If that did not exist, try with unsorted xpubs for backwards compatibility.
if (!btc_common_multisig_hash_unsorted(coin, multisig, keypath, keypath_len, hash)) {
return false;
}
return memory_multisig_get_by_hash(hash, name_out);
}
<|start_filename|>src/ui/components/ui_images.h<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _UI_IMAGES_H_
#define _UI_IMAGES_H_
#include <platform/platform_config.h>
#include <stdbool.h>
#include <stdint.h>
#if PRODUCT_BITBOX_BTCONLY == 1
#define IMAGE_BB2_LOGO_W 79
#define IMAGE_BB2_LOGO_H 25
static const uint8_t IMAGE_BB2_LOGO[] = {
0xfe, 0x0c, 0x30, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x18, 0x60, 0xff, 0x00, 0x00,
0x00, 0x07, 0x80, 0xf3, 0x06, 0x00, 0xc1, 0x83, 0x00, 0x00, 0x00, 0x10, 0x82, 0x16, 0x0c, 0x67,
0xe3, 0x06, 0x0f, 0x87, 0x1c, 0x21, 0x08, 0x1c, 0x18, 0xcf, 0xc6, 0x0c, 0x3f, 0x86, 0x30, 0x81,
0x00, 0x3f, 0xe1, 0x86, 0x0f, 0xf0, 0x63, 0x06, 0xc1, 0x02, 0x00, 0x7f, 0xc3, 0x0c, 0x1f, 0xe1,
0x83, 0x0f, 0x82, 0x04, 0x01, 0x60, 0xc6, 0x18, 0x30, 0x63, 0x06, 0x0e, 0x04, 0x08, 0x0c, 0xc1,
0x8c, 0x30, 0x60, 0xc6, 0x0c, 0x1c, 0x08, 0x10, 0x61, 0x83, 0x18, 0x60, 0xc1, 0x8c, 0x18, 0x7c,
0x10, 0x21, 0x03, 0x06, 0x30, 0xc1, 0x83, 0x0c, 0x60, 0xd8, 0x10, 0x84, 0x07, 0xf8, 0x61, 0xe3,
0xfc, 0x1f, 0xc3, 0x18, 0x21, 0x08, 0x0f, 0xe0, 0xc1, 0xc7, 0xf0, 0x1f, 0x0e, 0x38, 0x3c, 0x1f,
0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe4, 0x00,
0x04, 0x00, 0x00, 0x20, 0x00, 0x0a, 0x08, 0x01, 0x21, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x10,
0x80, 0x02, 0x57, 0x31, 0x97, 0x01, 0x9c, 0xa2, 0x18, 0xeb, 0xa6, 0x77, 0xa4, 0x94, 0xa9, 0x04,
0xa5, 0x44, 0x4a, 0x52, 0x52, 0x99, 0x49, 0x09, 0x52, 0xe9, 0x4a, 0x50, 0xf4, 0xa4, 0xa5, 0x32,
0x92, 0x52, 0xa4, 0x12, 0x94, 0xa1, 0x09, 0x49, 0x4a, 0x79, 0x23, 0x19, 0x48, 0x19, 0x28, 0x81,
0xce, 0x92, 0x64, 0x80, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00};
#elif (PRODUCT_BITBOX_MULTI == 1) || PRODUCT_BITBOX02_FACTORYSETUP == 1
#define IMAGE_BB2_LOGO_W 79
#define IMAGE_BB2_LOGO_H 23
static const uint8_t IMAGE_BB2_LOGO[] = {
0xfe, 0x0c, 0x30, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x18, 0x60, 0xff, 0x00, 0x00,
0x00, 0x07, 0x80, 0xf3, 0x06, 0x00, 0xc1, 0x83, 0x00, 0x00, 0x00, 0x10, 0x82, 0x16, 0x0c, 0x67,
0xe3, 0x06, 0x0f, 0x87, 0x1c, 0x21, 0x08, 0x1c, 0x18, 0xcf, 0xc6, 0x0c, 0x3f, 0x86, 0x30, 0x81,
0x00, 0x3f, 0xe1, 0x86, 0x0f, 0xf0, 0x63, 0x06, 0xc1, 0x02, 0x00, 0x7f, 0xc3, 0x0c, 0x1f, 0xe1,
0x83, 0x0f, 0x82, 0x04, 0x01, 0x60, 0xc6, 0x18, 0x30, 0x63, 0x06, 0x0e, 0x04, 0x08, 0x0c, 0xc1,
0x8c, 0x30, 0x60, 0xc6, 0x0c, 0x1c, 0x08, 0x10, 0x61, 0x83, 0x18, 0x60, 0xc1, 0x8c, 0x18, 0x7c,
0x10, 0x21, 0x03, 0x06, 0x30, 0xc1, 0x83, 0x0c, 0x60, 0xd8, 0x10, 0x84, 0x07, 0xf8, 0x61, 0xe3,
0xfc, 0x1f, 0xc3, 0x18, 0x21, 0x08, 0x0f, 0xe0, 0xc1, 0xc7, 0xf0, 0x1f, 0x0e, 0x38, 0x3c, 0x1f,
0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x82, 0x04,
0x10, 0x00, 0xa0, 0x80, 0x00, 0x00, 0x00, 0x01, 0x8c, 0x09, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00,
0x00, 0x02, 0xaa, 0x57, 0x41, 0x8e, 0xba, 0x67, 0x00, 0x00, 0x00, 0x05, 0x54, 0xa4, 0x84, 0xa5,
0x25, 0x29, 0x00, 0x00, 0x00, 0x09, 0x29, 0x49, 0x0f, 0x4a, 0x4a, 0x52, 0x00, 0x00, 0x00, 0x12,
0x52, 0x92, 0x10, 0x94, 0x94, 0xa4, 0x00, 0x00, 0x00, 0x20, 0x99, 0x24, 0x1c, 0xe9, 0x26, 0x48,
0x00, 0x00, 0x00, 0x00};
#else
#error "Invalid product"
#endif
#define IMAGE_ROTATE_W 22
#define IMAGE_ROTATE_H 14
static const uint8_t IMAGE_ROTATE[] = {0x00, 0x60, 0x00, 0x06, 0x00, 0x00, 0x20, 0x04, 0x01, 0x00,
0x38, 0x04, 0x01, 0xf0, 0x20, 0x0f, 0xe0, 0x80, 0x7f, 0xc2,
0x00, 0x10, 0x08, 0x00, 0x40, 0x10, 0x02, 0x00, 0x40, 0x08,
0x00, 0x80, 0x40, 0x01, 0x86, 0x00, 0x01, 0xe0, 0x00};
static const uint8_t IMAGE_ROTATE_REVERSE[] = {
0x00, 0x78, 0x00, 0x06, 0x18, 0x00, 0x20, 0x10, 0x01, 0x00, 0x20, 0x04, 0x00,
0x80, 0x20, 0x01, 0x00, 0x80, 0x04, 0x3f, 0xe0, 0x10, 0x7f, 0x00, 0x40, 0xf8,
0x02, 0x01, 0xc0, 0x08, 0x02, 0x00, 0x40, 0x00, 0x06, 0x00, 0x00, 0x60, 0x00};
#define IMAGE_DEFAULT_ARROW_HEIGHT 6
#define IMAGE_DEFAULT_CHECKMARK_HEIGHT 7
#define IMAGE_DEFAULT_CROSS_HEIGHT 6
#define IMAGE_DEFAULT_LOCK_RADIUS 6
typedef enum {
ARROW_RIGHT,
ARROW_LEFT,
ARROW_UP,
ARROW_DOWN,
} arrow_orientation_t;
void image_arrow(int x, int y, int height, arrow_orientation_t orientation);
void image_arrow_hollow(int x, int y, int height, arrow_orientation_t orientation);
void image_checkmark(int x, int y, int h);
void image_cross(int x, int y, int h);
void image_lock(int x, int y, int r);
void image_unlock(int x, int y, int r);
void image_sdcard(bool mirror);
#define IMAGE_SCREENSAVER_W 17
#define IMAGE_SCREENSAVER_H 20
static const uint8_t IMAGE_SCREENSAVER[] = {
0x01, 0x40, 0x01, 0xb0, 0x01, 0xdc, 0x01, 0xef, 0x00, 0xf7, 0x80, 0x7b, 0xc0, 0x3d, 0xe0,
0x1e, 0xf0, 0x0f, 0x78, 0x0f, 0xbe, 0x1f, 0xdf, 0xdf, 0xc7, 0xff, 0xc1, 0xff, 0x84, 0x3e,
0x0f, 0x82, 0x1f, 0xf0, 0x3f, 0xfe, 0x0f, 0xfe, 0x01, 0xfc, 0x00, 0x38, 0x00};
#endif
<|start_filename|>src/memory/bitbox02_smarteeprom.c<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "bitbox02_smarteeprom.h"
#include "hardfault.h"
#include "memory/mpu.h"
#include "memory/smarteeprom.h"
#include <stddef.h>
#include <stdio.h>
#include <string.h>
/**
* Current version of the data stored in SmartEEPROM.
*/
#define BITBOX02_SMARTEEPROM_DATA_VERSION (1)
#define BITBOX02_SMARTEEPROM_UNINITIALIZED_VERSION (0xFF)
/**
* Contents of the SmartEEPROM, as stored in the BitBox02.
* Version 1.
*
* Each field is stored in a separate SmartEEPROM page (32B) to help
* maximizing the lifetime of the device.
* The version is fixed at virtual address zero for every possible
* future structure (see _get_data_version).
*
* See smarteeprom_setup() for a description of how the SmartEEPROM
* is configured.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpacked"
typedef struct __attribute__((__packed__)) {
/** == 1 */
uint8_t version;
uint8_t padding[SMARTEEPROM_PAGE_SIZE - sizeof(uint8_t)];
/** Number of unlock attempts since last successful unlock. */
uint8_t unlock_attempts;
uint8_t padding_2[SMARTEEPROM_PAGE_SIZE - sizeof(uint8_t)];
} bitbox02_smarteeprom_image_v1_t;
#pragma GCC diagnostic pop
/**
* Reads the version field at address zero.
*
* The offset (in memory) of the version needs to stay out
* of the data structure. Otherwise, we need to know the version
* of the struct we're going to use in order to know the location
* of the version field... Which loses the point of the field itself.
*/
static uint8_t _get_data_version(void)
{
uint8_t result;
smarteeprom_read(0, sizeof(result), &result);
return result;
}
/**
* Reads the version field at address zero.
*/
static void _set_data_version(uint8_t new_version)
{
smarteeprom_write(0, sizeof(new_version), &new_version);
}
static void _init_v1(void)
{
bitbox02_smarteeprom_image_v1_t new_image;
smarteeprom_read(0, sizeof(new_image), (uint8_t*)&new_image);
/*
* Note that this forcefully resets the unlock counter
* the first and only time the device is upgraded.
* Not too bad...
*/
new_image.unlock_attempts = 0;
smarteeprom_write(0, sizeof(new_image), (uint8_t*)&new_image);
_set_data_version(0x01);
}
void bitbox02_smarteeprom_init(void)
{
uint8_t current_version = _get_data_version();
if (current_version == BITBOX02_SMARTEEPROM_DATA_VERSION) {
return;
}
/*
* Migrate from old versions.
* FUTURE: if the data structures are changed, add here the code
* to migrate from each version.
*/
if (current_version == BITBOX02_SMARTEEPROM_UNINITIALIZED_VERSION) {
_init_v1();
} else {
/*
* Incorrect version!
* Something has gone terribly wrong.
* Maybe reset the whole device?
*/
char msg[200] = {0};
snprintf(msg, sizeof(msg), "Unrecognized SmartEEPROM version.\nGot %d", current_version);
AbortAutoenter(msg);
}
}
uint8_t bitbox02_smarteeprom_get_unlock_attempts(void)
{
uint8_t result;
smarteeprom_read(
offsetof(bitbox02_smarteeprom_image_v1_t, unlock_attempts),
sizeof(((bitbox02_smarteeprom_image_v1_t*)0)->unlock_attempts),
&result);
/*
* Sanity-check the value.
*
* At no point this number should be allowed to go above MAX_UNLOCK_ATTEMPTS.
*/
if (result > MAX_UNLOCK_ATTEMPTS) {
Abort("#Unlock attempts increased past the maximum allowed value.");
}
return result;
}
void bitbox02_smarteeprom_increment_unlock_attempts(void)
{
uint8_t unlock_attempts = bitbox02_smarteeprom_get_unlock_attempts();
/*
* The number of attempts can never grow past the maximum.
* Catch an attempt to increment it past the maximum before we
* do the actual increment.
*/
if (unlock_attempts == MAX_UNLOCK_ATTEMPTS) {
Abort("Tried to increment the number of unlocks past the maximum allowed value.");
}
unlock_attempts++;
smarteeprom_write(
offsetof(bitbox02_smarteeprom_image_v1_t, unlock_attempts),
sizeof(unlock_attempts),
&unlock_attempts);
}
void bitbox02_smarteeprom_reset_unlock_attempts(void)
{
/* Sanity-check the current value */
(void)bitbox02_smarteeprom_get_unlock_attempts();
uint8_t w_unlock_attempts = 0;
smarteeprom_write(
offsetof(bitbox02_smarteeprom_image_v1_t, unlock_attempts),
sizeof(w_unlock_attempts),
&w_unlock_attempts);
}
<|start_filename|>src/apps/btc/confirm_multisig.c<|end_filename|>
// Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "confirm_multisig.h"
#include "btc_common.h"
#include <apps/common/bip32.h>
#include <hardfault.h>
#include <keystore.h>
#include <rust/rust.h>
#include <workflow/confirm.h>
#include <stdio.h>
bool apps_btc_confirm_multisig_basic(
const char* title,
const app_btc_coin_params_t* params,
const char* name,
const BTCScriptConfig_Multisig* multisig)
{
char basic_info[100] = {0};
int snprintf_result = snprintf(
basic_info,
sizeof(basic_info),
"%lu-of-%lu\n%s multisig",
(unsigned long)multisig->threshold,
(unsigned long)multisig->xpubs_count,
params->name);
if (snprintf_result < 0 || snprintf_result >= (int)sizeof(basic_info)) {
Abort("apps_btc_confirm_multisig/0");
}
const confirm_params_t params_basic = {
.title = title,
.body = basic_info,
.accept_is_nextarrow = true,
};
if (!workflow_confirm_blocking(¶ms_basic)) {
return false;
}
const confirm_params_t params_name = {
.title = title,
.body = name,
.scrollable = true,
.accept_is_nextarrow = true,
};
return workflow_confirm_blocking(¶ms_name);
}
bool apps_btc_confirm_multisig_extended(
const char* title,
const app_btc_coin_params_t* params,
const char* name,
const BTCScriptConfig_Multisig* multisig,
BTCRegisterScriptConfigRequest_XPubType xpub_type,
const uint32_t* keypath,
size_t keypath_len)
{
const char* script_type_string;
switch (multisig->script_type) {
case BTCScriptConfig_Multisig_ScriptType_P2WSH:
script_type_string = "p2wsh";
break;
case BTCScriptConfig_Multisig_ScriptType_P2WSH_P2SH:
script_type_string = "p2wsh-p2sh";
break;
default:
return false;
}
char keypath_string[100] = {0};
rust_bip32_to_string(
keypath, keypath_len, rust_util_cstr_mut(keypath_string, sizeof(keypath_string)));
if (!apps_btc_confirm_multisig_basic(title, params, name, multisig)) {
return false;
}
char info[200] = {0};
int snprintf_result =
snprintf(info, sizeof(info), "%s\nat\n%s", script_type_string, keypath_string);
if (snprintf_result < 0 || snprintf_result >= (int)sizeof(info)) {
Abort("apps_btc_confirm_multisig/0");
}
const confirm_params_t confirm_params = {
.title = title,
.body = info,
.accept_is_nextarrow = true,
};
if (!workflow_confirm_blocking(&confirm_params)) {
return false;
}
xpub_type_t output_xpub_type;
switch (xpub_type) {
case BTCRegisterScriptConfigRequest_XPubType_AUTO_ELECTRUM:
switch (params->coin) {
case BTCCoin_BTC:
case BTCCoin_LTC:
switch (multisig->script_type) {
case BTCScriptConfig_Multisig_ScriptType_P2WSH:
output_xpub_type = CAPITAL_ZPUB;
break;
case BTCScriptConfig_Multisig_ScriptType_P2WSH_P2SH:
output_xpub_type = CAPITAL_YPUB;
break;
default:
return false;
}
break;
case BTCCoin_TBTC:
case BTCCoin_TLTC:
switch (multisig->script_type) {
case BTCScriptConfig_Multisig_ScriptType_P2WSH:
output_xpub_type = CAPITAL_VPUB;
break;
case BTCScriptConfig_Multisig_ScriptType_P2WSH_P2SH:
output_xpub_type = CAPITAL_UPUB;
break;
default:
return false;
}
break;
default:
Abort("confirm multisig: unknown coin");
}
break;
case BTCRegisterScriptConfigRequest_XPubType_AUTO_XPUB_TPUB:
switch (params->coin) {
case BTCCoin_BTC:
case BTCCoin_LTC:
output_xpub_type = XPUB;
break;
case BTCCoin_TBTC:
case BTCCoin_TLTC:
output_xpub_type = TPUB;
break;
default:
Abort("confirm multisig: unknown coin");
}
break;
default:
Abort("confirm multisig: unknown xpub_type");
}
size_t num_cosigners = multisig->xpubs_count;
for (size_t i = 0; i < num_cosigners; i++) {
const XPub* xpub_in = &multisig->xpubs[i];
struct ext_key xpub = {0};
if (!apps_common_bip32_xpub_from_protobuf(xpub_in, &xpub)) {
return false;
}
char xpub_str[XPUB_ENCODED_LEN] = {0};
if (!keystore_encode_xpub(&xpub, output_xpub_type, xpub_str, sizeof(xpub_str))) {
return false;
}
char confirm[XPUB_ENCODED_LEN + 100] = {0};
if (i == multisig->our_xpub_index) {
int result = snprintf(
confirm,
sizeof(confirm),
"Cosigner %lu/%lu (this device): %s",
(unsigned long)(i + 1),
(unsigned long)num_cosigners,
xpub_str);
if (result < 0 || result >= (int)sizeof(confirm)) {
Abort("apps_btc_confirm_multisig/1");
}
} else {
int result = snprintf(
confirm,
sizeof(confirm),
"Cosigner %lu/%lu: %s",
(unsigned long)(i + 1),
(unsigned long)num_cosigners,
xpub_str);
if (result < 0 || result >= (int)sizeof(confirm)) {
Abort("apps_btc_confirm_multisig/2");
}
}
const confirm_params_t params_xpub = {
.title = title,
.body = confirm,
.scrollable = true,
.longtouch = i == num_cosigners - 1,
.accept_is_nextarrow = true,
};
if (!workflow_confirm_blocking(¶ms_xpub)) {
return false;
}
}
return true;
}
| Stadicus/bitbox02-firmware |
<|start_filename|>ModernWorkplaceConcierge/Models/Alert.cs<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace ModernWorkplaceConcierge.Models
{
// Used to flash error messages in the app's views.
public class Alert
{
public const string AlertKey = "TempDataAlerts";
public string Message { get; set; }
public string Debug { get; set; }
}
public class Info
{
public const string SessKey = "TempDataInfo";
public string Message { get; set; }
public string Debug { get; set; }
}
}
<|start_filename|>ModernWorkplaceConcierge/Controllers/AutoPilotConfigurationController.cs<|end_filename|>
using ModernWorkplaceConcierge.Helpers;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Web.Mvc;
using System.Threading.Tasks;
using Microsoft.Graph;
namespace ModernWorkplaceConcierge.Controllers
{
[Authorize]
[HandleError]
public class AutoPilotConfigurationController : BaseController
{
// GET: AutoPilotConfigurationJSON
public async Task<ActionResult> Index()
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
var AutopilotProfiles = await graphIntune.GetWindowsAutopilotDeploymentProfiles();
return View(AutopilotProfiles);
}
catch (ServiceException e)
{
Flash(e.Error.Message);
return RedirectToAction("Index", "Home");
}
}
public async Task<ActionResult> Detail(String Id)
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
var AutopilotProfile = await graphIntune.GetWindowsAutopilotDeploymentProfile(Id);
return View(AutopilotProfile);
}
catch (ServiceException e)
{
Flash(e.Error.Message);
return RedirectToAction("Index", "Home");
}
}
public async Task<FileResult> DownloadAutopilotConfigurationJSON(string Id)
{
GraphIntune graphIntune = new GraphIntune(null);
var profile = await graphIntune.GetWindowsAutopilotDeploymentProfile(Id);
var org = await GraphHelper.GetOrgDetailsAsync();
AutopilotConfiguration windowsAutopilotDeploymentProfile = new AutopilotConfiguration(profile, org);
var enc = Encoding.GetEncoding(1252);
byte[] autopilotconfiguraton = enc.GetBytes(JsonConvert.SerializeObject(windowsAutopilotDeploymentProfile,
// remove nullvalues from output and pretty format JSON
new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented
}
));
return File(autopilotconfiguraton, "application/json", "AutoPilotConfigurationFile.json");
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Views/Advanced/Index.cshtml<|end_filename|>
@{
ViewBag.Current = "Advanced";
}
<div class="jumbotron">
<h1>Advanced features</h1>
<p>You have been assigned the <code>AdvancedUser</code> role. You can execute the following actions - but use them with caution!</p>
<button type="button" class="btn btn-danger mt-1" data-toggle="modal" data-target="#exampleModalCenter">
Clear Conditional Access policies
</button>
<br />
<button type="button" class="btn btn-danger mt-2" data-toggle="modal" data-target="#IntuneModal">
Clear Intune Configuration
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title text-black-50" id="exampleModalLongTitle">Are you sure?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body text-black-50">
<p>This action will DELETE all conditional access policies from the signed-in tenant. This action is irreversible.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Abort</button>
@Html.ActionLink("Clear all Conditional Access policies", "ClearAll", "ConditionalAccess", new { Confirm = true }, new { @class = "btn btn-danger" })
</div>
</div>
</div>
</div>
<div class="modal fade" id="IntuneModal" tabindex="-1" role="dialog" aria-labelledby="IntuneModalTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title text-black-50" id="exampleModalLongTitle">Are you sure?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body text-black-50">
<p>This action will DELETE all device configurations, compliance policies, app protection policies and device management scripts. This action is irreversible.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Abort</button>
@Html.ActionLink("Clear all Intune Configuration", "ClearAll", "Intune", new { Confirm = true }, new { @class = "btn btn-danger" })
</div>
</div>
</div>
</div>
<|start_filename|>ModernWorkplaceConcierge/Helpers/UserConnectionManager.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ModernWorkplaceConcierge.Helpers
{
public class UserConnectionManager
{
private static Dictionary<string, List<string>> userConnectionMap = new Dictionary<string, List<string>>();
private static string userConnectionMapLocker = string.Empty;//find away to avoid lock later
public void KeepUserConnection(string userId, string connectionId)
{
lock (userConnectionMapLocker)
{
if (!userConnectionMap.ContainsKey(userId))
{
userConnectionMap[userId] = new List<string>();
}
userConnectionMap[userId].Add(connectionId);
}
}
public void RemoveUserConnection(string connectionId)
{
//Remove the connectionId of user
lock (userConnectionMapLocker)
{
foreach (var userId in userConnectionMap.Keys)
{
if (userConnectionMap.ContainsKey(userId))
{
if (userConnectionMap[userId].Contains(connectionId))
{
userConnectionMap[userId].Remove(connectionId);
break;
}
}
}
}
}
public List<string> GetUserConnections(string userId)
{
var conn = new List<string>();
lock (userConnectionMapLocker)
{
conn = userConnectionMap[userId];
}
return conn;
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Views/Intune/Win32AppDetectionScripts.cshtml<|end_filename|>
@model IEnumerable<Microsoft.Graph.Win32LobApp>
@{
ViewBag.Current = "IntuneWin32AppDetectionScripts";
}
<script src="~/Content/Prismjs/prism.js"></script>
<link rel="stylesheet" href="~/Content/Prismjs/prism.css">
<div class="jumbotron">
<h1>Win32 App Custom Detection Scripts</h1>
<p>View and download custom PowerShell detection scripts of your Win32 apps.</p>
</div>
<table class="table table-borderless">
<tr>
<th>
@Html.DisplayNameFor(model => model.DisplayName)
</th>
<th>
@Html.DisplayNameFor(model => model.Publisher)
</th>
<th>
@Html.DisplayNameFor(model => model.LastModifiedDateTime)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
if (item.DisplayName != null)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DisplayName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Publisher)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastModifiedDateTime)
</td>
<td>
<a href="javascript:void(0);" class="anchorDetail btn btn-outline-light" data-id="@item.Id">Preview</a>
@Html.ActionLink("Download", "DownloadDetectionScript", new { Id = item.Id }, new { @class = "btn btn-outline-light" })
</td>
</tr>
}
else
{
<caption> Could not fetch DeviceManagementScript.</caption>
}
}
</table>
<div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" id="myModal" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header" style="border:none; color: black;">
<h5 class="modal-title">PowerShell Preview</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<pre class="line-numbers">
<code id="myModalContent" class="language-powershell"></code>
</pre>
<div class="modal-footer" style="border:none">
<button type="button" id="closbtn" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
var URL = '/Intune/Win32AppPsDetectionScriptContent';
Prism.plugins.NormalizeWhitespace.setDefaults({
'remove-trailing': true,
'remove-indent': true,
'left-trim': true,
'right-trim': true,
'remove-initial-line-feed': true,
});
$(function () {
$(".anchorDetail").click(function () {
debugger;
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
$.ajax({
type: "GET",
url: URL,
contentType: "text/plain; charset=utf-8",
data: { "Id": id },
datatype: "text/html",
success: function (data) {
debugger;
$('#myModalContent').html(data.trim());
$('#myModal').modal('show');
Prism.highlightAll();
},
error: function () {
alert("Dynamic content load failed.");
}
});
});
});
</script>
<|start_filename|>ModernWorkplaceConcierge/Helpers/DeviceManagementScripts.cs<|end_filename|>
using Microsoft.Graph;
using Newtonsoft.Json;
namespace IntuneConcierge.Helpers
{
public class DeviceManagementScripts
{
[JsonProperty("@odata.context")]
public string odatacontext { get; set; }
[JsonProperty("value")]
public DeviceManagementScript[] value { get; set; }
}
}
<|start_filename|>ModernWorkplaceConcierge/Views/About/Index.cshtml<|end_filename|>
@{
ViewBag.Current = "AboutIndex";
}
<div class="card">
<div class="card-body">
<h3 class="card-title">Motivation</h3>
<p class="card-text">This tool was initially created to learn some C# programming and to better understand the Microsoft Graph API.</p>
<p style="text-indent: 2em; font-style: italic; line-height:initial;">...Now fellow workplace engineers have a tool supporting them with powerful automation for various Enterprise Mobility + Security features.</p>
<p>Managing Intune (MEM) and Conditional Access configuration requires a lot of clicking around in the portal. While the author of this tool is daydreaming about of "EM+S" as code the Modern Workplace Concierge automates most of this tasks and provides functionality to import and export configurations. Even across different tenants. So replicating, upating, rolling-back or even migrating you configuration to a new tenant becomes fairly easy.</p>
<p>The Modern Workplace Concierge is open source and proudly presented by <NAME>. Made in Switzerland <img src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/apple/237/flag-for-switzerland_1f1e8-1f1ed.png" width="25" />.</p>
<a href="https://github.com/nicolonsky/ModernWorkplaceConcierge" target="_blank" class="btn btn-outline-info">
<span>View this project on GitHub</span>
</a>
<a href="https://github.com/nicolonsky/ModernWorkplaceConcierge/issues/new" target="_blank" class="btn btn-outline-warning">
<span>Report an issue or request a feature</span>
</a>
<a href="https://tech.nicolonsky.ch" target="_blank" class="btn btn-outline-info">
<span>Nicola's techblog</span>
</a>
</div>
</div>
<div class="card mt-3">
<div class="card-body">
<h3 class="card-title">Permissions</h3>
<p class="card-text">The Modern Workplace Concierge needs the following delegated Microsoft Graph permissions:</p>
@{
string permissions = @System.Configuration.ConfigurationManager.AppSettings["AppScopes"].ToString();
string[] allpermissions = permissions.Split(' ');
Array.Sort(allpermissions);
<ul style="font-weight: 100;">
@foreach (var permission in allpermissions)
{
<li>@permission</li>
}
</ul>
}
<a href="https://docs.microsoft.com/en-us/graph/permissions-reference" target="_blank" class="card-link">Microsoft Graph permissions reference</a>
</div>
</div>
<div class="card mt-3">
<div class="card-body">
<h3 class="card-title">Instance Details</h3>
<p>App Configuration</p>
@{
<ul style="font-weight: 100;">
<li>TokenEndpoint: <code class="text-dark">@System.Configuration.ConfigurationManager.AppSettings["TokenEndpoint"].ToString()</code></li>
<li>Application ID: <code class="text-dark">@System.Configuration.ConfigurationManager.AppSettings["AppId"].ToString()</code></li>
<li>Redirect URI: <code class="text-dark">@System.Configuration.ConfigurationManager.AppSettings["RedirectUri"].ToString()</code></li>
<li>Graph Endpoint: <code class="text-dark">@System.Configuration.ConfigurationManager.AppSettings["GraphEndpoint"].ToString()</code></li>
<li>Instance: <code class="text-dark">@System.Configuration.ConfigurationManager.AppSettings["InstanceType"].ToString()</code></li>
</ul>
}
<p>Azure DevOps CI</p>
@{
<ul style="font-weight: 100;">
<li>Repository: <code class="text-dark">@System.Configuration.ConfigurationManager.AppSettings["Repository"].ToString()</code></li>
<li>Branch: <code class="text-dark">@System.Configuration.ConfigurationManager.AppSettings["Branch"].ToString()</code></li>
<li>Commit: <a target="_blank" class="text-info" href="https://github.com/@System.Configuration.ConfigurationManager.AppSettings["Repository"].ToString()/commit/@System.Configuration.ConfigurationManager.AppSettings["CommitID"].ToString()">@System.Configuration.ConfigurationManager.AppSettings["CommitID"].ToString()</a></li>
<li>Build: <code class="text-dark">@typeof(ModernWorkplaceConcierge.BundleConfig).Assembly.GetName().Version</code></li>
<li>DeploymentTime: <code class="text-dark">@System.Configuration.ConfigurationManager.AppSettings["DeploymentTime"].ToString()</code></li>
<li><img src="https://dev.azure.com/nicolonsky/ModernWorkplaceTools/_apis/build/status/ModernWorkplaceConcierge%20-%20CI?branchName=master" /></li>
</ul>
}
</div>
</div>
<|start_filename|>ModernWorkplaceConcierge/Views/Planner/Index.cshtml<|end_filename|>
@model IEnumerable<Microsoft.Graph.PlannerPlan>
@{
ViewBag.Current = "PlannerImport";
}
<div class="jumbotron">
<h1>Import trello boards to Microsoft Planner</h1>
<p>Migrate exported trello boards to Micorosoft planner. Documentation is available on the <a href="https://github.com/nicolonsky/ModernWorkplaceConcierge/wiki/Migrate-trello-tasks-to-Microsoft-Planner" target="_blank">GitHub wiki</a>.</p>
</div>
@using (Html.BeginForm("Import", "Planner", FormMethod.Post, new { @class = "form", enctype = "multipart/form-data" }))
{
<input type="text" name="clientId" class="d-none" id="clientId" required>
<div class="form-row">
<div class="col">
<div class="form-group">
<label for="PlannerPlan" data_toggle = "tooltip", data_placement = "left" >Target Office 365 Planner Plan</label>
@Html.DropDownList("PlannerPlan", new SelectList(Model, "Id", "Title"), new { @class = "form-control required", data_toggle = "tooltip", data_placement = "left" })
</div>
</div>
<div class="col">
<div class="form-group">
<label for="file" data-toggle="tooltip" data-placement="left">Exported trello board json</label>
<div class="custom-file">
<input type="file" name="file" class="custom-file-input" id="file" accept=".json">
<label class="custom-file-label overflow-hidden" for="file">Choose file</label>
</div>
<script>
// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
$("#upload").removeAttr("disabled");
});
</script>
</div>
</div>
</div>
<div class="form-row">
<div class="col">
<button class="btn btn-info form-group" type="submit" id="upload" disabled>
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display: none" id="loady"></span>
Import
</button>
<script>
(function () {
$('#upload').click(function () {
$('#loady').show();
})
})();
</script>
</div>
</div>
}
@section scripts {
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script src="~/Content/MwConciergeSignalR.js"></script>
<!-- Tooltips -->
<script>
$('#PlannerPlan').tooltip({ 'trigger': 'focus', 'title': 'Name of the Office 365 Planner Plan where the trello tasks will be imported.' });
$('#file').tooltip({ 'trigger': 'focus', 'title': 'Upload your exportred trello board in json representation.' });
</script>
}
<|start_filename|>ModernWorkplaceConcierge/Helpers/RoleScopeTagTranslation.cs<|end_filename|>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ModernWorkplaceConcierge.Helpers
{
public class RoleScopeTagTranslation
{
public static List<string> TranslateRoleScopeTags(string[] roleScopeTagIds, Hashtable scopeTagMigrationTable)
{
// Translate scope tag with table
List<string> newMapping = new List<string>();
foreach (string roleScopeTagId in roleScopeTagIds)
{
try
{
newMapping.Add(scopeTagMigrationTable[roleScopeTagId].ToString());
}
catch
{
newMapping.Add("0");
}
}
return newMapping;
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Views/ConditionalAccess/DeployBaseline.cshtml<|end_filename|>
@model IEnumerable<String>
@{
ViewBag.Current = "ConditionalAccessDeployBasline";
}
<div class="jumbotron">
<h1>Deploy Conditional Access Basline</h1>
<p>Deploy a rock solid set of Conditional Access Policies including the creation and assignment of exclusion groups. Policy sets are provided by <a href="https://github.com/AlexFilipin/ConditionalAccess" target="_blank">@@AlexFilipin</a>. Kudos for his excellent work!</p>
<ol>
<li>Deploy a policy set</li>
<li>Add users like break glass and AAD connect accounts to the exclusion group</li>
<li>Enable the policies</li>
</ol>
</div>
@using (Html.BeginForm("DeployBaseline", "ConditionalAccess", FormMethod.Post, new { @class = "form", enctype = "multipart/form-data", autocomplete = "off" }))
{
<input type="text" name="clientId" class="d-none" id="clientId" required>
<div class="form-row">
<div class="col">
<div class="form-group">
<label for="displayName">Conditional Access Excluded Group</label>
<input type="text" name="displayName" class="form-control" data-toggle="tooltip" data-placement="bottom" placeholder="aad-conditional-access-exclusions" id="displayName" required>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="allowLegacyAuth">Legacy Authentication Excluded Group</label>
<input type="text" name="allowLegacyAuth" class="form-control" data-toggle="tooltip" data-placement="bottom" placeholder="aad-conditional-access-allow-legacy-auth" id="allowLegacyAuth" required>
</div>
</div>
</div>
<div class="form-row">
<div class="col">
<div class="form-group">
<label for="policyPrefix">Conditional Access Policy Prefix (optional)</label>
<input type="text" name="policyPrefix" class="form-control" data-toggle="tooltip" data-placement="bottom" id="policyPrefix" placeholder="CAR -">
</div>
</div>
<div class="col">
<div class="form-group">
<label for="selectedBaseline">Conditional Access Policy Set</label>
@Html.DropDownList("selectedBaseline", new SelectList(Model), new { @class = "form-control", data_toggle = "tooltip", data_placement = "bottom" })
</div>
</div>
</div>
<div class="form-row">
<div class="col">
<div class="form-group">
<button class="btn btn-info" type="submit" id="upload">Deploy ✨</button>
</div>
</div>
</div>
}
@section scripts {
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script src="~/Content/MwConciergeSignalR.js"></script>
<!-- Tooltips -->
<script>
$('#displayName').tooltip({ 'trigger': 'focus', 'title': 'This Azure AD Group will be created (if it does not exist) and excluded from all Conditional Access policies.' });
$('#allowLegacyAuth').tooltip({ 'trigger': 'focus', 'title': 'This Azure AD Group will be created (if it does not exist) and excluded from the policy preventing legacy authentication.' });
$('#policyPrefix').tooltip({ 'trigger': 'focus', 'title': 'This optional prefix will be added to each policies display name.' });
$('#selectedBaseline').tooltip({ 'trigger': 'focus', 'title': 'Select your desired conditional access policy set.' });
</script>
}
<|start_filename|>ModernWorkplaceConcierge/Models/AADLicensePlan.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ModernWorkplaceConcierge.Models
{
public enum AADLicensePlan
{
FREE,
PREMIUM_P1,
PREMIUM_P2
}
public enum DeviceState
{
AAD_HYBRID,
MEMCM,
NOT_ENROLLED
}
public enum NetworkLocations
{
YES,
NO
}
public enum AdditionalLicenses
{
YES,
NO
}
}
<|start_filename|>ModernWorkplaceConcierge/Views/Intune/Index.cshtml<|end_filename|>
@{
ViewBag.Current = "IntuneExport";
}
<div class="jumbotron">
<h1>Export Intune configuration</h1>
<p>Items in export will be included in json format within a zip file. A list of supported items is available <a href="https://github.com/nicolonsky/ModernWorkplaceConcierge/wiki/Entities-supported-in-exports-and-imports" target="_blank">here</a>.</p>
@using (Html.BeginForm("DownloadAsync", "IntuneConfigExport", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="text" name="clientId" class="d-none" id="clientId">
<button class="btn btn-info btn-large" type="submit" id="upload">
<i class="far fa-file-archive"></i>
<span>Export Intune configuration</span>
</button>
}
</div>
@section scripts {
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script src="~/Content/MwConciergeSignalR.js"></script>
}
<|start_filename|>ModernWorkplaceConcierge/Views/Intune/import.cshtml<|end_filename|>
@{
ViewBag.Current = "IntuneImport";
}
<div class="jumbotron">
<h1>Import Intune configuration</h1>
<p>Import previously exported data to your Intune tenant from zip or json files. A list of supported items is available <a href="https://github.com/nicolonsky/ModernWorkplaceConcierge/wiki/Entities-supported-in-exports-and-imports" target="_blank">here</a>.<p>
<ul>
<li>For zip-file uploads do not modify the folder structure</li>
</ul>
</div>
@using (Html.BeginForm("Upload", "Intune", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="text" name="clientId" class="d-none" id="clientId" required>
<div class="form-row">
<div class="col">
<label for="file">File</label>
<div class="custom-file">
<input type="file" name="files" class="custom-file-input" id="file" accept=".json,.zip" multiple required>
<label class="custom-file-label overflow-hidden" for="file">Choose file</label>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="overwriteBehaviour">When a configuration already exists</label>
@Html.DropDownList("overwriteBehaviour", EnumHelper.GetSelectList(typeof(ModernWorkplaceConcierge.Models.OverwriteBehaviour)), new { @class = "form-control readonly"})
</div>
<script>
//$('option:not(:selected)').attr('disabled', true);
</script>
</div>
</div>
<div class="form-row">
<div class="col">
<div class="form-group">
<button class="btn btn-info" type="submit" id="upload" disabled>
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display: none" id="loady"></span>
Import
</button>
</div>
</div>
</div>
<script>
// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
$("#upload").removeAttr("disabled");
});
</script>
<script>
(function () {
$('#upload').click(function () {
$('#loady').show();
})
})();
</script>
}
@section scripts {
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script src="~/Content/MwConciergeSignalR.js"></script>
}
<|start_filename|>ModernWorkplaceConcierge/Helpers/OverwriteBehaviour.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ModernWorkplaceConcierge.Helpers
{
public class OverwriteBehaviour
{
public string Name { get; set; }
public string Behaviour { get; set; }
}
public class ViewModel
{
private readonly List<OverwriteBehaviour> overwriteBehaviours;
[Display(Name = "Overwrite Behaviour")]
public string SelectedBehaviour { get; set; }
public IEnumerable<SelectListItem> SelectListItems
{
get { return new SelectList(overwriteBehaviours, "Name", "Behaviour"); }
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Helpers/MwHub.cs<|end_filename|>
using Microsoft.AspNet.SignalR;
namespace ModernWorkplaceConcierge.Helpers
{
public class MwHub : Hub
{
public void SendMessage(string message)
{
Clients.Caller.addMessage(message); // Message sent
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Controllers/ConditionalAccessController.cs<|end_filename|>
using ModernWorkplaceConcierge.Helpers;
using ModernWorkplaceConcierge.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace ModernWorkplaceConcierge.Controllers
{
[Authorize]
public class ConditionalAccessController : BaseController
{
private readonly string TEMPLATE_CA_POLICY_FOLDER_PATH = "~/Content/PolicySets/";
[HttpPost]
public async Task<ActionResult> Upload(HttpPostedFileBase[] files, OverwriteBehaviour overwriteBehaviour, string clientId)
{
SignalRMessage signalRMessage = new SignalRMessage(clientId);
try
{
GraphConditionalAccess graphConditionalAccess = new GraphConditionalAccess(clientId);
IEnumerable<ConditionalAccessPolicy> conditionalAccessPolicies = await graphConditionalAccess.GetConditionalAccessPoliciesAsync();
List<string> uploadedConditionalAccessPolicies = new List<string>();
if (files.Length > 0 && files[0].FileName.Contains(".json"))
{
foreach (HttpPostedFileBase file in files)
{
BinaryReader binaryReader = new BinaryReader(file.InputStream);
byte[] binData = binaryReader.ReadBytes(file.ContentLength);
uploadedConditionalAccessPolicies.Add(Encoding.UTF8.GetString(binData));
}
}
else if (files.Length > 0 && files[0].FileName.Contains(".zip"))
{
try
{
MemoryStream target = new MemoryStream();
files[0].InputStream.CopyTo(target);
byte[] data = target.ToArray();
using (var zippedStream = new MemoryStream(data))
{
using (var archive = new ZipArchive(zippedStream))
{
foreach (var entry in archive.Entries)
{
try
{
if (entry != null)
{
using (var unzippedEntryStream = entry.Open())
{
using (var ms = new MemoryStream())
{
unzippedEntryStream.CopyTo(ms);
var unzippedArray = ms.ToArray();
uploadedConditionalAccessPolicies.Add(Encoding.UTF8.GetString(unzippedArray));
}
}
}
}
catch (Exception e)
{
signalRMessage.sendMessage("Error: " + e.Message);
}
}
}
}
}
catch (Exception e)
{
signalRMessage.sendMessage("Error: " + e.Message);
}
}
foreach (string uploadedPolicy in uploadedConditionalAccessPolicies)
{
ConditionalAccessPolicy conditionalAccessPolicy = JsonConvert.DeserializeObject<ConditionalAccessPolicy>(uploadedPolicy);
switch (overwriteBehaviour)
{
case OverwriteBehaviour.DISCARD:
// Check for any policy with same name or id
if (conditionalAccessPolicies.All(p => !p.id.Contains(conditionalAccessPolicy.id) && conditionalAccessPolicies.All(policy => !policy.displayName.Equals(conditionalAccessPolicy.displayName))))
{
var response = await graphConditionalAccess.TryAddConditionalAccessPolicyAsync(conditionalAccessPolicy);
}
else
{
if (conditionalAccessPolicies.Any(p => p.id.Contains(conditionalAccessPolicy.id)))
{
signalRMessage.sendMessage($"Discarding Policy '{conditionalAccessPolicy.displayName}' ({conditionalAccessPolicy.id}) already exists!");
}
else
{
signalRMessage.sendMessage($"Discarding Policy '{conditionalAccessPolicy.displayName}' - policy with this name already exists!");
}
}
break;
case OverwriteBehaviour.IMPORT_AS_DUPLICATE:
await graphConditionalAccess.TryAddConditionalAccessPolicyAsync(conditionalAccessPolicy);
break;
case OverwriteBehaviour.OVERWRITE_BY_ID:
// match by object ID
if (conditionalAccessPolicies.Any(policy => policy.id.Equals(conditionalAccessPolicy.id)))
{
await graphConditionalAccess.PatchConditionalAccessPolicyAsync(conditionalAccessPolicy);
}
// Create a new policy
else
{
var result = await graphConditionalAccess.TryAddConditionalAccessPolicyAsync(conditionalAccessPolicy);
}
break;
case OverwriteBehaviour.OVERWRITE_BY_NAME:
if (conditionalAccessPolicies.Any(policy => policy.displayName.Equals(conditionalAccessPolicy.displayName)))
{
string replaceObjectId = conditionalAccessPolicies.Where(policy => policy.displayName.Equals(conditionalAccessPolicy.displayName)).Select(policy => policy.id).First();
conditionalAccessPolicy.id = replaceObjectId;
await graphConditionalAccess.PatchConditionalAccessPolicyAsync(conditionalAccessPolicy);
}
else
{
var result = await graphConditionalAccess.TryAddConditionalAccessPolicyAsync(conditionalAccessPolicy);
}
break;
}
}
}
catch (Exception e)
{
signalRMessage.sendMessage("Error: " + e.Message);
}
signalRMessage.sendMessage("Done#!");
return new HttpStatusCodeResult(204);
}
[HttpPost]
public async Task<ActionResult> DeployBaseline(string displayName, string selectedBaseline, string policyPrefix, string allowLegacyAuth, string clientId = null)
{
SignalRMessage signalR = new SignalRMessage(clientId);
GraphConditionalAccess graphConditionalAccess = new GraphConditionalAccess(clientId);
signalR.sendMessage("Selected baseline: " + selectedBaseline);
try
{
// Create exclusion group (if the group already exists we retrieve the ID)
Microsoft.Graph.Group createdGroup = await GraphHelper.CreateGroup(displayName, clientId);
List<string> groupsCreated = new List<string>
{
createdGroup.Id
};
// Load CA policies for policy set
string[] filePaths = Directory.GetFiles(Server.MapPath(TEMPLATE_CA_POLICY_FOLDER_PATH + selectedBaseline), "*.json");
if (filePaths.Length == 0)
{
signalR.sendMessage($"Warning no Conditional Access Policies found within selected set ({selectedBaseline})!");
}
// Modify exclusions & Display Name
List<ConditionalAccessPolicy> conditionalAccessPolicies = new List<ConditionalAccessPolicy>();
foreach (string filePath in filePaths)
{
try
{
if (System.IO.File.Exists(filePath))
{
using (var streamReader = new StreamReader(filePath, Encoding.UTF8))
{
string textCaPolicy = streamReader.ReadToEnd();
// Modify properties on template
ConditionalAccessPolicy conditionalAccessPolicy = JsonConvert.DeserializeObject<ConditionalAccessPolicy>(textCaPolicy);
conditionalAccessPolicy.conditions.users.excludeGroups = groupsCreated.ToArray();
string placeholder = "<RING> -";
int startDisplayName = conditionalAccessPolicy.displayName.IndexOf(placeholder) + placeholder.Length;
conditionalAccessPolicy.displayName = conditionalAccessPolicy.displayName.Substring(startDisplayName, conditionalAccessPolicy.displayName.Length - startDisplayName);
conditionalAccessPolicy.displayName = conditionalAccessPolicy.displayName.Insert(0, policyPrefix).Replace("<PREFIX> -", "").Trim();
// Check for legacy auth exclusion group
if (conditionalAccessPolicy.conditions.clientAppTypes.Contains("other") && conditionalAccessPolicy.grantControls.builtInControls.Contains("block"))
{
// Wee need to initialize a new list to avoid modifications to the existing!
List<String> newGroupsCreated = new List<String>(groupsCreated);
Microsoft.Graph.Group allowLegacyAuthGroup = await GraphHelper.CreateGroup(allowLegacyAuth, clientId);
newGroupsCreated.Add(allowLegacyAuthGroup.Id);
conditionalAccessPolicy.conditions.users.excludeGroups = newGroupsCreated.ToArray();
}
// Create the policy
await graphConditionalAccess.TryAddConditionalAccessPolicyAsync(conditionalAccessPolicy);
}
}
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e.Message);
}
}
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e.Message);
}
signalR.sendMessage("Done#!");
return new HttpStatusCodeResult(204);
}
public ViewResult DeployBaseline()
{
List<String> dirs = new List<string>();
String[] XmlFiles = Directory.GetDirectories(Server.MapPath(TEMPLATE_CA_POLICY_FOLDER_PATH));
for (int x = 0; x < XmlFiles.Length; x++)
dirs.Add(Path.GetFileNameWithoutExtension(XmlFiles[x]));
return View(dirs);
}
public ViewResult Import()
{
return View();
}
// GET: ConditionalAccess
public ViewResult Index()
{
return View();
}
public async Task<ActionResult> DownloadAll(string clientId = null)
{
SignalRMessage signalR = new SignalRMessage(clientId);
try
{
GraphConditionalAccess graphConditionalAccess = new GraphConditionalAccess(clientId);
IEnumerable<ConditionalAccessPolicy> conditionalAccessPolicies = await graphConditionalAccess.GetConditionalAccessPoliciesAsync();
using (MemoryStream ms = new MemoryStream())
{
using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
{
foreach (ConditionalAccessPolicy item in conditionalAccessPolicies)
{
byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, Formatting.Indented).ToString());
string displayName = item.displayName;
char[] illegal = Path.GetInvalidFileNameChars();
foreach (char illegalChar in illegal)
{
displayName = displayName.Replace(illegalChar, '-');
}
var zipArchiveEntry = archive.CreateEntry(displayName + "_" + item.id.Substring(0,8) + ".json", CompressionLevel.Fastest);
using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length);
}
}
string domainName = await GraphHelper.GetDefaultDomain(clientId);
return File(ms.ToArray(), "application/zip", "ConditionalAccessConfig_" + domainName + ".zip");
}
}
catch (Exception e)
{
signalR.sendMessage("Error " + e);
}
return new HttpStatusCodeResult(204);
}
public ViewResult Documentation()
{
return View();
}
[CustomAuthorization(Roles = ("AdvancedUser"))]
public async Task<ActionResult> ClearAll(bool confirm = false)
{
try
{
GraphConditionalAccess graphConditionalAccess = new GraphConditionalAccess(null);
if (confirm)
{
await graphConditionalAccess.ClearConditonalAccessPolicies();
}
return new HttpStatusCodeResult(204);
}
catch (Exception e)
{
Flash(e.Message);
return RedirectToAction("Index", "Home");
}
}
public async Task<ActionResult> CreateDocumentation(string clientId = null)
{
IEnumerable<ConditionalAccessPolicy> conditionalAccessPolicies = null;
SignalRMessage signalR = new SignalRMessage(clientId);
try
{
GraphConditionalAccess graphConditionalAccess = new GraphConditionalAccess(clientId);
conditionalAccessPolicies = await graphConditionalAccess.GetConditionalAccessPoliciesAsync();
DataTable dataTable = new DataTable();
dataTable.BeginInit();
dataTable.Columns.Add("Name");
dataTable.Columns.Add("State");
// Assignments: first include then exclude
dataTable.Columns.Add("IncludeUsers");
dataTable.Columns.Add("IncludeGroups");
dataTable.Columns.Add("IncludeRoles");
dataTable.Columns.Add("ExcludeUsers");
dataTable.Columns.Add("ExcludeGroups");
dataTable.Columns.Add("ExcludeRoles");
dataTable.Columns.Add("IncludeApps");
dataTable.Columns.Add("ExcludeApps");
dataTable.Columns.Add("IncludeUserActions");
dataTable.Columns.Add("ClientAppTypes");
dataTable.Columns.Add("IncludePlatforms");
dataTable.Columns.Add("ExcludePlatforms");
dataTable.Columns.Add("IncludeLocations");
dataTable.Columns.Add("ExcludeLocations");
dataTable.Columns.Add("IncludeDeviceStates");
dataTable.Columns.Add("ExcludeDeviceStates");
dataTable.Columns.Add("GrantControls");
dataTable.Columns.Add("GrantControlsOperator");
dataTable.Columns.Add("ApplicationEnforcedRestrictions");
dataTable.Columns.Add("CloudAppSecurity");
dataTable.Columns.Add("PersistentBrowser");
dataTable.Columns.Add("SignInFrequency");
// Init cache for AAD Object ID's in CA policies
AzureADIDCache azureADIDCache = new AzureADIDCache(clientId);
foreach (ConditionalAccessPolicy conditionalAccessPolicy in conditionalAccessPolicies)
{
try
{
// Init a new row
DataRow row = dataTable.NewRow();
row["Name"] = conditionalAccessPolicy.displayName;
row["State"] = conditionalAccessPolicy.state;
row["IncludeUsers"] = $"\"{String.Join("\n", await azureADIDCache.getUserDisplayNamesAsync(conditionalAccessPolicy.conditions.users.includeUsers))}\"";
row["ExcludeUsers"] = $"\"{String.Join("\n", await azureADIDCache.getUserDisplayNamesAsync(conditionalAccessPolicy.conditions.users.excludeUsers))}\"";
row["IncludeGroups"] = $"\"{String.Join("\n", await azureADIDCache.getGroupDisplayNamesAsync(conditionalAccessPolicy.conditions.users.includeGroups))}\"";
row["ExcludeGroups"] = $"\"{String.Join("\n", await azureADIDCache.getGroupDisplayNamesAsync(conditionalAccessPolicy.conditions.users.excludeGroups))}\"";
row["IncludeRoles"] = $"\"{String.Join("\n", await azureADIDCache.getRoleDisplayNamesAsync(conditionalAccessPolicy.conditions.users.includeRoles))}\"";
row["ExcludeRoles"] = $"\"{String.Join("\n", await azureADIDCache.getRoleDisplayNamesAsync(conditionalAccessPolicy.conditions.users.excludeRoles))}\"";
row["IncludeApps"] = $"\"{String.Join("\n", await azureADIDCache.getApplicationDisplayNamesAsync(conditionalAccessPolicy.conditions.applications.includeApplications))}\"";
row["ExcludeApps"] = $"\"{String.Join("\n", await azureADIDCache.getApplicationDisplayNamesAsync(conditionalAccessPolicy.conditions.applications.excludeApplications))}\"";
row["IncludeUserActions"] = $"\"{String.Join("\n", await azureADIDCache.getApplicationDisplayNamesAsync(conditionalAccessPolicy.conditions.applications.includeUserActions))}\"";
if (conditionalAccessPolicy.conditions.platforms != null && conditionalAccessPolicy.conditions.platforms.includePlatforms != null)
{
row["IncludePlatforms"] = $"\"{String.Join("\n", conditionalAccessPolicy.conditions.platforms.includePlatforms)}\"";
}
if (conditionalAccessPolicy.conditions.platforms != null && conditionalAccessPolicy.conditions.platforms.excludePlatforms != null)
{
row["ExcludePlatforms"] = $"\"{String.Join("\n", conditionalAccessPolicy.conditions.platforms.excludePlatforms)}\"";
}
if (conditionalAccessPolicy.conditions.locations != null && conditionalAccessPolicy.conditions.locations.includeLocations != null)
{
row["IncludeLocations"] = $"\"{String.Join("\n", await azureADIDCache.getNamedLocationDisplayNamesAsync(conditionalAccessPolicy.conditions.locations.includeLocations))}\"";
}
if (conditionalAccessPolicy.conditions.locations != null && conditionalAccessPolicy.conditions.locations.excludeLocations != null)
{
row["ExcludeLocations"] = $"\"{String.Join("\n", await azureADIDCache.getNamedLocationDisplayNamesAsync(conditionalAccessPolicy.conditions.locations.excludeLocations))}\"";
}
row["ClientAppTypes"] = $"\"{String.Join("\n", conditionalAccessPolicy.conditions.clientAppTypes)}\"";
if (conditionalAccessPolicy.conditions.devices != null && conditionalAccessPolicy.conditions.devices.includeDeviceStates != null)
{
row["IncludeDeviceStates"] = $"\"{String.Join("\n", conditionalAccessPolicy.conditions.devices.includeDeviceStates)}\"";
}
if (conditionalAccessPolicy.conditions.devices != null && conditionalAccessPolicy.conditions.devices.excludeDeviceStates != null)
{
row["IncludeDeviceStates"] = $"\"{String.Join("\n", conditionalAccessPolicy.conditions.devices.excludeDeviceStates)}\"";
}
if (conditionalAccessPolicy.grantControls != null && conditionalAccessPolicy.grantControls.builtInControls != null)
{
row["GrantControls"] = $"\"{String.Join("\n", conditionalAccessPolicy.grantControls.builtInControls)}\"";
row["GrantControlsOperator"] = $"\"{String.Join("\n", conditionalAccessPolicy.grantControls.op)}\"";
}
if (conditionalAccessPolicy.sessionControls != null && conditionalAccessPolicy.sessionControls.applicationEnforcedRestrictions != null)
{
row["ApplicationEnforcedRestrictions"] = $"\"{String.Join("\n", conditionalAccessPolicy.sessionControls.applicationEnforcedRestrictions.isEnabled)}\"";
}
if (conditionalAccessPolicy.sessionControls != null && conditionalAccessPolicy.sessionControls.cloudAppSecurity != null)
{
row["CloudAppSecurity"] = $"\"{String.Join("\n", conditionalAccessPolicy.sessionControls.cloudAppSecurity)}\"";
}
if (conditionalAccessPolicy.sessionControls != null && conditionalAccessPolicy.sessionControls.persistentBrowser != null)
{
row["PersistentBrowser"] = conditionalAccessPolicy.sessionControls.persistentBrowser.mode;
}
if (conditionalAccessPolicy.sessionControls != null && conditionalAccessPolicy.sessionControls.signInFrequency != null)
{
row["SignInFrequency"] = conditionalAccessPolicy.sessionControls.signInFrequency.value + " " + conditionalAccessPolicy.sessionControls.signInFrequency.type;
}
// Add new row to table
dataTable.Rows.Add(row);
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e);
}
}
// Convert datatable to CSV string output
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dataTable.Columns.Cast<DataColumn>().Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dataTable.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
string domainName = await GraphHelper.GetDefaultDomain(clientId);
if (!string.IsNullOrEmpty(clientId))
{
signalR.sendMessage("Success: Report generated");
}
return File(Encoding.ASCII.GetBytes(sb.ToString()), "text/csvt", "ConditionalAccessReport_" + domainName + ".csv");
}
catch (Exception e)
{
signalR.sendMessage($"Error {e.Message}");
}
return new HttpStatusCodeResult(204);
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Views/ConditionalAccess/Documentation.cshtml<|end_filename|>
@{
ViewBag.Current = "ConditionalAccessDocumentation";
}
<div class="jumbotron">
<h1>Create Conditional Access Documentation</h1>
<p>Generate a documentation about your configured conditional access policies. Comes in handy CSV format.</p>
@using (Html.BeginForm("CreateDocumentation", "ConditionalAccess", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="text" name="clientId" class="d-none" id="clientId" required>
<button class="btn btn-info btn-large" type="submit" id="upload">Create Documentation ✨</button>
}
</div>
@section scripts {
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script src="~/Content/MwConciergeSignalR.js"></script>
}
<|start_filename|>ModernWorkplaceConcierge/Controllers/AdvancedController.cs<|end_filename|>
using ModernWorkplaceConcierge.Helpers;
using System.Web.Mvc;
namespace ModernWorkplaceConcierge.Controllers
{
[CustomAuthorization(Roles = "AdvancedUser")]
public class AdvancedController : BaseController
{
public ActionResult Index()
{
return View();
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Models/OverwriteBehaviour.cs<|end_filename|>
namespace ModernWorkplaceConcierge.Models
{
public enum OverwriteBehaviour
{
IMPORT_AS_DUPLICATE,
DISCARD,
OVERWRITE_BY_ID,
OVERWRITE_BY_NAME
}
}
<|start_filename|>ModernWorkplaceConcierge/Content/Site.css<|end_filename|>
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*
* !#23364A;
*/
a.btn.btn-large.SignInButton {
background-color: #2F2F2F;
}
.fa-download:before {
color: gray;
}
.fa-download:hover {
color: aqua;
}
.tooltip-inner {
min-width: 100px;
max-width: 100%;
}
a {
color: #17a2b8;
}
a:hover {
color: #17a2b8;
}
a.card-link:hover {
text-decoration: underline;
}
.dropdown-item.active, .dropdown-item:active {
background-color: #17a2b8;
}
.dropdown-item:hover a {
background-color: #17a2b8;
color: white;
}
.dropdown-item:hover {
background-color: #17a2b8;
color: white;
}
body {
padding-top: 4.5rem;
background-color: #215b7d;
color: white;
}
.table {
color: #ffffff;
}
.text-muted {
color: #adadad !important;
}
.card-body {
color: black;
}
.jumbotron {
background-color: white;
color: #18161C;
}
.footer {
background-color: #31302f;
color: #F9F9F7;
}
.bg-dark {
background-color: #31302f !important;
}
.alert-pre {
word-wrap: break-word;
word-break: break-all;
white-space: pre-wrap;
}
.mt-auto, .my-auto {
margin-top: auto !important;
}
.pb-3, .py-3 {
padding-bottom: 1rem !important;
}
.pt-3, .py-3 {
padding-top: 1rem !important;
}
<|start_filename|>ModernWorkplaceConcierge/Views/Index.cshtml<|end_filename|>
@model IEnumerable<Microsoft.Graph.PlannerPlan>
@{
ViewBag.Current = "PlannerImport";
}
<div class="jumbotron">
<h1>Import Trello Tasks to Microsoft Planner</h1>
<p>Migrate a trello board to Micorosoft planner</p>
</div>
@using (Html.BeginForm("Import", "Planner", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<b>Target Office 365 Planner Plan:</b>
@Html.DropDownList("PlannerPlan", new SelectList(Model, "Id", "Title"), new {@class = "form-control"});
<br />
<div class="form-group">
<b>Exported Trello Tasks JSON:</b>
<div class="custom-file">
<input type="file" name="file" class="custom-file-input" id="file" accept=".json">
<label class="custom-file-label" for="file">Choose file</label>
</div>
<script>
// Add the following code if you want the name of the file appear on select
$(".custom-file-input").on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
$("#upload").removeAttr("disabled");
});
</script>
<br />
<br />
<button class="btn btn-primary" type="submit" id="upload" disabled>
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" style="display: none" id="loady"></span>
Import
</button>
</div>
}
<script>
(function () {
$('#upload').click(function () {
$('#loady').show();
})
})();
</script>
<|start_filename|>ModernWorkplaceConcierge/Helpers/AutopilotConfiguration.cs<|end_filename|>
using Microsoft.Graph;
using Newtonsoft.Json;
using System;
namespace ModernWorkplaceConcierge.Helpers
{
public class CloudAssignedAadServerData
{
public ZeroTouchConfig ZeroTouchConfig;
public CloudAssignedAadServerData(ZeroTouchConfig zeroTouchConfig)
{
this.ZeroTouchConfig = new ZeroTouchConfig(zeroTouchConfig.CloudAssignedTenantDomain, zeroTouchConfig.ForcedEnrollment);
}
}
public class ZeroTouchConfig
{
public String CloudAssignedTenantUpn;
public int ForcedEnrollment;
public String CloudAssignedTenantDomain;
public ZeroTouchConfig(String CloudAssignedTenantDomain, int ForcedEnrollment)
{
this.CloudAssignedTenantUpn = "";
this.ForcedEnrollment = ForcedEnrollment;
this.CloudAssignedTenantDomain = CloudAssignedTenantDomain;
}
}
public class AutopilotConfiguration
{
//https://docs.microsoft.com/en-us/windows/deployment/windows-autopilot/existing-devices
public String CloudAssignedTenantId;
public String CloudAssignedDeviceName;
public int CloudAssignedForcedEnrollment;
public int Version;
public String Comment_File;
public string CloudAssignedAadServerData;
public int CloudAssignedDomainJoinMethod;
public int CloudAssignedOobeConfig;
public String ZtdCorrelationId;
public String CloudAssignedTenantDomain;
public String CloudAssignedLanguage;
public AutopilotConfiguration(Microsoft.Graph.WindowsAutopilotDeploymentProfile profile, Microsoft.Graph.Organization organization)
{
Comment_File = "Offline Autopilot Profile " + profile.DisplayName;
Version = 2049;
ZtdCorrelationId = profile.Id;
if (profile.ODataType.Equals("#microsoft.graph.activeDirectoryWindowsAutopilotDeploymentProfile"))
{
CloudAssignedDomainJoinMethod = 1;
}
else
{
CloudAssignedDomainJoinMethod = 0;
}
if (profile.DeviceNameTemplate.Length > 0)
{
CloudAssignedDeviceName = profile.DeviceNameTemplate;
}
CloudAssignedOobeConfig = 8 + 256;
if (profile.OutOfBoxExperienceSettings.UserType.Equals("standard"))
{
CloudAssignedOobeConfig += 2;
}
if ((bool)profile.OutOfBoxExperienceSettings.HidePrivacySettings)
{
CloudAssignedOobeConfig += 4;
}
if ((bool)profile.OutOfBoxExperienceSettings.HideEULA)
{
CloudAssignedOobeConfig += 16;
}
if ((bool)profile.OutOfBoxExperienceSettings.SkipKeyboardSelectionPage)
{
CloudAssignedOobeConfig += 1024;
}
if (profile.OutOfBoxExperienceSettings.DeviceUsageType.Equals("shared"))
{
CloudAssignedOobeConfig += 32 + 64;
}
if (profile.Language.Length > 0)
{
CloudAssignedLanguage = profile.Language;
}
if ((bool)profile.OutOfBoxExperienceSettings.HideEscapeLink)
{
CloudAssignedForcedEnrollment = 1;
}
else
{
CloudAssignedForcedEnrollment = 0;
}
CloudAssignedTenantId = organization.Id;
foreach (VerifiedDomain domain in organization.VerifiedDomains)
{
if ((bool)domain.IsDefault)
{
CloudAssignedTenantDomain = domain.Name;
}
}
int hideEscapeLink = 0;
if (profile.OutOfBoxExperienceSettings.HideEscapeLink.HasValue)
{
hideEscapeLink = 1;
}
// Nest a ZeroTouchConfig within the CloudAssignedAadServerData object -> required for the JSON
ZeroTouchConfig touchConfig = new ZeroTouchConfig(CloudAssignedTenantDomain, hideEscapeLink);
CloudAssignedAadServerData zeroTouchConfig = new CloudAssignedAadServerData(touchConfig);
// Serialize ZeroTouchConfig as JSON string
this.CloudAssignedAadServerData = JsonConvert.SerializeObject(zeroTouchConfig,
new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
}
);
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Controllers/AboutController.cs<|end_filename|>
using System.Web.Mvc;
namespace ModernWorkplaceConcierge.Controllers
{
[AllowAnonymous]
public class AboutController : BaseController
{
// GET: About
public ActionResult Index()
{
return View();
}
public ActionResult Terms()
{
return View();
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Views/AutoPilotConfiguration/Index.cshtml<|end_filename|>
@model IEnumerable<Microsoft.Graph.WindowsAutopilotDeploymentProfile>
@{
ViewBag.Current = "IntuneAutoPilotConfiguration";
}
<div class="jumbotron">
<h1>Offline Autopilot Profiles</h1>
<p>Download Windows Autopilot profiles ready for OSD with SCCM, mOSD...</p>
Inject profile during OSD to: <code class="text-dark">%WINDIR%\Provisioning\Autopilot\AutoPilotConfigurationFile.json</code>
</div>
<table class="table table-borderless">
<tr>
<th>
@Html.DisplayNameFor(model => model.DisplayName)
</th>
<th>
@Html.DisplayNameFor(model => model.LastModifiedDateTime)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DisplayName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastModifiedDateTime)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.ActionLink("Details", "Detail", new { id = item.Id }, new { @class = "btn btn-outline-light" })
@Html.ActionLink("Download", "DownloadAutopilotConfigurationJSON", new { id = item.Id }, new { @class = "btn btn-outline-light" })
</td>
</tr>
}
</table>
<|start_filename|>ModernWorkplaceConcierge/Views/Intune/_PowerShellScriptContent.cshtml<|end_filename|>
@model string
@Html.Raw(Model)
<|start_filename|>ModernWorkplaceConcierge/Helpers/GraphClient.cs<|end_filename|>
using Microsoft.Graph;
using Microsoft.Identity.Client;
using ModernWorkplaceConcierge.TokenStorage;
using System.Configuration;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Web;
namespace ModernWorkplaceConcierge.Helpers
{
public class GraphClient
{
// Load configuration settings from PrivateSettings.config
protected static readonly string appId = ConfigurationManager.AppSettings["AppId"];
protected static readonly string appSecret = ConfigurationManager.AppSettings["AppSecret"];
protected static readonly string redirectUri = ConfigurationManager.AppSettings["RedirectUri"];
protected static readonly string graphScopes = ConfigurationManager.AppSettings["AppScopes"];
public static readonly string graphEndpoint = ConfigurationManager.AppSettings["GraphEndpoint"];
protected GraphServiceClient GetAuthenticatedClient()
{
return new Microsoft.Graph.GraphServiceClient(
new Microsoft.Graph.DelegateAuthenticationProvider(
async (requestMessage) =>
{
var idClient = ConfidentialClientApplicationBuilder.Create(appId)
.WithRedirectUri(redirectUri)
.WithClientSecret(appSecret)
.Build();
var tokenStore = new SessionTokenStore(idClient.UserTokenCache,
HttpContext.Current, ClaimsPrincipal.Current);
var accounts = await idClient.GetAccountsAsync();
// By calling this here, the token can be refreshed
// if it's expired right before the Graph call is made
var scopes = graphScopes.Split(' ');
var result = await idClient.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.ExecuteAsync();
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
}
)
);
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Helpers/FilenameHelper.cs<|end_filename|>
using System.Text.RegularExpressions;
namespace ModernWorkplaceConcierge.Helpers
{
public class FilenameHelper
{
public static string ProcessFileName(string input)
{
Regex illegalInFileName = new Regex(@"[\\/:*?""<>|]");
return illegalInFileName.Replace(input, "");
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Controllers/IntuneController.cs<|end_filename|>
using Microsoft.Graph;
using ModernWorkplaceConcierge.Helpers;
using ModernWorkplaceConcierge.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace ModernWorkplaceConcierge.Controllers
{
[System.Web.Mvc.Authorize]
public class IntuneController : BaseController
{
private List<string> supportedFolders = new List<string>();
public ActionResult Import()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Upload(HttpPostedFileBase[] files, OverwriteBehaviour overwriteBehaviour, string clientId)
{
SignalRMessage signalR = new SignalRMessage(clientId);
supportedFolders.Add("WindowsAutopilotDeploymentProfile");
supportedFolders.Add("DeviceConfiguration");
supportedFolders.Add("DeviceCompliancePolicy");
supportedFolders.Add("DeviceManagementScript");
supportedFolders.Add("ManagedAppPolicy");
supportedFolders.Add("RoleDefinition");
try
{
GraphIntuneImport graphIntuneImport = new GraphIntuneImport(clientId, overwriteBehaviour);
if (files.Length > 0 && files[0].FileName.Contains(".json"))
{
foreach (HttpPostedFileBase file in files)
{
try
{
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);
string result = Encoding.UTF8.GetString(binData);
await graphIntuneImport.AddIntuneConfig(result);
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e.Message);
}
}
}
else if (files.Length > 0 && files[0].FileName.Contains(".zip"))
{
try
{
Dictionary<string, string> importFiles = new Dictionary<string, string>();
MemoryStream target = new MemoryStream();
files[0].InputStream.CopyTo(target);
byte[] data = target.ToArray();
using (var zippedStream = new MemoryStream(data))
{
using (var archive = new ZipArchive(zippedStream))
{
foreach (var entry in archive.Entries)
{
try
{
if (entry != null)
{
using (var unzippedEntryStream = entry.Open())
{
using (var ms = new MemoryStream())
{
unzippedEntryStream.CopyTo(ms);
var unzippedArray = ms.ToArray();
string result = Encoding.UTF8.GetString(unzippedArray);
if (!string.IsNullOrEmpty(result))
{
// Check if key exists
// Only the case because of enrollment restrictions coming with no value
if (importFiles.ContainsKey(entry.FullName))
{
Random r = new Random();
importFiles.Add(entry.FullName + r.Next(), result);
}
else
{
importFiles.Add(entry.FullName, result);
}
}
}
}
}
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e.Message);
}
}
}
}
// First create all scope tags
foreach (KeyValuePair<string, string> entry in importFiles)
{
if (entry.Key.Contains("RoleScopeTags"))
{
await graphIntuneImport.AddIntuneScopeTag(entry.Value);
}
}
// Process all remaining intune objects
foreach (KeyValuePair<string, string> entry in importFiles)
{
// Verify folder name
if (supportedFolders.Contains(entry.Key.Split('\\')[0]))
{
await graphIntuneImport.AddIntuneConfig(entry.Value);
}
}
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e.Message);
}
}
else if (files.Length > 0)
{
signalR.sendMessage("Error unsupported file: " + files[0].FileName);
}
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e.Message);
}
signalR.sendMessage("Done#!");
return new HttpStatusCodeResult(204);
}
// GET: Export
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> DeviceManagementScripts()
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
var scripts = await graphIntune.GetDeviceManagementScriptsAsync();
return View(scripts);
}
catch (ServiceException e)
{
Flash(e.Error.Message);
return RedirectToAction("Index", "Home");
}
}
public async Task<ActionResult> Win32AppDetectionScripts()
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
var apps = await graphIntune.GetWin32MobileAppsAsync();
List<Win32LobApp> win32LobApps = new List<Win32LobApp>();
foreach (Win32LobApp app in apps)
{
var details = await graphIntune.GetWin32MobileAppAsync(app.Id);
if (details.DetectionRules.Any(d => d is Win32LobAppPowerShellScriptDetection))
{
win32LobApps.Add(details);
}
}
return View(win32LobApps);
}
catch (ServiceException e)
{
Flash(e.Error.Message);
return RedirectToAction("Index", "Home");
}
}
public async Task<ActionResult> Win32AppPsDetectionScriptContent(string Id)
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
var script = await graphIntune.GetWin32MobileAppPowerShellDetectionRuleAsync(Id);
string powerShellCode = Encoding.UTF8.GetString(Convert.FromBase64String(script.ScriptContent));
return PartialView("_PowerShellDetectionScriptContent", powerShellCode);
}
catch (ServiceException e)
{
Flash(e.Error.Message);
return RedirectToAction("Index", "Home");
}
}
public async Task<ActionResult> DownloadDetectionScript(string Id)
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
Win32LobApp win32LobApp = await graphIntune.GetWin32MobileAppAsync(Id);
Win32LobAppPowerShellScriptDetection script = await graphIntune.GetWin32MobileAppPowerShellDetectionRuleAsync(Id);
string fileName = $"{FilenameHelper.ProcessFileName(win32LobApp.DisplayName)}_detect.ps1";
return File(Convert.FromBase64String(script.ScriptContent), "text/plain", fileName);
}
catch (ServiceException e)
{
Flash(e.Error.Message);
return RedirectToAction("Index", "Home");
}
}
public async Task<ActionResult> PowerShellScriptContent(string Id)
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
var scripts = await graphIntune.GetDeviceManagementScriptAsync(Id);
string powerShellCode = Encoding.UTF8.GetString(scripts.ScriptContent);
return PartialView("_PowerShellScriptContent", powerShellCode);
}
catch (ServiceException e)
{
Flash(e.Error.Message);
return RedirectToAction("Index", "Home");
}
}
public async Task<ActionResult> DownloadDeviceManagementScript(String Id)
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
DeviceManagementScript script = await graphIntune.GetDeviceManagementScriptAsync(Id);
return File(script.ScriptContent, "text/plain", script.FileName);
}
catch (ServiceException e)
{
Flash(e.Error.Message);
return RedirectToAction("Index", "Home");
}
}
public async Task<ActionResult> ClearAll(bool confirm = false)
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
if (confirm)
{
await graphIntune.ClearIntuneTenant();
}
return new HttpStatusCodeResult(204);
}
catch (Exception e)
{
Flash(e.Message);
return RedirectToAction("Index", "Home");
}
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Helpers/GraphHelper.cs<|end_filename|>
using Microsoft.AspNet.SignalR;
using Microsoft.Graph;
using Microsoft.Identity.Client;
using ModernWorkplaceConcierge.TokenStorage;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
namespace ModernWorkplaceConcierge.Helpers
{
public static class GraphHelper
{
// Load configuration settings from PrivateSettings.config
private static readonly string appId = ConfigurationManager.AppSettings["AppId"];
private static readonly string appSecret = ConfigurationManager.AppSettings["AppSecret"];
private static readonly string redirectUri = ConfigurationManager.AppSettings["RedirectUri"];
private static readonly string graphScopes = ConfigurationManager.AppSettings["AppScopes"];
private static readonly string graphEndpoint = ConfigurationManager.AppSettings["GraphEndpoint"];
public static async Task<User> GetUser(string displayName, string clientId = null)
{
var graphClient = GetAuthenticatedClient();
if (!string.IsNullOrEmpty(clientId))
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MwHub>();
hubContext.Clients.Client(clientId).addMessage("GET: " + graphClient.Users.Request().Filter($"startsWith(displayName,'{displayName}')").RequestUrl);
}
var response = await graphClient
.Users
.Request()
.Filter($"startsWith(displayName,'{displayName}')")
.GetAsync();
return response.CurrentPage.First();
}
public static async Task<Group> CreateGroup(string displayName, string clientId = null)
{
var graphClient = GetAuthenticatedClient();
if (!string.IsNullOrEmpty(clientId))
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MwHub>();
hubContext.Clients.Client(clientId).addMessage("POST: " + graphClient.Groups.Request().RequestUrl);
}
// Check if group not already exists
try
{
var check = await graphClient.Groups.Request().Filter($"displayName eq '{displayName}'").GetAsync();
if (check.FirstOrDefault() != null && check.FirstOrDefault().Id != null)
{
if (!string.IsNullOrEmpty(clientId))
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MwHub>();
hubContext.Clients.Client(clientId).addMessage("Warning AAD Group with name: '" + displayName + "' already exists!");
}
return check.CurrentPage.FirstOrDefault();
}
}
catch (System.Exception)
{
}
Group group = new Group();
group.SecurityEnabled = true;
group.DisplayName = displayName;
group.Description = "Created with the ModernWorkplaceConcierge";
group.MailEnabled = false;
group.MailNickname = displayName;
var respGroup = await graphClient.Groups.Request().AddAsync(group);
return respGroup;
}
public static async Task<Group> GetGroup(string Id, string clientId = null)
{
var graphClient = GetAuthenticatedClient();
if (!string.IsNullOrEmpty(clientId))
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MwHub>();
hubContext.Clients.Client(clientId).addMessage("GET: " + graphClient.Groups[Id].Request().RequestUrl);
}
var group = await graphClient.Groups[Id].Request().GetAsync();
return group;
}
public static async Task<IEnumerable<DirectoryRoleTemplate>> GetDirectoryRoleTemplates(string clientId = null)
{
var graphClient = GetAuthenticatedClient();
if (!string.IsNullOrEmpty(clientId))
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MwHub>();
hubContext.Clients.Client(clientId).addMessage("GET: " + graphClient.DirectoryRoleTemplates.Request().RequestUrl);
}
var roles = await graphClient.DirectoryRoleTemplates.Request().GetAsync();
return roles.CurrentPage;
}
public static async Task<IEnumerable<ServicePrincipal>> GetServicePrincipals(string clientId = null)
{
var graphClient = GetAuthenticatedClient();
if (!string.IsNullOrEmpty(clientId))
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MwHub>();
hubContext.Clients.Client(clientId).addMessage("GET: " + graphClient.ServicePrincipals.Request().RequestUrl);
}
var servicePrincipals = await graphClient.ServicePrincipals.Request().GetAsync();
return servicePrincipals.CurrentPage;
}
public static async Task<User> GetUserById(string Id, string clientId = null)
{
var graphClient = GetAuthenticatedClient();
if (!string.IsNullOrEmpty(clientId))
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MwHub>();
hubContext.Clients.Client(clientId).addMessage("GET: " + graphClient.Users[Id].Request().RequestUrl);
}
var user = await graphClient.Users[Id].Request().GetAsync();
return user;
}
public static async Task<Organization> GetOrgDetailsAsync(string clientId = null)
{
var graphClient = GetAuthenticatedClient();
if (!string.IsNullOrEmpty(clientId))
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MwHub>();
hubContext.Clients.Client(clientId).addMessage("GET: " + graphClient.Organization.Request().RequestUrl);
}
var org = await graphClient.Organization.Request().GetAsync();
Organization organization = org.CurrentPage.First();
return organization;
}
public static async Task<string> GetDefaultDomain(string clientId = null)
{
Organization organization = await GetOrgDetailsAsync(clientId);
string verifiedDomain = organization.VerifiedDomains.First().Name;
foreach (VerifiedDomain domain in organization.VerifiedDomains)
{
if ((bool)domain.IsDefault)
{
verifiedDomain = domain.Name;
}
}
return verifiedDomain;
}
public static async Task<User> GetUserDetailsAsync(string accessToken)
{
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
}));
return await graphClient.Me.Request().GetAsync();
}
public static async Task<byte[]> GetUserPhotoAsync(string accessToken)
{
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
}));
var content = await graphClient.Me.Photo.Content.Request().GetAsync();
byte[] bytes = new byte[content.Length];
content.Read(bytes, 0, (int)content.Length);
return bytes;
}
private static GraphServiceClient GetAuthenticatedClient()
{
return new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var idClient = ConfidentialClientApplicationBuilder.Create(appId)
.WithRedirectUri(redirectUri)
.WithClientSecret(appSecret)
.Build();
var tokenStore = new SessionTokenStore(idClient.UserTokenCache,
HttpContext.Current, ClaimsPrincipal.Current);
var accounts = await idClient.GetAccountsAsync();
// By calling this here, the token can be refreshed
// if it's expired right before the Graph call is made
var scopes = graphScopes.Split(' ');
var result = await idClient.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.ExecuteAsync();
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
}));
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Helpers/AdministrativeTemplateExport.cs<|end_filename|>
using Microsoft.Graph;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Ajax.Utilities;
namespace ModernWorkplaceConcierge.Helpers
{
public class AdministrativeTemplateExport
{
private GraphIntune graphIntune;
public AdministrativeTemplateExport(GraphIntune graphIntune)
{
this.graphIntune = graphIntune;
}
public async Task<List<JObject>> GetExportableGroupPolicies()
{
// List for exported admx templates
List<JObject> administrativeTemplates = new List<JObject>();
// Process Administrative Templates
var gpos = await graphIntune.GetGroupPolicyConfigurationsAsync();
foreach (GroupPolicyConfiguration gpo in gpos)
{
// 2. Configured settings
var values = await graphIntune.GetGroupPolicyDefinitionValuesAsync(gpo.Id);
JObject administrativeTemplate = JObject.FromObject(gpo);
JArray settings = new JArray();
// 3. Configured Values
foreach (GroupPolicyDefinitionValue value in values)
{
var groupPolicyDefinition = await graphIntune.GetGroupPolicyDefinitionValueAsync(gpo.Id, value.Id);
var res = await graphIntune.GetGroupPolicyPresentationValuesAsync(gpo.Id, value.Id);
JObject jObject = new JObject
{
// Link setting to field
{ "definition@<EMAIL>", $"https://graph.microsoft.com/beta/deviceManagement/groupPolicyDefinitions('{groupPolicyDefinition.Id}')" },
{ "enabled", value.Enabled }
};
JArray jArray = new JArray();
// We need a type cast to access value property of GroupPolicyPresentationValue
foreach (GroupPolicyPresentationValue presentationValue in res)
{
JObject val = new JObject
{
{ "@odata.type", presentationValue.ODataType }
};
if (presentationValue is GroupPolicyPresentationValueBoolean)
{
val.Add("value", ((GroupPolicyPresentationValueBoolean)presentationValue).Value);
}
else if (presentationValue is GroupPolicyPresentationValueDecimal)
{
val.Add("value", ((GroupPolicyPresentationValueDecimal)presentationValue).Value);
}
else if (presentationValue is GroupPolicyPresentationValueList)
{
JArray valueList = new JArray();
foreach (KeyValuePair valueListEntry in ((GroupPolicyPresentationValueList)presentationValue).Values)
{
JObject valueEntry = new JObject
{
{ "name", valueListEntry.Name },
{ "value", valueListEntry.Value }
};
valueList.Add(valueEntry);
}
val.Add("values", valueList);
}
else if (presentationValue is GroupPolicyPresentationValueLongDecimal)
{
val.Add("value", ((GroupPolicyPresentationValueLongDecimal)presentationValue).Value);
}
else if (presentationValue is GroupPolicyPresentationValueMultiText)
{
JArray valueList = new JArray();
((GroupPolicyPresentationValueMultiText)presentationValue).Values.ForEach(stringValue => valueList.Add(stringValue));
val.Add("values", valueList);
}
else if (presentationValue is GroupPolicyPresentationValueText)
{
val.Add("value", ((GroupPolicyPresentationValueText)presentationValue).Value);
}
// Binds configured value to settings id
val.Add("presentation<EMAIL>", $"https://graph.microsoft.com/beta/deviceManagement/groupPolicyDefinitions('{groupPolicyDefinition.Id}')/presentations('{presentationValue.Presentation.Id}')");
jArray.Add(val);
}
jObject.Add("presentationValues", jArray);
settings.Add(jObject);
}
administrativeTemplate.Add("configuredSettings", settings);
administrativeTemplates.Add(administrativeTemplate);
}
return administrativeTemplates;
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Startup.cs<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(ModernWorkplaceConcierge.Startup))]
namespace ModernWorkplaceConcierge
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
ConfigureAuth(app);
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Helpers/GraphPlanner.cs<|end_filename|>
using Microsoft.Graph;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ModernWorkplaceConcierge.Helpers
{
public class GraphPlanner : GraphClient
{
private string clientId;
private GraphServiceClient graphServiceClient;
private SignalRMessage signalRMessage;
public GraphPlanner(string clientId)
{
this.clientId = clientId;
this.signalRMessage = new SignalRMessage(clientId);
this.graphServiceClient = GetAuthenticatedClient();
}
public async Task<PlannerBucket> AddPlannerBucketAsync(PlannerBucket plannerBucket)
{
signalRMessage.sendMessage($"POST: {graphServiceClient.Planner.Buckets.Request().RequestUrl}");
var response = await graphServiceClient.Planner.Buckets.Request().AddAsync(plannerBucket);
return response;
}
public async Task<PlannerTask> AddPlannerTaskAsync(PlannerTask plannerTask)
{
signalRMessage.sendMessage($"POST: {graphServiceClient.Planner.Tasks.Request().RequestUrl}");
var response = await graphServiceClient.Planner.Tasks.Request().AddAsync(plannerTask);
return response;
}
public async Task<PlannerTaskDetails> AddPlannerTaskDetailsAsync(PlannerTaskDetails plannerTaskDetails, string taskId)
{
signalRMessage.sendMessage($"GET: {graphServiceClient.Planner.Tasks[taskId].Details.Request().RequestUrl}");
var originalTaskDescription = await graphServiceClient.Planner.Tasks[taskId].Details.Request().GetAsync();
signalRMessage.sendMessage($"PATCH: {graphServiceClient.Planner.Tasks[taskId].Details.Request().Header("If-Match", originalTaskDescription.GetEtag()).RequestUrl}");
var response = await graphServiceClient.Planner.Tasks[taskId].Details.Request().Header("If-Match", originalTaskDescription.GetEtag()).UpdateAsync(plannerTaskDetails);
return response;
}
public async Task<IEnumerable<PlannerBucket>> GetPlannerBucketsAsync(string planId)
{
signalRMessage.sendMessage($"GET: {graphServiceClient.Planner.Plans[planId].Buckets.Request().RequestUrl}");
var response = await graphServiceClient.Planner.Plans[planId].Buckets.Request().GetAsync();
return response.CurrentPage;
}
public async Task<PlannerPlan> GetplannerPlanAsync(string id)
{
signalRMessage.sendMessage($"GET: {graphServiceClient.Planner.Plans[id].Request().RequestUrl}");
var response = await graphServiceClient.Planner.Plans[id].Request().GetAsync();
return response;
}
public async Task<IEnumerable<PlannerPlan>> GetplannerPlansAsync()
{
signalRMessage.sendMessage($"GET: {graphServiceClient.Me.Planner.Plans.Request().RequestUrl}");
var response = await graphServiceClient.Me.Planner.Plans.Request().GetAsync();
return response.CurrentPage;
}
public async Task<PlannerTaskDetails> GetPlannerTaskDetailsAsync(string taskId)
{
signalRMessage.sendMessage($"GET: {graphServiceClient.Planner.Tasks[taskId].Details.Request().RequestUrl}");
var response = await graphServiceClient.Planner.Tasks[taskId].Details.Request().GetAsync();
return response;
}
}
}
<|start_filename|>ModernWorkplaceConcierge/TokenStorage/SessionTokenStore.cs<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using Microsoft.Identity.Client;
using Newtonsoft.Json;
using System.Security.Claims;
using System.Threading;
using System.Web;
namespace ModernWorkplaceConcierge.TokenStorage
{
// Simple class to serialize into the session
public class CachedUser
{
public string DisplayName { get; set; }
public string Email { get; set; }
public string Avatar { get; set; }
public string TenantID { get; set; }
}
public class SessionTokenStore
{
private static readonly ReaderWriterLockSlim sessionLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
private HttpContext httpContext = null;
private string tokenCacheKey = string.Empty;
private string userCacheKey = string.Empty;
public SessionTokenStore(ITokenCache tokenCache, HttpContext context, ClaimsPrincipal user)
{
httpContext = context;
if (tokenCache != null)
{
tokenCache.SetBeforeAccess(BeforeAccessNotification);
tokenCache.SetAfterAccess(AfterAccessNotification);
}
var userId = GetUsersUniqueId(user);
tokenCacheKey = $"{userId}_TokenCache";
userCacheKey = $"{userId}_UserCache";
}
public bool HasData()
{
return (httpContext.Session[tokenCacheKey] != null &&
((byte[])httpContext.Session[tokenCacheKey]).Length > 0);
}
public void Clear()
{
sessionLock.EnterWriteLock();
try
{
httpContext.Session.Remove(tokenCacheKey);
}
finally
{
sessionLock.ExitWriteLock();
}
}
private void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
sessionLock.EnterReadLock();
try
{
// Load the cache from the session
args.TokenCache.DeserializeMsalV3((byte[])httpContext.Session[tokenCacheKey]);
}
finally
{
sessionLock.ExitReadLock();
}
}
private void AfterAccessNotification(TokenCacheNotificationArgs args)
{
if (args.HasStateChanged)
{
sessionLock.EnterWriteLock();
try
{
// Store the serialized cache in the session
httpContext.Session[tokenCacheKey] = args.TokenCache.SerializeMsalV3();
}
finally
{
sessionLock.ExitWriteLock();
}
}
}
public void SaveUserDetails(CachedUser user)
{
sessionLock.EnterWriteLock();
httpContext.Session[userCacheKey] = JsonConvert.SerializeObject(user);
sessionLock.ExitWriteLock();
}
public CachedUser GetUserDetails()
{
sessionLock.EnterReadLock();
var cachedUser = JsonConvert.DeserializeObject<CachedUser>((string)httpContext.Session[userCacheKey]);
sessionLock.ExitReadLock();
return cachedUser;
}
private string GetUsersUniqueId(ClaimsPrincipal user)
{
// Combine the user's object ID with their tenant ID
if (user != null)
{
var userObjectId = user.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value ??
user.FindFirst("oid").Value;
var userTenantId = user.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value ??
user.FindFirst("tid").Value;
if (!string.IsNullOrEmpty(userObjectId) && !string.IsNullOrEmpty(userTenantId))
{
return $"{userObjectId}.{userTenantId}";
}
}
return null;
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Helpers/GraphJson.cs<|end_filename|>
using Newtonsoft.Json;
namespace ModernWorkplaceConcierge.Helpers
{
public class GraphJson
{
[JsonProperty("@odata.type", NullValueHandling = NullValueHandling.Ignore)]
public string OdataType { get; set; }
[JsonProperty("@odata.context", NullValueHandling = NullValueHandling.Ignore)]
public string OdataValue { get { return OdataType; } set { OdataType = value; } }
}
}
<|start_filename|>ModernWorkplaceConcierge/Helpers/AzureADApplicationIdentifiers.cs<|end_filename|>
using System.Collections.Generic;
namespace ModernWorkplaceConcierge.Helpers
{
public static class AzureADApplicationIdentifiers
{
public static IDictionary<string, string> keyValuePairs = new Dictionary<string, string>()
{
{"00000004-0000-0ff1-ce00-000000000000", "Microsoft.Lync"},
{"00000006-0000-0ff1-ce00-000000000000", "Microsoft.Office365Portal"},
{"00000003-0000-0ff1-ce00-000000000000", "Microsoft.SharePoint"},
{"00000005-0000-0000-c000-000000000000", "Microsoft.Azure.Workflow"},
{"00000009-0000-0000-c000-000000000000", "Microsoft.Azure.AnalysisServices"},
{"00000002-0000-0ff1-ce00-000000000000", "Microsoft.Exchange"},
{"00000007-0000-0ff1-ce00-000000000000", "Microsoft.ExchangeOnlineProtection"},
{"00000002-0000-0000-c000-000000000000", "Microsoft.Azure.ActiveDirectory"},
{"8fca0a66-c008-4564-a876-ab3ae0fd5cff", "Microsoft.SMIT"},
{"0000000b-0000-0000-c000-000000000000", "Microsoft.SellerDashboard"},
{"0000000f-0000-0000-c000-000000000000", "Microsoft.Azure.GraphExplorer"},
{"0000000c-0000-0000-c000-000000000000", "MicrosoftAppAccessPanel"},
{"00000013-0000-0000-c000-000000000000", "Microsoft.Azure.Portal"},
{"00000010-0000-0000-c000-000000000000", "Microsoft.Azure.GraphStore"},
{"93ee9413-cf4c-4d4e-814b-a91ff20a01bd", "Workflow"},
{"aa9ecb1e-fd53-4aaa-a8fe-7a54de2c1334", "Microsoft.Office365.Configure"},
{"797f4846-ba00-4fd7-ba43-dac1f8f63013", "WindowsAzureServiceManagementAPI"},
{"00000005-0000-0ff1-ce00-000000000000", "Microsoft.YammerEnterprise"},
{"601d4e27-7bb3-4dee-8199-90d47d527e1c", "Microsoft.Office365.ChangeManagement"},
{"6f82282e-0070-4e78-bc23-e6320c5fa7de", "Microsoft.DiscoveryService"},
{"0f698dd4-f011-4d23-a33e-b36416dcb1e6", "Microsoft.OfficeClientService"},
{"67e3df25-268a-4324-a550-0de1c7f97287", "Microsoft.OfficeWebAppsService"},
{"ab27a73e-a3ba-4e43-8360-8bcc717114d8", "Microsoft.OfficeModernCalendar"},
{"aedca418-a84d-430d-ab84-0b1ef06f318f", "Workflow"},
{"595d87a1-277b-4c0a-aa7f-44f8a068eafc", "Microsoft.SupportTicketSubmission"},
{"e3583ad2-c781-4224-9b91-ad15a8179ba0", "Microsoft.ExtensibleRealUserMonitoring"},
{"b645896d-566e-447e-8f7f-e2e663b5d182", "OpsDashSharePointApp"},
{"48229a4a-9f1d-413a-8b96-4c02462c0360", "OpsDashSharePointApp"},
{"48717084-a59c-4306-9dc4-3f618dbecdf9", "Office365DevelopmentTools"},
{"c859ff33-eb41-4ba6-8093-a2c5153bbd7c", "Workflow"},
{"67cad61c-3411-48d7-ab73-561c64f11ed6", "Workflow"},
{"914ed757-9257-4200-b68e-a2bed2f12c5a", "RbacBackfill"},
{"499b84ac-1321-427f-aa17-267ca6975798", "Microsoft.VisualStudio.Online"},
{"b2590339-0887-4e94-93aa-13357eb510d7", "Workflow"},
{"0000001b-0000-0000-c000-000000000000", "MicrosoftPowerBIInformationService"},
{"89f80565-bfac-4c01-9535-9f0eba332ffe", "PowerBI"},
{"433895fb-4ec7-45c3-a53c-c44d10f80d5b", "CompromisedAccountService"},
{"d7c17728-4f1e-4a1e-86cf-7e0adf3fe903", "Workflow"},
{"17ef6d31-381f-4783-b186-7b440a3c85c1", "Workflow"},
{"00000012-0000-0000-c000-000000000000", "Microsoft.Azure.RMS"},
{"81ce94d4-9422-4c0d-a4b9-3250659366ce", "Workflow"},
{"8d3a7d3c-c034-4f19-a2ef-8412952a9671", "MicrosoftOffice"},
{"0469d4cd-df37-4d93-8a61-f8c75b809164", "MicrosoftPolicyAdministrationService"},
{"31d3f3f5-7267-45a8-9549-affb00110054", "WindowsAzureRemoteAppService"},
{"4e004241-32db-46c2-a86f-aaaba29bea9c", "Workflow"},
{"748d098e-7a3b-436d-8b0a-006a58b29647", "Workflow"},
{"dbf08535-1d3b-4f89-bf54-1d48dd613a61", "Workflow"},
{"ed9fe1ef-25a4-482f-9981-2b60f91e2448", "Workflow"},
{"8ad28d50-ee26-42fc-8a29-e41ea38461f2", "Office365RESTAPIExplorer.Office365App"},
{"38285dce-a13d-4107-9b04-3016b941bb3a", "BasicDataOperationsREST"},
{"92bb96c8-321c-47f9-bcc5-8849490c2b07", "BasicSelfHostedAppREST"},
{"488a57a0-00e2-4817-8c8d-cf8a15a994d2", "WindowsFormsApplication2.Office365App"},
{"11c174dc-1945-4a9a-a36b-c79a0f246b9b", "AzureApplicationInsights"},
{"e6acb561-0d94-4287-bd3a-3169f421b112", "Tutum"},
{"7b77b3a2-8490-49e1-8842-207cd0899af9", "Nearpod"},
{"0000000a-0000-0000-c000-000000000000", "Microsoft.Intune"},
{"93625bc8-bfe2-437a-97e0-3d0060024faa", "SelfServicePasswordReset"},
{"dee7ba80-6a55-4f3b-a86c-746a9231ae49", "MicrosoftAppPlatEMA"},
{"803ee9ca-3f7f-4824-bd6e-0b99d720c35c", "AzureMediaService"},
{"2d4d3d8e-2be3-4bef-9f87-7875a61c29de", "OneNote"},
{"8d40666e-5abf-45f6-a5e7-b7192d6d56ed", "Workflow"},
{"262044b1-e2ce-469f-a196-69ab7ada62d3", "BackupManagementService"},
{"087a2c70-c89e-463f-8dd3-e3959eabb1a9", "MicrosoftProfileServicePlatformService"},
{"7cd684f4-8a78-49b0-91ec-6a35d38739ba", "AzureLogicApps"},
{"c5393580-f805-4401-95e8-94b7a6ef2fc2", "Office365ManagementAPIs"},
{"96231a05-34ce-4eb4-aa6a-70759cbb5e83", "MicrosoftAzureRedisCache"},
{"b8340c3b-9267-498f-b21a-15d5547fd85e", "Hyper-VRecoveryManager"},
{"abfa0a7c-a6b6-4736-8310-5855508787cd", "Microsoft.Azure.WebSites"},
{"c44b4083-3bb0-49c1-b47d-974e53cbdf3c", "IbizaPortal"},
{"905fcf26-4eb7-48a0-9ff0-8dcc7194b5ba", "Sway"},
{"b10686fd-6ba8-49f2-a3cd-67e4d2f52ac8", "NovoEd"},
{"c606301c-f764-4e6b-aa45-7caaaea93c9a", "OfficeStore"},
{"569e8598-685b-4ba2-8bff-5bced483ac46", "Evercontact"},
{"20a23a2f-8c32-4de7-8063-8c8f909602c0", "Workflow"},
{"aaf214cc-8013-4b95-975f-13203ae36039", "PowerBITiles"},
{"d88a361a-d488-4271-a13f-a83df7dd99c2", "IDMLGraphResolverServiceandCAD"},
{"dff9b531-6290-4620-afce-26826a62a4e7", "DocuSign"},
{"01cb2876-7ebd-4aa4-9cc9-d28bd4d359a9", "DeviceRegistrationService"},
{"3290e3f7-d3ac-4165-bcef-cf4874fc4270", "Smartsheet"},
{"a4ee6867-8640-4495-b1fd-8b26037a5bd3", "Workflow"},
{"aa0e3dd4-df02-478d-869e-fc61dd71b6e8", "Workflow"},
{"0f6edad5-48f2-4585-a609-d252b1c52770", "AIGraphClient"},
{"0c8139b5-d545-4448-8d2b-2121bb242680", "BillingExtension"},
{"475226c6-020e-4fb2-8a90-7a972cbfc1d4", "KratosAppsService"},
{"39624784-6cbe-4a60-afbe-9f46d10fdb27", "SkypeForBusinessRemotePowershell"},
{"8bdebf23-c0fe-4187-a378-717ad86f6a53", "ResourceHealthRP"},
{"c161e42e-d4df-4a3d-9b42-e7a3c31f59d4", "MicrosoftIntuneAPI"},
{"9cb77803-d937-493e-9a3b-4b49de3f5a74", "MicrosoftIntuneServiceDiscovery"},
{"ddbf3205-c6bd-46ae-8127-60eb93363864", "MicrosoftAzureBatch"},
{"80ccca67-54bd-44ab-8625-4b79c4dc7775", "ComplianceCenter"},
{"0a5f63c0-b750-4f38-a71c-4fc0d58b89e2", "MicrosoftMobileApplicationManagement"},
{"e1335bb1-2aec-4f92-8140-0e6e61ae77e5", "CIWebService"},
{"75018fbe-21fe-4a57-b63c-83252b5eaf16", "TeamImprover-TeamOrganizationChart"},
{"a393296b-5695-4463-97cb-9fa8638a494a", "MySharePointSites"},
{"fe217466-5583-431c-9531-14ff7268b7b3", "MicrosoftEducation"},
{"5bfe8a29-054e-4348-9e7a-3981b26b125f", "BingPlacesforBusiness"},
{"eaf8a961-f56e-47eb-9ffd-936e22a554ef", "DevilFish"},
{"4b4b1d56-1f03-47d9-a0a3-87d4afc913c9", "Wunderlist"},
{"00000003-0000-0000-c000-000000000000", "MicrosoftGraph"},
{"60e6cd67-9c8c-4951-9b3c-23c25a2169af", "ComputeResourceProvider"},
{"507bc9da-c4e2-40cb-96a7-ac90df92685c", "Office365Reports"},
{"09abbdfd-ed23-44ee-a2d9-a627aa1c90f3", "ProjectWorkManagement"},
{"28ec9756-deaf-48b2-84d5-a623b99af263", "OfficePersonalAssistantatWorkService"},
{"9e4a5442-a5c9-4f6f-b03f-5b9fcaaf24b1", "OfficeServicesManager"},
{"3138fe80-4087-4b04-80a6-8866c738028a", "SharePointNotificationService"},
{"d2a0a418-0aac-4541-82b2-b3142c89da77", "MicrosoftAzureOperationalInsights"},
{"2cf9eb86-36b5-49dc-86ae-9a63135dfa8c", "AzureTrafficManagerandDNS"},
{"32613fc5-e7ac-4894-ac94-fbc39c9f3e4a", "OAuthSandbox"},
{"925eb0d0-da50-4604-a19f-bd8de9147958", "GroupiesWebService"},
{"e4ab13ed-33cb-41b4-9140-6e264582cf85", "AzureSQLDatabaseBackupToAzureBackupVault"},
{"ad230543-afbe-4bb4-ac4f-d94d101704f8", "ApiaryforPowerBI"},
{"11cd3e2e-fccb-42ad-ad00-878b93575e07", "AutomatedCallDistribution"},
{"de17788e-c765-4d31-aba4-fb837cfff174", "SkypeforBusinessManagementReportingandAnalytics"},
{"65d91a3d-ab74-42e6-8a2f-0add61688c74", "MicrosoftApprovalManagement"},
{"5225545c-3ebd-400f-b668-c8d78550d776", "OfficeAgentService"},
{"1cda9b54-9852-4a5a-96d4-c2ab174f9edf", "O365Account"},
{"4747d38e-36c5-4bc3-979b-b0ef74df54d1", "PushChannel"},
{"b97b6bd4-a49f-4a0c-af18-af507d1da76c", "OfficeShreddingService"},
{"d4ebce55-015a-49b5-a083-c84d1797ae8c", "MicrosoftIntuneEnrollment"},
{"5b20c633-9a48-4a5f-95f6-dae91879051f", "AzureInformationProtection"},
{"441509e5-a165-4363-8ee7-bcf0b7d26739", "EnterpriseAgentPlatform"},
{"e691bce4-6612-4025-b94c-81372a99f77e", "Boomerang"},
{"8edd93e1-2103-40b4-bd70-6e34e586362d", "WindowsAzureSecurityResourceProvider"},
{"94c63fef-13a3-47bc-8074-75af8c65887a", "OfficeDelve"},
{"e95d8bee-4725-4f59-910d-94d415da51b9", "SkypeforBusinessNameDictionaryService"},
{"e3c5dbcd-bb5f-4bda-b943-adc7a5bbc65e", "Workflow"},
{"8602e328-9b72-4f2d-a4ae-1387d013a2b3", "AzureAPIManagement"},
{"8b3391f4-af01-4ee8-b4ea-9871b2499735", "O365SecureScore"},
{"c26550d6-bc82-4484-82ca-ac1c75308ca3", "Office365YammerOnOls"},
{"33be1cef-03fb-444b-8fd3-08ca1b4d803f", "OneDriveWeb"},
{"dcad865d-9257-4521-ad4d-bae3e137b345", "MicrosoftSharePointOnline-SharePointHome"},
{"b2cc270f-563e-4d8a-af47-f00963a71dcd", "OneProfileService"},
{"4660504c-45b3-4674-a709-71951a6b0763", "MicrosoftInvitationAcceptancePortal"},
{"ba23cd2a-306c-48f2-9d62-d3ecd372dfe4", "OfficeGraph"},
{"d52485ee-4609-4f6b-b3a3-68b6f841fa23", "On-PremisesDataGatewayConnector"},
{"996def3d-b36c-4153-8607-a6fd3c01b89f", "Dynamics365forFinancials"},
{"b6b84568-6c01-4981-a80f-09da9a20bbed", "MicrosoftInvoicing"},
{"9d3e55ba-79e0-4b7c-af50-dc460b81dca1", "MicrosoftAzureDataCatalog"},
{"4345a7b9-9a63-4910-a426-35363201d503", "O365SuiteUX"},
{"ac815d4a-573b-4174-b38e-46490d19f894", "Workflow"},
{"bb8f18b0-9c38-48c9-a847-e1ef3af0602d", "Microsoft.Azure.ActiveDirectoryIUX"},
{"cc15fd57-2c6c-4117-a88c-83b1d56b4bbe", "MicrosoftTeamsServices"},
{"5e3ce6c0-2b1f-4285-8d4b-75ee78787346", "SkypeTeams"},
{"1fec8e78-bce4-4aaf-ab1b-5451cc387264", "MicrosoftTeams"},
{"6d32b7f8-782e-43e0-ac47-aaad9f4eb839", "PermissionServiceO365"},
{"cdccd920-384b-4a25-897d-75161a4b74c1", "SkypeTeamsFirehose"},
{"1c0ae35a-e2ec-4592-8e08-c40884656fa5", "SkypeTeamSubstrateconnector"},
{"cf6c77f8-914f-4078-baef-e39a5181158b", "SkypeTeamsSettingsStore"},
{"64f79cb9-9c82-4199-b85b-77e35b7dcbcb", "MicrosoftTeamsBots"},
{"b7912db9-aa33-4820-9d4f-709830fdd78f", "ConnectionsService"},
{"82f77645-8a66-4745-bcdf-9706824f9ad0", "PowerAppsRuntimeService"},
{"6204c1d1-4712-4c46-a7d9-3ed63d992682", "MicrosoftFlowPortal"},
{"7df0a125-d3be-4c96-aa54-591f83ff541c", "MicrosoftFlowService"},
{"331cc017-5973-4173-b270-f0042fddfd75", "PowerAppsService"},
{"0a0e9e37-25e3-47d4-964c-5b8237cad19a", "CloudSponge"},
{"df09ff61-2178-45d8-888c-4210c1c7b0b2", "O365UAPProcessor"},
{"8338dec2-e1b3-48f7-8438-20c30a534458", "ViewPoint"},
{"00000001-0000-0000-c000-000000000000", "AzureESTSService"},
{"394866fc-eedb-4f01-8536-3ff84b16be2a", "MicrosoftPeopleCardsService"},
{"0a0a29f9-0a25-49c7-94bf-c53c3f8fa69d", "CortanaExperiencewithO365"},
{"bb2a2e3a-c5e7-4f0a-88e0-8e01fd3fc1f4", "CPIMService"},
{"0004c632-673b-4105-9bb6-f3bbd2a927fe", "PowerAppsandFlow"},
{"d3ce4cf8-6810-442d-b42e-375e14710095", "GraphExplorer"},
{"3aa5c166-136f-40eb-9066-33ac63099211", "O365CustomerMonitoring"},
{"d6fdaa33-e821-4211-83d0-cf74736489e1", "MicrosoftServiceTrust"},
{"ef4a2a24-4b4e-4abf-93ba-cc11c5bd442c", "Edmodo"},
{"b692184e-b47f-4706-b352-84b288d2d9ee", "Microsoft.MileIQ.RESTService"},
{"a25dbca8-4e60-48e5-80a2-0664fdb5c9b6", "Microsoft.MileIQ"},
{"f7069a8d-9edc-4300-b365-ae53c9627fc4", "Microsoft.MileIQ.Dashboard"},
{"02e3ae74-c151-4bda-b8f0-55fbf341de08", "ApplicationRegistrationPortal"},
{"1f5530b3-261a-47a9-b357-ded261e17918", "AzureMulti-FactorAuthConnector"},
{"981f26a1-7f43-403b-a875-f8b09b8cd720", "AzureMulti-FactorAuthClient"},
{"6ea8091b-151d-447a-9013-6845b83ba57b", "ADHybridHealth"},
{"fc68d9e5-1f76-45ef-99aa-214805418498", "AzureADIdentityProtection"},
{"01fc33a7-78ba-4d2f-a4b7-768e336e890e", "MS-PIM"},
{"a6aa9161-5291-40bb-8c5c-923b567bee3b", "StorageResourceProvider"},
{"4e9b8b9a-1001-4017-8dd1-6e8f25e19d13", "AdobeAcrobat"},
{"159b90bb-bb28-4568-ad7c-adad6b814a2f", "LastPass"},
{"b4bddae8-ab25-483e-8670-df09b9f1d0ea", "Signup"},
{"aa580612-c342-4ace-9055-8edee43ccb89", "MicrosoftStaffHub"},
{"51133ff5-8e0d-4078-bcca-84fb7f905b64", "MicrosoftTeamsMailhook"},
{"ab3be6b7-f5df-413d-ac2d-abf1e3fd9c0b", "MicrosoftTeamsGraphService"},
{"b1379a75-ce5e-4fa3-80c6-89bb39bf646c", "MicrosoftTeamsChatAggregator"},
{"48af08dc-f6d2-435f-b2a7-069abd99c086", "Connectors"},
{"d676e816-a17b-416b-ac1a-05ad96f43686", "Workflow"},
{"cfa8b339-82a2-471a-a3c9-0fc0be7a4093", "AzureKeyVault"},
{"c2f89f53-3971-4e09-8656-18eed74aee10", "calendly"},
{"6da466b6-1d13-4a2c-97bd-51a99e8d4d74", "ExchangeOfficeGraphClientforAAD-Interactive"},
{"0eda3b13-ddc9-4c25-b7dd-2f6ea073d6b7", "MicrosoftFlowCDSIntegrationService"},
{"eacba838-453c-4d3e-8c6a-eb815d3469a3", "MicrosoftFlowCDSIntegrationServiceTIP1"},
{"4ac7d521-0382-477b-b0f8-7e1d95f85ca2", "SQLServerAnalysisServicesAzure"},
{"b4114287-89e4-4209-bd99-b7d4919bcf64", "OfficeDelve"},
{"4580fd1d-e5a3-4f56-9ad1-aab0e3bf8f76", "CallRecorder"},
{"a855a166-fd92-4c76-b60d-a791e0762432", "MicrosoftTeamsVSTS"},
{"c37c294f-eec8-47d2-b3e2-fc3daa8f77d3", "Workflow"},
{"fc75330b-179d-49af-87dd-3b1acf6827fa", "AzureAutomationAADPatchS2S"},
{"766d89a4-d6a6-444d-8a5e-e1a18622288a", "OneDrive"},
{"f16c4a38-5aff-4549-8199-ee7d3c5bd8dc", "Workflow"},
{"4c4f550b-42b2-4a16-93f9-fdb9e01bb6ed", "TargetedMessagingService"},
{"765fe668-04e7-42ba-aec0-2c96f1d8b652", "ExchangeOfficeGraphClientforAAD-Noninteractive"},
{"0130cc9f-7ac5-4026-bd5f-80a08a54e6d9", "AzureDataWarehousePolybase"},
{"a1cf9e0a-fe14-487c-beb9-dd3360921173", "Meetup"},
{"76cd24bf-a9fc-4344-b1dc-908275de6d6d", "AzureSQLVirtualNetworktoNetworkResourceProvider"},
{"9f505dbd-a32c-4685-b1c6-72e4ef704cb0", "AmazonAlexa"},
{"1e2ca66a-c176-45ea-a877-e87f7231e0ee", "MicrosoftB2BAdminWorker"},
{"2634dd23-5e5a-431c-81ca-11710d9079f4", "MicrosoftStreamService"},
{"cf53fce8-def6-4aeb-8d30-b158e7b1cf83", "MicrosoftStreamPortal"},
{"c9a559d2-7aab-4f13-a6ed-e7e9c52aec87", "MicrosoftForms"},
{"978877ea-b2d6-458b-80c7-05df932f3723", "MicrosoftTeamsAuditService"},
{"dbc36ae1-c097-4df9-8d94-343c3d091a76", "ServiceEncryption"},
{"fa7ff576-8e31-4a58-a5e5-780c1cd57caa", "OneNote"},
{"cb4dc29f-0bf4-402a-8b30-7511498ed654", "PowerBIPremium"},
{"f5aeb603-2a64-4f37-b9a8-b544f3542865", "MicrosoftTeamsRetentionHookService"},
{"da109bdd-abda-4c06-8808-4655199420f8", "GlipContacts"},
{"76c7f279-7959-468f-8943-3954880e0d8c", "AzureSQLManagedInstancetoMicrosoft.Network"},
{"3a9ddf38-83f3-4ea1-a33a-ecf934644e2d", "ProtectedMessageViewer"},
{"5635d99c-c364-4411-90eb-764a511b5fdf", "ResponsiveBannerSlider"},
{"a43e5392-f48b-46a4-a0f1-098b5eeb4757", "Cloudsponge"},
{"d73f4b35-55c9-48c7-8b10-651f6f2acb2e", "MCAPIAuthorizationProd"},
{"166f1b03-5b19-416f-a94b-1d7aa2d247dc", "OfficeHive"},
{"b815ce1c-748f-4b1e-9270-a42c1fa4485a", "Workflow"},
{"bd7b778b-4aa8-4cde-8d90-8aeb821c0bd2", "Workflow"},
{"9d06afd9-66c9-49a6-b385-ea7509332b0b", "O365SBRMService"},
{"9ea1ad79-fdb6-4f9a-8bc3-2b70f96e34c7", "Bing"},
{"57fb890c-0dab-4253-a5e0-7188c88b2bb4", "SharePointOnlineClient"},
{"45c10911-200f-4e27-a666-9e9fca147395", "drawio"},
{"b73f62d0-210b-4396-a4c5-ea50c4fab79b", "SkypeBusinessVoiceFraudDetectionandPrevention"},
{"bc59ab01-8403-45c6-8796-ac3ef710b3e3", "OutlookOnlineAdd-inApp"},
{"035f9e1d-4f00-4419-bf50-bf2d87eb4878", "AzureMonitorRestricted"},
{"7c33bfcb-8d33-48d6-8e60-dc6404003489", "NetworkWatcher"},
{"a0be0c72-870e-46f0-9c49-c98333a996f7", "AzureDnsFrontendApp"},
{"1e3e4475-288f-4018-a376-df66fd7fac5f", "NetworkTrafficAnalyticsService"},
{"7557eb47-c689-4224-abcf-aef9bd7573df", "SkypeforBusiness"},
{"c39c9bac-9d1f-4dfb-aa29-27f6365e5cb7", "AzureAdvisor"},
{"2087bd82-7206-4c0a-b305-1321a39e5926", "MicrosoftTo-Do"},
{"f8d98a96-0999-43f5-8af3-69971c7bb423", "iOSAccounts"},
{"c27373d3-335f-4b45-8af9-fe81c240d377", "P2PServer"},
{"5c2ffddc-f1d7-4dc3-926e-3c1bd98e32bd", "RITSDev"},
{"982bda36-4632-4165-a46a-9863b1bbcf7d", "O365Demeter"},
{"98c8388a-4e86-424f-a176-d1288462816f", "OfficeFeedProcessors"},
{"bf9fc203-c1ff-4fd4-878b-323642e462ec", "JarvisTransactionService"},
{"257601fd-462f-4a21-b623-7f719f0f90f4", "CentralizedDeployment"},
{"2a486b53-dbd2-49c0-a2bc-278bdfc30833", "CortanaatWorkService"},
{"22d7579f-06c2-4baa-89d2-e844486adb9d", "CortanaatWorkBingServices"},
{"4c8f074c-e32b-4ba7-b072-0f39d71daf51", "IPSubstrate"},
{"a164aee5-7d0a-46bb-9404-37421d58bdf7", "MicrosoftTeamsAuthSvc"},
{"354b5b6d-abd6-4736-9f51-1be80049b91f", "MicrosoftMobileApplicationManagementBackend"},
{"82b293b2-d54d-4d59-9a95-39c1c97954a7", "TasksinaBox"},
{"fdc83783-b652-4258-a622-66bc85f1a871", "FedExPackageTracking"},
{"d0597157-f0ae-4e23-b06c-9e65de434c4f", "MicrosoftTeamsTaskService"},
{"f5c26e74-f226-4ae8-85f0-b4af0080ac9e", "ApplicationInsightsAPI"},
{"57c0fc58-a83a-41d0-8ae9-08952659bdfd", "AzureCosmosDBVirtualNetworkToNetworkResourceProvider"},
{"744e50be-c4ff-4e90-8061-cd7f1fabac0b", "LinkedInMicrosoftGraphConnector"},
{"823dfde0-1b9a-415a-a35a-1ad34e16dd44", "MicrosoftTeamsWikiImagesMigration"},
{"3ab9b3bc-762f-4d62-82f7-7e1d653ce29f", "MicrosoftVolumeLicensing"},
{"44eb7794-0e11-42b6-800b-dc31874f9f60", "Alignable"},
{"c58637bb-e2e1-4312-8a00-04b5ffcd3403", "SharePointOnlineClientExtensibility"},
{"62b732f7-fc71-40bc-b27d-35efcb0509de", "MicrosoftTeamsAadSync"},
{"07978fee-621a-42df-82bb-3eabc6511c26", "SurveyMonkey"},
{"47ee738b-3f1a-4fc7-ab11-37e4822b007e", "AzureADApplicationProxy"},
{"00000007-0000-0000-c000-000000000000", "DynamicsCRMOnline"},
{"913c6de4-2a4a-4a61-a9ce-945d2b2ce2e0", "DynamicsLifecycleservices"},
{"f217ad13-46b8-4c5b-b661-876ccdf37302", "AttachOneDrivefilestoAsana"},
{"00000008-0000-0000-c000-000000000000", "Microsoft.Azure.DataMarket"},
{"9b06ebd4-9068-486b-bdd2-dac26b8a5a7a", "Microsoft.DynamicsMarketing"},
{"e8ab36af-d4be-4833-a38b-4d6cf1cfd525", "MicrosoftSocialEngagement"},
{"8909aac3-be91-470c-8a0b-ff09d669af91", "MicrosoftParatureDynamicsCRM"},
{"71234da4-b92f-429d-b8ec-6e62652e50d7", "MicrosoftCustomerEngagementPortal"},
{"b861dbcc-a7ef-4219-a005-0e4de4ea7dcf", "DataExportServiceforMicrosoftDynamics365"},
{"2db8cb1d-fb6c-450b-ab09-49b6ae35186b", "MicrosoftDynamicsCRMLearningPath"},
{"2e49aa60-1bd3-43b6-8ab6-03ada3d9f08b", "DynamicsDataIntegration"},
{"d1ddf0e4-d672-4dae-b554-9d5bdfd93547", "Microsoft Intune Powershell" }
};
}
}
<|start_filename|>ModernWorkplaceConcierge/Helpers/SignalRMessage.cs<|end_filename|>
using Microsoft.AspNet.SignalR;
namespace ModernWorkplaceConcierge.Helpers
{
public class SignalRMessage
{
public string clientId { get; set; }
public SignalRMessage(string clientId)
{
this.clientId = clientId;
}
public void sendMessage(string message)
{
if ((!string.IsNullOrEmpty(message) && !string.IsNullOrEmpty(this.clientId)))
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<MwHub>();
hubContext.Clients.Client(this.clientId).addMessage(message);
}
}
}
}
<|start_filename|>ModernWorkplaceConcierge/Views/AutoPilotConfiguration/Detail.cshtml<|end_filename|>
@model Microsoft.Graph.WindowsAutopilotDeploymentProfile
@{
ViewBag.Current = "IntuneAutoPilotConfiguration";
}
@if (Model.DisplayName != null)
{
<h1>Autopilot Profile Details</h1>
<table class="table table-borderless table-responsive-sm table-sm mt-5">
<thead class="thead">
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tr>
<td>DisplayName</td>
<td>@Model.DisplayName</td>
</tr>
<tr>
<td>DeviceType</td>
<td>@Model.DeviceType</td>
</tr>
<tr>
<td>DeviceNameTemplate</td>
<td>@Model.DeviceNameTemplate</td>
</tr>
<tr>
<td>EnableWhiteGlove</td>
<td>@Model.EnableWhiteGlove</td>
</tr>
<tr>
<td>OutOfBoxExperienceSettings.DeviceUsageType</td>
<td>@Model.OutOfBoxExperienceSettings.DeviceUsageType</td>
</tr>
<tr>
<td>OutOfBoxExperienceSettings.HideEULA</td>
<td>@Model.OutOfBoxExperienceSettings.HideEULA</td>
</tr>
<tr>
<td>OutOfBoxExperienceSettings.HidePrivacySettings</td>
<td>@Model.OutOfBoxExperienceSettings.HidePrivacySettings</td>
</tr>
<tr>
<td>OutOfBoxExperienceSettings.SkipKeyboardSelectionPage</td>
<td>@Model.OutOfBoxExperienceSettings.SkipKeyboardSelectionPage</td>
</tr>
<tr>
<td>OutOfBoxExperienceSettings.UserType</td>
<td>@Model.OutOfBoxExperienceSettings.UserType</td>
</tr>
<tr>
<td>Language</td>
<td>@Model.Language</td>
</tr>
<tr>
<td>Id</td>
<td>@Model.Id</td>
</tr>
</table>
<br />
@Html.ActionLink("Back", "Index", "AutoPilotConfiguration", new { area = "" }, new { @class = "btn btn-outline-light" })
}
else
{
<div class="alert alert-danger" role="alert">
<h4 class="alert-heading">Error</h4>
Could not fetch WindowsAutopilotDeploymentProfile.
</div>
}
<|start_filename|>ModernWorkplaceConcierge/Views/Home/Index.cshtml<|end_filename|>
<!-- Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. -->
@{
ViewBag.Current = "Home";
}
<div class="jumbotron">
<h1>Modern Workplace Concierge</h1>
<p class="lead">Your concierge of choice to manage a modern workplace based on Microsoft 365 services.</p>
@if (Request.IsAuthenticated)
{
<h4>Welcome @ViewBag.User.DisplayName!</h4>
<p>Use the navigation bar at the top of the page to get started.</p>
<a href="https://github.com/nicolonsky/ModernWorkplaceConcierge" target="_blank" class="btn btn-dark btn-large">
<i class="fab fa-github"></i>
<span>View this project on GitHub</span>
</a>
}
else
{
<a href="@Url.Action("SignIn", "Account")" class="btn btn-large SignInButton">
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="80%" viewBox="0 0 3278 522" class="SignInButton">
<style type="text/css">.fil0:hover {fill: #4B4B4B;} .fnt0 {font-size: 260px;font-family: 'Segoe UI Semibold', 'Segoe UI'; text-decoration: none;}</style>
<rect x="150" y="129" width="122" height="122" fill="#F35325" />
<rect x="284" y="129" width="122" height="122" fill="#81BC06" />
<rect x="150" y="263" width="122" height="122" fill="#05A6F0" />
<rect x="284" y="263" width="122" height="122" fill="#FFBA08" />
<text x="470" y="357" fill="white" class="fnt0">Sign in with Microsoft</text>
</svg>
</a>
}
</div>
<script>
$(function () {
$('#tenant').tooltip('show')
})
</script>
<|start_filename|>ModernWorkplaceConcierge/Helpers/AzureADIDCache.cs<|end_filename|>
using Microsoft.Graph;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ModernWorkplaceConcierge.Helpers
{
/*
Stores Azure AD Object IDs in order to avoid multiple queries for the same resource's display names
*/
public class AzureADIDCache
{
// Store Object ID and displayName
private Dictionary<String, String> graphCache;
private string clientId;
private IEnumerable<DirectoryRoleTemplate> roleTemplates;
private IEnumerable<ServicePrincipal> servicePrincipals;
private IEnumerable<NamedLocation> namedLocations;
private GraphConditionalAccess graphConditionalAccess;
public AzureADIDCache(string clientId = null)
{
this.clientId = clientId;
this.graphCache = new Dictionary<string, string>();
this.graphConditionalAccess = new GraphConditionalAccess(clientId);
}
public async System.Threading.Tasks.Task<List<string>> getUserDisplayNamesAsync(string[] userIDs)
{
List<String> displayNames = new List<string>();
foreach (String userID in userIDs)
{
// Check for UID
if (Guid.TryParse(userID, out Guid result))
{
// Check if AAD Object in in cache
if (graphCache.ContainsKey(userID))
{
displayNames.Add(graphCache[userID]);
}
else
{
Microsoft.Graph.User user = await GraphHelper.GetUserById(userID, clientId);
graphCache.Add(user.Id, user.UserPrincipalName);
displayNames.Add(user.UserPrincipalName);
}
}
else
{
displayNames.Add(userID);
}
}
return displayNames;
}
public async System.Threading.Tasks.Task<List<string>> getGroupDisplayNamesAsync(string[] groupIDs)
{
List<String> displayNames = new List<string>();
foreach (String groupID in groupIDs)
{
// Check for UID
if (Guid.TryParse(groupID, out Guid result))
{
// Check if AAD Object in in cache
if (graphCache.ContainsKey(groupID))
{
displayNames.Add(graphCache[groupID]);
}
else
{
Group group = await GraphHelper.GetGroup(groupID, clientId);
graphCache.Add(group.Id, group.DisplayName);
displayNames.Add(group.DisplayName);
}
}
else
{
displayNames.Add(groupID);
}
}
return displayNames;
}
public async System.Threading.Tasks.Task<List<string>> getRoleDisplayNamesAsync(string[] roleIDs)
{
if (roleTemplates == null || roleTemplates.Count() == 0)
{
roleTemplates = await GraphHelper.GetDirectoryRoleTemplates(clientId);
}
List<String> displayNames = new List<string>();
foreach (String roleID in roleIDs)
{
// Check for UID
if (Guid.TryParse(roleID, out Guid result))
{
displayNames.Add(roleTemplates.Where(role => role.Id == roleID).Select(role => role.DisplayName).First());
}
else
{
displayNames.Add(roleID);
}
}
return displayNames;
}
public async Task<List<string>> getNamedLocationDisplayNamesAsync(string[] locationIDs)
{
if (namedLocations == null || namedLocations.Count() == 0)
{
namedLocations = await graphConditionalAccess.GetNamedLocationsAsync();
}
List<String> displayNames = new List<string>();
foreach (String locationID in locationIDs)
{
// Check for UID
if (Guid.TryParse(locationID, out Guid result))
{
displayNames.Add(namedLocations.Where(loc => loc.Id == locationID).Select(loc => loc.DisplayName).First());
}
else
{
displayNames.Add(locationID);
}
}
return displayNames;
}
public async Task<List<string>> getApplicationDisplayNamesAsync(string[] applicationIDs)
{
if (servicePrincipals == null || !servicePrincipals.Any())
{
servicePrincipals = await GraphHelper.GetServicePrincipals(clientId);
}
List<String> displayNames = new List<string>();
foreach (String applicationID in applicationIDs)
{
// Check for UID
if (Guid.TryParse(applicationID, out Guid result))
{
try
{
displayNames.Add(servicePrincipals.Where(app => app.AppId == applicationID).Select(app => app.AppDisplayName).First());
}
catch
{
if (AzureADApplicationIdentifiers.keyValuePairs.TryGetValue(applicationID, out string appDisplayName))
{
displayNames.Add(appDisplayName);
}
else
{
displayNames.Add(applicationID);
}
}
}
else
{
displayNames.Add(applicationID);
}
}
return displayNames;
}
}
} | TuukkaTanner/ModernWorkplaceConcierge |
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/layer/AbstractLayer.kt<|end_filename|>
package kittoku.osc.layer
import kittoku.osc.ControlClient
internal enum class PppStatus {
NEGOTIATE_LCP, AUTHENTICATE, NEGOTIATE_IPCP, NEGOTIATE_IPV6CP, NETWORK
}
internal enum class SstpStatus {
CALL_ABORT_IN_PROGRESS_1,
CALL_ABORT_IN_PROGRESS_2,
CALL_DISCONNECT_IN_PROGRESS_1,
CALL_DISCONNECT_IN_PROGRESS_2,
CLIENT_CALL_DISCONNECTED,
CLIENT_CONNECT_REQUEST_SENT,
CLIENT_CONNECT_ACK_RECEIVED,
CLIENT_CALL_CONNECTED
}
internal class DualClientStatus {
internal var ppp = PppStatus.NEGOTIATE_LCP
internal var sstp = SstpStatus.CLIENT_CALL_DISCONNECTED
}
internal class Counter(private val maxCount: Int) {
private var currentCount = maxCount
internal val isExhausted: Boolean
get() = currentCount <= 0
internal fun consume() {
currentCount--
}
internal fun reset() {
currentCount = maxCount
}
}
internal class Timer(private val maxLength: Long) {
private var startedTime = System.currentTimeMillis()
internal val isOver: Boolean
get() = (System.currentTimeMillis() - startedTime) > maxLength
internal fun reset() {
startedTime = System.currentTimeMillis()
}
}
internal abstract class Client(internal val parent: ControlClient) {
internal val status = parent.status
internal val incomingBuffer = parent.incomingBuffer
internal val networkSetting = parent.networkSetting
internal abstract fun proceed() // just check its state or timers, not bytes
}
internal abstract class Terminal(protected val parent: ControlClient) {
internal abstract fun release()
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/ControlClient.kt<|end_filename|>
package kittoku.osc
import android.content.SharedPreferences
import android.net.Uri
import android.net.VpnService
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.documentfile.provider.DocumentFile
import androidx.preference.PreferenceManager
import kittoku.osc.layer.*
import kittoku.osc.misc.*
import kittoku.osc.preference.OscPreference
import kittoku.osc.preference.accessor.getBooleanPrefValue
import kittoku.osc.preference.accessor.getIntPrefValue
import kittoku.osc.preference.accessor.setBooleanPrefValue
import kittoku.osc.unit.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.BufferedOutputStream
import java.nio.ByteBuffer
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.LinkedBlockingQueue
internal class ReconnectionSettings(prefs: SharedPreferences) {
internal val isEnabled = getBooleanPrefValue(OscPreference.RECONNECTION_ENABLED, prefs)
private val initialCount = if (isEnabled) getIntPrefValue(OscPreference.RECONNECTION_COUNT, prefs) else 0
private var currentCount = initialCount
private val interval = getIntPrefValue(OscPreference.RECONNECTION_INTERVAL, prefs)
internal val intervalMillis = (interval * 1000).toLong()
internal val isRetryable: Boolean
get() = currentCount > 0
internal fun resetCount() {
currentCount = initialCount
}
internal fun consumeCount() {
currentCount--
}
internal fun generateMessage(): String {
val triedCount = initialCount - currentCount
return "Reconnection will be tried (COUNT: $triedCount/$initialCount)"
}
}
internal class ControlClient(internal val vpnService: SstpVpnService) :
CoroutineScope by CoroutineScope(Dispatchers.IO + SupervisorJob()) {
private val prefs = PreferenceManager.getDefaultSharedPreferences(vpnService.applicationContext)
internal lateinit var networkSetting: NetworkSetting
internal lateinit var status: DualClientStatus
internal lateinit var builder: VpnService.Builder
internal lateinit var incomingBuffer: IncomingBuffer
private var observer: NetworkObserver? = null
internal val controlQueue = LinkedBlockingQueue<Any>()
internal var logStream: BufferedOutputStream? = null
internal val reconnectionSettings = ReconnectionSettings(prefs)
internal lateinit var sslTerminal: SslTerminal
private lateinit var sstpClient: SstpClient
private lateinit var pppClient: PppClient
internal lateinit var ipTerminal: IpTerminal
private var jobIncoming: Job? = null
private var jobControl: Job? = null
private var jobEncapsulate: Job? = null
private var jobData: Job? = null
private val isAllJobCompleted: Boolean
get() {
arrayOf(jobIncoming, jobControl, jobEncapsulate, jobData).forEach {
if (it?.isCompleted != true) {
return false
}
}
return true
}
private val mutex = Mutex()
private var isClosing = false
private val handler = CoroutineExceptionHandler { _, exception ->
if (!isClosing) kill(exception)
}
init {
initialize()
}
private fun initialize() {
networkSetting = NetworkSetting(prefs)
status = DualClientStatus()
builder = vpnService.Builder()
incomingBuffer = IncomingBuffer(networkSetting.BUFFER_INCOMING, this)
controlQueue.clear()
isClosing = false
}
internal fun kill(exception: Throwable?) {
launch {
mutex.withLock {
if (!isClosing) {
isClosing = true
controlQueue.add(0)
if (exception != null && exception !is SuicideException) {
inform("An unexpected event occurred", exception)
}
// release ConnectivityManager resource
observer?.close()
// no more packets needed to be retrieved
ipTerminal.release()
jobData?.cancel()
jobEncapsulate?.cancel()
// wait until SstpClient.sendLastGreeting() is invoked
jobIncoming?.join()
// wait until jobControl finishes sending messages
withTimeout(10_000) {
while (isActive) {
if (jobControl?.isCompleted == false) {
delay(100)
}
else break
}
}
// avoid jobControl being stuck with socket
sslTerminal.release()
// ensure jobControl is completed
jobControl?.cancel()
if (exception != null && reconnectionSettings.isEnabled) {
if (reconnectionSettings.isRetryable) {
tryReconnection()
return@withLock
} else {
inform("Exhausted retry counts", null)
makeNotification(0, "Failed to reconnect")
}
}
bye()
}
}
}
}
private fun bye() {
inform("Terminate VPN connection", null)
logStream?.close()
setBooleanPrefValue(false, OscPreference.HOME_CONNECTOR, prefs)
vpnService.stopForeground(true)
vpnService.stopSelf()
}
private fun tryReconnection() {
launch {
reconnectionSettings.consumeCount()
makeNotification(0, reconnectionSettings.generateMessage())
delay(reconnectionSettings.intervalMillis)
val result = withTimeoutOrNull(10_000) {
while (true) {
if (isAllJobCompleted) {
return@withTimeoutOrNull true
} else {
delay(1)
}
}
}
if (result == null) {
inform("The last session cannot be cleaned up", null)
makeNotification(0, "Failed to reconnect")
bye()
} else {
initialize()
run()
}
}
}
internal fun run() {
if (networkSetting.LOG_DO_SAVE_LOG && logStream == null) {
prepareLog()
}
inform("Establish VPN connection", null)
prepareLayers()
launchJobIncoming()
launchJobControl()
}
private fun launchJobIncoming() {
jobIncoming = launch(handler) {
while (isActive) {
sstpClient.proceed()
pppClient.proceed()
if (isClosing) {
status.sstp = SstpStatus.CALL_DISCONNECT_IN_PROGRESS_1
}
}
}
}
private fun launchJobControl() {
jobControl = launch(handler) {
val controlBuffer = ByteBuffer.allocate(CONTROL_BUFFER_SIZE)
while (isActive) {
val candidate = controlQueue.take()
if (candidate == 0) break
controlBuffer.clear()
when (candidate) {
is ControlPacket -> {
candidate.write(controlBuffer)
}
is PppFrame -> {
controlBuffer.putShort(SSTP_PACKET_TYPE_DATA)
controlBuffer.putShort((candidate._length + 8).toShort())
candidate.write(controlBuffer)
}
else -> throw Exception("Invalid Control Unit")
}
controlBuffer.flip()
sslTerminal.send(controlBuffer)
}
}
}
private fun launchJobEncapsulate(channel: Channel<ByteBuffer>) {
jobEncapsulate = launch(handler) { // buffer packets
val dataBuffer = ByteBuffer.allocate(networkSetting.BUFFER_OUTGOING)
val minCapacity = networkSetting.currentMtu + 8
val ipv4Version: Int = (0x4).shl(28)
val ipv6Version: Int = (0x6).shl(28)
val versionMask: Int = (0xF).shl(28)
var polled: ByteBuffer?
fun encapsulate(src: ByteBuffer): Boolean // true if data protocol is enabled
{
val header = src.getInt(0)
val version = when (header and versionMask) {
ipv4Version -> {
if (!networkSetting.PPP_IPv4_ENABLED) return false
PPP_PROTOCOL_IP
}
ipv6Version -> {
if (!networkSetting.PPP_IPv6_ENABLED) return false
PPP_PROTOCOL_IPV6
}
else -> throw Exception("Invalid data protocol was detected")
}
dataBuffer.putShort(SSTP_PACKET_TYPE_DATA)
dataBuffer.putShort((src.limit() + 8).toShort())
dataBuffer.putShort(PPP_HEADER)
dataBuffer.putShort(version)
dataBuffer.put(src)
return true
}
while (isActive) {
dataBuffer.clear()
if (!encapsulate(channel.receive())) continue
while (isActive) {
polled = channel.poll()
if (polled != null) {
encapsulate(polled)
if (dataBuffer.remaining() < minCapacity) break
} else {
break
}
}
dataBuffer.flip()
sslTerminal.send(dataBuffer)
}
}
}
internal fun launchJobData() {
jobData = launch(handler) {
val channel = Channel<ByteBuffer>(0)
val readBufferAlpha = ByteBuffer.allocate(networkSetting.currentMtu)
val readBufferBeta = ByteBuffer.allocate(networkSetting.currentMtu)
var isBlockingAlpha = true
launchJobEncapsulate(channel)
suspend fun read(dst: ByteBuffer) {
dst.clear()
dst.position(
ipTerminal.ipInput.read(
dst.array(),
0,
networkSetting.currentMtu
)
)
dst.flip()
channel.send(dst)
}
while (isActive) {
isBlockingAlpha = if (isBlockingAlpha) {
read(readBufferAlpha)
false
} else {
read(readBufferBeta)
true
}
}
}
}
internal fun attachNetworkObserver() {
observer = NetworkObserver(this)
}
private fun prepareLayers() {
sslTerminal = SslTerminal(this)
sstpClient = SstpClient(this)
pppClient = PppClient(this)
ipTerminal = IpTerminal(this)
}
private fun prepareLog() {
val currentTime = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(Date())
val filename = "log_osc_${currentTime}.txt"
val uri = Uri.parse(networkSetting.LOG_DIR)
DocumentFile.fromTreeUri(vpnService, uri)!!.createFile("text/plain", filename).also {
logStream = BufferedOutputStream(vpnService.contentResolver.openOutputStream(it!!.uri))
}
}
private fun makeNotification(id: Int, message: String) {
val builder = NotificationCompat.Builder(vpnService.applicationContext, vpnService.CHANNEL_ID).also {
it.setSmallIcon(R.drawable.ic_baseline_vpn_lock_24)
it.setContentText(message)
it.priority = NotificationCompat.PRIORITY_DEFAULT
it.setAutoCancel(true)
}
NotificationManagerCompat.from(vpnService.applicationContext).also {
it.notify(id, builder.build())
}
inform(message, null)
}
}
<|start_filename|>strongswan/app/src/main/java/org/strongswan/android/logic/imc/collectors/Protocol.java<|end_filename|>
/*
* Copyright (C) 2013 <NAME>
* HSR Hochschule fuer Technik Rapperswil
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package org.strongswan.android.logic.imc.collectors;
public enum Protocol
{
TCP((byte)6, "tcp", "tcp6"),
UDP((byte)17, "udp", "udp6");
private final byte mValue;
private String[] mNames;
private Protocol(byte value, String... names)
{
mValue = value;
mNames = names;
}
/**
* Get the numeric value of the protocol.
* @return numeric value
*/
public byte getValue()
{
return mValue;
}
/**
* Get the protocol from the given protocol name, if found.
* @param name protocol name (e.g. "udp" or "tcp")
* @return enum entry or null
*/
public static Protocol fromName(String name)
{
for (Protocol protocol : Protocol.values())
{
for (String keyword : protocol.mNames)
{
if (keyword.equalsIgnoreCase(name))
{
return protocol;
}
}
}
return null;
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/unit/PppIpv6cpFrame.kt<|end_filename|>
package kittoku.osc.unit
import kittoku.osc.misc.DataUnitParsingError
import kittoku.osc.misc.IncomingBuffer
import java.nio.ByteBuffer
import kotlin.properties.Delegates
internal const val IPv6CP_CODE_CONFIGURE_REQUEST: Byte = 1
internal const val IPv6CP_CODE_CONFIGURE_ACK: Byte = 2
internal const val IPv6CP_CODE_CONFIGURE_NAK: Byte = 3
internal const val IPv6CP_CODE_CONFIGURE_REJECT: Byte = 4
internal const val IPv6CP_CODE_TERMINATE_REQUEST: Byte = 5
internal const val IPv6CP_CODE_TERMINATE_ACK: Byte = 6
internal const val IPv6CP_CODE_CODE_REJECT: Byte = 7
internal const val IPv6CP_OPTION_TYPE_IDENTIFIER: Byte = 0x01
internal abstract class Ipv6cpOption : ByteLengthDataUnit() {
internal abstract val type: Byte
override val validLengthRange = 2..Byte.MAX_VALUE
internal fun writeHeader(bytes: ByteBuffer) {
bytes.put(type)
bytes.put(getTypedLength())
}
}
internal class Ipv6cpIdentifierOption : Ipv6cpOption() {
override val type = IPv6CP_OPTION_TYPE_IDENTIFIER
override val validLengthRange = 10..10
internal val identifier = ByteArray(8)
override fun read(bytes: IncomingBuffer) {
setTypedLength(bytes.getByte())
bytes.get(identifier)
}
override fun write(bytes: ByteBuffer) {
writeHeader(bytes)
bytes.put(identifier)
}
override fun update() {
_length = validLengthRange.first
}
}
internal class Ipv6cpUnknownOption(unknownType: Byte) : Ipv6cpOption() {
override val type = unknownType
internal var holder = ByteArray(0)
override fun read(bytes: IncomingBuffer) {
setTypedLength(bytes.getByte())
holder = ByteArray(_length - validLengthRange.first).also { bytes.get(it) }
}
override fun write(bytes: ByteBuffer) {
writeHeader(bytes)
bytes.put(holder)
}
override fun update() {
_length = holder.size + validLengthRange.first
}
}
internal abstract class Ipv6cpFrame : PppFrame() {
override val protocol = PPP_PROTOCOL_IPV6CP
}
internal abstract class Ipv6cpConfigureFrame : Ipv6cpFrame() {
internal var options = mutableListOf<Ipv6cpOption>()
// contains all options to be sent or received
private inline fun <reified T : Ipv6cpOption> delegateOption() =
Delegates.observable<T?>(null) { _, old, new ->
if (old != null) {
if (new == null) { // erase option
for (i in options.indices) {
if (options[i] is T) {
options.removeAt(i)
break
}
}
} else { // update option
for (i in options.indices) {
if (options[i] is T) {
options[i] = new
break
}
}
}
} else if (new != null) { // install option
options.add(new)
}
}
internal var optionIdentifier by delegateOption<Ipv6cpIdentifierOption>()
internal val hasUnknownOption: Boolean
get() {
options.forEach { if (it is Ipv6cpUnknownOption) return true }
return false
}
internal fun extractUnknownOption(): MutableList<Ipv6cpOption> {
val onlyUnknowns = mutableListOf<Ipv6cpOption>()
this.options.forEach { if (it is Ipv6cpUnknownOption) onlyUnknowns.add(it) }
return onlyUnknowns
}
override fun read(bytes: IncomingBuffer) {
options.clear()
readHeader(bytes)
var remaining = _length - validLengthRange.first
while (true) {
when (remaining) {
0 -> return
in Int.MIN_VALUE..-1 -> throw DataUnitParsingError()
}
val type = bytes.getByte()
val option: Ipv6cpOption = when (type) {
IPv6CP_OPTION_TYPE_IDENTIFIER -> Ipv6cpIdentifierOption().also {
optionIdentifier = it
}
else -> Ipv6cpUnknownOption(type).also { options.add(it) }
}
option.read(bytes)
remaining -= option._length
}
}
override fun write(bytes: ByteBuffer) {
writeHeader(bytes)
options.forEach { it.write(bytes) }
}
override fun update() {
_length = validLengthRange.first
options.forEach {
it.update()
_length += it._length
}
}
}
internal class Ipv6cpConfigureRequest : Ipv6cpConfigureFrame() {
override val code = IPv6CP_CODE_CONFIGURE_REQUEST
}
internal class Ipv6cpConfigureAck : Ipv6cpConfigureFrame() {
override val code = IPv6CP_CODE_CONFIGURE_ACK
}
internal class Ipv6cpConfigureNak : Ipv6cpConfigureFrame() {
override val code = IPv6CP_CODE_CONFIGURE_NAK
}
internal class Ipv6cpConfigureReject : Ipv6cpConfigureFrame() {
override val code = IPv6CP_CODE_CONFIGURE_REJECT
}
<|start_filename|>strongswan/app/src/main/java/org/strongswan/android/utils/SettingsWriter.java<|end_filename|>
/*
* Copyright (C) 2015 <NAME>
* HSR Hochschule fuer Technik Rapperswil
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package org.strongswan.android.utils;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.regex.Pattern;
/**
* Simple generator for data/files that may be parsed by libstrongswan's
* settings_t class.
*/
public class SettingsWriter
{
/**
* Top-level section
*/
private final SettingsSection mTop = new SettingsSection();
/**
* Set a string value
* @param key
* @param value
* @return the writer
*/
public SettingsWriter setValue(String key, String value)
{
Pattern pattern = Pattern.compile("[^#{}=\"\\n\\t ]+");
if (key == null || !pattern.matcher(key).matches())
{
return this;
}
String[] keys = key.split("\\.");
SettingsSection section = mTop;
section = findOrCreateSection(Arrays.copyOfRange(keys, 0, keys.length-1));
section.Settings.put(keys[keys.length-1], value);
return this;
}
/**
* Set an integer value
* @param key
* @param value
* @return the writer
*/
public SettingsWriter setValue(String key, Integer value)
{
return setValue(key, value == null ? null : value.toString());
}
/**
* Set a boolean value
* @param key
* @param value
* @return the writer
*/
public SettingsWriter setValue(String key, Boolean value)
{
return setValue(key, value == null ? null : value ? "1" : "0");
}
/**
* Serializes the settings to a string in the format understood by
* libstrongswan's settings_t parser.
* @return serialized settings
*/
public String serialize()
{
StringBuilder builder = new StringBuilder();
serializeSection(mTop, builder);
return builder.toString();
}
/**
* Serialize the settings in a section and recursively serialize sub-sections
* @param section
* @param builder
*/
private void serializeSection(SettingsSection section, StringBuilder builder)
{
for (Entry<String, String> setting : section.Settings.entrySet())
{
builder.append(setting.getKey()).append('=');
if (setting.getValue() != null)
{
builder.append("\"").append(escapeValue(setting.getValue())).append("\"");
}
builder.append('\n');
}
for (Entry<String, SettingsSection> subsection : section.Sections.entrySet())
{
builder.append(subsection.getKey()).append(" {\n");
serializeSection(subsection.getValue(), builder);
builder.append("}\n");
}
}
/**
* Escape value so it may be wrapped in "
* @param value
* @return
*/
private String escapeValue(String value)
{
return value.replace("\\", "\\\\").replace("\"", "\\\"");
}
/**
* Find or create the nested sections with the given names
* @param sections list of section names
* @return final section
*/
private SettingsSection findOrCreateSection(String[] sections)
{
SettingsSection section = mTop;
for (String name : sections)
{
SettingsSection subsection = section.Sections.get(name);
if (subsection == null)
{
subsection = new SettingsSection();
section.Sections.put(name, subsection);
}
section = subsection;
}
return section;
}
/**
* A section containing sub-sections and settings.
*/
private class SettingsSection
{
/**
* Assigned key/value pairs
*/
LinkedHashMap<String,String> Settings = new LinkedHashMap<String, String>();
/**
* Assigned sub-sections
*/
LinkedHashMap<String,SettingsSection> Sections = new LinkedHashMap<String, SettingsWriter.SettingsSection>();
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/preference/accessor/set.kt<|end_filename|>
package kittoku.osc.preference.accessor
import android.content.SharedPreferences
import kittoku.osc.preference.OscPreference
internal fun getSetPrefValue(key: OscPreference, prefs: SharedPreferences): Set<String> {
val defaultValue = when (key) {
OscPreference.SSL_SUITES -> setOf<String>()
else -> throw NotImplementedError()
}
return prefs.getStringSet(key.name, defaultValue)!!
}
internal fun setSetPrefValue(value: Set<String>, key: OscPreference, prefs: SharedPreferences) {
prefs.edit().also {
it.putStringSet(key.name, value)
it.apply()
}
}
<|start_filename|>strongswan/app/src/main/java/org/strongswan/android/data/VpnType.java<|end_filename|>
/*
* Copyright (C) 2012-2014 <NAME>
* HSR Hochschule fuer Technik Rapperswil
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package org.strongswan.android.data;
import java.util.EnumSet;
public enum VpnType
{
/* the order here must match the items in R.array.vpn_types */
IKEV2_EAP("ikev2-eap", EnumSet.of(VpnTypeFeature.USER_PASS)),
IKEV2_CERT("ikev2-cert", EnumSet.of(VpnTypeFeature.CERTIFICATE)),
IKEV2_CERT_EAP("ikev2-cert-eap", EnumSet.of(VpnTypeFeature.USER_PASS, VpnTypeFeature.CERTIFICATE)),
IKEV2_EAP_TLS("ikev2-eap-tls", EnumSet.of(VpnTypeFeature.CERTIFICATE)),
IKEV2_BYOD_EAP("ikev2-byod-eap", EnumSet.of(VpnTypeFeature.USER_PASS, VpnTypeFeature.BYOD));
/**
* Features of a VPN type.
*/
public enum VpnTypeFeature
{
/** client certificate is required */
CERTIFICATE,
/** username and password are required */
USER_PASS,
/** enable BYOD features */
BYOD;
}
private String mIdentifier;
private EnumSet<VpnTypeFeature> mFeatures;
/**
* Enum which provides additional information about the supported VPN types.
*
* @param id identifier used to store and transmit this specific type
* @param features of the given VPN type
* @param certificate true if a client certificate is required
*/
VpnType(String id, EnumSet<VpnTypeFeature> features)
{
mIdentifier = id;
mFeatures = features;
}
/**
* The identifier used to store this value in the database
* @return identifier
*/
public String getIdentifier()
{
return mIdentifier;
}
/**
* Checks whether a feature is supported/required by this type of VPN.
*
* @return true if the feature is supported/required
*/
public boolean has(VpnTypeFeature feature)
{
return mFeatures.contains(feature);
}
/**
* Get the enum entry with the given identifier.
*
* @param identifier get the enum entry with this identifier
* @return the enum entry, or the default if not found
*/
public static VpnType fromIdentifier(String identifier)
{
for (VpnType type : VpnType.values())
{
if (identifier.equals(type.mIdentifier))
{
return type;
}
}
return VpnType.IKEV2_EAP;
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/misc/Debug.kt<|end_filename|>
package kittoku.osc.misc
import kittoku.osc.ControlClient
import kittoku.osc.unit.DataUnit
import java.io.BufferedOutputStream
import java.text.SimpleDateFormat
import java.util.*
import kotlin.reflect.KFunction
internal class DataUnitParsingError : Error("Failed to parse data unit")
internal class SuicideException : Exception("Kill this client as intended")
internal class Ticker(private val key:String, private val logStream: BufferedOutputStream) {
private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault())
private var lastTick = System.nanoTime()
internal fun tick(event: String, value: String="NULL") {
val currentTick = System.nanoTime()
val diff = currentTick - lastTick
lastTick = currentTick
"TICK, $key, ${dateFormat.format(Date())}, $diff, $event, $value\n".also {
logStream.write(it.toByteArray())
}
}
}
internal fun ControlClient.inform(message: String, cause: Throwable?) {
val currentTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault()).format(Date())
var printing = "[$currentTime] $message"
cause?.also {
printing += ":\n"
val trace =
it::class.simpleName + "\n" + it.message + "\n" + it.stackTrace.joinToString("\n")
printing += trace
}
printing += "\n"
logStream?.write(printing.toByteArray())
}
internal fun ControlClient.informDataUnitParsingError(unit: DataUnit<*>, cause: DataUnitParsingError) {
inform("Failed to parse ${unit::class.simpleName}", cause)
}
internal fun ControlClient.informTimerOver(where: KFunction<*>) {
inform("The timer was over: ${where.name}", null)
}
internal fun ControlClient.informCounterExhausted(where: KFunction<*>) {
inform("The counter was exhausted: ${where.name}", null)
}
internal fun ControlClient.informOptionRejected(option: DataUnit<*>) {
inform("${option::class.simpleName} was rejected", null)
}
internal fun ControlClient.informInvalidUnit(where: KFunction<*>) {
inform("Received an invalid unit: ${where.name}", null)
}
internal fun ControlClient.informAuthenticationFailed(where: KFunction<*>) {
inform("Failed to be authenticated: ${where.name}", null)
}
internal fun ControlClient.informReceivedCallDisconnect(where: KFunction<*>) {
inform("Received a Call Disconnect: ${where.name}", null)
}
internal fun ControlClient.informReceivedCallAbort(where: KFunction<*>) {
inform("Received a Call Abort: ${where.name}", null)
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/SstpTileService.kt<|end_filename|>
package kittoku.osc
import android.content.Intent
import android.content.SharedPreferences
import android.net.VpnService
import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import androidx.annotation.RequiresApi
import androidx.preference.PreferenceManager
import kittoku.osc.preference.OscPreference
import kittoku.osc.preference.accessor.getBooleanPrefValue
import kittoku.osc.preference.checkPreferences
@RequiresApi(Build.VERSION_CODES.N)
internal class SstpTileService : TileService() {
private val prefs by lazy {
PreferenceManager.getDefaultSharedPreferences(applicationContext)
}
private val listener by lazy {
SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == OscPreference.ROOT_STATE.name) {
updateTileState()
}
}
}
private val rootState: Boolean
get() = getBooleanPrefValue(OscPreference.ROOT_STATE, prefs)
private val isVpnPrepared: Boolean
get() = VpnService.prepare(applicationContext) == null
private fun invalidateTileState() {
qsTile.state = Tile.STATE_UNAVAILABLE
qsTile.updateTile()
}
private fun updateTileState() {
qsTile.state = if (rootState) {
Tile.STATE_ACTIVE
} else {
Tile.STATE_INACTIVE
}
qsTile.updateTile()
}
private fun flipTileState() {
qsTile.state = if (qsTile.state == Tile.STATE_ACTIVE) {
Tile.STATE_INACTIVE
} else {
Tile.STATE_ACTIVE
}
qsTile.updateTile()
}
private fun initializeState() {
if (isVpnPrepared) {
updateTileState()
} else {
invalidateTileState()
}
}
override fun onTileAdded() {
initializeState()
}
override fun onStartListening() {
initializeState()
prefs.registerOnSharedPreferenceChangeListener(listener)
}
override fun onStopListening() {
prefs.unregisterOnSharedPreferenceChangeListener(listener)
}
private fun startVpnService(action: String) {
val intent = Intent(applicationContext, SstpVpnService::class.java).setAction(action)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent)
} else {
startService(intent)
}
}
override fun onClick() {
if (!isVpnPrepared || checkPreferences(prefs) != null) return
flipTileState()
when (qsTile.state) {
Tile.STATE_ACTIVE -> startVpnService(ACTION_VPN_CONNECT)
Tile.STATE_INACTIVE -> startVpnService(ACTION_VPN_DISCONNECT)
}
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/preference/accessor/boolean.kt<|end_filename|>
package kittoku.osc.preference.accessor
import android.content.SharedPreferences
import kittoku.osc.preference.OscPreference
internal fun getBooleanPrefValue(key: OscPreference, prefs: SharedPreferences): Boolean {
val defaultValue = when (key) {
OscPreference.ROOT_STATE -> false
OscPreference.HOME_CONNECTOR -> false
OscPreference.SSL_DO_VERIFY -> true
OscPreference.SSL_DO_ADD_CERT -> false
OscPreference.SSL_DO_SELECT_SUITES -> false
OscPreference.PPP_PAP_ENABLED -> true
OscPreference.PPP_MSCHAPv2_ENABLED -> true
OscPreference.PPP_IPv4_ENABLED -> true
OscPreference.PPP_IPv6_ENABLED -> false
OscPreference.IP_ONLY_LAN -> false
OscPreference.IP_ONLY_ULA -> false
OscPreference.RECONNECTION_ENABLED -> false
OscPreference.LOG_DO_SAVE_LOG -> false
else -> throw NotImplementedError()
}
return prefs.getBoolean(key.name, defaultValue)
}
internal fun setBooleanPrefValue(value: Boolean, key: OscPreference, prefs: SharedPreferences) {
prefs.edit().also {
it.putBoolean(key.name, value)
it.apply()
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/preference/custom/SwitchPreference.kt<|end_filename|>
package kittoku.osc.preference.custom
import android.content.Context
import android.util.AttributeSet
import androidx.preference.SwitchPreferenceCompat
import kittoku.osc.preference.OscPreference
import kittoku.osc.preference.accessor.getBooleanPrefValue
internal abstract class SwitchPreference(context: Context, attrs: AttributeSet) : SwitchPreferenceCompat(context, attrs) {
abstract val oscPreference: OscPreference
abstract val preferenceTitle: String
private fun initialize() {
isChecked = getBooleanPrefValue(oscPreference, sharedPreferences)
}
override fun onAttached() {
super.onAttached()
initialize()
title = preferenceTitle
isSingleLineTitle = false
}
}
internal class SSLDoAddCertPreference(context: Context, attrs: AttributeSet) : SwitchPreference(context, attrs) {
override val oscPreference = OscPreference.SSL_DO_ADD_CERT
override val preferenceTitle = "Add Trusted Certificates"
}
internal class SSLDoSelectSuitesPreference(context: Context, attrs: AttributeSet) : SwitchPreference(context, attrs) {
override val oscPreference = OscPreference.SSL_DO_SELECT_SUITES
override val preferenceTitle = "Enable Only Selected Cipher Suites"
}
internal class ReconnectionEnabledPreference(context: Context, attrs: AttributeSet) : SwitchPreference(context, attrs) {
override val oscPreference = OscPreference.RECONNECTION_ENABLED
override val preferenceTitle = "Enable Reconnection"
}
internal class LogDoSaveLogPreference(context: Context, attrs: AttributeSet) : SwitchPreference(context, attrs) {
override val oscPreference = OscPreference.LOG_DO_SAVE_LOG
override val preferenceTitle = "Save Log"
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/negotiator/SstpNegotiator.kt<|end_filename|>
package kittoku.osc.negotiator
import kittoku.osc.layer.SstpClient
import kittoku.osc.layer.SstpStatus
import kittoku.osc.misc.*
import kittoku.osc.unit.*
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.security.MessageDigest
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
internal fun SstpClient.tryReadingPacket(packet: ControlPacket): Boolean {
try {
packet.read(incomingBuffer)
} catch (e: DataUnitParsingError) {
parent.informDataUnitParsingError(packet, e)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return false
}
return true
}
internal fun SstpClient.challengeWholePacket(): Boolean {
if (!incomingBuffer.challenge(4)) {
return false
}
incomingBuffer.move(2)
(incomingBuffer.getShort().toInt() - 4).also {
if (it < 0) {
parent.informInvalidUnit(::challengeWholePacket)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return false
}
if (!incomingBuffer.challenge(it)) {
incomingBuffer.reset()
return false
}
}
incomingBuffer.reset()
return true
}
internal fun SstpClient.sendCallConnectRequest() {
if (negotiationCounter.isExhausted) {
parent.informCounterExhausted(::sendCallConnectRequest)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return
}
negotiationCounter.consume()
val sending = SstpCallConnectRequest().also { it.update() }
parent.controlQueue.add(sending)
negotiationTimer.reset()
}
internal fun SstpClient.sendCallConnected() {
val sending = SstpCallConnected()
val cmkInputBuffer = ByteBuffer.allocate(32)
val cmacInputBuffer = ByteBuffer.allocate(sending.validLengthRange.first)
val hashSetting = HashSetting(networkSetting.hashProtocol)
networkSetting.nonce.copyInto(sending.binding.nonce)
MessageDigest.getInstance(hashSetting.digestProtocol).also {
it.digest(networkSetting.serverCertificate.encoded).copyInto(sending.binding.certHash)
}
sending.binding.hashProtocol = networkSetting.hashProtocol
sending.update()
sending.write(cmacInputBuffer)
val HLAK = when (networkSetting.currentAuth) {
AuthSuite.PAP -> ByteArray(32)
AuthSuite.MSCHAPv2 -> generateChapHLAK(networkSetting)
}
val cmkSeed = "SSTP inner method derived CMK".toByteArray(Charset.forName("US-ASCII"))
cmkInputBuffer.put(cmkSeed)
cmkInputBuffer.putShort(hashSetting.cmacSize)
cmkInputBuffer.put(1)
Mac.getInstance(hashSetting.macProtocol).also {
it.init(SecretKeySpec(HLAK, hashSetting.macProtocol))
val cmk = it.doFinal(cmkInputBuffer.array())
it.init(SecretKeySpec(cmk, hashSetting.macProtocol))
val cmac = it.doFinal(cmacInputBuffer.array())
cmac.copyInto(sending.binding.compoundMac)
}
sending.update()
parent.controlQueue.add(sending)
}
internal fun SstpClient.sendEchoRequest() {
if (echoCounter.isExhausted) {
parent.informCounterExhausted(::sendEchoRequest)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return
}
echoCounter.consume()
val sending = SstpEchoRequest().also { it.update() }
parent.controlQueue.add(sending)
echoTimer.reset()
}
internal fun SstpClient.sendEchoResponse() {
val sending = SstpEchoResponse().also { it.update() }
parent.controlQueue.add(sending)
}
internal fun SstpClient.sendLastGreeting() {
val sending = when (status.sstp) {
SstpStatus.CALL_DISCONNECT_IN_PROGRESS_1 -> SstpCallDisconnect()
SstpStatus.CALL_DISCONNECT_IN_PROGRESS_2 -> SstpCallDisconnectAck()
else -> SstpCallAbort()
}
sending.update()
parent.controlQueue.add(sending)
throw SuicideException()
}
internal fun SstpClient.receiveCallConnectAck() {
val received = SstpCallConnectAck()
if (!tryReadingPacket(received)) return
networkSetting.hashProtocol = when (received.request.bitmask.toInt()) {
in 2..3 -> CERT_HASH_PROTOCOL_SHA256
1 -> CERT_HASH_PROTOCOL_SHA1
else -> {
parent.informInvalidUnit(::receiveCallConnectAck)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return
}
}
networkSetting.nonce = received.request.nonce
status.sstp = SstpStatus.CLIENT_CONNECT_ACK_RECEIVED
negotiationCounter.reset()
negotiationTimer.reset()
}
internal fun SstpClient.receiveEchoRequest() {
val received = SstpEchoRequest()
if (!tryReadingPacket(received)) return
sendEchoResponse()
}
internal fun SstpClient.receiveEchoResponse() {
val received = SstpEchoResponse()
if (!tryReadingPacket(received)) return
}
private class HashSetting(hashProtocol: Byte) {
val cmacSize: Short // little endian
val digestProtocol: String
val macProtocol: String
init {
when (hashProtocol) {
CERT_HASH_PROTOCOL_SHA1 -> {
cmacSize = 0x1400.toShort()
digestProtocol = "SHA-1"
macProtocol = "HmacSHA1"
}
CERT_HASH_PROTOCOL_SHA256 -> {
cmacSize = 0x2000.toShort()
digestProtocol = "SHA-256"
macProtocol = "HmacSHA256"
}
else -> throw NotImplementedError()
}
}
}
private fun generateChapHLAK(setting: NetworkSetting): ByteArray {
val passArray = setting.HOME_PASSWORD.toByteArray(Charset.forName("UTF-16LE"))
val magic1 = sum(
"5468697320697320746865204D505045",
"204D6173746572204B6579"
).toHexByteArray()
val magic2 = sum(
"4F6E2074686520636C69656E74207369",
"64652C20746869732069732074686520",
"73656E64206B65793B206F6E20746865",
"2073657276657220736964652C206974",
"20697320746865207265636569766520",
"6B65792E"
).toHexByteArray()
val magic3 = sum(
"4F6E2074686520636C69656E74207369",
"64652C20746869732069732074686520",
"72656365697665206B65793B206F6E20",
"7468652073657276657220736964652C",
"206974206973207468652073656E6420",
"6B65792E"
).toHexByteArray()
val pad1 = sum(
"00000000000000000000000000000000",
"00000000000000000000000000000000",
"0000000000000000"
).toHexByteArray()
val pad2 = sum(
"F2F2F2F2F2F2F2F2F2F2F2F2F2F2F2F2",
"F2F2F2F2F2F2F2F2F2F2F2F2F2F2F2F2",
"F2F2F2F2F2F2F2F2"
).toHexByteArray()
return MessageDigest.getInstance("SHA-1").let {
it.update(hashMd4(hashMd4(passArray)))
it.update(setting.chapSetting.clientResponse)
it.update(magic1)
val masterkey = it.digest().sliceArray(0 until 16)
val hlak = ByteArray(32)
it.reset()
it.update(masterkey)
it.update(pad1)
it.update(magic2)
it.update(pad2)
it.digest().copyInto(hlak, endIndex = 16)
it.reset()
it.update(masterkey)
it.update(pad1)
it.update(magic3)
it.update(pad2)
it.digest().copyInto(hlak, 16, endIndex = 16)
hlak
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/misc/supplement.kt<|end_filename|>
package kittoku.osc.misc
import java.nio.ByteBuffer
internal fun ByteArray.isSame(other: ByteArray): Boolean {
if (this.size != other.size) return false
this.zip(other).forEach {
if (it.first != it.second) return false
}
return true
}
internal fun ByteArray.toHexString(parse: Boolean = false): String {
var output = ""
forEachIndexed { index, byte ->
output += String.format("%02X", byte.toInt() and 0xFF)
if (parse) output += if (index % 16 == 15) "\n" else " "
}
return output
}
internal fun String.toHexByteArray(): ByteArray {
if (length % 2 != 0) throw Exception("Fragmented Byte")
val arrayLength = length / 2
val output = ByteArray(arrayLength)
repeat(arrayLength) {
val start = it * 2
output[it] = this.slice(start..start + 1).toInt(16).toByte()
}
return output
}
internal fun sum(vararg words: String): String {
var result = ""
words.forEach {
result += it
}
return result
}
internal fun ByteBuffer.move(length: Int) = this.position(this.position() + length)
<|start_filename|>strongswan/app/src/main/java/org/strongswan/android/logic/imc/collectors/Collector.java<|end_filename|>
/*
* Copyright (C) 2013 <NAME>
* HSR Hochschule fuer Technik Rapperswil
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package org.strongswan.android.logic.imc.collectors;
import org.strongswan.android.logic.imc.attributes.Attribute;
/**
* Interface for measurement collectors
*/
public interface Collector
{
/**
* This method shall return the result of a measurement, if available
* @return attribute or null
*/
public abstract Attribute getMeasurement();
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/layer/SstpClietnt.kt<|end_filename|>
package kittoku.osc.layer
import kittoku.osc.ControlClient
import kittoku.osc.misc.*
import kittoku.osc.negotiator.*
import kittoku.osc.unit.*
internal class SstpClient(parent: ControlClient) : Client(parent) {
internal val negotiationTimer = Timer(60_000L)
internal val negotiationCounter = Counter(3)
internal val echoTimer = Timer(10_000L)
internal val echoCounter = Counter(1)
private fun proceedRequestSent() {
if (negotiationTimer.isOver) {
sendCallConnectRequest()
return
}
if (!challengeWholePacket()) return
if (incomingBuffer.getShort() != SSTP_PACKET_TYPE_CONTROL) {
parent.informInvalidUnit(::proceedRequestSent)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return
}
incomingBuffer.move(2)
when (incomingBuffer.getShort()) {
SSTP_MESSAGE_TYPE_CALL_CONNECT_ACK -> receiveCallConnectAck()
SSTP_MESSAGE_TYPE_CALL_CONNECT_NAK -> {
parent.inform("Received Call Connect Nak", null)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return
}
SSTP_MESSAGE_TYPE_CALL_DISCONNECT -> {
parent.informReceivedCallDisconnect(::proceedRequestSent)
status.sstp = SstpStatus.CALL_DISCONNECT_IN_PROGRESS_2
}
SSTP_MESSAGE_TYPE_CALL_ABORT -> {
parent.informReceivedCallAbort(::proceedRequestSent)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_2
}
else -> {
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return
}
}
incomingBuffer.forget()
}
private fun proceedAckReceived() {
if (negotiationTimer.isOver) {
parent.informTimerOver(::proceedAckReceived)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return
}
if (status.ppp == PppStatus.NEGOTIATE_IPCP || status.ppp == PppStatus.NETWORK) {
sendCallConnected()
status.sstp = SstpStatus.CLIENT_CALL_CONNECTED
echoTimer.reset()
return
}
if (!challengeWholePacket()) return
when (incomingBuffer.getShort()) {
SSTP_PACKET_TYPE_DATA -> readAsData()
SSTP_PACKET_TYPE_CONTROL -> {
incomingBuffer.move(2)
when (incomingBuffer.getShort()) {
SSTP_MESSAGE_TYPE_CALL_DISCONNECT -> {
parent.informReceivedCallDisconnect(::proceedAckReceived)
status.sstp = SstpStatus.CALL_DISCONNECT_IN_PROGRESS_2
}
SSTP_MESSAGE_TYPE_CALL_ABORT -> {
parent.informReceivedCallAbort(::proceedAckReceived)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_2
}
else -> {
parent.informInvalidUnit(::proceedAckReceived)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return
}
}
incomingBuffer.forget()
}
else -> {
parent.informInvalidUnit(::proceedAckReceived)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
}
}
}
private fun proceedConnected() {
if (echoTimer.isOver) {
sendEchoRequest()
return
}
if (!challengeWholePacket()) return
echoTimer.reset()
echoCounter.reset()
when (incomingBuffer.getShort()) {
SSTP_PACKET_TYPE_DATA-> readAsData()
SSTP_PACKET_TYPE_CONTROL -> {
incomingBuffer.move(2)
when (incomingBuffer.getShort()) {
SSTP_MESSAGE_TYPE_CALL_DISCONNECT -> {
parent.informReceivedCallDisconnect(::proceedConnected)
status.sstp = SstpStatus.CALL_DISCONNECT_IN_PROGRESS_2
}
SSTP_MESSAGE_TYPE_CALL_ABORT -> {
parent.informReceivedCallAbort(::proceedConnected)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_2
}
SSTP_MESSAGE_TYPE_ECHO_REQUEST -> receiveEchoRequest()
SSTP_MESSAGE_TYPE_ECHO_RESPONSE -> receiveEchoResponse()
else -> {
parent.informInvalidUnit(::proceedConnected)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
return
}
}
incomingBuffer.forget()
}
else -> {
parent.informInvalidUnit(::proceedConnected)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
}
}
}
override fun proceed() {
when (status.sstp) {
SstpStatus.CLIENT_CALL_DISCONNECTED -> {
parent.sslTerminal.initializeSocket()
sendCallConnectRequest()
status.sstp = SstpStatus.CLIENT_CONNECT_REQUEST_SENT
}
SstpStatus.CLIENT_CONNECT_REQUEST_SENT -> proceedRequestSent()
SstpStatus.CLIENT_CONNECT_ACK_RECEIVED -> proceedAckReceived()
SstpStatus.CLIENT_CALL_CONNECTED -> proceedConnected()
else -> sendLastGreeting()
}
}
private fun readAsData() {
incomingBuffer.pppLimit = incomingBuffer.getShort().toInt() + incomingBuffer.position() - 4
if (incomingBuffer.getShort() != PPP_HEADER) {
parent.inform("Received a non-PPP payload", null)
status.sstp = SstpStatus.CALL_ABORT_IN_PROGRESS_1
}
}
}
<|start_filename|>strongswan/app/src/main/java/org/strongswan/android/logic/TrustedCertificateManager.java<|end_filename|>
/*
* Copyright (C) 2012-2015 <NAME>
* Copyright (C) 2012 <NAME>
* Copyright (C) 2012 <NAME>
* HSR Hochschule fuer Technik Rapperswil
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package org.strongswan.android.logic;
import android.util.Log;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Observable;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class TrustedCertificateManager extends Observable
{
private static final String TAG = TrustedCertificateManager.class.getSimpleName();
private final ReentrantReadWriteLock mLock = new ReentrantReadWriteLock();
private Hashtable<String, X509Certificate> mCACerts = new Hashtable<String, X509Certificate>();
private volatile boolean mReload;
private boolean mLoaded;
private final ArrayList<KeyStore> mKeyStores = new ArrayList<KeyStore>();
public enum TrustedCertificateSource
{
SYSTEM("system:"),
USER("user:"),
LOCAL("local:");
private final String mPrefix;
private TrustedCertificateSource(String prefix)
{
mPrefix = prefix;
}
private String getPrefix()
{
return mPrefix;
}
}
/**
* Private constructor to prevent instantiation from other classes.
*/
private TrustedCertificateManager()
{
for (String name : new String[]{"LocalCertificateStore", "AndroidCAStore"})
{
KeyStore store;
try
{
store = KeyStore.getInstance(name);
store.load(null, null);
mKeyStores.add(store);
}
catch (Exception e)
{
Log.e(TAG, "Unable to load KeyStore: " + name);
e.printStackTrace();
}
}
}
/**
* This is not instantiated until the first call to getInstance()
*/
private static class Singleton
{
public static final TrustedCertificateManager mInstance = new TrustedCertificateManager();
}
/**
* Get the single instance of the CA certificate manager.
*
* @return CA certificate manager
*/
public static TrustedCertificateManager getInstance()
{
return Singleton.mInstance;
}
/**
* Invalidates the current load state so that the next call to load()
* will force a reload of the cached CA certificates.
*
* Observers are notified when this method is called.
*
* @return reference to itself
*/
public TrustedCertificateManager reset()
{
Log.d(TAG, "Force reload of cached CA certificates on next load");
this.mReload = true;
this.setChanged();
this.notifyObservers();
return this;
}
/**
* Ensures that the certificates are loaded but does not force a reload.
* As this takes a while if the certificates are not loaded yet it should
* be called asynchronously.
*
* Observers are only notified when the certificates are initially loaded, not when reloaded.
*
* @return reference to itself
*/
public TrustedCertificateManager load()
{
Log.d(TAG, "Ensure cached CA certificates are loaded");
this.mLock.writeLock().lock();
if (!this.mLoaded || this.mReload)
{
this.mReload = false;
loadCertificates();
}
this.mLock.writeLock().unlock();
return this;
}
/**
* Opens the CA certificate KeyStore and loads the cached certificates.
* The lock must be locked when calling this method.
*/
private void loadCertificates()
{
Log.d(TAG, "Load cached CA certificates");
Hashtable<String, X509Certificate> certs = new Hashtable<String, X509Certificate>();
for (KeyStore store : this.mKeyStores)
{
fetchCertificates(certs, store);
}
this.mCACerts = certs;
if (!this.mLoaded)
{
this.setChanged();
this.notifyObservers();
this.mLoaded = true;
}
Log.d(TAG, "Cached CA certificates loaded");
}
/**
* Load all X.509 certificates from the given KeyStore.
*
* @param certs Hashtable to store certificates in
* @param store KeyStore to load certificates from
*/
private void fetchCertificates(Hashtable<String, X509Certificate> certs, KeyStore store)
{
try
{
Enumeration<String> aliases = store.aliases();
while (aliases.hasMoreElements())
{
String alias = aliases.nextElement();
Certificate cert;
cert = store.getCertificate(alias);
if (cert != null && cert instanceof X509Certificate)
{
certs.put(alias, (X509Certificate)cert);
}
}
}
catch (KeyStoreException ex)
{
ex.printStackTrace();
}
}
/**
* Retrieve the CA certificate with the given alias.
*
* @param alias alias of the certificate to get
* @return the certificate, null if not found
*/
public X509Certificate getCACertificateFromAlias(String alias)
{
X509Certificate certificate = null;
if (this.mLock.readLock().tryLock())
{
certificate = this.mCACerts.get(alias);
this.mLock.readLock().unlock();
}
else
{ /* if we cannot get the lock load it directly from the KeyStore,
* should be fast for a single certificate */
for (KeyStore store : this.mKeyStores)
{
try
{
Certificate cert = store.getCertificate(alias);
if (cert != null && cert instanceof X509Certificate)
{
certificate = (X509Certificate)cert;
break;
}
}
catch (KeyStoreException e)
{
e.printStackTrace();
}
}
}
return certificate;
}
/**
* Get all CA certificates (from all keystores).
*
* @return Hashtable mapping aliases to certificates
*/
@SuppressWarnings("unchecked")
public Hashtable<String, X509Certificate> getAllCACertificates()
{
Hashtable<String, X509Certificate> certs;
this.mLock.readLock().lock();
certs = (Hashtable<String, X509Certificate>)this.mCACerts.clone();
this.mLock.readLock().unlock();
return certs;
}
/**
* Get all certificates from the given source.
*
* @param source type to filter certificates
* @return Hashtable mapping aliases to certificates
*/
public Hashtable<String, X509Certificate> getCACertificates(TrustedCertificateSource source)
{
Hashtable<String, X509Certificate> certs = new Hashtable<String, X509Certificate>();
this.mLock.readLock().lock();
for (String alias : this.mCACerts.keySet())
{
if (alias.startsWith(source.getPrefix()))
{
certs.put(alias, this.mCACerts.get(alias));
}
}
this.mLock.readLock().unlock();
return certs;
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/SstpVpnService.kt<|end_filename|>
package kittoku.osc
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.VpnService
import android.os.Build
import android.service.quicksettings.TileService
import androidx.core.app.NotificationCompat
import androidx.preference.PreferenceManager
import kittoku.osc.preference.OscPreference
import kittoku.osc.preference.accessor.getBooleanPrefValue
import kittoku.osc.preference.accessor.setBooleanPrefValue
internal const val ACTION_VPN_CONNECT = "kittoku.osc.connect"
internal const val ACTION_VPN_DISCONNECT = "kittoku.osc.disconnect"
internal class SstpVpnService : VpnService() {
private lateinit var prefs: SharedPreferences
private lateinit var listener: SharedPreferences.OnSharedPreferenceChangeListener
internal val CHANNEL_ID = "OpenSSTPClient"
private var controlClient: ControlClient? = null
private fun setRootState(state: Boolean) {
setBooleanPrefValue(state, OscPreference.ROOT_STATE, prefs)
}
private fun requestTileListening() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
TileService.requestListeningState(
applicationContext,
ComponentName(applicationContext, SstpTileService::class.java)
)
}
}
override fun onCreate() {
prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == OscPreference.ROOT_STATE.name) {
val newState = getBooleanPrefValue(OscPreference.ROOT_STATE, prefs)
setBooleanPrefValue(newState, OscPreference.HOME_CONNECTOR, prefs)
requestTileListening()
}
}
prefs.registerOnSharedPreferenceChangeListener(listener)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return if (ACTION_VPN_DISCONNECT == intent?.action ?: false) {
controlClient?.kill(null)
controlClient = null
stopSelf()
Service.START_NOT_STICKY
} else {
controlClient?.kill(null)
controlClient = ControlClient(this).also {
beForegrounded()
it.run()
}
setRootState(true)
Service.START_STICKY
}
}
private fun beForegrounded() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT)
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
val intent = Intent(
applicationContext,
SstpVpnService::class.java
).setAction(ACTION_VPN_DISCONNECT)
val pendingIntent = PendingIntent.getService(applicationContext, 0, intent, 0)
val builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID).also {
it.setSmallIcon(R.drawable.ic_baseline_vpn_lock_24)
it.setContentText("Disconnect SSTP connection")
it.priority = NotificationCompat.PRIORITY_DEFAULT
it.setContentIntent(pendingIntent)
it.setAutoCancel(true)
}
startForeground(1, builder.build())
}
override fun onDestroy() {
controlClient?.kill(null)
setRootState(false)
prefs.unregisterOnSharedPreferenceChangeListener(listener)
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/fragment/HomeFragment.kt<|end_filename|>
package kittoku.osc.fragment
import android.app.Activity
import android.content.*
import android.net.*
import android.os.Bundle
import android.view.View
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import kittoku.osc.*
import kittoku.osc.preference.OscPreference
import kittoku.osc.preference.accessor.*
import kittoku.osc.preference.checkPreferences
import kittoku.osc.preference.custom.HomeConnectorPreference
import kittoku.osc.preference.toastInvalidSetting
class HomeFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.home, rootKey)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
attachConnectorListener()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
startVpnService(ACTION_VPN_CONNECT)
}
}
private fun startVpnService(action: String) {
context?.startService(Intent(context, SstpVpnService::class.java).setAction(action))
}
private fun attachConnectorListener() {
findPreference<HomeConnectorPreference>(OscPreference.HOME_CONNECTOR.name)!!.also {
it.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newState ->
if (newState == true) {
checkPreferences(preferenceManager.sharedPreferences)?.also { message ->
toastInvalidSetting(message, context)
return@OnPreferenceChangeListener false
}
VpnService.prepare(context)?.also { intent ->
startActivityForResult(intent, 0)
} ?: onActivityResult(0, Activity.RESULT_OK, null)
} else {
startVpnService(ACTION_VPN_DISCONNECT)
}
true
}
}
}
}
<|start_filename|>strongswan/app/src/main/java/org/strongswan/android/utils/IPRangeSet.java<|end_filename|>
/*
* Copyright (C) 2012-2017 <NAME>
* HSR Hochschule fuer Technik Rapperswil
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package org.strongswan.android.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
/**
* Class that represents a set of IP address ranges (not necessarily proper subnets) and allows
* modifying the set and enumerating the resulting subnets.
*/
public class IPRangeSet implements Iterable<IPRange>
{
private TreeSet<IPRange> mRanges = new TreeSet<>();
/**
* Parse the given string (space separated ranges in CIDR or range notation) and return the
* resulting set or {@code null} if the string was invalid. An empty set is returned if the given string
* is {@code null}.
*/
public static IPRangeSet fromString(String ranges)
{
IPRangeSet set = new IPRangeSet();
if (ranges != null)
{
for (String range : ranges.split("\\s+"))
{
try
{
set.add(new IPRange(range));
}
catch (Exception unused)
{ /* besides due to invalid strings exceptions might get thrown if the string
* contains a hostname (NetworkOnMainThreadException) */
return null;
}
}
}
return set;
}
/**
* Add a range to this set. Automatically gets merged with existing ranges.
*/
public void add(IPRange range)
{
if (mRanges.contains(range))
{
return;
}
reinsert:
while (true)
{
Iterator<IPRange> iterator = mRanges.iterator();
while (iterator.hasNext())
{
IPRange existing = iterator.next();
IPRange replacement = existing.merge(range);
if (replacement != null)
{
iterator.remove();
range = replacement;
continue reinsert;
}
}
mRanges.add(range);
break;
}
}
/**
* Add all ranges from the given set.
*/
public void add(IPRangeSet ranges)
{
if (ranges == this)
{
return;
}
for (IPRange range : ranges.mRanges)
{
add(range);
}
}
/**
* Add all ranges from the given collection to this set.
*/
public void addAll(Collection<? extends IPRange> coll)
{
for (IPRange range : coll)
{
add(range);
}
}
/**
* Remove the given range from this set. Existing ranges are automatically adjusted.
*/
public void remove(IPRange range)
{
ArrayList <IPRange> additions = new ArrayList<>();
Iterator<IPRange> iterator = mRanges.iterator();
while (iterator.hasNext())
{
IPRange existing = iterator.next();
List<IPRange> result = existing.remove(range);
if (result.size() == 0)
{
iterator.remove();
}
else if (!result.get(0).equals(existing))
{
iterator.remove();
additions.addAll(result);
}
}
mRanges.addAll(additions);
}
/**
* Remove the given ranges from ranges in this set.
*/
public void remove(IPRangeSet ranges)
{
if (ranges == this)
{
mRanges.clear();
return;
}
for (IPRange range : ranges.mRanges)
{
remove(range);
}
}
/**
* Get all the subnets derived from all the ranges in this set.
*/
public Iterable<IPRange> subnets()
{
return new Iterable<IPRange>()
{
@Override
public Iterator<IPRange> iterator()
{
return new Iterator<IPRange>()
{
private Iterator<IPRange> mIterator = mRanges.iterator();
private List<IPRange> mSubnets;
@Override
public boolean hasNext()
{
return (mSubnets != null && mSubnets.size() > 0) || mIterator.hasNext();
}
@Override
public IPRange next()
{
if (mSubnets == null || mSubnets.size() == 0)
{
IPRange range = mIterator.next();
mSubnets = range.toSubnets();
}
return mSubnets.remove(0);
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
};
}
@Override
public Iterator<IPRange> iterator()
{
return mRanges.iterator();
}
/**
* Returns the number of ranges, not subnets.
*/
public int size()
{
return mRanges.size();
}
@Override
public String toString()
{ /* we could use TextUtils, but that causes the unit tests to fail */
StringBuilder sb = new StringBuilder();
for (IPRange range : mRanges)
{
if (sb.length() > 0)
{
sb.append(" ");
}
sb.append(range.toString());
}
return sb.toString();
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/misc/NetworkObserver.kt<|end_filename|>
package kittoku.osc.misc
import android.net.*
import android.os.Build
import androidx.preference.PreferenceManager
import kittoku.osc.ControlClient
import kittoku.osc.preference.OscPreference
import kittoku.osc.preference.accessor.setStringPrefValue
internal class NetworkObserver(val parent: ControlClient) {
private val manager = parent.vpnService.getSystemService(ConnectivityManager::class.java)
private val callback: ConnectivityManager.NetworkCallback
private val prefs = PreferenceManager.getDefaultSharedPreferences(parent.vpnService.applicationContext)
init {
wipeStatus()
val request = NetworkRequest.Builder().let {
it.addTransportType(NetworkCapabilities.TRANSPORT_VPN)
it.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
it.build()
}
callback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
manager.getLinkProperties(network)?.also {
updateSummary(it)
}
}
}
override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
updateSummary(linkProperties)
}
}
manager.registerNetworkCallback(request, callback)
}
private fun updateSummary(properties: LinkProperties) {
val summary = mutableListOf<String>()
summary.add("[Assigned IP Address]")
properties.linkAddresses.forEach {
summary.add(it.address.hostAddress)
}
summary.add("")
summary.add("[DNS server]")
properties.dnsServers.forEach {
summary.add(it.hostAddress)
}
summary.add("")
summary.add("[Route]")
properties.routes.forEach {
summary.add(it.toString())
}
summary.add("")
summary.add("[SSL/TLS parameters]")
summary.add("PROTOCOL: ${parent.sslTerminal.socket.session.protocol}")
summary.add("SUITE: ${parent.sslTerminal.socket.session.cipherSuite}")
summary.reduce { acc, s ->
acc + "\n" + s
}.also {
setStringPrefValue(it, OscPreference.HOME_STATUS, prefs)
}
}
private fun wipeStatus() {
setStringPrefValue("", OscPreference.HOME_STATUS, prefs)
}
internal fun close() {
try {
manager.unregisterNetworkCallback(callback)
} catch (_: IllegalArgumentException) {} // already unregistered
wipeStatus()
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/unit/PppChapFrame.kt<|end_filename|>
package kittoku.osc.unit
import kittoku.osc.misc.DataUnitParsingError
import kittoku.osc.misc.IncomingBuffer
import java.nio.ByteBuffer
import kotlin.properties.Delegates
internal const val CHAP_CODE_CHALLENGE: Byte = 1
internal const val CHAP_CODE_RESPONSE: Byte = 2
internal const val CHAP_CODE_SUCCESS: Byte = 3
internal const val CHAP_CODE_FAILURE: Byte = 4
internal abstract class ChapFrame : PppFrame() {
override val protocol = PPP_PROTOCOL_CHAP
}
internal class ChapChallenge : ChapFrame() {
override val code = CHAP_CODE_CHALLENGE
override val validLengthRange = 21..Short.MAX_VALUE
private var valueLength by Delegates.observable(16) { _, _, new ->
if (new != 16) throw DataUnitParsingError()
}
internal val value = ByteArray(16)
internal var name = ByteArray(0)
override fun read(bytes: IncomingBuffer) {
readHeader(bytes)
valueLength = bytes.getByte().toInt()
bytes.get(value)
name = ByteArray(_length - validLengthRange.first).also { bytes.get(it) }
}
override fun write(bytes: ByteBuffer) {
writeHeader(bytes)
bytes.put(valueLength.toByte())
bytes.put(value)
bytes.put(name)
}
override fun update() {
_length = validLengthRange.first + name.size
}
}
internal class ChapResponse : ChapFrame() {
override val code = CHAP_CODE_RESPONSE
override val validLengthRange = 54..Short.MAX_VALUE
internal var valueLength by Delegates.observable(49) { _, _, new ->
if (new != 49) throw DataUnitParsingError()
}
internal val challenge = ByteArray(16)
internal val response = ByteArray(24)
internal var flag: Byte = 0
internal var name = ByteArray(0)
override fun read(bytes: IncomingBuffer) {
readHeader(bytes)
valueLength = bytes.getByte().toInt()
bytes.get(challenge)
bytes.move(8)
bytes.get(response)
flag = bytes.getByte()
name = ByteArray(_length - validLengthRange.first).also { bytes.get(it) }
}
override fun write(bytes: ByteBuffer) {
writeHeader(bytes)
bytes.put(valueLength.toByte())
bytes.put(challenge)
bytes.put(ByteArray(8))
bytes.put(response)
bytes.put(flag)
bytes.put(name)
}
override fun update() {
_length = validLengthRange.first + name.size
}
}
internal class ChapSuccess : ChapFrame() {
override val code = CHAP_CODE_SUCCESS
override val validLengthRange = 46..Short.MAX_VALUE
internal val response = ByteArray(42)
internal var message = ByteArray(0)
private val isValidResponse: Boolean
get() {
if (response[0] != 0x53.toByte()) return false
if (response[1] != 0x3D.toByte()) return false
response.sliceArray(2..response.lastIndex).forEach {
if (it !in 0x30..0x39 && it !in 0x41..0x46) return false
}
return true
}
override fun read(bytes: IncomingBuffer) {
readHeader(bytes)
bytes.get(response)
message = ByteArray(_length - validLengthRange.first).also { bytes.get(it) }
if (!isValidResponse) throw DataUnitParsingError()
}
override fun write(bytes: ByteBuffer) {
writeHeader(bytes)
bytes.put(response)
bytes.put(message)
}
override fun update() {
_length = validLengthRange.first + message.size
}
}
internal class ChapFailure : ChapFrame() {
override val code = CHAP_CODE_FAILURE
override val validLengthRange = 4..Short.MAX_VALUE
internal var message = ByteArray(0)
override fun read(bytes: IncomingBuffer) {
readHeader(bytes)
message = ByteArray(_length - validLengthRange.first).also { bytes.get(it) }
}
override fun write(bytes: ByteBuffer) {
writeHeader(bytes)
bytes.put(message)
}
override fun update() {
_length = validLengthRange.first + message.size
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/fragment/SettingFragment.kt<|end_filename|>
package kittoku.osc.fragment
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import kittoku.osc.R
import kittoku.osc.preference.OscPreference
import kittoku.osc.preference.accessor.setStringPrefValue
import kittoku.osc.preference.custom.DirectoryPreference
private const val CERT_DIR_REQUEST_CODE: Int = 0
private const val LOG_DIR_REQUEST_CODE: Int = 1
internal class SettingFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.settings, rootKey)
setCertDirListener()
setLogDirListener()
}
private fun setCertDirListener() {
findPreference<DirectoryPreference>(OscPreference.SSL_CERT_DIR.name)!!.also {
it.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
startActivityForResult(intent, CERT_DIR_REQUEST_CODE)
true
}
}
}
private fun setLogDirListener() {
findPreference<Preference>(OscPreference.LOG_DIR.name)!!.also {
it.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
intent.flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION
startActivityForResult(intent, LOG_DIR_REQUEST_CODE)
true
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
when (requestCode) {
CERT_DIR_REQUEST_CODE -> {
val uri = if (resultCode == Activity.RESULT_OK) resultData?.data?.also {
context?.contentResolver?.takePersistableUriPermission(
it, Intent.FLAG_GRANT_READ_URI_PERMISSION
)
} else null
setStringPrefValue(
uri?.toString() ?: "",
OscPreference.SSL_CERT_DIR,
preferenceManager.sharedPreferences
)
}
LOG_DIR_REQUEST_CODE -> {
val uri = if (resultCode == Activity.RESULT_OK) resultData?.data?.also {
context?.contentResolver?.takePersistableUriPermission(
it, Intent.FLAG_GRANT_WRITE_URI_PERMISSION
)
} else null
setStringPrefValue(
uri?.toString() ?: "",
OscPreference.LOG_DIR,
preferenceManager.sharedPreferences
)
}
}
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/MainActivity.kt<|end_filename|>
package kittoku.osc
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import kittoku.osc.databinding.ActivityMainBinding
import kittoku.osc.fragment.HomeFragment
import kittoku.osc.fragment.SettingFragment
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = "Open SSTP Client: ${BuildConfig.VERSION_NAME}"
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
object : FragmentStateAdapter(this) {
private val homeFragment = HomeFragment()
private val settingFragment = SettingFragment()
override fun getItemCount() = 2
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> homeFragment
1 -> settingFragment
else -> throw NotImplementedError()
}
}
}.also {
binding.pager.adapter = it
}
TabLayoutMediator(binding.tabBar, binding.pager) { tab, position ->
tab.text = when (position) {
0 -> "HOME"
1 -> "SETTING"
else -> throw NotImplementedError()
}
}.attach()
}
}
<|start_filename|>Open-SSTP-Client/app/src/main/java/kittoku/osc/preference/accessor/string.kt<|end_filename|>
package kittoku.osc.preference.accessor
import android.content.SharedPreferences
import kittoku.osc.preference.OscPreference
internal fun getStringPrefValue(key: OscPreference, prefs: SharedPreferences): String {
val defaultValue = when (key) {
OscPreference.HOME_HOSTNAME,
OscPreference.HOME_USERNAME,
OscPreference.HOME_PASSWORD,
OscPreference.HOME_STATUS,
OscPreference.SSL_CERT_DIR,
OscPreference.LOG_DIR -> ""
OscPreference.SSL_VERSION -> "DEFAULT"
else -> throw NotImplementedError()
}
return prefs.getString(key.name, defaultValue)!!
}
internal fun setStringPrefValue(value: String, key: OscPreference, prefs: SharedPreferences) {
prefs.edit().also {
it.putString(key.name, value)
it.apply()
}
}
| rakasatria/vpn-bpk |
<|start_filename|>app/src/main/java/co/touchlab/compose/animations/shapes/Triangle.kt<|end_filename|>
package co.touchlab.compose.animations.shapes
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import co.touchlab.compose.animations.R
@Composable
fun Triangle(
modifier: Modifier = Modifier,
size: Dp = 24.dp,
backgroundColor: Color = colorResource(id = R.color.ball_gray),
) {
Box(
modifier = modifier
.width(size)
.height(size)
.clipToBounds()
.background(backgroundColor, TriangleShape)
)
}
private val TriangleShape = GenericShape { size, _ ->
moveTo(size.width / 2f, 0f)
lineTo(size.width, size.height)
lineTo(0f, size.height)
}
@Composable
@Preview
fun TrianglePreview() {
Triangle()
}
<|start_filename|>value-animator/src/main/kotlin/co/touchlab/compose/value/animator/ValueAtFraction.kt<|end_filename|>
package co.touchlab.compose.value.animator
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.colorspace.ColorSpaces
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import co.touchlab.compose.value.animator.utils.minus
import co.touchlab.compose.value.animator.utils.plus
import co.touchlab.compose.value.animator.utils.times
import kotlin.math.pow
/**
* This interface is responsible for converting the fraction value into one value of type T
* between initialValue and finalValue
*/
fun interface ValueAtFraction<T> {
companion object {}
/**
* @param fraction Float representing an animation progress. Always between 0f and 1f
* @param initialValue The initial value from the range
* @param finalValue The final value from the range
*/
operator fun invoke(
fraction: Float,
initialValue: T,
finalValue: T,
): T
}
val ValueAtFraction.Companion.Float: ValueAtFraction<Float>
get() = floatAtFraction
val ValueAtFraction.Companion.Int: ValueAtFraction<Int>
get() = intAtFraction
val ValueAtFraction.Companion.Dp: ValueAtFraction<Dp>
get() = dpAtFraction
val ValueAtFraction.Companion.Size: ValueAtFraction<Size>
get() = sizeAtFraction
val ValueAtFraction.Companion.Offset: ValueAtFraction<Offset>
get() = offsetAtFraction
val ValueAtFraction.Companion.Rect: ValueAtFraction<Rect>
get() = rectAtFraction
val ValueAtFraction.Companion.IntOffset: ValueAtFraction<IntOffset>
get() = intOffsetAtFraction
val ValueAtFraction.Companion.IntSize: ValueAtFraction<IntSize>
get() = intSizeAtFraction
val ValueAtFraction.Companion.Color: ValueAtFraction<Color>
get() = colorAtFraction
private val floatAtFraction = ValueAtFraction<Float> { fraction, initialValue, finalValue ->
initialValue + (finalValue - initialValue) * fraction
}
private val intAtFraction = ValueAtFraction<Int> { fraction, initialValue, finalValue ->
initialValue + ((finalValue - initialValue) * fraction).toInt()
}
private val dpAtFraction = ValueAtFraction<Dp> { fraction, initialValue, finalValue ->
initialValue + (finalValue - initialValue) * fraction
}
private val sizeAtFraction = ValueAtFraction<Size> { fraction, initialValue, finalValue ->
initialValue + (finalValue - initialValue) * fraction
}
private val offsetAtFraction = ValueAtFraction<Offset> { fraction, initialValue, finalValue ->
initialValue + (finalValue - initialValue) * fraction
}
private val rectAtFraction = ValueAtFraction<Rect> { fraction, initialValue, finalValue ->
initialValue + (finalValue - initialValue) * fraction
}
private val intOffsetAtFraction = ValueAtFraction<IntOffset> { fraction, initialValue, finalValue ->
initialValue + (finalValue - initialValue) * fraction
}
private val intSizeAtFraction = ValueAtFraction<IntSize> { fraction, initialValue, finalValue ->
initialValue + (finalValue - initialValue) * fraction
}
private val colorAtFraction = ValueAtFraction<Color> { fraction, initialValue, finalValue ->
val initialValueAsSRGB = initialValue.convert(ColorSpaces.Srgb)
val finalValueAsSRGB = finalValue.convert(ColorSpaces.Srgb)
val startA = initialValueAsSRGB.alpha
val startR = initialValueAsSRGB.red.pow(2.2f)
val startG = initialValueAsSRGB.green.pow(2.2f)
val startB = initialValueAsSRGB.blue.pow(2.2f)
val endA = finalValueAsSRGB.alpha
val endR = finalValueAsSRGB.red.pow(2.2f)
val endG = finalValueAsSRGB.green.pow(2.2f)
val endB = finalValueAsSRGB.blue.pow(2.2f)
Color(
red = startR + fraction * (endR - startR),
green = startG + fraction * (endG - startG),
blue = startB + fraction * (endB - startB),
alpha = startA + fraction * (endA - startA),
colorSpace = ColorSpaces.Srgb
)
}
<|start_filename|>value-animator-compat/src/main/kotlin/co/touchlab/compose/value/animator/compat/valueAnimatorOfIntAsState.kt<|end_filename|>
package co.touchlab.compose.value.animator.compat
import android.animation.ValueAnimator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.remember
@Composable
fun rememberIntValueAnimator(
vararg values: Int,
setupAnimator: ValueAnimator.() -> Unit = {},
): ValueAnimator = remember(keys = values.toTypedArray()) {
ValueAnimator.ofInt(*values).apply(setupAnimator)
}
@Composable
fun valueAnimatorOfIntAsState(
vararg values: Int,
setupAnimator: ValueAnimator.() -> Unit = {},
): State<Int> {
val animator = rememberIntValueAnimator(
values = values,
setupAnimator = setupAnimator
)
return valueAnimatorChangesAsState(
values = values.toTypedArray(),
animator = animator,
)
}
<|start_filename|>value-animator/src/main/kotlin/co/touchlab/compose/value/animator/utils/+size.kt<|end_filename|>
package co.touchlab.compose.value.animator.utils
import androidx.compose.ui.geometry.Size
operator fun Size.minus(other: Size): Size = Size(
width = this.width - other.width,
height = this.height - other.height
)
operator fun Size.plus(other: Size): Size = Size(
width = this.width + other.width,
height = this.height + other.height
)
<|start_filename|>build.gradle.kts<|end_filename|>
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
// TODO: Remove this when upgrade to gradle/agp 7.2
// https://github.com/gradle/gradle/issues/16958
val libs = project.extensions.getByType<VersionCatalogsExtension>().named("libs")
as org.gradle.accessors.dm.LibrariesForLibs
classpath(libs.android.gradlePlugin)
classpath(libs.kotlin.gradlePlugin)
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
tasks.register("clean", Delete::class) {
delete(rootProject.buildDir)
}
<|start_filename|>easing/src/main/java/co/touchlab/compose/easing/Sine.kt<|end_filename|>
package co.touchlab.compose.easing
import androidx.compose.animation.core.Easing
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
// https://easings.net/#easeInSine
object EaseInSine : Easing {
override fun transform(fraction: Float): Float =
1 - cos((fraction * PI.toFloat()) / 2)
}
// https://easings.net/#easeOutSine
object EaseOutSine : Easing {
override fun transform(fraction: Float): Float =
sin((fraction * PI.toFloat()) / 2)
}
// https://easings.net/#easeInOutSine
object EaseInOutSine : Easing {
override fun transform(fraction: Float): Float =
-(cos(fraction * PI.toFloat()) - 1) / 2
}
<|start_filename|>easing/src/main/java/co/touchlab/compose/easing/Cubic.kt<|end_filename|>
package co.touchlab.compose.easing
import androidx.compose.animation.core.Easing
import kotlin.math.pow
// https://easings.net/#easeInCubic
object EaseInCubic : Easing {
override fun transform(fraction: Float): Float =
fraction.pow(3)
}
// https://easings.net/#easeOutCubic
object EaseOutCubic : Easing {
override fun transform(fraction: Float): Float =
1 - (1 - fraction).pow(3)
}
// https://easings.net/#easeInOutCubic
object EaseInOutCubic : Easing {
override fun transform(fraction: Float): Float = if (fraction < 0.5f) {
4 * fraction.pow(3)
} else {
1 - (-2 * fraction + 2).pow(3) / 2
}
}
<|start_filename|>easing/src/main/java/co/touchlab/compose/easing/Circ.kt<|end_filename|>
package co.touchlab.compose.easing
import androidx.compose.animation.core.Easing
import kotlin.math.pow
import kotlin.math.sqrt
// https://easings.net/#easeInCirc
object EaseInCirc : Easing {
override fun transform(fraction: Float): Float =
1 - sqrt(1 - fraction.pow(2))
}
// https://easings.net/#easeOutCirc
object EaseOutCirc : Easing {
override fun transform(fraction: Float): Float =
sqrt(1 - (fraction - 1).pow(2))
}
// https://easings.net/#easeInOutCirc
object EaseInOutCirc : Easing {
override fun transform(fraction: Float): Float = if (fraction < 0.5f) {
(1 - sqrt(1 - (2 * fraction).pow(2))) / 2
} else {
(sqrt(1 - (-2 * fraction + 2).pow(2)) + 1) / 2
}
}
<|start_filename|>value-animator/src/main/kotlin/co/touchlab/compose/value/animator/utils/+rect.kt<|end_filename|>
package co.touchlab.compose.value.animator.utils
import androidx.compose.ui.geometry.Rect
operator fun Rect.minus(other: Rect): Rect = Rect(
left = this.left - other.left,
right = this.right - other.right,
top = this.top - other.top,
bottom = this.bottom - other.bottom,
)
operator fun Rect.plus(other: Rect): Rect = Rect(
left = this.left + other.left,
right = this.right + other.right,
top = this.top + other.top,
bottom = this.bottom + other.bottom,
)
operator fun Rect.times(value: Float): Rect = Rect(
left = this.left * value,
right = this.right * value,
top = this.top * value,
bottom = this.bottom * value,
)
operator fun Rect.div(value: Float): Rect = Rect(
left = this.left / value,
right = this.right / value,
top = this.top / value,
bottom = this.bottom / value,
)
<|start_filename|>value-animator/src/main/kotlin/co/touchlab/compose/value/animator/animateTransitionValuesAsState.kt<|end_filename|>
package co.touchlab.compose.value.animator
import androidx.compose.animation.core.InfiniteRepeatableSpec
import androidx.compose.animation.core.InfiniteTransition
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
@Composable
fun InfiniteTransition.animateFloatValues(
vararg values: Float,
animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(animation = tween()),
): State<Float> = animateValues(
values = values.toTypedArray(),
getValueAtFraction = ValueAtFraction.Float,
animationSpec = animationSpec,
)
@Composable
fun InfiniteTransition.animateIntValues(
values: Array<Int>,
animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(animation = tween()),
): State<Int> = animateValues(
values = values,
getValueAtFraction = ValueAtFraction.Int,
animationSpec = animationSpec,
)
@Composable
fun InfiniteTransition.animateDpValues(
values: Array<Dp>,
animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(animation = tween()),
): State<Dp> = animateValues(
values = values,
getValueAtFraction = ValueAtFraction.Dp,
animationSpec = animationSpec,
)
@Composable
fun InfiniteTransition.animateSizeValues(
values: Array<Size>,
animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(animation = tween()),
): State<Size> = animateValues(
values = values,
getValueAtFraction = ValueAtFraction.Size,
animationSpec = animationSpec,
)
@Composable
fun InfiniteTransition.animateOffsetValues(
values: Array<Offset>,
animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(animation = tween()),
): State<Offset> = animateValues(
values = values,
getValueAtFraction = ValueAtFraction.Offset,
animationSpec = animationSpec,
)
@Composable
fun InfiniteTransition.animateRectValues(
values: Array<Rect>,
animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(animation = tween()),
): State<Rect> = animateValues(
values = values,
getValueAtFraction = ValueAtFraction.Rect,
animationSpec = animationSpec,
)
@Composable
fun InfiniteTransition.animateIntOffsetValues(
values: Array<IntOffset>,
animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(animation = tween()),
): State<IntOffset> = animateValues(
values = values,
getValueAtFraction = ValueAtFraction.IntOffset,
animationSpec = animationSpec,
)
@Composable
fun InfiniteTransition.animateIntSizeValues(
values: Array<IntSize>,
animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(animation = tween()),
): State<IntSize> = animateValues(
values = values,
getValueAtFraction = ValueAtFraction.IntSize,
animationSpec = animationSpec,
)
@Composable
fun InfiniteTransition.animateColorValues(
values: Array<Color>,
animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(animation = tween()),
): State<Color> = animateValues(
values = values,
getValueAtFraction = ValueAtFraction.Color,
animationSpec = animationSpec,
)
@Composable
fun <T> InfiniteTransition.animateValues(
vararg values: T,
getValueAtFraction: ValueAtFraction<T>,
animationSpec: InfiniteRepeatableSpec<Float> = infiniteRepeatable(animation = tween()),
): State<T> {
require(values.isNotEmpty()) {
"You should provide at least one item to animate"
}
val valueAnimator by rememberUpdatedState(
MultipleValuesAnimator(values.toList())
)
val animatedFrame by animateFloat(
initialValue = valueAnimator.initialFrameValue,
targetValue = valueAnimator.targetFrameValue,
animationSpec = animationSpec,
)
return remember(valueAnimator) {
derivedStateOf {
valueAnimator.animate(animatedFrame, getValueAtFraction)
}
}
}
<|start_filename|>value-animator-compat/src/main/kotlin/co/touchlab/compose/value/animator/compat/valueAnimatorAsState.kt<|end_filename|>
package co.touchlab.compose.value.animator.compat
import android.animation.ValueAnimator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
@Composable
fun ValueAnimator.observeAsState(
initialValue: Int,
): State<Int> = produceState(initialValue = initialValue) {
removeAllUpdateListeners()
addUpdateListener { value = it.animatedValue as Int }
}
@Composable
fun ValueAnimator.observeAsState(
initialValue: Float,
): State<Float> = produceState(initialValue = initialValue) {
removeAllUpdateListeners()
addUpdateListener { value = it.animatedValue as Float }
}
@Composable
internal fun <T> valueAnimatorChangesAsState(
values: Array<T>,
animator: ValueAnimator,
): State<T> {
val state = remember(keys = values) { mutableStateOf(values.first()) }
DisposableEffect(keys = values) {
val (_, updateCurrentValue) = state
animator.addUpdateListener { updateCurrentValue(it.animatedValue as T) }
animator.start()
onDispose {
animator.removeAllUpdateListeners()
animator.cancel()
}
}
return state
}
<|start_filename|>app/src/main/java/co/touchlab/compose/animations/utils/size.kt<|end_filename|>
package co.touchlab.compose.animations.utils
val IntRange.size: Int
get() = toList().size
<|start_filename|>value-animator/src/main/kotlin/co/touchlab/compose/value/animator/utils/+intSize.kt<|end_filename|>
package co.touchlab.compose.value.animator.utils
import androidx.compose.ui.unit.IntSize
import kotlin.math.roundToInt
operator fun IntSize.minus(other: IntSize): IntSize = IntSize(
width = this.width - other.width,
height = this.height - other.height
)
operator fun IntSize.plus(other: IntSize): IntSize = IntSize(
width = this.width + other.width,
height = this.height + other.height
)
operator fun IntSize.times(value: Float): IntSize = IntSize(
width = (this.width * value).toInt(),
height = (this.height * value).toInt()
)
operator fun IntSize.div(value: Float): IntSize = IntSize(
width = (this.width / value).roundToInt(),
height = (this.height / value).roundToInt()
)
<|start_filename|>easing/src/main/java/co/touchlab/compose/easing/Back.kt<|end_filename|>
package co.touchlab.compose.easing
import androidx.compose.animation.core.Easing
import kotlin.math.pow
// https://easings.net/#easeInBack
object EaseInBack : Easing {
override fun transform(fraction: Float): Float {
val c1 = 1.70158f
val c3 = c1 + 1
return c3 * fraction.pow(3) - c1 * fraction.pow(2)
}
}
// https://easings.net/#easeOutBack
object EaseOutBack : Easing {
override fun transform(fraction: Float): Float {
val c1 = 1.70158f
val c3 = c1 + 1
return 1 + c3 * (fraction - 1).pow(3) + c1 * (fraction - 1).pow(2)
}
}
// https://easings.net/#easeInOutBack
object EaseInOutBack : Easing {
override fun transform(fraction: Float): Float {
val c1 = 1.70158f
val c2 = c1 * 1.525f
return if (fraction < 0.5f) {
((2 * fraction).pow(2) * ((c2 + 1) * 2 * fraction - c2)) / 2
} else {
((2 * fraction - 2).pow(2) * ((c2 + 1) * (fraction * 2 - 2) + c2) + 2) / 2
}
}
}
<|start_filename|>value-animator-compat/src/main/kotlin/co/touchlab/compose/value/animator/compat/valueAnimatorOfFloatAsState.kt<|end_filename|>
package co.touchlab.compose.value.animator.compat
import android.animation.ValueAnimator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.remember
@Composable
fun rememberFloatValueAnimator(
vararg values: Float,
setupAnimator: ValueAnimator.() -> Unit = {},
): ValueAnimator = remember(keys = values.toTypedArray()) {
ValueAnimator.ofFloat(*values).apply(setupAnimator)
}
@Composable
fun valueAnimatorOfFloatAsState(
vararg values: Float,
setupAnimator: ValueAnimator.() -> Unit = {},
): State<Float> {
val animator = rememberFloatValueAnimator(
values = values,
setupAnimator = setupAnimator
)
return valueAnimatorChangesAsState(
values = values.toTypedArray(),
animator = animator,
)
}
<|start_filename|>app/src/main/java/co/touchlab/compose/animations/page/Home.kt<|end_filename|>
package co.touchlab.compose.animations.page
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Icon
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import co.touchlab.compose.animations.R
val HOME_ROUTE = "demo/home"
private const val TAG = "Home"
@Composable
fun Home(navController: NavController) {
Log.d(TAG, "Color: ${Color.Red}")
Log.d(TAG, "Color: ${Color.Green}")
Log.d(TAG, "Color: ${Color.Blue}")
Scaffold(
topBar = {
TopAppBar(
title = { Text("Compose Animations Demo") },
)
},
) {
HomeContent(navController)
}
}
@Composable
private fun HomeContent(
navController: NavController,
) {
LazyColumn {
items(ALL_DEMOS) { (name, route) ->
DemoLink(name = name) {
navController.navigate(route)
}
}
}
}
@Composable
private fun DemoLink(
name: String,
onClick: () -> Unit,
) {
Row(
modifier = Modifier
.clickable(onClick = onClick)
.fillMaxWidth()
.padding(vertical = 16.dp, horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = name,
fontSize = 16.sp,
fontWeight = FontWeight.Bold,
)
Icon(painter = painterResource(id = R.drawable.arrow_forward), null)
}
}
@Composable
@Preview
fun DemoLinkPreview() {
DemoLink("Hello World") {}
}
private val ALL_DEMOS = listOf(
"Easing" to EASING_ROUTE,
"Value Animator (Compat)" to VALUE_ANIMATOR_COMPAT_ROUTE,
"Value Animator" to VALUE_ANIMATOR_ROUTE,
)
<|start_filename|>app/src/main/java/co/touchlab/compose/animations/page/ValueAnimatorDemo.kt<|end_filename|>
package co.touchlab.compose.animations.page
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import co.touchlab.compose.animations.shapes.Ball
import co.touchlab.compose.animations.shapes.Triangle
import co.touchlab.compose.animations.utils.size
import co.touchlab.compose.value.animator.animateColorValuesAsState
import co.touchlab.compose.value.animator.animateFloatValuesAsState
import co.touchlab.compose.value.animator.animateIntValuesAsState
import kotlinx.coroutines.delay
val VALUE_ANIMATOR_ROUTE = "demo/value-animator"
@Composable
fun ValueAnimatorDemo(navController: NavController) {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Value Animator") },
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(Icons.Filled.ArrowBack, null)
}
}
)
},
) { ValueAnimatorContent() }
}
@Composable
private fun ValueAnimatorContent() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
BouncingDots()
BouncingDotsCompat()
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
LoadingButton()
LoadingButtonCompat()
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
SpinningTriangle()
SpinningTriangleCompat()
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
ColorFadingTriangle()
ColorFadingTriangleCompat()
}
}
}
@Composable
private fun BouncingDots() {
// Based on https://github.com/81813780/AVLoadingIndicatorView/blob/master/library/src/main/java/com/wang/avi/indicators/BallPulseSyncIndicator.java
val ballsRange = (0..2)
val ballSize = 12.dp
val animators = ballsRange.map { index ->
animateFloatValuesAsState(
values = floatArrayOf(0f, ballSize.value, 0f),
startDelay = (1 + index) * 70L,
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 200 * ballsRange.size,
),
)
)
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Float Animator",
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
Row(
modifier = Modifier
.padding(top = 8.dp)
.width(ballSize * (ballsRange.size + 1)),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
ballsRange.forEach { index ->
Ball(
modifier = Modifier
.offset(y = animators[index].value.dp)
)
}
}
}
}
@Composable
private fun LoadingButton() {
var isLoading by remember { mutableStateOf(false) }
if (isLoading) {
LaunchedEffect(key1 = isLoading) {
delay(1500)
isLoading = false
}
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Trigger animation",
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
Button(
modifier = Modifier
.width(150.dp)
.padding(top = 4.dp),
onClick = { if (!isLoading) isLoading = true },
) {
if (isLoading) {
val ballOffset by animateFloatValuesAsState(
values = floatArrayOf(-35f, 35f),
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 175,
),
repeatMode = RepeatMode.Reverse,
)
)
Ball(
modifier = Modifier.offset(x = ballOffset.dp)
)
} else {
Text(text = "Login")
}
}
}
}
@Composable
fun SpinningTriangle() {
val rotateXAnimation by animateIntValuesAsState(
values = arrayOf(0, 180, 180, 0, 0),
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 2500,
easing = LinearEasing
),
)
)
val rotateYAnimation by animateIntValuesAsState(
values = arrayOf(0, 0, 180, 180, 0),
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 2500,
easing = LinearEasing
),
)
)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Int animator",
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
Triangle(
modifier = Modifier
.padding(top = 8.dp)
.graphicsLayer(
rotationX = rotateXAnimation.toFloat(),
rotationY = rotateYAnimation.toFloat(),
)
)
}
}
@Composable
fun ColorFadingTriangle() {
val colorAnimation by animateColorValuesAsState(
values = arrayOf(Color.Red, Color.Green, Color.Blue),
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 2500,
easing = LinearEasing,
),
repeatMode = RepeatMode.Reverse,
),
)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "ARGB animator",
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
Triangle(
modifier = Modifier.padding(top = 8.dp),
backgroundColor = colorAnimation
)
}
}
<|start_filename|>app/src/main/java/co/touchlab/compose/animations/MainActivity.kt<|end_filename|>
package co.touchlab.compose.animations
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import co.touchlab.compose.animations.nav.RootNav
import co.touchlab.compose.animations.page.EasingDemo
import co.touchlab.compose.animations.ui.theme.ComposeAnimationsTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeAnimationsTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
RootNav()
}
}
}
}
}
<|start_filename|>easing/src/main/java/co/touchlab/compose/easing/Elastic.kt<|end_filename|>
package co.touchlab.compose.easing
import androidx.compose.animation.core.Easing
import kotlin.math.PI
import kotlin.math.pow
import kotlin.math.sin
// https://easings.net/#easeInElastic
object EaseInElastic : Easing {
override fun transform(fraction: Float): Float {
val c4: Float = (2 * PI.toFloat()) / 3
return if (fraction == 0f || fraction == 1f) {
fraction
} else {
-(2f.pow(10 * fraction - 10)) * sin((fraction * 10 - 10.75f) * c4)
}
}
}
// https://easings.net/#easeOutElastic
object EaseOutElastic : Easing {
override fun transform(fraction: Float): Float {
val c4: Float = (2 * PI.toFloat()) / 3
return if (fraction == 0f || fraction == 1f) {
fraction
} else {
2f.pow(-10 * fraction) * sin((fraction * 10 - 0.75f) * c4) + 1
}
}
}
// https://easings.net/#easeInOutElastic
object EaseInOutElastic : Easing {
override fun transform(fraction: Float): Float {
val c5: Float = (2 * PI.toFloat()) / 4.5f
return when {
fraction == 0f || fraction == 1f -> fraction
fraction < 0.5f -> -(2f.pow(20 * fraction - 10) * sin((20 * fraction - 11.125f) * c5)) / 2
else -> (2f.pow(-20 * fraction + 10) * sin((20 * fraction - 11.125f) * c5)) / 2 + 1
}
}
}
<|start_filename|>easing/src/main/java/co/touchlab/compose/easing/Expo.kt<|end_filename|>
package co.touchlab.compose.easing
import androidx.compose.animation.core.Easing
import kotlin.math.pow
// https://easings.net/#easeInExpo
object EaseInExpo : Easing {
override fun transform(fraction: Float): Float =
if (fraction == 0f) fraction else 2f.pow(10 * fraction - 10)
}
// https://easings.net/#easeOutExpo
object EaseOutExpo : Easing {
override fun transform(fraction: Float): Float =
if (fraction == 1f) fraction else (1 - 2f.pow(-10 * fraction))
}
// https://easings.net/#easeInOutExpo
object EaseInOutExpo : Easing {
override fun transform(fraction: Float): Float = when {
fraction == 0f || fraction == 1f -> fraction
fraction < 0.5f -> 2f.pow(20 * fraction - 10) / 2
else -> (2 - 2f.pow(-20 * fraction + 10)) / 2
}
}
<|start_filename|>easing/src/main/java/co/touchlab/compose/easing/Quint.kt<|end_filename|>
package co.touchlab.compose.easing
import androidx.compose.animation.core.Easing
import kotlin.math.pow
// https://easings.net/#easeInQuint
object EaseInQuint : Easing {
override fun transform(fraction: Float): Float =
1 - (1 - fraction).pow(5)
}
// https://easings.net/#easeOutQuint
object EaseOutQuint : Easing {
override fun transform(fraction: Float): Float =
1 - (1 - fraction).pow(5)
}
// https://easings.net/#easeInOutQuint
object EaseInOutQuint : Easing {
override fun transform(fraction: Float): Float = if (fraction < 0.5f) {
16 * fraction.pow(5)
} else {
1 - (-2 * fraction + 2).pow(5) / 2
}
}
<|start_filename|>app/src/main/java/co/touchlab/compose/animations/page/ValueAnimatorCompatDemo.kt<|end_filename|>
package co.touchlab.compose.animations.page
import android.animation.ValueAnimator
import android.graphics.Color
import android.view.animation.LinearInterpolator
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import co.touchlab.compose.animations.shapes.Ball
import co.touchlab.compose.animations.shapes.Triangle
import co.touchlab.compose.animations.utils.size
import co.touchlab.compose.value.animator.compat.observeAsState
import co.touchlab.compose.value.animator.compat.rememberAnimatorSet
import co.touchlab.compose.value.animator.compat.rememberArgbValueAnimator
import co.touchlab.compose.value.animator.compat.rememberIntValueAnimator
import co.touchlab.compose.value.animator.compat.valueAnimatorOfArgbAsState
import co.touchlab.compose.value.animator.compat.valueAnimatorOfFloatAsState
import co.touchlab.compose.value.animator.compat.valueAnimatorOfIntAsState
import kotlinx.coroutines.delay
val VALUE_ANIMATOR_COMPAT_ROUTE = "demo/value-animator-compat"
@Composable
fun ValueAnimatorCompatDemo(navController: NavController) {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Value Animator (Compat)") },
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(Icons.Filled.ArrowBack, null)
}
}
)
},
) { ValueAnimatorCompatContent() }
}
@Composable
private fun ValueAnimatorCompatContent() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
BouncingDotsCompat()
LoadingButtonCompat()
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
SpinningTriangleCompat()
ColorFadingTriangleCompat()
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
SpinningTriangleAnimatorSetCompat()
}
}
}
@Composable
fun BouncingDotsCompat() {
// Based on https://github.com/81813780/AVLoadingIndicatorView/blob/master/library/src/main/java/com/wang/avi/indicators/BallPulseSyncIndicator.java
val ballsRange = (0..2)
val ballSize = 12.dp
val animators = ballsRange.map { index ->
valueAnimatorOfFloatAsState(0f, ballSize.value, 0f) {
duration = 200 * ballsRange.size.toLong()
repeatCount = ValueAnimator.INFINITE
startDelay = (1 + index) * 70L
}
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Float Animator (Compat)",
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
Row(
modifier = Modifier
.padding(top = 8.dp)
.width(ballSize * (ballsRange.size + 1)),
horizontalArrangement = Arrangement.SpaceEvenly,
) {
ballsRange.forEach { index ->
Ball(
modifier = Modifier
.offset(y = animators[index].value.dp)
)
}
}
}
}
@Composable
fun LoadingButtonCompat() {
var isLoading by remember { mutableStateOf(false) }
if (isLoading) {
LaunchedEffect(key1 = isLoading) {
delay(1500)
isLoading = false
}
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Trigger animation (Compat)",
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
Button(
modifier = Modifier
.width(150.dp)
.padding(top = 4.dp),
onClick = { if (!isLoading) isLoading = true },
) {
if (isLoading) {
val ballOffset by valueAnimatorOfFloatAsState(-35f, 35f) {
repeatMode = ValueAnimator.REVERSE
repeatCount = ValueAnimator.INFINITE
duration = 175
}
Ball(
modifier = Modifier.offset(x = ballOffset.dp)
)
} else {
Text(text = "Login")
}
}
}
}
@Composable
fun SpinningTriangleCompat() {
val rotateXAnimation by valueAnimatorOfIntAsState(0, 180, 180, 0, 0) {
interpolator = LinearInterpolator()
repeatCount = ValueAnimator.INFINITE
duration = 2500
}
val rotateYAnimation by valueAnimatorOfIntAsState(0, 0, 180, 180, 0) {
interpolator = LinearInterpolator()
repeatCount = ValueAnimator.INFINITE
duration = 2500
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Int animator (Compat)",
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
Triangle(
modifier = Modifier
.padding(top = 8.dp)
.graphicsLayer(
rotationX = rotateXAnimation.toFloat(),
rotationY = rotateYAnimation.toFloat(),
)
)
}
}
@Composable
fun ColorFadingTriangleCompat() {
val colorAnimation by valueAnimatorOfArgbAsState(Color.RED, Color.GREEN, Color.BLUE) {
interpolator = LinearInterpolator()
repeatCount = ValueAnimator.INFINITE
repeatMode = ValueAnimator.REVERSE
duration = 2500
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "ARGB animator (Compat)",
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
Triangle(
modifier = Modifier.padding(top = 8.dp),
backgroundColor = androidx.compose.ui.graphics.Color(colorAnimation)
)
}
}
@Composable
fun SpinningTriangleAnimatorSetCompat() {
val colorAnimator = rememberArgbValueAnimator(Color.RED, Color.GREEN, Color.BLUE, Color.GREEN, Color.RED) {
repeatCount = ValueAnimator.INFINITE
}
val rotationXAnimator = rememberIntValueAnimator(0, 180, 180, 0, 0) {
repeatCount = ValueAnimator.INFINITE
}
val rotationYAnimator = rememberIntValueAnimator(0, 0, 180, 180, 0) {
repeatCount = ValueAnimator.INFINITE
}
val animatorSet = rememberAnimatorSet {
play(rotationXAnimator)
.before(rotationYAnimator)
.before(colorAnimator)
duration = 1500
}
val rotationX by rotationXAnimator.observeAsState(0)
val rotationY by rotationYAnimator.observeAsState(0)
val color by colorAnimator.observeAsState(Color.RED)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Animator Set (Compat)",
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
Triangle(
modifier = Modifier
.padding(top = 8.dp)
.graphicsLayer(
rotationX = rotationX.toFloat(),
rotationY = rotationY.toFloat(),
),
backgroundColor = androidx.compose.ui.graphics.Color(color)
)
Button(
modifier = Modifier.padding(top = 8.dp),
onClick = { animatorSet.toggle() },
) {
Text(text = if (animatorSet.isAnimating) "Stop" else "Play")
}
}
}
<|start_filename|>app/build.gradle.kts<|end_filename|>
plugins {
id("com.android.application")
kotlin("android")
}
android {
compileSdk = 30
defaultConfig {
applicationId = "co.touchlab.compose.animations"
minSdk = 21
targetSdk = 30
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
}
buildTypes {
release {
isMinifyEnabled = false
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = libs.versions.compose.get()
}
packagingOptions {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}
dependencies {
// Libs
implementation(projects.easing)
implementation(projects.valueAnimatorCompat)
implementation(projects.valueAnimator)
// External Libs
implementation(libs.androidx.coreKtx)
implementation(libs.androidx.lifecycle)
implementation(libs.androidx.activityCompose)
implementation(libs.androidx.appCompat)
androidTestImplementation(libs.androidx.androidJunit)
androidTestImplementation(libs.androidx.espresso)
implementation(libs.google.material)
testImplementation(libs.junit)
implementation(libs.compose.ui)
implementation(libs.compose.animation)
implementation(libs.compose.material)
implementation(libs.compose.toolingPreview)
androidTestImplementation(libs.compose.test)
debugImplementation(libs.compose.tooling)
implementation("androidx.navigation:navigation-compose:2.4.0-alpha05")
}
<|start_filename|>easing/src/main/java/co/touchlab/compose/easing/Quart.kt<|end_filename|>
package co.touchlab.compose.easing
import androidx.compose.animation.core.Easing
import kotlin.math.pow
// https://easings.net/#easeInQuart
object EaseInQuart : Easing {
override fun transform(fraction: Float): Float =
fraction.pow(4)
}
// https://easings.net/#easeOutQuart
object EaseOutQuart : Easing {
override fun transform(fraction: Float): Float =
1 - (1 - fraction).pow(4)
}
// https://easings.net/#easeInOutQuart
object EaseInOutQuart : Easing {
override fun transform(fraction: Float): Float = if (fraction < 0.5f) {
8 * fraction.pow(4)
} else {
1 - (-2 * fraction + 2).pow(4) / 2
}
}
<|start_filename|>value-animator/src/main/kotlin/co/touchlab/compose/value/animator/MultipleValuesAnimator.kt<|end_filename|>
package co.touchlab.compose.value.animator
internal data class MultipleValuesAnimator<T>(
val values: List<T>,
) {
private val groups = values.zipWithNext()
val initialAnimationValue: T = values.first()
val targetAnimationValue: T = values.last()
val initialFrameValue: Float = 0f
val targetFrameValue: Float = groups.size.toFloat()
fun animate(frame: Float, valueAtFraction: ValueAtFraction<T>): T = when {
groups.isEmpty() -> initialAnimationValue
frame <= initialFrameValue -> initialAnimationValue
frame >= targetFrameValue -> targetAnimationValue
else -> {
val integerPart = frame.toInt()
val decimalPart = frame - integerPart
val (initialValue, finalValue) = groups[frame.toInt()]
valueAtFraction(decimalPart, initialValue, finalValue)
}
}
}
<|start_filename|>easing/src/main/java/co/touchlab/compose/easing/Bounce.kt<|end_filename|>
package co.touchlab.compose.easing
import androidx.compose.animation.core.Easing
import kotlin.math.pow
// https://easings.net/#easeInBounce
object EaseInBounce : Easing {
override fun transform(fraction: Float): Float =
1 - EaseOutBounce.transform(1 - fraction)
}
// https://easings.net/#easeOutBounce
object EaseOutBounce : Easing {
override fun transform(fraction: Float): Float {
val n1 = 7.5625f
val d1 = 2.75f
return when {
fraction < (1f / d1) -> n1 * fraction.pow(2)
fraction < (2f / d1) -> {
val fractionSub = fraction - (1.5f / d1)
n1 * fractionSub.pow(2) + 0.75f
}
fraction < (2.5f / d1) -> {
val fractionSub = fraction - (2.25f / d1)
n1 * fractionSub.pow(2) + 0.9375f
}
else -> {
val fractionSub = fraction - (2.625f / d1)
n1 * fractionSub.pow(2) + 0.984375f
}
}
}
}
// https://easings.net/#easeInOutBounce
object EaseInOutBounce : Easing {
override fun transform(fraction: Float): Float = if (fraction < 0.5f) {
(1 - EaseOutBounce.transform(1 - 2 * fraction)) / 2
} else {
(1 + EaseOutBounce.transform(2 * fraction - 1)) / 2
}
}
<|start_filename|>easing/src/main/java/co/touchlab/compose/easing/Quad.kt<|end_filename|>
package co.touchlab.compose.easing
import androidx.compose.animation.core.Easing
import kotlin.math.pow
// https://easings.net/#easeInQuad
object EaseInQuad : Easing {
override fun transform(fraction: Float): Float =
fraction.pow(2)
}
// https://easings.net/#easeOutQuad
object EaseOutQuad : Easing {
override fun transform(fraction: Float): Float =
1 - (1 - fraction).pow(2)
}
// https://easings.net/#easeInOutQuad
object EaseInOutQuad : Easing {
override fun transform(fraction: Float): Float = if (fraction < 0.5f) {
2 * fraction.pow(2)
} else {
1 - (-2 * fraction + 2).pow(2) / 2
}
}
<|start_filename|>value-animator-compat/src/main/kotlin/co/touchlab/compose/value/animator/compat/valueAnimatorOfArgbAsState.kt<|end_filename|>
package co.touchlab.compose.value.animator.compat
import android.animation.ValueAnimator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.remember
@Composable
fun rememberArgbValueAnimator(
vararg values: Int,
setupAnimator: ValueAnimator.() -> Unit = {},
): ValueAnimator = remember(keys = values.toTypedArray()) {
ValueAnimator.ofArgb(*values).apply(setupAnimator)
}
@Composable
fun valueAnimatorOfArgbAsState(
vararg values: Int,
setupAnimator: ValueAnimator.() -> Unit = {},
): State<Int> {
val animator = rememberArgbValueAnimator(
values = values,
setupAnimator = setupAnimator
)
return valueAnimatorChangesAsState(
values = values.toTypedArray(),
animator = animator,
)
}
<|start_filename|>app/src/main/java/co/touchlab/compose/animations/page/Easings.kt<|end_filename|>
package co.touchlab.compose.animations.page
import androidx.compose.animation.core.Easing
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import co.touchlab.compose.easing.EaseInBack
import co.touchlab.compose.easing.EaseInBounce
import co.touchlab.compose.easing.EaseInCirc
import co.touchlab.compose.easing.EaseInCubic
import co.touchlab.compose.easing.EaseInElastic
import co.touchlab.compose.easing.EaseInExpo
import co.touchlab.compose.easing.EaseInOutBack
import co.touchlab.compose.easing.EaseInOutBounce
import co.touchlab.compose.easing.EaseInOutCirc
import co.touchlab.compose.easing.EaseInOutCubic
import co.touchlab.compose.easing.EaseInOutElastic
import co.touchlab.compose.easing.EaseInOutExpo
import co.touchlab.compose.easing.EaseInOutQuad
import co.touchlab.compose.easing.EaseInOutQuart
import co.touchlab.compose.easing.EaseInOutQuint
import co.touchlab.compose.easing.EaseInOutSine
import co.touchlab.compose.easing.EaseInQuad
import co.touchlab.compose.easing.EaseInQuart
import co.touchlab.compose.easing.EaseInQuint
import co.touchlab.compose.easing.EaseInSine
import co.touchlab.compose.easing.EaseOutBack
import co.touchlab.compose.easing.EaseOutBounce
import co.touchlab.compose.easing.EaseOutCirc
import co.touchlab.compose.easing.EaseOutCubic
import co.touchlab.compose.easing.EaseOutElastic
import co.touchlab.compose.easing.EaseOutExpo
import co.touchlab.compose.easing.EaseOutQuad
import co.touchlab.compose.easing.EaseOutQuart
import co.touchlab.compose.easing.EaseOutQuint
import co.touchlab.compose.easing.EaseOutSine
val EASING_ROUTE = "demo/easings"
@Composable
fun EasingDemo(navController: NavController) {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Easing functions") },
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(Icons.Filled.ArrowBack, null)
}
}
)
},
) { EasingDemoContent() }
}
@Composable
private fun EasingDemoContent() {
LazyColumn {
items(ALL_EASIGNS.toList()) { (name, easing) ->
Graph(
name = name,
easingFunction = easing
)
}
}
}
@Composable
private fun Graph(
name: String,
easingFunction: Easing,
) {
val infiniteTransition = rememberInfiniteTransition()
val time by infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 2500,
easing = LinearEasing,
)
)
)
val value by infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(
durationMillis = 2500,
easing = easingFunction,
)
)
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Text(
text = name,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(bottom = 8.dp)
)
Canvas(
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.padding(vertical = 24.dp)
) {
val canvasWidth = size.width
val canvasHeight = size.height
drawLine(
color = Color.Blue,
strokeWidth = 3f,
start = Offset.Zero,
end = Offset(0f, canvasHeight),
)
drawLine(
color = Color.Blue,
strokeWidth = 3f,
start = Offset(canvasWidth, 0f),
end = Offset(canvasWidth, canvasHeight),
)
drawLine(
color = Color.Red,
strokeWidth = 3f,
start = Offset(0f, canvasHeight),
end = Offset(canvasWidth, canvasHeight),
)
drawLine(
color = Color.Red,
strokeWidth = 3f,
start = Offset(0f, 0f),
end = Offset(canvasWidth, 0f),
)
val canvasSizeInt = canvasWidth.toInt()
for (i in 1..canvasSizeInt) {
val currentTime = (i + 1) / canvasSizeInt.toFloat()
val previousTime = (i - 1) / canvasSizeInt.toFloat()
drawLine(
color = Color.LightGray,
strokeWidth = 2f,
start = Offset(
x = canvasWidth * previousTime,
y = canvasHeight * (1 - easingFunction.transform(previousTime))
),
end = Offset(
x = canvasWidth * currentTime,
y = canvasHeight * (1 - easingFunction.transform(currentTime))
),
)
}
drawCircle(
color = Color.Black,
radius = 10f,
center = Offset(canvasWidth * time, canvasHeight * (1 - value))
)
}
}
}
@Composable
@Preview
fun GraphPreview() {
Graph(
name = "Some function",
easingFunction = LinearEasing
)
}
private val ALL_EASIGNS = mapOf(
"LinearEasing (Compose)" to LinearEasing,
"FastOutSlowInEasing (Compose)" to FastOutSlowInEasing,
"LinearOutSlowInEasing (Compose)" to LinearOutSlowInEasing,
"FastOutLinearInEasing (Compose)" to FastOutLinearInEasing,
"EaseInSine" to EaseInSine,
"EaseOutSine" to EaseOutSine,
"EaseInOutSine" to EaseInOutSine,
"EaseInQuad" to EaseInQuad,
"EaseOutQuad" to EaseOutQuad,
"EaseInOutQuad" to EaseInOutQuad,
"EaseInCubic" to EaseInCubic,
"EaseOutCubic" to EaseOutCubic,
"EaseInOutCubic" to EaseInOutCubic,
"EaseInQuart" to EaseInQuart,
"EaseOutQuart" to EaseOutQuart,
"EaseInOutQuart" to EaseInOutQuart,
"EaseInQuint" to EaseInQuint,
"EaseOutQuint" to EaseOutQuint,
"EaseInOutQuint" to EaseInOutQuint,
"EaseInExpo" to EaseInExpo,
"EaseOutExpo" to EaseOutExpo,
"EaseInOutExpo" to EaseInOutExpo,
"EaseInCirc" to EaseInCirc,
"EaseOutCirc" to EaseOutCirc,
"EaseInOutCirc" to EaseInOutCirc,
"EaseInBack" to EaseInBack,
"EaseOutBack" to EaseOutBack,
"EaseInOutBack" to EaseInOutBack,
"EaseInElastic" to EaseInElastic,
"EaseOutElastic" to EaseOutElastic,
"EaseInOutElastic" to EaseInOutElastic,
"EaseInBounce" to EaseInBounce,
"EaseOutBounce" to EaseOutBounce,
"EaseInOutBounce" to EaseInOutBounce,
)
<|start_filename|>value-animator/src/main/kotlin/co/touchlab/compose/value/animator/animateAsState.kt<|end_filename|>
package co.touchlab.compose.value.animator
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.spring
import androidx.compose.runtime.Composable
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
@Composable
fun animateFloatValueAsState(
initialValue: Float,
targetValue: Float,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
) = animateFloatValuesAsState(
values = floatArrayOf(initialValue, targetValue),
startDelay = startDelay,
animationSpec = animationSpec
)
@Composable
fun animateIntAsState(
initialValue: Int,
targetValue: Int,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
) = animateIntValuesAsState(
values = arrayOf(initialValue, targetValue),
startDelay = startDelay,
animationSpec = animationSpec
)
@Composable
fun animateDpAsState(
initialValue: Dp,
targetValue: Dp,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
) = animateDpValuesAsState(
values = arrayOf(initialValue, targetValue),
startDelay = startDelay,
animationSpec = animationSpec
)
@Composable
fun animateSizeAsState(
initialValue: Size,
targetValue: Size,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
) = animateSizeValuesAsState(
values = arrayOf(initialValue, targetValue),
startDelay = startDelay,
animationSpec = animationSpec
)
@Composable
fun animateOffsetAsState(
initialValue: Offset,
targetValue: Offset,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
) = animateOffsetValuesAsState(
values = arrayOf(initialValue, targetValue),
startDelay = startDelay,
animationSpec = animationSpec
)
@Composable
fun animateRectAsState(
initialValue: Rect,
targetValue: Rect,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
) = animateRectValuesAsState(
values = arrayOf(initialValue, targetValue),
startDelay = startDelay,
animationSpec = animationSpec
)
@Composable
fun animateIntOffsetAsState(
initialValue: IntOffset,
targetValue: IntOffset,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
) = animateIntOffsetValuesAsState(
values = arrayOf(initialValue, targetValue),
startDelay = startDelay,
animationSpec = animationSpec
)
@Composable
fun animateIntSizeAsState(
initialValue: IntSize,
targetValue: IntSize,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
) = animateIntSizeValuesAsState(
values = arrayOf(initialValue, targetValue),
startDelay = startDelay,
animationSpec = animationSpec
)
@Composable
fun animateColorAsState(
initialValue: Color,
targetValue: Color,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
) = animateColorValuesAsState(
values = arrayOf(initialValue, targetValue),
startDelay = startDelay,
animationSpec = animationSpec
)
<|start_filename|>app/src/main/java/co/touchlab/compose/animations/nav/RootNav.kt<|end_filename|>
package co.touchlab.compose.animations.nav
import androidx.compose.runtime.Composable
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import co.touchlab.compose.animations.page.EASING_ROUTE
import co.touchlab.compose.animations.page.EasingDemo
import co.touchlab.compose.animations.page.HOME_ROUTE
import co.touchlab.compose.animations.page.Home
import co.touchlab.compose.animations.page.VALUE_ANIMATOR_COMPAT_ROUTE
import co.touchlab.compose.animations.page.VALUE_ANIMATOR_ROUTE
import co.touchlab.compose.animations.page.ValueAnimatorCompatDemo
import co.touchlab.compose.animations.page.ValueAnimatorDemo
@Composable
fun RootNav() {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = HOME_ROUTE,
) {
composable(HOME_ROUTE) { Home(navController) }
composable(EASING_ROUTE) { EasingDemo(navController) }
composable(VALUE_ANIMATOR_ROUTE) { ValueAnimatorDemo(navController) }
composable(VALUE_ANIMATOR_COMPAT_ROUTE) { ValueAnimatorCompatDemo(navController) }
}
}
<|start_filename|>settings.gradle.kts<|end_filename|>
// https://docs.gradle.org/current/userguide/platforms.html
enableFeaturePreview("VERSION_CATALOGS")
// https://docs.gradle.org/current/userguide/declaring_dependencies.html
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
}
}
rootProject.name = "ComposeAnimations"
// Modules
include(":app")
include(":easing")
include(":value-animator-compat")
include(":value-animator")
<|start_filename|>app/src/main/java/co/touchlab/compose/animations/shapes/Ball.kt<|end_filename|>
package co.touchlab.compose.animations.shapes
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import co.touchlab.compose.animations.R
@Composable
fun Ball(
modifier: Modifier = Modifier,
size: Dp = 12.dp,
backgroundColor: Color = colorResource(id = R.color.ball_gray),
) {
Box(
modifier = modifier
.width(size)
.height(size)
.clipToBounds()
.background(backgroundColor, CircleShape)
)
}
@Preview
@Composable
fun BallPreview() {
Ball(
size = 32.dp,
backgroundColor = colorResource(id = R.color.purple_700),
)
}
<|start_filename|>value-animator-compat/src/main/kotlin/co/touchlab/compose/value/animator/compat/rememberAnimatorSet.kt<|end_filename|>
package co.touchlab.compose.value.animator.compat
import android.animation.Animator
import android.animation.AnimatorSet
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
data class ComposableAnimatorSet(
val animatorSet: AnimatorSet,
val isAnimating: Boolean,
val play: () -> Unit,
val stop: () -> Unit,
val toggle: () -> Unit,
)
@Composable
fun rememberAnimatorSet(
vararg keys: Any?,
setupAnimator: AnimatorSet.() -> Unit,
): ComposableAnimatorSet {
val animatorSet = if (keys.isEmpty()) {
remember { AnimatorSet().apply(setupAnimator) }
} else {
remember(keys = keys) { AnimatorSet().apply(setupAnimator) }
}
var playing by remember { mutableStateOf(false) }
DisposableEffect(key1 = playing) {
animatorSet.removeAllListeners()
animatorSet.addOnAnimationStop { if (playing) playing = false }
if (playing) {
animatorSet.start()
}
onDispose { animatorSet.cancel() }
}
return remember(key1 = animatorSet, key2 = playing) {
ComposableAnimatorSet(
animatorSet = animatorSet,
isAnimating = playing,
play = { if (!playing) playing = true },
stop = { if (playing) playing = false },
toggle = { playing = !playing }
)
}
}
private fun AnimatorSet.addOnAnimationStop(block: () -> Unit) {
addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator?) {}
override fun onAnimationRepeat(animation: Animator?) {}
override fun onAnimationEnd(animation: Animator?) {
block()
}
override fun onAnimationCancel(animation: Animator?) {
block()
}
})
}
<|start_filename|>value-animator/src/main/kotlin/co/touchlab/compose/value/animator/animateValuesAsState.kt<|end_filename|>
package co.touchlab.compose.value.animator
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.animate
import androidx.compose.animation.core.spring
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import kotlinx.coroutines.delay
@Composable
fun animateFloatValuesAsState(
vararg values: Float,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
): State<Float> = animateValuesAsState(
values = values.toTypedArray(),
getValueAtFraction = ValueAtFraction.Float,
startDelay = startDelay,
animationSpec = animationSpec,
)
@Composable
fun animateIntValuesAsState(
values: Array<Int>,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
): State<Int> = animateValuesAsState(
values = values,
getValueAtFraction = ValueAtFraction.Int,
startDelay = startDelay,
animationSpec = animationSpec,
)
@Composable
fun animateDpValuesAsState(
values: Array<Dp>,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
): State<Dp> = animateValuesAsState(
values = values,
getValueAtFraction = ValueAtFraction.Dp,
startDelay = startDelay,
animationSpec = animationSpec,
)
@Composable
fun animateSizeValuesAsState(
values: Array<Size>,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
): State<Size> = animateValuesAsState(
values = values,
getValueAtFraction = ValueAtFraction.Size,
startDelay = startDelay,
animationSpec = animationSpec,
)
@Composable
fun animateOffsetValuesAsState(
values: Array<Offset>,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
): State<Offset> = animateValuesAsState(
values = values,
getValueAtFraction = ValueAtFraction.Offset,
startDelay = startDelay,
animationSpec = animationSpec,
)
@Composable
fun animateRectValuesAsState(
values: Array<Rect>,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
): State<Rect> = animateValuesAsState(
values = values,
getValueAtFraction = ValueAtFraction.Rect,
startDelay = startDelay,
animationSpec = animationSpec,
)
@Composable
fun animateIntOffsetValuesAsState(
values: Array<IntOffset>,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
): State<IntOffset> = animateValuesAsState(
values = values,
getValueAtFraction = ValueAtFraction.IntOffset,
startDelay = startDelay,
animationSpec = animationSpec,
)
@Composable
fun animateIntSizeValuesAsState(
values: Array<IntSize>,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
): State<IntSize> = animateValuesAsState(
values = values,
getValueAtFraction = ValueAtFraction.IntSize,
startDelay = startDelay,
animationSpec = animationSpec,
)
@Composable
fun animateColorValuesAsState(
values: Array<Color>,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
): State<Color> = animateValuesAsState(
values = values,
getValueAtFraction = ValueAtFraction.Color,
startDelay = startDelay,
animationSpec = animationSpec,
)
@Composable
fun <T> animateValuesAsState(
vararg values: T,
getValueAtFraction: ValueAtFraction<T>,
startDelay: Long = 0,
animationSpec: AnimationSpec<Float> = spring(),
): State<T> {
require(values.isNotEmpty()) {
"You should provide at least one item to animate"
}
val valueAnimator by rememberUpdatedState(
MultipleValuesAnimator(values.toList())
)
val animatedValue = remember(valueAnimator) {
mutableStateOf(valueAnimator.initialAnimationValue)
}
LaunchedEffect(valueAnimator) {
if (startDelay > 0) {
delay(startDelay)
}
val (_, setValue) = animatedValue
animate(
initialValue = valueAnimator.initialFrameValue,
targetValue = valueAnimator.targetFrameValue,
animationSpec = animationSpec,
) { frame, _ -> setValue(valueAnimator.animate(frame, getValueAtFraction)) }
}
return animatedValue
}
| touchlab-lab/compose-animations |
<|start_filename|>src/appimaged/appimage.go<|end_filename|>
package main
import (
"bytes"
"crypto/md5"
"encoding/hex"
"io/ioutil"
"net/url"
"gopkg.in/ini.v1"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/adrg/xdg"
"github.com/probonopd/go-appimage/internal/helpers"
"github.com/probonopd/go-appimage/src/goappimage"
"go.lsp.dev/uri"
)
// AppImage Handles AppImage files.
type AppImage struct {
*goappimage.AppImage
uri string
md5 string
desktopfilename string
desktopfilepath string
thumbnailfilename string
thumbnailfilepath string
updateinformation string
startup bool //used so we don't notify applications being added on startup
// offset int64
// rawcontents string
// niceName string
}
// NewAppImage creates an AppImage object from the location defined by path.
// The AppImage object will also be created if path does not exist,
// because the AppImage that used to be there may need to be removed
// and for this the functions of an AppImage are needed.
// Non-existing and invalid AppImages will have type -1.
func NewAppImage(path string) (ai *AppImage, err error) {
ai = new(AppImage)
ai.AppImage, err = goappimage.NewAppImage(path)
ai.uri = strings.TrimSpace(string(uri.File(filepath.Clean(ai.Path))))
ai.md5 = ai.calculateMD5filenamepart() // Need this also for non-existing AppImages for removal
ai.desktopfilename = "appimagekit_" + ai.md5 + ".desktop"
ai.desktopfilepath = xdg.DataHome + "/applications/" + "appimagekit_" + ai.md5 + ".desktop"
ai.thumbnailfilename = ai.md5 + ".png"
if strings.HasSuffix(ThumbnailsDirNormal, "/") {
ai.thumbnailfilepath = ThumbnailsDirNormal + ai.thumbnailfilename
} else {
ai.thumbnailfilepath = ThumbnailsDirNormal + "/" + ai.thumbnailfilename
}
if err != nil {
return ai, err
}
ui, err := ai.ReadUpdateInformation()
if err == nil && ui != "" {
ai.updateinformation = ui
}
return ai, nil
}
func (ai AppImage) calculateMD5filenamepart() string {
hasher := md5.New()
hasher.Write([]byte(ai.uri))
return hex.EncodeToString(hasher.Sum(nil))
}
func (ai AppImage) setExecBit() {
err := os.Chmod(ai.Path, 0755)
if err == nil {
if *verbosePtr {
log.Println("appimage: Set executable bit on", ai.Path)
}
}
// printError("appimage", err) // Do not print error since AppImages on read-only media are common
}
// Validate checks the quality of an AppImage and sends desktop notification, returns error or nil
// TODO: Add more checks and reuse this in appimagetool
func (ai AppImage) Validate() error {
if *verbosePtr {
log.Println("Validating AppImage", ai.Path)
}
// Check validity of the updateinformation in this AppImage, if it contains some
if ai.updateinformation != "" {
log.Println("Validating updateinformation in", ai.Path)
err := helpers.ValidateUpdateInformation(ai.updateinformation)
if err != nil {
helpers.PrintError("appimage: updateinformation verification", err)
return err
}
}
return nil
}
// Do not call this directly. Instead, call IntegrateOrUnintegrate
// Integrate an AppImage into the system (put in menu, extract thumbnail)
// Can take a long time, hence run with "go"
func (ai AppImage) _integrate() {
// log.Println("integrate called on:", ai.path)
// Return immediately if the filename extension is not .AppImage or .app
if !strings.HasSuffix(strings.ToUpper(ai.Path), ".APPIMAGE") && !strings.HasSuffix(strings.ToUpper(ai.Path), ".APP") {
// log.Println("No .AppImage suffix:", ai.path)
return
}
ai.setExecBit()
// For performance reasons, we stop working immediately
// in case a desktop file already exists at that location
if !*overwritePtr {
// Compare mtime of desktop file and AppImage, similar to
// https://specifications.freedesktop.org/thumbnail-spec/thumbnail-spec-latest.html#MODIFICATIONS
if desktopFileInfo, err := os.Stat(ai.desktopfilepath); err == nil {
if appImageInfo, err := os.Stat(ai.Path); err == nil {
diff := desktopFileInfo.ModTime().Sub(appImageInfo.ModTime())
if diff > (time.Duration(0) * time.Second) {
// Do nothing if the desktop file is already newer than the AppImage file
// but subscribe
if CheckIfConnectedToNetwork() {
go SubscribeMQTT(MQTTclient, ai.updateinformation)
}
return
}
}
}
}
// Let's be evil and integrate only good AppImages...
// err := ai.Validate()
// if err != nil {
// log.Println("AppImage did not pass validation:", ai.path)
// return
// }
writeDesktopFile(ai) // Do not run with "go" as it would interfere with extractDirIconAsThumbnail
// Subscribe to MQTT messages for this application
if ai.updateinformation != "" {
if CheckIfConnectedToNetwork() {
go SubscribeMQTT(MQTTclient, ai.updateinformation)
}
}
// SimpleNotify(ai.path, "Integrated", 3000)
// For performance reasons, we stop working immediately
// in case a thumbnail file already exists at that location
// if *overwritePtr == false {
// Compare mtime of thumbnail file and AppImage, similar to
// https://specifications.freedesktop.org/thumbnail-spec/thumbnail-spec-latest.html#MODIFICATIONS
if thumbnailFileInfo, err := os.Stat(ai.thumbnailfilepath); err == nil {
if appImageInfo, err := os.Stat(ai.Path); err == nil {
diff := thumbnailFileInfo.ModTime().Sub(appImageInfo.ModTime())
if diff > (time.Duration(0) * time.Second) {
// Do nothing if the thumbnail file is already newer than the AppImage file
return
}
}
}
// }
ai.extractDirIconAsThumbnail() // Do not run with "go" as it would interfere with writeDesktopFile
}
// Do not call this directly. Instead, call IntegrateOrUnintegrate
func (ai AppImage) _removeIntegration() {
log.Println("appimage: Remove integration", ai.Path)
err := os.Remove(ai.thumbnailfilepath)
if err == nil {
log.Println("appimage: Deleted", ai.thumbnailfilepath)
} else {
log.Println("appimage:", err, ai.thumbnailfilepath)
}
// Unsubscribe to MQTT messages for this application
if ai.updateinformation != "" {
go UnSubscribeMQTT(MQTTclient, ai.updateinformation)
}
err = os.Remove(ai.desktopfilepath)
if err == nil {
log.Println("appimage: Deleted", ai.desktopfilepath)
sendDesktopNotification("Removed", ai.Path, 3000)
} else {
log.Println("appimage:", err, ai.desktopfilename)
}
}
// IntegrateOrUnintegrate integrates or unintegrates
// (registers or unregisters) an AppImage from the system,
// depending on whether the file exists on disk. NEVER call this directly,
// ONLY have this called from a function that limits parallelism and ensures
// uniqueness of the AppImages to be processed
func (ai AppImage) IntegrateOrUnintegrate() bool {
if _, err := os.Stat(ai.Path); os.IsNotExist(err) {
ai._removeIntegration()
} else {
ai._integrate()
return true
}
return false
}
// ReadUpdateInformation reads updateinformation from an AppImage
// Returns updateinformation string and error
func (ai AppImage) ReadUpdateInformation() (string, error) {
aibytes, err := helpers.GetSectionData(ai.Path, ".upd_info")
ui := strings.TrimSpace(string(bytes.Trim(aibytes, "\x00")))
if err != nil {
return "", err
}
// Don't validate here, we don't want to get warnings all the time.
// We have AppImage.Validate as its own function which we call less frequently than this.
return ui, nil
}
// LaunchMostRecentAppImage launches an the most recent application for a given
// updateinformation that we found among the integrated AppImages.
// Kinda like poor man's Launch Services. Probably we should make as much use of it as possible.
// Downside: Applications without updateinformation cannot be used in this way.
func LaunchMostRecentAppImage(updateinformation string, args []string) {
if updateinformation == "" {
return
}
if !*quietPtr {
aipath := FindMostRecentAppImageWithMatchingUpdateInformation(updateinformation)
log.Println("Launching", aipath, args)
cmd := []string{aipath}
cmd = append(cmd, args...)
err := helpers.RunCmdTransparently(cmd)
if err != nil {
helpers.PrintError("LaunchMostRecentAppImage", err)
}
}
}
// FindMostRecentAppImageWithMatchingUpdateInformation finds the most recent registered AppImage
// that havs matching upate information embedded
func FindMostRecentAppImageWithMatchingUpdateInformation(updateinformation string) string {
results := FindAppImagesWithMatchingUpdateInformation(updateinformation)
mostRecent := helpers.FindMostRecentFile(results)
return mostRecent
}
// FindAppImagesWithMatchingUpdateInformation finds registered AppImages
// that have matching upate information embedded
func FindAppImagesWithMatchingUpdateInformation(updateinformation string) []string {
files, err := ioutil.ReadDir(xdg.DataHome + "/applications/")
helpers.LogError("desktop", err)
var results []string
if err != nil {
return results
}
for _, file := range files {
if strings.HasSuffix(file.Name(), ".desktop") && strings.HasPrefix(file.Name(), "appimagekit_") {
cfg, e := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, // Do not cripple lines hat contain ";"
xdg.DataHome+"/applications/"+file.Name())
helpers.LogError("desktop", e)
dst := cfg.Section("Desktop Entry").Key(ExecLocationKey).String()
_, err = os.Stat(dst)
if os.IsNotExist(err) {
log.Println(dst, "does not exist, it is mentioned in", xdg.DataHome+"/applications/"+file.Name())
continue
}
ai, err := NewAppImage(dst)
if err != nil {
continue
}
ui, err := ai.ReadUpdateInformation()
if err == nil && ui != "" {
//log.Println("updateinformation:", ui)
// log.Println("updateinformation:", url.QueryEscape(ui))
unescapedui, _ := url.QueryUnescape(ui)
// log.Println("updateinformation:", unescapedui)
if updateinformation == unescapedui {
results = append(results, ai.Path)
}
}
continue
}
}
return results
}
<|start_filename|>src/appimaged/thumbnail.go<|end_filename|>
package main
import (
"bytes"
"fmt"
"image"
"image/png"
"io"
"log"
"os"
"time"
_ "embed"
"github.com/adrg/xdg"
issvg "github.com/h2non/go-is-svg"
"github.com/probonopd/go-appimage/internal/helpers"
pngembed "github.com/sabhiram/png-embed" // For embedding metadata into PNG
"github.com/srwiley/oksvg" // https://github.com/niemeyer/gopkg/issues/72
"github.com/srwiley/rasterx"
)
/* The thumbnail cache directory is prefixed with $XDG_CACHE_DIR/ and the leading dot removed
(since $XDG_CACHE_DIR is normally $HOME/.cache).
The glib ChangeLog indicates the path for large sizes was "fixed" (Added $XDG_CACHE_DIR) starting with 2.35.3 */
var ThumbnailsDirNormal = xdg.CacheHome + "/thumbnails/normal/"
//go:embed embed/appimage.png
var defaultIcon []byte
//Tries to get .DirIcon or the desktop's icon (in that order). If a failure, return generic icon.
func (ai AppImage) getThumbnailOrIcon() (out []byte) {
fallback := defaultIcon
rdr, err := ai.Thumbnail()
if err != nil {
fmt.Println("Error getting thumbnail")
goto icon
}
out, err = io.ReadAll(rdr)
if err != nil {
fmt.Println("Error reading thumbnail")
goto icon
}
if issvg.Is(out) {
fmt.Println("Thumbnail is svg, checking desktop icon")
fallback = out
goto icon
}
return
icon:
fmt.Println("Checking icon")
rdr, _, err = ai.Icon()
if err != nil {
fmt.Println("Error getting icon")
return fallback
}
out, err = io.ReadAll(rdr)
if err != nil {
fmt.Println("Error reading icon")
return fallback
}
return
}
//This reads the icon from the appimage then makes necessary changes or uses the default icon as necessary.
//All this is now done in memory instead of constantly writing the changes to disk.
func (ai AppImage) extractDirIconAsThumbnail() {
// log.Println("thumbnail: extract DirIcon as thumbnail")
if ai.Type() <= 0 {
return
}
// TODO: Detect Modifications by reading the 'Thumb::MTime' key as per
// https://specifications.freedesktop.org/thumbnail-spec/thumbnail-spec-latest.html#MODIFICATIONS
var err error
iconBuf := ai.getThumbnailOrIcon()
if issvg.Is(iconBuf) {
log.Println("thumbnail: .DirIcon in", ai.Path, "is an SVG, this is discouraged. Costly converting it now")
iconBuf, err = convertToPng(iconBuf)
if err != nil {
helpers.LogError("thumbnail", err)
iconBuf = defaultIcon
}
}
if !helpers.CheckMagicAtOffsetBytes(iconBuf, "504e47", 1) {
log.Println("thumbnail: Not a PNG file, using generic icon")
iconBuf = defaultIcon
}
// Write "Thumbnail Attributes" metadata as mandated by
// https://specifications.freedesktop.org/thumbnail-spec/thumbnail-spec-latest.html#ADDINFOS
// and set thumbnail permissions to 0600 as mandated by
// https://specifications.freedesktop.org/thumbnail-spec/thumbnail-spec-latest.html#AEN245
// Thumb::URI The absolute canonical uri for the original file. (eg file:///home/jens/photo/me.jpg)
// FIXME; github.com/sabhiram/png-embed does not overwrite pre-existing values,
// https://github.com/sabhiram/png-embed/issues/1
// content, err := pngembed.Extract(iconBuf)
// if *verbosePtr {
// if _, ok := content["Thumb::URI"]; ok {
// log.Println("thumbnail: FIXME: Remove pre-existing Thumb::URI in", ai.Path)
// // log.Println(content["Thumb::URI"])
// }
// if _, ok := content["Thumb::MTime"]; ok {
// log.Println("thumbnail: FIXME: Remove pre-existing Thumb::MTime", content["Thumb::MTime"], "in", ai.Path) // FIXME; pngembed does not seem to overwrite pre-existing values, is it a bug there?
// // log.Println(content["Thumb::MTime"])
// }
// }
out, err := pngembed.Embed(iconBuf, "Thumb::URI", ai.uri)
helpers.LogError("thumbnail", err)
if err == nil {
iconBuf = out
}
/* Set 'Thumb::MTime' metadata of the thumbnail file to the mtime of the AppImage.
NOTE: https://specifications.freedesktop.org/thumbnail-spec/thumbnail-spec-latest.html#MODIFICATIONS says:
It is not sufficient to do a file.mtime > thumb.MTime check.
If the user moves another file over the original, where the mtime changes but is in fact lower
than the thumbnail stored mtime, we won't recognize this modification.
If for some reason the thumbnail doesn't have the 'Thumb::MTime' key (although it's required)
it should be recreated in any case. */
if appImageInfo, e := os.Stat(ai.Path); e == nil {
out, err = pngembed.Embed(iconBuf, "Thumb::MTime", appImageInfo.ModTime())
if err != nil {
helpers.LogError("thumbnail", err)
} else {
iconBuf = out
}
}
helpers.LogError("thumbnail", err)
// Set thumbnail permissions to 0600 as mandated by
// https://specifications.freedesktop.org/thumbnail-spec/thumbnail-spec-latest.html#AEN245
// err = os.Chmod(thumbnailcachedir+"/.DirIcon", 0600)
// printError("thumbnail", err)
err = os.MkdirAll(ThumbnailsDirNormal, os.ModePerm)
helpers.LogError("thumbnail", err)
if *verbosePtr {
log.Println("thumbnail: Writing icon to", ai.thumbnailfilepath)
}
err = os.WriteFile(ai.thumbnailfilepath, iconBuf, 0600)
helpers.LogError("thumbnail", err)
/* Also set mtime of the thumbnail file to the mtime of the AppImage. Quite possibly this is not needed.
TODO: Perhaps we can remove it.
See https://specifications.freedesktop.org/thumbnail-spec/thumbnail-spec-latest.html#MODIFICATIONS */
if appImageInfo, e := os.Stat(ai.Path); e == nil {
e = os.Chtimes(ai.thumbnailfilepath, time.Now().Local(), appImageInfo.ModTime())
helpers.LogError("thumbnail", e)
}
// In Xfce, the new thumbnail is not shown in the file manager until we touch the file
// In fact, touching it from within this program makes the thumbnail not work at all
// TODO: Read XDG Thumbnail spec regarding this
// The following all does not work
// time.Sleep(2 * time.Second)
// now := time.Now()
// err = os.Chtimes(ai.path, now, now)
// printError("thumbnail", err)
// cmd = exec.Command("touch", ai.thumbnailfilepath)
}
// Convert a given file into a PNG; its dependencies add about 2 MB to the executable
func convertToPng(iconBuf []byte) ([]byte, error) {
// Strange colors: https://github.com/srwiley/oksvg/issues/15
icon, err := oksvg.ReadIconStream(bytes.NewReader(iconBuf), oksvg.WarnErrorMode)
if err != nil {
return nil, err
}
w, h := int(icon.ViewBox.W), int(icon.ViewBox.H)
img := image.NewRGBA(image.Rect(0, 0, w, h))
scannerGV := rasterx.NewScannerGV(w, h, img, img.Bounds())
raster := rasterx.NewDasher(w, h, scannerGV)
icon.Draw(raster, 1.0)
buf := bytes.NewBuffer(make([]byte, 0))
err = png.Encode(buf, img)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
<|start_filename|>src/mkappimage/appimage.go<|end_filename|>
package main
import (
"os"
"os/exec"
"strconv"
"strings"
"github.com/probonopd/go-appimage/internal/helpers"
)
// Handles AppImage files.
// Currently it is using using a static build of mksquashfs/unsquashfs
// but eventually may be rewritten to do things natively in Go
type AppImage struct {
path string
imagetype int
offset int64
}
// NewAppImage creates an AppImage object from the location defined by path.
// The AppImage object will also be created if path does not exist,
// because the AppImage that used to be there may need to be removed
// and for this the functions of an AppImage are needed.
// Non-existing and invalid AppImages will have type -1.
func NewAppImage(path string) AppImage {
ai := AppImage{path: path, imagetype: 0}
// If we got a temp file, exit immediately
// E.g., ignore typical Internet browser temporary files used during download
if strings.HasSuffix(path, ".temp") ||
strings.HasSuffix(path, "~") ||
strings.HasSuffix(path, ".part") ||
strings.HasSuffix(path, ".partial") ||
strings.HasSuffix(path, ".zs-old") ||
strings.HasSuffix(path, ".crdownload") {
ai.imagetype = -1
return ai
}
ai.imagetype = ai.DetermineImageType()
// Don't waste more time if the file is not actually an AppImage
if ai.imagetype < 0 {
return ai
}
if ai.imagetype < 1 {
return ai
}
if ai.imagetype > 1 {
ai.offset = helpers.CalculateElfSize(ai.path)
}
// ai.discoverContents() // Only do when really needed since this is slow
// log.Println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX rawcontents:", ai.rawcontents)
// Besides, for whatever reason it is not working properly yet
return ai
}
// Fills rawcontents with the raw output of our extraction tools,
// libarchive and unsquashfs. This is a slow operation and should hence only be done
// once we are sure that we really need this information.
// Maybe we should consider to have a fixed directory inside the AppDir
// for everything that should be extracted, or a MANIFEST file. That would save
// us this slow work at runtime
func (ai AppImage) ShowContents(isLong bool) error {
// Let's get the listing of files inside the AppImage. We can work on this later on
// to resolve symlinks, and to determine which files to extract in addition to the desktop file and icon
cmd := exec.Command("")
if ai.imagetype == 1 {
cmd = exec.Command("bsdtar", "-t", ai.path)
} else if ai.imagetype == 2 {
listCommand := "-l"
if isLong {
listCommand = "-ll"
}
// cmd = exec.Command("unsquashfs", "-h")
cmd = exec.Command("unsquashfs", "-f", "-n", listCommand, "-o", strconv.FormatInt(ai.offset, 10), ai.path)
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
return err
}
// Check whether we have an AppImage at all.
// Return image type, or -1 if it is not an AppImage
func (ai AppImage) DetermineImageType() int {
// log.Println("appimage: ", ai.path)
f, err := os.Open(ai.path)
// printError("appimage", err)
if err != nil {
return -1 // If we were not able to open the file, then we report that it is not an AppImage
}
info, err := os.Stat(ai.path)
if err != nil {
return -1
}
// Directories cannot be AppImages, so return fast
if info.IsDir() {
return -1
}
// Very small files cannot be AppImages, so return fast
if info.Size() < 100*1024 {
return -1
}
if helpers.CheckMagicAtOffset(f, "414902", 8) {
return 2
}
if helpers.CheckMagicAtOffset(f, "414901", 8) {
return 1
}
// ISO9660 files that are also ELF files
if helpers.CheckMagicAtOffset(f, "7f454c", 0) && helpers.CheckMagicAtOffset(f, "4344303031", 32769) {
return 1
}
return -1
}
<|start_filename|>src/appimaged/mqtt.go<|end_filename|>
package main
import (
"encoding/json"
"fmt"
"log"
"net/url"
"strings"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/probonopd/go-appimage/internal/helpers"
)
func connect(clientId string, uri *url.URL) mqtt.Client {
opts := createClientOptions(clientId, uri)
client := mqtt.NewClient(opts)
token := client.Connect()
for !token.WaitTimeout(3 * time.Second) {
}
if err := token.Error(); err != nil {
helpers.PrintError("MQTT", err) // We land here in "horror network" situations, so this must not be fatal
}
return client
}
func createClientOptions(clientId string, uri *url.URL) *mqtt.ClientOptions {
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s", uri.Host))
opts.SetUsername(uri.User.Username())
password, _ := uri.User.Password()
opts.SetPassword(password)
opts.SetClientID(clientId)
return opts
}
// UnSubscribeMQTT unubscribe from receiving update notifications for updateinformation
// TODO: Keep track of what we have already subscribed, and remove from that list
func UnSubscribeMQTT(client mqtt.Client, updateinformation string) {
queryEscapedUpdateInformation := url.QueryEscape(updateinformation)
if queryEscapedUpdateInformation == "" {
return
}
client.Unsubscribe(queryEscapedUpdateInformation)
}
// SubscribeMQTT subscribes to receive update notifications for updateinformation
// TODO: Keep track of what we have already subscribed, and don't subscribe again
func SubscribeMQTT(client mqtt.Client, updateinformation string) {
if helpers.SliceContains(subscribedMQTTTopics, updateinformation) {
// We have already subscribed to this; so nothing to do here
return
}
// Need to do this immediately here, otherwise it comes too late
subscribedMQTTTopics = helpers.AppendIfMissing(subscribedMQTTTopics, updateinformation)
time.Sleep(time.Second * 10) // We get retained messages immediately when we subscribe;
// at this point our AppImage may not be integrated yet...
// Also it's better user experience not to be bombarded with updates immediately at startup.
// 10 seconds should be plenty of time.
queryEscapedUpdateInformation := url.QueryEscape(updateinformation)
if queryEscapedUpdateInformation == "" {
return
}
topic := helpers.MQTTNamespace + "/" + queryEscapedUpdateInformation + "/#"
if *verbosePtr {
log.Println("mqtt: Waiting for messages on topic", helpers.MQTTNamespace+"/"+queryEscapedUpdateInformation+"/version")
} else {
log.Println("Subscribing to updates for", updateinformation)
}
client.Subscribe(topic, 0, func(_ mqtt.Client, msg mqtt.Message) {
// log.Printf("* [%s] %s\n", msg.Topic(), string(msg.Payload()))
// log.Println(topic)
short := strings.Replace(msg.Topic(), helpers.MQTTNamespace+"/", "", -1)
parts := strings.Split(short, "/")
log.Println("mqtt: received:", parts)
if len(parts) < 2 {
return
}
if parts[1] == "version" {
// version := string(msg.Payload())
// Decode incoming JSON
var data helpers.PubSubData
err := json.Unmarshal(msg.Payload(), &data)
if err != nil {
helpers.PrintError("mqtt unmarshal", err)
}
version := data.Version
if version == "" {
return
}
queryEscapedUpdateInformation := parts[0]
log.Println("mqtt:", queryEscapedUpdateInformation, "reports version", version)
unescapedui, _ := url.QueryUnescape(queryEscapedUpdateInformation)
if unescapedui == thisai.updateinformation {
log.Println("++++++++++++++++++++++++++++++++++++++++++++++++++")
log.Println("+ Update available for this AppImage.")
log.Println("+ Something special should happen here: Selfupdate")
log.Println("+ To be imlpemented.")
log.Println("++++++++++++++++++++++++++++++++++++++++++++++++++")
sendDesktopNotification("Update available", "An update for the AppImage daemon is available; I could update myself now...", 0)
}
mostRecent := FindMostRecentAppImageWithMatchingUpdateInformation(unescapedui)
ai, _ := NewAppImage(mostRecent)
fstime := ai.ModTime()
log.Println("mqtt:", updateinformation, "reports version", version, "with FSTime", data.FSTime.Unix(), "- we have", mostRecent, "with FSTime", fstime.Unix())
// FIXME: Only notify if the version is newer than what we already have.
// More precisely, if the AppImage being offered is *different* from the one we already have
// even despite version numbers being the same.
// Blocked by https://github.com/AppImage/AppImageSpec/issues/29,
// in the meantime we are using "-fstime" from unsquashfs to
// check whether two AppImages are "different". Note that we are
// not using this to determine whether which one is newer,
// since we don't trust that timestamp enough.
// We just determine what is the newest AppImage on the local system
// and if that one is deemed "different" from what was received over PubPub,
// then we assume we should offer to update.
// This mechanism should be more robust against wrong timestamps.
if fstime.Unix() != data.FSTime.Unix() {
ui, err := helpers.NewUpdateInformationFromString(updateinformation)
if err != nil {
helpers.PrintError("mqtt: NewUpdateInformationFromString:", err)
} else {
msg, err := helpers.GetCommitMessageForLatestCommit(ui)
// changelog_url, _ := helpers.GetReleaseURL(ui)
if err != nil {
helpers.PrintError("mqtt: GetCommitMessageForLatestCommit:", err)
} else {
// The following could not be tested yet
go sendUpdateDesktopNotification(ai, version, msg)
//sendDesktopNotification("Update available for "+ai.niceName, "It can be updated to version "+version+". \n"+msg, 120000)
}
}
} else {
log.Println("mqtt: Not taking action on", ai.Name, "because FStime is identical")
}
}
})
}
<|start_filename|>src/appimaged/inotify.go<|end_filename|>
package main
// Watches a directory using inotify recursively.
// There is a package "recwatcher" but it only is recursive for the directories
// that were existing at the time when the watch was started, so it is not useful for us.
// So we handle recursion ourselves.
//
// We should find a way to do with inotify since
// normal users can only have 128 watched directories
// (subdirectories seemingly count separately)
// me@host:~$ cat /proc/sys/fs/inotify/max_user_instances
// 128
//
// TODO: Check https://github.com/amir73il/fsnotify-utils/wiki/Super-block-root-watch
// Super block root watch is designed to solve the scalability issues with inotify recursive watches.
// The fanotify super block watch patch set is meant to fill this gap in functionality and add the functionality of a root watch.
// It was merged to kernel v5.1-rc1.
// Currently fanotify needs root rights (CAP_ADMIN privileges)
// Not using the "gopkg.in/fsnotify.v1" package because it does not implement
// a way to find out when a complete is completed, since the needed IN_CLOSE_WRITE
// us Unix specific and not cross-platform. Therefore, we are using https://github.com/rjeczalik/notify
import (
"log"
"github.com/rjeczalik/notify"
)
// Can we watch files with a certain file name extension only
// and how would this improve performance?
func inotifyWatch(path string) {
// Make the channel buffered to ensure no event is dropped. Notify will drop
// an event if the receiver is not able to keep up the sending pace.
c := make(chan notify.EventInfo, 1)
// Set up a watchpoint listening for inotify-specific events within a
// current working directory. Dispatch each InCloseWrite and InMovedTo
// events separately to c.
if err := notify.Watch(path, c, notify.InCloseWrite, notify.InMovedTo,
notify.InMovedFrom, notify.InDelete,
notify.InDeleteSelf); err != nil {
log.Println(err) // Don't be fatal if a directory cannot be read (e.g., no read rights)
}
defer notify.Stop(c)
for {
// Block until an event is received.
switch ei := <-c; ei.Event() {
case notify.InDeleteSelf:
log.Println("TODO:", ei.Path(), "was deleted, un-integrate all AppImages that were conteined herein")
fallthrough
// log.Println("ToBeIntegratedOrUnintegrated now contains:", ToBeIntegratedOrUnintegrated)
case notify.InMovedFrom:
ai, _ := NewAppImage(ei.Path())
ai.startup = false
integrationChannel <- ai
default:
log.Println("inotifyWatch:", ei.Path(), ei.Event())
ai, err := NewAppImage(ei.Path())
if err == nil {
ai.startup = false
integrationChannel <- ai
}
// log.Println("ToBeIntegratedOrUnintegrated now contains:", ToBeIntegratedOrUnintegrated)
}
}
}
| mgord9518/go-appimage |
<|start_filename|>XLLLimaTest/Vendors/Lima/LMRowView.h<|end_filename|>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "LMBoxView.h"
NS_ASSUME_NONNULL_BEGIN
/**
* Baseline options.
*/
typedef NS_ENUM(NSInteger, LMBaseline) {
/** First baseline. */
LMBaselineFirst,
/** Last baseline. */
LMBaselineLast
};
/**
* Layout view that arranges subviews horizontally in a row.
*/
@interface LMRowView : LMBoxView
/**
* The baseline to which subviews will be aligned when aligning to baseline.
* By default, subviews will be aligned to the first baseline.
*/
@property (nonatomic) LMBaseline baseline;
@end
NS_ASSUME_NONNULL_END
<|start_filename|>XLLLimaTest/Vendors/Lima/LMScrollView.h<|end_filename|>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
* Scroll view that automatically adapts to the size of its content.
*/
@interface LMScrollView : UIScrollView
/**
* Indicates that the width of the scroll view's content should match the scroll view's width.
* The default value is <code>NO</code>.
*/
@property (nonatomic) BOOL fitToWidth NS_SWIFT_NAME(isFitToWidth);
/**
* Indicates that the height of the scroll view's content should match the scroll view's height.
* The default value is <code>NO</code>.
*/
@property (nonatomic) BOOL fitToHeight NS_SWIFT_NAME(isFitToHeight);
/**
* The scroll view's content.
*/
@property (nonatomic, nullable) UIView *content;
@end
NS_ASSUME_NONNULL_END
<|start_filename|>XLLLimaTest/Vendors/Lima/LMBoxView.h<|end_filename|>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "LMLayoutView.h"
NS_ASSUME_NONNULL_BEGIN
/**
* Horizontal alignment options.
*/
typedef NS_ENUM(NSInteger, LMHorizontalAlignment) {
/** Fill horizontal alignment. */
LMHorizontalAlignmentFill,
/** Leading horizontal alignment. */
LMHorizontalAlignmentLeading,
/** Trailing horizontal alignment. */
LMHorizontalAlignmentTrailing,
/** Center horizontal alignment. */
LMHorizontalAlignmentCenter
};
/**
* Vertical alignment options.
*/
typedef NS_ENUM(NSInteger, LMVerticalAlignment) {
/** Fill vertical alignment. */
LMVerticalAlignmentFill,
/** Top vertical alignment. */
LMVerticalAlignmentTop,
/** Bottom vertical alignment. */
LMVerticalAlignmentBottom,
/** Center vertical alignment. */
LMVerticalAlignmentCenter
};
/**
* Abstract base class for box views.
*/
@interface LMBoxView : LMLayoutView
/**
* The horizontal alignment of the subviews. The default is "fill".
*/
@property (nonatomic) LMHorizontalAlignment horizontalAlignment;
/**
* The vertical alignment of the subviews. The default is "fill".
*/
@property (nonatomic) LMVerticalAlignment verticalAlignment;
/**
* The amount of spacing between successive subviews.
*/
@property (nonatomic) CGFloat spacing;
/**
* Specifies that subviews should be baseline-aligned. The default value is
* <code>NO</code>.
*/
@property (nonatomic) BOOL alignToBaseline NS_SWIFT_NAME(isAlignToBaseline);
@end
NS_ASSUME_NONNULL_END
| XLLIosTest/XLLLimaTest |
<|start_filename|>protohelpers.go<|end_filename|>
package main
import (
"net/http"
tasks "google.golang.org/genproto/googleapis/cloud/tasks/v2"
rpccode "google.golang.org/genproto/googleapis/rpc/code"
)
func toHTTPMethod(taskMethod tasks.HttpMethod) string {
switch taskMethod {
case tasks.HttpMethod_GET:
return http.MethodGet
case tasks.HttpMethod_POST:
return http.MethodPost
case tasks.HttpMethod_DELETE:
return http.MethodDelete
case tasks.HttpMethod_HEAD:
return http.MethodHead
case tasks.HttpMethod_OPTIONS:
return http.MethodOptions
case tasks.HttpMethod_PATCH:
return http.MethodPatch
case tasks.HttpMethod_PUT:
return http.MethodPut
default:
panic("Unsupported http method")
}
}
func toRPCStatusCode(statusCode int) int32 {
switch statusCode {
case 200:
return int32(rpccode.Code_OK)
case 400:
// TODO: or rpccode.Code_FAILED_PRECONDITION
// TODO: or rpcCode.Code_OUT_OF_RANGE
return int32(rpccode.Code_INVALID_ARGUMENT)
case 401:
return int32(rpccode.Code_UNAUTHENTICATED)
case 403:
return int32(rpccode.Code_PERMISSION_DENIED)
case 404:
return int32(rpccode.Code_NOT_FOUND)
case 409:
// TODO: or rpccde.Code_ABORTED
return int32(rpccode.Code_ALREADY_EXISTS)
case 429:
return int32(rpccode.Code_RESOURCE_EXHAUSTED)
case 499:
return int32(rpccode.Code_CANCELLED)
case 500:
//TODO: or rpccode.Code_DATA_LOSS
return int32(rpccode.Code_INTERNAL)
case 501:
return int32(rpccode.Code_UNIMPLEMENTED)
case 503:
return int32(rpccode.Code_UNAVAILABLE)
case 504:
return int32(rpccode.Code_DEADLINE_EXCEEDED)
default:
return int32(rpccode.Code_UNKNOWN)
}
}
func toCodeName(rpcCode int32) string {
return rpccode.Code_name[rpcCode]
}
| phalimee/cloud-tasks-emulator |
<|start_filename|>src/index.js<|end_filename|>
export { default as forceMagnetic } from './magnetic';
<|start_filename|>src/magnetic.js<|end_filename|>
import constant from './constant';
import {binarytree} from 'd3-binarytree';
import {quadtree} from 'd3-quadtree';
import {octree} from 'd3-octree';
export default function() {
let nDim,
nodes = [],
links = [],
id = (node => node.index), // accessor: node unique id
charge = (node => 100), // accessor: number (equivalent to node mass)
strength = (link => 1), // accessor: number (equivalent to G constant)
polarity = ((q1, q2) => null), // boolean or null (asymmetrical)
distanceWeight = (d => 1/(d*d)), // Intensity falls with the square of the distance (inverse-square law)
theta = 0.9;
function force(alpha) {
if (links.length) { // Pre-set node pairs
for (let i = 0; i < links.length; i++) {
const link = links[i],
dx = link.target.x - link.source.x,
dy = (link.target.y - link.source.y) || 0,
dz = (link.target.z - link.target.z) || 0,
d = distance(dx, dy, dz);
if (d === 0) continue;
const relStrength = alpha * strength(link) * distanceWeight(d);
const qSrc = charge(link.source),
qTgt = charge(link.target);
// Set attract/repel polarity
const linkPolarity = polarity(qSrc, qTgt);
const sourceAcceleration = signedCharge(qTgt, linkPolarity) * relStrength;
const targetAcceleration = signedCharge(qSrc, linkPolarity) * relStrength;
link.source.vx += dx / d * sourceAcceleration;
link.target.vx -= dx / d * targetAcceleration;
if (nDim > 1) {
link.source.vy += dy / d * sourceAcceleration;
link.target.vy -= dy / d * targetAcceleration;
}
if (nDim > 2) {
link.source.vz += dz / d * sourceAcceleration;
link.target.vz -= dz / d * targetAcceleration;
}
}
} else { // Assume full node mesh if no links specified
const tree =
(nDim === 1 ? binarytree(nodes, d => d.x)
:(nDim === 2 ? quadtree(nodes, d => d.x, d => d.y)
:(nDim === 3 ? octree(nodes, d => d.x, d => d.y, d => d.z)
:null
))).visitAfter(accumulate);
const etherStrength = alpha * strength();
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i],
nodeQ = charge(node);
tree.visit((treeNode, x1, arg1, arg2, arg3) => {
if (!treeNode.value) return true;
const x2 = [arg1, arg2, arg3][nDim-1];
const dx = treeNode.x - node.x,
dy = (treeNode.y - node.y) || 0,
dz = (treeNode.z - node.z) || 0,
d = distance(dx, dy, dz);
// Apply the Barnes-Hut approximation if possible.
if ((x2-x1) / d < theta) {
if (d > 0) {
applyAcceleration();
}
return true;
}
// Otherwise, process points directly.
else if (treeNode.length || d === 0) return;
do if (treeNode.data !== node) {
applyAcceleration();
} while (treeNode = treeNode.next);
//
function applyAcceleration() {
const acceleration = signedCharge(treeNode.value, polarity(nodeQ, treeNode.value)) * etherStrength * distanceWeight(d);
node.vx += dx/d * acceleration;
if (nDim > 1) { node.vy += dy/d * acceleration; }
if (nDim > 2) { node.vz += dz/d * acceleration; }
}
});
}
}
//
function accumulate(treeNode) {
let localCharge = 0, q, c, weight = 0, x, y, z, i;
// For internal nodes, accumulate forces from child tree-nodes (segments/quadrants/octants).
if (treeNode.length) {
for (x = y = z = i = 0; i < (2 ** nDim); ++i) {
if ((q = treeNode[i]) && (c = Math.abs(q.value))) {
localCharge += q.value, weight += c, x += c * (q.x || 0), y += c * (q.y || 0), z += c * (q.z || 0);
}
}
treeNode.x = x / weight;
if (nDim > 1) { treeNode.y = y / weight; }
if (nDim > 2) { treeNode.z = z / weight; }
}
// For leaf nodes, accumulate forces from coincident tree nodes.
else {
q = treeNode;
q.x = q.data.x;
if (nDim > 1) { q.y = q.data.y; }
if (nDim > 2) { q.z = q.data.z; }
do localCharge += charge(q.data);
while (q = q.next);
}
treeNode.value = localCharge;
}
function signedCharge(q, polarity) {
if (polarity === null) return q; // No change with null polarity
return Math.abs(q) * (polarity ? 1 : -1);
}
function distance(x, y, z) {
return Math.sqrt(x*x + y*y + z*z);
}
}
function initialize() {
const nodesById = {};
nodes.forEach(node => {
nodesById[id(node)] = node;
});
links.forEach(link => {
if (typeof link.source !== "object") link.source = nodesById[link.source] || link.source;
if (typeof link.target !== "object") link.target = nodesById[link.target] || link.target;
});
}
force.initialize = function(initNodes, ...args) {
nodes = initNodes;
nDim = args.find(arg => [1, 2, 3].includes(arg)) || 2;
initialize();
};
force.links = function(_) {
return arguments.length ? (links = _, initialize(), force) : links;
};
// Node id
force.id = function(_) {
return arguments.length ? (id = _, force) : id;
};
// Node capacity to attract (positive) or repel (negative)
force.charge = function(_) {
return arguments.length ? (charge = typeof _ === "function" ? _ : constant(+_), force) : charge;
};
// Link strength (ability of the medium to propagate charges)
force.strength = function(_) {
return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), force) : strength;
};
// How force direction is determined (whether nodes should attract each other (boolean), or asymmetrical based on opposite node's charge sign (null))
force.polarity = function(_) {
return arguments.length ? (polarity = typeof _ === "function" ? _ : constant(+_), force) : polarity;
};
// How the force intensity relates to the distance between nodes
force.distanceWeight = function(_) {
return arguments.length ? (distanceWeight = _, force) : distanceWeight;
};
// Barnes-Hut approximation tetha threshold (for full-mesh mode)
force.theta = function(_) {
return arguments.length ? (theta = _, force) : theta;
};
return force;
} | vasturiano/d3-force-magnetic |
<|start_filename|>app/src/main/java/eu/kanade/tachiyomi/data/glide/FileFetcher.kt<|end_filename|>
package eu.kanade.tachiyomi.data.glide
import android.content.ContentValues.TAG
import android.util.Log
import com.bumptech.glide.Priority
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.data.DataFetcher
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import timber.log.Timber
open class FileFetcher(private val filePath: String = "") : DataFetcher<InputStream> {
private var data: InputStream? = null
override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in InputStream>) {
loadFromFile(callback)
}
private fun loadFromFile(callback: DataFetcher.DataCallback<in InputStream>) {
loadFromFile(File(filePath), callback)
}
protected fun loadFromFile(file: File, callback: DataFetcher.DataCallback<in InputStream>) {
try {
data = FileInputStream(file)
} catch (e: FileNotFoundException) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Timber.d(e, "Failed to open file")
}
callback.onLoadFailed(e)
return
}
callback.onDataReady(data)
}
override fun cleanup() {
try {
data?.close()
} catch (e: IOException) {
// Ignored.
}
}
override fun cancel() {
// Do nothing.
}
override fun getDataClass(): Class<InputStream> {
return InputStream::class.java
}
override fun getDataSource(): DataSource {
return DataSource.LOCAL
}
}
<|start_filename|>app/src/main/java/eu/kanade/tachiyomi/ui/base/holder/BaseFlexibleViewHolder.kt<|end_filename|>
package eu.kanade.tachiyomi.ui.base.holder
import android.view.View
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.viewholders.FlexibleViewHolder
import kotlinx.android.extensions.LayoutContainer
abstract class BaseFlexibleViewHolder(
view: View,
adapter: FlexibleAdapter<*>,
stickyHeader: Boolean = false
) : FlexibleViewHolder(view, adapter, stickyHeader), LayoutContainer {
override val containerView: View?
get() = itemView
}
| lmj0011/tachiyomi |
<|start_filename|>Extensions/ExternalTfs/Src/Tasks/DownloadArtifactsTfsGit/package.json<|end_filename|>
{
"name": "DownloadArtifactsTfsGit",
"main": "download.js",
"dependencies": {
"azure-devops-node-api": "10.2.1",
"vsts-task-lib": "2.0.5"
}
}
<|start_filename|>Extensions/ExternalTfs/Src/Tasks/DownloadArtifactsTfsGit/gitwrapper.js<|end_filename|>
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var tl = require('vsts-task-lib');
var events = require('events');
var Q = require('q');
var fs = require('fs');
var shell = require('shelljs');
var path = require('path');
exports.envGitUsername = 'GIT_USERNAME';
exports.envGitPassword = '<PASSWORD>';
var GitWrapper = (function (_super) {
__extends(GitWrapper, _super);
function GitWrapper() {
_super.call(this);
this.gitInstalled = shell.which('git', false) !== null;
}
GitWrapper.prototype.clone = function (repository, progress, folder, options) {
options = options || {};
options.useGitExe = true;
options.creds = true;
var args = ['clone', repository];
if (progress) {
args.push('--progress');
}
if (folder) {
args.push(folder);
}
return this.exec(args, options);
};
GitWrapper.prototype.fetch = function (args, options) {
options = options || {};
options.useGitExe = true;
options.creds = true;
return this.exec(['fetch'].concat(args), options);
};
GitWrapper.prototype.checkout = function (ref, options) {
options = options || {};
options.useGitExe = true;
options.creds = true;
return this.exec(['checkout', ref], options);
};
GitWrapper.prototype.reset = function (args, options) {
options = options || {};
options.useGitExe = true;
return this.exec(['reset'].concat(args), options);
};
GitWrapper.prototype.exec = function (args, options) {
var _this = this;
options = options || {};
var defer = Q.defer();
var gitPath = shell.which('git', false);
var rootDirectory = path.dirname(path.dirname(path.dirname(path.dirname(path.dirname(require.main.filename)))));
var agentGit = path.join(rootDirectory, "externals", "git", "cmd", "git.exe");
if(fs.existsSync(agentGit)){
gitPath = agentGit;
}
if (!gitPath) {
throw (new Error('git not found. ensure installed and in the path'));
}
var git = new tl.ToolRunner(gitPath);
git.silent = true;
var creds = this.username + ':' + this.password;
var escapedCreds = encodeURIComponent(this.username) + ':' + encodeURIComponent(this.password);
git.on('debug', function (message) {
if (options.debugOutput) {
var repl = message.replace(creds, '...');
repl = repl.replace(escapedCreds, '...');
_this.emit('stdout', '[debug]' + repl);
}
});
git.on('stdout', function (data) {
_this.emit('stdout', data);
});
git.on('stderr', function (data) {
_this.emit('stderr', data);
});
// TODO: if HTTP_PROXY is set (debugging) we can also supply http.proxy config
// TODO: handle and test with spaces in the path
if (false // not using credhelper for now, user/pass in url
&& options.creds) {
// protect against private repo where no creds are supplied (external) - we don't want a prompt
process.env[exports.envGitUsername] = this.username || 'none';
process.env[exports.envGitPassword] = this.password || '';
var credHelper = path.join(__dirname, 'credhelper.js');
git.arg('-c');
// TODO: test quoting and spaces
git.arg('credential.helper=' + credHelper, true); // raw arg
}
args.map(function (arg) {
git.arg(arg, true); // raw arg
});
options = options || {};
var ops = {
cwd: options.cwd || process.cwd(),
env: options.env || process.env,
silent: true,
outStream: options.outStream || process.stdout,
errStream: options.errStream || process.stderr,
failOnStdErr: false,
ignoreReturnCode: false
};
return git.exec(ops)
.fin(function () {
process.env[exports.envGitUsername] = null;
process.env[exports.envGitPassword] = null;
});
};
return GitWrapper;
}(events.EventEmitter));
exports.GitWrapper = GitWrapper;
<|start_filename|>Extensions/ExternalTfs/Src/Tasks/DownloadArtifactsTfsGit/downloadTfGit.js<|end_filename|>
var tl = require('vsts-task-lib/task');
var path = require('path');
var webApim = require('azure-devops-node-api/WebApi');
var Q = require('q');
var url = require('url');
var shell = require("shelljs");
var gitwm = require('./gitwrapper');
var PullRefsPrefix = "refs/pull/";
var PullRefsOriginPrefix = "refs/remotes/origin/pull/";
var repositoryId = tl.getInput("definition");
var projectId = tl.getInput("project");
var branch = tl.getInput("branch");
var commitId = tl.getInput("version");
var downloadPath = tl.getInput("downloadPath");
var tfsEndpoint = getEndpointDetails("connection");
var VSTS_HTTP_RETRY = 4;
shell.rm('-rf', downloadPath);
var error = shell.error();
if(error){
tl.error(error);
tl.exit(1);
}
function executeWithRetries (operationName, operation, currentRetryCount) {
var deferred = Q.defer()
operation().then((result) => {
deferred.resolve(result)
}).fail((error) => {
if (currentRetryCount <= 0) {
tl.error('OperationFailed: ' + operationName)
tl.setResult(tl.TaskResult.Failed, error);
deferred.reject(error)
}else {
console.log('RetryingOperation', operationName, currentRetryCount)
currentRetryCount = currentRetryCount - 1
setTimeout(() => executeWithRetries(operationName, operation, currentRetryCount), 4 * 1000)
}
})
return deferred.promise
}
var gitRepositoryPromise = getRepositoryDetails(tfsEndpoint, repositoryId, projectId);
Q.resolve(gitRepositoryPromise).then( function (gitRepository) {
var gitw = new gitwm.GitWrapper();
gitw.on('stdout', function (data) {
console.log(data.toString());
});
gitw.on('stderr', function (data) {
console.log(data.toString());
});
var remoteUrl = gitRepository.remoteUrl;
tl.debug("Remote Url:" + remoteUrl);
// encodes projects and repo names with spaces
var gu = url.parse(remoteUrl);
if (tfsEndpoint.Username && tfsEndpoint.Password) {
gu.auth = tfsEndpoint.Username + ':' + tfsEndpoint.Password;
}
var giturl = gu.format(gu);
var isPullRequest = !!branch && (branch.toLowerCase().startsWith(PullRefsPrefix) || branch.toLowerCase().startsWith(PullRefsOriginPrefix));
tl.debug("IsPullRequest:" + isPullRequest);
// if branch, we want to clone remote branch name to avoid tracking etc.. ('/refs/remotes/...')
var ref;
var brPre = 'refs/heads/';
if (branch.startsWith(brPre)) {
ref = 'refs/remotes/origin/' + branch.substr(brPre.length, branch.length - brPre.length);
}
else{
ref = branch;
}
var gopt = {
creds: true,
debugOutput: this.debugOutput
};
gitw.username = this.username;
gitw.password = <PASSWORD>;
Q(0).then(() => executeWithRetries('gitClone', function (code) {
return gitw.clone(giturl, true, downloadPath, gopt).then(function (result) {
if (isPullRequest) {
// clone doesn't pull the refs/pull namespace, so fetch it
shell.cd(downloadPath);
return gitw.fetch(['origin', branch], gopt);
}
else {
return Q(result);
}
});
}, VSTS_HTTP_RETRY)).then(function (code) {
shell.cd(downloadPath);
if (isPullRequest) {
ref = commitId;
}
return gitw.checkout(ref, gopt);
}).then(function (code) {
if(!isPullRequest){
return gitw.checkout(commitId);
}
}).fail(function (error) {
tl.error(error);
tl.setResult(tl.TaskResult.Failed, error);
tl.exit(1);
});
});
function getRepositoryDetails(tfsEndpoint, repositoryId, projectId){
var handler = webApim.getBasicHandler(tfsEndpoint.Username, tfsEndpoint.Password);
var webApi = new webApim.WebApi(tfsEndpoint.Url, handler);
var gitClientPromise = webApi.getGitApi();
Q.resolve(gitClientPromise).then( function (gitClient) {
var promise = gitClient.getRepository(repositoryId, projectId);
return promise;
});
}
function getEndpointDetails(inputFieldName) {
var errorMessage = "Could not decode the External Tfs endpoint. Please ensure you are running the latest agent";
if (!tl.getEndpointUrl) {
throw new Error(errorMessage);
}
var externalTfsEndpoint = tl.getInput(inputFieldName);
if (!externalTfsEndpoint) {
throw new Error(errorMessage);
}
var hostUrl = tl.getEndpointUrl(externalTfsEndpoint, false);
if (!hostUrl) {
throw new Error(errorMessage);
}
var auth = tl.getEndpointAuthorization(externalTfsEndpoint, false);
if (auth.scheme != "UsernamePassword" && auth.scheme != "Token") {
throw new Error("The authorization scheme " + auth.scheme + " is not supported for a External Tfs endpoint.");
}
var hostUsername = ".";
var hostPassword = "";
if(auth.scheme == "Token") {
hostPassword = getAuthParameter(auth, 'ap<PASSWORD>');
}
else {
hostUsername = getAuthParameter(auth, 'username');
hostPassword = getAuthParameter(auth, 'password');
}
return {
"Url": hostUrl,
"Username": hostUsername,
"Password": <PASSWORD>Password
};
}
function getAuthParameter(auth, paramName) {
var paramValue = null;
var parameters = Object.getOwnPropertyNames(auth['parameters']);
var keyName;
parameters.some(function (key) {
if (key.toLowerCase() === paramName.toLowerCase()) {
keyName = key;
return true;
}
});
paramValue = auth['parameters'][keyName];
return paramValue;
}
<|start_filename|>Extensions/ExternalTfs/Src/Tasks/DownloadExternalBuildArtifacts/package.json<|end_filename|>
{
"name": "DownloadExternalBuildArtifacts",
"main": "download.js",
"dependencies": {
"azure-devops-node-api": "10.2.1",
"vsts-task-lib": "2.2.1",
"artifact-engine": "0.1.29"
}
}
| finkinfridom/azure-pipelines-extensions |
<|start_filename|>src/chart.config.js<|end_filename|>
// get chart components
import {
Chart,
Legend,
Tooltip,
Filler,
CategoryScale,
LinearScale,
PointElement,
LineElement,
LineController,
BarElement,
BarController,
ArcElement,
DoughnutController
} from "chart.js";
// register chart components
Chart.register(
Legend,
Tooltip,
Filler,
CategoryScale,
LinearScale,
PointElement,
LineElement,
LineController,
BarElement,
BarController,
ArcElement,
DoughnutController
);
// set global configuration
Chart.defaults.color = "#8a8a97";
Chart.defaults.plugins.legend.display = false;
Chart.defaults.plugins.tooltip.mode = "index";
Chart.defaults.plugins.tooltip.intersect = false;
Chart.defaults.plugins.tooltip.multiKeyBackground = "#000";
Chart.defaults.plugins.tooltip.titleMarginBottom = 10;
Chart.defaults.plugins.tooltip.padding = 10;
Chart.defaults.plugins.tooltip.cornerRadius = 2;
Chart.defaults.hover.mode = "index";
// provide transparent gradient coloring based on given color for line chart backgrounds
const transparentGradientLine = (ctx, chartArea, hexColor) => {
const gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
const fromColor = hexColor.slice(0, 7) + '00';
const toColor = hexColor.length === 9 ? hexColor : hexColor.slice(0, 7) + '77';
gradient.addColorStop(0, fromColor);
gradient.addColorStop(1, toColor);
return gradient;
}
// provide transparent gradient coloring based on given color for bar chart backgrounds
const transparentGradientBar = (ctx, chartArea, hexColor, horizontal=false) => {
const gradient = horizontal
? ctx.createLinearGradient(chartArea.left, 0, chartArea.right, 0)
: ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
gradient.addColorStop(0, hexColor.slice(0, 7) + '33');
gradient.addColorStop(1, hexColor.slice(0, 7) + '77');
return gradient;
}
export {
Chart,
transparentGradientLine,
transparentGradientBar
}
<|start_filename|>src/options.js<|end_filename|>
import Vue from "vue"
import Options from "./Options.vue"
// vue configuration
Vue.config.productionTip = false
Vue.config.devtools = false
// internationalization
import VueI18n from "vue-i18n"
Vue.use(VueI18n)
import { messages } from "./translations"
import { pluralizationPolish } from "./utils"
const i18n = new VueI18n({
locale: messenger.i18n.getUILanguage(),
fallbackLocale: "en",
messages,
pluralizationRules: {
"pl": (choice) => pluralizationPolish(choice)
}
})
new Vue({
i18n,
render: h => h(Options),
}).$mount("#options")
<|start_filename|>src/stats.js<|end_filename|>
import Vue from "vue"
import Stats from "./Stats.vue"
// vue local configuration
Vue.config.productionTip = false
Vue.config.devtools = false
// vue global properties
Vue.prototype.$version = process.env.VUE_APP_VERSION
// global mixins
Vue.mixin({
methods: {
twoDigit: n => n.toFixed(2),
oneDigit: n => n.toFixed(1),
round: (n,d) => Number(Math.round(n + "e+" + d) + "e-" + d),
},
})
// internationalization
import VueI18n from "vue-i18n"
Vue.use(VueI18n)
import { pluralizationPolish } from "./utils"
import { messages } from "./translations"
const i18n = new VueI18n({
locale: messenger.i18n.getUILanguage(),
fallbackLocale: "en",
messages,
pluralizationRules: {
"pl": (choice) => pluralizationPolish(choice)
}
})
new Vue({
i18n,
render: h => h(Stats),
}).$mount("#stats")
<|start_filename|>public/js/background.js<|end_filename|>
// nothing here yet
// this script serves as a dummy to create a background page as a workaround to retrieve account list on options page
// see https://thunderbird.topicbox.com/groups/addons/Te33a79990d7a857e
// see https://github.com/thundernest/developer-docs/blob/master/add-ons/updating/tb78/README.md#replacing-options
| utolosa002/third-stats |
<|start_filename|>src/leola/lang/LangLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.lib.LeolaMethod;
import leola.vm.lib.LeolaMethodVarargs;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoDouble;
import leola.vm.types.LeoInteger;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoNativeClass;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoObject.LeoType;
import leola.vm.util.Classpath;
/**
* The system core functions
*
* @author Tony
*
*/
public class LangLeolaLibrary implements LeolaLibrary {
/**
* The runtime
*/
private Leola runtime;
/* (non-Javadoc)
* @see leola.frontend.LeolaLibrary#init(leola.frontend.Leola)
*/
@LeolaIgnore
public void init(Leola runtime, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = runtime;
runtime.putIntoNamespace(this, namespace);
}
/**
* Includes either a Leola script file or Jar file.
*
* @param lib
* @param namespace
* @throws Exception
*/
public final void include(String lib, String namespace) throws Exception {
runtime.getResourceLoader().include(lib, namespace);
}
/**
* Loads a {@link LeolaLibrary} file.
*
* @param lib
* @param namespace
* @throws Exception
*/
public final void require(String lib, String namespace) throws Exception {
runtime.getResourceLoader().require(lib, namespace);
}
/**
* Reloads a library
* @param lib
* @param namespace
* @throws Exception
*/
public void reload(String lib, String namespace) throws Exception {
runtime.getResourceLoader().removeFromCache(lib);
include(lib, namespace);
}
/**
* Dynamically loads a jar file
* @param jarFile
* @throws Exception
*/
public final static void loadJar(String jarFile) throws IOException {
Classpath.addFile(jarFile);
}
/**
* Dynamically loads all the jar files located in the directory
*
* @param directory
* @throws IOException
*/
public final static void loadJars(String directory) throws IOException {
File dir = new File(directory);
if ( dir.isDirectory() ) {
File[] jars = dir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".jar");
}
});
for(File jar : jars) {
Classpath.addFile(jar);
}
}
}
/**
* Loads the URL to the classpath.
*
* @param url
* @throws IOException
*/
public final static void loadURL(String url) throws IOException {
File dir = new File(url);
Classpath.addURL(dir.toURI().toURL());
}
/**
* Loads a library
*
* @param lib
*/
public final void loadLibrary(String lib) throws Exception {
runtime.errorIfSandboxed();
runtime.loadLibrary(Class.forName(lib));
}
/**
* Loads a class
*
* @param className
* @param namespace
* @throws Exception
*/
@LeolaMethod(alias="import")
public final void __import(String className, String namespace) throws Exception {
runtime.errorIfSandboxed();
if(namespace != null && !namespace.equals("")) {
runtime.loadStatics(runtime.getOrCreateNamespace(namespace), Class.forName(className));
}
else {
runtime.loadStatics(Class.forName(className));
}
}
/**
* Evaluates the expression.
*
* @param expr
* @return the result of evaluation
* @throws Exception
*/
public final LeoObject eval(String expr) throws Exception {
LeoObject result = runtime.eval(expr);
return result;
}
/**
* Reads a line from sys in
*
* TODO - move to io
* @return the line read from system in
*/
@SuppressWarnings("resource")
public final String readln() {
String result = null;
Scanner s = new Scanner(java.lang.System.in);
try {
if ( s.hasNextLine() ) {
result = s.nextLine();
}
}
finally {
// s.close(); DO NOT close because this will close SysIn
}
return result;
}
private void printf(PrintStream out, Object x, LeoObject ... args) {
if(args!=null) {
int len = args.length;
Object[] params = new Object[len];
for(int i = 0; i < len; i++) {
params[i] = args[i].getValue();
}
out.printf(x.toString(), params);
}
else {
out.printf(x.toString());
}
}
/**
* Print format to system error
*
* @param x
* @param args
*/
@LeolaMethodVarargs
public final void eprintf(Object x, LeoObject ...args) {
printf(System.err, x, args);
}
/**
* Print format
*
* @param x the string to be formatted
* @param args the format arguments
*/
@LeolaMethodVarargs
public final void printf(Object x, LeoObject ... args) {
printf(System.out, x, args);
}
/**
* Prints to system error with a new line
*
* @param x
*/
public final void eprintln(Object x) {
System.err.println(x);
}
/**
* Prints to system out with a new line
*
* @param x
*/
public final void println(Object x) {
java.lang.System.out.println(x);
}
/**
* Prints to system error.
*
* @param x
*/
public final void eprint(Object x) {
System.err.print(x);
}
/**
* Prints to system out.
*
* @param x
*/
public final void print(Object x) {
java.lang.System.out.print(x);
}
/**
* Transforms the supplied object into a number
* @param x
* @return the double
*/
public final double toNumber(Object x) {
String str = x.toString();
return Double.parseDouble(str);
}
/**
* Transforms the supplied object into a string
* @param x
* @return the string
*/
public final String toString(Object x) {
return x.toString();
}
/**
* Converts the string into byte[]
*
* @param str
* @return the byte[]
*/
public final LeoNativeClass toBytes(String str) {
return new LeoNativeClass(byte[].class, str.getBytes());
}
/**
* @param x
* @return an integer representation
*/
public final int toInt(Object x) {
Double d = toNumber(x);
return d.intValue();
}
/**
* @param x
* @return a long representation
*/
public final long toLong(Object x) {
Number number = toNumber(x);
return number.longValue();
}
/**
* @param x
* @return a double representation
*/
public final double toDouble(Object x) {
return toNumber(x);
}
/**
* Synchronizes the supplied {@link LeoObject} function
*
* @param function
* @return the result of invoking the function
*/
@LeolaMethod(alias="synchronized")
public final LeoObject _synchronized(LeoObject function) {
synchronized (function) {
return function.xcall();
}
}
/**
* Converts the {@link Collection} into a {@link LeoArray}
*
* @param list
* @return the {@link LeoArray}
*/
public final LeoArray toArray(Collection<Object> list) {
return LeoArray.toArray(list);
}
/**
* Converts the java {@link Map} into a {@link LeoMap} object.
*
* @param map
* @return the {@link LeoMap}
*/
public final LeoMap toMap(Map<Object, Object> map) {
return LeoMap.toMap(map);
}
/**
* Converts the object to a character
*
* @param x
* @return the character
*/
public final char toChar(Object x) {
if ( x instanceof String) {
return ((String) x).charAt(0);
}
else if ( x instanceof LeoObject ) {
LeoObject obj = (LeoObject)x;
if ( obj.isOfType(LeoType.STRING)) {
return obj.toString().charAt(0);
}
if ( obj.isOfType(LeoType.INTEGER)) {
return ((LeoInteger)obj).asChar();
}
if ( obj.isOfType(LeoType.REAL)) {
return ((LeoDouble)obj).asChar();
}
}
throw new IllegalArgumentException("Not a valid char: " + x);
}
/**
* Constructs a new Array
* @param size
* @param func optional fill function
* @return the new array
*/
public final LeoArray newArray(int size, LeoObject func) {
LeoArray result = new LeoArray(size);
if( func != null ) {
for(int i = 0; i < size; i++ ) {
result.add(func.xcall(LeoInteger.valueOf(i)));
}
}
else {
for(int i = 0; i < size; i++ ) {
result.add(LeoNull.LEONULL);
}
}
return result;
}
/**
* Returns a new thread with the supplied {@link LeoObject} serving
* as the thread runnable.
*
* @param function
* @return the thread class
*/
public final LeoNativeClass newThread(final LeoObject function, String name, Boolean daemon) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
function.xcall();
}
catch (Throwable t) {
t.printStackTrace();
}
}
}, name!=null?name:"leola-user-thread");
if(daemon != null) {
thread.setDaemon(daemon);
}
return new LeoNativeClass(thread);
}
/**
* Creates a new {@link Scheduler}
*
* @param poolSize
* @return the {@link Scheduler}
*/
public final LeoNativeClass newScheduler(int poolSize) {
return new LeoNativeClass(new Scheduler(poolSize));
}
/**
*
* @author Tony
*
*/
public static class Scheduler {
private ScheduledExecutorService executorService;
Scheduler(int poolSize) {
this.executorService = Executors.newScheduledThreadPool(poolSize);
}
/**
* Terminates the scheduler
*/
public void shutdown() {
this.executorService.shutdownNow();
}
/**
* Schedules the function
*
* @param timeMsec
* @param function
*/
public void schedule(long timeMsec, final LeoObject function) {
this.executorService.schedule(new Callable<Void>() {
public Void call() throws Exception {
try {
function.xcall();
}
catch (Throwable t) {
t.printStackTrace();
}
return null;
}
}, timeMsec, TimeUnit.MILLISECONDS);
}
/**
* Repeatedly executes the function
*
* @param delay
* @param function
*/
public void repeat(long delay, final LeoObject function) {
this.executorService.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
function.xcall();
}
catch (Throwable t) {
t.printStackTrace();
}
}
}, delay, delay, TimeUnit.MILLISECONDS);
}
}
}
<|start_filename|>src/leola/ast/ASTNode.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Abstract Syntax tree node
*
* @author Tony
*
*/
public abstract class ASTNode {
public static final int MEMBER_PROPERTY = (1<<1);
/**
* The line number
*/
private int lineNumber;
/**
* Flags
*/
private int flags;
/**
* The parent node
*/
private ASTNode parentNode;
/**
* The source in which this node was created
*/
private String source;
/**
*/
protected ASTNode() {
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "[ " + this.source + " ]" + " @ line: " + this.lineNumber;
}
/**
* @return true if this node has no parent nodes (aka is the root)
*/
public boolean isRootNode() {
return this.parentNode == null;
}
/**
* @return the parentNode
*/
public ASTNode getParentNode() {
return parentNode;
}
/**
* @param parentNode the parentNode to set
*/
public void setParentNode(ASTNode parentNode) {
this.parentNode = parentNode;
}
/**
* Sets the parent of the supplied node to this node
* @param node
* @return the node passed in
*/
protected <T extends ASTNode> T becomeParentOf(T node) {
if(node !=null ) {
node.setParentNode(this);
}
return node;
}
/**
* @param lineNumber the lineNumber to set
*/
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
/**
* @return the lineNumber
*/
public int getLineNumber() {
return lineNumber;
}
/**
* @param sourceLine
*/
public void setSourceLine(String sourceLine) {
this.source = sourceLine;
}
/**
* @return the sourceFile
*/
public String getSourceLine() {
return source;
}
/**
* @return the flags
*/
public int getFlags() {
return flags;
}
/**
* @param flags the flags to set
*/
public void setFlags(int flags) {
this.flags = flags;
}
public void appendFlag(int flag) {
this.flags |= flag;
}
public boolean hasFlag(int flag) {
return (this.flags & flag) != 0;
}
/**
* Visits the {@link ASTNode}.
*
* @param v
*/
public abstract void visit(ASTNodeVisitor v) throws EvalException;
}
<|start_filename|>src/leola/vm/types/LeoClass.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import leola.vm.ClassDefinition;
import leola.vm.Leola;
import leola.vm.Opcodes;
import leola.vm.Scope;
import leola.vm.compiler.Bytecode;
/**
* Represents an instance of a Class
*
* @author Tony
*
*/
public class LeoClass extends LeoScopedObject {
/**
* Metaclass is used for reflection
*
* @author Tony
*
*/
public static class Metaclass {
private LeoClass clss;
/**
* @param clss
*/
public Metaclass(LeoClass clss) {
this.clss = clss;
}
public LeoObject className() {
return clss.className;
}
/**
* @see LeoScopedObject#getProperties()
* @return
*/
public LeoArray members() {
return clss.getProperties();
}
/**
* @see LeoScopedObject#getPropertyNames()
* @return
*/
public LeoArray memberNames() {
return clss.getPropertyNames();
}
public Bytecode bytecode() {
return clss.constructor;
}
public LeoObject superClass() {
return clss.superClass;
}
public LeoArray paramNames() {
return new LeoArray(clss.paramNames);
}
}
private Leola runtime;
private Bytecode constructor;
private LeoObject className;
private LeoObject[] paramNames;
private LeoObject superClass;
private ClassDefinition classDefinition;
/**
* @param runtime
* @param scope
* @param superClass
* @param className
* @param constructor
* @param paramNames
* @param params
*/
public LeoClass(Leola runtime
, Scope scope
, ClassDefinition classDefinition
, LeoObject superClass
, LeoObject[] params) {
super(LeoType.CLASS, scope, classDefinition.getBody().numOuters);
this.runtime = runtime;
this.classDefinition = classDefinition;
this.superClass = superClass;
this.className = classDefinition.getClassName();
this.constructor = classDefinition.getBody();
this.paramNames = classDefinition.getParameterNames();
this.outers = classDefinition.getOuters();
putObject("super", superClass);
putObject("this", this);
if ( paramNames != null ) {
for(int i = 0; i < paramNames.length; i++) {
if ( params == null || params.length <= i ) {
addProperty(paramNames[i], LeoNull.LEONULL);
}
else {
addProperty(paramNames[i], params[i]);
}
}
}
/**
* The constructor may be an empty body, if it is,
* no need to construct anything.
*
* A class is empty if define as such:
* class X();
* class X() {}
*
* The former actually produces a bytecode of LOAD_NULL, which
* we have to also check.
*/
boolean isEmpty = this.constructor.len < 1 ||
(this.constructor.len < 2 &&
Opcodes.OPCODE(this.constructor.instr[0]) == Opcodes.LOAD_NULL);
if(!isEmpty) {
this.runtime.execute(this, this.constructor);
}
}
/**
* @return the paramNames
*/
public LeoObject[] getParamNames() {
return paramNames;
}
/**
* @return the className
*/
public LeoObject getClassName() {
return className;
}
/**
* @return the constructor
*/
public Bytecode getConstructor() {
return constructor;
}
/**
* @return the superClass
*/
public LeoObject getSuperClass() {
return superClass;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isClass()
*/
@Override
public boolean isClass() {
return true;
}
@Override
public boolean isAccessible() {
return true;
}
private LeoObject override(LeoString name) {
LeoObject function = xgetProperty(name);
LeoObject result = function.xcall();
return result;
}
private LeoObject override(LeoString name, LeoObject arg1) {
LeoObject function = xgetProperty(name);
LeoObject result = function.xcall(arg1);
return result;
}
private LeoObject override(LeoString name, LeoObject arg1, LeoObject arg2) {
LeoObject function = xgetProperty(name);
LeoObject result = function.xcall(arg1, arg2);
return result;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#toString()
*/
@Override
public String toString() {
if ( hasProperty(toString) ) {
LeoObject result = override(toString);
return result.toString();
}
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
LeoMap map = this.getScope().getRawObjects();
sb.append("{ ");
final LeoString THIS = LeoString.valueOf("this");
final LeoString SUPER = LeoString.valueOf("super");
for(int i = 0; i < map.hashKeys.length; i++) {
if(map.hashKeys[i] != null && (!map.hashKeys[i].equals(THIS) && !map.hashKeys[i].equals(SUPER)) ) {
if ( !isFirst) {
sb.append(", ");
}
LeoObject key = map.hashKeys[i];
if(key.isString() ) {
sb.append("\"").append(key).append("\"");
}
else if(key.isNull()) {
sb.append("null");
}
else {
sb.append(key);
}
sb.append(" : ");
LeoObject val = map.get(map.hashKeys[i]);
if ( val != null && val != this) {
if(val.isString()) {
sb.append("\"").append(val).append("\"");
}
else if (val.isScopedObject()) {
sb.append("\"<...>\"");
}
else if(val.isNull()) {
sb.append("null");
}
else {
sb.append(val);
}
}
else {
sb.append("\"<...>\"");
}
isFirst = false;
}
}
sb.append(" }");
return sb.toString();
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if ( obj instanceof LeoObject ) {
return this.$eq((LeoObject)obj);
}
return false;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isOfType(java.lang.String)
*/
@Override
public boolean isOfType(String rawType) {
boolean isType = false;
/* If this is a fully qualified name, go ahead
* and check the class definitions are the same,
* otherwise we can simply check the class names
*/
if(rawType.contains(":")) {
ClassDefinition def = this.getScope().lookupClassDefinition(LeoObject.valueOf(rawType));
if(def != null) {
isType = this.classDefinition == def;
}
}
else {
isType = this.className.toString().equals(rawType);
}
/* Check the parent hierarchy if there is
* one.
*/
if(!isType && this.superClass != null) {
isType = this.superClass.isOfType(rawType);
}
return isType;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#eq(leola.vm.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
if ( this == other ) {
return true;
}
if ( hasProperty(EQ) ) {
LeoObject result = override(EQ, other);
return LeoObject.isTrue(result);
}
return super.$eq(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#neq(leola.vm.types.LeoObject)
*/
@Override
public boolean $neq(LeoObject other) {
if ( hasProperty(NEQ) ) {
LeoObject result = override(NEQ, other);
return LeoObject.isTrue(result);
}
return super.$neq(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#lte(leola.vm.types.LeoObject)
*/
@Override
public boolean $lte(LeoObject other) {
if ( hasProperty(LTE) ) {
LeoObject result = override(LTE, other);
return LeoObject.isTrue(result);
}
return super.$lte(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#lt(leola.vm.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
if ( hasProperty(LT) ) {
LeoObject result = override(LT, other);
return LeoObject.isTrue(result);
}
return false;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#gte(leola.vm.types.LeoObject)
*/
@Override
public boolean $gte(LeoObject other) {
if ( hasProperty(GTE) ) {
LeoObject result = override(GTE, other);
return LeoObject.isTrue(result);
}
return super.$gte(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#gt(leola.vm.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
if ( hasProperty(GT) ) {
LeoObject result = override(GT, other);
return LeoObject.isTrue(result);
}
return false;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#add(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $add(LeoObject other) {
if ( hasProperty(ADD) ) {
LeoObject result = override(ADD, other);
return result;
}
else {
if (other.isString()) {
return LeoString.valueOf(toString() + other.toString());
}
}
return super.$add(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#sub(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $sub(LeoObject other) {
if ( hasProperty(SUB) ) {
LeoObject result = override(SUB, other);
return result;
}
return super.$sub(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#mul(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $mul(LeoObject other) {
if ( hasProperty(MUL) ) {
LeoObject result = override(MUL, other);
return result;
}
return super.$mul(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#div(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $div(LeoObject other) {
if ( hasProperty(DIV) ) {
LeoObject result = override(DIV, other);
return result;
}
return super.$div(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#mod(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $mod(LeoObject other) {
if ( hasProperty(MOD) ) {
LeoObject result = override(MOD, other);
return result;
}
return super.$mod(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#neg()
*/
@Override
public LeoObject $neg() {
if ( hasProperty(NEG) ) {
LeoObject result = override(NEG);
return result;
}
return super.$neg();
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#bnot()
*/
@Override
public LeoObject $bnot() {
if ( hasProperty(BNOT) ) {
LeoObject result = override(BNOT);
return result;
}
return super.$bnot();
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#bsl(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $bsl(LeoObject other) {
if ( hasProperty(BSL) ) {
LeoObject result = override(BSL, other);
return result;
}
return super.$bsl(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#bsr(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $bsr(LeoObject other) {
if ( hasProperty(BSR) ) {
LeoObject result = override(BSR, other);
return result;
}
return super.$bsr(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#land(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $band(LeoObject other) {
if ( hasProperty(BAND) ) {
LeoObject result = override(BAND, other);
return result;
}
return super.$band(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#lor(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $bor(LeoObject other) {
if ( hasProperty(BOR) ) {
LeoObject result = override(BOR, other);
return result;
}
return super.$bor(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#xor(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $xor(LeoObject other) {
if ( hasProperty(XOR) ) {
LeoObject result = override(XOR, other);
return result;
}
return super.$xor(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $index(LeoObject key) {
if ( hasProperty(INDEX) ) {
LeoObject result = override(INDEX, key);
return result;
}
return getObject(key);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public void $sindex(LeoObject key, LeoObject value) {
if ( hasProperty(SINDEX) ) {
override(SINDEX, key, value);
return;
}
setObject(key, value);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return null;
}
@Override
public void write(DataOutput out) throws IOException {
out.write(this.getType().ordinal());
this.className.write(out);
this.constructor.write(out);
}
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the {@link LeoObject}
* @throws IOException
*/
public static LeoClass read(DataInput in) throws IOException {
return null; /* TODO */
}
}
<|start_filename|>src/leola/lang/sql/ParameterMapIndex.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.sql;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Parameter listing, maps the variable names to the actual JDBC parameter index.
*
* @author Tony
*
*/
public class ParameterMapIndex {
/**
* Parameter map
*/
private Map<String, ParameterLocation> params;
/**
* Index
*/
private int index;
/**
*/
public ParameterMapIndex() {
this.params = new HashMap<String, ParameterLocation>();
this.index = 1;
}
/**
* Adds a parameter, adding to the current index.
*
* @param parameterKey
* @param index
*/
public void addParameter(String parameterKey, int charPosition) {
/* Store the parameter information */
if ( ! params.containsKey(parameterKey) ) {
params.put(parameterKey, new ParameterLocation(parameterKey));
}
ParameterLocation location = this.params.get(parameterKey);
location.addParameterIndex(this.index++);
location.addSqlCharPosition(charPosition);
}
/**
* Adds a parameter and a list of its indexes
* @param paramKey
* @param indexes
*/
public void addParameters(String parameterKey, ParameterLocation location) {
/* Store the parameter information */
if ( ! params.containsKey(parameterKey) ) {
params.put(parameterKey, new ParameterLocation(parameterKey));
}
params.get(parameterKey).addParameterLocation(location);
}
/**
* @param paramKey
* @return the parameter indexes associated with the parameter Key
*/
public List<Integer> getParameterIndexes(String paramKey) {
if ( ! params.containsKey(paramKey)) {
throw new IllegalArgumentException("No indexes found for: " + paramKey);
}
return params.get(paramKey).getParameterIndexes();
}
/**
* @param paramKey
* @return the sql character position of the parameters associated with the parameter key
*/
public List<Integer> getSqlCharPositions(String paramKey) {
if ( ! params.containsKey(paramKey)) {
throw new IllegalArgumentException("No indexes found for: " + paramKey);
}
return params.get(paramKey).getSqlCharPositions();
}
/**
* Get the {@link ParameterLocation}.
*
* @param paramKey
* @return the {@link ParameterLocation}
*/
public ParameterLocation getParameterLocation(String paramKey) {
if ( ! params.containsKey(paramKey)) {
throw new IllegalArgumentException("No indexes found for: " + paramKey);
}
return params.get(paramKey);
}
/**
* The current parameter index
* @return
*/
public int getIndex() {
return this.index;
}
/**
* Set the index
* @param index
*/
public void setIndex(int index) {
this.index = index;
}
}
<|start_filename|>src/leola/vm/compiler/BytecodeGeneratorVisitor.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.compiler;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import leola.ast.ASTNode;
import leola.ast.ASTNodeVisitor;
import leola.ast.ArrayDeclExpr;
import leola.ast.AssignmentExpr;
import leola.ast.BinaryExpr;
import leola.ast.BlockStmt;
import leola.ast.BooleanExpr;
import leola.ast.BreakStmt;
import leola.ast.CaseExpr;
import leola.ast.CatchStmt;
import leola.ast.ClassDeclStmt;
import leola.ast.ContinueStmt;
import leola.ast.DecoratorExpr;
import leola.ast.ElvisGetExpr;
import leola.ast.EmptyStmt;
import leola.ast.Expr;
import leola.ast.FuncDefExpr;
import leola.ast.FuncInvocationExpr;
import leola.ast.GenDefExpr;
import leola.ast.GetExpr;
import leola.ast.IfStmt;
import leola.ast.IntegerExpr;
import leola.ast.IsExpr;
import leola.ast.LongExpr;
import leola.ast.MapDeclExpr;
import leola.ast.NamedParameterExpr;
import leola.ast.NamespaceGetExpr;
import leola.ast.NamespaceSetExpr;
import leola.ast.NamespaceStmt;
import leola.ast.NewExpr;
import leola.ast.NullExpr;
import leola.ast.ParameterList;
import leola.ast.ProgramStmt;
import leola.ast.RealExpr;
import leola.ast.ReturnStmt;
import leola.ast.SetExpr;
import leola.ast.Stmt;
import leola.ast.StringExpr;
import leola.ast.SubscriptGetExpr;
import leola.ast.SubscriptSetExpr;
import leola.ast.SwitchStmt;
import leola.ast.ThrowStmt;
import leola.ast.TryStmt;
import leola.ast.UnaryExpr;
import leola.ast.VarDeclStmt;
import leola.ast.VarExpr;
import leola.ast.WhileStmt;
import leola.ast.YieldStmt;
import leola.frontend.tokens.Token;
import leola.frontend.tokens.TokenType;
import leola.vm.EvalException;
import leola.vm.Leola;
import leola.vm.compiler.EmitterScope.ScopeType;
import leola.vm.types.LeoString;
import leola.vm.util.Pair;
/**
* Generates {@link Bytecode} based off of an Abstract Syntax Tree.
*
*
* @author Tony
*
*/
public class BytecodeGeneratorVisitor implements ASTNodeVisitor {
/**
* The assembler
*/
private BytecodeEmitter asm;
private Stack<String> breakLabelStack;
private Stack<String> continueLabelStack;
private Stack<Tailcall> tailCallStack;
/**
* Marks a tail call recursive method.
*/
static class Tailcall {
String name;
FuncInvocationExpr tailcallExpr;
Tailcall(String name, FuncInvocationExpr tailcallExpr) {
this.name = name;
this.tailcallExpr = tailcallExpr;
}
}
/**
* @param runtime
* @param symbols
*/
public BytecodeGeneratorVisitor(Leola runtime, EmitterScopes symbols) {
this.asm = new BytecodeEmitter(symbols);
this.asm.setDebug(runtime.getArgs().isDebugMode());
this.breakLabelStack = new Stack<String>();
this.continueLabelStack = new Stack<String>();
this.tailCallStack = new Stack<BytecodeGeneratorVisitor.Tailcall>();
}
/**
* @return the asm
*/
public BytecodeEmitter getAsm() {
return asm;
}
@Override
public void visit(NamespaceSetExpr s) throws EvalException {
asm.line(s.getLineNumber());
if(s.getOperator().getType() != TokenType.EQUALS) {
asm.getnamespace(s.getNamespace().getVarName());
asm.getk(s.getIdentifier());
s.getValue().visit(this);
visitAssignmentOperator(s.getOperator());
}
else {
s.getValue().visit(this);
}
asm.getnamespace(s.getNamespace().getVarName());
asm.setk(s.getIdentifier());
}
@Override
public void visit(SetExpr s) throws EvalException {
asm.line(s.getLineNumber());
if(s.getOperator().getType() != TokenType.EQUALS) {
s.getObject().visit(this);
asm.getk(s.getIdentifier());
s.getValue().visit(this);
visitAssignmentOperator(s.getOperator());
}
else {
s.getValue().visit(this);
}
s.getObject().visit(this);
asm.setk(s.getIdentifier());
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.SubscriptGetExpr)
*/
@Override
public void visit(SubscriptGetExpr s) throws EvalException {
asm.line(s.getLineNumber());
s.getObject().visit(this);
s.getElementIndex().visit(this);
asm.idx();
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.SubscriptSetExpr)
*/
@Override
public void visit(SubscriptSetExpr s) throws EvalException {
asm.line(s.getLineNumber());
if(s.getOperator().getType() != TokenType.EQUALS) {
s.getObject().visit(this);
s.getElementIndex().visit(this);
asm.idx();
s.getValue().visit(this);
visitAssignmentOperator(s.getOperator());
}
else {
s.getValue().visit(this);
}
s.getObject().visit(this);
s.getElementIndex().visit(this);
asm.sidx();
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ArrayDeclExpr)
*/
@Override
public void visit(ArrayDeclExpr s) throws EvalException {
asm.line(s.getLineNumber());
List<Expr> exprs = s.getElements();
for(Expr expr : exprs) {
expr.visit(this);
}
asm.newarray(exprs.size());
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.MapDeclExpr)
*/
@Override
public void visit(MapDeclExpr s) throws EvalException {
asm.line(s.getLineNumber());
List<Pair<Expr, Expr>> elements = s.getElements();
for(int i = 0; i < elements.size(); i++) {
Pair<Expr, Expr> element = elements.get(i);
Expr key = element.getFirst();
key.appendFlag(ASTNode.MEMBER_PROPERTY); /* Let VarExpr be converted to strings */
key.visit(this);
Expr value = element.getSecond();
value.visit(this);
}
int numElements = elements.size();
asm.newmap(numElements);
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.AssignmentExpr)
*/
@Override
public void visit(AssignmentExpr s) throws EvalException {
asm.line(s.getLineNumber());
VarExpr var = s.getVar();
String varName = var.getVarName();
if(s.getOperator().getType() == TokenType.EQUALS) {
s.getValue().visit(this);
asm.dup();
asm.store(varName);
}
else {
s.getVar().visit(this);
s.getValue().visit(this);
visitAssignmentOperator(s.getOperator());
asm.dup();
asm.store(varName);
}
}
private void visitAssignmentOperator(Token operator) {
switch(operator.getType()) {
case EQUALS: break;
case PLUS_EQ: asm.add(); break;
case MINUS_EQ: asm.sub(); break;
case STAR_EQ: asm.mul(); break;
case SLASH_EQ: asm.div(); break;
case MOD_EQ: asm.mod(); break;
case BSL_EQ: asm.bsl(); break;
case BSR_EQ: asm.bsr(); break;
case BOR_EQ: asm.lor(); break;
case BAND_EQ: asm.land();break;
case BXOR_EQ: asm.xor(); break;
default:
throw new EvalException("Invalid operator: '" + operator.getText() + "'");
}
}
/**
* Visits a Binary Expression
*
* @param op
* @throws EvalException
*/
private void visitBinaryExpression(TokenType op) throws EvalException {
switch(op) {
case PLUS: asm.add(); break;
case MINUS: asm.sub(); break;
case STAR: asm.mul(); break;
case SLASH: asm.div(); break;
case MOD: asm.mod(); break;
// comparisons
case LOGICAL_AND: asm.and(); break;
case LOGICAL_OR: asm.or(); break;
case REF_EQUALS: asm.req(); break;
case REF_NOT_EQUALS: asm.rneq(); break;
case D_EQUALS: asm.eq(); break;
case NOT_EQUALS: asm.neq(); break;
case GREATER_THAN: asm.gt(); break;
case GREATER_EQUALS: asm.gte(); break;
case LESS_THAN: asm.lt(); break;
case LESS_EQUALS: asm.lte(); break;
// bit ops
case BITWISE_AND: asm.land(); break;
case BITWISE_OR: asm.lor(); break;
case BIT_SHIFT_LEFT: asm.bsl(); break;
case BIT_SHIFT_RIGHT: asm.bsr(); break;
case BITWISE_XOR: asm.xor(); break;
default:
throw new EvalException("Unknown BinaryOperator: " + op);
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.BinaryExpr)
*/
@Override
public void visit(BinaryExpr s) throws EvalException {
asm.line(s.getLineNumber());
Token operator = s.getOp();
switch(operator.getType()) {
case LOGICAL_AND: {
s.getLeft().visit(this);
String escape = asm.ifeq();
s.getRight().visit(this);
String endif = asm.jmp();
asm.label(escape);
asm.loadfalse();
asm.label(endif);
break;
}
case LOGICAL_OR: {
s.getLeft().visit(this);
String secondConditional = asm.ifeq();
String skip = asm.jmp();
asm.label(secondConditional);
s.getRight().visit(this);
String end = asm.jmp();
asm.label(skip);
asm.loadtrue();
asm.label(end);
break;
}
default: {
s.getLeft().visit(this);
s.getRight().visit(this);
visitBinaryExpression(operator.getType());
}
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.BooleanExpr)
*/
@Override
public void visit(BooleanExpr s) throws EvalException {
asm.line(s.getLineNumber());
if(s.getValue()) {
asm.loadtrue();
}
else {
asm.loadfalse();
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.BreakStmt)
*/
@Override
public void visit(BreakStmt s) throws EvalException {
asm.line(s.getLineNumber());
if(!this.breakLabelStack.isEmpty()) {
String label = this.breakLabelStack.peek();
asm.brk(label);
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ClassDeclStmt)
*/
@Override
public void visit(ClassDeclStmt s) throws EvalException {
asm.line(s.getLineNumber());
String className = s.getClassName();
// this class name
asm.addAndloadconst(className);
// parent class name
String parentClassNAme = s.getParentClassName();
if(parentClassNAme != null) {
asm.addAndloadconst(parentClassNAme);
}
else {
asm.loadnull();
}
// TODO - Determine how this will take advantage of varargs
ParameterList params = s.getClassParameters();
for(String ref:params.getParameters()) {
asm.addAndloadconst(ref);
}
asm.addAndloadconst(params.size());
/*
* NOTE: this places Constants in the parameters and
* if there is a reference it will put the
* reference name as a string so it can later look the
* reference up via the passed constructor value
*
* @see ClassDefinitions
*/
List<Expr> superArguments = s.getParentClassArguments();
if(superArguments != null) {
for(Expr e: superArguments) {
/* may pass values from sibling class to parent class */
if(e instanceof VarExpr) {
e.appendFlag(ASTNode.MEMBER_PROPERTY);
}
e.visit(this);
}
}
asm.addAndloadconst(superArguments!=null?superArguments.size():0);
asm.addAndloadconst(asm.getBytecodeIndex());
asm.classdef(params.size(), params.isVarargs());
{
Stmt body = s.getClassBodyStmt();
body.visit(this);
}
asm.end();
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.BlockStmt)
*/
@Override
public void visit(BlockStmt s) throws EvalException {
asm.line(s.getLineNumber());
/* if the parent has already created a new scope, we don't
* want to force a new lexical scope
*/
ASTNode parent = s.getParentNode();
boolean newLexicalScope = ((parent instanceof ClassDeclStmt) ||
(parent instanceof NamespaceStmt) ||
(parent instanceof GenDefExpr) ||
(parent instanceof FuncDefExpr) );
if(!newLexicalScope) {
asm.markLexicalScope();
}
List<Stmt> nodes = s.getStatements();
int numNodes = nodes.size();
for(int i = 0; i < numNodes; i++) {
ASTNode n = nodes.get(i);
n.visit(this);
if(n instanceof Expr) {
asm.oppop();
}
}
if(!newLexicalScope) {
asm.unmarkLexicalScope();
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ContinueStmt)
*/
@Override
public void visit(ContinueStmt s) throws EvalException {
asm.line(s.getLineNumber());
String label = this.continueLabelStack.peek();
asm.cont(label);
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.DecoratorExpr)
*/
@Override
public void visit(DecoratorExpr s) throws EvalException {
asm.line(s.getLineNumber());
List<Expr> existingParams = s.getArguments();
List<Expr> arguments = new ArrayList<>();
arguments.add(s.getDecoratedExpr());
arguments.addAll(existingParams);
FuncInvocationExpr functionInvokeExpr = new FuncInvocationExpr(s.getDecoratorName(), arguments);
functionInvokeExpr.setLineNumber(s.getLineNumber());
visit(functionInvokeExpr);
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.NamespaceStmt)
*/
@Override
public void visit(NamespaceStmt s) throws EvalException {
asm.line(s.getLineNumber());
String name = s.getName();
asm.addAndloadconst(name);
asm.namespacedef();
{
s.getStmt().visit(this);
}
asm.end();
//asm.addAndstorelocal(name);
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.NumberExpr)
*/
@Override
public void visit(RealExpr s) throws EvalException {
asm.line(s.getLineNumber());
asm.addAndloadconst(s.getValue());
}
@Override
public void visit(IntegerExpr s) throws EvalException {
asm.line(s.getLineNumber());
asm.addAndloadconst(s.getValue());
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.LongExpr)
*/
@Override
public void visit(LongExpr s) throws EvalException {
asm.line(s.getLineNumber());
asm.addAndloadconst(s.getValue());
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ProgramStmt)
*/
@Override
public void visit(ProgramStmt s) throws EvalException {
asm.start(ScopeType.GLOBAL_SCOPE);
{
for(Stmt n : s.getStatements()) {
n.visit(this);
if(n instanceof Expr) {
asm.pop();
}
}
}
asm.end();
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.IsExpr)
*/
@Override
public void visit(IsExpr s) throws EvalException {
asm.line(s.getLineNumber());
asm.addAndloadconst(s.getClassName());
s.getObject().visit(this);
asm.isa();
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.EmptyStmt)
*/
@Override
public void visit(EmptyStmt s) throws EvalException {
asm.line(s.getLineNumber());
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.GenDefExpr)
*/
@Override
public void visit(GenDefExpr s) throws EvalException {
asm.line(s.getLineNumber());
ParameterList parameters = s.getParameters();
asm.gendef(parameters.size(), parameters.isVarargs());
{
for(String name : parameters.getParameters()) {
asm.addLocal(name);
}
s.getBody().visit(this);
}
asm.end();
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.NamedParameterStmt)
*/
@Override
public void visit(NamedParameterExpr s) throws EvalException {
int index = asm.getConstants().store(s.getParameterName());
asm.loadname(index);
s.getValueExpr().visit(this);
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.FuncDefExpr)
*/
@Override
public void visit(FuncDefExpr s) throws EvalException {
asm.line(s.getLineNumber());
ParameterList parameters = s.getParameters();
asm.funcdef(parameters.size(), parameters.isVarargs());
{
for(String name : parameters.getParameters()) {
asm.addLocal(name);
}
s.getBody().visit(this);
}
asm.end();
}
/**
* Checks to see if there are Named Parameters or any
* Expandable variable arguments
*
* @param arguments
* @return the number of expanded argument index (if any, otherwise 0);
*/
private int checkArguments(List<Expr> arguments) {
int expandedArgsIndex = 0;
if(arguments != null && !arguments.isEmpty()) {
boolean hasNamedParameters = false;
/* check to see if there are any NamedParameters,
* if so, we need to add some additional instructions
* that effect performance
*/
int index = 0;
for(Expr param : arguments) {
// Check if there are named parameters
if(param instanceof NamedParameterExpr) {
hasNamedParameters = true;
NamedParameterExpr nExpr = (NamedParameterExpr)param;
param = nExpr.getValueExpr();
}
// check if the parameters need an Array Expansion (*array)
if(param instanceof UnaryExpr) {
UnaryExpr unaryExpr = (UnaryExpr)param;
if(unaryExpr.getOp().getType() == TokenType.STAR) {
expandedArgsIndex=index+1;
}
}
index++;
}
for(Expr param : arguments) {
param.visit(this);
/* mark the end of the parameter,
* so that we can properly index
* the named parameters
*/
if(hasNamedParameters) {
asm.paramend();
}
}
}
return expandedArgsIndex;
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.FuncInvocationExpr)
*/
@Override
public void visit(FuncInvocationExpr s) throws EvalException {
asm.line(s.getLineNumber());
s.getCallee().visit(this);
List<Expr> arguments = s.getArguments();
int nargs = arguments.size();
int expandedArgsIndex = checkArguments(arguments);
boolean isTailcall = false;
if(!this.tailCallStack.isEmpty()) {
Tailcall tc = this.tailCallStack.peek();
if(tc.tailcallExpr == s) {
asm.tailcall(nargs, expandedArgsIndex);
isTailcall = true;
}
}
if(!isTailcall) {
asm.invoke(nargs, expandedArgsIndex);
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.IfStmt)
*/
@Override
public void visit(IfStmt s) throws EvalException {
asm.line(s.getLineNumber());
Expr cond = s.getCondition();
cond.visit(this);
String elseLabel = asm.ifeq();
Stmt stmt = s.getStmt();
stmt.visit(this);
String endif = asm.jmp();
asm.label(elseLabel);
Stmt elseStmt = s.getElseStmt();
if(elseStmt != null) {
elseStmt.visit(this);
}
asm.label(endif);
}
@Override
public void visit(NamespaceGetExpr s) throws EvalException {
asm.line(s.getLineNumber());
asm.getnamespace(s.getNamespace().getVarName());
asm.getk(s.getIdentifier());
}
@Override
public void visit(ElvisGetExpr s) throws EvalException {
asm.line(s.getLineNumber());
s.getObject().visit(this);
asm.dup();
asm.loadnull();
asm.neq();
String end = asm.ifeq();
asm.egetk(s.getIdentifier());
asm.label(end);
}
@Override
public void visit(GetExpr s) throws EvalException {
asm.line(s.getLineNumber());
s.getObject().visit(this);
asm.getk(s.getIdentifier());
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.NewExpr)
*/
@Override
public void visit(NewExpr s) throws EvalException {
asm.line(s.getLineNumber());
List<Expr> arguments = s.getArguments();
int nargs = arguments.size();
int expandedArgsIndex = checkArguments(arguments);
String className = s.getClassName();
asm.addAndloadconst(className);
asm.newobj(nargs, expandedArgsIndex);
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.NullExpr)
*/
@Override
public void visit(NullExpr s) throws EvalException {
asm.line(s.getLineNumber());
asm.loadnull();
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ReturnStmt)
*/
@Override
public void visit(YieldStmt s) throws EvalException {
asm.line(s.getLineNumber());
Expr expr = s.getExpr();
if ( expr != null ) {
expr.visit(this);
}
else {
asm.loadnull();
}
asm.yield();
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ReturnStmt)
*/
@Override
public void visit(ReturnStmt s) throws EvalException {
asm.line(s.getLineNumber());
Expr expr = s.getExpr();
if ( expr != null ) {
expr.visit(this);
}
else {
asm.loadnull();
}
asm.ret();
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.StringExpr)
*/
@Override
public void visit(StringExpr s) throws EvalException {
asm.line(s.getLineNumber());
asm.addAndloadconst(s.getValue());
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.SwitchStmt)
*/
@Override
public void visit(SwitchStmt s) throws EvalException {
asm.line(s.getLineNumber());
Expr condExpr = s.getCondition();
condExpr.visit(this);
String endCase = asm.nextLabelName();
String nextWhenLabel = null;
List<Pair<Expr, Stmt>> whenStmts = s.getWhenStmts();
boolean isSingle = whenStmts.size() < 2;
for(Pair<Expr, Stmt> whenExpr : whenStmts) {
if(!isSingle) {
asm.dup();
}
Expr cond = whenExpr.getFirst();
cond.visit(this);
asm.eq();
nextWhenLabel = asm.ifeq();
Stmt stmt = whenExpr.getSecond();
if(!isSingle) {
asm.pop();
}
stmt.visit(this);
if( stmt instanceof Expr) {
asm.oppop(); /* remove any pushed items */
}
asm.jmp(endCase);
asm.label(nextWhenLabel);
}
if(!isSingle) {
asm.pop();
}
Stmt elseStmt = s.getElseStmt();
if ( elseStmt != null ) {
elseStmt.visit(this);
if( elseStmt instanceof Expr) {
asm.oppop(); /* remove any pushed items */
}
}
asm.label(endCase);
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.CaseExpr)
*/
@Override
public void visit(CaseExpr s) throws EvalException {
asm.line(s.getLineNumber());
Expr condExpr = s.getCondition();
condExpr.visit(this);
String endCase = asm.nextLabelName();
String nextWhenLabel = null;
List<Pair<Expr, Expr>> whenExprs = s.getWhenExprs();
boolean isSingle = whenExprs.size() < 2;
for(Pair<Expr, Expr> whenExpr : whenExprs) {
if(!isSingle) {
asm.dup();
}
Expr cond = whenExpr.getFirst();
cond.visit(this);
asm.eq();
nextWhenLabel = asm.ifeq();
Expr stmt = whenExpr.getSecond();
if(!isSingle) {
asm.pop();
}
stmt.visit(this);
asm.jmp(endCase);
asm.label(nextWhenLabel);
}
if(!isSingle) {
asm.pop();
}
Expr elseExpr = s.getElseExpr();
if ( elseExpr != null ) {
elseExpr.visit(this);
}
else {
asm.loadnull();
}
asm.label(endCase);
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ThrowStmt)
*/
@Override
public void visit(ThrowStmt s) throws EvalException {
asm.line(s.getLineNumber());
s.getExpr().visit(this);
asm.throw_();
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.TryStmt)
*/
@Override
public void visit(TryStmt s) throws EvalException {
asm.line(s.getLineNumber());
boolean hasCatch = s.getCatchStmt() != null;
boolean hasFinally = s.getFinallyStmt() != null;
if(hasFinally) {
asm.initfinally();
}
if(hasCatch) {
asm.initcatch();
}
s.getStmt().visit(this);
/* if the VM has made it this
* far, go ahead and pop off
* the Catch block (if there is
* one)
*/
if(hasCatch) {
asm.endblock();
}
String finallyLabel = null;
String endLabel = null;
/*
* If we have a finally block,
* jump to that, otherwise jump
* over the Catch clause
*/
if(hasFinally) {
finallyLabel = asm.jmp();
}
else {
endLabel = asm.jmp();
}
if(hasCatch) {
asm.taginitcatch();
asm.endcatch();
s.getCatchStmt().visit(this);
}
if(hasFinally) {
asm.label(finallyLabel);
asm.taginitfinally();
s.getFinallyStmt().visit(this);
asm.endfinally();
}
else {
/*
* There is no finally block and the
* VM made it without an Error being
* thrown, so this lets us skip the
* catch block
*/
asm.label(endLabel);
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.OnStmt)
*/
@Override
public void visit(CatchStmt s) throws EvalException {
asm.line(s.getLineNumber());
String endOn = asm.nextLabelName();
asm.markLexicalScope();
asm.addAndstorelocal(s.getIdentifier());
Stmt stmt = s.getBody();
stmt.visit(this);
if( stmt instanceof Expr) {
asm.oppop(); /* remove any pushed items */
}
asm.unmarkLexicalScope();
asm.jmp(endOn);
asm.label(endOn);
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.UnaryExpr)
*/
@Override
public void visit(UnaryExpr s) throws EvalException {
asm.line(s.getLineNumber());
s.getExpr().visit(this);
TokenType operator = s.getOp().getType();
switch(operator) {
case BITWISE_NOT: asm.bnot(); break;
case MINUS: asm.neg(); break;
case NOT: asm.not(); break;
case STAR: break;
default:
throw new EvalException("Unknown UnaryOperator: " + operator);
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.VarDeclStmt)
*/
@Override
public void visit(VarDeclStmt s) throws EvalException {
asm.line(s.getLineNumber());
String ref = s.getVarName();
Expr expr = s.getValue();
/*
* In case of recursion, we want to tell the locals
* about this
*/
int index = -1;
if(asm.usesLocals()) {
index = asm.addLocal(ref);
}
boolean isTailcall = false;
if ( expr instanceof FuncDefExpr ) {
TailcallOptimizerVisitor tc = new TailcallOptimizerVisitor(ref);
Stmt body = ((FuncDefExpr)expr).getBody();
body.visit(tc);
isTailcall = tc.isTailcall();
if ( isTailcall ) {
this.tailCallStack.add(new Tailcall(ref, tc.getTailCallExpr()));
}
}
expr.visit(this);
if ( isTailcall ) {
this.tailCallStack.pop();
}
// asm.dup(); Seems to be causing a stack leak, I'm not sure why this
// was here, Variable declaration isn't an 'Expression'
if(asm.usesLocals()) {
asm.storelocal(index);
}
else {
asm.setglobal(ref);
}
}
/**
* Determines if the supplied "ref" is a constant, local, global or an
* "outstanding" global.
*
* @param s
* @param ref
* @throws EvalException
*/
private void loadmember(ASTNode s, String ref, boolean checkConstantFirst) throws EvalException {
loadmember(s, ref, checkConstantFirst, false);
}
/**
* Determines if the supplied "ref" is a constant, local, global or an
* "outstanding" global.
*
* @param s
* @param ref
* @param checkConstantFirst
* @param loadconst
* @throws EvalException
*/
private void loadmember(ASTNode s, String ref, boolean checkConstantFirst, boolean loadconst) throws EvalException {
if ( checkConstantFirst && s.hasFlag(ASTNode.MEMBER_PROPERTY) ) {
asm.addAndloadconst(ref);
}
else if ( ! asm.load(ref) ) {
/* check and see if this is a map lookup */
LeoString member = LeoString.valueOf(ref);
Constants constants = asm.getConstants();
int index = constants.get(member);
if ( index < 0) {
/* inline string definition */
if ( s.hasFlag(ASTNode.MEMBER_PROPERTY) || loadconst ) {
index = constants.store(member);
asm.loadconst(index);
}
else {
/* A variable that hasn't been defined yet */
asm.getglobal(ref);
}
}
else {
if(loadconst) {
asm.loadconst(index);
}
else {
/* A variable that hasn't been defined yet */
asm.getglobal(ref);
}
}
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.VarExpr)
*/
@Override
public void visit(VarExpr s) throws EvalException {
asm.line(s.getLineNumber());
loadmember(s, s.getVarName(), true);
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.WhileStmt)
*/
@Override
public void visit(WhileStmt s) throws EvalException {
asm.line(s.getLineNumber());
String beginWhile = asm.label();
this.continueLabelStack.push(beginWhile);
Expr cond = s.getCondition();
cond.visit(this);
String endWhile = asm.ifeq();
this.breakLabelStack.push(endWhile);
Stmt stmt = s.getStmt();
stmt.visit(this);
asm.jmp(beginWhile);
asm.label(endWhile);
this.breakLabelStack.pop();
this.continueLabelStack.pop();
}
}
<|start_filename|>src/leola/frontend/tokens/Token.java<|end_filename|>
package leola.frontend.tokens;
import leola.frontend.Source;
/**
* A Token represents a language token such as a symbol or identifier
*
* @author Tony
*
*/
public class Token {
protected TokenType type; // language-specific token type
protected String text; // token text
protected Object value; // token value
protected Source source; // source
protected int lineNum; // line number of the token's source line
protected int position; // position of the first token character
/**
* Constructor.
*
* @param source
* the source from where to fetch the token's characters.
*/
public Token(Source source) {
this.source = source;
this.lineNum = source.getLineNum();
this.position = source.getPosition();
extract();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.text;
}
/**
* Getter
*
* @return the token type
*/
public TokenType getType() {
return this.type;
}
/**
* Getter.
*
* @return the token text.
*/
public String getText() {
return text;
}
/**
* Getter.
*
* @return the token value.
*/
public Object getValue() {
return value;
}
/**
* Getter.
*
* @return the source line number.
*/
public int getLineNumber() {
return lineNum;
}
/**
* Getter.
*
* @return the position.
*/
public int getPosition() {
return position;
}
/**
* Default method to extract only one-character tokens from the source.
* Subclasses can override this method to construct language-specific
* tokens. After extracting the token, the current source line position will
* be one beyond the last token character.
*
*/
protected void extract() {
text = Character.toString(currentChar());
value = null;
nextChar(); // consume current character
}
/**
* Call the source's currentChar() method.
*
* @return the current character from the source.
*/
protected char currentChar() {
return source.currentChar();
}
/**
* Call the source's nextChar() method.
*
* @return the next character from the source after moving forward.
*/
protected char nextChar() {
return source.nextChar();
}
/**
* Call the source's peekChar() method.
*
* @return the next character from the source without moving forward.
*/
protected char peekChar() {
return source.peekChar();
}
/**
* Peek ahead <code>pos</code> many spaces.
*
* @param pos
* @return the char at the current position + pos, or EOL/EOF if it reached the end of the line or file.
*/
protected char peekAhead(int pos) {
return source.peekAhead(pos);
}
}
<|start_filename|>src/leola/lang/io/Buffer.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.io;
import java.nio.ByteBuffer;
/**
* Wrapper around {@link ByteBuffer}.
*
* @author Tony
*
*/
public class Buffer {
/**
* Buffer
*/
private ByteBuffer buffer;
/**
* @param size
*/
public Buffer(int size) {
this.buffer = ByteBuffer.allocate(size);
}
public void putByte(Number n) {
this.buffer.put( n.byteValue() );
}
public byte readByte() {
return this.buffer.get();
}
public void putShort(Number n) {
this.buffer.putShort( n.shortValue() );
}
public short readShort() {
return this.buffer.getShort();
}
/**
* @return reads the byte as a string
*/
public String readString() {
return (char)this.buffer.get() + "";
}
public char readChar() {
return (char)this.buffer.get();
}
public void putBuffer(Buffer buffer) {
this.buffer.put(buffer.buffer);
}
public void putString(String str) {
this.buffer.put(str.getBytes());
}
public int position() {
return this.buffer.position();
}
public void setPosition(int pos) {
this.buffer.position(pos);
}
public int capacity() {
return this.buffer.capacity();
}
public void clear() {
this.buffer.clear();
}
public void rewind() {
this.buffer.rewind();
}
public int remaining() {
return this.buffer.remaining();
}
public byte[] getArray() {
return this.buffer.array();
}
public int limit() {
return this.buffer.limit();
}
public void setLimit(int limit) {
this.buffer.limit(limit);
}
public void mark() {
this.buffer.limit(this.buffer.position());
}
}
<|start_filename|>src/leola/ast/NamespaceGetExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* @author Tony
*
*/
public class NamespaceGetExpr extends Expr {
private VarExpr namespace;
private String identifier;
public NamespaceGetExpr(VarExpr namespace, String identifier) {
this.namespace = namespace;
this.identifier = identifier;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public VarExpr getNamespace() {
return namespace;
}
public String getIdentifier() {
return identifier;
}
}
<|start_filename|>src/leola/frontend/tokens/EofToken.java<|end_filename|>
package leola.frontend.tokens;
import leola.frontend.Source;
/**
* End of File token
*
* @author Tony
*
*/
public class EofToken extends Token {
public EofToken(Source source) {
super(source);
this.type = TokenType.END_OF_FILE;
}
}
<|start_filename|>src/leola/ast/GenDefExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* @author Tony
*
*/
public class GenDefExpr extends FuncDefExpr {
/**
* @param body
* @param parameters
*/
public GenDefExpr(Stmt body, ParameterList parameters) {
super(body, parameters);
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
}
<|start_filename|>src/leola/vm/types/LeoInteger.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import leola.vm.util.ClassUtil;
/**
* Represents a double float precision number
*
* @author Tony
*
*/
public class LeoInteger extends LeoObject {
private static final int CACHE_SIZE = 512;
private static final int NCACHE_SIZE = CACHE_SIZE / 2;
private static final LeoInteger[] CACHE = new LeoInteger[CACHE_SIZE];
static {
for(int i = 0; i < CACHE_SIZE; i++) {
CACHE[i] = new LeoInteger(i - NCACHE_SIZE);
}
}
public static LeoInteger valueOf(int number) {
if ( number < NCACHE_SIZE && number > -NCACHE_SIZE ) {
return CACHE[ number + NCACHE_SIZE ];
}
return new LeoInteger(number);
}
/**
* Number
*/
private int number;
/**
* @param number
*/
private LeoInteger(int number) {
super(LeoType.INTEGER);
this.number = number;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#hashCode()
*/
@Override
public int hashCode() {
return this.number;
}
/**
* @return the number
*/
public int getNumber() {
return number;
}
@Override
public int asInt() {
return this.number;
}
@Override
public double asDouble() {
return (double)this.number;
}
@Override
public long asLong() {
return (long)this.number;
}
@Override
public float asFloat() {
return (float)this.number;
}
@Override
public byte asByte() {
return (byte)this.number;
}
@Override
public short asShort() {
return (short)this.number;
}
@Override
public char asChar() {
return (char)this.number;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#isNumber()
*/
@Override
public boolean isNumber() {
return true;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isTrue()
*/
@Override
public boolean isTrue() {
return this.number != 0;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#toString()
*/
@Override
public String toString() {
return Integer.toString(number);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this.number;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getValue(java.lang.Class)
*/
@Override
public Object getValue(Class<?> type) {
if ( ClassUtil.isType(type, ClassUtil.INT) ){
return this.number;
}
else if(ClassUtil.inheritsFrom(type, LeoObject.class) ) {
return this;
}
else if ( ClassUtil.isType(type, ClassUtil.BYTE) ){
return (byte)this.number;
}
else if ( ClassUtil.isType(type, ClassUtil.CHAR) ){
return (char)this.number;
}
else if ( ClassUtil.isType(type, ClassUtil.SHORT) ){
return (short)this.number;
}
else if ( ClassUtil.isType(type, ClassUtil.FLOAT) ){
return (float)this.number;
}
else if ( ClassUtil.isType(type, ClassUtil.DOUBLE) ){
return (double)this.number;
}
else if ( ClassUtil.isType(type, ClassUtil.LONG) ){
return (long)this.number;
}
else if ( ClassUtil.isType(type, ClassUtil.STRING) ){
return Integer.toString(this.number);
}
return this.number;
}
@Override
public boolean isAssignable(Class<?> javaType) {
if(javaType.isPrimitive()) {
javaType = ClassUtil.primitiveToWrapper(javaType);
}
return Number.class.isAssignableFrom(javaType);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return this;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#eq(leola.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
return other.$eq(this.number);
}
@Override
public boolean $eq(double other) {
return other == this.number;
}
@Override
public boolean $eq(int other) {
return other == this.number;
}
@Override
public boolean $eq(long other) {
return other == this.number;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gt(leola.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return other.$gt(this.number);
}
@Override
public boolean $gt(double other) {
return other > this.number;
}
@Override
public boolean $gt(int other) {
return other > this.number;
}
@Override
public boolean $gt(long other) {
return other > this.number;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lt(leola.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return other.$lt(this.number);
}
@Override
public boolean $lt(double other) {
return other < this.number;
}
@Override
public boolean $lt(int other) {
return other < this.number;
}
@Override
public boolean $lt(long other) {
return other < this.number;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gte(leola.types.LeoObject)
*/
@Override
public boolean $gte(LeoObject other) {
return other.$gte(this.number);
}
@Override
public boolean $gte(double other) {
return other >= this.number;
}
@Override
public boolean $gte(int other) {
return other >= this.number;
}
@Override
public boolean $gte(long other) {
return other >= this.number;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lte(leola.types.LeoObject)
*/
@Override
public boolean $lte(LeoObject other) {
return other.$lte(this.number);
}
@Override
public boolean $lte(double other) {
return other <= this.number;
}
@Override
public boolean $lte(int other) {
return other <= this.number;
}
@Override
public boolean $lte(long other) {
return other <= this.number;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#add(leola.types.LeoObject)
*/
@Override
public LeoObject $add(LeoObject other) {
return other.$add(this.number);
}
@Override
public LeoObject $add(double other) {
return LeoDouble.valueOf(other + this.number);
}
@Override
public LeoObject $add(int other) {
return LeoInteger.valueOf(other + this.number);
}
@Override
public LeoObject $add(long other) {
return LeoLong.valueOf(other + this.number);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#sub(leola.types.LeoObject)
*/
@Override
public LeoObject $sub(LeoObject other) {
return other.$sub(this.number);
}
@Override
public LeoObject $sub(double other) {
return LeoDouble.valueOf(other - this.number);
}
@Override
public LeoObject $sub(int other) {
return LeoInteger.valueOf(other - this.number);
}
@Override
public LeoObject $sub(long other) {
return LeoLong.valueOf(other - this.number);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#mul(leola.types.LeoObject)
*/
@Override
public LeoObject $mul(LeoObject other) {
return other.$mul(this.number);
}
@Override
public LeoObject $mul(double other) {
return LeoDouble.valueOf(other * this.number);
}
@Override
public LeoObject $mul(int other) {
return LeoInteger.valueOf(other * this.number);
}
@Override
public LeoObject $mul(long other) {
return LeoLong.valueOf(other * this.number);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#div(leola.types.LeoObject)
*/
@Override
public LeoObject $div(LeoObject other) {
return other.$div(this.number);
}
@Override
public LeoObject $div(double other) {
if ( number == 0 ) {
throwDivideByZeroError();
}
return LeoDouble.valueOf(other / this.number);
}
@Override
public LeoObject $div(int other) {
if ( number == 0 ) {
throwDivideByZeroError();
}
return LeoInteger.valueOf(other / this.number);
}
@Override
public LeoObject $div(long other) {
if ( number == 0 ) {
throwDivideByZeroError();
}
return LeoLong.valueOf(other / this.number);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#mod(leola.types.LeoObject)
*/
@Override
public LeoObject $mod(LeoObject other) {
return other.$mod(this.number);
}
@Override
public LeoObject $mod(double other) {
if ( number == 0 ) {
throwDivideByZeroError();
}
return LeoDouble.valueOf(other % this.number);
}
@Override
public LeoObject $mod(int other) {
if ( number == 0 ) {
throwDivideByZeroError();
}
return LeoInteger.valueOf(other % this.number);
}
@Override
public LeoObject $mod(long other) {
if ( number == 0 ) {
throwDivideByZeroError();
}
return LeoLong.valueOf(other % this.number);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#neg()
*/
@Override
public LeoObject $neg() {
return LeoInteger.valueOf(-this.number);
}
@Override
public LeoObject $bnot() {
LeoObject result = LeoInteger.valueOf( ~this.number );
return result;
}
@Override
public LeoObject $bsl(LeoObject other) {
return other.$bsl(this.number);
}
@Override
public LeoObject $bsl(double other) {
return LeoInteger.valueOf((int)other << this.number);
}
@Override
public LeoObject $bsl(int other) {
return LeoInteger.valueOf(other << this.number);
}
@Override
public LeoObject $bsl(long other) {
return LeoLong.valueOf(other << this.number);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#bsr(leola.types.LeoObject)
*/
@Override
public LeoObject $bsr(LeoObject other) {
return other.$bsr(this.number);
}
@Override
public LeoObject $bsr(double other) {
return LeoInteger.valueOf((int)other >> this.number);
}
@Override
public LeoObject $bsr(int other) {
return LeoInteger.valueOf(other >> this.number);
}
@Override
public LeoObject $bsr(long other) {
return LeoLong.valueOf(other >> this.number);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#xor(leola.types.LeoObject)
*/
@Override
public LeoObject $xor(LeoObject other) {
return other.$xor(this.number);
}
@Override
public LeoObject $xor(double other) {
return LeoInteger.valueOf((int)other ^ this.number);
}
@Override
public LeoObject $xor(int other) {
return LeoInteger.valueOf(other ^ this.number);
}
@Override
public LeoObject $xor(long other) {
return LeoLong.valueOf(other ^ this.number);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lor(leola.types.LeoObject)
*/
@Override
public LeoObject $bor(LeoObject other) {
return other.$bor(this.number);
}
@Override
public LeoObject $bor(double other) {
return LeoInteger.valueOf((int)other | this.number);
}
@Override
public LeoObject $bor(int other) {
return LeoInteger.valueOf(other | this.number);
}
@Override
public LeoObject $bor(long other) {
return LeoLong.valueOf(other | this.number);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#land(leola.types.LeoObject)
*/
@Override
public LeoObject $band(LeoObject other) {
return other.$band(this.number);
}
@Override
public LeoObject $band(double other) {
return LeoInteger.valueOf((int)other & this.number);
}
@Override
public LeoObject $band(int other) {
return LeoInteger.valueOf(other & this.number);
}
@Override
public LeoObject $band(long other) {
return LeoLong.valueOf(other & this.number);
}
@Override
public void write(DataOutput out) throws IOException {
out.write(this.getType().ordinal());
out.writeInt(this.number);
}
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the {@link LeoObject}
* @throws IOException
*/
public static LeoInteger read(DataInput in) throws IOException {
int number = in.readInt();
return LeoInteger.valueOf(number);
}
}
<|start_filename|>src/leola/vm/Repl.java<|end_filename|>
/*
* see license.txt
*/
package leola.vm;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.StringReader;
import java.util.Date;
import java.util.List;
import leola.ast.Expr;
import leola.ast.ProgramStmt;
import leola.ast.ReturnStmt;
import leola.ast.Stmt;
import leola.frontend.ErrorCode;
import leola.frontend.ParseException;
import leola.frontend.Parser;
import leola.frontend.Scanner;
import leola.frontend.Source;
import leola.frontend.tokens.Token;
import leola.frontend.tokens.TokenType;
import leola.vm.compiler.Bytecode;
import leola.vm.compiler.Compiler;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoUserFunction;
import static leola.frontend.tokens.TokenType.*;
/**
* Read Evaluate Print Loop
*
* @author Tony
*
*/
public class Repl {
private Leola runtime;
public Repl(Leola runtime) {
this.runtime = runtime;
}
/**
* Delegates to standard in/out/err streams
*
* @throws Exception
*/
public void execute() throws Exception {
execute(System.out, System.err, System.in);
}
/**
* Executes the Read Evaluate Print Loop
*
* @param printStream
* @param errStream
* @param inputStream
* @throws Exception
*/
public void execute(PrintStream printStream, PrintStream errStream, InputStream inputStream) throws Exception {
printStream.println("");
printStream.println("Leola v" + Leola.VERSION);
printStream.println("Date: " + new Date());
printStream.println("");
printStream.println("Type `quit()` to exit");
printStream.println("\n");
InputStreamReader input = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(input);
runtime.put("quit", new LeoUserFunction() {
@Override
public LeoObject xcall() throws LeolaRuntimeException {
System.exit(0);
return super.xcall();
}
});
Compiler compiler = new Compiler(runtime);
for (;;) {
try {
printStream.print(">>> ");
ProgramStmt program = readStmt(reader, printStream);
List<Stmt> stmts = program.getStatements();
boolean isStmt = true;
if(!stmts.isEmpty()) {
Stmt lastStmt = stmts.get(stmts.size()-1);
if (lastStmt instanceof Expr) {
stmts.set(stmts.size()-1, new ReturnStmt((Expr)lastStmt));
isStmt = false;
}
}
Bytecode bytecode = compiler.compile(program);
LeoObject result = runtime.execute(bytecode);
if(!isStmt) {
printStream.println(result);
}
}
catch(Exception e) {
errStream.println(e.getMessage());
}
}
}
private ProgramStmt readStmt(BufferedReader reader, PrintStream out) throws Exception {
boolean isStatementCompleted = true;
ProgramStmt program = null;
StringBuilder sourceBuffer = new StringBuilder();
String line = null;
do {
try {
line = readLine(reader);
sourceBuffer.append(line).append("\n");
Source source = new Source(new StringReader(sourceBuffer.toString()));
Scanner scanner = new Scanner(source);
Parser parser = new Parser(scanner);
program = parser.parse();
isStatementCompleted = true;
}
catch(ParseException e) {
Token token = e.getToken();
TokenType type = token != null ? token.getType() : null;
// if this is an end of file OR an Error of type Unexpected end of file, the user
// has submitted a partial statement
if(type != null && (type.equals(END_OF_FILE) ||
(type.equals(ERROR) && token.getValue().equals(ErrorCode.UNEXPECTED_EOF)))) {
isStatementCompleted = false;
if(!line.trim().isEmpty()) {
out.print("> ");
}
}
else {
throw e;
}
}
}
while(!isStatementCompleted);
return program;
}
private String readLine(BufferedReader reader) throws Exception {
StringBuilder buffer = new StringBuilder();
String line = reader.readLine();
buffer.append(line).append("\n");
// if the user pasted in a chunk of code
// the buffer will be able to read in the
// full input, however we still want to
// block and wait for the user to press
// enter for the final input
boolean pasted = false;
while(reader.ready()) {
line = reader.readLine();
buffer.append(line).append("\n");
pasted = true;
}
if(pasted) {
line = reader.readLine();
buffer.append(line).append("\n");
}
return buffer.toString();
}
}
<|start_filename|>src/leola/lang/StringLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.lib.LeolaMethodVarargs;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
/**
* Standard String functions
*
* @author Tony
*
*/
public class StringLeolaLibrary implements LeolaLibrary {
private Leola runtime;
/* (non-Javadoc)
* @see leola.frontend.LeolaLibrary#init(leola.frontend.Leola)
*/
@Override
@LeolaIgnore
public void init(Leola runtime, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = runtime;
this.runtime.putIntoNamespace(this, namespace);
}
public void foreach(LeoString str, LeoObject function) {
int size = str.length();
for(int i = 0; i < size; i++) {
LeoObject result = function.xcall(str.charAt(i));
if ( LeoObject.isTrue(result) ) {
break;
}
}
}
/**
* Combines the list of arguments (separating them by the supplied delimiter).
*
* @param delimiter
* @param args
* @return the joined string
*/
@LeolaMethodVarargs
public LeoString join(Object delimiter, Object ... args) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < args.length; i++) {
if(i>0) {
sb.append(delimiter);
}
sb.append(args[i]);
}
return LeoString.valueOf(sb.toString());
}
@LeolaMethodVarargs
public LeoString printf(Object str, LeoObject ... args) {
LeoString result = null;
if(args!=null) {
int len = args.length;
Object[] params = new Object[len];
for(int i = 0; i < len; i++) {
params[i] = args[i].getValue();
}
result = LeoString.valueOf(String.format(str.toString(), params));
}
else {
result = LeoString.valueOf(String.format(str.toString()));
}
return result;
}
public LeoString append(LeoString str, LeoString v) {
return str.append(v);
}
public LeoString charAt(LeoString str, int i) {
return str.charAt(i);
}
public LeoString insert(LeoString str, int index, LeoObject v) {
return str.insert(index, v);
}
public LeoString replace(LeoString str, int start, int end, LeoObject v) {
return str.replace(start, end, v);
}
public LeoString replaceAll(LeoString str, LeoObject replaceMe, LeoObject v) {
return str.replaceAll(replaceMe, v);
}
public LeoArray split(LeoString str, LeoObject v) {
return str.split(v);
}
public boolean contains(LeoString str, LeoObject v) {
return str.contains(v);
}
public int indexOf(LeoString str, LeoObject v) {
return str.indexOf(v);
}
public LeoString substring(LeoString str, int start, int end) {
return str.substring(start, end);
}
public LeoString rest(LeoString str, int start) {
return str.rest(start);
}
public boolean endsWith(LeoString str, LeoObject v) {
return str.endsWith(v);
}
public boolean startsWith(LeoString str, LeoObject v) {
return str.startsWith(v);
}
public LeoString toLower(LeoString str) {
return str.toLower();
}
public LeoString toUpper(LeoString str) {
return str.toUpper();
}
public boolean empty(LeoObject str) {
return str == null ||
str == LeoNull.LEONULL ||
str.toLeoString().empty();
}
public LeoString trim(LeoObject str) {
return LeoString.valueOf(str.toString().trim());
}
public byte[] bytes(LeoObject str) {
return str.toString().getBytes();
}
/**
* Retrieves all of the indexes where 'v' is found in this string.
* @param v
* @return list of all indexes where 'v' is found in this string.
*/
public LeoArray indexesOf(LeoString str, LeoObject v) {
return str.indexesOf(v);
}
}
<|start_filename|>src/leola/ast/IfStmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* If Statement
*
* @author Tony
*
*/
public class IfStmt extends Stmt {
private Expr condition;
private Stmt stmt;
private Stmt elseStmt;
/**
* @param condition
* @param stmt
* @param elseStmt
*/
public IfStmt(Expr condition, Stmt stmt, Stmt elseStmt) {
this.condition = becomeParentOf(condition);
this.stmt = becomeParentOf(stmt);
this.elseStmt = becomeParentOf(elseStmt);
}
/**
* @param condition
* @param stmt
*/
public IfStmt(Expr condition, Stmt stmt) {
this(condition, stmt, null);
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the condition
*/
public Expr getCondition() {
return condition;
}
/**
* @return the stmt
*/
public Stmt getStmt() {
return stmt;
}
/**
* @return the elseStmt
*/
public Stmt getElseStmt() {
return elseStmt;
}
}
<|start_filename|>src/leola/ast/NullExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Represents null
*
* @author Tony
*
*/
public class NullExpr extends Expr {
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
}
<|start_filename|>src/leola/vm/NamespaceDefinitions.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoObject;
/**
* Stores the {@link LeoNamespace}s
*
* @author Tony
*
*/
public class NamespaceDefinitions {
private Map<LeoObject, LeoNamespace> namespaces;
/**
* Determine if there are any {@link LeoNamespace}'s defined
*
* @return true if there are {@link LeoNamespace}'s defined
*/
public boolean hasDefinitions() {
return this.namespaces != null && ! this.namespaces.isEmpty();
}
/**
* Removes all {@link LeoNamespace}'s. Use this method with care.
*/
public void clearDefinitions() {
if(hasDefinitions()) {
this.namespaces.clear();
}
}
/**
* @return the classDefinitions
*/
public Map<LeoObject, LeoNamespace> getNamespaceDefinitions() {
if ( this.namespaces == null ) {
this.namespaces = new ConcurrentHashMap<LeoObject, LeoNamespace>();
}
return namespaces;
}
/**
* Stores the {@link LeoNamespace}
*
* @param ns
*/
public void storeNamespace(LeoNamespace ns) {
storeNamespace(ns.getName(), ns);
}
/**
* Stores the {@link LeoNamespace}, bounded to the supplied namespace name
*
* @param namespaceName
* @param ns
*/
public void storeNamespace(LeoObject namespaceName, LeoNamespace ns) {
getNamespaceDefinitions().put(namespaceName, ns);
}
/**
* Removes the {@link LeoNamespace} associated with the supplied name
*
* @param namespaceName
*/
public void removeNamespace(LeoObject namespaceName) {
getNamespaceDefinitions().remove(namespaceName);
}
/**
* Determines if there is a {@link LeoNamespace} associated with the supplied name.
*
* @param namespace
* @return true if there is a {@link LeoNamespace} associated with the supplied name.
*/
public boolean containsNamespace(LeoObject namespace) {
return getNamespaceDefinitions().containsKey(namespace);
}
/**
* Retrieves the {@link LeoNamespace} associated with the supplied name.
* @param namespace
* @return the {@link LeoNamespace} associated with the supplied name,
* or null if not bound.
*/
public LeoNamespace getNamespace(LeoObject namespace) {
return getNamespaceDefinitions().get(namespace);
}
}
<|start_filename|>src/leola/ast/NamespaceSetExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.frontend.tokens.Token;
import leola.vm.EvalException;
/**
* @author Tony
*
*/
public class NamespaceSetExpr extends Expr {
private VarExpr namespace;
private String identifier;
private Expr value;
private Token operator;
public NamespaceSetExpr(VarExpr namespace, String identifier, Expr value, Token operator) {
this.namespace = namespace;
this.identifier = identifier;
this.value = value;
this.operator = operator;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public VarExpr getNamespace() {
return namespace;
}
public String getIdentifier() {
return identifier;
}
public Expr getValue() {
return value;
}
public Token getOperator() {
return operator;
}
}
<|start_filename|>src/leola/frontend/tokens/SpecialSymbolToken.java<|end_filename|>
package leola.frontend.tokens;
import static leola.frontend.ErrorCode.INVALID_CHARACTER;
import static leola.frontend.tokens.TokenType.ERROR;
import static leola.frontend.tokens.TokenType.SPECIAL_SYMBOLS;
import leola.frontend.Source;
/**
* Special symbol tokens
*
* @author Tony
*
*/
public class SpecialSymbolToken extends Token {
/**
* @param source the source from where to fetch the token's characters.
*/
public SpecialSymbolToken(Source source) {
super(source);
}
/**
* Extract a Leola special symbol token from the source.
*/
@Override
protected void extract() {
char currentChar = currentChar();
text = Character.toString(currentChar);
type = null;
switch (currentChar) {
// Single-character special symbols.
case ',': case ';': case '(': case ')':
case '[': case ']': case '{': case '}': case ':':
case '@': case '~': case '?':
// case '^':
{
nextChar(); // consume character
break;
}
// . or ..
case '.': {
currentChar = nextChar();
if (currentChar == '.') {
text += currentChar;
currentChar = nextChar(); // consume '.'
if(currentChar == '.') {
text += currentChar;
nextChar();
}
else {
type = ERROR;
value = INVALID_CHARACTER;
}
}
break;
}
// + or +=
case '+' : {
currentChar = nextChar();
if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
break;
}
// * or *=
case '*' : {
currentChar = nextChar();
if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
break;
}
// / or /=
case '/' : {
currentChar = nextChar();
if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
break;
}
// % or %=
case '%' : {
currentChar = nextChar();
if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
break;
}
// ^ or ^=
case '^' : {
currentChar = nextChar();
if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
break;
}
// = or == or =>
case '=': {
currentChar = nextChar(); // consume '=';
if (currentChar == '=') {
text += currentChar;
currentChar = nextChar(); // consume '='
if(currentChar == '=') {
text += currentChar;
nextChar();
}
}
else if(currentChar == '>') {
text += currentChar;
currentChar = nextChar(); // consume '>'
}
break;
}
// < or <= or <>
case '<': {
currentChar = nextChar(); // consume '<';
if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
else if (currentChar == '<') {
text += currentChar;
nextChar(); // consume '<'
char peekChar = currentChar();
if ( peekChar == '=' ) {
text += peekChar;
nextChar(); // consume '='
}
}
break;
}
// > or >=
case '>': {
currentChar = nextChar(); // consume '>';
if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
else if (currentChar == '>') {
text += currentChar;
nextChar(); // consume '>'
char peekChar = currentChar();
if ( peekChar == '=' ) {
text += peekChar;
nextChar(); // consume '='
}
}
break;
}
// - or ->
case '-': {
currentChar = nextChar(); // consume '-';
if (currentChar == '>') {
text += currentChar;
nextChar(); // consume '>'
}
else if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
break;
}
case '!': {
currentChar = nextChar(); // consume '!';
if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
char peekChar = currentChar();
if ( peekChar == '=' ) {
text += peekChar;
nextChar(); // consume '='
}
break;
}
case '&': {
currentChar = nextChar(); // consume '&';
if (currentChar == '&') {
text += currentChar;
nextChar(); // consume '&'
}
else if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
break;
}
case '|': {
currentChar = nextChar(); // consume '|';
if (currentChar == '|') {
text += currentChar;
nextChar(); // consume '|'
}
else if (currentChar == '=') {
text += currentChar;
nextChar(); // consume '='
}
break;
}
default: {
nextChar(); // consume bad character
type = ERROR;
value = INVALID_CHARACTER;
}
}
// Set the type if it wasn't an error.
if (type == null) {
type = SPECIAL_SYMBOLS.get(text);
}
}
}
<|start_filename|>src/leola/ast/NamespaceStmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Namespace definition Statement
*
* @author Tony
*
*/
public class NamespaceStmt extends Stmt {
/**
* The namespace
*/
private Stmt stmt;
/**
* Name
*/
private String name;
/**
* @param stmt
* @param name
*/
public NamespaceStmt(Stmt stmt, String name) {
this.stmt = becomeParentOf(stmt);
this.name = name;
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the stmt
*/
public Stmt getStmt() {
return stmt;
}
/**
* @return the name
*/
public String getName() {
return name;
}
}
<|start_filename|>src/leola/ast/Stmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
/**
* A Statement
*
* @author Tony
*
*/
public abstract class Stmt extends ASTNode {
}
<|start_filename|>src/leola/frontend/tokens/TokenType.java<|end_filename|>
package leola.frontend.tokens;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import leola.frontend.ErrorCode;
import leola.frontend.ParseException;
/**
* Leola token types.
*
* @author Tony
*
*/
public enum TokenType {
// Reserved words.
SWITCH,
CASE, WHEN, RETURN, ELSE, NAMESPACE, DEF, GEN,
YIELD, IF, NULL, VAR, WHILE, IS, CATCH,
NEW, TRUE, FALSE, BREAK, CONTINUE, THROW, TRY, FINALLY,
CLASS,
// end Reserved words
// Special symbols.
PLUS("+"),
MINUS("-"), STAR("*"), MOD("%"), SLASH("/"), D_EQUALS("=="),
REF_EQUALS("==="), REF_NOT_EQUALS("!=="),
DOT("."), VAR_ARGS("..."), AT("@"), QUESTION_MARK("?"), COMMA(","), SEMICOLON(";"), COLON(":"),
EQUALS("="), NOT_EQUALS("!="), LESS_THAN("<"), LESS_EQUALS("<="),
GREATER_EQUALS(">="), GREATER_THAN(">"), LEFT_PAREN("("), RIGHT_PAREN(")"),
LEFT_BRACKET("["), RIGHT_BRACKET("]"), LEFT_BRACE("{"), RIGHT_BRACE("}"),
LOGICAL_OR("||"), LOGICAL_AND("&&"), NOT("!"), DQUOTE("\""), ARROW("->"), FAT_ARROW("=>"),
BIT_SHIFT_LEFT("<<"), BIT_SHIFT_RIGHT(">>"),
// Binary Assignment operators
PLUS_EQ("+="),
MINUS_EQ("-="), STAR_EQ("*="), SLASH_EQ("/="), MOD_EQ("%="),
BSL_EQ("<<="), BSR_EQ(">>="), BOR_EQ("|="), BAND_EQ("&="),
BXOR_EQ("^="),
// end Binary Assignment operators
BITWISE_NOT("~"), BITWISE_OR("|"), BITWISE_AND("&"),
BITWISE_XOR("^"),
// end Special symbols
IDENTIFIER,
INTEGER,
LONG,
REAL,
STRING,
ERROR,
END_OF_FILE;
private static final int FIRST_RESERVED_INDEX = SWITCH.ordinal();
private static final int LAST_RESERVED_INDEX = CLASS.ordinal();
private static final int FIRST_SPECIAL_INDEX = PLUS.ordinal();
private static final int LAST_SPECIAL_INDEX = BITWISE_XOR.ordinal();
private static final int FIRST_BIN_ASSGN_INDEX = PLUS_EQ.ordinal();
private static final int LAST_BIN_ASSGN_INDEX = BXOR_EQ.ordinal();
private String text; // token text
/**
*/
TokenType() {
this.text = this.toString().toLowerCase();
}
/**
* @param text the token text.
*/
TokenType(String text) {
this.text = text;
}
/**
* @return the token text.
*/
public String getText() {
return text;
}
/**
* Returns the text as a number
* @return the text as a number
* @throws Exception
*/
public double getTextAsNumber() throws Exception {
try {
return Double.parseDouble(this.text);
}
catch(Exception e) {
throw new ParseException
(ErrorCode.INVALID_NUMBER, null, "Unable to parse: " + this.text + " as a number.", e);
}
}
// Set of lower-cased Leola reserved word text strings.
public static Set<String> RESERVED_WORDS = new HashSet<String>();
static {
TokenType values[] = TokenType.values();
for (int i = FIRST_RESERVED_INDEX; i <= LAST_RESERVED_INDEX; ++i) {
RESERVED_WORDS.add(values[i].getText().toLowerCase());
}
}
// Hash table of Leola special symbols. Each special symbol's text
// is the key to its Leola token type.
public static Map<String, TokenType> SPECIAL_SYMBOLS = new HashMap<String, TokenType>();
static {
TokenType values[] = TokenType.values();
for (int i = FIRST_SPECIAL_INDEX; i <= LAST_SPECIAL_INDEX; ++i) {
SPECIAL_SYMBOLS.put(values[i].getText(), values[i]);
}
}
/**
* Binary Assignment operators
*/
public static Map<String, TokenType> BINARY_ASSIGNMENT = new HashMap<String, TokenType>();
static {
TokenType values[] = TokenType.values();
for (int i = FIRST_BIN_ASSGN_INDEX; i <= LAST_BIN_ASSGN_INDEX; ++i) {
BINARY_ASSIGNMENT.put(values[i].getText(), values[i]);
}
}
}
<|start_filename|>src/leola/vm/types/LeoObject.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import leola.vm.Leola;
import leola.vm.Scope;
import leola.vm.compiler.Outer;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaMethod;
import leola.vm.util.ClassUtil;
import leola.vm.util.LeoTypeConverter;
import leola.vm.util.LeoTypeConverter.Converter;
/**
* Base object for {@link Leola} types. The basic design principal for the {@link LeoObject} is to treat all
* types the same, that is avoid the need to cast as much as possible and error if the underlying type does not
* support an operation.
*
* <p>
* This does have the negative consequence of having the {@link LeoObject} blow up in size and responsibility. However, I
* feel the trade-off is warranted.
*
* <p>
* There are a number of operators that can be overridden (both in Java and Leola code). The operators include:
* <table border="1">
* <tr>
* <th>Leola Operator</th>
* <th>Java/Leola method name</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>===</td>
* <td>$req</td>
* <td>Reference equals operator, the default functionality is to check the equality of the references (identical to Java '==' operator)</td>
* </tr>
* <tr>
* <td>==</td>
* <td>$eq</td>
* <td>Object equals operator, the default functionality is to check the equality of the objects (identical to Java <code>equals</code> method)</td>
* </tr>
* <tr>
* <td>!=</td>
* <td>$neq</td>
* <td>Object not equals operator, the default functionality is to check the negated equality of the objects (identical to Java <code>!equals</code> method)</td>
* </tr>
* <tr>
* <td><</td>
* <td>$lt</td>
* <td>Object less than operator, the default functionality is to check if the left hand object is less than the right hand object (identical to Java <code><</code> operator)</td>
* </tr>
* <tr>
* <td><=</td>
* <td>$lte</td>
* <td>Object less than or equals operator, the default functionality is to check if the left hand object is less than or equal to the right hand object (identical to Java <code>equals</code> method and/or the <code><</code> operator)</td>
* </tr>
* <tr>
* <td>></td>
* <td>$gt</td>
* <td>Object greater than operator, the default functionality is to check if the left hand object is greater than the right hand object (identical to Java <code>></code> operator)</td>
* </tr>
* <tr>
* <td>>=</td>
* <td>$gte</td>
* <td>Object greater than or equals operator, the default functionality is to check if the left hand object is greater than or equal to the right hand object (identical to Java <code>equals</code> method and/or the <code>></code> operator)</td>
* </tr>
* <tr>
* <td>+</td>
* <td>$add</td>
* <td>Object addition operator, the default functionality is to add the right hand object to the left hand object (identical to Java <code>+</code> operator)</td>
* </tr>
* <tr>
* <td>-</td>
* <td>$sub</td>
* <td>Object subtraction operator, the default functionality is to subtract the right hand object from the left hand object (identical to Java <code>-</code> operator)</td>
* </tr>
* <tr>
* <td>*</td>
* <td>$mul</td>
* <td>Object multiplication operator, the default functionality is to multiply the right hand object by the left hand object (identical to Java <code>*</code> operator)</td>
* </tr>
* <tr>
* <td>/</td>
* <td>$div</td>
* <td>Object division operator, the default functionality is to divide the left hand object by the right hand object (identical to Java <code>/</code> operator)</td>
* </tr>
* <tr>
* <td>%</td>
* <td>$mod</td>
* <td>Object remainder (or modules) operator, the default functionality is to take the remainder of dividing the left hand object by the right hand object (identical to Java <code>%</code> operator)</td>
* </tr>
* <tr>
* <td>!</td>
* <td>$neg</td>
* <td>Object negate operator, the default functionality is to take the negative of the object (identical to Java <code>!</code> operator)</td>
* </tr>
* <tr>
* <td>~</td>
* <td>$bnot</td>
* <td>Object binary NOT operator, the default functionality is to negate/flip the object (identical to Java <code>~</code> operator)</td>
* </tr>
* <tr>
* <td>&</td>
* <td>$band</td>
* <td>Object binary AND operator, the default functionality is to binary AND together the right hand object and the left hand object (identical to Java <code>&</code> operator)</td>
* </tr>
* <tr>
* <td>|</td>
* <td>$bor</td>
* <td>Object binary OR operator, the default functionality is to binary OR together the right hand object and the left hand object (identical to Java <code>|</code> operator)</td>
* </tr>
* <tr>
* <td><<</td>
* <td>$bsl</td>
* <td>Object binary shift left operator, the default functionality is to binary shift left the left hand object by the right hand object (identical to Java <code><<</code> operator)</td>
* </tr>
* <tr>
* <td>>></td>
* <td>$bsr</td>
* <td>Object binary shift right operator, the default functionality is to binary shift right the left hand object by the right hand object (identical to Java <code>>></code> operator)</td>
* </tr>
* <tr>
* <td>^</td>
* <td>$xor</td>
* <td>Object binary EXCLUSIVE OR operator, the default functionality is to binary exclusive or of the left hand object by the right hand object (identical to Java <code>^</code> operator)</td>
* </tr>
* <tr>
* <td>[]</td>
* <td>$sindex</td>
* <td>Object set at index operator, the default functionality is to set the right hand object at the supplied index of the left hand object (identical to Java <code>left[index] = right</code> operator)</td>
* </tr>
* <tr>
* <td>[]</td>
* <td>$index</td>
* <td>Object get object at index operator, the default functionality is to retrieve the object at the supplied index (identical to Java <code>left[index]</code> operator)</td>
* </tr>
* <tr>
* <td>toString()</td>
* <td>toString</td>
* <td>Object toString operator, should convert the object to a {@link String} object (identical to Java <code>toString()</code> method)</td>
* </tr>
* </table>
*
* <p>
* Some example Leola scripts that override the above operators:
* <pre>
* class Vector(x, y) {
* var $add = def(other) {
* return new Vector(x+other.x, y+other.y)
* }
* var $sub = def(other) {
* return new Vector(x-other.x, y-other.y)
* }
* var $mul = def(other) {
* return case
* when other is Vector -> new Vector(x*other.x, y*other.y)
* else new Vector(x*other, y*other)
* }
*
* var toString = def() {
* return "(" + x + "," + y + ")"
* }
* }
*
* var v = new Vector(10, 5)
* var z = new Vector(4, 10)
*
* var delta = v-z
* println(delta) // (6,-5)
* println(delta * 2) // 12, -10
*
* </pre>
*
* @author Tony
*
*/
public abstract class LeoObject implements Comparable<LeoObject> {
public static final LeoString REQ = LeoString.valueOf("$req");
public static final LeoString EQ = LeoString.valueOf("$eq");
public static final LeoString NEQ = LeoString.valueOf("$neq");
public static final LeoString LT = LeoString.valueOf("$lt");
public static final LeoString LTE = LeoString.valueOf("$lte");
public static final LeoString GT = LeoString.valueOf("$gt");
public static final LeoString GTE = LeoString.valueOf("$gte");
public static final LeoString ADD = LeoString.valueOf("$add");
public static final LeoString SUB = LeoString.valueOf("$sub");
public static final LeoString MUL = LeoString.valueOf("$mul");
public static final LeoString DIV = LeoString.valueOf("$div");
public static final LeoString MOD = LeoString.valueOf("$mod");
public static final LeoString NEG = LeoString.valueOf("$neg");
public static final LeoString BNOT = LeoString.valueOf("$bnot");
public static final LeoString BAND = LeoString.valueOf("$band");
public static final LeoString BOR = LeoString.valueOf("$bor");
public static final LeoString BSL = LeoString.valueOf("$bsl");
public static final LeoString BSR = LeoString.valueOf("$bsr");
public static final LeoString XOR = LeoString.valueOf("$xor");
public static final LeoString INDEX = LeoString.valueOf("$index");
public static final LeoString SINDEX = LeoString.valueOf("$sindex");
public static final LeoString toString = LeoString.valueOf("toString");
/**
* A convenience means for retrieving the {@link LeoNull} object
*/
public static final LeoObject NULL = LeoNull.LEONULL;
public static final LeoObject TRUE = LeoBoolean.LEOTRUE;
public static final LeoObject FALSE = LeoBoolean.LEOFALSE;
/**
* Converts the supplied Java object into the appropriate {@link LeoObject} type.
*
* @param v the Java object
* @return the converted Java object to the respective {@link LeoObject} type.
*/
public static final LeoObject valueOf(Object v) {
return LeoTypeConverter.convertToLeolaType(v);
}
/**
* Attempts to convert the supplied {@link LeoObject} into the equivalent Java Object using
* the supplied Class as a hint.
*
* @param jtype the hint at which type the Java Object should be
* @param v the {@link LeoObject} to convert
* @return the Java Object version of the supplied {@link LeoObject}
*/
public static final Object toJavaObject(Class<?> jtype, LeoObject v) {
return LeoTypeConverter.convertLeoObjectToJavaObj(jtype, v);
}
/**
* This will create a <b>new</b> Java object based off of the supplied {@link LeoObject}, this is different from
* {@link LeoObject#toJavaObject(Class, LeoObject)} as this will attempt to coerce the existing object into
* a Java object. This method acts much like <code>Gson</code> or <code>Jackson</code> libraries.
*
*
* @param value
* @param type
* @param converters
* @return the newly created Java object
*/
public static final <T> T fromLeoObject(LeoObject value, Class<T> type, Map<Class<?>, Converter> converters) {
return LeoTypeConverter.fromLeoObject(value, converters, type);
}
/**
* This will create a <b>new</b> Java object based off of the supplied {@link LeoObject}, this is different from
* {@link LeoObject#toJavaObject(Class, LeoObject)} as this will attempt to coerce the existing object into
* a Java object. This method acts much like <code>Gson</code> or <code>Jackson</code> libraries.
*
* @param value
* @param type
* @return the newly created Java object
*/
public static final <T> T fromLeoObject(LeoObject value, Class<T> type) {
return LeoTypeConverter.fromLeoObject(value, null, type);
}
/*
* Type
*/
public enum LeoType {
NULL
, BOOLEAN
, INTEGER
, LONG
, REAL
// , NUMBER
, STRING
, GENERATOR
, FUNCTION
, NATIVE_FUNCTION
, USER_FUNCTION
, ARRAY
, MAP
, CLASS
, NAMESPACE
, NATIVE_CLASS
, ERROR
;
/* Java instantiates a new array for each values() call */
private static final LeoType[] values = values();
public static LeoType fromOrdinal(int ordinal) {
return values[ordinal];
}
}
/**
* The underlying type
*/
private final LeoType type;
/**
* @param type
*/
protected LeoObject(LeoType type) {
this.type = type;
}
public LeoString toLeoString() {
return LeoString.valueOf(toString());
}
/**
* @return the type
*/
public LeoType getType() {
return type;
}
/**
* @return the scope
*/
public Scope getScope() {
return null;
}
/**
* @return the outers
*/
public Outer[] getOuters() {
return null;
}
/**
* @return the locals
*/
public LeoObject[] getLocals() {
return null;
}
public boolean isNull() {
return false;
}
public boolean isNumber() {
return false;
}
public boolean isString() {
return false;
}
public boolean isMap() {
return false;
}
public boolean isArray() {
return false;
}
public boolean isBoolean() {
return false;
}
public boolean isClass() {
return false;
}
public boolean isNativeClass() {
return false;
}
public boolean isGenerator() {
return false;
}
public boolean isFunction() {
return false;
}
public boolean isNativeFunction() {
return false;
}
public boolean isOuter() {
return false;
}
public boolean isError() {
return false;
}
public boolean isNamespace() {
return false;
}
/**
* @return if this object has it's own scope.
*/
public boolean isScopedObject() {
return false;
}
/**
* @return if this object implements {@link LeoObject#setObject(LeoObject, LeoObject)} and
* {@link LeoObject#getObject(LeoObject)} methods
*/
public boolean isAccessible() {
return false;
}
/**
* Determines if its one of these types
* @param leoTypes
* @return
*/
public boolean isOfType(LeoType leoType) {
return (this.type==leoType);
}
/**
* Determines if its one of these types
* @param leoTypes
* @return
*/
public boolean isOfType(LeoType ... leoTypes) {
for(LeoType t: leoTypes) {
if ( this.type==t ) {
return true;
}
}
return false;
}
/**
* Determines if its one of these types
* @param leoTypes
* @return
*/
public boolean isOfType(Class<?> ... leoTypes) {
for(Class<?> c: leoTypes) {
if ( this.getClass().equals(c)) {
return true;
}
}
return false;
}
/**
* Determines if this type is of the supplied type.
*
* @param rawType
* @return
*/
public boolean isOfType(String rawType) {
boolean isa = false;
try {
LeoType type = LeoType.valueOf(rawType.toUpperCase());
isa = isOfType(type);
}
catch(Exception e) {
isa = false;
}
return isa;
}
/**
* Up Casts the supplied {@link LeoObject}
* @param <T>
* @param obj
* @return
*/
@SuppressWarnings("unchecked")
public static <T extends LeoObject> T as(LeoObject obj) {
return (T)obj;
}
/**
* Up Casts this {@link LeoObject}
*
* @param <T>
* @return
*/
@SuppressWarnings("unchecked")
public <T extends LeoObject> T as() {
return (T)this;
}
/**
* @return this object represented as an integer
*/
public int asInt() {
throw new LeolaRuntimeException("Not a valid integer");
}
/**
* @return this object represented as a Long
*/
public long asLong() {
throw new LeolaRuntimeException("Not a valid long");
}
/**
* @return this object represented as a Double
*/
public double asDouble() {
throw new LeolaRuntimeException("Not a valid double");
}
/**
* @return this object represented as a Float
*/
public float asFloat() {
return (float)asDouble();
}
/**
* @return this object represented as a Byte
*/
public byte asByte() {
return (byte)asInt();
}
/**
* @return this object represented as a Short
*/
public short asShort() {
return (short)asInt();
}
/**
* @return this object represented as a Character
*/
public char asChar() {
return (char)asInt();
}
/**
* Determines if the two objects are equal.
*
* @param left
* @param right
* @return
*/
public static boolean $eq(LeoObject left, LeoObject right) {
if ( left == null && right == null ) {
return true;
}
if ( left == right ) {
return true;
}
if ( left != null && right != null ) {
return left.$eq(right);
}
return false;
}
/**
* Determines if the supplied object is of type TRUE.
*
* @param obj
* @return
*/
public static boolean isTrue(LeoObject obj) {
boolean isTrue = (obj != null) && obj.isTrue();
return isTrue;
}
/**
* Determines if the supplied object is either a Java <code>null</code> or
* a {@link LeoNull} instance.
*
* @param obj
* @return true if either <code>null</code> or
* a {@link LeoNull} instance.
*/
public static boolean isNull(LeoObject obj) {
return obj == null || obj == LeoNull.NULL;
}
/**
* Determines if the supplied object is of type TRUE.
*
* @param obj
* @return
*/
public boolean isTrue() {
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("[ %s @ %s ]", this.type, super.toString());
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LeoObject other = (LeoObject) obj;
if (type != other.type)
return false;
return this.$eq(other);
}
/**
* Tests if the references are the same. Java equivalent to '=='
* @param other
* @return true if they are the same reference
*/
public boolean $req(LeoObject other) {
return this == other;
}
/**
* Tests if the references are not the same. Java equivalent to ! '=='
* @param other
* @return true if they are not the same references
*/
public boolean $rneq(LeoObject other) {
return (this != other);
}
/**
* Determines if it equals another object.
*
* @param other
* @return true if it equals
*/
public abstract boolean $eq(LeoObject other);
public boolean $eq(int other) { return false; }
public boolean $eq(double other) { return false; }
public boolean $eq(long other) { return false; }
/**
* If it's not equal another object.
*
* @param other
* @return
*/
public boolean $neq(LeoObject other) {
return ! $eq(other);
}
public boolean $neq(int other) {
return ! $eq(other);
}
public boolean $neq(double other) {
return ! $eq(other);
}
public boolean $neq(long other) {
return ! $eq(other);
}
/**
* If it's less than to another object
* @param other
* @return
*/
public abstract boolean $lt(LeoObject other);
public boolean $lt(int other) { return false; }
public boolean $lt(double other) { return false; }
public boolean $lt(long other) { return false; }
/**
* If it's less than or equal to another object.
* @param other
* @return
*/
public boolean $lte(LeoObject other) {
return $eq(other) || $lt(other);
}
public boolean $lte(int other) {
return $eq(other) || $lt(other);
}
public boolean $lte(double other) {
return $eq(other) || $lt(other);
}
public boolean $lte(long other) {
return $eq(other) || $lt(other);
}
/**
* If it's greater than to another object
* @param other
* @return
*/
public abstract boolean $gt(LeoObject other);
public boolean $gt(int other) { return false; }
public boolean $gt(double other) { return false; }
public boolean $gt(long other) { return false; }
/**
* If it's greater than or equal to another object.
* @param other
* @return
*/
public boolean $gte(LeoObject other) {
return $eq(other) || $gt(other);
}
public boolean $gte(int other) {
return $eq(other) || $gt(other);
}
public boolean $gte(double other) {
return $eq(other) || $gt(other);
}
public boolean $gte(long other) {
return $eq(other) || $gt(other);
}
public LeoObject $add(LeoObject other) { throwNotImplementedError("$add"); return null; }
public LeoObject $sub(LeoObject other) { throwNotImplementedError("$sub"); return null; }
public LeoObject $mul(LeoObject other) { throwNotImplementedError("$mul"); return null; }
public LeoObject $div(LeoObject other) { throwNotImplementedError("$div"); return null; }
public LeoObject $mod(LeoObject other) { throwNotImplementedError("$mod"); return null; }
public LeoObject $add(int other) { throwNotImplementedError("$add"); return null; }
public LeoObject $sub(int other) { throwNotImplementedError("$sub"); return null; }
public LeoObject $mul(int other) { throwNotImplementedError("$mul"); return null; }
public LeoObject $div(int other) { throwNotImplementedError("$div"); return null; }
public LeoObject $mod(int other) { throwNotImplementedError("$mod"); return null; }
public LeoObject $add(double other) { throwNotImplementedError("$add"); return null; }
public LeoObject $sub(double other) { throwNotImplementedError("$sub"); return null; }
public LeoObject $mul(double other) { throwNotImplementedError("$mul"); return null; }
public LeoObject $div(double other) { throwNotImplementedError("$div"); return null; }
public LeoObject $mod(double other) { throwNotImplementedError("$mod"); return null; }
public LeoObject $add(long other) { throwNotImplementedError("$add"); return null; }
public LeoObject $sub(long other) { throwNotImplementedError("$sub"); return null; }
public LeoObject $mul(long other) { throwNotImplementedError("$mul"); return null; }
public LeoObject $div(long other) { throwNotImplementedError("$div"); return null; }
public LeoObject $mod(long other) { throwNotImplementedError("$mod"); return null; }
public LeoObject $neg() { throwNotImplementedError("$neg"); return null; }
// public LeoObject not() { return null; }
public LeoObject $bnot() { throwNotImplementedError("$bnot"); return null; }
public LeoObject $index(LeoObject other) { throwNotImplementedError("$index"); return null; }
public void $sindex(LeoObject key, LeoObject other) { throwNotImplementedError("$sindex"); }
public LeoObject $bsl(LeoObject other) { throwNotImplementedError("$bsl"); return null; }
public LeoObject $bsr(LeoObject other) { throwNotImplementedError("$bsr"); return null; }
public LeoObject $xor(LeoObject other) { throwNotImplementedError("$xor"); return null; }
public LeoObject $bor(LeoObject other) { throwNotImplementedError("$bor"); return null; }
public LeoObject $band(LeoObject other) { throwNotImplementedError("$band"); return null; }
public LeoObject $index(int other) { throwNotImplementedError("$index"); return null; }
public LeoObject $bsl(int other) { throwNotImplementedError("$bsl"); return null; }
public LeoObject $bsr(int other) { throwNotImplementedError("$bsr"); return null; }
public LeoObject $xor(int other) { throwNotImplementedError("$xor"); return null; }
public LeoObject $bor(int other) { throwNotImplementedError("$bor"); return null; }
public LeoObject $band(int other) { throwNotImplementedError("$band"); return null; }
public LeoObject $index(double other) { throwNotImplementedError("$index"); return null; }
public LeoObject $bsl(double other) { throwNotImplementedError("$bsl"); return null; }
public LeoObject $bsr(double other) { throwNotImplementedError("$bsr"); return null; }
public LeoObject $xor(double other) { throwNotImplementedError("$xor"); return null; }
public LeoObject $bor(double other) { throwNotImplementedError("$bor"); return null; }
public LeoObject $band(double other) { throwNotImplementedError("$band"); return null; }
public LeoObject $index(long other) { throwNotImplementedError("$index"); return null; }
public LeoObject $bsl(long other) { throwNotImplementedError("$bsl"); return null; }
public LeoObject $bsr(long other) { throwNotImplementedError("$bsr"); return null; }
public LeoObject $xor(long other) { throwNotImplementedError("$xor"); return null; }
public LeoObject $bor(long other) { throwNotImplementedError("$bor"); return null; }
public LeoObject $band(long other) { throwNotImplementedError("$band"); return null; }
/**
* Sets a property on this object.
*
* @param key
* @param value
*/
public void setObject(LeoObject key, LeoObject value) {
throw new LeolaRuntimeException("AccessError: " + this + " is not a complex object; unable to access: '" + key + "'");
}
/**
* Sets a property on this object.
*
* @param key -- converts to a LeoString
* @param value
*/
public void setObject(String key, LeoObject value) {
setObject(LeoString.valueOf(key), value);
}
/**
* Similar to {@link LeoObject#getObject(LeoObject)} in every way, with the exception that
* this will throw a {@link LeolaRuntimeException} is the attribute is not found.
*
* @param key
* @return the object associated with the supplied key
* @throws LeolaRuntimeException if the key is not bound
*/
public LeoObject xgetObject(LeoObject key) throws LeolaRuntimeException {
throw new LeolaRuntimeException("AccessError: " + this + " is not a complex object; unable to access: '" + key + "'");
}
/**
* Similar to {@link LeoObject#getObject(String)} in every way, with the exception that
* this will throw a {@link LeolaRuntimeException} is the attribute is not found.
*
*
* @param key
* @return the object associated with the supplied key
* @throws LeolaRuntimeException if the key is not bound
*/
public LeoObject xgetObject(String key) throws LeolaRuntimeException {
return xgetObject(LeoString.valueOf(key));
}
/**
* Retrieves a property from this object. If this {@link LeoObject} supports associations, this
* will attempt to find the object with the associated key. If the key is not found, this will return {@link LeoObject#NULL}.
*
* @see LeoObject#xgetObject(LeoObject)
* @param key
* @return the associated object if found; otherwise {@link LeoObject#NULL}
*/
public LeoObject getObject(LeoObject key) {
throw new LeolaRuntimeException("AccessError: " + this + " is not a complex object; unable to access: '" + key + "'");
}
/**
* Retrieves a property from this object.
*
* @param key - converts to a LeoString
* @return
*/
public LeoObject getObject(String key) {
return getObject(LeoString.valueOf(key));
}
/**
* Determines if the supplied key has an associated value
*
* @param key
* @return true if the supplied key has an associated value, otherwise false
*/
public boolean hasObject(String key) {
return hasObject(LeoString.valueOf(key));
}
/**
* Determines if the supplied key has an associated value
*
* @param key
* @return true if the supplied key has an associated value, otherwise false
*/
public boolean hasObject(LeoObject key) {
throw new LeolaRuntimeException("AccessError: " + this + " is not a complex object; unable to access: '" + key + "'");
}
/**
* This is the equivalent of:
*
* <pre>
* LeoObject result = x.call().throwIfError();
* </pre>
*
* @return the result of invoking the function.
* @throws LeolaRuntimeException if the result of invoking the object returns a {@link LeoError}
*/
public LeoObject xcall() throws LeolaRuntimeException {
return call().throwIfError();
}
/**
* This is the equivalent of:
*
* <pre>
* LeoObject result = x.call(arg1).throwIfError();
* </pre>
*
* @param arg1 the first argument
* @return the result of invoking the function.
* @throws LeolaRuntimeException if the result of invoking the object returns a {@link LeoError}
*/
public LeoObject xcall(LeoObject arg1) throws LeolaRuntimeException {
return call(arg1).throwIfError();
}
/**
* This is the equivalent of:
*
* <pre>
* LeoObject result = x.call(arg1,arg2).throwIfError();
* </pre>
*
* @param arg1 the first argument
* @param arg2 the second argument
* @return the result of invoking the function.
* @throws LeolaRuntimeException if the result of invoking the object returns a {@link LeoError}
*/
public LeoObject xcall(LeoObject arg1, LeoObject arg2) throws LeolaRuntimeException {
return call(arg1, arg2).throwIfError();
}
/**
* This is the equivalent of:
*
* <pre>
* LeoObject result = x.call(arg1,arg2,arg3).throwIfError();
* </pre>
*
* @param arg1 the first argument
* @param arg2 the second argument
* @param arg3 the third argument
* @return the result of invoking the function.
* @throws LeolaRuntimeException if the result of invoking the object returns a {@link LeoError}
*/
public LeoObject xcall(LeoObject arg1, LeoObject arg2, LeoObject arg3) throws LeolaRuntimeException {
return call(arg1, arg2,arg3).throwIfError();
}
/**
* This is the equivalent of:
*
* <pre>
* LeoObject result = x.call(arg1,arg2,arg3,arg4).throwIfError();
* </pre>
*
* @param arg1 the first argument
* @param arg2 the second argument
* @param arg3 the third argument
* @param arg4 the fourth argument
* @return the result of invoking the function.
* @throws LeolaRuntimeException if the result of invoking the object returns a {@link LeoError}
*/
public LeoObject xcall(LeoObject arg1, LeoObject arg2, LeoObject arg3, LeoObject arg4) throws LeolaRuntimeException {
return call(arg1, arg2, arg3, arg4).throwIfError();
}
/**
* This is the equivalent of:
*
* <pre>
* LeoObject result = x.call(arg1,arg2,arg3,arg4,arg5).throwIfError();
* </pre>
*
* @param arg1 the first argument
* @param arg2 the second argument
* @param arg3 the third argument
* @param arg4 the fourth argument
* @param arg5 the fifth argument
* @return the result of invoking the function.
* @throws LeolaRuntimeException if the result of invoking the object returns a {@link LeoError}
*/
public LeoObject xcall(LeoObject arg1, LeoObject arg2, LeoObject arg3, LeoObject arg4, LeoObject arg5) throws LeolaRuntimeException {
return call(arg1, arg2, arg3, arg4, arg5).throwIfError();
}
/**
* This is the equivalent of:
*
* <pre>
* LeoObject result = x.call(args).throwIfError();
* </pre>
*
* @param args the argument list
* @return the result of invoking the function.
* @throws LeolaRuntimeException if the result of invoking the object returns a {@link LeoError}
*/
public LeoObject xcall(LeoObject[] args) throws LeolaRuntimeException {
return call(args).throwIfError();
}
/**
* Invokes the function
*
* @return the result of the function call
*/
public LeoObject call() {
throw new LeolaRuntimeException(this + " is not a function.");
}
/**
* Invokes the function
*
* @param arg1
* @return the result of the function call
*/
public LeoObject call(LeoObject arg1) {
throw new LeolaRuntimeException(this + " is not a function.");
}
/**
* Invokes the function
*
* @param arg1
* @param arg2
* @return the result of the function call
*/
public LeoObject call(LeoObject arg1, LeoObject arg2) {
throw new LeolaRuntimeException(this + " is not a function.");
}
/**
* Invokes the function
*
* @param arg1
* @param arg2
* @param arg3
* @return the result of the function call
*/
public LeoObject call(LeoObject arg1, LeoObject arg2, LeoObject arg3) {
throw new LeolaRuntimeException(this + " is not a function.");
}
/**
* Invokes the function
*
* @param arg1
* @param arg2
* @param arg3
* @param arg4
* @return the result of the function call
*/
public LeoObject call(LeoObject arg1, LeoObject arg2, LeoObject arg3, LeoObject arg4) {
throw new LeolaRuntimeException(this + " is not a function.");
}
/**
* Invokes the function
*
* @param arg1
* @param arg2
* @param arg3
* @param arg4
* @param arg5
* @return the result of the function call
*/
public LeoObject call(LeoObject arg1, LeoObject arg2, LeoObject arg3, LeoObject arg4, LeoObject arg5) {
throw new LeolaRuntimeException(this + " is not a function.");
}
/**
* Invokes the function
*
* @param args
* @return the result of the function call
*/
public LeoObject call(LeoObject[] args) {
throw new LeolaRuntimeException(this + " is not a function.");
}
/**
* @return this types value
*/
public abstract Object getValue();
/**
* Attempts to narrow the {@link LeoObject} to a more specific Java Type
* @param narrowType
* @return the Java Object
*/
public Object getValue(Class<?> narrowType) {
return this;
}
/**
* Determines if the supplied Java type can be assigned to this
* {@link LeoObject}.
*
* @param javaType
* @return true if the supplied type can be represented (assigned) to
* this {@link LeoObject}
*/
public boolean isAssignable(Class<?> javaType) {
Object obj = getValue();
if(obj!=null) {
return javaType.isAssignableFrom(obj.getClass());
}
return false;
}
/**
* @return a deep copy clone of this object
*/
@Override
public abstract LeoObject clone();
@Override
public int compareTo(LeoObject other) {
if(this.$lt(other)) {
return -1;
}
if(this.$gt(other)) {
return 1;
}
return 0;
}
/**
* @return the number of parameters this object takes
*/
public int getNumberOfArgs() {
return 0;
}
/**
* @return true if this function has variable arguments
*/
public boolean hasVarargs() {
return false;
}
/**
* Writes this object out
*
* @param out
* @throws IOException
*/
public abstract void write(DataOutput out) throws IOException;
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the reconstituted {@link LeoObject}
* @throws IOException
*/
public static LeoObject read(LeoObject env, DataInput in) throws IOException {
int type = in.readByte();
LeoType leoType = LeoType.fromOrdinal(type);
LeoObject result = null;
switch(leoType) {
case ARRAY: {
result = LeoArray.read(env, in);
break;
}
case BOOLEAN: {
result = LeoBoolean.read(env, in);
break;
}
case ERROR:
case CLASS: {
// result = LeoClass.read(env, symbols, in); TODO
break;
}
case GENERATOR: {
result = LeoGenerator.read(env, in);
break;
}
case FUNCTION: {
result = LeoFunction.read(env, in);
break;
}
case MAP: {
result = LeoMap.read(env, in);
break;
}
case NAMESPACE: {
break;
}
case NATIVE_CLASS: {
break;
}
case USER_FUNCTION:
case NATIVE_FUNCTION: {
break;
}
case NULL: {
result = LeoNull.read(in);
break;
}
case INTEGER: {
result = LeoInteger.read(in);
break;
}
case LONG: {
result = LeoLong.read(in);
break;
}
case REAL: {
result = LeoDouble.read(in);
break;
}
case STRING: {
result = LeoString.read(in);
break;
}
}
return result;
}
/**
* Throws a {@link LeolaRuntimeException} if this is a {@link LeoError} instance
*
* @return this object for method chaining
* @throws LeolaRuntimeException the underlying {@link LeoError}
*
*/
public LeoObject throwIfError() throws LeolaRuntimeException {
if(isError()) {
LeoError error = as();
throw new LeolaRuntimeException(error);
}
return this;
}
/**
* Throws a ClassNotFoundError
*
* @param message the error message
* @throws LeolaRuntimeException
*/
public static void throwClassNotFoundError(String message) throws LeolaRuntimeException {
throw new LeolaRuntimeException("NoClassDefinitionError: " + message);
}
/**
* Throws a MethodError
*
* @param message the error message
* @throws LeolaRuntimeException
*/
public static void throwMethodError(String message) throws LeolaRuntimeException {
throw new LeolaRuntimeException("MethodError: " + message);
}
/**
* Throws a NativeMethodError
*
* @param message the error message
* @throws LeolaRuntimeException
*/
public static void throwNativeMethodError(String message) throws LeolaRuntimeException {
throw new LeolaRuntimeException("NativeMethodError: " + message);
}
/**
* Throws a {@link LeolaRuntimeException} denoting a DivideByZeroError.
* @throws LeolaRuntimeException
*/
public static void throwDivideByZeroError() throws LeolaRuntimeException {
throw new LeolaRuntimeException("DivideByZeroError: Can't divide by zero.");
}
/**
* Throws a {@link LeolaRuntimeException} denoting a NotImplemetnedError.
* @throws LeolaRuntimeException
*/
public void throwNotImplementedError(String functionName) throws LeolaRuntimeException {
throw new LeolaRuntimeException("NotImplementedError: '" + getType() + "' does not implement the '" + functionName + "' method.");
}
/**
* Throws a {@link LeolaRuntimeException} denoting an AttributeError, stating that a requested attribute
* does not exist in the owned scope.
*
* @param name the name of the attribute
* @throws LeolaRuntimeException
*/
public void throwAttributeError(LeoObject name) throws LeolaRuntimeException {
if(isClass()) {
if(isNativeClass()) {
LeoNativeClass nClass = as();
throwAttributeError(nClass.getNativeClass(), name);
}
else {
LeoClass aClass = as();
throw new LeolaRuntimeException
("AttributeError: '" + aClass.getClassName() + "' has no attribute with the name '" + name + "'");
}
}
else if(isNamespace()) {
LeoNamespace namespace = as();
throw new LeolaRuntimeException
("AttributeError: '" + namespace.getName() + "' has no attribute with the name '" + name + "'");
}
else {
throw new LeolaRuntimeException
("AttributeError: No attribute found with the name '" + name + "'");
}
}
/**
* Throws a {@link LeolaRuntimeException} denoting an AttributeError, stating that a requested attribute
* does not exist in the owned scope and/or class.
*
* @param ownerClass the containing class in which the attribute was requested.
* @param name the name of the attribute
* @throws LeolaRuntimeException
*/
public static void throwAttributeError(Class<?> ownerClass, LeoObject name) throws LeolaRuntimeException {
throw new LeolaRuntimeException
("AttributeError: '" + ownerClass.getSimpleName() + "' has no attribute with the name '" + name + "'");
}
/**
* Throws a {@link LeolaRuntimeException} denoting an AttributeAccessError, stating that a requested attribute
* could not be accessed in the owned scope and/or class.
*
* @param ownerClass the containing class in which the attribute was requested.
* @param name the name of the attribute
* @throws LeolaRuntimeException
*/
public static void throwAttributeAccessError(Class<?> ownerClass, LeoObject name) throws LeolaRuntimeException {
throw new LeolaRuntimeException
("AttributeAccessError: '" + ownerClass.getSimpleName() + "' could not access attribute with the name '" + name + "'");
}
/**
* Rethrows the supplied {@link Throwable} as a {@link LeolaRuntimeException}
*
* @param t
* @throws LeolaRuntimeException
*/
public static void rethrow(Throwable t) throws LeolaRuntimeException {
throw new LeolaRuntimeException(t);
}
/**
* Determines if the supplied owner has a method by the supplied method name.
*
* @param owner
* @param methodName
* @return true if the supplied object (owner) has a method by the supplied name
*/
protected static boolean hasNativeMethod(Object owner, LeoObject methodName) {
return hasNativeMethod(owner.getClass(), methodName);
}
/**
* Determines if the supplied class has a method by the supplied method name.
*
* @param aClass
* @param methodName
* @return true if the supplied object (owner) has a method by the supplied name
*/
protected static boolean hasNativeMethod(Class<?> aClass, LeoObject methodName) {
List<Method> methods = ClassUtil.getMethodsByName(aClass, methodName.toString());
removeInterfaceMethods(methods);
return !methods.isEmpty();
}
/**
* Retrieve the native methods or fields from the owner public method listings. This will query the owner class
* using reflection if the supplied nativeApi {@link Map} is empty.
*
* @param ownerClass the class in which to inspect
* @param owner the instance in which owns the native methods; this may be null if looking for static methods
* @param nativeApi the cache of native methods
* @param key the method name
* @return the {@link LeoObject} of the native method, or null if not found
*/
protected static LeoObject getNativeMember(Class<?> ownerClass, Object owner, Map<LeoObject, LeoObject> nativeApi, LeoObject key) {
LeoObject func = nativeApi.get(key);
if (!LeoObject.isTrue(func)) {
synchronized (nativeApi) {
/* unsure that we don't override
* any previous thread's attempt at creating
* our native function
*/
func = nativeApi.get(key);
if (!LeoObject.isTrue(func)) {
String keyStr = key.toString();
List<Method> methods = ClassUtil.getMethodsByName(ownerClass, keyStr);
removeInterfaceMethods(methods);
if (methods.isEmpty()) {
methods = ClassUtil.getMethodsByAnnotationAlias(ownerClass, keyStr);
/* If there still isn't any methods by this name,
* check the classes field members
*/
if(methods.isEmpty()) {
Field field = ClassUtil.getInheritedField(ownerClass, keyStr);
if(field != null) {
try {
Object value = field.get(owner);
func = LeoObject.valueOf(value);
/* Do not cache this value, as it
* may change by calling methods
* on this native object, so we
* must grab the latest value
* every time
*/
//nativeApi.put(key, func);
return (func);
}
catch(Exception e) {
throwAttributeAccessError(ownerClass, key);
}
}
throwAttributeError(ownerClass, key);
}
}
func = new LeoNativeFunction(methods, owner);
nativeApi.put(key, func);
}
}
}
return func;
}
/**
* Retrieve the native methods from the owner public method listings. This will query the owner class
* using reflection if the supplied nativeApi {@link Map} is empty.
*
* @param ownerClass the class in which to inspect
* @param owner the instance in which owns the native methods; this may be null if looking for static methods
* @param nativeApi the cache of native methods
* @param key the method name
* @return the {@link LeoObject} of the native method, or null if not found
*/
protected static LeoObject getNativeMethod(Class<?> ownerClass, Object owner, Map<LeoObject, LeoObject> nativeApi, LeoObject key) {
LeoObject func = nativeApi.get(key);
if (!LeoObject.isTrue(func)) {
synchronized (nativeApi) {
/* unsure that we don't override
* any previous thread's attempt at creating
* our native function
*/
func = nativeApi.get(key);
if (!LeoObject.isTrue(func)) {
List<Method> methods = ClassUtil.getMethodsByName(ownerClass, key.toString());
removeInterfaceMethods(methods);
if (methods.isEmpty()) {
methods = ClassUtil.getMethodsByAnnotationAlias(ownerClass, key.toString());
if(methods.isEmpty()) {
throwAttributeError(ownerClass, key);
}
}
func = new LeoNativeFunction(methods, owner);
nativeApi.put(key, func);
}
}
}
return func;
}
/**
* Retrieve the native methods from the owner public method listings. This will query the owner class
* using reflection if the supplied nativeApi {@link Map} is empty.
*
* @param owner the instance in which owns the native methods; owner can not be null
* @param nativeApi the cache of native methods
* @param key the method name
* @return the {@link LeoObject} of the native method, or null if not found
*/
protected static LeoObject getNativeMethod(Object owner, Map<LeoObject, LeoObject> nativeApi, LeoObject key) {
return getNativeMethod(owner.getClass(), owner, nativeApi, key);
}
/**
* HACK - removes weird interface methods from the API listing.
* @param methods
*/
protected static void removeInterfaceMethods(List<Method> methods) {
if(methods.size() > 1) {
// This occurs when an implementation implements an interface
// with an overridden method, we want to grab the Overriding one
// and NOT the parent
// first determine that we indeed have multiple of the same
// method signature
String signature = methods.get(0).toGenericString();
for (int i = 1; i < methods.size(); i++) {
// if we have different method signatures, this just means
// we have overloaded methods
if(!signature.equals(methods.get(i).toGenericString())) {
return;
}
}
for (int i = 0; i < methods.size(); i++) {
Method method = methods.get(i);
boolean isOverride = method.isAnnotationPresent(LeolaMethod.class) ||
method.isAnnotationPresent(Override.class);
// if this method has the override or LeolaMethod
// annotations, this means it is our method that we want to
// use
if(isOverride) {
continue;
}
for (int j = 0; j < method.getParameterTypes().length; j++) {
Class<?> pType = method.getParameterTypes()[j];
if (pType.isPrimitive()) {
continue;
}
if (pType.equals(Object.class)) {
methods.remove(i);
i -= 1;
break;
}
}
}
}
}
}
<|start_filename|>src/leola/ast/CatchStmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* ON Statement:
*
* <pre>
* try
* stmt
* catch identifier
* stmt
* </pre>
*
* @author Tony
*
*/
public class CatchStmt extends Stmt {
private String identifier;
private Stmt body;
/**
* @param identifier
* @param body
*/
public CatchStmt(String identifier, Stmt body) {
super();
this.identifier = identifier;
this.body = body;
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the identifier
*/
public String getIdentifier() {
return identifier;
}
/**
* @return the body
*/
public Stmt getBody() {
return body;
}
}
<|start_filename|>src/leola/vm/types/LeoError.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Stack;
/**
* An Error object
*
* @author Tony
*
*/
public class LeoError extends LeoObject {
private LeoObject message;
private int lineNumber;
private String sourceFile;
private Stack<LeoError> stackTrace;
public LeoError(LeoObject message, int lineNumber) {
super(LeoType.ERROR);
this.message = message;
this.lineNumber = lineNumber;
this.stackTrace = new Stack<LeoError>();
}
/**
* @param message
*/
public LeoError(LeoObject message) {
this(message, -1);
}
public LeoError(Exception e) {
this(e.getMessage());
}
public LeoError(String msg) {
this(LeoString.valueOf(msg));
}
public LeoError(String msg, int lineNumber) {
this(LeoString.valueOf(msg), lineNumber);
}
public LeoError(int lineNumber) {
this(LeoString.valueOf(""), lineNumber);
}
public LeoError() {
this(LeoNull.LEONULL);
}
public void addStack(LeoError error) {
this.stackTrace.add(error);
}
/**
* @return the message
*/
public LeoObject getMessage() {
return message;
}
/**
* @param lineNumber the lineNumber to set
*/
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
/**
* @param sourceFile the sourceFile to set
*/
public void setSourceFile(String sourceFile) {
this.sourceFile = sourceFile;
}
/**
* @return the sourceFile
*/
public String getSourceFile() {
return sourceFile;
}
/**
* @return the lineNumber
*/
public int getLineNumber() {
return lineNumber;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isError()
*/
@Override
public boolean isError() {
return true;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#toString()
*/
@Override
public String toString() {
final String INDENT = " ";
StringBuilder sb = new StringBuilder();
sb.append("Error");
if(this.sourceFile!=null) {
sb.append(" <").append(this.sourceFile).append("> ");
}
/*if(lineNumber > 0) sb.append("Error: root cause on line: ").append(lineNumber);
else sb.append("Error: root cause: ");*/
if(lineNumber > 0) {
sb.append("@ line: ").append(lineNumber);
}
sb.append(" >> ").append(this.message);
sb.append("\n");
int tab = 0;
int size = stackTrace.size();
for(int i = 0; i < size; i++) {
LeoError error = stackTrace.get(i);
if(error.getLineNumber()>0) {
if(error.sourceFile!=null) {
sb.append("+-Thrown from ")
.append("<").append(error.sourceFile).append("> @ line: ")
.append(error.lineNumber);
}
else {
sb.append("+-Thrown from line: ").append(error.lineNumber);
}
}
else {
sb.append("+-Thrown: ");
}
String message = error.message.isNull() ? "" : error.message.toString();
if ( i < size-1 ) {
sb.append("\n");
for(int j = 0; j < tab; j++) sb.append(INDENT);
sb.append("|\n");
for(int j = 0; j < tab; j++) sb.append(INDENT);
sb.append("+--");
}
if( message!=null && !"".equals(message) ) {
sb.append(">>>").append(message);
}
tab++;
}
return sb.toString();
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$eq(leola.vm.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
if(this == other) {
return true;
}
if(other == null) {
return false;
}
if(getMessage().equals(other)) {
return true;
}
return false;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$lt(leola.vm.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$gt(leola.vm.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return new LeoError(this.message.clone(), this.lineNumber);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#write(java.io.DataOutput)
*/
@Override
public void write(DataOutput out) throws IOException {
out.write(this.getType().ordinal());
this.message.write(out);
out.writeInt(this.lineNumber);
}
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the {@link LeoObject}
* @throws IOException
*/
public static LeoError read(LeoObject env, DataInput in) throws IOException {
LeoObject message = LeoObject.read(env, in);
int lineNumber = in.readInt();
return new LeoError(message, lineNumber);
}
}
<|start_filename|>src/leola/vm/compiler/Label.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.compiler;
import java.util.Stack;
/**
* A Label to jmp instructions
*
* @author Tony
*
*/
public class Label {
private int index;
private Stack<Long> deltas;
private BytecodeEmitter asm;
public Label(BytecodeEmitter asm) {
this.asm = asm;
this.index = -1;
this.deltas = new Stack<Long>();
}
/**
* Sets the location of the label
*/
public void set() {
this.index = asm.getInstructionCount();
}
/**
* @return the index in the instruction list where
* this label is defined
*/
public int getLabelInstructionIndex() {
return index;
}
/**
* @return the deltas
*/
public Stack<Long> getDeltas() {
return deltas;
}
/**
* Marks an occurrence of the label (later calculates the
* jmp delta)
*
* @param opcode
*/
public void mark(int opcode) {
int instrIndex = this.asm.getInstructionCount() - 1;
int instr = opcode;
long delta = instrIndex;
delta = delta << 32 | instr;
this.deltas.push(delta);
}
}
<|start_filename|>src/leola/ast/SubscriptGetExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Accounts for array access expressions:
*
* <pre>
* array[10]
* </pre>
*
* @author Tony
*
*/
public class SubscriptGetExpr extends Expr {
/**
* element index
*/
private Expr elementIndex;
/**
* Variable name
*/
private Expr object;
/**
* @param elementIndex
*/
public SubscriptGetExpr(Expr object, Expr elementIndex) {
this.object = object;
this.elementIndex = becomeParentOf(elementIndex);
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public Expr getObject() {
return object;
}
/**
* @return the elementIndex
*/
public Expr getElementIndex() {
return elementIndex;
}
}
<|start_filename|>src/leola/vm/types/LeoGenerator.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import leola.vm.Leola;
import leola.vm.compiler.Bytecode;
/**
* A {@link LeoGenerator} is an object that behaves like a function, but
* is "resumeable" from a yield statement. That is, after successive invocations
* it will pick up executing the function after the yield statement.
*
* <p>
* Example:
* <pre>
* var talk = gen() {
* var i = 0
* yield "Hello: " + i
* i += 1
* yield "World: " + i
* }
*
* println( talk() ) // prints Hello: 0
* println( talk() ) // prints World: 1
* println( talk() ) // prints null, the function is done computing
*
* </pre>
*
* @author Tony
*
*/
public class LeoGenerator extends LeoFunction {
/**
* The locals that need to be saved with this
* generator
*/
private LeoObject[] locals;
/**
* @param type
* @param numberOfArgs
* @param body
*/
public LeoGenerator(Leola runtime, LeoObject env, Bytecode bytecode) {
super(runtime, LeoType.GENERATOR, env, bytecode);
this.locals = new LeoObject[bytecode.numLocals];
}
/**
* @return the locals
*/
public LeoObject[] getLocals() {
return locals;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isGenerator()
*/
@Override
public boolean isGenerator() {
return true;
}
/**
* Returns a sequence consisting of those items from the generator for which function(item) is true
*
* <pre>
* var count = def(to) {
* return gen() {
* var i = 0
* while i < to {
* yield i
* i += 1
* }
* }
* }
*
* filter(count(5), def(e) return e%2==0)
* .foreach(println)
*
* // prints:
* // 0
* // 2
* // 4
*
* </pre>
*
* @param function
* @return the resulting {@link LeoArray}
*/
public LeoArray filter(LeoObject function) {
LeoArray result = new LeoArray();
while(true) {
LeoObject generatorResult = xcall();
if(generatorResult == LeoNull.LEONULL) {
break;
}
if( LeoObject.isTrue(function.xcall(generatorResult))) {
result.add(generatorResult);
}
}
return result;
}
/**
* Iterates through the array, invoking the supplied
* function object for each element
*
* <pre>
* var count = def(to) {
* return gen() {
* var i = 0
* while i < to {
* yield i
* i += 1
* }
* }
* }
*
* foreach(count(5), println)
* // prints:
* // 0
* // 1
* // 2
* // 3
* // 4
*
* </pre>
*
* @param function
* @return the {@link LeoObject} returned from the supplied function if returned <code>true</code>
*/
public LeoObject foreach(LeoObject function) {
while(true) {
LeoObject generatorResult = xcall();
if(generatorResult == LeoNull.LEONULL) {
break;
}
LeoObject result = function.xcall(generatorResult);
if ( LeoObject.isTrue(result) ) {
return result;
}
}
return LeoObject.NULL;
}
/**
* Applies a function to each generator iteration.
*
* <pre>
* var count = def(to) {
* return gen() {
* var i = 0
* while i < to {
* yield i
* i += 1
* }
* }
* }
*
* map(count(5), def(e) return e + 10)
* .foreach(println)
* // prints:
* // 10
* // 11
* // 12
* // 13
* // 14
* </pre>
*
* @param function
* @return a {@link LeoArray} of results
*/
public LeoArray map(LeoObject function) {
LeoArray result = new LeoArray();
while(true) {
LeoObject generatorResult = xcall();
if(generatorResult == LeoNull.LEONULL) {
break;
}
result.add(function.xcall(generatorResult));
}
return result;
}
/**
* Reduces all of the elements in this generator into one value.
*
* <pre>
* var count = def(to) {
* return gen() {
* var i = 0
* while i < to {
* yield i
* i += 1
* }
* }
* }
* var sum = reduce(count(5), def(p,n) return p+n)
* println(sum) // 10
* </pre>
*
*
* @param function
* @return
*/
public LeoObject reduce(LeoObject function) {
LeoObject result = xcall();
if(result != LeoObject.NULL) {
while(true) {
LeoObject generatorResult = xcall();
if(generatorResult == LeoNull.LEONULL) {
break;
}
result = function.xcall(result, generatorResult);
}
}
return result;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoFunction#clone()
*/
@Override
public LeoObject clone() {
LeoGenerator clone = new LeoGenerator(this.runtime, this.env, getBytecode());
if(clone.outers!=null) {
for(int i = 0; i < clone.outers.length; i++) {
clone.outers[i] = this.outers[i];
}
}
return clone;
}
@Override
public void write(DataOutput out) throws IOException {
}
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the {@link LeoObject}
* @throws IOException
*/
public static LeoGenerator read(Leola runtime, LeoObject env, DataInput in) throws IOException {
Bytecode bytecode = Bytecode.read(env, in);
int nouters = in.readInt();
LeoObject[] outers = new LeoObject[nouters];
for(int i =0; i < nouters; i++) {
outers[i] = LeoObject.read(env, in);
}
LeoGenerator function = new LeoGenerator(runtime, env, bytecode);
return function;
}
}
<|start_filename|>src/leola/frontend/ErrorCode.java<|end_filename|>
package leola.frontend;
/**
* Leola error codes
*
* @author Tony
*
*/
public enum ErrorCode {
INVALID_ASSIGNMENT("Invalid assignment statement"),
INVALID_CHARACTER("Invalid character"),
INVALID_NUMBER("Invalid number"),
INVALID_VAR_ARGS_START("Invalid variable argument; must have variable name"),
INVALID_VAR_ARGS("Invalid variable argument; must be last argument"),
INVALID_MULTI_VAR_ARGS("Invalid variable argument; only one variable argument is allowed"),
INVALID_ARGS_EXPANSION("Invalid variable argument expansion; can only be used in function arguments"),
INVALID_NAMED_PARAMETER("Invalid name parameter expression"),
INVALID_MULTI_ARGS_EXPANSION("Invalid variable argument expansion; can only expand one argument"),
INVALID_CONTINUE_STMT("Invalid 'continue' use, must be inside a while loop"),
INVALID_BREAK_STMT("Invalid 'break' use, must be inside a while loop"),
INVALID_NAMESPACE_ACCESS("Invalid namespace access"),
MISSING_ARROW("Missing ->"),
MISSING_COMMA("Missing ,"),
MISSING_RIGHT_BRACE("Missing Right Brace"),
MISSING_EQUALS("Missing ="),
MISSING_IDENTIFIER("Missing identifier"),
MISSING_RIGHT_BRACKET("Missing ]"),
MISSING_RIGHT_PAREN("Missing )"),
MISSING_LEFT_PAREN("Missing ("),
MISSING_LEFT_BRACE("Missing {"),
MISSING_WHEN("Missing 'when'"),
MISSING_CATCH_OR_FINALLY("Missing an 'catch' or 'finally' block"),
MISSING_INTERFACE("Missing interface definition on class."),
MISSING_SEMICOLON("Missing semicolon after empty 'return' or 'yield' statement"),
RANGE_INTEGER("Integer literal out of range"),
RANGE_LONG("Long literal out of range"),
RANGE_REAL("Real literal out of range"),
UNEXPECTED_EOF("Unexpected end of file"),
UNEXPECTED_TOKEN("Unexpected token"),
UNIMPLEMENTED("Unimplemented feature"),
UNKNOWN_ERROR("An unknown error occured"),
// Fatal errors.
//IO_ERROR(-101, "Object I/O error"),
TOO_MANY_ERRORS(-102, "Too many syntax errors");
private int status; // exit status
private String message; // error message
/**
* Constructor.
* @param message the error message.
*/
ErrorCode(String message) {
this.status = 0;
this.message = message;
}
/**
* Constructor.
* @param status the exit status.
* @param message the error message.
*/
ErrorCode(int status, String message) {
this.status = status;
this.message = message;
}
/**
* Getter.
* @return the exit status.
*/
public int getStatus() {
return status;
}
/**
* @return the message.
*/
@Override
public String toString() {
return message;
}
}
<|start_filename|>src/leola/vm/util/LeoTypeConverter.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.util;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import leola.vm.Scope;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoBoolean;
import leola.vm.types.LeoDouble;
import leola.vm.types.LeoInteger;
import leola.vm.types.LeoLong;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoNativeClass;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
/**
* Converts Java types to Leola types and vice versa.
*
* @author Tony
*
*/
public class LeoTypeConverter {
public static interface Converter {
/**
* Coerces the supplied Java Object into the equivalent
* {@link LeoObject}
*
* @param type
* @param javaObj
* @return the LeoObject
*/
LeoObject convert(Class<?> type, Object javaObj);
/**
* Coerces the supplied {@link LeoObject} into the equivalent
* Java Object
*
* @param field
* @param type
* @param leoObj
* @return a new Java instance
*/
Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj);
}
private static final Map<Class<?>, Converter> CONVERTERS = new HashMap<Class<?>, LeoTypeConverter.Converter>();
static {
CONVERTERS.put(null, new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoNull.LEONULL;
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return null;
}
});
Converter stringConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoString.valueOf(javaObj.toString());
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj.toString();
}
};
CONVERTERS.put(String.class, stringConverter);
CONVERTERS.put(char.class, stringConverter);
CONVERTERS.put(Character.class, stringConverter);
// Boolean
Converter booleanConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return ((Boolean)javaObj) ? LeoBoolean.LEOTRUE
: LeoBoolean.LEOFALSE;
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return LeoObject.isTrue(leoObj);
}
};
CONVERTERS.put(boolean.class, booleanConverter);
CONVERTERS.put(Boolean.class, booleanConverter);
// Long
Converter longConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoLong.valueOf(((Number)javaObj).longValue());
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj.asLong();
}
};
CONVERTERS.put(long.class, longConverter);
CONVERTERS.put(Long.class, longConverter);
// integer
Converter integerConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoInteger.valueOf(((Number)javaObj).intValue());
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj.asInt();
}
};
CONVERTERS.put(byte.class, integerConverter);
CONVERTERS.put(Byte.class, integerConverter);
CONVERTERS.put(short.class, integerConverter);
CONVERTERS.put(Short.class, integerConverter);
CONVERTERS.put(int.class, integerConverter);
CONVERTERS.put(Integer.class, integerConverter);
// Double
Converter doubleConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoDouble.valueOf(((Number)javaObj).doubleValue());
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj.asDouble();
}
};
CONVERTERS.put(double.class, doubleConverter);
CONVERTERS.put(Double.class, doubleConverter);
CONVERTERS.put(float.class, doubleConverter);
CONVERTERS.put(Float.class, doubleConverter);
CONVERTERS.put(Number.class, doubleConverter);
// LeoObject converter
CONVERTERS.put(LeoObject.class, new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return (LeoObject) javaObj;
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj;
}
});
}
// Generic catch-all converter
private final static Converter objectConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
LeoObject result = null;
if ( ClassUtil.inheritsFrom(type, LeoObject.class)) {
result = (LeoObject)javaObj;
}
else if ( type.isArray() ) {
int len = Array.getLength(javaObj);
LeoArray array = new LeoArray(len);
for(int i = 0; i < len; i++) {
Object obj = Array.get(javaObj, i);
array.add(LeoObject.valueOf(obj));
}
result = array;
}
else {
result = new LeoNativeClass(type, javaObj);
}
return (result);
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return LeoObject.fromLeoObject(leoObj, type);
}
};
private final static Converter leolaConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return (LeoObject) javaObj;
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj;
}
};
private final static Converter listConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return null;
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
if(!leoObj.isArray()) {
throw new LeolaRuntimeException();
}
LeoArray array = leoObj.as();
Type genericType = field.getGenericType();
ParameterizedType paramType = (ParameterizedType) genericType;
Class<?> listType = ClassUtil.getRawType(paramType.getActualTypeArguments()[0]);
List<Object> result = new ArrayList<>(array.size());
for(int i = 0; i < array.size(); i++) {
LeoObject obj = array.get(i);
result.add(LeoObject.fromLeoObject(obj, listType));
}
return result;
}
};
private final static Converter mapConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return null;
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
TypeVariable<?>[] types = type.getTypeParameters();
Map<Object, Object> result = new HashMap<>();
Class<?> keyType = ClassUtil.getRawType(types[0]);
Class<?> valueType = ClassUtil.getRawType(types[1]);
LeoMap map = null;
if(leoObj.isScopedObject()) {
Scope scope = leoObj.getScope();
if(scope.hasObjects()) {
map = scope.getRawObjects();
}
else {
map = new LeoMap(1);
}
}
else if(leoObj.isMap()) {
map = leoObj.as();
}
else {
throw new LeolaRuntimeException();
}
for(int i = 0; i < map.bucketLength(); i++) {
LeoObject key = map.getKey(i);
LeoObject value = map.getValue(i);
if(key != null) {
result.put(LeoObject.fromLeoObject(key, keyType),
LeoObject.fromLeoObject(value, valueType));
}
}
return result;
}
};
private final static Converter enumConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoObject.valueOf(javaObj.toString());
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
Object[] constants = type.getEnumConstants();
String name = leoObj.toString();
for(int i = 0; i < constants.length; i++) {
if(constants[i].toString().equals(name)) {
return constants[i];
}
}
return null;
}
};
private static final Map<Class<?>, Converter> FROM_CONVERTERS = new HashMap<Class<?>, LeoTypeConverter.Converter>(CONVERTERS);
static {
Converter charConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoString.valueOf(javaObj.toString());
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj.toString().charAt(0);
}
};
FROM_CONVERTERS.put(char.class, charConverter);
FROM_CONVERTERS.put(Character.class, charConverter);
Converter byteConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoInteger.valueOf(((Number)javaObj).intValue());
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj.asByte();
}
};
FROM_CONVERTERS.put(byte.class, byteConverter);
FROM_CONVERTERS.put(Byte.class, byteConverter);
Converter shortConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoInteger.valueOf(((Number)javaObj).intValue());
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj.asShort();
}
};
FROM_CONVERTERS.put(short.class, shortConverter);
FROM_CONVERTERS.put(Short.class, shortConverter);
Converter floatConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoDouble.valueOf(((Number)javaObj).doubleValue());
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj.asFloat();
}
};
FROM_CONVERTERS.put(float.class, floatConverter);
FROM_CONVERTERS.put(Float.class, floatConverter);
FROM_CONVERTERS.put(List.class, listConverter);
FROM_CONVERTERS.put(Map.class, mapConverter);
Converter leolaConverter = new Converter() {
@Override
public LeoObject convert(Class<?> type, Object javaObj) {
return LeoObject.valueOf(javaObj);
}
@Override
public Object fromLeoObject(Field field, Class<?> type, LeoObject leoObj) {
return leoObj;
}
};
FROM_CONVERTERS.put(LeoObject.class, leolaConverter);
}
/**
* Converts the supplied java object into a {@link LeoObject}.
*
* @param javaObj
* @return
* @throws LeolaRuntimeException
*/
public static LeoObject convertToLeolaType(Object javaObj) {
LeoObject result = null;
if(javaObj == null) {
result = LeoNull.LEONULL;
}
else {
Class<?> type = javaObj.getClass();
Converter converter = CONVERTERS.get(type);
result = (converter!=null) ? converter.convert(type, javaObj)
: objectConverter.convert(type, javaObj);
}
return result;
}
/**
* Convert to the specified type.
*
* @param v
* @param type
* @param obj
* @throws Exception
*/
public static Object convertLeoObjectToJavaObj(Class<?> type
, LeoObject obj) throws LeolaRuntimeException {
Object jObj = null;
if(obj!=null) {
jObj = obj.getValue(type);
}
return jObj;
}
private static Converter getConverter(Class<?> type, Map<Class<?>, Converter> converters) {
Converter converter = converters != null
? converters.get(type) : null;
if(converter == null) {
converter = FROM_CONVERTERS.get(type);
}
if(LeoObject.class.isAssignableFrom(type)) {
converter = leolaConverter;
}
else if(List.class.isAssignableFrom(type)) {
converter = listConverter;
}
else if(Map.class.isAssignableFrom(type)) {
converter = mapConverter;
}
else if(type.isEnum()) {
converter = enumConverter;
}
return converter;
}
/**
* Creates a new Java object based on the supplied class type and populates it with the supplied {@link LeoObject}
*
* @param obj
* @param converters
* @param type
* @return the java object
*/
@SuppressWarnings("unchecked")
public static <T> T fromLeoObject(LeoObject obj, Map<Class<?>, Converter> converters, Class<T> type) {
try {
if(obj.isNativeClass()) {
return (T) obj.getValue(type);
}
Converter rootConverter = getConverter(type, converters);
if(rootConverter != null) {
return (T) rootConverter.fromLeoObject(null, type, obj);
}
T result = type.newInstance();
List<Field> fields = ClassUtil.getBeanFields(type);
for(Field field : fields) {
String fieldName = field.getName();
Class<?> fieldType = field.getType();
if(obj.hasObject(fieldName)) {
Converter converter = getConverter(fieldType, converters);
if(converter == null) {
converter = objectConverter;
}
ClassUtil.setFieldValue(result, field, converter.fromLeoObject(field, fieldType, obj.getObject(fieldName)));
}
}
return result;
}
catch (Exception e) {
throw new LeolaRuntimeException(e);
}
}
}
<|start_filename|>src/leola/vm/types/LeoUserFunction.java<|end_filename|>
/*
* see license.txt
*/
package leola.vm.types;
import java.io.DataOutput;
import java.io.IOException;
/**
* A user defined function. This allows one to write Java code:
*
* <pre>
* Leola runtime = ...
* LeoArray array = ...
* array.foreach( new LeoUserFunction() {
* public LeoObject call(LeoObject element) {
* System.out.println(element);
* }
* });
* </pre>
*
* @author Tony
*
*/
public class LeoUserFunction extends LeoObject {
/**
*/
public LeoUserFunction() {
super(LeoType.USER_FUNCTION);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isFunction()
*/
@Override
public boolean isFunction() {
return true;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$eq(leola.vm.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
return other==this;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$lt(leola.vm.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$gt(leola.vm.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return this;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#write(java.io.DataOutput)
*/
@Override
public void write(DataOutput out) throws IOException {
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#call()
*/
@Override
public LeoObject call() {
return call(new LeoObject[] {});
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#call(leola.vm.types.LeoObject)
*/
@Override
public LeoObject call(LeoObject arg1) {
return call(new LeoObject[] {arg1});
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#call(leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2) {
return call(new LeoObject[] {arg1, arg2});
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#call(leola.vm.types.LeoObject, leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2, LeoObject arg3) {
return call(new LeoObject[] {arg1, arg2, arg3});
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#call(leola.vm.types.LeoObject, leola.vm.types.LeoObject, leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2, LeoObject arg3, LeoObject arg4) {
return call(new LeoObject[] {arg1, arg2, arg3, arg4});
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#call(leola.vm.types.LeoObject, leola.vm.types.LeoObject, leola.vm.types.LeoObject, leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2, LeoObject arg3, LeoObject arg4, LeoObject arg5) {
return call(new LeoObject[] {arg1, arg2, arg3, arg4, arg5});
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#call(leola.vm.types.LeoObject[])
*/
@Override
public LeoObject call(LeoObject[] args) {
return LeoObject.NULL;
}
}
<|start_filename|>src/leola/ast/ElvisGetExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* @author Tony
*
*/
public class ElvisGetExpr extends GetExpr {
public ElvisGetExpr(Expr object, String identifier) {
super(object, identifier);
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
}
<|start_filename|>src/leola/ast/BooleanExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* @author Tony
*
*/
public class BooleanExpr extends Expr {
private boolean value;
/**
* @param value
*/
public BooleanExpr(boolean value) {
this.value = value;
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public boolean getValue() {
return this.value;
}
}
<|start_filename|>src/leola/frontend/Parser.java<|end_filename|>
package leola.frontend;
import static leola.frontend.tokens.TokenType.*;
import java.util.ArrayList;
import java.util.List;
import leola.ast.*;
import leola.frontend.tokens.Token;
import leola.frontend.tokens.TokenType;
import leola.vm.util.Pair;
/**
* A {@link Parser} for the Leola programming language.
*
* @author Tony
*
*/
public class Parser {
private final Scanner scanner;
private final List<Token> tokens;
private int current;
private int loopLevel;
private int argumentsLevel;
private Token startToken;
/**
* @param scanner
* the scanner to be used with this parser.
*/
public Parser(Scanner scanner) {
this.scanner = scanner;
this.tokens = scanner.getTokens();
this.current = 0;
this.loopLevel = 0;
this.argumentsLevel = 0;
}
/**
* Parse a source program and generate the intermediate code and the symbol
* table. To be implemented by a language-specific parser subclass.
*
*/
public ProgramStmt parse() {
List<Stmt> statements = new ArrayList<>();
while(!isAtEnd()) {
Stmt statement = statement();
statements.add(statement);
match(SEMICOLON); // eat any optional semi-colons
}
return new ProgramStmt(statements);
}
private Stmt statement() {
source();
if(match(CLASS)) return classDeclaration();
if(match(NAMESPACE)) return namespaceDeclaration();
if(match(VAR)) return varDeclaration();
if(match(IF)) return ifStatement();
if(match(WHILE)) return whileStatement();
if(match(SWITCH)) return switchStatement();
if(match(TRY)) return tryStatement();
if(match(THROW)) return throwStatement();
if(match(LEFT_BRACE))return blockStatement();
if(match(RETURN)) return returnStatement();
if(match(YIELD)) return yieldStatement();
if(match(BREAK)) return breakStatement();
if(match(CONTINUE)) return continueStatement();
if(match(SEMICOLON)) return emptyStatement();
return expression();
}
private ClassDeclStmt classDeclaration() {
Token className = consume(IDENTIFIER, ErrorCode.MISSING_IDENTIFIER);
ParameterList parameters = check(LEFT_PAREN)
? parameters() : new ParameterList();
String parentClassName = null;
List<Expr> parentClassArguments = null;
if(match(IS)) {
parentClassName = className();
match(LEFT_PAREN);
parentClassArguments = arguments();
}
Stmt body = check(SEMICOLON)
? emptyStatement() : statement();
return node(new ClassDeclStmt(className.getText(), parameters, body, parentClassName, parentClassArguments));
}
private NamespaceStmt namespaceDeclaration() {
Token name = consume(IDENTIFIER, ErrorCode.MISSING_IDENTIFIER);
Stmt body = statement();
return node(new NamespaceStmt(body, name.getText()));
}
private VarDeclStmt varDeclaration() {
Token name = consume(IDENTIFIER, ErrorCode.MISSING_IDENTIFIER);
Expr initializer = null;
if(match(EQUALS)) {
initializer = assignment();
}
return node(new VarDeclStmt(name.getText(), initializer));
}
private IfStmt ifStatement() {
Expr condition = expression();
Stmt thenBranch = statement();
Stmt elseBranch = null;
if (match(ELSE)) {
elseBranch = statement();
}
return node(new IfStmt(condition, thenBranch, elseBranch));
}
private WhileStmt whileStatement() {
Expr condition = expression();
try {
this.loopLevel++;
Stmt body = statement();
return node(new WhileStmt(condition, body));
}
finally {
this.loopLevel--;
}
}
private SwitchStmt switchStatement() {
Expr condition = null;
if(!check(WHEN) && !check(LEFT_BRACE)) {
condition = expression();
}
else {
condition = new BooleanExpr(true);
}
List<Pair<Expr, Stmt>> whenStmts = new ArrayList<>();
boolean hasBraces = match(LEFT_BRACE);
do {
consume(WHEN, ErrorCode.MISSING_WHEN);
Expr whenCond = expression();
consume(ARROW, ErrorCode.MISSING_ARROW);
Stmt stmt = statement();
whenStmts.add(new Pair<>(whenCond, stmt));
}
while(check(WHEN));
Stmt elseStmt = null;
if(match(ELSE)) {
elseStmt = statement();
}
if(hasBraces) {
consume(RIGHT_BRACE, ErrorCode.MISSING_RIGHT_BRACE);
}
return node(new SwitchStmt(condition, whenStmts, elseStmt));
}
private TryStmt tryStatement() {
Stmt body = statement();
CatchStmt catchBody = null;
Stmt finallyBody = null;
if(match(CATCH)) {
catchBody = catchStatement();
}
if(match(FINALLY)) {
finallyBody = statement();
}
return node(new TryStmt(body, catchBody, finallyBody));
}
private CatchStmt catchStatement() {
Token exceptionName = consume(IDENTIFIER, ErrorCode.MISSING_IDENTIFIER);
Stmt body = statement();
return node(new CatchStmt(exceptionName.getText(), body));
}
private ThrowStmt throwStatement() {
Expr value = expression();
return node(new ThrowStmt(value));
}
private EmptyStmt emptyStatement() {
return node(new EmptyStmt());
}
private ReturnStmt returnStatement() {
Expr value = null;
if(!check(SEMICOLON)) {
value = expression();
}
if(value == null) {
consume(SEMICOLON, ErrorCode.MISSING_SEMICOLON);
}
return node(new ReturnStmt(value));
}
private YieldStmt yieldStatement() {
Expr value = null;
if(!check(SEMICOLON)) {
value = expression();
}
if(value == null) {
consume(SEMICOLON, ErrorCode.MISSING_SEMICOLON);
}
return node(new YieldStmt(value));
}
private BreakStmt breakStatement() {
if(this.loopLevel < 1) {
throw error(previous(), ErrorCode.INVALID_BREAK_STMT);
}
match(SEMICOLON);
return node(new BreakStmt());
}
private ContinueStmt continueStatement() {
if(this.loopLevel < 1) {
throw error(previous(), ErrorCode.INVALID_CONTINUE_STMT);
}
match(SEMICOLON);
return node(new ContinueStmt());
}
private BlockStmt blockStatement() {
List<Stmt> statements = new ArrayList<>();
while(!check(RIGHT_BRACE) && !isAtEnd()) {
Stmt statement = statement();
statements.add(statement);
match(SEMICOLON); // eat any optional semi-colons
}
consume(RIGHT_BRACE, ErrorCode.MISSING_RIGHT_BRACE);
return node(new BlockStmt(statements));
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Expression parsing
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
private Expr expression() {
return assignment();
}
private Expr assignment() {
Expr expr = or();
if(match(EQUALS, PLUS_EQ, MINUS_EQ, STAR_EQ, SLASH_EQ,
MOD_EQ, BSL_EQ, BSR_EQ, BOR_EQ, BAND_EQ, BXOR_EQ)) {
Token operatorEquals = previous();
Expr value = assignment();
if(expr instanceof VarExpr) {
VarExpr varExpr = (VarExpr)expr;
return node(new AssignmentExpr(varExpr, value, operatorEquals));
}
else if(expr instanceof GetExpr) {
GetExpr getExpr = (GetExpr)expr;
return node(new SetExpr(getExpr.getObject(), getExpr.getIdentifier(), value, operatorEquals));
}
else if(expr instanceof SubscriptGetExpr) {
SubscriptGetExpr subscriptExpr = (SubscriptGetExpr)expr;
return node(new SubscriptSetExpr(subscriptExpr.getObject(), subscriptExpr.getElementIndex(), value, operatorEquals));
}
else if(expr instanceof NamespaceGetExpr) {
NamespaceGetExpr getExpr = (NamespaceGetExpr)expr;
return node(new NamespaceSetExpr(getExpr.getNamespace(), getExpr.getIdentifier(), value, operatorEquals));
}
throw error(operatorEquals, ErrorCode.INVALID_ASSIGNMENT);
}
return expr;
}
private Expr or() {
Expr expr = and();
while(match(LOGICAL_OR)) {
Token operator = previous();
Expr right = and();
expr = node(new BinaryExpr(expr, right, operator));
}
return expr;
}
private Expr and() {
Expr expr = equality();
while(match(LOGICAL_AND)) {
Token operator = previous();
Expr right = equality();
expr = node(new BinaryExpr(expr, right, operator));
}
return expr;
}
private Expr equality() {
Expr expr = comparison();
while(match(NOT_EQUALS, D_EQUALS, REF_EQUALS, REF_NOT_EQUALS)) {
Token operator = previous();
Expr right = comparison();
expr = node(new BinaryExpr(expr, right, operator));
}
return expr;
}
private Expr comparison() {
Expr expr = bitShift();
while(match(GREATER_THAN, GREATER_EQUALS, LESS_THAN, LESS_EQUALS)) {
Token operator = previous();
Expr right = bitShift();
expr = node(new BinaryExpr(expr, right, operator));
}
return expr;
}
private Expr bitShift() {
Expr expr = term();
while(match(BIT_SHIFT_LEFT, BIT_SHIFT_RIGHT)) {
Token operator = previous();
Expr right = term();
expr = node(new BinaryExpr(expr, right, operator));
}
return expr;
}
private Expr term() {
Expr expr = factor();
while(match(MINUS, PLUS)) {
Token operator = previous();
Expr right = factor();
expr = node(new BinaryExpr(expr, right, operator));
}
return expr;
}
private Expr factor() {
Expr expr = unary();
while(match(SLASH, STAR, MOD)) {
Token operator = previous();
Expr right = unary();
expr = node(new BinaryExpr(expr, right, operator));
}
return expr;
}
private Expr unary() {
if(match(NOT, MINUS, BITWISE_NOT) || (this.argumentsLevel > 0 && match(STAR)) ) {
Token operator = previous();
Expr right = unary();
return node(new UnaryExpr(right, operator));
}
return functionCall();
}
private Expr functionCall() {
Expr expr = primary();
while(true) {
if(match(LEFT_PAREN)) {
expr = finishFunctionCall(expr);
}
else if(match(LEFT_BRACKET)) {
Expr indexExpr = expression();
consume(RIGHT_BRACKET, ErrorCode.MISSING_RIGHT_BRACKET);
expr = node(new SubscriptGetExpr(expr, indexExpr));
}
else if(match(DOT)) {
Token name = consume(IDENTIFIER, ErrorCode.MISSING_IDENTIFIER);
expr = node(new GetExpr(expr, name.getText()));
}
else if(match(QUESTION_MARK)) {
Token name = consume(IDENTIFIER, ErrorCode.MISSING_IDENTIFIER);
expr = node(new ElvisGetExpr(expr, name.getText()));
}
else if(match(COLON)) {
VarExpr varExpr = null;
if((expr instanceof VarExpr)) {
varExpr = (VarExpr)expr;
}
else if(expr instanceof NamespaceGetExpr) {
NamespaceGetExpr getExpr = (NamespaceGetExpr)expr;
varExpr = new VarExpr(getExpr.getNamespace().getVarName() + ":" + getExpr.getIdentifier());
}
else {
throw error(previous(), ErrorCode.INVALID_NAMESPACE_ACCESS);
}
Token name = consume(IDENTIFIER, ErrorCode.MISSING_IDENTIFIER);
expr = node(new NamespaceGetExpr(varExpr, name.getText()));
}
else if(match(IS)) {
String name = className();
expr = node(new IsExpr(expr, name));
}
else if(this.argumentsLevel > 0 && match(FAT_ARROW)) {
if(!(expr instanceof VarExpr)) {
throw error(previous(), ErrorCode.INVALID_NAMED_PARAMETER);
}
VarExpr var = (VarExpr)expr;
Expr valueExpr = expression();
expr = node(new NamedParameterExpr(var.getVarName(), valueExpr));
}
else {
break;
}
}
return expr;
}
private Expr primary() {
source();
if(match(TRUE)) return node(new BooleanExpr(true));
if(match(FALSE)) return node(new BooleanExpr(false));
if(match(NULL)) return node(new NullExpr());
if(match(INTEGER)) return node(new IntegerExpr((int)previous().getValue()));
if(match(LONG)) return node(new LongExpr((long)previous().getValue()));
if(match(REAL)) return node(new RealExpr((double)previous().getValue()));
if(match(STRING)) return node(new StringExpr(previous().getValue().toString()));
if(match(IDENTIFIER)) return node(new VarExpr(previous().getText()));
if(match(LEFT_PAREN)) {
Expr expr = expression();
consume(RIGHT_PAREN, ErrorCode.MISSING_RIGHT_PAREN);
return expr;
}
if(match(CASE)) return caseExpression();
if(match(DEF)) return function();
if(match(GEN)) return generator();
if(match(AT)) return decorator();
if(match(LEFT_BRACKET)) return array();
if(match(LEFT_BRACE)) return map();
if(match(NEW)) return newInstance();
throw error(peek(), ErrorCode.UNEXPECTED_TOKEN);
}
private DecoratorExpr decorator() {
Token name = consume(IDENTIFIER, ErrorCode.MISSING_IDENTIFIER);
List<Expr> arguments = new ArrayList<>();
if(match(LEFT_PAREN)) {
arguments.addAll(arguments());
}
Expr decoratedExpr = expression();
return node(new DecoratorExpr(new VarExpr(name.getText()), arguments, decoratedExpr));
}
private FuncDefExpr function() {
ParameterList parameters = parameters();
Stmt body = statement();
return node(new FuncDefExpr(body, parameters));
}
private GenDefExpr generator() {
ParameterList parameters = parameters();
Stmt body = statement();
return node(new GenDefExpr(body, parameters));
}
private Expr finishFunctionCall(Expr callee) {
List<Expr> arguments = arguments();
return node(new FuncInvocationExpr(callee, arguments));
}
private CaseExpr caseExpression() {
Expr condition = null;
if(!check(WHEN) && !check(LEFT_BRACE)) {
condition = expression();
}
else {
condition = new BooleanExpr(true);
}
List<Pair<Expr, Expr>> whenStmts = new ArrayList<>();
boolean hasBraces = match(LEFT_BRACE);
do {
consume(WHEN, ErrorCode.MISSING_WHEN);
Expr whenCond = expression();
consume(ARROW, ErrorCode.MISSING_ARROW);
Expr expr = expression();
whenStmts.add(new Pair<>(whenCond, expr));
}
while(check(WHEN));
Expr elseExpr = null;
if(match(ELSE)) {
elseExpr = expression();
}
if(hasBraces) {
consume(RIGHT_BRACE, ErrorCode.MISSING_RIGHT_BRACE);
}
return node(new CaseExpr(condition, whenStmts, elseExpr));
}
private NewExpr newInstance() {
String className = className();
match(LEFT_PAREN);
List<Expr> arguments = arguments();
return node(new NewExpr(className, arguments));
}
private ArrayDeclExpr array() {
List<Expr> elements = new ArrayList<>();
do {
if(check(RIGHT_BRACKET)) {
break;
}
Expr element = expression();
elements.add(element);
}
while(match(COMMA));
consume(RIGHT_BRACKET, ErrorCode.MISSING_RIGHT_BRACKET);
return new ArrayDeclExpr(elements);
}
private MapDeclExpr map() {
List<Pair<Expr, Expr>> elements = new ArrayList<>();
do {
if(check(RIGHT_BRACE)) {
break;
}
Expr key = expression();
consume(ARROW, ErrorCode.MISSING_ARROW);
Expr value = expression();
elements.add(new Pair<>(key, value));
}
while(match(COMMA));
consume(RIGHT_BRACE, ErrorCode.MISSING_RIGHT_BRACE);
return new MapDeclExpr(elements);
}
/**
* Parses parameters:
*
* def(x,y,z) {
* }
*
* The (x,y,z) part
*
* @return the parsed {@link ParameterList}
*/
private ParameterList parameters() {
consume(LEFT_PAREN, ErrorCode.MISSING_LEFT_PAREN);
ParameterList parameters = new ParameterList();
if(!check(RIGHT_PAREN)) {
do {
parameters.addParameter(consume(IDENTIFIER, ErrorCode.MISSING_IDENTIFIER).getText());
if(check(VAR_ARGS)) {
if(parameters.isVarargs()) {
throw error(previous(), ErrorCode.INVALID_MULTI_VAR_ARGS);
}
advance();
parameters.setVarargs(true);
}
}
while(match(COMMA));
}
consume(RIGHT_PAREN, ErrorCode.MISSING_RIGHT_PAREN);
return parameters;
}
/**
* Parses arguments:
*
* someFunction( 1.0, x );
*
* Parses the ( 1.0, x ) into a {@link List} of {@link Expr}
*
* @return the {@link List} of {@link Expr}
*/
private List<Expr> arguments() {
List<Expr> arguments = new ArrayList<>();
if(!check(RIGHT_PAREN)) {
try {
this.argumentsLevel++;
do {
arguments.add(assignment());
}
while(match(COMMA));
}
finally {
this.argumentsLevel--;
}
}
consume(RIGHT_PAREN, ErrorCode.MISSING_RIGHT_PAREN);
return arguments;
}
/**
* Parses a class name, in leola a class name may be:
*
* identifier [(.|:) identifier]*
*
* @return the class name
*/
private String className() {
boolean requiresIdentifier;
StringBuilder className = new StringBuilder();
do {
Token classNamePart = consume(IDENTIFIER, ErrorCode.MISSING_IDENTIFIER);
className.append(classNamePart.getText());
requiresIdentifier = false;
if(check(DOT) || check(COLON)) {
className.append(advance().getText());
requiresIdentifier = true;
}
}
while(requiresIdentifier);
return className.toString();
}
/**
* Mark the start of parsing a statement
* so that we can properly mark the AST node
* source line and number information
*/
private void source() {
this.startToken = peek();
}
/**
* Updates the AST node parsing information
*
* @param node
* @return the supplied node
*/
private <T extends ASTNode> T node(T node) {
if(this.startToken != null) {
node.setSourceLine(this.startToken.getText());
node.setLineNumber(this.startToken.getLineNumber());
}
return node;
}
/**
* Determines if the supplied {@link TokenType} is
* the current {@link Token}, if it is it will advance
* over it.
*
* @param type
* @return true if we've advanced (i.e., the supplied token type was
* the current one).
*/
private boolean match(TokenType type) {
if(check(type)) {
advance();
return true;
}
return false;
}
/**
* Determines if any of the supplied {@link TokenType}'s are
* the current {@link Token}, if it is it will advance.
*
* @param type
* @return true if we've advanced (i.e., the supplied token type was
* the current one).
*/
private boolean match(TokenType ...types) {
for(TokenType type : types) {
if(check(type)) {
advance();
return true;
}
}
return false;
}
/**
* Ensures the supplied {@link TokenType} is the current one and
* advances. If the {@link TokenType} does not match, this will
* throw a {@link ParseException}
*
* @param type
* @param errorCode
* @return the skipped {@link Token}
*/
private Token consume(TokenType type, ErrorCode errorCode) {
if(check(type)) {
return advance();
}
throw error(peek(), errorCode);
}
/**
* Checks to see if the current {@link Token} is of the supplied
* {@link TokenType}
*
* @param type
* @return true if it is
*/
private boolean check(TokenType type) {
if(isAtEnd()) {
return false;
}
return peek().getType() == type;
}
/**
* Advances to the next Token. If we've reached
* the END_OF_FILE token, this stop advancing.
*
* @return the previous token.
*/
private Token advance() {
if(!isAtEnd()) {
this.current++;
}
return previous();
}
/**
* The previous token
* @return The previous token
*/
private Token previous() {
return this.tokens.get(current - 1);
}
/**
* The current token
* @return The current token
*/
private Token peek() {
return this.tokens.get(current);
}
/**
* If we've reached the end of the file
*
* @return true if we're at the end
*/
private boolean isAtEnd() {
return peek().getType() == END_OF_FILE;
}
/**
* Constructs an error message into a {@link ParseException}
*
* @param token
* @param errorCode
* @return the {@link ParseException} to be thrown
*/
private ParseException error(Token token, ErrorCode errorCode) {
int lineNumber = token.getLineNumber();
int position = token.getPosition();
String tokenText = token.getType() != TokenType.END_OF_FILE ? token.getText() : null;
String errorMessage = errorCode.toString();
int spaceCount = position + 1;
String currentLine = this.scanner.getSourceLine(lineNumber);
StringBuilder flagBuffer = new StringBuilder(currentLine != null ? currentLine : "");
flagBuffer.append("\n");
// Spaces up to the error position.
for (int i = 1; i < spaceCount; ++i) {
flagBuffer.append(' ');
}
// A pointer to the error followed by the error message.
flagBuffer.append("^\n*** ").append(errorMessage);
flagBuffer.append(" [at line: ").append(lineNumber);
// Text, if any, of the bad token.
if (tokenText != null) {
flagBuffer.append(" '").append(tokenText).append("'");
}
flagBuffer.append("]");
return new ParseException(errorCode, token, flagBuffer.toString());
}
}
<|start_filename|>src/leola/lang/DebugLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang;
import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.concurrent.atomic.AtomicBoolean;
import leola.vm.Args;
import leola.vm.Leola;
import leola.vm.compiler.Assembler;
import leola.vm.compiler.Bytecode;
import leola.vm.debug.DebugEvent;
import leola.vm.debug.DebugListener;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoClass;
import leola.vm.types.LeoFunction;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
/**
* The system core functions
*
* @author Tony
*
*/
public class DebugLeolaLibrary implements LeolaLibrary {
/**
* The runtime
*/
private Leola runtime;
/* (non-Javadoc)
* @see leola.frontend.LeolaLibrary#init(leola.frontend.Leola)
*/
@LeolaIgnore
public void init(Leola runtime, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = runtime;
this.runtime.putIntoNamespace(this, namespace);
}
/**
* Retrieves the {@link Bytecode} from the supplied object.
* @param f
* @return the bytecode
* @throws Exception
*/
public final Bytecode getbytecode(LeoObject f) throws Exception {
Bytecode result = null;
switch(f.getType()) {
case GENERATOR:
case FUNCTION: {
LeoFunction fun = f.as();
result = fun.getBytecode();
break;
}
case CLASS: {
LeoClass cls = f.as();
result = cls.getConstructor();
break;
}
default:
throw new LeolaRuntimeException("Unsupported type!");
}
return result;
}
/**
* Creates a {@link LeoFunction} based off of the supplied assembler code (string).
* @param asm
* @return the {@link LeoObject} function
* @throws Exception
*/
public LeoObject asm(LeoObject asm) throws Exception {
Assembler assember = new Assembler();
Bytecode code = assember.compile(new BufferedReader(new StringReader(asm.toString())));
return new LeoFunction(runtime, runtime.getGlobalNamespace(), code);
}
/**
* Attaches a debugger script. The script should return
* back a callback function that will be used to pass back
* the {@link DebugEvent}.
*
* @param filename the script file
*/
public void debugger(final String filename) throws Exception {
final File scriptFile = new File(filename);
runtime.setDebugListener(new DebugListener() {
Leola runtime = Args.builder()
.setIncludeDirectories(DebugLeolaLibrary.this.runtime.getIncludePath())
.setFileName(filename)
.newRuntime();
LeoObject fun = runtime.eval(scriptFile);
@Override
public void onLineNumber(DebugEvent event) {
fun.xcall(LeoObject.valueOf(event));
}
});
}
/**
* The assert function by default is disabled.
*/
private AtomicBoolean assertEnabled = new AtomicBoolean(false);
/**
* Toggles the Assert mechanism.
* @param enable
*/
public final void enableAssert(boolean enable) {
assertEnabled.set(enable);
}
/**
* Fail with an optional message. This exits the program.
* @param message
*/
public final void assertFail(String message) throws Exception {
if (assertEnabled.get()) {
throw new AssertionError(message);
}
}
/**
* Assert that obj is true
*
* @param obj
* @param message
* @throws Exception
*/
public final void assertTrue(LeoObject obj, String message) throws Exception {
if (assertEnabled.get()) {
if (!LeoObject.isTrue(obj)) {
assertFail("ASSERT FAIL: The object is not equal to true. " + message);
}
}
}
/**
* Assert that obj is false
*
* @param obj
* @param message
* @throws Exception
*/
public final void assertFalse(LeoObject obj, String message) throws Exception {
if (assertEnabled.get()) {
if (LeoObject.isTrue(obj)) {
assertFail("ASSERT FAIL: The object is not equal to true. " + message);
}
}
}
/**
* Assert that both objects are equal to each other.
*
* @param l
* @param r
* @param message
* @throws Exception
*/
public final void assertEq(LeoObject l, LeoObject r, String message) throws Exception {
if (assertEnabled.get()) {
if (l != null ) {
if ( ! l.$eq(r) ) {
assertFail("ASSERT FAIL: Left object (" + l + ") is not equal to the Right object (" + r + ") " + message);
}
}
else if ( r != null ) {
assertFail("ASSERT FAIL: Left object (null) is not equal to the Right object " + r + ") " + message);
}
}
}
/**
* Assert that the supplied object is not null.
*
* @param obj
* @param message
* @throws Exception
*/
public final void assertNotNull(LeoObject obj, String message) throws Exception {
if (assertEnabled.get()) {
if (obj == null || LeoNull.LEONULL == obj ) {
assertFail("ASSERT FAIL: The supplied object is null. " + message);
}
}
}
/**
* Assert that the supplied object is null.
*
* @param obj
* @param message
* @throws Exception
*/
public final void assertNull(LeoObject obj, String message) throws Exception {
if (assertEnabled.get()) {
if (obj != null && LeoNull.LEONULL != obj ) {
assertFail("ASSERT FAIL: The supplied object is not null. " + message);
}
}
}
}
<|start_filename|>src/leola/ast/AssignmentExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.frontend.tokens.Token;
import leola.vm.EvalException;
/**
* Assignment statement
*
* @author Tony
*
*/
public class AssignmentExpr extends Expr {
/**
* Var name
*/
private VarExpr var;
/**
* Expr to assign
*/
private Expr value;
private Token operator;
/**
* @param var
* @param value
*/
public AssignmentExpr(VarExpr var, Expr value, Token operator) {
this.var = var;
this.value = value;
this.operator = operator;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public VarExpr getVar() {
return var;
}
public Expr getValue() {
return value;
}
public Token getOperator() {
return operator;
}
}
<|start_filename|>src/leola/lang/sql/Conn.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.sql;
import java.sql.Connection;
import java.sql.Savepoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoNativeClass;
import leola.vm.types.LeoObject;
/**
* Represents a DatabaseConnection
* @author Tony
*
*/
public class Conn {
/**
* SQL connection
*/
private Connection sqlConn;
private Map<String, Savepoint> savepoints;
private LeoObject thisObject;
/**
* @param sqlConn
*/
public Conn(Connection sqlConn) throws Exception {
super();
this.sqlConn = sqlConn;
this.thisObject = new LeoNativeClass(this);
this.sqlConn.setAutoCommit(false);
this.savepoints = new ConcurrentHashMap<String, Savepoint>();
}
/**
* @return the sqlConn
*/
public Connection jdbc() {
return sqlConn;
}
public boolean isOpen() throws Exception {
return ! this.sqlConn.isClosed();
}
public void close() throws Exception {
if ( ! this.sqlConn.isClosed() ) {
this.sqlConn.close();
}
}
/**
* Executes the supplied function and will always close out the connection after executing it.
*
* @param function
* @return anything returned from the supplied function
* @throws Exception
*/
public LeoObject with(LeoObject function) throws Exception {
try {
return function.call(LeoObject.valueOf(this));
}
finally {
close();
}
}
public void commit() throws Exception {
this.sqlConn.commit();
}
public void rollback() throws Exception {
this.sqlConn.rollback();
}
public void rollbackTo(LeoObject savepoint) throws Exception {
String sp = savepoint.toString();
if ( ! this.savepoints.containsKey(sp) ) {
throw new IllegalArgumentException("No savepoint defined for: " + sp);
}
this.sqlConn.rollback(this.savepoints.get(sp));
}
public void savepoint(LeoObject savepoint) throws Exception {
String sp = savepoint.toString();
this.savepoints.put(sp, this.sqlConn.setSavepoint(sp));
}
public void releaseSavepoint(LeoObject savepoint) throws Exception {
String sp = savepoint.toString();
if ( ! this.savepoints.containsKey(sp) ) {
throw new IllegalArgumentException("No savepoint defined for: " + sp);
}
this.sqlConn.releaseSavepoint(this.savepoints.get(sp));
}
public Query query(LeoObject sql) {
String query = sql.toString();
ParsedSql parsedSql = SqlParameterParser.parseSqlStatement(query);
return new Query(this.sqlConn, parsedSql);
}
/**
* Streams the response.
*
* @param function
* @param sql
* @param params
* @param pageSize
* @throws Exception
*/
public void streamExecute(LeoObject function, LeoObject sql, LeoMap params, Integer pageSize) throws Exception {
Query aQuery = query(sql);
aQuery.params(params);
Savepoint savepoint = this.sqlConn.setSavepoint();
try {
aQuery.streamExecute(function, pageSize);
this.sqlConn.commit();
}
catch(Exception t) {
this.sqlConn.rollback(savepoint);
throw t;
}
finally {
aQuery.close();
}
}
/**
* Executes a read-only query.
*
* @param sql
* @param params
* @return the result set
* @throws Exception
*/
public LeoObject execute(LeoObject sql, LeoMap params, Integer maxResults) throws Exception {
Query aQuery = query(sql);
aQuery.params(params);
if(maxResults != null) {
aQuery.setMaxResults(maxResults);
}
LeoObject result = null;
Savepoint savepoint = this.sqlConn.setSavepoint();
try {
result = aQuery.execute();
this.sqlConn.commit();
}
catch(Exception t) {
this.sqlConn.rollback(savepoint);
throw t;
}
finally {
aQuery.close();
}
return result;
}
/**
* Executes a update statement
* @param sql
* @param params
* @return the number of rows updated
* @throws Exception
*/
public int update(LeoObject sql, LeoMap params) throws Exception {
Query aQuery = query(sql);
aQuery.params(params);
int result = 0;
Savepoint savepoint = this.sqlConn.setSavepoint();
try {
result = aQuery.update();
this.sqlConn.commit();
}
catch(Exception t) {
this.sqlConn.rollback(savepoint);
throw t;
}
finally {
aQuery.close();
}
return result;
}
/**
* Executes a block of code around a transaction.
*
* @param interpreter
* @param func
* @return
* @throws Exception
*/
public LeoObject transaction(LeoObject func) throws Exception {
LeoObject result = null;
Savepoint savepoint = this.sqlConn.setSavepoint();
try {
result = func.xcall(this.thisObject);
this.sqlConn.commit();
}
catch(Exception t) {
this.sqlConn.rollback(savepoint);
throw t;
}
return result;
}
}
<|start_filename|>src/leola/vm/types/LeoBoolean.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import leola.vm.util.ClassUtil;
/**
* Leola boolean value
*
* @author Tony
*
*/
public class LeoBoolean extends LeoObject {
/**
* True
*/
public static final LeoBoolean LEOTRUE = new LeoBoolean(true);
/**
* False
*/
public static final LeoBoolean LEOFALSE = new LeoBoolean(false);
/*
* Value
*/
private boolean value;
/**
* @param value
*/
private LeoBoolean(boolean value) {
super(LeoType.BOOLEAN);
this.value = value;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#hashCode()
*/
@Override
public int hashCode() {
return value ? 1231 : 1237;
}
@Override
public boolean isBoolean() {
return true;
}
@Override
public int asInt() {
return (isTrue()) ? 1 : 0;
}
@Override
public double asDouble() {
return (isTrue()) ? 1.0 : 0.0;
}
@Override
public long asLong() {
return (isTrue()) ? 1L : 0L;
}
/**
* @return true if this is an instance of True
*/
@Override
public boolean isTrue() {
return this.value;
}
/**
* @return true if this is an instance of False
*/
public boolean isFalse() {
return ! this.value;
}
/**
* Gets the instance of the boolean.
*
* @param value
* @return
*/
public static LeoBoolean valueOf(boolean value) {
return value ? LEOTRUE : LEOFALSE;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#toString()
*/
@Override
public String toString() {
return Boolean.toString(this.value);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#eq(leola.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
return (other != null) && (other.isTrue() == this.isTrue());
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gt(leola.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lt(leola.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this.isTrue();
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getValue(java.lang.Class)
*/
@Override
public Object getValue(Class<?> type) {
if(ClassUtil.isType(type, ClassUtil.BOOLEAN)) {
return isTrue();
}
else if ( ClassUtil.isType(type, ClassUtil.BYTE) ){
return (byte)(isTrue() ? 1 : 0);
}
else if ( ClassUtil.isType(type, ClassUtil.CHAR) ){
return (char)(isTrue() ? 1 : 0);
}
else if ( ClassUtil.isType(type, ClassUtil.SHORT) ){
return (short)(isTrue() ? 1 : 0);
}
else if ( ClassUtil.isType(type, ClassUtil.INT) ){
return (int)(isTrue() ? 1 : 0);
}
else if ( ClassUtil.isType(type, ClassUtil.FLOAT) ){
return (float)(isTrue() ? 1 : 0);
}
else if ( ClassUtil.isType(type, ClassUtil.DOUBLE) ){
return (double)(isTrue() ? 1 : 0);
}
else if ( ClassUtil.isType(type, ClassUtil.LONG) ){
return (long)(isTrue() ? 1 : 0);
}
else if ( ClassUtil.isType(type, ClassUtil.STRING) ){
return Boolean.toString(isTrue());
}
else if(ClassUtil.inheritsFrom(type, LeoObject.class) ) {
return this;
}
return isTrue();
}
@Override
public boolean isAssignable(Class<?> javaType) {
if(javaType.isPrimitive()) {
javaType = ClassUtil.primitiveToWrapper(javaType);
}
return Boolean.class.isAssignableFrom(javaType);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return this;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#add(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $add(LeoObject other) {
if ( other.isString() ) {
return LeoString.valueOf(this.value + other.toString());
}
return super.$add(other);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#bnot()
*/
@Override
public LeoObject $bnot() {
LeoObject result = this.value ? LEOFALSE : LEOTRUE;
return result;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#xor(leola.types.LeoObject)
*/
@Override
public LeoObject $xor(LeoObject other) {
LeoObject result = (this.value ^ LeoObject.isTrue(other)) ? LEOTRUE : LEOFALSE;
return result;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lor(leola.types.LeoObject)
*/
@Override
public LeoObject $bor(LeoObject other) {
LeoObject result = (this.value | LeoObject.isTrue(other)) ? LEOTRUE : LEOFALSE;
return result;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#land(leola.types.LeoObject)
*/
@Override
public LeoObject $band(LeoObject other) {
LeoObject result = (this.value & LeoObject.isTrue(other)) ? LEOTRUE : LEOFALSE;
return result;
}
@Override
public void write(DataOutput out) throws IOException {
out.write(this.getType().ordinal());
out.writeBoolean(this.value);
}
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the {@link LeoObject}
* @throws IOException
*/
public static LeoBoolean read(LeoObject env, DataInput in) throws IOException {
return in.readBoolean() ? LEOTRUE : LEOFALSE;
}
}
<|start_filename|>src/leola/frontend/tokens/NumberToken.java<|end_filename|>
package leola.frontend.tokens;
import static leola.frontend.ErrorCode.INVALID_NUMBER;
import static leola.frontend.ErrorCode.RANGE_INTEGER;
import static leola.frontend.ErrorCode.RANGE_LONG;
import static leola.frontend.ErrorCode.RANGE_REAL;
import static leola.frontend.tokens.TokenType.ERROR;
import static leola.frontend.tokens.TokenType.INTEGER;
import static leola.frontend.tokens.TokenType.LONG;
import static leola.frontend.tokens.TokenType.REAL;
import java.math.BigInteger;
import leola.frontend.Source;
/**
* Number Token, parses number formats
*
* @author Tony
*
*/
public class NumberToken extends Token {
private static final int MAX_EXPONENT = 37;
public NumberToken(Source source) {
super(source);
}
@Override
protected void extract() {
StringBuilder textBuffer = new StringBuilder(); // token's characters
extractNumber(textBuffer);
text = textBuffer.toString();
}
/**
* Extract a Leola number token from the source.
*
* @param textBuffer
* the buffer to append the token's characters.
*/
protected void extractNumber(StringBuilder textBuffer) {
String wholeDigits = null; // digits before the decimal point
String fractionDigits = null; // digits after the decimal point
String exponentDigits = null; // exponent digits
char exponentSign = '+'; // exponent sign '+' or '-'
boolean sawDotDot = false; // true if saw .. token
char currentChar; // current character
type = INTEGER; // assume INTEGER token type for now
// Extract the digits of the whole part of the number.
wholeDigits = unsignedIntegerDigits(textBuffer);
if (type == ERROR) {
return;
}
// Is there a . ?
// It could be a decimal point or the start of a .. token.
currentChar = this.source.currentChar();
if (currentChar == '.') {
if (this.source.peekChar() == '.') {
sawDotDot = true; // it's a ".." token, so don't consume it
}
else {
type = REAL; // decimal point, so token type is REAL
textBuffer.append(currentChar);
currentChar = this.source.nextChar(); // consume decimal point
// Collect the digits of the fraction part of the number.
if(Character.isDigit(currentChar)) {
fractionDigits = unsignedIntegerDigits(textBuffer);
if (type == ERROR) {
return;
}
}
}
}
else if (currentChar == 'L') {
type = LONG;
this.source.nextChar();
long longValue = computeLongValue(wholeDigits);
value = new Long(longValue);
return;
}
// Is there an exponent part?
// There cannot be an exponent if we already saw a ".." token.
currentChar = this.source.currentChar();
if (!sawDotDot && ((currentChar == 'E') || (currentChar == 'e'))) {
type = REAL; // exponent, so token type is REAL
textBuffer.append(currentChar);
currentChar = this.source.nextChar(); // consume 'E' or 'e'
// Exponent sign?
if ((currentChar == '+') || (currentChar == '-')) {
textBuffer.append(currentChar);
exponentSign = currentChar;
currentChar = this.source.nextChar(); // consume '+' or '-'
}
// Extract the digits of the exponent.
exponentDigits = unsignedIntegerDigits(textBuffer);
}
// Compute the value of an integer number token.
if (type == INTEGER) {
int integerValue = computeIntegerValue(wholeDigits);
if (type != ERROR) {
value = new Integer(integerValue);
}
else if (value == RANGE_INTEGER) {
type = LONG;
long longValue = computeLongValue(wholeDigits);
value = new Long(longValue);
}
}
// Compute the value of a real number token.
else if (type == REAL) {
double floatValue = computeFloatValue(wholeDigits, fractionDigits, exponentDigits, exponentSign);
if (type != ERROR) {
value = new Double(floatValue);
}
}
}
/**
* Extract and return the digits of an unsigned integer.
*
* @param textBuffer
* the buffer to append the token's characters.
* @return the string of digits.
*/
private String unsignedIntegerDigits(StringBuilder textBuffer) {
char currentChar = this.source.currentChar();
// Must have at least one digit.
if (!Character.isDigit(currentChar)) {
type = ERROR;
value = INVALID_NUMBER;
return null;
}
boolean isHex = false;
// Extract the digits.
StringBuilder digits = new StringBuilder();
while (Character.isDigit(currentChar) ||
('_' == currentChar) ||
('x' == currentChar && !isHex) ||
(isHex && isHexDigit(currentChar))) {
if ('x' == currentChar) {
isHex = true;
}
else if ('_' == currentChar) {
currentChar = this.source.nextChar(); // consume _
continue;
}
textBuffer.append(currentChar);
digits.append(currentChar);
currentChar = this.source.nextChar(); // consume digit
}
String digitsStr = digits.toString();
if(isHex) {
if(!digitsStr.startsWith("0x")) {
type = ERROR;
value = INVALID_NUMBER;
return null;
}
}
return digitsStr;
}
/**
* If the character is a Hex digit
*
* @param c
* @return
*/
private boolean isHexDigit(char c) {
return ((c >= 48 && c <= 57) || // 0 - 9
(c >= 65 && c <= 70) || // A - F
(c >= 97 && c <= 102) // a - f
);
}
/**
* Compute and return the integer value of a string of digits. Check for
* overflow.
*
* @param digits
* the string of digits.
* @return the integer value.
*/
private int computeIntegerValue(String digits) {
// Return 0 if no digits.
if (digits == null) {
return 0;
}
/* If it's a HEX number, parse it out */
if (digits.contains("0x")) {
if (digits.length() > "0xFFFFFFFF".length()) {
// Overflow: Set the integer out of range error.
type = ERROR;
value = RANGE_INTEGER;
return 0;
}
return new BigInteger(digits.replace("0x", ""), 16).intValue();
}
int integerValue = 0;
int prevValue = -1; // overflow occurred if prevValue > integerValue
int index = 0;
// Loop over the digits to compute the integer value
// as long as there is no overflow.
while ((index < digits.length()) && (integerValue >= prevValue)) {
prevValue = integerValue;
integerValue = 10 * integerValue + Character.getNumericValue(digits.charAt(index++));
}
// No overflow: Return the integer value.
if (integerValue >= prevValue) {
return integerValue;
}
// Overflow: Set the integer out of range error.
else {
type = ERROR;
value = RANGE_INTEGER;
return 0;
}
}
/**
* Compute and return the long value of a string of digits. Check for
* overflow.
*
* @param digits
* the string of digits.
* @return the integer value.
*/
private long computeLongValue(String digits) {
// Return 0 if no digits.
if (digits == null) {
return 0L;
}
/* If it's a HEX number, parse it out */
if (digits.contains("0x")) {
if (digits.length() > "0xFFFFFFFFFFFFFFFF".length()) {
// Overflow: Set the integer out of range error.
type = ERROR;
value = RANGE_LONG;
return 0L;
}
return Long.parseLong(digits.replace("0x", ""), 16);
}
long longValue = 0L;
long prevValue = -1L; // overflow occurred if prevValue > integerValue
int index = 0;
// Loop over the digits to compute the integer value
// as long as there is no overflow.
while ((index < digits.length()) && (longValue >= prevValue)) {
prevValue = longValue;
longValue = 10 * longValue + Character.getNumericValue(digits.charAt(index++));
}
// No overflow: Return the integer value.
if (longValue >= prevValue) {
return longValue;
}
// Overflow: Set the integer out of range error.
else {
type = ERROR;
value = RANGE_LONG;
return 0L;
}
}
/**
* Compute and return the float value of a real number.
*
* @param wholeDigits
* the string of digits before the decimal point.
* @param fractionDigits
* the string of digits after the decimal point.
* @param exponentDigits
* the string of exponent digits.
* @param exponentSign
* the exponent sign.
* @return the float value.
*/
private double computeFloatValue(String wholeDigits, String fractionDigits, String exponentDigits, char exponentSign) {
double floatValue = 0.0;
int exponentValue = computeIntegerValue(exponentDigits);
String digits = wholeDigits; // whole and fraction digits
// Negate the exponent if the exponent sign is '-'.
if (exponentSign == '-') {
exponentValue = -exponentValue;
}
// If there are any fraction digits, adjust the exponent value
// and append the fraction digits.
if (fractionDigits != null) {
exponentValue -= fractionDigits.length();
digits += fractionDigits;
}
// Check for a real number out of range error.
if (Math.abs(exponentValue + wholeDigits.length()) > MAX_EXPONENT) {
type = ERROR;
value = RANGE_REAL;
return 0.0f;
}
// Loop over the digits to compute the float value.
int index = 0;
while (index < digits.length()) {
floatValue = 10 * floatValue + Character.getNumericValue(digits.charAt(index++));
}
// Adjust the float value based on the exponent value.
if (exponentValue != 0) {
floatValue *= Math.pow(10, exponentValue);
}
return floatValue;
}
}
<|start_filename|>test/leola/SuiteTest.java<|end_filename|>
/*
* see license.txt
*/
package leola;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileFilter;
import org.junit.Test;
import leola.vm.Leola;
import leola.vm.types.LeoObject;
/**
* Runs all tests
*
* @author Tony
*
*/
public class SuiteTest {
@Test
public void test() {
File testsDir = new File(System.getProperty("user.dir"), "tests");
File[] testScripts = testsDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith("test.leola");
}
});
for(File testScript : testScripts) {
runTest(testScript);
}
}
private void runTest(File testScript) {
System.out.print("Running test: " + testScript + "...");
Leola leola = Leola.builder()
.setIsDebugMode(true)
.newRuntime();
try {
LeoObject result = leola.eval(testScript);
assertFalse(result.isError());
}
catch(AssertionError error) {
error.printStackTrace();
throw error;
}
catch(Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
System.out.println("passed!");
}
}
<|start_filename|>src/leola/ast/ClassDeclStmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.List;
import leola.vm.EvalException;
/**
* Class Declaration
*
* @author Tony
*
*/
public class ClassDeclStmt extends Stmt {
/**
* Class name
*/
private String className;
/**
* Class parameters
*/
private ParameterList classParameters;
/**
* Parent Class name
*/
private String parentClassName;
/**
* Parent classes params
*/
private List<Expr> parentClassArguments;
/**
* Class body
*/
private Stmt classBodyStmt;
/**
* @param className
* @param classParams
* @param classBodyStmt
* @param parentClassName
* @param interfaceNames
*/
public ClassDeclStmt(String className
, ParameterList classParams
, Stmt classBodyStmt
, String parentClassName
, List<Expr> parentClassArguments) {
this.className = className;
this.classParameters = classParams;
this.classBodyStmt = becomeParentOf(classBodyStmt);
this.parentClassName = parentClassName;
this.parentClassArguments = parentClassArguments;
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the className
*/
public String getClassName() {
return className;
}
/**
* @return the parentClassName
*/
public String getParentClassName() {
return parentClassName;
}
/**
* @return the classBodyStmt
*/
public Stmt getClassBodyStmt() {
return classBodyStmt;
}
/**
* @return the classParameters
*/
public ParameterList getClassParameters() {
return classParameters;
}
/**
* @return the parentClassArguments
*/
public List<Expr> getParentClassArguments() {
return parentClassArguments;
}
}
<|start_filename|>src/leola/ast/ProgramStmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.List;
import leola.vm.EvalException;
/**
* A program, the root node
*
* @author Tony
*
*/
public class ProgramStmt extends BlockStmt {
/**
*/
public ProgramStmt(List<Stmt> statements) {
super(statements);
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
}
<|start_filename|>src/leola/ast/GetExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* @author Tony
*
*/
public class GetExpr extends Expr {
private Expr object;
private String identifier;
public GetExpr(Expr object, String identifier) {
this.object = object;
this.identifier = identifier;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public Expr getObject() {
return object;
}
public String getIdentifier() {
return identifier;
}
}
<|start_filename|>src/leola/ast/DecoratorExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.List;
import leola.vm.EvalException;
/**
* Decorator expression
*
* @author Tony
*
*/
public class DecoratorExpr extends Expr {
private VarExpr decoratorName;
private List<Expr> arguments;
private Expr decoratedExpr;
/**
* @param decoratorName
* @param arguments
* @param decoratedExpr
*/
public DecoratorExpr(VarExpr decoratorName, List<Expr> arguments, Expr decoratedExpr) {
this.decoratorName = decoratorName;
this.arguments = arguments;
this.decoratedExpr = becomeParentOf(decoratedExpr);
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the decoratorName
*/
public VarExpr getDecoratorName() {
return decoratorName;
}
public Expr getDecoratedExpr() {
return decoratedExpr;
}
public List<Expr> getArguments() {
return arguments;
}
}
<|start_filename|>src/leola/vm/types/LeoArray.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.NoSuchElementException;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaMethod;
/**
* An expandable array that can act as a Stack or a randomly accessed array. The underlying implementation
* is almost identical to an {@link ArrayList}, the major difference is that it only accepts {@link LeoObject}'s
* as the contained object.
*
* <p>
* All optional methods are implemented from the {@link List} interface and {@link Iterator}.
*
* @author Tony
*
*/
public class LeoArray extends LeoObject implements List<LeoObject> {
/**
* Copies the elements of supplied {@link Collection} into a {@link LeoArray}.
*
* @param list the list of elements to be converted/copied into the {@link LeoArray}
* @return the new {@link LeoArray} containing the elements from the {@link Collection}
*/
public static LeoArray toArray(Collection<?> list) {
LeoArray array = new LeoArray(list.size());
for(Object o : list) {
array.add(LeoObject.valueOf(o));
}
return array;
}
/**
* Converts the raw array to a {@link LeoArray}
*
* @param leoObjects
* @return a new {@link LeoArray} consisting of the supplied objects
*/
public static LeoArray newLeoArray(LeoObject ...leoObjects ) {
LeoArray array = null;
if ( leoObjects != null ) {
array = new LeoArray(leoObjects);
}
else {
array = new LeoArray();
}
return array;
}
private LeoObject[] array;
private int size;
/**
*/
public LeoArray() {
this(10);
}
/**
* @param initialSize
*/
public LeoArray(int initialSize) {
super(LeoType.ARRAY);
this.size = 0;
this.array = new LeoObject[initialSize];
clear();
}
/**
* @param array
*/
public LeoArray(List<LeoObject> array) {
super(LeoType.ARRAY);
this.size = array.size();
this.array = new LeoObject[this.size];
for(int i = 0; i < this.size; i++) {
this.array[i] = array.get(i);
}
}
/**
* @param a
*/
public LeoArray(LeoObject[] a) {
this(a, a.length);
}
/**
* @param a
* @param size
*/
public LeoArray(LeoObject[] a, int size) {
super(LeoType.ARRAY);
this.array = a;
this.size = size;
}
/**
* Adds ability to reference the public API of this class
*/
private Map<LeoObject, LeoObject> arrayApi;
private Map<LeoObject, LeoObject> getApiMappings() {
if(this.arrayApi == null) {
synchronized (this) {
if(this.arrayApi == null) {
this.arrayApi = new LeoMap();
}
}
}
return this.arrayApi;
}
private LeoObject getNativeMethod(LeoObject key) {
return getNativeMethod(this, getApiMappings(), key);
}
/**
* Iterates through the array invoking the call back filling the
* array
*
* @param function
* @return this instance for method chaining
*/
public final LeoArray fill(LeoObject function) {
int size = size();
for(int i = 0; i < size; i++) {
LeoObject result = function.xcall(LeoInteger.valueOf(i));
set(i, result);
}
return this;
}
/**
* Iterates through the array given the supplied bounds
*
* <pre>
* [1,2,3,4].for(1,3,println)
* // prints
* // 2
* // 3
* </pre>
*
* @param startIndex
* @param endIndex
* @param function
*/
@LeolaMethod(alias="for")
public void _for(int startIndex, int endIndex, LeoObject function) {
if ( startIndex < 0 || endIndex > size()) {
throw new LeolaRuntimeException("Invalid array index: " + startIndex + " to " + endIndex + "[Size of array: " + size() + "]");
}
for(int i = startIndex; i < endIndex; i++) {
LeoObject result = function.xcall(get(i));
if ( LeoObject.isTrue(result) ) {
break;
}
}
}
/**
* Sorts the Array, it sorts it in place (meaning this will <b>not</b> allocate
* a new array, but rather sort this instance of the array).
*
* <pre>
* println( [1,5,2,87,324,4,2].sort(def(a,b) return a-b) )
* // prints:
* // [1,2,2,4,5,87,324]
*
* @param function
* @return this array sorted
*/
public LeoArray sort(final LeoObject function) {
if(function != null) {
Arrays.sort(this.array, 0, this.size, new Comparator<LeoObject>() {
@Override
public int compare(LeoObject o1, LeoObject o2) {
LeoObject result = function.xcall(o1, o2);
return result.asInt();
}
});
}
else {
Arrays.sort(this.array, 0, this.size);
}
return this;
}
/**
* Iterates through the array, invoking the supplied
* function object for each element
*
* <pre>
* [1,2,3].foreach(println)
* // prints:
* // 1
* // 2
* // 3
* </pre>
*
* @param function
* @return the {@link LeoObject} returned from the supplied function if returned <code>true</code>
*/
public LeoObject foreach(LeoObject function) {
if(function != null) {
for(int i = 0; i < this.size; i++) {
LeoObject obj = get(i);
LeoObject result = function.xcall(obj);
if(LeoObject.isTrue(result)) {
return result;
}
}
}
return LeoObject.NULL;
}
/**
* Filters the {@link LeoArray}
*
* <pre>
* var evens = [1,2,3,4].filter(def(e) {
* return e % 2 == 0
* })
* println(evens) // prints, 2, 4
* </pre>
*
* @param function
* @return a resulting {@link LeoArray}
*/
public LeoArray filter(LeoObject function) {
if(function != null) {
LeoArray array = new LeoArray();
for(int i = 0; i < this.size; i++) {
LeoObject obj = get(i);
if( LeoObject.isTrue(function.xcall(obj)) ) {
array.add(obj);
}
}
return array;
}
return this;
}
/**
* Maps the supplied function to each element in the array.
*
* <pre>
* var result = [1,2,3,4].map(def(e) return e*2)
* println(result) // 2, 4, 6, 8
* </pre>
*
* @param function
* @return
*/
public LeoArray map(LeoObject function) {
if(function != null) {
LeoArray array = new LeoArray(this.size);
for(int i = 0; i < this.size; i++) {
LeoObject obj = get(i);
LeoObject result = function.xcall(obj);
array.add(result);
}
return array;
}
return this;
}
/**
* Reduces all of the elements in this array into one value.
*
* <pre>
* var sum = [1,2,3,4].reduce(def(p,n) return p+n)
* println(sum) // 10
* </pre>
*
*
* @param function
* @return
*/
public LeoObject reduce(LeoObject function) {
if(function != null && !isEmpty()) {
LeoObject result = get(0);
for(int i = 1; i < this.size; i++) {
LeoObject obj = get(i);
result = function.xcall(result, obj);
}
return result;
}
return LeoNull.LEONULL;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#isArray()
*/
@Override
public boolean isArray() {
return true;
}
@Override
public boolean isAccessible() {
return true;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#toString()
*/
@Override
public String toString() {
if (this.array == null)
return "[]";
int iMax = this.size - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
LeoObject v = this.array[i];
if(v==null) {
b.append("null");
}
else if(v.isString()) {
b.append("\"").append(this.array[i].toString()).append("\"");
}
else if(v.isNull()) {
b.append("null");
}
else {
b.append(this.array[i].toString());
}
if (i >= iMax)
return b.append(']').toString();
b.append(", ");
}
}
/**
* Adds an object
* @param obj
*/
@Override
public LeoObject $add(LeoObject obj) {
add(obj);
return this;
}
public void addAll(LeoObject other) {
if ( other.isOfType(LeoType.ARRAY)) {
LeoArray aOther = other.as();
addAll((Collection<LeoObject>)aOther);
}
else {
$add(other);
}
}
/**
* Adds an object to the array
* @param obj
*/
public void push(LeoObject obj) {
add(obj);
}
/**
* Removes an object.
* @param obj
*/
@LeolaMethod(alias="remove")
public boolean remove(LeoObject obj) {
return this._remove(obj);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#sub(leola.types.LeoObject)
*/
@Override
public LeoObject $sub(LeoObject other) {
this._remove(other);
return this;
}
public void removeAll(LeoObject other) {
if ( other.isOfType(LeoType.ARRAY)) {
LeoArray aOther = other.as();
this.removeAll((Collection<?>)aOther);
}
else {
_remove(other);
}
}
/**
* Clears the array
*/
public void clear() {
for(int i = 0; i < this.size; i++ ) {
this.array[i] = LeoNull.LEONULL;
}
this.size = 0;
}
/**
* @return
*/
public LeoObject pop() {
return this.remove(this.size-1);
}
/**
* @return
*/
public LeoObject peek() {
return this.get(this.size-1);
}
/**
* Gets an element
* @param i
* @return
*/
@LeolaMethod(alias="get")
public LeoObject get(int i) {
return this.array[i];
}
/**
* @return the size of the array
*/
public int size() {
return this.size;
}
/**
* @return
*/
public boolean empty() {
return this.size == 0;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(double)
*/
@Override
public LeoObject $index(double other) {
return get( (int) other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(int)
*/
@Override
public LeoObject $index(int other) {
return get(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(long)
*/
@Override
public LeoObject $index(long other) {
return get( (int)other );
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $index(LeoObject other) {
return get(other.asInt());
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public void $sindex(LeoObject key, LeoObject other) {
set(key, other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#setObject(leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public void setObject(LeoObject key, LeoObject value) {
if(key.isNumber()) {
set(key,value);
}
else {
this.getApiMappings().put(key, value);
}
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getObject(leola.vm.types.LeoObject)
*/
@Override
public LeoObject getObject(LeoObject key) {
if(key.isNumber()) {
return get(key.asInt());
}
if(hasNativeMethod(this, key)) {
return getNativeMethod(key);
}
return LeoObject.NULL;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getObject(leola.vm.types.LeoObject)
*/
@Override
public LeoObject xgetObject(LeoObject key) {
if(key.isNumber()) {
return get(key.asInt());
}
return getNativeMethod(key);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#hasObject(leola.vm.types.LeoObject)
*/
@Override
public boolean hasObject(LeoObject key) {
return hasNativeMethod(this, key);
}
/**
* Sets an element
* @param index
* @param obj
*/
public LeoObject set(int index, LeoObject obj) {
return this.array[index] = obj;
}
/**
* Sets the element at the provided index
* @param index
* @param obj
*/
public void set(LeoObject index, LeoObject obj) {
this.array[index.asInt()] = obj;
}
public LeoObject reverse() {
LeoArray result = new LeoArray(this.size);
for(int i = this.size-1; i >=0; i--) {
result.add(get(i));
}
return result;
}
/**
* gets a sublist
* @param start
* @param end
* @return
*/
public LeoArray slice(int start, int end) {
if(start>end) {
throw new LeolaRuntimeException("Can't slice an array with start > end");
}
LeoObject[] slice = new LeoObject[end-start];
System.arraycopy(this.array, start, slice, 0, slice.length);
return new LeoArray(slice);
}
/**
* gets a sublist
* @param start
* @param end
* @return
*/
public LeoArray tail(int start) {
return slice(start, this.size);
}
/**
* @return the first element
*/
public LeoObject first() {
return this.array[0];
}
/**
* @return the last element
*/
public LeoObject last() {
if(this.array.length > 0) {
return this.array[this.size-1];
}
return LeoNull.LEONULL;
}
/**
* Truncates the first element and returns the rest of the array.
* @return
*/
public LeoObject rest() {
if (this.size < 2 ) return new LeoArray(0);
return slice(1, this.size);
}
/**
* @return the array
*/
public List<LeoObject> getArray() {
return this;
}
/**
* @param value
* @return
*/
public boolean has(LeoObject value) {
for(int i = 0; i < this.size; i++) {
LeoObject l = this.array[i];
if ( l != null && l.$eq(value)) {
return true;
}
}
return false;
}
/**
* @return a native array representation
*/
public LeoObject[] toArray() {
LeoObject[] clone = new LeoObject[this.size];
System.arraycopy(this.array, 0, clone, 0, clone.length);
return clone;
}
/**
* @return a native array representation
*/
public LeoObject[] getRawArray() {
return this.array;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return new LeoArray(this.array, this.size);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$bsl(double)
*/
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$bsl(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $bsl(LeoObject other) {
addAll(other);
return this;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$bsr(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $bsr(LeoObject other) {
removeAll(other);
return this;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$xor(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $xor(LeoObject other) {
return has(other) ? LeoBoolean.LEOTRUE : LeoBoolean.LEOFALSE;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$neq(leola.vm.types.LeoObject)
*/
@Override
public boolean $neq(LeoObject other) {
return ! $eq(other);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#eq(leola.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
if(other==this) {
return true;
}
if ( other != null && other.isOfType(LeoType.ARRAY)) {
LeoArray otherarray = other.as();
if ( otherarray.size == this.size) {
for(int i = 0; i < this.size; i++) {
LeoObject l = this.array[i];
LeoObject r = otherarray.array[i];
if ( ! LeoObject.$eq(l, r) ) {
return false;
}
}
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this; /*this.array;*/
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getValue(java.lang.Class)
*/
@Override
public Object getValue(Class<?> narrowType) {
if(narrowType.isArray()) {
Class<?> arrayType = narrowType.getComponentType();
Object array = Array.newInstance(arrayType, size());
for(int i = 0; i < size(); i++) {
Object javaElement = LeoObject.toJavaObject(arrayType, this.array[i]);
Array.set(array, i, javaElement);
}
return array;
}
return super.getValue(narrowType);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gt(leola.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lt(leola.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return false;
}
@Override
public void write(DataOutput out) throws IOException {
out.write(this.getType().ordinal());
out.writeInt(this.size);
for(int i = 0; i < this.size; i++) {
this.array[i].write(out);
}
}
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the {@link LeoObject}
* @throws IOException
*/
public static LeoArray read(LeoObject env, DataInput in) throws IOException {
int size = in.readInt();
LeoArray result = new LeoArray(size);
for(int i = 0; i < size; i++) {
LeoObject obj = LeoObject.read(env, in);
result.$add(obj);
}
return result;
}
/* (non-Javadoc)
* @see java.util.List#isEmpty()
*/
public boolean isEmpty() {
return this.size == 0;
}
/* (non-Javadoc)
* @see java.util.List#contains(java.lang.Object)
*/
@LeolaMethod(alias="contains")
public boolean contains(Object o) {
return this.has(LeoObject.valueOf(o));
}
/* (non-Javadoc)
* @see java.util.List#iterator()
*/
public Iterator<LeoObject> iterator() {
return new LeoArrayListIterator(this, 0);
}
/* (non-Javadoc)
* @see java.util.List#toArray(T[])
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if(a.length < this.size) {
a = (T[])Array.newInstance(a.getClass().getComponentType(), this.size);
}
for(int i = 0; i < this.size; i++) {
a[i] = (T)this.array[i].getValue();
}
return a;
}
private void ensureCapacity(int minCapacity) {
int oldCapacity = this.array.length;
if (minCapacity > oldCapacity) {
LeoObject oldData[] = this.array;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity) newCapacity = minCapacity;
this.array = new LeoObject[newCapacity];
System.arraycopy(oldData, 0, this.array, 0, oldCapacity);
for(int i = this.size; i < newCapacity; i++) {
this.array[i] = LeoNull.LEONULL;
}
}
}
/* (non-Javadoc)
* @see java.util.List#add(java.lang.Object)
*/
public boolean add(LeoObject e) {
ensureCapacity(this.size + 1);
this.array[this.size++] = e;
return true;
}
/* (non-Javadoc)
* @see java.util.List#remove(java.lang.Object)
*/
public boolean remove(Object o) {
return _remove(o);
}
private boolean _remove(Object o) {
for (int index = 0; index < size; index++) {
if (o.equals(this.array[index])) {
fastRemove(index);
return true;
}
}
return false;
}
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(array, index+1, array, index,
numMoved);
array[--size] = LeoNull.LEONULL;
}
/* (non-Javadoc)
* @see java.util.List#containsAll(java.util.Collection)
*/
public boolean containsAll(Collection<?> c) {
boolean containsAll = true;
for(Object o : c) {
if( ! contains(o) ) {
return false;
}
}
return containsAll;
}
/* (non-Javadoc)
* @see java.util.List#addAll(java.util.Collection)
*/
public boolean addAll(Collection<? extends LeoObject> c) {
ensureCapacity(this.size + c.size());
for(LeoObject o : c) {
this.add(o);
}
return true;
}
/* (non-Javadoc)
* @see java.util.List#addAll(int, java.util.Collection)
*/
public boolean addAll(int index, Collection<? extends LeoObject> c) {
ensureCapacity(this.size + c.size());
for(LeoObject o : c) {
add(index++, o);
}
return true;
}
/* (non-Javadoc)
* @see java.util.List#removeAll(java.util.Collection)
*/
public boolean removeAll(Collection<?> c) {
for(Object o : c) {
this._remove(o);
}
return true;
}
/* (non-Javadoc)
* @see java.util.List#retainAll(java.util.Collection)
*/
public boolean retainAll(Collection<?> c) {
List<LeoObject> objectsToRemove = new ArrayList<LeoObject>();
for(int i = 0; i < this.size; i++) {
LeoObject o = this.array[i];
if(o != null) {
if(!c.contains(o)) {
objectsToRemove.add(o);
}
}
}
return this.removeAll(objectsToRemove);
}
/* (non-Javadoc)
* @see java.util.List#add(int, java.lang.Object)
*/
public void add(int index, LeoObject element) {
ensureCapacity(size+1);
System.arraycopy(this.array, index, this.array, index + 1, size - index);
this.array[index] = element;
size++;
}
/* (non-Javadoc)
* @see java.util.List#remove(int)
*/
public LeoObject remove(int index) {
LeoObject oldValue = this.array[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(this.array, index+1, this.array, index, numMoved);
this.array[--size] = LeoNull.LEONULL;
return oldValue;
}
/* (non-Javadoc)
* @see java.util.List#indexOf(java.lang.Object)
*/
public int indexOf(Object o) {
for (int i = 0; i < size; i++) {
if (o.equals(this.array[i]))
return i;
}
return -1;
}
/* (non-Javadoc)
* @see java.util.List#lastIndexOf(java.lang.Object)
*/
public int lastIndexOf(Object o) {
for (int i = size-1; i >= 0; i--) {
if (o.equals(this.array[i]))
return i;
}
return -1;
}
/* (non-Javadoc)
* @see java.util.List#listIterator()
*/
public ListIterator<LeoObject> listIterator() {
return new LeoArrayListIterator(this, 0);
}
/* (non-Javadoc)
* @see java.util.List#listIterator(int)
*/
public ListIterator<LeoObject> listIterator(int index) {
return new LeoArrayListIterator(this, index);
}
/* (non-Javadoc)
* @see java.util.List#subList(int, int)
*/
public List<LeoObject> subList(int fromIndex, int toIndex) {
return slice(fromIndex, toIndex);
}
static class LeoArrayListIterator implements ListIterator<LeoObject> {
private int cursor;
private int lastRet;
private LeoArray array;
/**
*
*/
public LeoArrayListIterator(LeoArray leoArray, int index) {
this.array = leoArray;
this.cursor = index;
this.lastRet = -1;
}
@Override
public boolean hasNext() {
return cursor < array.size;
}
@Override
public LeoObject next() {
int i = cursor;
if (i >= array.size)
throw new NoSuchElementException();
cursor = i + 1;
return array.array[(lastRet = i)];
}
@Override
public boolean hasPrevious() {
return cursor > 0;
}
@Override
public LeoObject previous() {
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
cursor = i;
return array.array[(lastRet = i)];
}
@Override
public int nextIndex() {
return cursor;
}
@Override
public int previousIndex() {
return cursor-1;
}
@Override
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
try {
array.remove(lastRet);
cursor = lastRet;
lastRet = -1;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
public void set(LeoObject e) {
if (lastRet < 0)
throw new IllegalStateException();
try {
array.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
public void add(LeoObject e) {
try {
int i = cursor;
array.add(i, e);
cursor = i + 1;
lastRet = -1;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
};
}
<|start_filename|>src/leola/vm/types/LeoOuterObject.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import leola.vm.compiler.Outer;
/**
* An object that can carry closure values along with it.
*
* @author Tony
*
*/
public abstract class LeoOuterObject extends LeoObject {
/**
* Dummy var
*/
public static final Outer[] NOOUTERS = {};
/**
* Any closure values
*/
protected Outer[] outers;
/**
* @param type
*/
public LeoOuterObject(LeoType type, int numberOfOuters) {
super(type);
this.outers = numberOfOuters>0 ? new Outer[numberOfOuters] : NOOUTERS;
}
/**
* @return true
*/
public boolean isOuter() {
return true;
}
/**
* @return the outers
*/
public Outer[] getOuters() {
return outers;
}
}
<|start_filename|>src/leola/ast/FuncDefExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* @author Tony
*
*/
public class FuncDefExpr extends Expr {
/**
* Body
*/
private Stmt body;
/**
* Parameters
*/
private ParameterList parameters;
/**
* @param body
* @param parameters
*/
public FuncDefExpr(Stmt body, ParameterList parameters) {
this.body = becomeParentOf(body);
this.parameters = parameters;
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the body
*/
public Stmt getBody() {
return body;
}
/**
* @return the parameters
*/
public ParameterList getParameters() {
return parameters;
}
}
<|start_filename|>src/leola/ast/BlockStmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.List;
import leola.vm.EvalException;
/**
* A statement composed of two statements
*
* @author Tony
*
*/
public class BlockStmt extends Stmt {
private List<Stmt> statements;
/**
*/
public BlockStmt(List<Stmt> statements) {
this.statements = statements;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public List<Stmt> getStatements() {
return statements;
}
}
<|start_filename|>src/leola/ast/ASTNodeVisitor.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Node Visitor
*
* @author Tony
*
*/
public interface ASTNodeVisitor {
void visit(SubscriptGetExpr s) throws EvalException;
void visit(SubscriptSetExpr s) throws EvalException;
void visit(ArrayDeclExpr s) throws EvalException;
void visit(MapDeclExpr s) throws EvalException;
void visit(AssignmentExpr s) throws EvalException;
void visit(BinaryExpr s) throws EvalException;
void visit(BooleanExpr s) throws EvalException;
void visit(BreakStmt s) throws EvalException;
void visit(CaseExpr s) throws EvalException;
void visit(ClassDeclStmt s) throws EvalException;
void visit(BlockStmt s) throws EvalException;
void visit(ContinueStmt s) throws EvalException;
void visit(DecoratorExpr s) throws EvalException;
void visit(NamespaceStmt s) throws EvalException;
void visit(CatchStmt s) throws EvalException;
void visit(RealExpr s) throws EvalException;
void visit(IntegerExpr s) throws EvalException;
void visit(LongExpr s) throws EvalException;
void visit(ProgramStmt s) throws EvalException;
void visit(IsExpr s) throws EvalException;
void visit(EmptyStmt s) throws EvalException;
void visit(GenDefExpr s) throws EvalException;
void visit(FuncDefExpr s) throws EvalException;
void visit(FuncInvocationExpr s) throws EvalException;
void visit(IfStmt s) throws EvalException;
void visit(NamespaceGetExpr s) throws EvalException;
void visit(NamespaceSetExpr s) throws EvalException;
void visit(ElvisGetExpr s) throws EvalException;
void visit(GetExpr s) throws EvalException;
void visit(SetExpr s) throws EvalException;
void visit(NamedParameterExpr s) throws EvalException;
void visit(NewExpr s) throws EvalException;
void visit(NullExpr s) throws EvalException;
void visit(ReturnStmt s) throws EvalException;
void visit(YieldStmt s) throws EvalException;
void visit(StringExpr s) throws EvalException;
void visit(SwitchStmt s) throws EvalException;
void visit(TryStmt s) throws EvalException;
void visit(ThrowStmt s) throws EvalException;
void visit(UnaryExpr s) throws EvalException;
void visit(VarDeclStmt s) throws EvalException;
void visit(VarExpr s) throws EvalException;
void visit(WhileStmt s) throws EvalException;
}
<|start_filename|>src/leola/lang/MapLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoObject;
/**
* Standard Map operations
*
* @author Tony
*
*/
public class MapLeolaLibrary implements LeolaLibrary {
private Leola runtime;
/* (non-Javadoc)
* @see leola.vm.lib.LeolaLibrary#init(leola.vm.Leola)
*/
@Override
@LeolaIgnore
public void init(Leola runtime, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = runtime;
this.runtime.putIntoNamespace(this, namespace);
}
public LeoObject foreach(LeoMap map, LeoObject function) {
return map.foreach(function);
}
public void put(LeoMap map, LeoObject key, LeoObject value) {
map.put(key, value);
}
public LeoObject remove(LeoMap map, LeoObject key) {
return map.remove(key);
}
public LeoObject get(LeoMap map, LeoObject key) {
return map.get(key);
}
public boolean has(LeoMap map, LeoObject key) {
return map.has(key);
}
public void putAll(LeoMap map, LeoObject values) {
map.putAllEntries(values);
}
public void removeAll(LeoMap map, LeoObject values) {
map.removeAllEntries(values);
}
public int size(LeoMap map) {
return map.size();
}
public boolean empty(LeoMap map) {
return map.empty();
}
public void clear(LeoMap map) {
map.clear();
}
public LeoObject keys(LeoMap map) {
return map.keys();
}
public LeoObject values(LeoMap map) {
return map.vals();
}
public LeoObject clone(LeoMap map) {
return map.clone();
}
}
<|start_filename|>src/leola/ast/ArrayDeclExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.List;
import leola.vm.EvalException;
/**
* Array declaration expression.
*
* <pre>
* var array = [ 1, 2, 3 ]
* </pre>
*
* @author Tony
*
*/
public class ArrayDeclExpr extends Expr {
/**
* Elements
*/
private List<Expr> elements;
/**
* @param elements
*/
public ArrayDeclExpr(List<Expr> elements) {
this.elements = elements;
if(elements!=null) {
for(int i = 0; i < this.elements.size(); i++) {
becomeParentOf( this.elements.get(i) );
}
}
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the elements
*/
public List<Expr> getElements() {
return elements;
}
}
<|start_filename|>src/leola/vm/VM.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm;
import static leola.vm.Opcodes.*;
import java.util.ArrayList;
import java.util.List;
import leola.vm.Scope.ScopeType;
import leola.vm.compiler.Bytecode;
import leola.vm.compiler.Outer;
import leola.vm.compiler.Outer.StackValue;
import leola.vm.debug.DebugEvent;
import leola.vm.debug.DebugListener;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoBoolean;
import leola.vm.types.LeoClass;
import leola.vm.types.LeoError;
import leola.vm.types.LeoFunction;
import leola.vm.types.LeoGenerator;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoScopedObject;
import leola.vm.util.ClassUtil;
/**
* The {@link VM} (i.e., the Virtual Machine) is responsible for executing the Leola bytecode. The current implementation uses a <code>stack</code>
* in order to operate. The stack is shared amongst the call stack. An important implementation detail is that if you are using a shared {@link Leola}
* runtime instance, in order to be thread-safe, you must configure it to use {@link ThreadLocal}'s (via {@link Args#allowThreadLocal()}). By enabling the
* use of {@link ThreadLocal}, a {@link VM} instance will be created per thread. Please note, this does not fully guarantee thread-safety as the {@link Scope}
* containers are still shared amongst threads, i.e., assigning scoped variables is not atomic.
*
* <p>
*
* <h2>The Stack</h2>
*
* The VM attempts to optimize the allotted stack space by growing it on demand. Upon initial startup, the VM will default to the {@link VM#DEFAULT_STACKSIZE}
* size (this may be altered by {@link Args#getStackSize()}). The stack size will grow if required (by checking the {@link Bytecode#maxstacksize}, if it is more
* than what is currently available); the stack size does have a max capacity of growth which defaults to <code>{@link Integer#MAX_VALUE}</code>
* - (this can be altered by {@link Args#getMaxStackSize()}).
*
* <p>
*
* The shared stack is purely a performance enhancement; it took me a while to convince myself this was the appropriate approach. The alternative would be
* to create a new stack per {@link VM#execute(LeoObject, LeoObject, Bytecode)}. In doing profiling, this created an immense amount of garbage (however speed
* was relatively the same).
*
* <p>
* <h2>Exception Handling</h2>
* The VM shouldn't throw any {@link Exception}s (unless there truly is an exceptional error in the VM), but instead will wrap any {@link Exception}s into a
* {@link LeoError} which will be used as the result of executing a {@link VM#execute(LeoObject, LeoObject, Bytecode)}. This approach keeps the execution
* functions 'predictable'. What does this mean? It means it allows me to write the Java code without having to worry about exceptions being thrown from
* the client code. I can treat the {@link LeoObject#call()} as a discrete unit of work, and if the Leola code contains an exception, it is a Leola exception
* and <b>not</b> an interpreter/Java exception.
* <p>
* Given the above, there are plenty of scenarios were I <b>do</b> want to listen for exceptions from the Leola function call. The common case for this
* scenario is in the standard library or {@link LeolaLibrary}'s. The API's will want to know when an exception occurs, and handle them accordingly. In these
* scenarios the API author should use the helper methods {@link LeoObject#xcall()}, which will throw a {@link LeolaRuntimeException} if the result of the
* call is a {@link LeoError}.
*
* <p>
* <h2>Object lifecyle</h2>
* As any sane implementation on the JVM, I take advantage of the JVM's garbage collector. However, the JVM has to know when an object should be collected.
* Since the Leola {@link VM} contains a shared stack, we must be diligent in ensuring the stack only contains 'alive' objects. After each
* {@link VM#execute(LeoObject, LeoObject, Bytecode)} call, the VM's stack values are <code>popped</code> off for that function. It does this by when an
* execution is started it marks the current <code>top</code> of the stack, once the execution is terminated, it will <code>pop</code> off of the stack until
* the marked <code>top</code>.
*
* <p>
* Since Leola supports closures, we have to be a little more advanced in our stack management and object life cycle. When a variable is accessed from
* two different scopes, the variable is considered an {@link Outer} (i.e., an outer variable). These {@link Outer}s can exist in two different flavors,
* one in which lives in the direct parent scope and the other, which can live further up (e.g. parent of a parent).
* <p>
* Example {@link Outer}:
* <pre>
* var x = 10
* var myClosure = def() {
* println(x) // x is considered an Outer for the myClosure function
* }
* </pre>
* After the scope of the closure, the {@link Outer}'s are <i>closed</i> over, this means the variable is still accessible to the closure even though the closure
* may go out of scope. Continuing our example, the <code>myClosure</code> may be called multiple times and it will still retain the reference to the {@link Outer}.
*
* <pre>
* myClosure() // prints 10
* x = 21
* myClosure() // prints 21
* </pre>
*
* <p>
*
* @author Tony
*
*/
public class VM {
/**
* Maximum stack size
*/
public static final int DEFAULT_STACKSIZE = 1024;
/**
* Runtime
*/
private Leola runtime;
/*thread stack
*/
private LeoObject[] stack;
/* list of open outers, if this function goes out of scope (i.e., the stack) then the outers
* are closed (i.e., the value contained on the stack is transferred used instead of the indexed value
*/
private Outer[] openouters;
private int top;
/**
* The maximum stack size
*/
private final int maxStackSize;
/**
* The stack value accounts for closures requesting a value off
* of the stack and when the are finally 'closed' over.
*
* We can't just use the VM.stack variable when closing over
* the Outer because the VM.stack variable may be replaced
* when the stack grows.
*/
private StackValue vmStackValue = new StackValue() {
@Override
public LeoObject getStackValue(int index) {
return stack[index];
}
@Override
public void setStackValue(int index, LeoObject value) {
stack[index] = value;
}
};
/**
* @param runtime the {@link Leola} runtime
*/
public VM(Leola runtime) {
this.runtime = runtime;
int stackSize = runtime.getArgs().getStackSize();
stackSize = (stackSize <= 0) ? DEFAULT_STACKSIZE : stackSize;
this.maxStackSize = Math.max(runtime.getArgs().getMaxStackSize(), stackSize);
this.stack = new LeoObject[stackSize];
this.openouters = new Outer[stackSize];
this.top = 0;
}
/**
* Executes the supplied {@link Bytecode}.
*
* <p>
* This method is <b>not</b> thread-safe. In fact, it <b>will</b> cause a world of hurt if this method is executed in multiple threads. If thread support
* must be had, the preferred way is to have multiple {@link Leola} runtime's, short of that, the {@link Leola} runtime must be configured to enable
* thread-locals via {@link Args#allowThreadLocal()}. This will create a {@link VM} instance per thread.
*
* @param env the current call site environment. If this is a member function, it will be the owning {@link LeoClass}. Otherwise, it will be the {@link LeoNamespace}.
* @param callee the object which owns the {@link Bytecode}. This will either be a function, class or namespace
* @param code the {@link Bytecode} to be executed
*
* @return the result of executing the {@link Bytecode}. This will always return a value (in Leola all functions return a value, if no return statement
* is specified, {@link LeoObject#NULL} is returned. Furthermore, if an exception is thrown in the Leola code, a {@link LeoError} is returned.
*
* @throws LeolaRuntimeException this will only throw if an exception has occurred with the {@link VM}. That is, this will not throw an
* exception if the {@link Bytecode} operation throws an Leola exception.
*/
public LeoObject execute(LeoObject env, LeoObject callee, Bytecode code) throws LeolaRuntimeException {
return execute(env, callee, code, (LeoObject[])null);
}
/**
* Executes the supplied {@link Bytecode}. This method should be used if there are more than five arguments (or the number of arguments is unknown),
* otherwise the other variations of <code>execute</code> should be preferred.
*
* <p>
* This method is <b>not</b> thread-safe. In fact, it <b>will</b> cause a world of hurt if this method is executed in multiple threads. If thread support
* must be had, the preferred way is to have multiple {@link Leola} runtime's, short of that, the {@link Leola} runtime must be configured to enable
* thread-locals via {@link Args#allowThreadLocal()}. This will create a {@link VM} instance per thread.
*
* @param env the current call site environment. If this is a member function, it will be the owning {@link LeoClass}. Otherwise, it will be the {@link LeoNamespace}.
* @param callee the object which owns the {@link Bytecode}. This will either be a function, class or namespace
* @param code the {@link Bytecode} to be executed
* @param args the list of arguments.
*
* @return the result of executing the {@link Bytecode}. This will always return a value (in Leola all functions return a value, if no return statement
* is specified, {@link LeoObject#NULL} is returned. Furthermore, if an exception is thrown in the Leola code, a {@link LeoError} is returned.
*
* @throws LeolaRuntimeException this will only throw if an exception has occurred with the {@link VM}. That is, this will not throw an
* exception if the {@link Bytecode} operation throws an Leola exception.
*/
public LeoObject execute(LeoObject env, LeoObject callee, Bytecode code, LeoObject[] args) throws LeolaRuntimeException {
final int base = top;
prepareStack(code);
if ( args != null ) {
System.arraycopy(args, 0, stack, base, args.length);
}
LeoObject result = executeStackframe(env, code, callee, base );
return result;
}
/**
* Executes the supplied {@link Bytecode}.
*
* <p>
* This method is <b>not</b> thread-safe. In fact, it <b>will</b> cause a world of hurt if this method is executed in multiple threads. If thread support
* must be had, the preferred way is to have multiple {@link Leola} runtime's, short of that, the {@link Leola} runtime must be configured to enable
* thread-locals via {@link Args#allowThreadLocal()}. This will create a {@link VM} instance per thread.
*
* @param env the current call site environment. If this is a member function, it will be the owning {@link LeoClass}. Otherwise, it will be the {@link LeoNamespace}.
* @param callee the object which owns the {@link Bytecode}. This will either be a function, class or namespace
* @param code the {@link Bytecode} to be executed
* @param arg1 the first argument
*
* @return the result of executing the {@link Bytecode}. This will always return a value (in Leola all functions return a value, if no return statement
* is specified, {@link LeoObject#NULL} is returned. Furthermore, if an exception is thrown in the Leola code, a {@link LeoError} is returned.
*
* @throws LeolaRuntimeException this will only throw if an exception has occurred with the {@link VM}. That is, this will not throw an
* exception if the {@link Bytecode} operation throws an Leola exception.
*/
public LeoObject execute(LeoObject env, LeoObject callee, Bytecode code, LeoObject arg1) throws LeolaRuntimeException {
final int base = top;
prepareStack(code);
stack[base + 0] = arg1;
LeoObject result = executeStackframe(env, code, callee, base );
return result;
}
/**
* Executes the supplied {@link Bytecode}.
*
* <p>
* This method is <b>not</b> thread-safe. In fact, it <b>will</b> cause a world of hurt if this method is executed in multiple threads. If thread support
* must be had, the preferred way is to have multiple {@link Leola} runtime's, short of that, the {@link Leola} runtime must be configured to enable
* thread-locals via {@link Args#allowThreadLocal()}. This will create a {@link VM} instance per thread.
*
* @param env the current call site environment. If this is a member function, it will be the owning {@link LeoClass}. Otherwise, it will be the {@link LeoNamespace}.
* @param callee the object which owns the {@link Bytecode}. This will either be a function, class or namespace
* @param code the {@link Bytecode} to be executed
* @param arg1 the first argument
* @param arg2 the second argument
*
* @return the result of executing the {@link Bytecode}. This will always return a value (in Leola all functions return a value, if no return statement
* is specified, {@link LeoObject#NULL} is returned. Furthermore, if an exception is thrown in the Leola code, a {@link LeoError} is returned.
*
* @throws LeolaRuntimeException this will only throw if an exception has occurred with the {@link VM}. That is, this will not throw an
* exception if the {@link Bytecode} operation throws an Leola exception.
*/
public LeoObject execute(LeoObject env, LeoObject callee, Bytecode code, LeoObject arg1, LeoObject arg2) throws LeolaRuntimeException {
final int base = top;
prepareStack(code);
stack[base + 0] = arg1;
stack[base + 1] = arg2;
LeoObject result = executeStackframe(env, code, callee, base );
return result;
}
/**
* Executes the supplied {@link Bytecode}.
*
* <p>
* This method is <b>not</b> thread-safe. In fact, it <b>will</b> cause a world of hurt if this method is executed in multiple threads. If thread support
* must be had, the preferred way is to have multiple {@link Leola} runtime's, short of that, the {@link Leola} runtime must be configured to enable
* thread-locals via {@link Args#allowThreadLocal()}. This will create a {@link VM} instance per thread.
*
* @param env the current call site environment. If this is a member function, it will be the owning {@link LeoClass}. Otherwise, it will be the {@link LeoNamespace}.
* @param callee the object which owns the {@link Bytecode}. This will either be a function, class or namespace
* @param code the {@link Bytecode} to be executed
* @param arg1 the first argument
* @param arg2 the second argument
* @param arg3 the third argument
*
* @return the result of executing the {@link Bytecode}. This will always return a value (in Leola all functions return a value, if no return statement
* is specified, {@link LeoObject#NULL} is returned. Furthermore, if an exception is thrown in the Leola code, a {@link LeoError} is returned.
*
* @throws LeolaRuntimeException this will only throw if an exception has occurred with the {@link VM}. That is, this will not throw an
* exception if the {@link Bytecode} operation throws an Leola exception.
*/
public LeoObject execute(LeoObject env, LeoObject callee, Bytecode code, LeoObject arg1, LeoObject arg2, LeoObject arg3) throws LeolaRuntimeException {
final int base = top;
prepareStack(code);
stack[base + 0] = arg1;
stack[base + 1] = arg2;
stack[base + 2] = arg3;
LeoObject result = executeStackframe(env, code, callee, base );
return result;
}
/**
* Executes the supplied {@link Bytecode}.
*
* <p>
* This method is <b>not</b> thread-safe. In fact, it <b>will</b> cause a world of hurt if this method is executed in multiple threads. If thread support
* must be had, the preferred way is to have multiple {@link Leola} runtime's, short of that, the {@link Leola} runtime must be configured to enable
* thread-locals via {@link Args#allowThreadLocal()}. This will create a {@link VM} instance per thread.
*
* @param env the current call site environment. If this is a member function, it will be the owning {@link LeoClass}. Otherwise, it will be the {@link LeoNamespace}.
* @param callee the object which owns the {@link Bytecode}. This will either be a function, class or namespace
* @param code the {@link Bytecode} to be executed
* @param arg1 the first argument
* @param arg2 the second argument
* @param arg3 the third argument
* @param arg4 the fourth argument
*
* @return the result of executing the {@link Bytecode}. This will always return a value (in Leola all functions return a value, if no return statement
* is specified, {@link LeoObject#NULL} is returned. Furthermore, if an exception is thrown in the Leola code, a {@link LeoError} is returned.
*
* @throws LeolaRuntimeException this will only throw if an exception has occurred with the {@link VM}. That is, this will not throw an
* exception if the {@link Bytecode} operation throws an Leola exception.
*/
public LeoObject execute(LeoObject env, LeoObject callee, Bytecode code, LeoObject arg1, LeoObject arg2, LeoObject arg3, LeoObject arg4) throws LeolaRuntimeException {
final int base = top;
prepareStack(code);
stack[base + 0] = arg1;
stack[base + 1] = arg2;
stack[base + 2] = arg3;
stack[base + 3] = arg4;
LeoObject result = executeStackframe(env, code, callee, base );
return result;
}
/**
* Executes the supplied {@link Bytecode}.
*
* <p>
* This method is <b>not</b> thread-safe. In fact, it <b>will</b> cause a world of hurt if this method is executed in multiple threads. If thread support
* must be had, the preferred way is to have multiple {@link Leola} runtime's, short of that, the {@link Leola} runtime must be configured to enable
* thread-locals via {@link Args#allowThreadLocal()}. This will create a {@link VM} instance per thread.
*
* @param env the current call site environment. If this is a member function, it will be the owning {@link LeoClass}. Otherwise, it will be the {@link LeoNamespace}.
* @param callee the object which owns the {@link Bytecode}. This will either be a function, class or namespace
* @param code the {@link Bytecode} to be executed
* @param arg1 the first argument
* @param arg2 the second argument
* @param arg3 the third argument
* @param arg4 the fourth argument
* @param arg5 the fifth argument
*
* @return the result of executing the {@link Bytecode}. This will always return a value (in Leola all functions return a value, if no return statement
* is specified, {@link LeoObject#NULL} is returned. Furthermore, if an exception is thrown in the Leola code, a {@link LeoError} is returned.
*
* @throws LeolaRuntimeException this will only throw if an exception has occurred with the {@link VM}. That is, this will not throw an
* exception if the {@link Bytecode} operation throws an Leola exception.
*/
public LeoObject execute(LeoObject env, LeoObject callee, Bytecode code, LeoObject arg1, LeoObject arg2, LeoObject arg3, LeoObject arg4, LeoObject arg5) throws LeolaRuntimeException {
final int base = top;
prepareStack(code);
stack[base + 0] = arg1;
stack[base + 1] = arg2;
stack[base + 2] = arg3;
stack[base + 3] = arg4;
stack[base + 4] = arg5;
LeoObject result = executeStackframe(env, code, callee, base );
return result;
}
/**
* Prepares the stack by assigning NULL to all of the bytecode's
* arguments.
*
* @param code
*/
private void prepareStack(Bytecode code) {
final int base = top;
growStackIfRequired(stack, base, code.maxstacksize);
for(int i = 0; i < code.numArgs; i++) {
stack[base + i] = LeoNull.LEONULL;
}
}
/**
* Checks to see if we should grow the stack
*
* @param stack
* @param base
* @param neededSize
* @return the new stack (if no growth was required, the supplied stack is returned).
*/
private void growStackIfRequired(LeoObject[] stack, int base, int neededSize) {
final int requiredStackSize = base + neededSize;
if ( requiredStackSize > this.maxStackSize) {
error("Stack overflow, required stack size over maxStackSize '" + this.maxStackSize + "'");
}
if( requiredStackSize > stack.length) {
final int newStackSize = Math.min( stack.length + ((requiredStackSize-stack.length) << 1), this.maxStackSize);
LeoObject[] newStack = new LeoObject[newStackSize];
System.arraycopy(stack, 0, newStack, 0, base);
this.stack = newStack;
Outer[] newOuters = new Outer[newStack.length];
System.arraycopy(openouters, 0, newOuters, 0, base);
this.openouters = newOuters;
}
}
/**
* The main VM execution loop.
*
* This is a big f'ing method. Since this is the hot spot (i.e., the most executed part of the code) there are a number
* of micro optimizations. The first such optimization is the use of a switch statement for Opcode handling. My tests have shown a slight
* improvement in speed using the switch over a Map<Opcode, OpcodeHandler> approach. However, the CPU cost wasn't my primary
* concern. Using the Map approach required more allocations (all of the local variables within this method need
* to be accessed in the OpcodeHandler, thus requring an allocated object to capture all of the locals).
*
* Java really needs Value Types -- or I suppose more correctly I should have used a more appropriate implementation language.
*
* At any rate, this whole codebase has sacrifriced readability/maintainability for these micro-optimizations. This method
* probably being the worst offender.
*
*/
private LeoObject executeStackframe(LeoObject env, Bytecode code, LeoObject callee, int base) throws LeolaRuntimeException {
LeoObject result = LeoNull.LEONULL;
LeoObject errorThrown = LeoNull.LEONULL;
final int[] instr = code.instr;
final int len = code.len;
int pc = code.pc;
final LeoObject[] constants = code.constants;
final Bytecode[] inner = code.inner;
final Outer[] calleeouters;
final LeoObject[] genLocals;
/* if there is some object calling this function
* this means there might be outer scoped variables
* that we can access within this byte code
*/
if(callee != null) {
calleeouters = callee.getOuters();
genLocals = callee.getLocals();
/* if this is a generator, let us copy its local variables onto
* the stack
*/
if(genLocals != null) {
System.arraycopy(genLocals, code.numArgs, stack, base+code.numArgs, code.numLocals-code.numArgs);
}
}
else {
calleeouters = null;
genLocals = null;
}
boolean closeOuters = false;
boolean yield = false;
boolean isReturnedSafely = true;
boolean exitFunction = false;
Scope scope = null;
/* check and see if this is a scoped object,
* if so use the scope
*/
LeoScopedObject scopedObj = null;
if ( env instanceof LeoScopedObject) {
scopedObj = (LeoScopedObject)env;
scope = scopedObj.getScope();
}
/* use the global scope if this object doesn't contain
* any scope
*/
if(scope==null) {
LeoNamespace global = runtime.getGlobalNamespace();
scope=global.getScope();
scopedObj=global;
}
/* named parameters
*/
List<LeoObject> params = null;
int paramIndex = 0;
if(code.hasParamIndexes()) {
params = new ArrayList<LeoObject>();
}
/* exception handling, keeps track of the catch program
* counter */
ExceptionStack blockStack = null;
if(code.hasBlocks()) {
blockStack = new ExceptionStack();
}
final int topStack = base + code.numLocals;
top = topStack;
int lineNumber = -1;
do {
try {
while( pc < len ) {
int i = instr[pc++];
int opcode = i & 255; //OPCODE(i);
switch(opcode) {
/* Debug */
case LINE: {
lineNumber = ARGx(i);
DebugListener listener = this.runtime.getDebugListener();
if(listener != null ) {
LeoObject[] stackSnapshot = new LeoObject[top-base];
System.arraycopy(stack, base, stackSnapshot, 0, stackSnapshot.length);
LeoObject[] localsSnapshot = new LeoObject[topStack-base];
System.arraycopy(stack, base, localsSnapshot, 0, localsSnapshot.length);
listener.onLineNumber(new DebugEvent(stack, base, topStack, top, pc
, lineNumber, scope, calleeouters, code));
}
continue;
}
/* Store operations */
case LOAD_CONST: {
int iname = ARGx(i);
stack[top++] = constants[iname];
continue;
}
case LOAD_LOCAL: {
int iname = ARGx(i);
stack[top++] = stack[base + iname];
continue;
}
case LOAD_OUTER: {
int iname = ARGx(i);
stack[top++] = calleeouters[iname].getValue();
continue;
}
case LOAD_NULL: {
stack[top++] = LeoNull.LEONULL;
continue;
}
case LOAD_TRUE: {
stack[top++] = LeoBoolean.LEOTRUE;
continue;
}
case LOAD_FALSE: {
stack[top++] = LeoBoolean.LEOFALSE;
continue;
}
case LOAD_NAME: {
int iname = ARGx(i);
LeoObject name = constants[iname];
params.add(paramIndex, name);
continue;
}
case PARAM_END: {
paramIndex++;
if(params.size() < paramIndex) {
params.add(null);
}
break;
}
case STORE_LOCAL: {
int iname = ARGx(i);
stack[base + iname] = stack[--top];
continue;
}
case STORE_OUTER: {
int iname = ARGx(i);
calleeouters[iname].setValue(stack[--top]);
continue;
}
/* stack operators */
case POP: {
stack[--top] = null;
continue;
}
case OPPOP: {
if (top>topStack) {
stack[--top] = null;
}
continue;
}
case DUP: {
LeoObject obj = stack[top-1];
stack[top++] = obj;
continue;
}
case RET: {
isReturnedSafely = true;
exitFunction = true;
pc = len; /* Break out of the bytecode */
if ( top>topStack) {
result = stack[--top];
}
break;
}
case YIELD: {
yield = true; /* lets not expire the generator */
isReturnedSafely = true;
exitFunction = true;
/* copy what was stored on the stack, back to the
* generators local copy
*/
System.arraycopy(stack, base+code.numArgs, genLocals, code.numArgs, code.numLocals-code.numArgs);
code.pc = pc;
pc = len;
if ( top>topStack) {
result = stack[--top];
}
break;
}
case JMP: {
int pos = ARGsx(i);
pc += pos;
continue;
}
case TAIL_CALL: {
pc = 0; /* return to the beginning of the function call, with the
stack persevered */
int nargs = ARG1(i);
LeoObject fun = stack[(top-1) - nargs];
/* determine if there are named parameters to resolve */
if(paramIndex > 0 ) {
nargs = resolveNamedParameters(params, stack, top-nargs, fun, nargs);
/* ready this for any other method calls */
params.clear();
paramIndex = 0;
}
if(code.hasVarargs()) {
int numberOfArguments = (nargs - code.numArgs) + 1;
int expandedArgs = ARG2(i);
/* If we don't have an expanded array request, wrap up the arguments
* into a new array
*/
if(expandedArgs<1) {
LeoArray arguments = new LeoArray(readArrayFromStack(numberOfArguments, stack));
stack[top++] = arguments;
nargs = code.numArgs;
}
}
switch(nargs) {
case 0: {
break;
}
case 1: {
LeoObject arg1 = stack[--top];
stack[base + 0] = arg1;
break;
}
case 2: {
LeoObject arg2 = stack[--top];
LeoObject arg1 = stack[--top];
stack[base + 0] = arg1;
stack[base + 1] = arg2;
break;
}
case 3: {
LeoObject arg3 = stack[--top];
LeoObject arg2 = stack[--top];
LeoObject arg1 = stack[--top];
stack[base + 0] = arg1;
stack[base + 1] = arg2;
stack[base + 2] = arg3;
break;
}
case 4: {
LeoObject arg4 = stack[--top];
LeoObject arg3 = stack[--top];
LeoObject arg2 = stack[--top];
LeoObject arg1 = stack[--top];
stack[base + 0] = arg1;
stack[base + 1] = arg2;
stack[base + 2] = arg3;
stack[base + 3] = arg4;
break;
}
case 5: {
LeoObject arg5 = stack[--top];
LeoObject arg4 = stack[--top];
LeoObject arg3 = stack[--top];
LeoObject arg2 = stack[--top];
LeoObject arg1 = stack[--top];
stack[base + 0] = arg1;
stack[base + 1] = arg2;
stack[base + 2] = arg3;
stack[base + 3] = arg4;
stack[base + 4] = arg5;
break;
}
default: {
LeoObject[] args = readArrayFromStack(nargs, stack);
System.arraycopy(args, 0, stack, base, nargs);
}
}
// pops the recursive function
top--;
continue;
}
case INVOKE: {
int nargs = ARG1(i);
LeoObject fun = stack[(top-1) - nargs];
/* determine if there are named parameters to resolve */
if(paramIndex > 0 && !fun.isNativeFunction() ) {
nargs = resolveNamedParameters(params, stack, top-nargs, fun, nargs);
/* ready this for any other method calls */
params.clear();
paramIndex = 0;
}
/* If we have an expanded array argument,
* go ahead and expand it
*/
int argIndex = ARG2(i);
if(argIndex>0) {
/*if(!fun.isNativeFunction()) {
if(!fun.hasVarargs()) {
error(fun + " does not accept variable arguments.");
}
int expectedNumberOfArguments = fun.getNumberOfArgs();
if(nargs < expectedNumberOfArguments) {
error("Invalid number of parameters '" + nargs + "' before the variable arguments expansion '" + expectedNumberOfArguments + "'.");
}
}*/
nargs += expandArrayArgument() - 1;
}
LeoObject c = null;
switch(nargs) {
case 0: {
c = fun.xcall();
break;
}
case 1: {
LeoObject arg1 = stack[--top];
c = fun.xcall(arg1);
break;
}
case 2: {
LeoObject arg2 = stack[--top];
LeoObject arg1 = stack[--top];
c = fun.xcall(arg1, arg2);
break;
}
case 3: {
LeoObject arg3 = stack[--top];
LeoObject arg2 = stack[--top];
LeoObject arg1 = stack[--top];
c = fun.xcall(arg1, arg2, arg3);
break;
}
case 4: {
LeoObject arg4 = stack[--top];
LeoObject arg3 = stack[--top];
LeoObject arg2 = stack[--top];
LeoObject arg1 = stack[--top];
c = fun.xcall(arg1, arg2, arg3, arg4);
break;
}
case 5: {
LeoObject arg5 = stack[--top];
LeoObject arg4 = stack[--top];
LeoObject arg3 = stack[--top];
LeoObject arg2 = stack[--top];
LeoObject arg1 = stack[--top];
c = fun.xcall(arg1, arg2, arg3, arg4, arg5);
break;
}
default: {
LeoObject[] args = readArrayFromStack(nargs, stack);
c = fun.xcall(args);
}
}
stack[top-1] = c;
continue;
}
case NEW_OBJ: {
LeoObject className = stack[--top];
int nargs = ARG1(i);
LeoObject instance = null;
ClassDefinitions defs = scope.lookupClassDefinitions(className);
if ( defs == null ) {
if(runtime.isSandboxed()) {
error("Unable to instantiate native Java classes ('"+ className +"') in Sandboxed mode.");
}
LeoObject[] args = readArrayFromStack(nargs, stack);
instance = ClassUtil.newNativeInstance(className.toString(), args);
}
else {
LeoObject resolvedClassName = scope.getClassName(className);
ClassDefinition definition = defs.getDefinition(resolvedClassName);
LeoObject[] args = new LeoObject[definition.getNumberOfParameters()];
args = readArrayFromStack(args, nargs, stack);
for(int j=nargs; j < args.length; j++) {
args[j]=LeoObject.NULL;
}
if(paramIndex > 0) {
resolveNamedParameters(params, args, 0, definition.getParameterNames(), nargs);
/* ready this for any other method calls */
params.clear();
paramIndex = 0;
}
if(definition.hasVarargs()) {
int numberOfArguments = (nargs - definition.getNumberOfParameters()) + 1;
int startVarArgIndex = nargs-numberOfArguments;
int expandedArgs = ARG2(i);
/* If we don't have an expanded array request, wrap up the arguments
* into a new array
*/
if(expandedArgs<1) {
LeoArray arguments = new LeoArray(numberOfArguments);
for(int k=startVarArgIndex; k<args.length;k++) {
arguments.add(args[k]);
}
args[startVarArgIndex] = arguments;
}
}
instance = defs.newInstance(runtime, definition, args);
}
stack[top++] = instance;
continue;
}
case NEW_ARRAY: {
int initialSize = ARGx(i);
LeoArray array = new LeoArray(initialSize);
for(int j = initialSize; j > 0; j--) {
array.add(stack[top-j]);
}
top -= initialSize;
stack[top++] = array;
continue;
}
case NEW_MAP: {
int initialSize = ARGx(i);
LeoMap map = new LeoMap(initialSize);
for(int j = 0; j < initialSize; j++) {
LeoObject value = stack[--top];
LeoObject key = stack[--top];
map.put(key, value);
}
stack[top++] = map;
continue;
}
case NAMESPACE_DEF: {
int innerIndex = ARGx(i);
Bytecode namespacecode = inner[innerIndex];
LeoObject name = stack[--top];
NamespaceDefinitions ndefs = scope.getNamespaceDefinitions();
LeoNamespace ns = ndefs.getNamespace(name);
if(ns==null) {
ns = new LeoNamespace(this.runtime, namespacecode, new Scope(ScopeType.Namespace, scope), name);
ndefs.storeNamespace(name, ns);
}
else {
if(namespacecode.numOuters>0) {
ns.setOuters(new Outer[namespacecode.numOuters]);
}
}
Outer[] outers = ns.getOuters();
if (assignOuters(outers, calleeouters, openouters, namespacecode.numOuters, base, pc, code)) {
closeOuters = true;
}
pc += namespacecode.numOuters;
this.runtime.execute(ns, namespacecode);
continue;
}
case GEN_DEF: {
int innerIndex = ARGx(i);
Bytecode bytecode = inner[innerIndex];
LeoGenerator fun = new LeoGenerator(this.runtime, scopedObj, bytecode.clone());
Outer[] outers = fun.getOuters();
if (assignOuters(outers, calleeouters, openouters, bytecode.numOuters, base, pc, code)) {
closeOuters = true;
}
pc += bytecode.numOuters;
stack[top++] = fun;
continue;
}
case FUNC_DEF: {
int innerIndex = ARGx(i);
Bytecode bytecode = inner[innerIndex];
LeoFunction fun = new LeoFunction(this.runtime, scopedObj, bytecode);
Outer[] outers = fun.getOuters();
if (assignOuters(outers, calleeouters, openouters, bytecode.numOuters, base, pc, code)) {
closeOuters = true;
}
pc += bytecode.numOuters;
stack[top++] = fun;
continue;
}
case CLASS_DEF: {
LeoObject bytecodeIndex = stack[--top];
Bytecode body = inner[bytecodeIndex.asInt()];
int numSuperParams = stack[--top].asInt();
LeoObject[] superParams = readArrayFromStack(numSuperParams, stack);
int nparams = stack[--top].asInt();
LeoObject[] paramNames = readArrayFromStack(nparams, stack);
LeoObject superClassname = stack[--top];
LeoObject className = stack[--top];
ClassDefinition superClassDefinition = null;
if ( ! superClassname.$eq(LeoNull.LEONULL) ) {
ClassDefinitions defs = scope.lookupClassDefinitions(superClassname);
superClassDefinition = defs.getDefinition(superClassname);
}
ClassDefinition classDefinition = new ClassDefinition(className
, superClassDefinition
, scope
, paramNames
, superParams
, body);
ClassDefinitions defs = scope.getClassDefinitions();
defs.storeClass(className, classDefinition);
Outer[] outers = classDefinition.getOuters();
if( assignOuters(outers, calleeouters, openouters, body.numOuters, base, pc, code)) {
closeOuters = true;
}
pc += body.numOuters;
continue;
}
case IS_A: {
LeoObject obj = stack[--top];
LeoObject type = stack[--top];
stack[top++] = LeoBoolean.valueOf(obj.isOfType(type.toString()));
continue;
}
case IFEQ: {
LeoObject cond = stack[--top];
if ( ! LeoObject.isTrue(cond) ) {
int pos = ARGsx(i);
pc += pos;
}
continue;
}
case THROW: {
LeoObject str = stack[--top];
throw new LeolaRuntimeException(new LeoError(str));
}
case IDX: {
LeoObject index = stack[--top];
LeoObject obj = stack[--top];
LeoObject value = obj.$index(index);
stack[top++] = value;
continue;
}
case SIDX: {
LeoObject index = stack[--top];
LeoObject obj = stack[--top];
LeoObject value = stack[--top];
obj.$sindex(index, value);
stack[top++] = obj; /* make this an expression */
continue;
}
/* object access */
case GET: {
LeoObject index = stack[--top];
LeoObject obj = stack[--top];
LeoObject value = obj.xgetObject(index);
stack[top++] = value;
continue;
}
case EGETK: {
int iname = ARGx(i);
LeoObject obj = stack[--top];
LeoObject value = obj.isAccessible()
? obj.getObject(constants[iname]) : LeoObject.NULL;
stack[top++] = value;
continue;
}
case GETK: {
int iname = ARGx(i);
LeoObject obj = stack[--top];
LeoObject value = obj.xgetObject(constants[iname]);
stack[top++] = value;
continue;
}
case SET: {
LeoObject index = stack[--top];
LeoObject obj = stack[--top];
LeoObject value = stack[--top];
obj.setObject(index, value);
stack[top++] = obj; /* make this an expression */
continue;
}
case SETK: {
int iname = ARGx(i);
LeoObject obj = stack[--top];
LeoObject value = stack[--top];
obj.setObject(constants[iname], value);
stack[top++] = obj; /* make this an expression */
continue;
}
case GET_GLOBAL: {
int iname = ARGx(i);
LeoObject member = scope.getObject(constants[iname]);
if(member==null) {
scopedObj.throwAttributeError(constants[iname]);
}
stack[top++] = member;
continue;
}
case SET_GLOBAL: {
int iname = ARGx(i);
scopedObj.addProperty(constants[iname], stack[--top]);
continue;
}
case GET_NAMESPACE: {
int iname = ARGx(i);
LeoNamespace ns = scope.lookupNamespace(constants[iname]);
stack[top++] = ns;
continue;
}
case INIT_FINALLY_BLOCK: {
/* Denote that we are entering a TRY
* block that may contain a FINALLY
* block
*/
int address = ARGsx(i);
blockStack.pushFinally(address);
continue;
}
case INIT_CATCH_BLOCK: {
/* Denote that we are entering a TRY
* block that may contain a CATCH
* block
*/
int address = ARGsx(i);
blockStack.pushCatch(address);
continue;
}
case END_BLOCK: {
int endType = ARG1(i);
switch(endType) {
// if this is a start of a catch block
// we can clear out the error states
case 1: /* End of a Catch */ {
/*
* try
* ..
* catch e
* .. // since we are catching
* // the exception, we need
* // to clear out the error flags
* // and denote we are safe to
* // return
*/
result = LeoNull.LEONULL;
errorThrown = LeoNull.LEONULL;
isReturnedSafely = true;
break;
}
case 2: /* End of a Finally */ {
/* if the result is an
* error, we need to bubble up the
* error. This happens for:
*
* try
* ..
* finally
* .. // the error is still present and
* // must be bubbled up
*/
if(errorThrown.isError() || exitFunction) {
pc = len;
}
break;
}
default: {
/*
* We have reached the end of an
* INIT_BLOCK, which means
* we have passed either a
* CATCH or FINALLY blocks
*/
blockStack.pop();
}
}
continue;
}
/* arithmetic operators */
case ADD: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = l.$add(r);
stack[top++] = c;
continue;
}
case SUB: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = l.$sub(r);
stack[top++] = c;
continue;
}
case MUL: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = l.$mul(r);
stack[top++] = c;
continue;
}
case DIV: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = l.$div(r);
stack[top++] = c;
continue;
}
case MOD: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = l.$mod(r);
stack[top++] = c;
continue;
}
case NEG: {
LeoObject l = stack[--top];
LeoObject c = l.$neg();
stack[top++] = c;
continue;
}
case BSL: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = l.$bsl(r);
stack[top++] = c;
continue;
}
case BSR: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = l.$bsr(r);
stack[top++] = c;
continue;
}
case BNOT: {
LeoObject l = stack[--top];
LeoObject c = l.$bnot();
stack[top++] = c;
continue;
}
case XOR: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = l.$xor(r);
stack[top++] = c;
continue;
}
case LOR: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = l.$bor(r);
stack[top++] = c;
continue;
}
case LAND: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = l.$band(r);
stack[top++] = c;
continue;
}
case OR: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(l.isTrue() || r.isTrue());
stack[top++] = c;
continue;
}
case AND: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(l.isTrue() && r.isTrue());
stack[top++] = c;
continue;
}
case NOT: {
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(!l.isTrue());
stack[top++] = c;
continue;
}
case REQ: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(l.$req(r));
stack[top++] = c;
continue;
}
case RNEQ: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(l.$rneq(r));
stack[top++] = c;
continue;
}
case EQ: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(l.$eq(r));
stack[top++] = c;
continue;
}
case NEQ: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(l.$neq(r));
stack[top++] = c;
continue;
}
case GT: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(l.$gt(r));
stack[top++] = c;
continue;
}
case GTE: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(l.$gte(r));
stack[top++] = c;
continue;
}
case LT: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(l.$lt(r));
stack[top++] = c;
continue;
}
case LTE: {
LeoObject r = stack[--top];
LeoObject l = stack[--top];
LeoObject c = LeoBoolean.valueOf(l.$lte(r));
stack[top++] = c;
continue;
}
default: {
error("Unknown opcode '" + opcode + "' found for the Bytecode '" + Integer.toHexString(i) + "'");
}
}
}
}
catch(Throwable e) {
/* clear out result in an ON block */
isReturnedSafely = false;
/* build up the stack trace */
errorThrown = buildStackTrace(code, errorThrown, e, lineNumber);
stack[top++] = errorThrown;
pc = len; /* exit out of this function */
}
finally {
if(blockStack != null && !blockStack.isEmpty()) {
/* If we explicitly exited out of this function
* either via a RETURN or YIELD statement inside
* of a TRY..CATCH..FINALLY block, we need to jump
* over any CATCH blocks, but still execute any
* FINALLY blocks
*/
if(exitFunction) {
/* Skip over any catch blocks, we can
* do this because we are exiting the function
* cleanly via the RETURN/YIELD statements
*/
while(blockStack.peekIsCatch()) {
blockStack.pop();
}
/* If we have a FINALLY block, go ahead
* and execute it
*/
if(blockStack.peekIsFinally()) {
pc = blockStack.peekAddress();
}
}
else {
/* We did not invoke a RETURN/YIELD,
* so we can proceed as normal (i.e.,
* if an exception is thrown, go to a CATCH
* block and then FINALLY blocks)
*/
pc = blockStack.peekAddress();
}
}
}
} while(blockStack != null && !blockStack.isEmpty());
exitCall(callee, code, closeOuters, base, yield, pc, len);
return isReturnedSafely ?
result : errorThrown;
}
private void exitCall(LeoObject callee, Bytecode code, boolean closeOuters, int base, boolean yield, int pc, int len) {
final int stackSize = Math.min(stack.length, base+code.maxstacksize);
/* close the outers for this function call */
if (closeOuters) {
for(int j=base;j<stackSize;j++) {
if(openouters[j]!=null) {
openouters[j].close();
openouters[j] = null;
}
stack[j] = null;
}
}
else {
for(int j=base;j<stackSize;j++) {
stack[j] = null;
}
}
top = base;
/* expire this generator if we hit the end of the function */
if(!yield && callee != null && callee.isGenerator()) {
if(pc == len) {
code.pc = pc;
}
}
}
/**
* Reads an array of values from the stack.
*
* @param args
* @param nargs
* @param stack
* @return the array of {@link LeoObject}'s, or null if nargs <= 0
*/
private LeoObject[] readArrayFromStack(LeoObject[] args, int nargs, LeoObject[] stack) {
for(int j = nargs - 1; j >= 0; j--) {
args[j] = stack[--top];
}
return args;
}
/**
* Reads an array of values from the stack.
*
* @param nargs
* @param stack
* @return the array of {@link LeoObject}'s, or null if nargs <= 0
*/
private LeoObject[] readArrayFromStack(int nargs, LeoObject[] stack) {
LeoObject[] args = null;
if ( nargs > 0 ) {
args = new LeoObject[nargs];
return readArrayFromStack(args, nargs, stack);
}
return args;
}
/**
* Expands the first function argument (which ends up really be the last argument in Leola code).
* This will also ensure that the stack is appropriately resized if necessary.
*
* @param doExpansion - if the expansion should actually be done
* @return the number of arguments that were expanded
*/
private int expandArrayArgument() {
LeoObject l = stack[--top];
if(!l.isArray()) {
error(l + " is not an array");
}
LeoArray array = l.as();
int size = array.size();
growStackIfRequired(stack, top, size+1);
for(int index = 0; index < size; index++) {
stack[top++] = array.get(index);
}
return size;
}
/**
* Builds the stack trace based off of the current stack trace and error message.
*
* @param code the current bytecode being executed
* @param errorThrown the current error thrown (if any)
* @param message the Error message and/or Exception
* @return the error thrown
*/
private LeoObject buildStackTrace(Bytecode code, LeoObject errorThrown, Object message, int lineNumber) {
if( (message instanceof LeolaRuntimeException) ) {
LeoError error = ((LeolaRuntimeException)message).getLeoError();
if(error.getLineNumber()<0) {
error.setSourceFile(code.getSourceFileName());
error.setLineNumber(lineNumber);
}
else if(errorThrown.isError()) {
LeoError parentError = errorThrown.as();
parentError.addStack(error);
error = parentError;
}
else {
LeoError cause = new LeoError();
cause.setSourceFile(code.getSourceFileName());
cause.setLineNumber(lineNumber);
error.addStack(cause);
}
errorThrown = error;
}
else {
LeoError error = new LeoError(message.toString());
if(error.getLineNumber()<0) {
error.setSourceFile(code.getSourceFileName());
error.setLineNumber(lineNumber);
}
if(errorThrown.isError()) {
LeoError parentError = errorThrown.as();
parentError.addStack(error);
}
else {
errorThrown = error;
}
}
return errorThrown;
}
/**
* Handles an error in the execution.
*
* @param errorMsg
*/
private void error(String errorMsg) {
if(errorMsg==null) {
errorMsg = "";
}
throw new LeolaRuntimeException("ExecutionError: " + errorMsg);
}
/**
* Resolve the named parameters
*
* @param params
* @param fun
* @param nargs
* @return the number of arguments to be expected
*/
private int resolveNamedParameters(List<LeoObject> params, LeoObject[] args, int argTop, LeoObject fun, int nargs) {
/* assume this is a function */
LeoFunction f = fun.as();
Bytecode bc = f.getBytecode();
resolveNamedParameters(params, args, argTop, bc.paramNames, nargs);
/* If we received less number of parameters than expected,
* adjust the top of the stack, because we are accounting for
* them now
*/
int expectedNumberOfParameters = bc.paramNames.length;
if(nargs < expectedNumberOfParameters) {
top += expectedNumberOfParameters-nargs;
nargs = expectedNumberOfParameters;
}
return nargs;
}
/**
* Resolve the named parameters
*
* @param params
* @param stack
* @param paramNames
* @param nargs
*/
private void resolveNamedParameters(List<LeoObject> params, LeoObject[] args, int topArgs, LeoObject[] paramNames, int nargs) {
int expectedNumberOfArgs = paramNames.length;
// int tmpTop = 0;//top;
int tmpTop = top;
// LeoObject[] tmp = new LeoObject[expectedNumberOfArgs];//stack
LeoObject[] tmp = stack;
/* Clone the supplied arguments into a temporary
* variable (we use the execution stack for performance reasons,
* this helps us avoid an allocation)
*/
for(int stackIndex = 0; stackIndex < expectedNumberOfArgs; stackIndex++) {
if(stackIndex < nargs) {
tmp[tmpTop + stackIndex] = args[topArgs + stackIndex];
}
else {
tmp[tmpTop + stackIndex] = LeoObject.NULL;
}
args[topArgs+stackIndex] = null;
}
int[] otherIndexes = new int[expectedNumberOfArgs];
/* iterate through the parameter names and adjust the stack
* so that the names match the position the function expects them
*/
for(int stackIndex = 0; stackIndex < params.size(); stackIndex++) {
LeoObject paramName = params.get(stackIndex);
if(paramName != null) {
/* Find the appropriate argument position
* index for the named parameter
*/
int paramIndex = 0;
for(; paramIndex < paramNames.length; paramIndex++) {
if(paramNames[paramIndex].$eq(paramName)) {
break;
}
}
if(paramIndex>=paramNames.length) {
error("Invalid parameter name '" + paramName + "'");
}
otherIndexes[stackIndex] = paramIndex + 1;
}
else {
otherIndexes[stackIndex] = -(stackIndex+1);
}
}
/* Assign the named parameters to the correct position
*/
for(int i = 0; i < expectedNumberOfArgs; i++) {
if(otherIndexes[i]>0) {
args[topArgs+ (otherIndexes[i]-1) ] = tmp[tmpTop + i];
}
}
/* Account for arguments that do not have a name
* in front of them. In these cases, we 'fill-in-the-blanks'
* in order from left to right.
*/
int lastUnusedIndex = 0;
for(int i = 0; i < expectedNumberOfArgs; i++) {
if(args[topArgs+i] == null) {
for(; lastUnusedIndex < otherIndexes.length;) {
if(otherIndexes[lastUnusedIndex]<0) {
args[ topArgs+i ] = tmp[tmpTop + lastUnusedIndex++ ];
break;
}
lastUnusedIndex++;
}
}
}
/* Whatever is left over, just assign
* them to NULL
*/
for(int i = 0; i < expectedNumberOfArgs; i++) {
if(args[topArgs+i]==null)
args[topArgs+i] = LeoObject.NULL;
}
}
/**
* Close over the outer variables for closures.
*
* @param outers
* @param calleeouters
* @param openouters
* @param numOuters
* @param base
* @param pc
* @param code
* @return true if there where Outers created that should be closed over once we leave the function
* scope
*/
private boolean assignOuters(Outer[] outers, Outer[] calleeouters, Outer[] openouters,
int numOuters,
int base,
int pc,
Bytecode code) {
boolean closeOuters = false;
for(int j = 0; j < numOuters; j++) {
int i = code.instr[pc++];
int opCode = i & 255;
int index = ARGx(i);
switch(opCode) {
case xLOAD_OUTER: {
outers[j] = calleeouters[index];
break;
}
case xLOAD_LOCAL: {
int bindex = base + index;
outers[j] = openouters[bindex] != null ?
openouters[bindex] :
(openouters[bindex] = new Outer(vmStackValue, bindex));
closeOuters = true;
break;
}
default: {
error("Outer opcode '" + opCode +"' is invalid");
}
}
}
return closeOuters;
}
}
<|start_filename|>src/leola/ast/VarExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* @author Tony
*
*/
public class VarExpr extends Expr {
/**
* The variable name
*/
private String varName;
/**
* @param owner
* @param varName
*/
public VarExpr(String varName) {
this.varName = varName;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the varName
*/
public String getVarName() {
return varName;
}
}
<|start_filename|>src/leola/ast/MapDeclExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.List;
import leola.vm.EvalException;
import leola.vm.util.Pair;
/**
* @author Tony
*
*/
public class MapDeclExpr extends Expr {
/**
* Elements
*/
private List<Pair<Expr, Expr>> elements;
/**
* @param elements
*/
public MapDeclExpr(List<Pair<Expr, Expr>> elements) {
this.elements = elements;
for(Pair<Expr, Expr> p : elements) {
becomeParentOf(p.getFirst());
becomeParentOf(p.getSecond());
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the elements
*/
public List<Pair<Expr, Expr>> getElements() {
return elements;
}
}
<|start_filename|>src/leola/vm/debug/DebugListener.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.debug;
/**
* Listens for debug lines
*
* @author Tony
*
*/
public interface DebugListener {
/**
* A line has been encountered
*
* @param event
*/
public void onLineNumber(DebugEvent event);
}
<|start_filename|>src/leola/ast/CaseExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.List;
import leola.vm.EvalException;
import leola.vm.util.Pair;
/**
* Case Expression
*
* @author Tony
*
*/
public class CaseExpr extends Expr {
private Expr condition;
private List<Pair<Expr, Expr>> whenExprs;
private Expr elseExpr;
/**
* @param condition
* @param whenExprs
*/
public CaseExpr(Expr condition, List<Pair<Expr, Expr>> whenExprs) {
this(condition, whenExprs, null);
}
/**
* @param condition
* @param whenExprs
* @param elseExpr
*/
public CaseExpr(Expr condition, List<Pair<Expr, Expr>> whenExprs, Expr elseExpr) {
this.condition = becomeParentOf(condition);
this.whenExprs = whenExprs;
this.elseExpr = becomeParentOf(elseExpr);
for(Pair<Expr, Expr> p : whenExprs) {
becomeParentOf(p.getFirst());
becomeParentOf(p.getSecond());
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the condition
*/
public Expr getCondition() {
return condition;
}
/**
* @return the whenExprs
*/
public List<Pair<Expr, Expr>> getWhenExprs() {
return this.whenExprs;
}
/**
* @return the elseExpr
*/
public Expr getElseExpr() {
return this.elseExpr;
}
}
<|start_filename|>src/leola/vm/types/LeoScopedObject.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.lang.reflect.Method;
import leola.vm.NamespaceDefinitions;
import leola.vm.Scope;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaMethod;
/**
* An object which contains code within it that can be referenced outside of the scope (namespaces, classes).
*
* @author Tony
*
*/
public abstract class LeoScopedObject extends LeoOuterObject {
/**
* The scope
*/
private Scope scope;
/**
* @param type
* @param scope
*/
public LeoScopedObject(LeoType type, Scope scope, int numberOfOuters) {
super(type, numberOfOuters);
this.scope = scope;
}
/**
* @return the scope
*/
public Scope getScope() {
return scope;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isScopedObject()
*/
@Override
public boolean isScopedObject() {
return true;
}
@Override
public boolean isAccessible() {
return true;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#eq(leola.vm.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
if ( other == this) {
return true;
}
if ( other instanceof LeoScopedObject ) {
LeoScopedObject otherObj = (LeoScopedObject)other;
return otherObj.scope.equals(this.scope);
}
return false;
}
/**
* @return the {@link NamespaceDefinitions} within this scope
*/
public NamespaceDefinitions getNamespaceDefinitions() {
return getScope().getNamespaceDefinitions();
}
/**
* Adds the Java method into this {@link LeoScopedObject}
*
* @param method
* @return the {@link LeoNativeFunction} that represents the Java method
*/
public LeoNativeFunction addMethod(Method method) {
return addMethod(this, method);
}
/**
* Adds the Java method into this {@link LeoScopedObject}, if the {@link LeolaMethod} annotation is present on the supplied
* {@link Method}, the {@link LeolaMethod#alias()} will be used as the method alias name.
*
* @param jObject
* @param method
* @return the {@link LeoNativeFunction} that represents the Java method
*/
public LeoNativeFunction addMethod(Object jObject, Method method) {
return addMethod(jObject, method, (method.isAnnotationPresent(LeolaMethod.class)) ?
method.getAnnotation(LeolaMethod.class).alias()
: method.getName());
}
/**
* Adds a native Java method into this {@link LeoScopedObject}
*
* @param jObject the Java instance
* @param method the Java method
* @param alias an alias name for the Java method
* @return the {@link LeoNativeFunction} that represents the Java method
*/
public LeoNativeFunction addMethod(Object jObject, Method method, String alias) {
LeoNativeFunction fun = new LeoNativeFunction(method, jObject);
this.scope.storeObject(alias, fun);
return fun;
}
/**
* @see LeoScopedObject#addProperty(LeoString, LeoObject)
*/
@Override
public void setObject(LeoObject key, LeoObject value) {
addProperty(key, value);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getObject(leola.vm.types.LeoObject)
*/
@Override
public LeoObject getObject(LeoObject key) {
return getProperty(key);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#xgetObject(leola.vm.types.LeoObject)
*/
@Override
public LeoObject xgetObject(LeoObject key) throws LeolaRuntimeException {
return xgetProperty(key);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#hasObject(leola.vm.types.LeoObject)
*/
@Override
public boolean hasObject(LeoObject key) {
return hasProperty(key);
}
/**
* Places the data member in this scope. This is different than
* {@link LeoScopedObject#setObject(LeoObject, LeoObject)} in that the latter
* from will scan the parent scopes to determine if it should override a data member,
* as this function will not, it will always place it in this {@link Scope}
*
* @param reference
* @param value
*/
public void putObject(String reference, LeoObject value) {
putObject(LeoString.valueOf(reference), value);
}
/**
* Places the data member in this scope. This is different than
* {@link LeoScopedObject#setObject(LeoObject, LeoObject)} in that the latter
* from will scan the parent scopes to determine if it should override a data member,
* as this function will not, it will always place it in this {@link Scope}
*
* @param reference
* @param value
*/
public void putObject(LeoObject reference, LeoObject value) {
this.scope.putObject(reference, value);
}
/**
* Determines if a data member exists in this {@link Scope} or parent scopes
*
* @param member
* @return true if found within the hierarchy of this {@link Scope}. This will always
* exclude the global {@link Scope}
*/
public boolean hasProperty(LeoObject member) {
return this.scope.getObjectNoGlobal(member) != null;
}
/**
* Attempts to look up the data member with the supplied name.
*
* @param member - the name of the property
* @return the property value if found, otherwise this will throw {@link LeolaRuntimeException}
*/
public LeoObject xgetProperty(LeoObject member) throws LeolaRuntimeException {
LeoObject result = this.scope.getObjectNoGlobal(member);
if(result == null) {
throwAttributeError(member);
}
return result;
}
/**
* Attempts to look up the data member with the supplied name.
*
* @param member - the name of the property
* @return the property value if found, otherwise {@link LeoNull}
*/
public LeoObject getProperty(LeoObject member) {
LeoObject result = this.scope.getObjectNoGlobal(member);
if(result==null) {
return LeoObject.NULL;
}
return result;
}
/**
* @return returns the property names, performance note, this is calculated
* new each time.
*/
public LeoArray getPropertyNames() {
LeoMap map = this.scope.getRawObjects();
return map.keys();
}
/**
* @return returns the property objects, performance note, this is calculated
* new each time, moreover any changes to the LeoArray are reflected on this scope.
*/
public LeoArray getProperties() {
return new LeoArray(this.scope.getScopedValues(), this.scope.getNumberOfObjects());
}
/**
* Adds a data member to this {@link LeoScopedObject}
*
* @param member
* @param property
*/
public void addProperty(LeoObject member, LeoObject property) {
this.scope.storeObject(member, property);
}
/**
* Removes the data member from this {@link LeoScopedObject}
* @param member
*/
public void removeProperty(LeoObject member) {
this.scope.removeObject(member);
}
}
<|start_filename|>src/leola/vm/lib/LeolaMethodVarargs.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.lib;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Denote that the native Java method is to accept
* variable arguments from Leola code.
*
* <pre>
* @LeolaMethodVarargs
* public String printf(Object str, LeoObject ... args) {
* ...
* }
*
* ...
* // in Leola
* printf("%s, is awesome and so is: %s", "Brett", "Packers")
*
* </pre>
*
* @author Tony
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface LeolaMethodVarargs {
}
<|start_filename|>src/leola/vm/compiler/EmitterScope.java<|end_filename|>
/*
* see license.txt
*/
package leola.vm.compiler;
import java.util.Stack;
import leola.vm.exceptions.LeolaRuntimeException;
/**
* Used to keep track of the current scope while compiling/emitting bytecode.
*
* @author Tony
*
*/
public class EmitterScope {
/**
* Scope type
* @author Tony
*
*/
public static enum ScopeType {
LOCAL_SCOPE,
OBJECT_SCOPE,
GLOBAL_SCOPE
;
}
/**
* Constants pool
*/
private Constants constants;
/**
* Local variables
*/
private Locals locals;
/**
* Closure 'outer' variables
*/
private Outers outers;
/**
* Max stack space needed for this scope
*/
private int maxstacksize;
/**
* The type of scope this is
*/
private ScopeType scopeType;
/**
* Parent Scope
*/
private EmitterScope parent;
/**
* The bytecode instructions
*/
private Instructions instructions;
private Labels labels;
/**
* Lexical scopes of local variables
*/
private Stack<Integer> lexicalScopes;
/**
* sizes of try or on block statements
*/
private Stack<Integer> blockSize;
/**
* Debug information symbols
*/
private DebugSymbols debugSymbols;
private boolean usesLocals;
private boolean debug;
private boolean hasParamIndexes;
private boolean isVarargs;
private boolean hasBlocks;
private int currentLineNumber;
private int numArgs;
/**
* @param parent
* @param scopeType
*/
public EmitterScope(EmitterScope parent, ScopeType scopeType) {
this.parent = parent;
this.scopeType = scopeType;
this.maxstacksize = 2; /* always leave room for binary operations */
this.usesLocals = false;
this.isVarargs = false;
this.hasBlocks = false;
this.hasParamIndexes = false;
this.currentLineNumber = -1;
this.lexicalScopes = new Stack<Integer>();
this.blockSize = new Stack<Integer>();
this.debugSymbols = new DebugSymbols();
this.usesLocals = scopeType == ScopeType.LOCAL_SCOPE;
this.instructions = new Instructions();
this.labels = new Labels();
}
/**
* @return the debugSymbols
*/
public DebugSymbols getDebugSymbols() {
return debugSymbols;
}
/**
* @return the numArgs
*/
public int getNumArgs() {
return numArgs;
}
/**
* @param numArgs the numArgs to set
*/
public void setNumArgs(int numArgs) {
this.numArgs = numArgs;
}
/**
* @return true if there are variable arguments passed to
* this scope
*/
public boolean hasVarargs() {
return this.isVarargs;
}
/**
* Sets if there are variable arguments passed to
* this scope.
*
* @param hasVarargs
*/
public void setVarargs(boolean hasVarargs) {
this.isVarargs = hasVarargs;
}
/**
* @return true if there are try/on/finally blocks in
* this scope
*/
public boolean hasBlocks() {
return this.hasBlocks;
}
/**
* Lets the compiler know there are try/on/finally blocks
* that need to be handled for this scope.
*/
public void activateBlocks() {
this.hasBlocks = true;
}
/**
* Activate a try or on block, this will capture the
* starting instruction pointer.
*
* @see EmitterScope#popBlock()
* @param instructionPosition
*/
public void activateBlocks(int instructionPosition) {
this.hasBlocks = true;
this.blockSize.add(instructionPosition);
}
/**
* Removes the try or on block, returning the
* starting instruction pointer.
*
* @return the starting instruction pointer of when {@link EmitterScope#activateBlocks(int)}
*/
public int popBlock() {
return blockSize.pop();
}
/**
* @return true if this scope has named parameters
*/
public boolean hasParameterIndexes() {
return this.hasParamIndexes;
}
/**
* This scope has named parameters
*/
public void activateParameterIndexes() {
this.hasParamIndexes = true;
}
/**
* Retrieves the raw instruction set that has been built up.
* @return the fixed array size (i.e., all element in the array are
* populated with an instruction) of the instructions.
*/
public int[] getRawInstructions() {
return this.instructions.truncate();
}
/**
* @return the currentLineNumber
*/
public int getCurrentLineNumber() {
return currentLineNumber;
}
/**
* @param currentLineNumber the currentLineNumber to set
*/
public void setCurrentLineNumber(int currentLineNumber) {
this.currentLineNumber = currentLineNumber;
}
/**
* Determines if this {@link EmitterScope} has a parent
* @return true if there is a parent {@link EmitterScope}
*/
public boolean hasParent() {
return this.parent != null;
}
/**
* @return the parent
*/
public EmitterScope getParent() {
return parent;
}
/**
* @return the scopeType
*/
public ScopeType getScopeType() {
return scopeType;
}
/**
* @return the debug
*/
public boolean isDebug() {
return debug;
}
/**
* @param debug the debug to set
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
/**
* @return true if the current scope stores variables on the stack
* or in the current environment
*/
public boolean usesLocals() {
return usesLocals || !lexicalScopes.isEmpty();
}
/**
* Adds the symbol to the {@link Locals}.
*
* @param reference
* @return the index it is stored in the locals table
*/
public int addLocal(String reference) {
if(isDebug()) {
debugSymbols.store(reference, getInstructionCount());
}
Locals locals = getLocals();
return locals.store(reference);
}
/**
* Adds an instruction
*
* @param instruction
*/
public void addInstr(int instruction) {
instructions.add(instruction);
}
/**
* Reconcile the labels, will correctly mark
* the <code>jump</code> labels with the correct instruction
* positions.
*/
public void reconcileLabels() {
getLabels().reconcileLabels(getInstructions());
}
/**
* @return the instructions
*/
public Instructions getInstructions() {
return instructions;
}
/**
* @return the number of instructions
*/
public int getInstructionCount() {
return getInstructions().getCount();
}
/**
* Mark the beginning of an inner scope
*/
public void markLexicalScope() {
int index = getLocals().getIndex();
lexicalScopes.push(index);
if(isDebug()) {
debugSymbols.startScope(getInstructionCount());
}
}
/**
* Leave the scope
*/
public void unmarkLexicalScope() {
if(lexicalScopes.isEmpty()) {
throw new LeolaRuntimeException("Illegal lexical scope");
}
/*
* This allows us for reusing the stack space
* for other local variables that will be in
* of scope by the time they get here
*/
int index = lexicalScopes.pop();
int currentIndex = getLocals().getIndex();
if(currentIndex != index) {
getLocals().setIndex(index);
}
if(isDebug()) {
debugSymbols.endScope(getInstructionCount());
}
}
/**
* @return the maxstacksize
*/
public int getMaxstacksize() {
return maxstacksize;
}
/**
* Increments the allocated stack size by delta.
* @param delta
*/
public void incrementMaxstacksize(int delta) {
this.maxstacksize += delta;
}
/**
* @return the constants
*/
public Constants getConstants() {
if ( constants == null ) {
constants = new Constants();
}
return constants;
}
/**
* @return true if there are constants in this scope
*/
public boolean hasConstants() {
return constants != null && constants.getNumberOfConstants() > 0;
}
/**
* @return the globals
*/
public Outers getOuters() {
if ( outers == null ) {
outers = new Outers();
}
return outers;
}
/**
* @return true if there are outers in this scope
*/
public boolean hasOuters() {
return outers != null && outers.getNumberOfOuters() > 0;
}
/**
* @return the labels
*/
public Labels getLabels() {
return labels;
}
/**
* @return the locals
*/
public Locals getLocals() {
if ( locals == null ) {
locals = new Locals();
}
return locals;
}
/**
* @return true if there are locals for this scope
*/
public boolean hasLocals() {
return locals != null && locals.getNumberOfLocals() > 0;
}
/**
* Finds a reference, generating an {@link OuterDesc} if found
*
* @param reference
* @return the {@link OuterDesc} that describes the {@link Outer}, which
* includes its local index and the up value (the number of scopes above
* this current scope).
*/
public OuterDesc find(String reference) {
OuterDesc upvalue = null;
int up = 0;
EmitterScope scope = this;
while(scope != null) {
if(scope.hasLocals()) {
Locals locals = scope.getLocals();
int index = locals.get(reference);
if ( index > -1) {
upvalue = new OuterDesc(index, up);
break;
}
}
scope = scope.getParent();
up++;
}
return upvalue;
}
}
<|start_filename|>src/leola/vm/compiler/Outer.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.compiler;
import leola.vm.types.LeoObject;
/**
* An {@link Outer} references a value off of the stack. These are created via Closures.
*
* @author Tony
*
*/
public class Outer {
/**
* A Value that can be obtained from the operation
* stack.
*
* @author Tony
*
*/
public static interface StackValue {
/**
* Retrieve an element from the stack at
* the supplied index.
*
* @param index the index into the stack
* @return the value
*/
LeoObject getStackValue(int index);
/**
* Sets the stack at the supplied index with the
* supplied value.
*
* @param index the index into the stack
* @param value the value to set
*/
void setStackValue(int index, LeoObject value);
}
/**
* Closed over stack value. This is used when the value is
* no longer on the stack, and the Closure is carrying this value
* within its scope (aka the value has been 'closed' over).
*
* @author Tony
*
*/
private static class ClosedStackValue implements StackValue {
private LeoObject value;
/**
* @param value
*/
public ClosedStackValue(LeoObject value) {
this.value = value;
}
@Override
public LeoObject getStackValue(int index) {
return value;
}
@Override
public void setStackValue(int index, LeoObject value) {
this.value = value;
}
}
private StackValue stack;
private int index;
/**
* @param stack
* @param index
*/
public Outer(StackValue stack, int index) {
this.stack = stack;
this.index = index;
}
/**
* @return the index
*/
public int getIndex() {
return index;
}
/**
* Sets the value
* @param value
*/
public void setValue(LeoObject value) {
stack.setStackValue(index, value);
}
/**
* @return the value
*/
public LeoObject getValue() {
return stack.getStackValue(index);
}
/**
* The value is no longer on the stack,
* so therefore we take the current value and store
* it. This value is now "closed" upon for a closure.
*/
public void close() {
this.stack = new ClosedStackValue(this.stack.getStackValue(this.index));
this.index = 0;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getValue().toString();
}
}
<|start_filename|>src/leola/frontend/Source.java<|end_filename|>
package leola.frontend;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import leola.frontend.tokens.ErrorToken;
import leola.frontend.tokens.Token;
/**
* Handles reading a source code file
*
* @author Tony
*
*/
public class Source implements AutoCloseable {
public static final char EOL = '\n'; // end-of-line character
public static final char EOF = (char) 0; // end-of-file character
private final Token errorToken;
private BufferedReader reader; // reader for the source program
private String line; // source line
private int lineNum; // current source line number
private int currentPos; // current source line position
private List<String> lines;
/**
*
* @param reader
* the reader for the source program
* @throws IOException
* if an I/O error occurred
*/
public Source(Reader reader) {
this.lineNum = 0;
this.currentPos = -2; // set to -2 to read the first source line
this.lines = new ArrayList<>();
this.reader = (reader instanceof BufferedReader) ?
(BufferedReader)reader : new BufferedReader(reader);
this.errorToken = new ErrorToken(this, ErrorCode.UNKNOWN_ERROR, "");
}
public String getLine(int lineNumber) {
if(lineNumber < 1 || lineNumber > this.lines.size()) {
throw new ParseException(errorToken, "Invalid line number: " + lineNumber);
}
return this.lines.get(lineNumber - 1);
}
/**
* Getter.
*
* @return the current source line number.
*/
public int getLineNum() {
return lineNum;
}
/**
* Getter.
*
* @return the position of the next source character in the current source
* line.
*/
public int getPosition() {
return currentPos;
}
/**
* Return the source character at the current position.
*
* @return the source character at the current position.
* @throws Exception
* if an error occurred.
*/
public char currentChar() {
// First time?
if (currentPos == -2) {
readLine();
return nextChar();
}
// At end of file?
else if (line == null) {
return EOF;
}
// At end of line?
else if ((currentPos == -1) || (currentPos == line.length())) {
return EOL;
}
// Need to read the next line?
else if (currentPos > line.length()) {
readLine();
return nextChar();
}
// Return the character at the current position.
else {
return line.charAt(currentPos);
}
}
/**
* Consume the current source character and return the next character.
*
* @return the next source character.
*/
public char nextChar() {
++currentPos;
return currentChar();
}
/**
* Return the source character following the current character without
* consuming the current character.
*
* @return the following character.
*/
public char peekChar() {
return peekAhead(1);
}
/**
* Looks ahead 'pos' positions
*
* @param pos
* @return the peeked character
*/
public char peekAhead(int pos) {
currentChar();
if (line == null) {
return EOF;
}
int nextPos = currentPos + pos;
return nextPos < line.length() ? line.charAt(nextPos) : EOL;
}
/**
* @return true if at the end of the line, else return false.
*/
public boolean atEol() {
return (line != null) && (currentPos == line.length());
}
/**
* @return true if at the end of the file, else return false.
*/
public boolean atEof() {
// First time?
if (currentPos == -2) {
readLine();
}
return line == null;
}
/**
* Skip the rest of the current input line by forcing the next read to read
* a new line.
*
*/
public void skipToNextLine() {
if (line != null) {
currentPos = line.length() + 1;
}
}
public String getCurrentLine() {
return this.line;
}
/**
* Read the next source line.
*
* @throws IOException
* if an I/O error occurred.
*/
private void readLine() {
try {
line = reader.readLine(); // null when at the end of the source
currentPos = -1;
if (line != null) {
++lineNum;
}
lines.add(line);
}
catch(IOException e) {
throw new ParseException(errorToken, e);
}
}
/**
* Close the source.
*/
@Override
public void close() {
this.lines.clear();
if (reader != null) {
try {
reader.close();
}
catch(IOException e) {
throw new ParseException(errorToken, e);
}
}
}
}
<|start_filename|>src/leola/ast/UnaryExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.frontend.tokens.Token;
import leola.vm.EvalException;
/**
* Unary operator
*
* @author Tony
*
*/
public class UnaryExpr extends Expr {
private Expr expr;
private Token op;
/**
* @param expr
*/
public UnaryExpr(Expr expr, Token op) {
this.expr = becomeParentOf(expr);
this.op = op;
}
/**
* @return the op
*/
public Token getOp() {
return op;
}
/**
* @return the expr
*/
public Expr getExpr() {
return expr;
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
}
<|start_filename|>src/leola/lang/sql/SqlLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.sql;
import java.sql.DriverManager;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoObject;
/**
* Handles all of the SQL/Persistence stuff
*
* @author Tony
*
*/
public class SqlLeolaLibrary implements LeolaLibrary {
private Leola runtime;
/* (non-Javadoc)
* @see leola.frontend.LeolaLibrary#init(leola.frontend.Leola)
*/
@Override
@LeolaIgnore
public void init(Leola leola, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = leola;
this.runtime.putIntoNamespace(this, namespace);
}
/**
* Sets the driver
*
* @param driver
* @throws Exception
*/
public void driver(LeoObject driver) throws Exception {
Class.forName(driver.toString());
}
public void usedb2() throws Exception {
// runtime.getResourceLoader().include ("db2jcc.jar");
// runtime.getResourceLoader().include ("db2jcc_license_cu.jar");
Class.forName("com.ibm.db2.jcc.DB2Driver");
}
/**
* Connects to a database.
*
* @param url
* @param username
* @param pw
* @return the {@link Conn} object which represents the database connection
* @throws Exception
*/
public Conn connect(LeoObject url, LeoObject username, LeoObject pw) throws Exception {
return new Conn(DriverManager.getConnection(url.toString(), username.toString(), pw.toString()));
}
}
<|start_filename|>src/leola/vm/EvalException.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm;
import leola.ast.ASTNode;
/**
* An evaluation exception, means that a bit of code was not able to be executed as intended.
*
* @author Tony
*
*/
public class EvalException extends RuntimeException {
/**
* SUID
*/
private static final long serialVersionUID = 159371812953160598L;
/**
*
*/
public EvalException() {
}
/**
* @param message
*/
public EvalException(ASTNode node, String message) {
super(message + " at line: " + node.getLineNumber());
}
/**
* @param message
*/
public EvalException(String message) {
super(message);
}
/**
* @param cause
*/
public EvalException(Throwable cause) {
super(cause);
}
/**
* @param message
* @param cause
*/
public EvalException(String message, Throwable cause) {
super(message, cause);
}
}
<|start_filename|>src/leola/lang/SystemLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoNamespace;
/**
* The system core functions
*
* @author Tony
*
*/
public class SystemLeolaLibrary implements LeolaLibrary {
/**
* The runtime
*/
private Leola runtime;
private Random random;
/* (non-Javadoc)
* @see leola.frontend.LeolaLibrary#init(leola.frontend.Leola)
*/
@LeolaIgnore
public void init(Leola runtime, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = runtime;
this.random = new Random();
this.runtime.putIntoNamespace(this, namespace);
}
public final void setPath(String paths) {
runtime.setIncludePath(paths);
}
public final void addPath(String path) throws Exception {
File filePath = new File(path);
runtime.getIncludePath().add(filePath);
if(filePath.isFile() && filePath.getName().toLowerCase().endsWith(".jar")) {
LangLeolaLibrary.loadJar(path);
}
else {
LangLeolaLibrary.loadJars(path);
}
}
public final String getPath() {
String result = "";
List<File> lpath = runtime.getIncludePath();
for(File file : lpath) {
result += file.getAbsolutePath() + ";";
}
return result;
}
/**
* Sets the java.library.path
* @param path
*/
public final void setLibraryPath(String path) throws Exception {
System.setProperty( "java.library.path", path );
Field fieldSysPath = ClassLoader.class.getDeclaredField( "usr_paths" );
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, new String[] {path} );
}
public final String javapath() {
StringBuilder sb=new StringBuilder(1024);
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
//Get the URLs
URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();
for(int i=0; i< urls.length; i++) {
sb.append(";").append(urls[i].getFile());
}
return sb.toString();
}
public final int random(int max) {
return this.random.nextInt(max);
}
public final long memused() {
Runtime rt = Runtime.getRuntime();
return rt.totalMemory() - rt.freeMemory();
}
public final void gc() {
Runtime.getRuntime().gc();
}
public final Process execute(String application, LeoArray args, String workingdir) throws Exception {
String[] cmds = null;
if ( args!=null) {
cmds = new String[args.size() + 1];
for(int i = 0; i < args.size(); i++) {
cmds[i+1] = args.get(i).toString();
}
}
else {
cmds = new String[1];
}
cmds[0] = application;
Process process = Runtime.getRuntime().exec(cmds, null, new File(workingdir));
return process;
}
public final void pipe(InputStream iStream) throws Exception {
Scanner scanner = new Scanner(iStream);
try {
while(scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
}
finally {
scanner.close();
}
}
/**
* Sleeps
*
* @param time
* @throws Exception
*/
public final void sleep(long time) throws Exception {
Thread.sleep(time);
}
/**
* Exits the JVM
*
* @param code
* @throws Exception
*/
public final void exit(int code) throws Exception {
java.lang.System.exit(code);
}
}
<|start_filename|>src/leola/lang/DateLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoNamespace;
/**
* Date functions
*
* @author Tony
*
*/
public class DateLeolaLibrary implements LeolaLibrary {
/**
* The runtime
*/
private Leola runtime;
/* (non-Javadoc)
* @see leola.frontend.LeolaLibrary#init(leola.frontend.Leola)
*/
@LeolaIgnore
public void init(Leola runtime, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = runtime;
this.runtime.putIntoNamespace(this, namespace);
}
/**
* Creates a new Date based off of the supplied string date, in the specified format
* @param date
* @param format
* @return the new Date
* @throws Exception
*/
public Date newDate(String date, String format) throws Exception {
return new SimpleDateFormat(format).parse(date);
}
/**
* Formats the supplied {@link Date}
* @param date
* @param format
* @return the formated string
*/
public String format(Date date, String format) {
DateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
/**
* Sets the default time zone
*
* @param timeZone
*/
public void setTimeZone(String timeZone) {
TimeZone.setDefault(TimeZone.getTimeZone(timeZone));
}
/**
* @return retrieves the default time zone
*/
public String getTimeZone() {
return TimeZone.getDefault().getID();
}
/**
* @param date
* @return the msec
*/
public int getMSec(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.MILLISECOND);
}
/**
* @param date
* @return the second
*/
public int getSecond(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.SECOND);
}
/**
* @param date
* @return the minute
*/
public int getMinute(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.MINUTE);
}
/**
* @param date
* @return the hour
*/
public int getHour(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.HOUR);
}
/**
* @param date
* @return the day
*/
public int getDay(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.DAY_OF_MONTH);
}
/**
* @param date
* @return the month
*/
public int getMonth(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.MONTH);
}
/**
* @param date
* @return the Year
*/
public int getYear(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.YEAR);
}
/**
* @param date
* @return the era
*/
public int getEra(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.ERA);
}
/**
* Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
* @param date
* @return the time
*/
public long toMSec(Date date) {
return date.getTime();
}
/**
* Converts the {@link Date} to a {@link Timestamp}
* @param date
* @return the time
*/
public Timestamp toTimestamp(Date date) {
return new Timestamp(date.getTime());
}
/**
* @param time
* @return the supplied time to a {@link Date} object
*/
public Date toDate(long time) {
return new Date(time);
}
/**
* @return the current time in milliseconds
*/
public long time() {
return System.currentTimeMillis();
}
/**
* @return the current time in nanoseconds
*/
public long timens() {
return System.nanoTime();
}
/**
* @return the current {@link Date}
*/
public Date now() {
return new Date();
}
private Date adjustDate(int type, Date date, int amount) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(type, amount);
return c.getTime();
}
/**
* Add/subtract the number of milli-seconds to the supplied date
*
* @param date
* @param msec
* @return the adjusted {@link Date}
*/
public Date addMSecs(Date date, int msec) {
return adjustDate(Calendar.MILLISECOND, date, msec);
}
/**
* Add/subtract the number of seconds to the supplied date
*
* @param date
* @param seconds
* @return the adjusted {@link Date}
*/
public Date addSeconds(Date date, int seconds) {
return adjustDate(Calendar.SECOND, date, seconds);
}
/**
* Add/subtract the number of minutes to the supplied date
*
* @param date
* @param minutes
* @return the adjusted {@link Date}
*/
public Date addMinutes(Date date, int minutes) {
return adjustDate(Calendar.MINUTE, date, minutes);
}
/**
* Add/subtract the number of hours to the supplied date
*
* @param date
* @param hours
* @return the adjusted {@link Date}
*/
public Date addHours(Date date, int hours) {
return adjustDate(Calendar.HOUR, date, hours);
}
/**
* Add/subtract the number of days to the supplied date
*
* @param date
* @param days
* @return the adjusted {@link Date}
*/
public Date addDays(Date date, int days) {
return adjustDate(Calendar.DATE, date, days);
}
/**
* Add/subtract the number of months to the supplied date
*
* @param date
* @param months
* @return the adjusted {@link Date}
*/
public Date addMonths(Date date, int months) {
return adjustDate(Calendar.MONTH, date, months);
}
/**
* Add/subtract the number of Years to the supplied date
*
* @param date
* @param years
* @return the adjusted {@link Date}
*/
public Date addYears(Date date, int years) {
return adjustDate(Calendar.YEAR, date, years);
}
/**
* Add/subtract the era to the supplied date
*
* @param date
* @param era
* @return the adjusted {@link Date}
*/
public Date addEra(Date date, int era) {
return adjustDate(Calendar.ERA, date, era);
}
}
<|start_filename|>test/leola/FromLeoObjectTest.java<|end_filename|>
package leola;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoObject;
public class FromLeoObjectTest {
public static class TestA {
public boolean b;
public char c;
public byte byt;
public short s;
public int i;
public float f;
public double d;
public long l;
public Boolean B;
public Character C;
public Byte Byt;
public Short S;
public Integer I;
public Float F;
public Double D;
public Long L;
public ArrayList<String> stringArray;
public List<TestA> testAArray;
public HashMap<String, String> stringMap;
public Map<String, TestA> testAMap;
public TestA testA;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((B == null) ? 0 : B.hashCode());
result = prime * result + ((Byt == null) ? 0 : Byt.hashCode());
result = prime * result + ((C == null) ? 0 : C.hashCode());
result = prime * result + ((D == null) ? 0 : D.hashCode());
result = prime * result + ((F == null) ? 0 : F.hashCode());
result = prime * result + ((I == null) ? 0 : I.hashCode());
result = prime * result + ((L == null) ? 0 : L.hashCode());
result = prime * result + ((S == null) ? 0 : S.hashCode());
result = prime * result + (b ? 1231 : 1237);
result = prime * result + byt;
result = prime * result + c;
long temp;
temp = Double.doubleToLongBits(d);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Float.floatToIntBits(f);
result = prime * result + i;
result = prime * result + (int) (l ^ (l >>> 32));
result = prime * result + s;
result = prime * result + ((stringArray == null) ? 0 : stringArray.hashCode());
result = prime * result + ((stringMap == null) ? 0 : stringMap.hashCode());
result = prime * result + ((testA == null) ? 0 : testA.hashCode());
result = prime * result + ((testAArray == null) ? 0 : testAArray.hashCode());
result = prime * result + ((testAMap == null) ? 0 : testAMap.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestA other = (TestA) obj;
if (B == null) {
if (other.B != null)
return false;
} else if (!B.equals(other.B))
return false;
if (Byt == null) {
if (other.Byt != null)
return false;
} else if (!Byt.equals(other.Byt))
return false;
if (C == null) {
if (other.C != null)
return false;
} else if (!C.equals(other.C))
return false;
if (D == null) {
if (other.D != null)
return false;
} else if (!D.equals(other.D))
return false;
if (F == null) {
if (other.F != null)
return false;
} else if (!F.equals(other.F))
return false;
if (I == null) {
if (other.I != null)
return false;
} else if (!I.equals(other.I))
return false;
if (L == null) {
if (other.L != null)
return false;
} else if (!L.equals(other.L))
return false;
if (S == null) {
if (other.S != null)
return false;
} else if (!S.equals(other.S))
return false;
if (b != other.b)
return false;
if (byt != other.byt)
return false;
if (c != other.c)
return false;
if (Double.doubleToLongBits(d) != Double.doubleToLongBits(other.d))
return false;
if (Float.floatToIntBits(f) != Float.floatToIntBits(other.f))
return false;
if (i != other.i)
return false;
if (l != other.l)
return false;
if (s != other.s)
return false;
if (stringArray == null) {
if (other.stringArray != null)
return false;
} else if (!stringArray.equals(other.stringArray))
return false;
if (stringMap == null) {
if (other.stringMap != null)
return false;
} else if (!stringMap.equals(other.stringMap))
return false;
if (testA == null) {
if (other.testA != null)
return false;
} else if (!testA.equals(other.testA))
return false;
if (testAArray == null) {
if (other.testAArray != null)
return false;
} else if (!testAArray.equals(other.testAArray))
return false;
if (testAMap == null) {
if (other.testAMap != null)
return false;
} else if (!testAMap.equals(other.testAMap))
return false;
return true;
}
}
@Test
public void test() {
LeoMap types = new LeoMap();
types.putByString("b", LeoObject.valueOf(true));
types.putByString("c", LeoObject.valueOf('c'));
types.putByString("byt", LeoObject.valueOf( (byte) 42));
types.putByString("s", LeoObject.valueOf( (short) 34532 ));
types.putByString("i", LeoObject.valueOf( 2345624));
types.putByString("f", LeoObject.valueOf( 1.5f ));
types.putByString("d", LeoObject.valueOf( 5.2d));
types.putByString("l", LeoObject.valueOf( 1231534234242342L ));
types.putByString("B", LeoObject.valueOf(true));
types.putByString("C", LeoObject.valueOf('c'));
types.putByString("Byt", LeoObject.valueOf( (byte) 42));
types.putByString("S", LeoObject.valueOf( (short) 34532 ));
types.putByString("I", LeoObject.valueOf( 2345624));
types.putByString("F", LeoObject.valueOf( 1.5f ));
types.putByString("D", LeoObject.valueOf( 5.2d));
types.putByString("L", LeoObject.valueOf( 1231534234242342L ));
LeoArray stringArray = new LeoArray();
stringArray.add(LeoObject.valueOf("a"));
stringArray.add(LeoObject.valueOf("b"));
types.putByString("stringArray", stringArray);
TestA aa = new TestA();
aa.b = true;
LeoArray testAArray = new LeoArray();
testAArray.add(LeoObject.valueOf(aa));
testAArray.add(types.clone());
types.putByString("testAArray", testAArray);
TestA a = LeoObject.fromLeoObject(types, TestA.class);
assertEquals(types.getBoolean("b"), a.b);
assertEquals(types.getString("c").charAt(0), a.c);
assertEquals(types.getInt("byt"), a.byt);
assertEquals(types.getInt("s"), a.s);
assertEquals(types.getInt("i"), a.i);
assertEquals( (float)types.getDouble("f"), a.f, 0.001f);
assertEquals(types.getDouble("d"), a.d, 0.001f);
assertEquals(types.getLong("l"), a.l);
assertEquals(types.getBoolean("B"), a.B);
assertEquals((Character)types.getString("C").charAt(0), a.C);
assertEquals((byte)types.getInt("Byt"), (byte)a.Byt);
assertEquals((short)types.getInt("S"), (short)a.S);
assertEquals((Integer)types.getInt("I"), a.I);
assertEquals( (float)types.getDouble("F"), a.F, 0.001f);
assertEquals(types.getDouble("D"), a.D, 0.001f);
assertEquals((Long)types.getLong("L"), a.L);
assertNotNull(a.stringArray);
assertEquals(2, a.stringArray.size());
int i = 0;
for(String s : a.stringArray) {
assertEquals(stringArray.get(i++).toString(), s);
}
assertNotNull(a.testAArray);
assertEquals(2, a.testAArray.size());
assertEquals(testAArray.get(0), aa);
//assertEquals(testAArray.get(1), );
}
public static enum EnumType {
A,B
}
public static class TestEnum {
public EnumType e;
}
@Test
public void testEnum() {
LeoMap map = new LeoMap();
map.putByString("e", LeoObject.valueOf("A"));
TestEnum e = LeoObject.fromLeoObject(map, TestEnum.class);
assertEquals(EnumType.A, e.e);
}
}
<|start_filename|>src/leola/frontend/tokens/StringToken.java<|end_filename|>
package leola.frontend.tokens;
import static leola.frontend.ErrorCode.UNEXPECTED_EOF;
import static leola.frontend.Source.EOF;
import static leola.frontend.tokens.TokenType.ERROR;
import static leola.frontend.tokens.TokenType.STRING;
import leola.frontend.Source;
/**
* The String token; which includes normal strings and verbatim strings.
*
* @author Tony
*
*/
public class StringToken extends Token {
public static final char STRING_CHAR = '"';
public static final String MULTI_STRING = "\"\"\"";
/**
* Constructor.
* @param source the source from where to fetch the token's characters.
*/
public StringToken(Source source) {
super(source);
}
/**
* Extract a Leola string token from the source.
*/
@Override
protected void extract() {
StringBuilder textBuffer = new StringBuilder();
StringBuilder valueBuffer = new StringBuilder();
char currentChar = nextChar(); // consume initial quote
textBuffer.append(STRING_CHAR);
boolean inBlockString = false;
boolean isStart = true;
// Get string characters.
do {
// Replace any whitespace character with a blank.
// if (Character.isWhitespace(currentChar)) {
// currentChar = ' ';
// }
if (isEscape(currentChar)) {
char escape = applyEscape(currentChar);
textBuffer.append(escape);
valueBuffer.append(escape);
currentChar = currentChar();
}
else if (( (inBlockString || currentChar != STRING_CHAR) ) && (currentChar != EOF)) {
textBuffer.append(currentChar);
valueBuffer.append(currentChar);
currentChar = nextChar(); // consume character
}
// Look for multi comments
if (currentChar == STRING_CHAR) {
if ((currentChar == STRING_CHAR) && (peekChar() == STRING_CHAR)) {
char thirdChar = peekAhead(isStart ? 1 : 2); // look for the third quote
if ( thirdChar == STRING_CHAR ) {
textBuffer.append(STRING_CHAR + STRING_CHAR);
// valueBuffer.append(currentChar); // append single-quote
currentChar = nextChar(); // consume quotes
currentChar = nextChar();
inBlockString = !inBlockString;
}
}
}
isStart = false;
} while ((inBlockString || currentChar != STRING_CHAR) && (currentChar != EOF));
if (currentChar == STRING_CHAR) {
nextChar(); // consume final quote
textBuffer.append(STRING_CHAR);
type = STRING;
value = valueBuffer.toString();
}
else {
type = ERROR;
value = UNEXPECTED_EOF;
}
text = textBuffer.toString();
}
/**
* Determines if this is an escape character.
*
* @param currentChar
* @return
*/
private boolean isEscape(char currentChar) {
boolean isEscape = false;
if ( currentChar == '\\' ) {
char nextChar = peekChar();
switch(nextChar) {
case 't':
case 'b':
case 'n':
case 'r':
case 'f':
case '\'':
case '\"':
case '\\':
isEscape = true;
break;
default:
isEscape = false;
}
}
return isEscape;
}
/**
* Eat to the end of the escape
* @param currentChar
* @return
*/
private char applyEscape(char currentChar) {
char result = currentChar;
char nextChar = nextChar();
switch(nextChar) {
case 't':
result = "\t".charAt(0);
break;
case 'b':
result = "\b".charAt(0);
break;
case 'n':
result = "\n".charAt(0);
break;
case 'r':
result = "\r".charAt(0);
break;
case 'f':
result = "\f".charAt(0);
break;
case '\'':
result = "\'".charAt(0);
break;
case '\"':
result = "\"".charAt(0);
break;
case '\\':
result = "\\".charAt(0);
break;
default:
throw new IllegalArgumentException("Must invoke isEscape first!");
}
nextChar(); // eat this char
return result;
}
}
<|start_filename|>src/leola/lang/CollectionsLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentMap;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.lib.LeolaMethod;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoGenerator;
import leola.vm.types.LeoInteger;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
/**
* Base collections API
*
* @author Tony
*
*/
public class CollectionsLeolaLibrary implements LeolaLibrary {
private Leola runtime;
/* (non-Javadoc)
* @see leola.frontend.LeolaLibrary#init(leola.frontend.Leola)
*/
@LeolaIgnore
public void init(Leola leola, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = leola;
runtime.putIntoNamespace(this, namespace);
}
/**
* Converts the optional supplied {@link LeoMap} into a {@link ConcurrentMap}.
*
* @param map
* @return the {@link ConcurrentMap}
*/
public ConcurrentMap<LeoObject, LeoObject> concurrentMap(LeoMap map) {
if(map == null) {
map = new LeoMap();
}
/* Since the LeoMap class does not use an internal java.util.Map structure;
* we have to add in some of the common API's to the concurrentMap. This
* is fairly sub-optimal from a development/maintenance perspective...
*/
return new ConcurrentHashMap<LeoObject, LeoObject>(map) {
private static final long serialVersionUID = 6526027801906112095L;
@LeolaMethod(alias="$sindex")
public LeoObject $sindex(LeoObject key, LeoObject value) {
return put(key,value);
}
@LeolaMethod(alias="$index")
public LeoObject $index(LeoObject key) {
return get(key);
}
@LeolaMethod(alias="has")
public boolean has(LeoObject key) {
return this.containsKey(key);
}
@LeolaMethod(alias="empty")
public boolean empty() {
return this.isEmpty();
}
@LeolaMethod(alias="vals")
public LeoArray vals() {
return new LeoArray(new ArrayList<LeoObject>(this.values()));
}
@LeolaMethod(alias="foreach")
public void foreach(LeoObject function) {
if(function != null) {
for(Map.Entry<LeoObject, LeoObject> entry : this.entrySet()) {
LeoObject key = entry.getKey();
if(key != null) {
LeoObject value = entry.getValue();
LeoObject result = function.xcall(key, value);
if(LeoObject.isTrue(result)) {
break;
}
}
}
}
}
@LeolaMethod(alias="filter")
public ConcurrentMap<LeoObject, LeoObject> filter(LeoObject function) {
if(function != null) {
ConcurrentMap<LeoObject, LeoObject> map = concurrentMap(null);
for(Map.Entry<LeoObject, LeoObject> entry : this.entrySet()) {
LeoObject key = entry.getKey();
if(key != null) {
LeoObject value = entry.getValue();
if( LeoObject.isTrue(function.xcall(key, value)) ) {
map.put(key, value);
}
}
}
return map;
}
return this;
}
@LeolaMethod(alias="map")
public ConcurrentMap<LeoObject, LeoObject> map(LeoObject function) {
if(function != null) {
ConcurrentMap<LeoObject, LeoObject> map = concurrentMap(null);
for(Map.Entry<LeoObject, LeoObject> entry : this.entrySet()) {
LeoObject key = entry.getKey();
if(key != null) {
LeoObject value = entry.getValue();
value = function.xcall(key, value);
map.put(key, value);
}
}
return map;
}
return this;
}
};
}
/**
* Creates a concurrent Deque data structure based off of the data in the {@link LeoArray}
*
* @param array
* @return the concurrent data structure
*/
public ConcurrentLinkedDeque<LeoObject> concurrentDeque(LeoArray array) {
if(array!=null && !array.isEmpty()) {
return new ConcurrentLinkedDeque<LeoObject>(array);
}
return new ConcurrentLinkedDeque<LeoObject>();
}
/**
* Creates a concurrent {@link Set} data structure based off of the data in the {@link LeoArray}
*
* @param array
* @return the concurrent {@link Set} data structure
*/
public Set<LeoObject> concurrentSet(LeoArray array) {
Set<LeoObject> set = Collections.newSetFromMap(new ConcurrentHashMap<LeoObject, Boolean>());
if(array!=null && !array.isEmpty()) {
for(int i = 0; i < array.size(); i++) {
LeoObject v = array.get(i);
set.add(v);
}
}
return set;
}
/**
* Repeats the function N times
*
* @param n
* @param function
*/
public final void repeat(int n, LeoObject function){
for(int i = 0; i < n; i++) {
LeoObject result = function.xcall(LeoInteger.valueOf(i));
if ( LeoObject.isTrue(result) ) {
break;
}
}
}
/**
* returns the length of the array
*
* @param array
* @return the length
*/
public final int length(LeoObject array) {
if ( array == null ) return 0;
switch(array.getType()) {
case NULL: return 0;
case STRING: return ((LeoString)array.as()).getString().length();
case ARRAY: return ((LeoArray)array.as()).size();
case MAP: return ((LeoMap)array.as()).size();
default: throw new IllegalArgumentException("Illegal Argument type: " + array);
}
}
/**
* Iterates through the array invoking the call back.
*
* @param list
* @param function
* @return the object returned from the function is true
*/
public final LeoObject foreach(LeoObject list, LeoObject function) {
LeoObject result = LeoNull.LEONULL;
if(list != null) {
switch(list.getType()) {
case ARRAY: {
LeoArray array = list.as();
result = array.foreach(function);
break;
}
case MAP: {
LeoMap map = list.as();
result = map.foreach(function);
break;
}
case STRING: {
LeoString str = list.as();
result = str.foreach(function);
break;
}
case GENERATOR: {
LeoGenerator gen = list.as();
result = gen.foreach(function);
break;
}
default: {
}
}
}
return result;
}
/**
* Iterates through the array.
*
* @param obj
* @param start
* @param end
* @param function
*/
@LeolaMethod(alias="for")
public void __for(LeoObject obj, int start, int end, LeoObject function) {
switch(obj.getType()) {
case ARRAY: {
LeoArray array = obj.as();
array._for(start, end, function);
break;
}
case STRING: {
LeoString string = obj.as();
string._for(start, end, function);
break;
}
default:
}
}
/**
* Iterates through the array invoking the call back filling the
* array
*
* @param array
* @param function
* @return the supplied array
*/
public final LeoArray fill(LeoArray array, LeoObject function) {
return array.fill(function);
}
private void checkTypes(LeoObject start, LeoObject end) {
if(start.getType() != end.getType()) {
throw new LeolaRuntimeException("Ranges do not match in type: " + start.getType() + " vs. " + end.getType());
}
}
/**
* Constructs a list given the range.
*
* @param start
* @param end
* @return the {@link LeoArray} of the range
*/
public final LeoObject range(LeoObject start, LeoObject end) {
checkTypes(start, end);
LeoObject result = LeoNull.LEONULL;
switch(start.getType()) {
case LONG:
case INTEGER: {
int s = start.asInt();
int e = end.asInt();
LeoArray r = new LeoArray( Math.abs(e-s) );
for(; s < e; s++) {
r.add(LeoInteger.valueOf(s));
}
result = r;
break;
}
default: {
}
}
return result;
}
/**
* returns a sequence consisting of those items from the sequence for which function(item) is true
*
* @param list (either an Array, Map or String)
* @param function
* @return the filtered list
*/
public final LeoObject filter(LeoObject list, LeoObject function) {
LeoObject result = LeoNull.LEONULL;
switch(list.getType()) {
case STRING: {
LeoString string = list.as();
result = string.filter(function);
break;
}
case ARRAY: {
LeoArray array = list.as();
result = array.filter(function);
break;
}
case MAP: {
LeoMap map = list.as();
result = map.filter(function);
break;
}
case GENERATOR: {
LeoGenerator gen = list.as();
result = gen.filter(function);
break;
}
default: {
}
}
return result;
}
/**
* calls function(item) for each of the sequence’s items and returns a list of the return values.
*
* @param list (either an Array or String)
* @param function
* @return the resulting list
*/
public final LeoObject map(LeoObject list, LeoObject function) {
LeoObject result = LeoNull.LEONULL;
switch(list.getType()) {
case STRING: {
LeoString string = list.as();
result = string.map(function);
break;
}
case ARRAY: {
LeoArray array = list.as();
result = array.map(function);
break;
}
case MAP: {
LeoMap map = list.as();
result = map.map(function);
break;
}
case GENERATOR: {
LeoGenerator gen = list.as();
result = gen.map(function);
break;
}
default: {
}
}
return result;
}
/**
* Reduces all of the values in the list into one value.
*
* @param list (either an Array or Generator)
* @param function
* @return the resulting object
*/
public final LeoObject reduce(LeoObject list, LeoObject function) {
LeoObject result = LeoNull.LEONULL;
switch(list.getType()) {
case ARRAY: {
LeoArray array = list.as();
result = array.reduce(function);
break;
}
case GENERATOR: {
LeoGenerator gen = list.as();
result = gen.reduce(function);
break;
}
default: {
}
}
return result;
}
}
<|start_filename|>src/leola/vm/types/LeoNamespace.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import leola.vm.Leola;
import leola.vm.Scope;
import leola.vm.compiler.Bytecode;
import leola.vm.compiler.Outer;
import leola.vm.lib.LeolaMethod;
import leola.vm.util.ClassUtil;
/**
* Defines a namespace.
*
* @author Tony
*
*/
public class LeoNamespace extends LeoScopedObject {
/**
* The namespaces name
*/
private LeoObject name;
/**
* @param scope
* @param name
*/
public LeoNamespace(Scope scope, LeoObject name) {
this(null, null, scope, name);
}
/**
* @param runtime
* @param code
* @param scope
* @param name
*/
public LeoNamespace(Leola runtime, Bytecode code, Scope scope, LeoObject name) {
super(LeoType.NAMESPACE, scope, (code !=null ) ? code.numOuters : 0);
this.name = name;
addProperty(LeoString.valueOf("this"), this);
// NOTE, we can't execute the bytecode here because
// the outers will not be set at this point
// if ( code != null && runtime != null ) {
// runtime.execute(this, code);
// }
}
/**
* Stores the Java Object into this {@link LeoNamespace}
*
* @param jObject
*/
public void store(Object jObject) {
Scope scope = getScope();
Class<?> nClass = jObject.getClass();
List<Method> methods = ClassUtil.getAllDeclaredMethods(nClass);
for(Method m: methods) {
LeoNativeFunction func = new LeoNativeFunction(m, jObject);
if(m.isAnnotationPresent(LeolaMethod.class)) {
scope.storeObject(m.getAnnotation(LeolaMethod.class).alias(), func);
}
else {
scope.storeObject(m.getName(), func);
}
}
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#toString()
*/
@Override
public String toString() {
return String.format("[ %s @ %s ]", this.getType(), this.name);
}
/**
* @return the name
*/
public LeoObject getName() {
return name;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isNamespace()
*/
@Override
public boolean isNamespace() {
return true;
}
/**
* Overrides the previous outers
* @param outers
*/
public void setOuters(Outer[] outers) {
this.outers = outers;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#add(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $add(LeoObject other) {
if (other.isString()) {
return LeoString.valueOf(toString() + other.toString());
}
return super.$add(other);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#eq(leola.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
boolean isEquals = (other == this);
if ( !isEquals && other != null ) {
if ( other.isOfType(LeoType.NAMESPACE)) {
LeoNamespace ns = other.as();
isEquals = this.name.equals(ns.name);
}
}
return isEquals;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gt(leola.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lt(leola.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return this;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#write(java.io.DataOutput)
*/
@Override
public void write(DataOutput out) throws IOException {
}
}
<|start_filename|>src/leola/lang/sql/SqlParameterParser.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.sql;
import java.util.HashSet;
import java.util.Set;
/**
* Parses sql parameters to and from JDBC style parameters.
*
*
* @author spring framework
*
*/
public class SqlParameterParser {
/** Flag for Parameterized token */
private final static char PARAMETER_TOKEN = ':';
/** JDBC Parameter type token */
//private final static char JDBC_TOKEN = '?';
/**
* Set of characters that qualify as parameter separators,
* indicating that a parameter name in a SQL String has ended.
*/
private static final char[] PARAMETER_SEPARATORS =
{'"', '\'', ':', '&', ',', ';', '(', ')', '|', '=', '+', '-', '*', '%', '/', '\\', '<', '>', '^'};
/**
* Parse the SQL statement and locate any placeholders or named parameters.
* Named parameters are substituted for a JDBC placeholder.
* @param sql the SQL statement
* @return the parsed statement, represented as ParsedSql instance
*/
public static ParsedSql parseSqlStatement(String sql) {
Set<String> namedParameters = new HashSet<String>();
ParsedSql parsedSql = new ParsedSql(sql);
char[] statement = sql.toCharArray();
boolean withinQuotes = false;
char currentQuote = '-';
int i = 0;
while (i < statement.length) {
char c = statement[i];
if (withinQuotes) {
if (c == currentQuote) {
withinQuotes = false;
currentQuote = '-';
}
}
else {
if (c == '"' || c == '\'') {
withinQuotes = true;
currentQuote = c;
}
else {
if (c == PARAMETER_TOKEN || c == '&') {
int j = i + 1;
if (j < statement.length && statement[j] == PARAMETER_TOKEN && c == PARAMETER_TOKEN) {
// Postgres-style "::" casting operator - to be skipped.
i = i + 2;
continue;
}
while (j < statement.length && !isParameterSeparator(statement[j])) {
j++;
}
if (j - i > 1) {
String parameter = sql.substring(i + 1, j);
if (!namedParameters.contains(parameter)) {
namedParameters.add(parameter);
}
parsedSql.addNamedParameter(parameter, i, j);
}
i = j - 1;
}
}
}
i++;
}
return parsedSql;
}
/**
* @param c
* @return
*/
private static boolean isParameterSeparator(char c) {
if (Character.isWhitespace(c)) {
return true;
}
for (int i = 0; i < PARAMETER_SEPARATORS.length; i++) {
if (c == PARAMETER_SEPARATORS[i]) {
return true;
}
}
return false;
}
}
<|start_filename|>src/leola/ast/TryStmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Try statement
*
* @author Tony
*
*/
public class TryStmt extends Stmt {
private Stmt stmt;
private CatchStmt catchStmt;
private Stmt finallyStmt;
/**
* @param stmt
* @param catchStmt
* @param finallyStmt
*/
public TryStmt(Stmt stmt, CatchStmt catchStmt, Stmt finallyStmt) {
this.stmt = becomeParentOf(stmt);
this.catchStmt = becomeParentOf(catchStmt);
this.finallyStmt = becomeParentOf(finallyStmt);
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the stmt
*/
public Stmt getStmt() {
return stmt;
}
/**
* @return the catchStmt
*/
public CatchStmt getCatchStmt() {
return catchStmt;
}
/**
* @return the finallyStmt
*/
public Stmt getFinallyStmt() {
return finallyStmt;
}
}
<|start_filename|>src/leola/vm/Args.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoObject;
/**
* {@link Leola} VM arguments
*
* @author Tony
*
*/
public class Args {
/**
* A builder for {@link Args}.
*
* <p>
* Example usage:
* <pre>
* Args args = new ArgsBuilder().setFileName("something.leola").setStackSize(1024).build();
* Leola runtime = new Leola(args);
* </pre>
*
* @author Tony
*
*/
public static class ArgsBuilder {
private Args args;
/**
*/
public ArgsBuilder() {
this.args = new Args();
}
/**
* The file name of the executed script. This is used
* for debugging purposes.
*
* @param fileName
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setFileName(String fileName) {
args.setFileName(fileName);
return this;
}
/**
* Displays the generated bytecode to System.out
* Defaults to false
*
* @param displayBytecode
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setDisplayBytecode(boolean displayBytecode) {
args.setDisplayBytecode(displayBytecode);
return this;
}
/**
* Compiles to Leola bytecode and does not interpret the code.
* Defaults to false
*
* @param generateBytecode
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setGenerateBytecode(boolean generateBytecode) {
args.setGenerateBytecode(generateBytecode);
return this;
}
/**
* Does not load any auxilary libraries.
* Defaults to false
*
* @param barebones
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setBarebones(boolean barebones) {
args.setBarebones(barebones);
return this;
}
/**
* Sets to interpret an in bound string.
* Defaults to false
*
* @param executeStatement
* @see ArgsBuilder#setStatement(String)
*
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setExecuteStatement(boolean executeStatement) {
args.setExecuteStatement(executeStatement);
return this;
}
/**
* Enables debugging symbols. Use this for better compiler/interpreter
* error messages. This does slow down execution so this should only
* be enabled during development.
*
* Defaults to false
* @param debugMode
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setIsDebugMode(boolean debugMode) {
args.setDebugMode(debugMode);
return this;
}
/**
* This enables the usage of creating a stack per Thread. This allows
* for safe concurrent code execution from the VM's perspective. You
* would only want to disable this if memory is a limiting factor or
* if you do not have an easy means for managing the Threads (which could
* cause memory leaks).
*
* Defaults to true.
* @param allowThreadLocals
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setAllowThreadLocals(boolean allowThreadLocals) {
args.enableVMThreadLocal(allowThreadLocals);
return this;
}
/**
* A statement to be executed immediately.
*
* @param statement
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setStatement(String statement) {
args.setStatement(statement);
return this;
}
/**
* Arguments passed to the runtime -- a kin to program
* arguments.
*
* @param scriptArgs
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setScriptArguments(LeoObject scriptArgs) {
args.setScriptArgs(scriptArgs);
return this;
}
/**
* The VM stack size.
*
* Defaults to {@link VM#DEFAULT_STACKSIZE}
*
* @param stackSize
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setStackSize(int stackSize) {
args.setStackSize(stackSize);
return this;
}
/**
* Sets the maximum stack size for this VM.
*
* @param maxStackSize
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setMaxStackSize(int maxStackSize) {
args.setMaxStackSize(maxStackSize);
return this;
}
/**
* Sets the VM to sandboxed mode. In sandboxed mode, all
* access to Java classes are disabled and importing {@link LeolaLibrary}s
* is also disabled.
* Defaults to disabling Sandboxed mode.
*
* @param isSandboxed
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setSandboxed(boolean isSandboxed) {
args.setSandboxed(isSandboxed);
return this;
}
/**
* Directories to be included on scanning for include and require
* statements
*
* @param directories
* @return the {@link ArgsBuilder} for method chaining
*/
public ArgsBuilder setIncludeDirectories(List<File> directories) {
args.setIncludeDirectories(directories);
return this;
}
/**
* Builds the {@link Args} structure with the configuration
* of the {@link ArgsBuilder}.
*
* @return the {@link Args}
*/
public Args build() {
return args;
}
/**
* A means for creating a {@link Leola} runtime with the {@link Args}
* built from this {@link ArgsBuilder}.
*
* <p>
* How to use:
* <pre>
* Leola runtime = Args.builder().newRuntime();
* </pre>
*
* @return the {@link Leola} instance built with the {@link Args} from {@link ArgsBuilder#build()}.
*/
public Leola newRuntime() {
return new Leola(build());
}
}
private String fileName;
private boolean displayBytecode;
private boolean generateBytecode;
private boolean barebones;
private boolean isExecuteStatement;
private boolean isDebugMode;
private boolean allowThreadLocals;
private boolean isSandboxed;
private boolean isREPL;
private String statement;
private LeoObject scriptArgs;
private int stackSize;
private int maxStackSize;
private List<File> includeDirectories = new ArrayList<File>();
/**
* Available arguments
*/
private static final String[][] args =
{
{ "b", "Outputs bytecode" },
{ "e", "Runs the Read Evaluate Print Loop (REPL) mode" },
{ "d", "Displays generated bytecode" },
{ "g", "Enables debug mode" },
{ "s", "Runs in sandboxed mode, doesn't allow for Java interop and disables certain API's" },
{ "r", "Executes a supplied statement" },
{ "x", "Sets the stack size. Ex. x=1024 " },
{ "mx", "Sets the max stack size. Ex. mx=1000000" },
{ "t", "Disables allocating a VM per thread. " },
{ "cp", "Path names to be included on include, require look ups. Use a ';' as " +
"a path separater. \n\t\t Ex. \"cp=C:/My Documents/libs;C:/leola/libs\" " },
};
/**
* @return the list of available options
*/
public static String getOptions() {
StringBuilder sb = new StringBuilder(100);
for(int i = 0; i < args.length; i++) {
sb.append(args[i][0]);
}
return sb.toString();
}
/**
* @return a string denoting all of the command line options
*/
public static String getOptionsWithDescription() {
StringBuilder sb = new StringBuilder(100);
for(int i = 0; i < args.length; i++) {
sb.append("\t").append(args[i][0])
.append("\t").append(args[i][1]);
sb.append("\n");
}
return sb.toString();
}
/**
* @return a new instance of an {@link ArgsBuilder}
*/
public static ArgsBuilder builder() {
return new ArgsBuilder();
}
/**
* Parses the argument list
* @param args
* @return
* @throws LeolaRuntimeException
*/
public static Args parse(String ... args) throws LeolaRuntimeException {
Args pargs = new Args();
int startProgramArgs = 0;
int i = 0;
for(; i < args.length; i++) {
String arg = args[i];
if ( arg.equals("b") ) {
pargs.generateBytecode = true;
}
else if (arg.equals("e")) {
pargs.isREPL = true;
}
else if ( arg.equals("d")) {
pargs.displayBytecode = true;
}
else if ( arg.equals("s")) {
pargs.barebones = true;
pargs.isSandboxed = true;
}
else if (arg.equals("g")) {
pargs.isDebugMode = true;
}
else if (arg.equals("t")) {
pargs.allowThreadLocals = false;
}
else if ( arg.startsWith("cp=") ) {
String[] paths = arg.replace("cp=", "").split(";");
for(String path : paths) {
pargs.includeDirectories.add(new File(path));
}
}
else if ( arg.startsWith("x=") ) {
String value = arg.replace("x=", "");
pargs.stackSize = Integer.parseInt(value);
}
else if ( arg.startsWith("mx=") ) {
String value = arg.replace("mx=", "");
pargs.maxStackSize = Integer.parseInt(value);
}
else if ( arg.equals("r") ) {
pargs.isExecuteStatement = true;
pargs.statement = "";
for(int j = i + 1; j < args.length; j++) {
pargs.statement += " " + args[j];
}
break;
}
else {
pargs.fileName = arg;
startProgramArgs = i;
break;
}
}
i=0; // account for file name argument
if ( startProgramArgs < args.length && startProgramArgs > -1 ) {
String[] sargs = new String[args.length-startProgramArgs];
System.arraycopy(args, startProgramArgs, sargs, 0, sargs.length);
LeoObject leoScriptArgs = LeoObject.valueOf(sargs);
pargs.scriptArgs = leoScriptArgs;
}
return pargs;
}
/**
*
*/
public Args() {
this.allowThreadLocals=true;
this.maxStackSize = Integer.MAX_VALUE;
}
/**
* @return the fileName
*/
public String getFileName() {
return fileName;
}
/**
* @return the displayBytecode
*/
public boolean displayBytecode() {
return displayBytecode;
}
/**
* @return the generateBytecode
*/
public boolean generateBytecode() {
return generateBytecode;
}
/**
* @return if the REPL is enabled
*/
public boolean isRepl() {
return isREPL;
}
/**
* @return the stackSize
*/
public int getStackSize() {
return stackSize;
}
/**
* @return the barebones
*/
public boolean isBarebones() {
return barebones;
}
/**
* @return the isDebugMode
*/
public boolean isDebugMode() {
return isDebugMode;
}
/**
* @return the isExecuteStatement
*/
public boolean executeStatement() {
return isExecuteStatement;
}
/**
* @return the statement
*/
public String getStatement() {
return statement;
}
/**
* @return the scripts arguments
*/
public LeoObject getScriptArgs() {
if(this.scriptArgs==null) return new LeoArray(0);
return this.scriptArgs;
}
/**
* @return the includeDirectories
*/
public List<File> getIncludeDirectories() {
return includeDirectories;
}
/**
* Default is true.
*
* @see #enableVMThreadLocal(boolean)
* @return true if the use of thread locals is enabled
*/
public boolean allowThreadLocal() {
return this.allowThreadLocals;
}
/**
* @return the isSandboxed
*/
public boolean isSandboxed() {
return isSandboxed;
}
/**
* @param isSandboxed the isSandboxed to set
*/
public void setSandboxed(boolean isSandboxed) {
this.isSandboxed = isSandboxed;
}
/**
* @param fileName the fileName to set
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* @param displayBytecode the displayBytecode to set
*/
public void setDisplayBytecode(boolean displayBytecode) {
this.displayBytecode = displayBytecode;
}
/**
* @param generateBytecode the generateBytecode to set
*/
public void setGenerateBytecode(boolean generateBytecode) {
this.generateBytecode = generateBytecode;
}
/**
* @param barebones the barebones to set
*/
public void setBarebones(boolean barebones) {
this.barebones = barebones;
}
/**
* @param isExecuteStatement the isExecuteStatement to set
*/
public void setExecuteStatement(boolean isExecuteStatement) {
this.isExecuteStatement = isExecuteStatement;
}
/**
* @param statement the statement to set
*/
public void setStatement(String statement) {
this.statement = statement;
}
/**
* @param scriptArgs the scriptArgs to set
*/
public void setScriptArgs(LeoObject scriptArgs) {
this.scriptArgs = scriptArgs;
}
/**
* @param stackSize the stackSize to set
*/
public void setStackSize(int stackSize) {
this.stackSize = stackSize;
}
/**
* @return the maxStackSize
*/
public int getMaxStackSize() {
return maxStackSize;
}
/**
* @param maxStackSize the maxStackSize to set
*/
public void setMaxStackSize(int maxStackSize) {
this.maxStackSize = maxStackSize;
}
/**
* @param includeDirectories the includeDirectories to set
*/
public void setIncludeDirectories(List<File> includeDirectories) {
this.includeDirectories = includeDirectories;
}
/**
* @param isDebugMode the isDebugMode to set
*/
public void setDebugMode(boolean isDebugMode) {
this.isDebugMode = isDebugMode;
}
/**
* When this is disabled, the Leola runtime will not spawn
* a {@link VM} instance per thread in which the runtime is invoked
* on. This property is enabled by default to allow for better
* multi-threaded support.
*
* @param allow
*/
public void enableVMThreadLocal(boolean allow) {
this.allowThreadLocals = allow;
}
}
<|start_filename|>src/leola/ast/IntegerExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Number expression
*
* @author Tony
*
*/
public class IntegerExpr extends Expr {
private int value;
/**
* @param value
*/
public IntegerExpr(int value) {
this.value = value;
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the value
*/
public int getValue() {
return value;
}
}
<|start_filename|>src/leola/vm/debug/DebugEvent.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.debug;
import leola.vm.Scope;
import leola.vm.compiler.Bytecode;
import leola.vm.compiler.Outer;
import leola.vm.types.LeoObject;
/**
* @author Tony
*
*/
public class DebugEvent {
private int base;
private int topStack;
private int stackPointer;
private int programCounter;
private int lineNumber;
private Scope scope;
private LeoObject[] stack;
private Outer[] calleeouters;
private Bytecode bytecode;
/**
* @param stack
* @param locals
* @param lineNumber
*/
public DebugEvent(LeoObject[] stack, int base, int topStack, int sp, int pc, int lineNumber, Scope scope, Outer[] calleeouters,
Bytecode bytecode) {
super();
this.stack = stack;
this.base = base;
this.topStack = topStack;
this.stackPointer = sp;
this.programCounter = pc;
this.lineNumber = lineNumber;
this.scope = scope;
this.calleeouters = calleeouters;
this.bytecode = bytecode;
}
/**
* @return the stack
*/
public LeoObject[] getStack() {
return stack;
}
/**
* @return the base
*/
public int getBase() {
return base;
}
/**
* @return the topStack
*/
public int getTopStack() {
return topStack;
}
/**
* @return the stackPointer
*/
public int getStackPointer() {
return stackPointer;
}
/**
* @return the programCounter
*/
public int getProgramCounter() {
return programCounter;
}
/**
* @return the lineNumber
*/
public int getLineNumber() {
return lineNumber;
}
/**
* @return the calleeouters
*/
public Outer[] getCalleeouters() {
return calleeouters;
}
/**
* @return the scope
*/
public Scope getScope() {
return scope;
}
/**
* @return the bytecode
*/
public Bytecode getBytecode() {
return bytecode;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
final String format = "%4s %4s %26s %26s\n";
sb.append(String.format(format, "Line#","PC","Stack", "Locals"));
sb.append("========================================================================\n");
sb.append(String.format(format, Integer.toString(this.lineNumber), Integer.toString(this.programCounter), this.stack[base], this.stack[base]));
for(int i=base; i < this.stackPointer; i++) {
String local = i<this.topStack ? this.stack[i].toString() : "";
sb.append(String.format(format, "", "", this.stack[i], local));
}
return sb.toString();
}
}
<|start_filename|>src/leola/vm/Opcodes.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm;
import java.util.HashMap;
import java.util.Map;
import leola.vm.exceptions.LeolaRuntimeException;
/**
* Instruction Operation Codes
*
* @author Tony
*
*/
public class Opcodes {
// instruction for ARG1 ARG2
// 0x222111FF
// instruction for ARGx
// 0xXXXXXXFF
// instruction for ARGsx (signed)
// 0x7XXXXXFF
// instruction
// 0x002211FF
// FF = opcode
// 11 = arg1
// 22 = arg2
// X = part of ARG(s)x
// 7 = 0111 last bit for signed value
public static final int OP_SIZE = 8;
public static final int ARG1_SIZE = 12; // number of bits
public static final int ARG2_SIZE = 12; // number of bits
public static final int ARGx_SIZE = ARG1_SIZE + ARG2_SIZE;
public static final int ARGsx_SIZE = ARG1_SIZE + ARG2_SIZE-1;
public static final int OP_POS = 0;
public static final int ARG1_POS = OP_POS + OP_SIZE;
public static final int ARG2_POS = ARG1_POS + ARG1_SIZE;
public static final int ARGx_POS = ARG1_POS;
public static final int MAX_OP = ( (1<<OP_SIZE) - 1);
public static final int MAX_ARG1 = ( (1<<ARG1_SIZE) - 1);
public static final int MAX_ARG2 = ( (1<<ARG2_SIZE) - 1);
public static final int MAX_ARGx = ( (1<<ARGx_SIZE) - 1);
public static final int MAX_ARGsx = (MAX_ARGx>>1);
public static final int OP_MASK = ((1<<OP_SIZE)-1)<<OP_POS;
public static final int ARG1_MASK = ((1<<ARG1_SIZE)-1)<<ARG1_POS;
public static final int ARG2_MASK = ((1<<ARG2_SIZE)-1)<<ARG2_POS;
public static final int ARGx_MASK = ((1<<ARGx_SIZE)-1)<<ARGx_POS;
public static final int NOT_OP_MASK = ~OP_MASK;
public static final int NOT_ARG1_MASK = ~ARG1_MASK;
public static final int NOT_ARG2_MASK = ~ARG2_MASK;
public static final int NOT_ARGx_MASK = ~ARGx_MASK;
/**
* Strips the opinstr out of the supplied integer
* @param instr
* @return
*/
public static final int OPCODE(int instr) {
// return (instr >> OP_POS) & MAX_OP;
return instr & MAX_OP;
}
/**
* Returns the first argument
* @param instr
* @return arg1 one value
*/
public static final int ARG1(int instr) {
return (instr >>> ARG1_POS) & MAX_ARG1;
}
/**
* Returns the second argument
* @param instr
* @return arg2 value
*/
public static final int ARG2(int instr) {
return (instr >>> ARG2_POS) & MAX_ARG2;
}
/**
* Returns the x argument
* @param instr
* @return the x argument
*/
public static final int ARGx(int instr) {
return ((instr >>> ARGx_POS) & MAX_ARGx);
}
/**
* Returns the signed x argument
* @param instr
* @return the signed x argument
*/
public static final int ARGsx(int instr) {
return ((instr >> ARGx_POS) & MAX_ARGx) - MAX_ARGsx;
}
/**
* Sets the signed x value on the instruction
* @param instr
* @param x
* @return the instruction with the set value
*/
public static final int SET_ARGsx(int instr, int sx) {
return (instr & (NOT_ARGx_MASK)) | (( (sx + MAX_ARGsx) << ARGx_POS) & ARGx_MASK);
}
/**
* Sets the x value on the instruction
* @param instr
* @param x
* @return the instruction with the set value
*/
public static final int SET_ARGx(int instr, int argx) {
return (instr & (NOT_ARGx_MASK)) | (( argx << ARGx_POS) & ARGx_MASK);
}
/**
* Sets the arg1 value on the instruction
* @param instr
* @param x
* @return the instruction with the set value
*/
public static final int SET_ARG1(int instr, int arg1) {
return (instr & NOT_ARG1_MASK) | (( arg1 << ARG1_POS) & ARG1_MASK);
}
/**
* Sets the arg2 value on the instruction
* @param instr
* @param x
* @return the instruction with the set value
*/
public static final int SET_ARG2(int instr, int arg2) {
return (instr & NOT_ARG2_MASK) | (( arg2 << ARG2_POS) & ARG2_MASK);
}
/**
* String to integer opcode
* @param opcode
* @return the opcode represented by the string, or -1 if not found.
*/
public static final int str2op(String opcode) {
Integer op = opcodes.get(opcode.toUpperCase());
return (op != null) ? op : -1;
}
/**
* Converts the byte opcode to a readable string
*
* @param opcode
* @return a string
*/
public static final String op2str(int opcode) {
String op = "";
switch(opcode) {
/* stack operators */
case POP: {
op = "POP";
break;
}
case DUP: {
op = "DUP";
break;
}
case OPPOP: {
op = "OPPOP";
break;
}
/* Store operations */
case LOAD_CONST: {
op = "LOAD_CONST";
break;
}
case LOAD_LOCAL: {
op = "LOAD_LOCAL";
break;
}
case LOAD_OUTER: {
op = "LOAD_OUTER";
break;
}
case LOAD_NULL: {
op = "LOAD_NULL";
break;
}
case LOAD_TRUE: {
op = "LOAD_TRUE";
break;
}
case LOAD_FALSE: {
op = "LOAD_FALSE";
break;
}
case STORE_LOCAL: {
op = "STORE_LOCAL";
break;
}
case STORE_OUTER: {
op = "STORE_OUTER";
break;
}
case LOAD_NAME: {
op = "LOAD_NAME";
break;
}
case PARAM_END: {
op = "PARAM_END";
break;
}
case xLOAD_OUTER: {
op = "xLOAD_OUTER";
break;
}
case xLOAD_LOCAL: {
op = "xLOAD_LOCAL";
break;
}
case JMP: {
op = "JMP";
break;
}
case IFEQ: {
op = "IFEQ";
break;
}
case IS_A: {
op = "IS_A";
break;
}
case NEW_ARRAY: {
op = "NEW_ARRAY";
break;
}
case NEW_MAP: {
op = "NEW_MAP";
break;
}
case NEW_OBJ: {
op = "NEW_OBJ";
break;
}
case FUNC_DEF: {
op = "FUNC_DEF";
break;
}
case GEN_DEF: {
op = "GEN_DEF";
break;
}
case CLASS_DEF: {
op = "CLASS_DEF";
break;
}
case NAMESPACE_DEF: {
op = "NAMESPACE_DEF";
break;
}
case YIELD: {
op = "YIELD";
break;
}
case RET: {
op = "RET";
break;
}
case INVOKE: {
op = "INVOKE";
break;
}
case TAIL_CALL: {
op = "TAIL_CALL";
break;
}
/* object access */
case GET: {
op = "GET";
break;
}
case SET: {
op = "SET";
break;
}
case EGETK: {
op = "EGETK";
break;
}
case GETK: {
op = "GETK";
break;
}
case SETK: {
op = "SETK";
break;
}
case GET_GLOBAL: {
op = "GET_GLOBAL";
break;
}
case SET_GLOBAL: {
op = "SET_GLOBAL";
break;
}
case GET_NAMESPACE: {
op = "GET_NAMESPACE";
break;
}
case INIT_CATCH_BLOCK: {
op = "INIT_BLOCK";
break;
}
case INIT_FINALLY_BLOCK: {
op = "INIT_FINALLY_BLOCK";
break;
}
case END_BLOCK: {
op = "END_BLOCK";
break;
}
case THROW: {
op = "THROW";
break;
}
/* arithmetic operators */
case ADD: {
op = "ADD";
break;
}
case SUB: {
op = "SUB";
break;
}
case MUL: {
op = "MUL";
break;
}
case DIV: {
op = "DIV";
break;
}
case MOD: {
op = "MOD";
break;
}
case NEG: {
op = "NEG";
break;
}
case BSL: {
op = "BSL";
break;
}
case BSR: {
op = "BSR";
break;
}
case BNOT: {
op = "BNOT";
break;
}
case XOR: {
op = "XOR";
break;
}
case LOR: {
op = "LOR";
break;
}
case LAND: {
op = "LAND";
break;
}
case OR: {
op = "OR";
break;
}
case AND: {
op = "AND";
break;
}
case NOT: {
op = "NOT";
break;
}
case REQ: {
op = "REQ";
break;
}
case RNEQ: {
op = "RNEQ";
break;
}
case EQ: {
op = "EQ";
break;
}
case NEQ: {
op = "NEQ";
break;
}
case GT: {
op = "GT";
break;
}
case GTE: {
op = "GTE";
break;
}
case LT: {
op = "LT";
break;
}
case LTE: {
op = "LTE";
break;
}
case IDX: {
op = "IDX";
break;
}
case SIDX: {
op = "SIDX";
break;
}
case LINE: {
op = "LINE";
break;
}
default: {
throw new LeolaRuntimeException("Unknown Opcode: " + opcode);
}
}
return op;
}
/**
* The opcode is in the range of 0-255
*/
public static final int
/* stack operators */
POP = 1, /* */
DUP = 2, /* */
OPPOP = 3, /* */
/* loading of values */
LOAD_CONST = 4, /* ARGx */
LOAD_LOCAL = 5, /* ARGx */
LOAD_OUTER = 6, /* ARGx */
LOAD_NULL = 7, /* */
LOAD_TRUE = 8, /* */
LOAD_FALSE = 9, /* */
/* named parameters */
LOAD_NAME = 10, /* ARGx */
PARAM_END = 11, /* */
/* storage of values */
STORE_LOCAL = 12, /* ARGx */
STORE_OUTER = 13, /* ARGx */
/* pseudo bytecodes */
xLOAD_OUTER = 14, /* ARGx */
xLOAD_LOCAL = 15, /* ARGx */
/* jump instructions */
JMP = 16, /* ARGsx */
IFEQ = 17, /* ARGsx */
IS_A = 18, /* */
/* value creation */
NEW_ARRAY = 19, /* ARGx */
NEW_MAP = 20, /* ARGx */
NEW_OBJ = 21, /* ARGx */
/* type declarations */
FUNC_DEF = 22, /* ARGx */
GEN_DEF = 23, /* ARGx */
CLASS_DEF = 24, /* ARGx */
NAMESPACE_DEF = 25, /* ARGx */
/* statement branching */
YIELD = 26, /* */
RET = 27, /* */
/* method invocation */
INVOKE = 28, /* ARG1, ARG2 */
TAIL_CALL = 29, /* ARG1, ARG2 */
/* member access */
GET = 30, /* */
SET = 31, /* */
EGETK = 32, /* ARGx */
GETK = 33, /* ARGx */
SETK = 34, /* ARGx */
GET_GLOBAL = 35, /* ARGx */
SET_GLOBAL = 36, /* ARGx */
GET_NAMESPACE = 37, /* ARGx */
IDX = 38, /* */
SIDX = 39, /* */
/* Exception handling */
INIT_CATCH_BLOCK = 40, /* ARGsx*/
INIT_FINALLY_BLOCK = 41, /* ARGsx*/
END_BLOCK = 42, /* ARG1 (0=pop index;1=clear error;2=exit if error)*/
THROW = 43, /* */
/* arithmetic operators */
ADD = 44, /* */
SUB = 45, /* */
MUL = 46, /* */
DIV = 47, /* */
MOD = 48, /* */
NEG = 49, /* */
BSL = 50, /* */
BSR = 51, /* */
BNOT = 52, /* */
XOR = 53, /* */
LOR = 54, /* */
LAND = 55, /* */
OR = 56, /* */
AND = 57, /* */
NOT = 58, /* */
REQ = 59, /* */
RNEQ = 60, /* */
EQ = 61, /* */
NEQ = 62, /* */
GT = 63, /* */
GTE = 64, /* */
LT = 65, /* */
LTE = 66, /* */
/* debug */
LINE = 67 /* ARGx */
;
private static final Map<String, Integer> opcodes = new HashMap<String, Integer>();
static {
/* stack operators */
opcodes.put("POP", POP);
opcodes.put("DUP", DUP);
opcodes.put("OPPOP", OPPOP);
opcodes.put("LOAD_CONST", LOAD_CONST);
opcodes.put("LOAD_LOCAL", LOAD_LOCAL);
opcodes.put("LOAD_OUTER", LOAD_OUTER);
opcodes.put("LOAD_NULL", LOAD_NULL);
opcodes.put("LOAD_TRUE", LOAD_TRUE);
opcodes.put("LOAD_FALSE", LOAD_FALSE);
opcodes.put("LOAD_NAME", LOAD_NAME);
opcodes.put("PARAM_END", PARAM_END);
opcodes.put("STORE_LOCAL", STORE_LOCAL);
opcodes.put("STORE_OUTER", STORE_OUTER);
opcodes.put("xLOAD_OUTER", xLOAD_OUTER);
opcodes.put("xLOAD_LOCAL", xLOAD_LOCAL);
opcodes.put("JMP", JMP);
opcodes.put("IFEQ", IFEQ);
opcodes.put("IS_A", IS_A);
opcodes.put("NEW_ARRAY", NEW_ARRAY);
opcodes.put("NEW_MAP", NEW_MAP);
opcodes.put("NEW_OBJ", NEW_OBJ);
opcodes.put("FUNC_DEF", FUNC_DEF);
opcodes.put("GEN_DEF", GEN_DEF);
opcodes.put("CLASS_DEF", CLASS_DEF);
opcodes.put("NAMESPACE_DEF", NAMESPACE_DEF);
opcodes.put("YIELD", YIELD);
opcodes.put("RET", RET);
opcodes.put("INVOKE", INVOKE);
opcodes.put("TAIL_CALL", TAIL_CALL);
/* object access */
opcodes.put("GET", GET);
opcodes.put("SET", SET);
opcodes.put("EGETK", EGETK);
opcodes.put("GETK", GETK);
opcodes.put("SETK", SETK);
opcodes.put("GET_GLOBAL", GET_GLOBAL);
opcodes.put("SET_GLOBAL", SET_GLOBAL);
opcodes.put("GET_NAMESPACE", GET_NAMESPACE);
/* exception handling */
opcodes.put("INIT_CATCH_BLOCK", INIT_CATCH_BLOCK);
opcodes.put("INIT_FINALLY_BLOCK", INIT_FINALLY_BLOCK);
opcodes.put("END_BLOCK", END_BLOCK);
opcodes.put("THROW", THROW);
/* arithmetic operators */
opcodes.put("ADD", ADD);
opcodes.put("SUB", SUB);
opcodes.put("MUL", MUL);
opcodes.put("DIV", DIV);
opcodes.put("MOD", MOD);
opcodes.put("NEG", NEG);
opcodes.put("BSL", BSL);
opcodes.put("BSR", BSR);
opcodes.put("BNOT", BNOT);
opcodes.put("XOR", XOR);
opcodes.put("LOR", LOR);
opcodes.put("LAND", LAND);
opcodes.put("OR", OR);
opcodes.put("AND", AND);
opcodes.put("NOT", NOT);
opcodes.put("REQ", REQ);
opcodes.put("RNEQ", RNEQ);
opcodes.put("EQ", EQ);
opcodes.put("NEQ", NEQ);
opcodes.put("GT", GT);
opcodes.put("GTE", GTE);
opcodes.put("LT", LT);
opcodes.put("LTE", LTE);
opcodes.put("IDX", IDX);
opcodes.put("SIDX", SIDX);
opcodes.put("LINE", LINE);
}
}
<|start_filename|>src/leola/vm/lib/LeolaMethod.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.lib;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used for aliasing method names
*
* @author Tony
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface LeolaMethod {
/* Used for overriding the method name */
String alias();
}
<|start_filename|>src/leola/ast/NamedParameterExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Named Parameter Expression
*
* @author Tony
*
*/
public class NamedParameterExpr extends Expr {
private String parameterName;
private Expr valueExpr;
/**
* @param parameterName
* @param valueExpr
*/
public NamedParameterExpr(String parameterName, Expr valueExpr) {
this.parameterName = parameterName;
this.valueExpr = valueExpr;
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the parameterName
*/
public String getParameterName() {
return parameterName;
}
/**
* @return the valueExpr
*/
public Expr getValueExpr() {
return valueExpr;
}
}
<|start_filename|>src/leola/vm/ClassDefinitions.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import leola.vm.Scope.ScopeType;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.types.LeoClass;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
/**
* Stores the available class definitions
*
* @author Tony
*
*/
public class ClassDefinitions {
private Map<LeoObject, ClassDefinition> classDefinitions;
/**
* Determine if there are any {@link ClassDefinition}'s defined
*
* @return true if there are {@link ClassDefinition}'s defined
*/
public boolean hasDefinitions() {
return this.classDefinitions != null && ! this.classDefinitions.isEmpty();
}
/**
* Removes all {@link ClassDefinition}'s. Use this method with care.
*/
public void clearDefinitions() {
if(hasDefinitions()) {
this.classDefinitions.clear();
}
}
/**
* @return the classDefinitions
*/
public Map<LeoObject, ClassDefinition> getClassDefinitions() {
if ( this.classDefinitions == null ) {
this.classDefinitions = new ConcurrentHashMap<LeoObject, ClassDefinition>();
}
return classDefinitions;
}
/**
* Stores a {@link ClassDefinition}
*
* @param className
* @param klass
*/
public void storeClass(LeoObject className, ClassDefinition klass) {
getClassDefinitions().put(className, klass);
}
/**
* Removes the {@link ClassDefinition} associated with the supplied class name.
*
* @param className
*/
public void removeClass(LeoObject className) {
getClassDefinitions().remove(className);
}
/**
* Determines if there is a {@link ClassDefinition} defined by the supplied
* class name.
*
* @param className
* @return true if there exists a {@link ClassDefinition} associated with the supplied class name.
*/
public boolean containsClass(LeoObject className) {
return getClassDefinitions().containsKey(className);
}
/**
* Retrieves the {@link ClassDefinition} associated with the supplied class name.
*
* @param className
* @return the {@link ClassDefinition} associated with the class name. If there is not
* a {@link ClassDefinition} associated with the class name, a {@link LeolaRuntimeException} is
* thrown.
*/
public ClassDefinition getDefinition(LeoObject className) {
if ( ! getClassDefinitions().containsKey(className)) {
LeoObject.throwClassNotFoundError("No Leola Class found for '" + className + "'");
}
return getClassDefinitions().get(className);
}
/**
* Resolves the passing of parameters to the super class.
*
* @param paramNames
* @param params
* @param superParams
*/
private void resolveSuperArguments(LeoObject[] paramNames, LeoObject[] params, LeoObject[] superParams) {
if(superParams != null && paramNames != null) {
for(int i = 0; i < superParams.length; i++) {
LeoObject sp = superParams[i];
if(sp.isString()) {
for(int j=0;j<paramNames.length;j++) {
if(sp.$eq(paramNames[j])) {
if ( params != null && j < params.length ) {
superParams[i] = params[j];
}
else {
superParams[i] = LeoNull.LEONULL;
}
}
}
}
}
}
}
/**
* Creates a new instance of a class defined by the {@link ClassDefinition} for the supplied
* class name.
*
* @param runtime
* @param className
* @param params
* @return the new {@link LeoObject} instance.
*/
public LeoObject newInstance(Leola runtime, LeoObject className, LeoObject[] params) {
ClassDefinition definition = getDefinition(className);
return newInstance(runtime, definition, params);
}
/**
* Creates a new instance of a class defined by the {@link ClassDefinition} for the supplied
* class name.
*
* @param runtime
* @param definition
* @param params
* @return the new {@link LeoObject} instance.
*/
public LeoObject newInstance(Leola runtime, ClassDefinition definition, LeoObject[] params) {
LeoObject parentClass = LeoNull.LEONULL;
if ( definition.hasParentClass() ) {
LeoObject[] paramNames = definition.getParameterNames();
LeoObject[] superParams = definition.getSuperParameterNames();
if ( superParams != null ) {
LeoObject[] clone = new LeoObject[superParams.length];
System.arraycopy(superParams, 0, clone, 0, superParams.length);
superParams = clone;
}
resolveSuperArguments(paramNames, params, superParams);
parentClass = newInstance(runtime, definition.getSuperClassDefinition().getClassName(), superParams);
}
/* The parent scope is either the parent Class, or the scope in which this class
* is defined in
*/
Scope parentScope = parentClass != LeoNull.LEONULL ?
((LeoClass)parentClass).getScope() : definition.getDeclaredScope();
Scope scope = new Scope(ScopeType.Class, parentScope);
LeoClass klass = new LeoClass(runtime
, scope
, definition
, parentClass
, params);
return klass;
}
}
<|start_filename|>src/leola/ast/ASTNodeVisitorAdapter.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Serves as an Adapter
*
* @author Tony
*
*/
public class ASTNodeVisitorAdapter implements ASTNodeVisitor {
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.SubscriptGetExpr)
*/
@Override
public void visit(SubscriptGetExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.SubscriptSetExpr)
*/
@Override
public void visit(SubscriptSetExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ArrayDeclExpr)
*/
@Override
public void visit(ArrayDeclExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.MapDeclExpr)
*/
@Override
public void visit(MapDeclExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.AssignmentExpr)
*/
@Override
public void visit(AssignmentExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.BinaryExpr)
*/
@Override
public void visit(BinaryExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.BooleanExpr)
*/
@Override
public void visit(BooleanExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.BreakStmt)
*/
@Override
public void visit(BreakStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.CaseExpr)
*/
@Override
public void visit(CaseExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ClassDeclStmt)
*/
@Override
public void visit(ClassDeclStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.BlockStmt)
*/
@Override
public void visit(BlockStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ContinueStmt)
*/
@Override
public void visit(ContinueStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.DecoratorExpr)
*/
@Override
public void visit(DecoratorExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.NamespaceStmt)
*/
@Override
public void visit(NamespaceStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.NumberExpr)
*/
@Override
public void visit(RealExpr s) throws EvalException {}
/*
* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.IntegerExpr)
*/
@Override
public void visit(IntegerExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.LongExpr)
*/
@Override
public void visit(LongExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ProgramStmt)
*/
@Override
public void visit(ProgramStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.IsExpr)
*/
@Override
public void visit(IsExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.EmptyStmt)
*/
@Override
public void visit(EmptyStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.GenDefExpr)
*/
@Override
public void visit(GenDefExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.FuncDefExpr)
*/
@Override
public void visit(FuncDefExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.FuncInvocationExpr)
*/
@Override
public void visit(FuncInvocationExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.IfStmt)
*/
@Override
public void visit(IfStmt s) throws EvalException {}
@Override
public void visit(NamespaceGetExpr s) throws EvalException {}
@Override
public void visit(NamespaceSetExpr s) throws EvalException {}
@Override
public void visit(ElvisGetExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.GetExpr)
*/
@Override
public void visit(GetExpr s) throws EvalException {}
@Override
public void visit(SetExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.NewExpr)
*/
@Override
public void visit(NewExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.NullExpr)
*/
@Override
public void visit(NullExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ReturnStmt)
*/
@Override
public void visit(ReturnStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.StringExpr)
*/
@Override
public void visit(StringExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.YieldStmt)
*/
@Override
public void visit(YieldStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.SwitchStmt)
*/
@Override
public void visit(SwitchStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ThrowStmt)
*/
@Override
public void visit(ThrowStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.TryStmt)
*/
@Override
public void visit(TryStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.OnStmt)
*/
@Override
public void visit(CatchStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.UnaryExpr)
*/
@Override
public void visit(UnaryExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.VarDeclStmt)
*/
@Override
public void visit(VarDeclStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.VarExpr)
*/
@Override
public void visit(VarExpr s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.WhileStmt)
*/
@Override
public void visit(WhileStmt s) throws EvalException {}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.NamedParameterStmt)
*/
@Override
public void visit(NamedParameterExpr s) throws EvalException {}
}
<|start_filename|>src/leola/vm/debug/SimpleStdOutDebugListener.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.debug;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import leola.vm.types.LeoObject;
/**
* @author Tony
*
*/
public class SimpleStdOutDebugListener implements DebugListener {
private boolean echo;
private Set<Integer> breakpoints;
private PrintStream out;
private Scanner input;
public SimpleStdOutDebugListener(PrintStream pstream, InputStream istream) {
this.out = pstream;
this.input = new Scanner(istream);
this.breakpoints = new HashSet<Integer>();
this.echo = true;
}
/**
* Pipes to System.out
*/
public SimpleStdOutDebugListener() {
this(System.out, System.in);
}
/* (non-Javadoc)
* @see leola.vm.debug.DebugListener#onLineNumber(leola.vm.debug.DebugEvent)
*/
@Override
public void onLineNumber(DebugEvent event) {
int lineNumber = event.getLineNumber();
if(isEcho()) {
out.println("Line: " + lineNumber);
debugPrint(event.getStack(), event.getBase(), event.getStackPointer(), event.getTopStack());
}
if(this.breakpoints.contains(lineNumber)) {
this.input.hasNext();
this.input.next();
}
}
/**
* Print out each line to standard out
*
* @param echo the echo to set
*/
public void setEcho(boolean echo) {
this.echo = echo;
}
/**
* @return the echo
*/
public boolean isEcho() {
return echo;
}
public void addBreakpoint(int lineNumber) {
this.breakpoints.add(lineNumber);
}
public void removeBreakpoint(int lineNumber) {
this.breakpoints.remove(new Integer(lineNumber));
}
public void removeAllBreakpoints() {
this.breakpoints.clear();
}
/**
* Prints the contents of the stack
*
* @param stack
* @param base
* @param top
*/
private void printStack(LeoObject[] stack, int base, int top) {
for(int i = base; i < top; i++) {
LeoObject obj = stack[i];
if ( obj == null ) {
out.println("\t\tType: <empty> Value: <empty>");
}
else {
out.println("\t\tType: " + obj.getType() + " Value: " + obj.toString());
}
}
}
/**
* Prints the locals
* @param stack
* @param base
* @param startOfStack
*/
private void printLocals(LeoObject[] stack, int base, int startOfStack) {
printStack(stack, base, startOfStack);
}
/**
* Prints the locals and stack values
*
* @param stack
* @param base
* @param top
* @param topStack
*/
private void debugPrint(LeoObject[] stack, int base, int top, int topStack) {
out.println("\tLocals {");
printLocals(stack, base, topStack);
out.println("\t}");
out.println("\tStack {");
printStack(stack, topStack, top);
out.println("\t}");
out.println("");
}
}
<|start_filename|>src/leola/ast/SetExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.frontend.tokens.Token;
import leola.vm.EvalException;
/**
* @author Tony
*
*/
public class SetExpr extends Expr {
private Expr object;
private String identifier;
private Expr value;
private Token operator;
public SetExpr(Expr object, String identifier, Expr value, Token operator) {
this.object = object;
this.identifier = identifier;
this.value = value;
this.operator = operator;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public Expr getObject() {
return object;
}
public String getIdentifier() {
return identifier;
}
public Expr getValue() {
return value;
}
public Token getOperator() {
return operator;
}
}
<|start_filename|>src/leola/lang/io/LeolaFile.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.io;
import java.io.EOFException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UTFDataFormatException;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
/**
* A simple wrapper around a {@link RandomAccessFile}
*
* @author Tony
*
*/
public class LeolaFile {
private RandomAccessFile raf;
/**
* @param raf the {@link RandomAccessFile} that has been opened
* @param runtime the Leola runtime
*/
public LeolaFile(RandomAccessFile raf) {
this.raf = raf;
}
/**
* Executes the supplied function and always closes the file afterwards (even if
* an exception occurs).
*
* @param func
* @throws Exception
*/
public LeoObject with(LeoObject func) throws Exception {
try {
return func.xcall(LeoObject.valueOf(this));
}
catch(Exception e) {
try {this.raf.close();}
catch(Exception ignore) {}
LeoObject.rethrow(e);
}
return LeoObject.NULL;
}
/**
* Reads the contents of the file into the supplied {@link Buffer} according to the
* {@link Buffer#position()} and {@link Buffer#limit()}.
*
* @param buffer
* @return the number of bytes read
* @throws Exception
*/
public final int readBuffer(Buffer buffer) throws Exception {
int bytesRead = raf.read(buffer.getArray(), buffer.position(), buffer.limit());
buffer.setLimit(bytesRead);
return bytesRead;
}
public final int read() throws Exception {
return raf.read();
}
public final boolean readBoolean() throws Exception {
return this.raf.readBoolean();
}
public final byte readByte() throws Exception {
return this.raf.readByte();
}
public final char readChar() throws Exception {
return this.raf.readChar();
}
public final short readShort() throws Exception {
return this.raf.readShort();
}
public final int readInt() throws Exception {
return this.raf.readInt();
}
public final float readFloat() throws Exception {
return this.raf.readFloat();
}
public final double readDouble() throws Exception {
return this.raf.readDouble();
}
public final long readLong() throws Exception {
return this.raf.readLong();
}
/**
* Reads in a string from this file. The string has been encoded
* using a
* <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
* format.
* <p>
* The first two bytes are read, starting from the current file
* pointer, as if by
* <code>readUnsignedShort</code>. This value gives the number of
* following bytes that are in the encoded string, not
* the length of the resulting string. The following bytes are then
* interpreted as bytes encoding characters in the modified UTF-8 format
* and are converted into characters.
* <p>
* This method blocks until all the bytes are read, the end of the
* stream is detected, or an exception is thrown.
*
* @return a Unicode string.
* @exception EOFException if this file reaches the end before
* reading all the bytes.
* @exception IOException if an I/O error occurs.
* @exception UTFDataFormatException if the bytes do not represent
* valid modified UTF-8 encoding of a Unicode string.
* @see java.io.RandomAccessFile#readUnsignedShort()
*/
public final String readUTF() throws Exception {
return this.raf.readUTF();
}
/**
* Reads the next line of text from this file. This method successively
* reads bytes from the file, starting at the current file pointer,
* until it reaches a line terminator or the end
* of the file. Each byte is converted into a character by taking the
* byte's value for the lower eight bits of the character and setting the
* high eight bits of the character to zero. This method does not,
* therefore, support the full Unicode character set.
*
* <p> A line of text is terminated by a carriage-return character
* (<code>'\r'</code>), a newline character (<code>'\n'</code>), a
* carriage-return character immediately followed by a newline character,
* or the end of the file. Line-terminating characters are discarded and
* are not included as part of the string returned.
*
* <p> This method blocks until a newline character is read, a carriage
* return and the byte following it are read (to see if it is a newline),
* the end of the file is reached, or an exception is thrown.
*
* @return the next line of text from this file, or null if end
* of file is encountered before even one byte is read.
* @exception IOException if an I/O error occurs.
*/
public final String readLine() throws Exception {
return this.raf.readLine();
}
/**
* Read the full contents of the file and stores it in a {@link String}. Users
* of this must be aware of memory consumption, as this will put the full file
* into VM memory.
*
* @return the full file contents in a {@link String}.
* @throws Exception
*/
public final String readFully() throws Exception {
StringBuilder sb = new StringBuilder((int)this.raf.length());
String line = null;
do {
line = this.raf.readLine();
if ( line != null) {
sb.append(line).append("\n");
}
} while(line != null);
return sb.toString();
}
/**
* Reads all lines according to the same rules as {@link LeolaFile#readLine()}
*
* @return an array containing all of the lines
* @throws Exception
*/
public final LeoArray readLines() throws Exception {
LeoArray result = new LeoArray();
String line = null;
do {
line = this.raf.readLine();
if ( line != null ) {
result.add(LeoString.valueOf(line));
}
} while(line != null);
return result;
}
/**
* Writes out bytes from the {@link Buffer}
*
* @param buffer
* @throws Exception
*/
public final void writeBuffer(Buffer buffer) throws Exception {
this.raf.write(buffer.getArray(), buffer.position(), buffer.remaining());
}
public final void write(int b) throws Exception {
this.raf.write(b);
}
public final void writeBoolean(boolean b) throws Exception {
this.raf.writeBoolean(b);
}
public final void writeByte(byte b) throws Exception {
this.raf.writeByte(b);
}
public final void writeChar(char b) throws Exception {
this.raf.writeChar(b);
}
public final void writeShort(short b) throws Exception {
this.raf.writeShort(b);
}
public final void writeInt(int b) throws Exception {
this.raf.writeInt(b);
}
public final void writeFloat(float b) throws Exception {
this.raf.writeFloat(b);
}
public final void writeDouble(double b) throws Exception {
this.raf.writeDouble(b);
}
public final void writeLong(long b) throws Exception {
this.raf.writeLong(b);
}
/**
* Writes a string to the file using
* <a href="DataInput.html#modified-utf-8">modified UTF-8</a>
* encoding in a machine-independent manner.
* <p>
* First, two bytes are written to the file, starting at the
* current file pointer, as if by the
* <code>writeShort</code> method giving the number of bytes to
* follow. This value is the number of bytes actually written out,
* not the length of the string. Following the length, each character
* of the string is output, in sequence, using the modified UTF-8 encoding
* for each character.
*
* @param line a string to be written.
* @exception IOException if an I/O error occurs.
*/
public final void writeUTF(String line) throws Exception {
this.raf.writeUTF(line);
}
/**
* Writes the string to the file as a sequence of bytes. Each
* character in the string is written out, in sequence, by discarding
* its high eight bits. The write starts at the current position of
* the file pointer. A new line is always appended.
*
* @param line a string of bytes to be written.
* @exception IOException if an I/O error occurs.
*/
public final void writeLine(String line) throws Exception {
this.raf.writeBytes(line);
this.raf.writeBytes("\n");
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this file.
*
* @param bytes the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
*/
public final void writeBytes(byte[] bytes, int off, int len) throws Exception {
this.raf.write(bytes, off, len);
}
/**
* Writes <code>b.length</code> bytes from the specified byte array
* to this file, starting at the current file pointer.
*
* @param bytes the data.
* @exception IOException if an I/O error occurs.
*/
public final void writeBytes(byte[] bytes) throws Exception {
this.raf.write(bytes);
}
/**
* Write out each element in the supplied {@link LeoArray}, each element is
* treated as a string, after which a new line will be appended.
*
* <pre>
* file.writeLines( [ "a", "b", "c" ] )
* // writes:
* // a
* // b
* // c
* </pre>
*
* @param array
* @throws Exception
*/
public final void writeLines(LeoArray array) throws Exception {
if ( array != null ) {
for(int i = 0; i < array.size(); i++) {
LeoObject obj = array.get(i);
if ( obj != null ) {
//this.raf.writeUTF(obj.toString() + "\n");
this.raf.writeBytes(obj.toString());
this.raf.writeBytes("\n");
}
else {
this.raf.writeBytes("\n");
// this.raf.writeUTF("\n");
}
}
}
}
/**
* Seeks into a this.
*
* @param pos the position in number of bytes
* @throws Exception
*/
public final void seek(long pos) throws Exception {
this.raf.seek(pos);
}
/**
* The current file position pointer
*
* @see LeolaFile#seek(long)
* @return the file position pointer in number of bytes
* @throws Exception
*/
public final long position() throws Exception {
return this.raf.getFilePointer();
}
/**
* Closes the this.
*
* @throws Exception
*/
public final void close() throws Exception {
this.raf.close();
}
/**
* Returns the length of the file in bytes
*
* @return the length of the file in number of bytes
* @throws Exception
*/
public final long length() throws Exception {
return this.raf.length();
}
/**
* Sets the new length of the this.
*
* @param newLength
* @throws Exception
*/
public final void setLength(int newLength) throws Exception {
this.raf.setLength(newLength);
}
}
<|start_filename|>src/leola/vm/lib/LeolaIgnore.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.lib;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Ignore a method
*
* @author Tony
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface LeolaIgnore {
}
<|start_filename|>src/leola/vm/compiler/Constants.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.compiler;
import java.util.ArrayList;
import java.util.List;
import leola.vm.types.LeoInteger;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
import leola.vm.util.ArrayUtil;
/**
* The {@link Constants} pool. For each {@link Bytecode} (in Leola that translates to either a Class, Namespace or a Function) there
* exists a constants pool. The pool stores literals such as strings and numbers.
*
* @author Tony
*
*/
public class Constants {
/**
* Storage
*/
private List<LeoObject> storage;
/**
*/
public Constants() {
}
/**
* @return The size of the constant pool
*/
public int getNumberOfConstants() {
return (this.storage != null ) ? this.storage.size() : 0;
}
/**
* @return the storage
*/
private List<LeoObject> lazystorage() {
if ( this.storage == null ) {
this.storage = new ArrayList<LeoObject>();
}
return storage;
}
/**
* Stores the string literal (converts it to a {@link LeoString}).
* @param value
* @return the constant index of where it's stored
*/
public int store(String value) {
LeoObject str = LeoString.valueOf(value);
return store(str);
}
/**
* Stores the number literal (converts it to a {@link LeoInteger}).
* @param value
* @return the constant index of where it's stored
*/
public int store(int n) {
LeoInteger number = LeoInteger.valueOf(n);
return store(number);
}
/**
* Stores a {@link LeoObject} literal
*
* @param obj
* @return the constant index of where it's stored
*/
public int store(LeoObject obj) {
if ( this.lazystorage().contains(obj) ) {
return this.storage.indexOf(obj);
}
this.storage.add(obj);
return this.storage.size() - 1;
}
/**
* Retrieves the index in which the supplied {@link LeoObject} is stored.
* @param obj
* @return the index (or -1 if not found) in where this object is stored in the pool
*/
public int get(LeoObject obj) {
return this.storage == null ? -1 : this.storage.indexOf(obj);
}
/**
* Retrieves the {@link LeoObject} and a particular index.
*
* @param index
* @return the {@link LeoObject} stored and the supplied index
*/
public LeoObject get(int index) {
return this.storage == null ? null : this.storage.get(index);
}
/**
* @return compiles into an array of constants
*/
public LeoObject[] compile() {
LeoObject[] constants = ArrayUtil.EMPTY_LEOOBJECTS;
if ( this.storage != null) {
constants = this.storage.toArray(new LeoObject[this.storage.size()]);
}
return constants;
}
}
<|start_filename|>src/leola/ast/Expr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
/**
* An Expression
*
* @author Tony
*
*/
public abstract class Expr extends Stmt {
}
<|start_filename|>src/leola/frontend/Scanner.java<|end_filename|>
package leola.frontend;
import static leola.frontend.Source.EOF;
import static leola.frontend.Source.EOL;
import java.util.ArrayList;
import java.util.List;
import leola.frontend.tokens.EofToken;
import leola.frontend.tokens.ErrorToken;
import leola.frontend.tokens.NumberToken;
import leola.frontend.tokens.SpecialSymbolToken;
import leola.frontend.tokens.StringToken;
import leola.frontend.tokens.Token;
import leola.frontend.tokens.WordToken;
import leola.frontend.tokens.TokenType;
/**
* A {@link Scanner} for the Leola programming language. This will break up
* the leola source code into {@link Token} that will be used by the {@link Parser}
* to make sense of.
*
* @author Tony
*
*/
public class Scanner {
public static final String START_COMMENT = "/*";
public static final String END_COMMENT = "*/";
public static final String SINGLE_COMMENT = "//";
private List<Token> tokens;
private Source source;
/**
* Constructor
*
* @param source
* the source to be used with this scanner.
*/
public Scanner(Source source) {
this.source = source;
this.tokens = new ArrayList<>();
while(!source.atEof()) {
this.tokens.add(this.extractToken());
}
}
/**
* Get a line of raw source code
*
* @param lineNumber
* @return the line of raw source code
*/
public String getSourceLine(int lineNumber) {
return this.source.getLine(lineNumber);
}
/**
* The scanned {@link Token}s
*
* @return The scanned {@link Token}s
*/
public List<Token> getTokens() {
return tokens;
}
/**
* Do the actual work of extracting and returning the next token from the
* source. Implemented by scanner subclasses.
*
* @return the next token.
*/
private Token extractToken() {
skipWhiteSpace();
Token token;
char currentChar = this.source.currentChar();
// Construct the next token. The current character determines the
// token type.
if (currentChar == EOF) {
token = new EofToken(source);
}
else if ( WordToken.isValidStartIdentifierCharacter(currentChar) ) {
token = new WordToken(source);
}
else if (Character.isDigit(currentChar)) {
token = new NumberToken(source);
}
else if (currentChar == StringToken.STRING_CHAR) {
token = new StringToken(source);
}
else if (TokenType.SPECIAL_SYMBOLS
.containsKey(Character.toString(currentChar))) {
token = new SpecialSymbolToken(source);
}
else {
token = new ErrorToken(source, ErrorCode.INVALID_CHARACTER,
Character.toString(currentChar));
this.source.nextChar(); // consume character
}
return token;
}
/**
* Skip whitespace characters by consuming them. A comment is whitespace.
*/
private void skipWhiteSpace() {
char currentChar = this.source.currentChar();
while (Character.isWhitespace(currentChar)
|| checkSequence(START_COMMENT)
|| checkSequence(SINGLE_COMMENT) ) {
// Start of a comment?
if ( checkSequence(START_COMMENT) ) {
do {
currentChar = this.source.nextChar(); // consume comment characters
}
while ((!checkSequence(END_COMMENT)) && (currentChar != EOF));
// Found closing '*/'?
if ( checkSequence(END_COMMENT) ) {
for(int i = 0; i < END_COMMENT.length(); i++) {
currentChar = this.source.nextChar(); // consume the comment
}
}
}
else if ( checkSequence(SINGLE_COMMENT) ) {
do {
currentChar = this.source.nextChar(); // consume comment characters
}
while (currentChar != EOL);
}
// Not a comment.
else {
currentChar = this.source.nextChar(); // consume whitespace character
}
}
}
/**
* Check the sequence matches the input (2 chars).
*
* @param seq
* @return
*/
private boolean checkSequence(String seq) {
boolean result = true;
char currentChar = this.source.currentChar();
for(int i = 0; i < 2; i++) {
if (currentChar == EOF ) {
result = false;
break;
}
if (currentChar != seq.charAt(i)) {
result = false;
break;
}
currentChar = this.source.peekChar();
}
/*if ( result ) {
nextChar(); // eat the char
}*/
return result;
}
}
<|start_filename|>src/leola/vm/compiler/Locals.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.compiler;
import leola.vm.Scope;
import leola.vm.util.ArrayUtil;
/**
* Represents local variables within a {@link Scope}. Used for compilation to determine the
* the amount of stack space needed for local variables.
*
* <p>
* Local variables within a {@link Scope} follow proper lexical scoping by overriding out
* of scope values. That is, the {@link Locals#getNumberOfLocals()} pool will only be the
* max number of visible variables within a {@link Scope}.
*
* @author Tony
*
*/
public class Locals {
/**
* The pool of reference symbols
*/
private String[] pool;
/**
* Current index to store in the pool
*/
private int index;
/**
* Total number of locals defined
* within the scope
*/
private int numberOfLocals;
public Locals() {
this.index = 0;
}
/**
* Retrieve the index at which the supplied reference lives in the
* pool.
*
* @param reference
* @return the index at which the reference is stored. If not found, -1.
*/
private int getFromPool(String reference) {
if(pool==null) {
pool = ArrayUtil.newStringArray();
return -1;
}
int index = -1;
for(int i = 0; i < this.index; i++) {
if ( this.pool[i].equals(reference) ) {
index = i;
break;
}
}
return index;
}
/**
* Stores the reference at the supplied index in the pool
*
* @param reference
* @param index
*/
private void putInPool(String reference, int index) {
if ( index >= this.pool.length ) {
this.pool = ArrayUtil.resize(pool, pool.length << 1 );
}
this.pool[index] = reference;
}
/**
* Allocates the number of local variables stored
*
* @param size
*/
public void allocate(int size) {
if ( this.pool == null ) {
this.pool = new String[size];
}
this.index = 0;
this.numberOfLocals = size;
}
/**
* Stores in the pool
*
* @param reference
* @return the index within the pool in which the reference is stored.
*/
public int store(String reference) {
int index = getFromPool(reference);
/* if this is a scoped object, put the reference in
* the values array
*/
if ( index < 0 ) {
putInPool(reference, this.index);
}
else {
return index;
}
int result = this.index++;
this.numberOfLocals = Math.max(this.index, this.numberOfLocals);
return result;
}
/**
* Retrieves the reference by index
* @param index
* @return the reference stored and the supplied index
*/
public String getReference(int index) {
return this.pool[index];
}
/**
* Sets the reference at the specified index
* @param index
* @param reference
*/
public void setReference(int index, String reference) {
this.pool[index] = reference;
}
/**
* Retrieves the index at which the supplied reference is stored.
*
* @param reference
* @return -1 if not found, otherwise the index
*/
public int get(String reference) {
int index = getFromPool(reference);
return index;
}
/**
* @return the number of local variables.
*/
public int getNumberOfLocals() {
return this.numberOfLocals;
}
/**
* Used for reseting the index for lexical scoping.
*
* @param index
*/
public void setIndex(int prevIndex) {
for(int i = prevIndex; i < this.index; i++) {
if(this.pool!=null ) this.pool[i] = null;
}
this.index = prevIndex;
}
/**
* @return the current index value
*/
public int getIndex() {
return this.index;
}
@Override
public Locals clone() {
Locals clone = new Locals();
clone.index = this.index;
if ( this.pool != null ) {
clone.pool = new String[this.pool.length];
System.arraycopy(this.pool, 0, clone.pool, 0, this.pool.length);
}
return clone;
}
}
<|start_filename|>src/leola/vm/util/Classpath.java<|end_filename|>
package leola.vm.util;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
/**
* Add Jars to the class path during runtime.
*
* @author Tony
*
*/
public class Classpath {
/**
* Do not allow clients to instantiate
*/
private Classpath() {
}
/*
* Parameters
*/
private static final Class<?>[] parameters = new Class<?> [] {
URL.class
};
/**
* Load a directory full of jars into the class path.
*
* @param directory
*/
public static void loadJars(String directory) throws IOException {
File dir = new File(directory);
if ( ! dir.isDirectory() ) {
throw new IOException(directory + " is not a valid directory!");
}
/*
* Get all the Jars
*/
List<File> jars = Classpath.getJarFiles(dir, new ArrayList<File>());
/*
* Iterate through each jar and add it to the class path
*/
for ( File jar : jars ) {
/*
* Add the jar to the class path
*/
Classpath.addFile(jar);
}
}
/**
* Add file to CLASSPATH
* @param s File name
* @throws IOException IOException
*/
public static void addFile(String s) throws IOException {
File f = new File(s);
addFile(f);
}
/**
* Add file to CLASSPATH
*
* @param f File object
* @throws IOException
*/
@SuppressWarnings("deprecation")
public static void addFile(File f) throws IOException {
addURL(f.toURL());
}
/**
* Add URL to CLASSPATH
* @param u URL
* @throws IOException IOException
*/
public static void addURL(URL u) throws IOException {
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
addURL(sysLoader, u);
}
public static void addURL(URLClassLoader sysLoader, URL u) throws IOException {
/*
* If the Url has not been loaded, load it.
*/
if ( ! isLoaded(sysLoader, u) ) {
Class<?> sysclass = URLClassLoader.class;
try {
/*
* Grab the protected method
*/
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
/*
* Execute it, effectively adding the url
*/
method.invoke(sysLoader, new Object[]{u});
}
catch (Throwable t) {
throw new IOException("Error, could not add " + u +" to system classloader - " + t.getLocalizedMessage());
}
}
}
/**
* Determine if the {@link URL} already exists.
*
* @param sysLoader
* @param u
* @return
*/
private static boolean isLoaded(URLClassLoader sysLoader, URL u) {
URL urls[] = sysLoader.getURLs();
for (int i = 0; i < urls.length; i++) {
/*
* If its already been loaded, ignore it
*/
if (urls[i].toString().equalsIgnoreCase(u.toString())) {
return true;
}
}
return false;
}
/**
* Recursively get the jar files in a given directory.
*
* @param dir
* @param output
* @return
*/
public static List<File> getJarFiles(File dir, List<File> output) {
/**
* Get Jars and Folders
*/
File [] jars = dir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory() || pathname.getName().endsWith(".jar");
}
});
/*
* Add to the output
*/
for ( File file : jars ) {
/*
* If its a directory recursively add
* the jars of the child folder
*/
if ( file.isDirectory() ) {
getJarFiles(file, output);
}
else {
/*
* Add the jar file
*/
output.add(file);
}
}
return (output);
}
}
<|start_filename|>src/leola/vm/types/LeoMap.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaMethod;
import leola.vm.util.ArrayUtil;
/**
* A {@link Map} data structure. All contents of the map must be {@link LeoObject}, that is both the keys and
* values.
*
* <p>
* This implements all optional methods of the {@link Map} interface. This implementation attempts to reduce the
* amount of allocations by storing keys in an array, and their corresponding values in another array. That is,
* this implementation is <b>not</b> like that of {@link HashMap}.
*
* @author Tony
*
*/
public class LeoMap extends LeoObject implements Map<LeoObject, LeoObject> {
/**
* Converts the java {@link Map} into a {@link LeoMap}.
*
* @param jMap
* @return the {@link LeoMap}
*/
public static LeoMap toMap(Map<?, ?> jMap) {
LeoMap result = new LeoMap();
for(Map.Entry<?, ?> entry : jMap.entrySet()) {
result.put(LeoObject.valueOf(entry.getKey()), LeoObject.valueOf(entry.getValue()));
}
return result;
}
/**
* A convenience method that creates a new {@link LeoMap}, inserting the key/value pair.
*
* @param key the key of an entry
* @param value the value of an entry
* @return the newly created {@link LeoMap}.
*/
public static LeoMap newLeoMap(Object key, Object value) {
LeoMap result = new LeoMap();
result.put(LeoObject.valueOf(key), LeoObject.valueOf(value));
return result;
}
/**
*/
public LeoMap() {
this(8);
}
/**
* @param initialCapacity
*/
public LeoMap(int initialCapacity) {
super(LeoType.MAP);
presize(initialCapacity);
}
/**
* @param array
*/
public LeoMap(Map<LeoObject, LeoObject> map) {
this(map.size());
putAll(map);
}
/**
* Adds ability to reference the public API of this class
*/
private Map<LeoObject, LeoObject> mapApi;
private Map<LeoObject, LeoObject> getApiMappings() {
if(this.mapApi == null) {
synchronized (this) {
if(this.mapApi == null) {
this.mapApi = new LeoMap();
}
}
}
return this.mapApi;
}
private LeoObject getNativeMethod(LeoObject key) {
return getNativeMethod(this, getApiMappings(), key);
}
/**
* Iterates through the array, invoking the supplied
* function object for each element
*
* <pre>
* var x = {x->1,y->2,z->3}.foreach(def(k,v) println(k + ":" + v))
* // prints:
* // x : 1
* // y : 2
* // z : 3
*
* </pre>
*
* @param function
* @return the {@link LeoObject} returned from the supplied function if returned <code>true</code>
*/
public LeoObject foreach(LeoObject function) {
if(function != null) {
for(int i = 0; i < this.bucketLength(); i++) {
LeoObject key = getKey(i);
if(key != null) {
LeoObject value = getValue(i);
LeoObject result = function.xcall(key, value);
if(LeoObject.isTrue(result)) {
return result;
}
}
}
}
return LeoObject.NULL;
}
/**
* Filters the {@link LeoArray}
*
* <pre>
* var evens = {x->1,y->2,z->3}.filter(def(k,v) {
* return v % 2 == 0
* })
* println(evens) // prints, {y->2}
* </pre>
*
* @param function
* @return a resulting {@link LeoArray}
*/
public LeoMap filter(LeoObject function) {
if(function != null) {
LeoMap map = new LeoMap();
for(int i = 0; i < this.bucketLength(); i++) {
LeoObject key = getKey(i);
if(key != null) {
LeoObject value = getValue(i);
if( LeoObject.isTrue(function.xcall(key, value)) ) {
map.put(key, value);
}
}
}
return map;
}
return this;
}
/**
* Maps the supplied function to each element in the array.
*
* <pre>
* var result = [1,2,3,4].map(def(e) return e*2)
* println(result) // 2, 4, 6, 8
* </pre>
*
* @param function
* @return the new mapped {@link LeoMap}
*/
public LeoMap map(LeoObject function) {
if(function != null) {
LeoMap map = new LeoMap();
for(int i = 0; i < this.bucketLength(); i++) {
LeoObject key = getKey(i);
if(key != null) {
LeoObject value = getValue(i);
value = function.xcall(key, value);
map.put(key, value);
}
}
return map;
}
return this;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#isMap()
*/
@Override
public boolean isMap() {
return true;
}
@Override
public boolean isAccessible() {
return true;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#hashCode()
*/
@Override
public int hashCode() {
int h = 0;
for(int i = 0; i < this.hashKeys.length; i++) {
if(this.hashKeys[i] != null) {
h += this.hashKeys[i].hashCode();
}
if(this.hashValues[i] != null ) {
h += this.hashValues[i].hashCode();
}
}
return h;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
sb.append("{ ");
for(int i = 0; i < this.hashKeys.length; i++) {
if(this.hashKeys[i] != null) {
if ( !isFirst) {
sb.append(", ");
}
LeoObject key = this.hashKeys[i];
if(key.isString() ) {
sb.append("\"").append(key).append("\"");
}
else if(key.isNull()) {
sb.append("null");
}
else {
sb.append(key);
}
sb.append(" : ");
LeoObject val = get(this.hashKeys[i]);
if ( val != null ) {
if(val.isString()) {
sb.append("\"").append(val).append("\"");
}
else if(val.isNull()) {
sb.append("null");
}
else {
sb.append(val);
}
}
isFirst = false;
}
}
sb.append(" }");
return sb.toString();
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(double)
*/
@Override
public LeoObject $index(double other) {
return get(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(int)
*/
@Override
public LeoObject $index(int other) {
return get(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(long)
*/
@Override
public LeoObject $index(long other) {
return get(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $index(LeoObject other) {
return get(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$sindex(leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public void $sindex(LeoObject key, LeoObject value) {
put(key,value);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#setObject(leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public void setObject(LeoObject key, LeoObject value) {
if( hasNativeMethod(this, key)) {
getApiMappings().put(key, value);
}
put(key,value);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getObject(leola.vm.types.LeoObject)
*/
@Override
public LeoObject getObject(LeoObject key) {
if(has(key)) {
return get(key);
}
else {
if(hasNativeMethod(this, key)) {
return getNativeMethod(key);
}
}
return LeoObject.NULL;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#xgetObject(leola.vm.types.LeoObject)
*/
@Override
public LeoObject xgetObject(LeoObject key) throws LeolaRuntimeException {
if(has(key)) {
return get(key);
}
else {
return getNativeMethod(key);
}
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#hasObject(leola.vm.types.LeoObject)
*/
@Override
public boolean hasObject(LeoObject key) {
return containsKey(key) || hasNativeMethod(this, key);
}
/**
* Determines if the supplied key is contained in the {@link LeoMap}
*
* @param key
* @return true if the supplied key is contained in the map
*/
public boolean has(LeoObject key) {
return this.containsKey(key);
}
/**
* Determines if the supplied value is contained in the {@link LeoMap}
*
* @param value
* @return true if the supplied value is contained in the map.
*/
public boolean hasValue(LeoObject value) {
return containsValue(value);
}
public void putAllEntries(LeoObject obj) {
if ( obj.isOfType(LeoType.MAP)) {
LeoMap map = obj.as();
this.putAll((Map<LeoObject, LeoObject>)map);
}
}
public void removeAllEntries(LeoObject obj) {
if ( obj.isOfType(LeoType.MAP)) {
LeoMap map = obj.as();
for(LeoObject key : map.keySet()) {
this.remove(key);
}
}
}
/**
* @return true if empty; false otherwise
*/
public boolean empty() {
return this.isEmpty();
}
/**
* @return the key set
* TODO - Optimize this mess
*/
public LeoArray keys() {
return new LeoArray(new ArrayList<LeoObject>(this.keySet()));
}
/**
* @return the value set
*/
public LeoArray vals() {
return new LeoArray(new ArrayList<LeoObject>(this.values()));
}
/**
* @return the array
*/
public Map<LeoObject,LeoObject> getMap() {
return this;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return new LeoMap(this);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#eq(leola.types.LeoObject)
*/
@Override
public boolean $eq( LeoObject val ) {
if ( val == null ) return false;
if ( this == val ) return true;
if ( val.getType() != LeoType.MAP ) return false;
LeoMap t = (LeoMap)val;
if (t.size() != this.size()) return false;
for(int i = 0; i < this.hashKeys.length; i++) {
LeoObject key = this.hashKeys[i];
if(key != null) {
LeoObject myValue = hashget(key);
LeoObject otherValue = t.get(key);
if(myValue != null && otherValue == null) {
return false;
}
if(myValue == null && otherValue != null) {
return false;
}
if(!myValue.equals(otherValue)) {
return false;
}
}
}
return true;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$add(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $add(LeoObject other) {
if (other.isString()) {
return LeoString.valueOf(toString() + other.toString());
}
return super.$add(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$xor(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $xor(LeoObject other) {
return has(other) ? LeoBoolean.LEOTRUE : LeoBoolean.LEOFALSE;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this; /*this.array;*/
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gt(leola.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lt(leola.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return false;
}
@Override
public void write(DataOutput out) throws IOException {
out.write(this.getType().ordinal());
out.writeInt(this.size());
for(Map.Entry<LeoObject, LeoObject> entry : this.entrySet()) {
entry.getKey().write(out);
entry.getValue().write(out);
}
}
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the {@link LeoObject}
* @throws IOException
*/
public static LeoMap read(LeoObject env, DataInput in) throws IOException {
int size = in.readInt();
LeoMap map = new LeoMap(size);
for(int i = 0; i < size; i++) {
LeoObject key = LeoObject.read(map, in);
LeoObject value = LeoObject.read(map, in);
map.put(key, value);
}
return map;
}
private static final int MIN_HASH_CAPACITY = 2;
/** the hash keys */
protected LeoObject[] hashKeys;
/** the hash values */
protected LeoObject[] hashValues;
/** the number of hash entries */
protected int hashEntries;
protected void presize(int nhash) {
if ( nhash >= 0 && nhash < MIN_HASH_CAPACITY )
nhash = MIN_HASH_CAPACITY;
hashKeys = (nhash>0? new LeoObject[nhash]: ArrayUtil.EMPTY_LEOOBJECTS);
hashValues = (nhash>0? new LeoObject[nhash]: ArrayUtil.EMPTY_LEOOBJECTS);
hashEntries = 0;
}
protected LeoObject hashget(LeoObject key) {
if ( hashEntries > 0 ) {
LeoObject v = hashValues[hashFindSlot(key)];
return v!=null? v: LeoNull.LEONULL;
}
return LeoNull.LEONULL;
}
/**
* Returns the value associated with the key. If the key is not found, a Java
* <code>null</code> is returned.
*
* @param key
* @return Returns the value associated with the key. If the key is not found, a Java
* <code>null</code> is returned.
*/
public LeoObject getWithJNull(LeoObject key) {
if ( hashEntries > 0 ) {
LeoObject v = hashValues[hashFindSlot(key)];
return v;
}
return null;
}
/** caller must ensure key is not nil */
public void set( LeoObject key, LeoObject value ) {
rawset(key, value);
}
/** caller must ensure key is not nil */
protected void rawset( LeoObject key, LeoObject value ) {
hashset( key, value );
}
public String getString(String key) {
LeoObject obj = getWithJNull(LeoString.valueOf(key));
return obj != null ? obj.toString() : "";
}
public int getInt(String key) {
LeoObject obj = getWithJNull(LeoString.valueOf(key));
return obj != null ? obj.asInt() : 0;
}
public long getLong(String key) {
LeoObject obj = getWithJNull(LeoString.valueOf(key));
return obj != null ? obj.asLong() : 0;
}
public double getDouble(String key) {
LeoObject obj = getWithJNull(LeoString.valueOf(key));
return obj != null ? obj.asDouble() : 0;
}
public LeoMap getMap(String key) {
LeoObject obj = getWithJNull(LeoString.valueOf(key));
return obj != null ? ((LeoMap)obj.as()) : null;
}
public LeoArray getArray(String key) {
LeoObject obj = getWithJNull(LeoString.valueOf(key));
return obj != null ? ((LeoArray)obj.as()) : null;
}
public boolean getBoolean(String key) {
LeoObject obj = get(LeoString.valueOf(key));
return LeoObject.isTrue(obj);
}
public int length() {
return this.hashEntries;
}
public int bucketLength() {
return this.hashKeys.length;
}
private void error(String error) {
throw new LeolaRuntimeException("LeoMapHashError: " + error);
}
protected int nexti( LeoObject key ) {
int i = 0;
do {
// find current key index
if ( key != LeoNull.LEONULL ) {
if ( hashKeys.length == 0 )
error( "invalid key to 'next'" );
i = hashFindSlot(key);
if ( hashKeys[i] == null )
error( "invalid key to 'next'" );
}
} while ( false );
// check hash part
for ( ; i<hashKeys.length; ++i )
if ( hashKeys[i] != null )
return i;
// nothing found, push nil, return nil.
return -1;
}
public LeoObject getKey(int index) {
return hashKeys[index];
}
public LeoObject getValue(int index) {
return hashValues[index];
}
protected LeoObject nextKey(LeoObject key) {
int i = nexti(key);
return hashKeys[i];
}
protected LeoObject nextValue(LeoObject key) {
int i = nexti(key);
return hashValues[i];
}
/**
* Set a hashtable value
*
* @param key key to set
* @param value value to set
*/
protected LeoObject hashset(LeoObject key, LeoObject value) {
LeoObject r = LeoNull.LEONULL;
/*if ( value == LeoNull.LEONULL )
r = hashRemove(key);
else */
{
if ( hashKeys.length == 0 ) {
hashKeys = new LeoObject[ MIN_HASH_CAPACITY ];
hashValues = new LeoObject[ MIN_HASH_CAPACITY ];
}
int slot = hashFindSlot( key );
r = hashValues[slot];
if ( hashFillSlot( slot, value ) )
return r;
hashKeys[slot] = key;
hashValues[slot] = value;
if ( checkLoadFactor() )
rehash();
}
return r;
}
/**
* Find the hashtable slot to use
* @param key key to look for
* @return slot to use
*/
protected int hashFindSlot(LeoObject key) {
int i = ( key.hashCode() & 0x7FFFFFFF ) % hashKeys.length;
// This loop is guaranteed to terminate as long as we never allow the
// table to get 100% full.
LeoObject k;
while ( ( k = hashKeys[i] ) != null && !k.$eq(key) ) {
i = ( i + 1 ) % hashKeys.length;
}
return i;
}
private boolean hashFillSlot( int slot, LeoObject value ) {
hashValues[ slot ] = value;
if ( hashKeys[ slot ] != null ) {
return true;
} else {
++hashEntries;
return false;
}
}
private LeoObject hashRemove( LeoObject key ) {
LeoObject r = LeoNull.LEONULL;
if ( hashKeys.length > 0 ) {
int slot = hashFindSlot( key );
r = hashValues[slot];
hashClearSlot( slot );
}
return r;
}
/**
* Clear a particular slot in the table
* @param i slot to clear.
*/
protected void hashClearSlot( int i ) {
if ( hashKeys[ i ] != null ) {
int j = i;
int n = hashKeys.length;
while ( hashKeys[ j = ( ( j + 1 ) % n ) ] != null ) {
final int k = ( ( hashKeys[ j ].hashCode() )& 0x7FFFFFFF ) % n;
if ( ( j > i && ( k <= i || k > j ) ) ||
( j < i && ( k <= i && k > j ) ) ) {
hashKeys[ i ] = hashKeys[ j ];
hashValues[ i ] = hashValues[ j ];
i = j;
}
}
--hashEntries;
hashKeys[ i ] = null;
hashValues[ i ] = null;
if ( hashEntries == 0 ) {
hashKeys = ArrayUtil.EMPTY_LEOOBJECTS;
hashValues = ArrayUtil.EMPTY_LEOOBJECTS;
}
}
}
private boolean checkLoadFactor() {
// Using a load factor of (n+1) >= 7/8 because that is easy to compute without
// overflow or division.
final int hashCapacity = hashKeys.length;
return hashEntries >= (hashCapacity - (hashCapacity>>3));
}
private void rehash() {
final int oldCapacity = hashKeys.length;
final int newCapacity = oldCapacity+(oldCapacity>>2)+MIN_HASH_CAPACITY;
final LeoObject[] oldKeys = hashKeys;
final LeoObject[] oldValues = hashValues;
hashKeys = new LeoObject[ newCapacity ];
hashValues = new LeoObject[ newCapacity ];
for ( int i = 0; i < oldCapacity; ++i ) {
final LeoObject k = oldKeys[i];
if ( k != null ) {
final LeoObject v = oldValues[i];
final int slot = hashFindSlot( k );
hashKeys[slot] = k;
hashValues[slot] = v;
}
}
}
/* (non-Javadoc)
* @see java.util.Map#size()
*/
@Override
public int size() {
return this.hashEntries;
}
/* (non-Javadoc)
* @see java.util.Map#isEmpty()
*/
@Override
public boolean isEmpty() {
return this.hashEntries == 0;
}
/* (non-Javadoc)
* @see java.util.Map#containsKey(java.lang.Object)
*/
@LeolaMethod(alias="containsKey")
@Override
public boolean containsKey(Object key) {
if(key instanceof String) {
key = LeoString.valueOf(key.toString());
}
int slot = hashFindSlot((LeoObject)key);
return this.hashValues[slot] != null;
}
/**
* Checks the keys, converts to {@link LeoString}
* @param key
* @return
* @see LeoMap#containsKey(Object)
*/
public boolean containsKeyByString(String key) {
int slot = hashFindSlot(LeoString.valueOf(key));
return this.hashValues[slot] != null;
}
/* (non-Javadoc)
* @see java.util.Map#containsValue(java.lang.Object)
*/
@LeolaMethod(alias="containsValue")
@Override
public boolean containsValue(Object value) {
LeoObject val = (LeoObject)value;
for(int i = 0; i < this.hashKeys.length; i++) {
if ( this.hashValues[i] != null) {
if ( this.hashValues[i].$eq(val) )
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see java.util.Map#get(java.lang.Object)
*/
@LeolaMethod(alias="get")
@Override
public LeoObject get(Object key) {
if(key instanceof String) {
key = LeoString.valueOf(key.toString());
}
return hashget((LeoObject)key);
}
/**
* Retrieves by key (a java {@link String})
* @param key
* @return
* @see LeoMap#get(Object)
*/
public LeoObject getByString(String key) {
return hashget(LeoString.valueOf(key));
}
/* (non-Javadoc)
* @see java.util.Map#put(java.lang.Object, java.lang.Object)
*/
@Override
public LeoObject put(LeoObject key, LeoObject value) {
return hashset(key, value);
}
/**
* Converts the Java String into a {@link LeoString}
* @param key
* @param value
* @return
* @see LeoMap#put(LeoObject, LeoObject)
*/
public LeoObject putByString(String key, LeoObject value) {
return hashset(LeoString.valueOf(key), value);
}
/* (non-Javadoc)
* @see java.util.Map#remove(java.lang.Object)
*/
@LeolaMethod(alias="remove")
@Override
public LeoObject remove(Object key) {
if(key instanceof String) {
key = LeoString.valueOf(key.toString());
}
return this.hashRemove((LeoObject)key);
}
/**
* Removes by key (a java String)
* @param key
* @return
* @see LeoMap#remove(Object)
*/
public LeoObject removeByString(String key) {
return this.hashRemove(LeoString.valueOf(key));
}
/* (non-Javadoc)
* @see java.util.Map#putAll(java.util.Map)
*/
@LeolaMethod(alias="putAll")
@Override
public void putAll(Map<? extends LeoObject, ? extends LeoObject> m) {
for(Map.Entry<? extends LeoObject, ? extends LeoObject> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
/* (non-Javadoc)
* @see java.util.Map#clear()
*/
@Override
public void clear() {
for(int i = 0; i < this.hashKeys.length; i++) {
this.hashKeys[i] = null;
this.hashValues[i] = null;
}
this.hashEntries = 0;
}
/* (non-Javadoc)
* @see java.util.Map#keySet()
*/
@Override
public Set<LeoObject> keySet() {
Set<LeoObject> r = new HashSet<LeoObject>(this.hashEntries);
for(int i = 0; i < this.hashKeys.length; i++) {
if ( this.hashKeys[i] != null ) {
r.add(this.hashKeys[i]);
}
}
return r;
}
/* (non-Javadoc)
* @see java.util.Map#values()
*/
@Override
public Collection<LeoObject> values() {
List<LeoObject> r = new ArrayList<LeoObject>(this.hashEntries);
for(int i = 0; i < this.hashValues.length; i++) {
if ( this.hashValues[i] != null ) {
r.add(this.hashValues[i]);
}
}
return r;
}
/* (non-Javadoc)
* @see java.util.Map#entrySet()
*/
@Override
public Set<java.util.Map.Entry<LeoObject, LeoObject>> entrySet() {
Set<java.util.Map.Entry<LeoObject, LeoObject>> r = new HashSet<java.util.Map.Entry<LeoObject, LeoObject>>(this.hashEntries);
for(int i = 0; i < this.hashKeys.length; i++) {
if ( this.hashKeys[i] != null ) {
r.add( new Entry(this.hashKeys[i], get(this.hashKeys[i])));
}
}
return r;
}
private class Entry implements java.util.Map.Entry<LeoObject, LeoObject> {
LeoObject key;
LeoObject val;
Entry(LeoObject key, LeoObject val) {
this.key = key;
this.val = val;
}
/* (non-Javadoc)
* @see java.util.Map.Entry#getKey()
*/
@Override
public LeoObject getKey() {
return key;
}
/* (non-Javadoc)
* @see java.util.Map.Entry#getValue()
*/
@Override
public LeoObject getValue() {
return val;
}
/* (non-Javadoc)
* @see java.util.Map.Entry#setValue(java.lang.Object)
*/
@Override
public LeoObject setValue(LeoObject value) {
LeoObject oldVal = this.val;
put(key, value);
this.val = value;
return oldVal;
}
}
}
<|start_filename|>src/leola/ast/ParameterList.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.ArrayList;
import java.util.List;
/**
* A parameter listing
*
* @author Tony
*
*/
public class ParameterList {
private List<String> parameters;
private boolean isVarargs;
/**
*/
public ParameterList() {
this.parameters = new ArrayList<String>();
this.isVarargs = false;
}
/**
* Adds a parameter
* @param parameter
*/
public void addParameter(String parameter) {
this.parameters.add(parameter);
}
/**
* @return the parameters
*/
public List<String> getParameters() {
return parameters;
}
/**
* @return the number of parameters
*/
public int size() {
return this.parameters.size();
}
/**
* @param isVarargs the isVarargs to set
*/
public void setVarargs(boolean isVarargs) {
this.isVarargs = isVarargs;
}
/**
* @return the isVarargs
*/
public boolean isVarargs() {
return isVarargs;
}
}
<|start_filename|>src/leola/vm/ExceptionStack.java<|end_filename|>
/*
* see license.txt
*/
package leola.vm;
import java.util.Stack;
/**
* Keeps track of the program counters for jumping during try/catch/finally blocks.
*
* <p>
* This keeps an internal {@link Stack} of the INIT_*_BLOCKS which contain a program counter to
* the jumping END_BLOCK instruction set (which depending on the type will execute a CATCH or FINALLY
* block statements).
*
* @author Tony
*
*/
public class ExceptionStack {
private Stack<Long> blockStack;
/**
*/
public ExceptionStack() {
this.blockStack = new Stack<Long>();
}
/**
* @return true if there are currently no try statements pushed
* on to the stack.
*/
public boolean isEmpty() {
return this.blockStack.isEmpty();
}
/**
* Push a Try block with a Finally statement on to the stack
*
* @param pc the program counter (instruction index) to jump
* to
*/
public void pushFinally(int pc) {
long instr = pc;
instr = (instr << 32) | 1;
this.blockStack.add(instr);
}
/**
* Push a Try block with a Catch statement on to the stack
*
* @param pc the program counter (instruction index) to jump
* to
*/
public void pushCatch(int pc) {
long instr = pc;
instr = (instr << 32) | 0;
this.blockStack.add(instr);
}
/**
* @return peek at the top of the stack to see if there is
* a Finally block to be executed
*/
public boolean peekIsFinally() {
if(!this.blockStack.isEmpty()) {
long instr = this.blockStack.peek();
return (instr << 32) > 0;
}
return false;
}
/**
* @return peek at the top of the stack to see if there is
* a Catch block to be executed
*/
public boolean peekIsCatch() {
if(!this.blockStack.isEmpty()) {
long instr = this.blockStack.peek();
return (instr << 32) == 0;
}
return false;
}
/**
* @return the program counter at the top of the stack
*/
public int peekAddress() {
long instr = this.blockStack.peek();
return (int) (instr >> 32);
}
/**
* Removes the top of the Stack
*/
public void pop() {
this.blockStack.pop();
}
}
<|start_filename|>src/leola/vm/Leola.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import leola.ast.ASTNode;
import leola.frontend.ParseException;
import leola.frontend.Parser;
import leola.frontend.Scanner;
import leola.frontend.Source;
import leola.lang.ArrayLeolaLibrary;
import leola.lang.CollectionsLeolaLibrary;
import leola.lang.DateLeolaLibrary;
import leola.lang.DebugLeolaLibrary;
import leola.lang.LangLeolaLibrary;
import leola.lang.MapLeolaLibrary;
import leola.lang.ReflectionLeolaLibrary;
import leola.lang.StringLeolaLibrary;
import leola.lang.SystemLeolaLibrary;
import leola.lang.io.IOLeolaLibrary;
import leola.lang.sql.SqlLeolaLibrary;
import leola.vm.Args.ArgsBuilder;
import leola.vm.Scope.ScopeType;
import leola.vm.compiler.Bytecode;
import leola.vm.compiler.Compiler;
import leola.vm.debug.DebugListener;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoScopedObject;
import leola.vm.types.LeoString;
import leola.vm.util.ResourceLoader;
/**
* The Leola Programming Language runtime. This can be either executed as a stand-alone application or by embedding in a Java application.
*
* @author Tony
*
*/
public class Leola {
public static final String VERSION = "0.10.5";
/**
* Usage
*/
private static final String USAGE =
"Leola v" + VERSION + "\n\n" +
"<USAGE> leola " + Args.getOptions() + " <file> [script args] \n" +
Args.getOptionsWithDescription();
private static final String LEOLA_COMPILED_EXT = "leolac";
private static final String LEOLA_EXT = "leola";
public static final String GLOBAL_SCOPE_NAME = "$G";
/**
* Create new instances of a {@link Leola} runtime
* via the {@link ArgsBuilder}
*
* <pre>
* Leola runtime = Leola.builder()
* .setAllowThreadLocals(false)
* .setIsDebugMode(true)
* .setBarebones(true)
* .setSandboxed(false)
* .newRuntime();
*
* </pre>
*
* @return the {@link ArgsBuilder} to build a {@link Leola} runtime
*/
public static ArgsBuilder builder() {
return Args.builder();
}
/**
* Converts the supplied Java Object into a {@link LeoObject} equivalent
*
* @param javaObject
* @return the {@link LeoObject} equivalent of the supplied Java Object
*/
public static LeoObject toLeoObject(Object javaObject) {
return LeoObject.valueOf(javaObject);
}
/**
* Runs the {@link Leola} runtime as a stand alone application
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if(args.length == 0) {
System.out.println(USAGE);
}
else {
Args pargs = Args.parse(args);
try {
if(pargs.executeStatement()) {
executeStatement(pargs);
}
else if(pargs.isRepl()) {
executeRepl(pargs);
}
else {
executeScript(pargs);
}
}
catch(ParseException e) {
System.err.println(e.getMessage());
}
catch(LeolaRuntimeException e) {
System.err.println(e.getLeoError());
}
}
}
/**
* Executes statement the command line statement
*
* @param pargs
* @throws Exception
*/
private static void executeStatement(Args pargs) throws Exception {
Leola runtime = new Leola(pargs);
Bytecode code = runtime.compile(new BufferedReader(
new StringReader(pargs.getStatement())));
if ( pargs.displayBytecode()) {
System.out.println(code.dump());
}
LeoObject result = runtime.execute(code);
if(result.isError()) {
System.err.println(result);
}
else {
System.out.println(result);
}
}
/**
* Executes the REPL
*
* @param args
* @throws Exception
*/
private static void executeRepl(Args args) throws Exception {
Repl repl = new Repl(new Leola(args));
repl.execute();
}
/**
* Finds the script file that was passed by the command line
*
* @param pargs
* @return the {@link File}
*/
private static File findScriptFile(Args pargs) {
String fileName = pargs.getFileName();
File file = new File(fileName);
if(!file.exists()) {
file = new File(System.getProperty("user.dir"), fileName);
if(!file.exists()) {
for(File dir : pargs.getIncludeDirectories()) {
file = new File(dir, fileName);
if(file.exists()) {
return file;
}
}
}
}
if(!file.exists()) {
System.out.println("Unable to find '" + fileName + "'");
System.exit(1);
}
pargs.getIncludeDirectories().add(file.getParentFile());
return file;
}
/**
* Execute or compile the supplied script
*
* @param pargs
* @throws Exception
*/
private static void executeScript(Args pargs) throws Exception {
File scriptFile = findScriptFile(pargs);
Leola runtime = new Leola(pargs);
boolean isCompiled = runtime.hasLeolaCompiledExtension(scriptFile);
Bytecode code = !isCompiled ?
runtime.compile(scriptFile) :
runtime.read(scriptFile);
if ( pargs.displayBytecode()) {
System.out.println(code);
}
if (! isCompiled && pargs.generateBytecode()) {
runtime.write(runtime.toLeolaCompiledFile(scriptFile), code);
}
else {
LeoObject result = runtime.execute(code);
if(result.isError()) {
System.err.println(result);
}
}
}
/**
* A means for retrieving a VM instance
*
* @author Tony
*
*/
private static interface VMReference {
public VM get();
}
/**
* Varargs
*/
private Args args;
/**
* Include directories
*/
private List<File> includeDirectories;
/**
* Resource loader
*/
private ResourceLoader resourceLoader;
/**
* Global namespace
*/
private LeoNamespace global;
/**
* Debug listener
*/
private DebugListener debugListener;
/**
* Local thread variable for the VM
*/
private VMReference vm;
/**
* @throws Exception
*/
public Leola() throws LeolaRuntimeException {
this(new Args());
}
/**
* @param args
* @throws LeolaRuntimeException
*/
public Leola(Args args) throws LeolaRuntimeException {
this.args = args;
setIncludePath(args.getIncludeDirectories());
this.resourceLoader = new ResourceLoader(this);
if(args.allowThreadLocal()) {
this.vm = new VMReference() {
private ThreadLocal<VM> vm = new ThreadLocal<VM>() {
@Override
protected VM initialValue() {
return new VM(Leola.this);
}
};
@Override
public VM get() {
return vm.get();
}
};
this.vm.get();
}
else {
this.vm = new VMReference() {
private VM vm = new VM(Leola.this);
@Override
public VM get() {
return this.vm;
}
};
}
Scope globalScope = new Scope(ScopeType.Namespace, null);
this.global = new LeoNamespace(globalScope, LeoString.valueOf(GLOBAL_SCOPE_NAME));
reset();
}
/**
* <b>Use with extreme caution!</b>
*
* <p>
* This will clear out all allocated objects, effectively resetting the {@link Leola} to its initial state.
*/
public void reset() {
this.resourceLoader.clearCache();
this.global.getScope().clear();
this.global.getNamespaceDefinitions().storeNamespace(this.global);
put("$args", args.getScriptArgs());
put("this", this.global);
/* allow default system libraries to be loaded */
boolean isSandboxed = args.isSandboxed();
args.setSandboxed(false);
try {
loadLibrary(new LangLeolaLibrary());
loadLibrary(new StringLeolaLibrary(), "str");
loadLibrary(new MapLeolaLibrary(), "map");
loadLibrary(new ArrayLeolaLibrary(), "array");
loadLibrary(new DateLeolaLibrary(), "date");
loadLibrary(new CollectionsLeolaLibrary());
// AUX libraries
if (!args.isBarebones() && !isSandboxed) {
loadLibrary(new IOLeolaLibrary(), "io");
loadLibrary(new SqlLeolaLibrary(), "db");
loadLibrary(new SystemLeolaLibrary(), "sys");
loadLibrary(new DebugLeolaLibrary(), "debug");
loadLibrary(new ReflectionLeolaLibrary(), "reflect");
}
}
finally {
args.setSandboxed(isSandboxed);
}
}
/**
* In Sandboxed mode, all
* access to Java classes are disabled and importing {@link LeolaLibrary}s
* is also disabled.
* @return true if in Sandboxed mode, false otherwise
*/
public boolean isSandboxed() {
return args.isSandboxed();
}
/**
* @return the varargs
*/
public Args getArgs() {
return args;
}
/**
* @return the resourceLoader
*/
public ResourceLoader getResourceLoader() {
return resourceLoader;
}
/**
* @return the includeDirectories
*/
public List<File> getIncludePath() {
return includeDirectories;
}
/**
* Sets the path
*
* @param includeDirectories
*/
public void setIncludePath(List<File> includeDirectories) {
this.includeDirectories = includeDirectories;
}
/**
* Adds a path to the paths to check for when include/require look
* ups.
*
* @param includeDirectory
*/
public void addIncludePath(File includeDirectory) {
if(this.includeDirectories==null) {
this.includeDirectories = new ArrayList<File>();
}
this.includeDirectories.add(includeDirectory);
}
/**
* Sets the include path
* @param paths
*/
public void setIncludePath(String paths) {
this.includeDirectories.clear();
String[] apaths = paths.split(";");
for(String path : apaths) {
this.includeDirectories.add(new File(path));
}
}
/**
* @param debugListener the debugListener to set
*/
public void setDebugListener(DebugListener debugListener) {
this.debugListener = debugListener;
}
/**
* @return the debugListener
*/
public DebugListener getDebugListener() {
return debugListener;
}
/**
* @return the current working directory
*/
public File getWorkingDirectory() {
return new File(System.getProperty("user.dir"));
}
/**
* If this {@link Leola} instance was started from the command-line or was supplied
* a script via the {@link Args#getFileName()}, this will return said script as a {@link File}.
*
* @return the execution script that was used for this {@link Leola} instance. This may return
* null, if no script was used.
*/
public File getExecutionScript() {
String executionScript = this.args.getFileName();
if(executionScript!=null) {
return new File(executionScript);
}
return null;
}
/**
* Determines if the supplied {@link File} has the Leola script
* file extension.
*
* @param file
* @return true if the {@link File} is named as a Leola script file
*/
public boolean hasLeolaExtension(File file) {
return file.getName().endsWith(LEOLA_EXT);
}
/**
* Determines if the supplied {@link File} has the Leola compiled script
* file extension.
*
* @param file
* @return true if the {@link File} is named as a Leola compiled script file
*/
public boolean hasLeolaCompiledExtension(File file) {
return file.getName().endsWith(LEOLA_COMPILED_EXT);
}
/**
* Creates a new {@link File} based on the supplied {@link File},
* converts it into a Leola compiled script file extension.
*
* @param file
* @return a {@link File} that has the Leola comiled script File extension.
*/
public File toLeolaCompiledFile(File file) {
String bytecodeFileName = file.getName()
+ ((file.getName().endsWith(LEOLA_EXT))
? "c" : "." + LEOLA_COMPILED_EXT);
return new File(bytecodeFileName);
}
/**
* Throws a {@link LeolaRuntimeException} if currently in sandboxed mode.
*
* This is an internal API used for error checking other components as a convenience method.
*/
public void errorIfSandboxed() {
if(isSandboxed()) {
throw new LeolaRuntimeException("Sandboxed mode is enabled, access restricted.");
}
}
private void checkIfSandboxed(Class<?> lib) {
if(isSandboxed()) {
throw new LeolaRuntimeException("Sandboxed mode is enabled, can not load library: " + lib.getSimpleName());
}
}
/**
* Loads the objects methods into the global {@link Scope}
* @param jObject
*/
public void loadNatives(Object jObject) {
loadNatives(this.global.getScope(), jObject);
}
/**
* Loads the objects methods into the supplied {@link LeoScopedObject}
*
* @param scope
* @param jObject
*/
public void loadNatives(LeoScopedObject scope, Object jObject) {
scope.getScope().loadNatives(jObject);
}
/**
* Loads the objects methods into the supplied {@link Scope}
* @param scope
* @param jObject
*/
public void loadNatives(Scope scope, Object jObject) {
scope.loadNatives(jObject);
}
/**
* Loads the static methods of the native class into the global {@link Scope}
* @param aClass
*/
public void loadStatics(Class<?> aClass) {
loadStatics(this.global.getScope(), aClass);
}
/**
* Loads the static methods of the native class into the supplied {@link LeoScopedObject}
*
* @param scope
* @param aClass
*/
public void loadStatics(LeoScopedObject scope, Class<?> aClass) {
loadStatics(scope.getScope(), aClass);
}
/**
* Loads the static methods of the native class into the supplied {@link Scope}
*
* @param scope
* @param aClass
*/
public void loadStatics(Scope scope, Class<?> aClass) {
scope.loadStatics(aClass);
}
/**
* Loads a {@link LeolaLibrary} into the global {@link Scope}
*
* @param lib
* @throws LeolaRuntimeException
*/
public void loadLibrary(LeolaLibrary lib) throws LeolaRuntimeException {
checkIfSandboxed(lib.getClass());
lib.init(this, this.global);
}
/**
* Loads a {@link LeolaLibrary} into the supplied namespace
*
* @param lib
* @param namespace
* @throws LeolaRuntimeException
*/
public void loadLibrary(LeolaLibrary lib, String namespace) throws LeolaRuntimeException {
checkIfSandboxed(lib.getClass());
LeoNamespace ns = getOrCreateNamespace(namespace);
lib.init(this, ns);
}
/**
* Loads a {@link LeolaLibrary}.
*
* @param lib
* @throws LeolaRuntimeException
*/
public void loadLibrary(LeolaLibrary lib, LeoNamespace namespace) throws LeolaRuntimeException {
checkIfSandboxed(lib.getClass());
lib.init(this, namespace);
}
/**
* Places the natives into the supplied namespace
*
* @param lib
* @param namespace
* @throws LeolaRuntimeException
*/
public LeoNamespace putIntoNamespace(Object lib, String namespace) throws LeolaRuntimeException {
Scope nsScope = null;
LeoNamespace ns = getNamespace(namespace);
if(ns != null) {
nsScope = ns.getScope();
}
else {
nsScope = new Scope(ScopeType.Namespace, this.global.getScope());
ns = new LeoNamespace(nsScope, LeoString.valueOf(namespace));
this.global.getNamespaceDefinitions().storeNamespace(ns);
}
loadNatives(nsScope, lib);
return ns;
}
/**
* Places the natives into the supplied namespace
*
* @param lib
* @param namespace
* @throws LeolaRuntimeException
*/
public LeoNamespace putIntoNamespace(Object lib, LeoNamespace namespace) throws LeolaRuntimeException {
Scope nsScope = namespace.getScope();
loadNatives(nsScope, lib);
return namespace;
}
/**
* Loads a {@link LeolaLibrary}.
*
* @param libClass
* @throws LeolaRuntimeException
*/
public void loadLibrary(Class<?> libClass, LeoNamespace namespace) throws LeolaRuntimeException {
checkIfSandboxed(libClass);
try {
LeolaLibrary lib = (LeolaLibrary)libClass.newInstance();
loadLibrary(lib, namespace);
}
catch (InstantiationException | IllegalAccessException e) {
throw new LeolaRuntimeException(e);
}
}
/**
* Loads a {@link LeolaLibrary}.
*
* @param libClass
* @throws LeolaRuntimeException
*/
public void loadLibrary(Class<?> libClass, String namespace) throws LeolaRuntimeException {
checkIfSandboxed(libClass);
try {
LeoNamespace ns = getOrCreateNamespace(namespace);
LeolaLibrary lib = (LeolaLibrary)libClass.newInstance();
loadLibrary(lib, ns);
}
catch (InstantiationException | IllegalAccessException e) {
throw new LeolaRuntimeException(e);
}
}
/**
* Loads a {@link LeolaLibrary}.
*
* @param libClass
* @throws LeolaRuntimeException
*/
public void loadLibrary(Class<?> libClass) throws LeolaRuntimeException {
checkIfSandboxed(libClass);
try {
LeolaLibrary lib = (LeolaLibrary)libClass.newInstance();
loadLibrary(lib);
}
catch (InstantiationException | IllegalAccessException e) {
throw new LeolaRuntimeException(e);
}
}
/**
* Places the object in the global {@link Scope}.
*
* @param reference
* @param value
*/
public void put(String reference, Object value) {
put(this.global.getScope(), reference, value);
}
/**
* Places the object into a specific {@link Scope}
*
* @param scope
* @param reference
* @param value
*/
public void put(Scope scope, String reference, Object value) {
scope.storeObject(reference, LeoObject.valueOf(value));
}
/**
* Places the object into a specific {@link LeoScopedObject}
*
* @param scope
* @param reference
* @param value
*/
public void put(LeoScopedObject scope, String reference, Object value) {
put(scope.getScope(), reference, value);
}
/**
* Depending on the configuration, this will return the active (if configured to
* do so, the {@link ThreadLocal} or simply just a shared instance) of {@link VM}.
*
* @see Args#allowThreadLocal()
*
* @return the active {@link VM}
*/
public VM getActiveVM() {
return this.vm.get();
}
/**
* Gets a {@link LeoObject} by reference from the global {@link Scope}.
*
* @param reference
* @return the {@link LeoObject}, or null if not found.
*/
public LeoObject get(String reference) {
return get( this.global.getScope(), reference);
}
/**
* Gets a {@link LeoObject} by reference from a specific {@link Scope}.
*
* @param scope
* @param reference
* @return the {@link LeoObject}, or null if not found
*/
public LeoObject get(Scope scope, String reference) {
return scope.getObject(reference);
}
/**
* Gets a {@link LeoObject} by reference from a specific {@link LeoScopedObject}.
*
* @param scope
* @param reference
* @return the {@link LeoObject}, or null if not found
*/
public LeoObject get(LeoScopedObject scope, String reference) {
return get(scope.getScope(), reference);
}
/**
* Retrieves the namespace or creates it if it isn't found
*
* @param namespace
* @return the {@link LeoNamespace}
*/
public LeoNamespace getOrCreateNamespace(String namespace) {
LeoNamespace ns = namespace != null ? this.getNamespace(namespace) : this.global;
if(ns == null) {
ns = new LeoNamespace(new Scope(ScopeType.Namespace, this.global.getScope()), LeoString.valueOf(namespace));
this.global.getScope().getNamespaceDefinitions().storeNamespace(ns);
}
return ns;
}
/**
* Attempts to lookup a {@link LeoNamespace}.
* @param namespace
* @return the {@link LeoNamespace} object, or null if not found
*/
public LeoNamespace getNamespace(String namespace) {
return this.global.getScope().lookupNamespace(LeoString.valueOf(namespace));
}
/**
* @return the global namespace
*/
public LeoNamespace getGlobalNamespace() {
return this.global;
}
/**
* Executes the supplied {@link Bytecode}
* @param callee
* @param code
* @param args
* @return an object of the resulting execution (always returns an object)
* @throws LeolaRuntimeException
*/
public LeoObject execute(LeoObject callee, Bytecode code, LeoObject[] args) throws LeolaRuntimeException {
return this.vm.get().execute(callee,callee, code,args).throwIfError();
}
/**
* Executes the supplied {@link Bytecode}
* @param callee
* @param code
* @return an object of the resulting execution (always returns an object)
* @throws LeolaRuntimeException
*/
public LeoObject execute(LeoObject callee, Bytecode code) throws LeolaRuntimeException {
return this.vm.get().execute(callee,callee, code).throwIfError();
}
/**
* Executes the supplied {@link Bytecode}
* @param code
* @param args
* @return an object of the resulting execution (always returns an object)
* @throws LeolaRuntimeException
*/
public LeoObject execute(Bytecode code, LeoObject[] args) throws LeolaRuntimeException {
return this.vm.get().execute(this.global,this.global, code,args).throwIfError();
}
/**
* Executes the supplied {@link Bytecode}
* @param code
* @return an object of the resulting execution (always returns an object)
* @throws LeolaRuntimeException
*/
public LeoObject execute(Bytecode code) throws LeolaRuntimeException {
return this.vm.get().execute(this.global, this.global, code).throwIfError();
}
/**
* Evaluates the inlined source code.
* <pre>
* leola.eval("val x = 10; println(x);");
* </pre>
*
* @param inlineSource
* @return
* @throws Exception
*/
public LeoObject eval(String inlineSource) throws Exception {
return eval(new BufferedReader(new StringReader(inlineSource)));
}
public LeoObject eval(InputStream iStream) throws Exception {
return eval(new BufferedReader(new InputStreamReader(iStream)) );
}
/**
* Checks the file extension, if it ends in "leolac" it will treat it as a
* compiled script and attempt to evaluate the bytecode.
*
* @param file
* @return the resulting {@link LeoObject}
* @throws Exception
*/
public LeoObject eval(File file) throws Exception {
return eval(file, Leola.GLOBAL_SCOPE_NAME);
}
/**
* Checks the file extension, if it ends in "leolac" it will treat it as a
* compiled script and attempt to evaluate the bytecode.
*
* @param file
* @param namespace -- if the namespace isn't found, a new one is created
* @return the resulting {@link LeoObject}
* @throws Exception
*/
public LeoObject eval(File file, String namespace) throws Exception {
LeoNamespace ns = getOrCreateNamespace(namespace);
LeoObject result = LeoNull.LEONULL;
boolean isCompiled = hasLeolaCompiledExtension(file);
if(isCompiled) {
try(BufferedInputStream iStream = new BufferedInputStream(new FileInputStream(file))) {
DataInput in = new DataInputStream(iStream);
Bytecode bytecode = Bytecode.read(ns, in);
bytecode.setSourceFile(file);
result = execute(ns, bytecode);
}
}
else {
try(Reader reader = new BufferedReader(new FileReader(file))) {
Bytecode bytecode = compile(reader);
bytecode.setSourceFile(file);
result = execute(ns, bytecode);
}
}
return result;
}
public LeoObject eval(Reader reader) throws Exception {
return eval(reader, this.global);
}
public LeoObject eval(Reader reader, LeoNamespace namespace) throws Exception {
Bytecode bytecode = compile(reader);
LeoObject result = execute(namespace, bytecode);
return result;
}
/**
* Reads the {@link Bytecode} from the {@link File}
*
* @param scriptFile
* @return the {@link Bytecode}
* @throws Exception
*/
public Bytecode read(File scriptFile) throws Exception {
try(InputStream iStream = new BufferedInputStream(new FileInputStream(scriptFile))) {
Bytecode code = read(iStream);
if(code != null) {
code.setSourceFile(scriptFile);
}
return code;
}
}
/**
* Reads the {@link Bytecode} from the {@link InputStream}
*
* @param iStream
* @return the {@link Bytecode}
* @throws Exception
*/
public Bytecode read(InputStream iStream) throws Exception {
try {
DataInput in = new DataInputStream(iStream);
Bytecode code = Bytecode.read(getGlobalNamespace(), in);
return code;
}
finally {
if(iStream != null) {
iStream.close();
}
}
}
/**
* Writes out the {@link Bytecode} to the {@link File}
*
* @param scriptFile
* @param bytecode
* @throws Exception
*/
public void write(File scriptFile, Bytecode bytecode) throws IOException {
FileOutputStream fStream = null;
try {
fStream = new FileOutputStream(scriptFile);
if (scriptFile.exists()) {
fStream.getChannel().truncate(0);
}
write(new BufferedOutputStream(fStream), bytecode);
}
finally {
if (fStream != null) {
fStream.close();
}
}
}
/**
* Writes the {@link Bytecode} out to the {@link OutputStream}
*
* @param oStream
* @param bytecode
* @throws IOException
*/
public void write(OutputStream oStream, Bytecode bytecode) throws IOException {
try {
DataOutput output = new DataOutputStream(oStream);
bytecode.write(output);
oStream.flush();
}
finally {
if (oStream != null) {
oStream.close();
}
}
}
/**
* Compiles the supplied script file
*
* @param scriptFile
* @return the {@link Bytecode}
* @throws Exception
*/
public Bytecode compile(File scriptFile) throws Exception {
Bytecode code = compile(new BufferedReader(new FileReader(scriptFile)));
code.setSourceFile(scriptFile);
return code;
}
/**
* Compiles the file.
*
* @param reader
* @return
* @throws Exception
*/
public Bytecode compile(Reader reader) throws Exception {
ASTNode program = generateAST(reader);
Compiler compiler = new Compiler(this);
return compiler.compile(program);
}
/**
* Evaluates the file.
*
* @param file
* @throws Exception
*/
public ASTNode generateAST(File file) throws Exception {
return generateAST(new BufferedReader(new FileReader(file)));
}
/**
* Reads in the inline source.
*
* @param inlineSource
* @throws Exception
*/
public ASTNode generateAST(String inlineSource) throws Exception {
return generateAST(new BufferedReader(new StringReader(inlineSource)));
}
/**
* Evaluate the stream.
*
* @param iStream
* @throws Exception
*/
public ASTNode generateAST(InputStream iStream) throws Exception {
return generateAST(new BufferedReader(new InputStreamReader(iStream)));
}
/**
* Generates an Abstract Syntax Tree from the stream.
*
* @param reader
* @return the root node of the AST
* @throws Exception
*/
public ASTNode generateAST(Reader reader) throws Exception {
final Source source = new Source(reader);
Scanner scanner = new Scanner(source);
Parser parser = new Parser(scanner);
ASTNode program = null;
try {
program = parser.parse();
}
finally {
source.close();
}
return program;
}
}
<|start_filename|>src/leola/vm/ClassDefinition.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm;
import leola.vm.compiler.Bytecode;
import leola.vm.compiler.Outer;
import leola.vm.types.LeoClass;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoOuterObject;
/**
* Represents a class definition, all of the meta data required to create a {@link LeoClass}
*
* @author Tony
*
*/
public class ClassDefinition {
private LeoObject className;
private ClassDefinition superClass;
private LeoObject[] params;
private LeoObject[] superParams;
private Bytecode body;
private Outer[] outers;
/**
* The scope in which the class
* was defined in
*/
private Scope declaredScope;
/**
* @param className
* @param superClass
* @param declaredScope
* @param numberOfParams
* @param body
*/
public ClassDefinition(LeoObject className, ClassDefinition superClass, Scope declaredScope,
LeoObject[] params, LeoObject[] superParams, Bytecode body) {
super();
this.className = className;
this.superClass = superClass;
this.declaredScope = declaredScope;
this.params = params;
this.superParams = superParams;
this.body = body;
this.outers = body.numOuters>0 ? new Outer[body.numOuters] : LeoOuterObject.NOOUTERS;
}
/**
* @return true if the constructor contains variable arguments
*/
public boolean hasVarargs() {
return this.body.hasVarargs();
}
/**
* @return the number of parameters the constructor takes
*/
public int getNumberOfParameters() {
return this.body.numArgs;
}
/**
* @return the declaredScope
*/
public Scope getDeclaredScope() {
return declaredScope;
}
/**
* @return the outers
*/
public Outer[] getOuters() {
return outers;
}
/**
* @return the className
*/
public LeoObject getClassName() {
return className;
}
/**
* @return the superClass
*/
public ClassDefinition getSuperClassDefinition() {
return superClass;
}
/**
* @return the superParams
*/
public LeoObject[] getSuperParameterNames() {
return superParams;
}
/**
* @return the params
*/
public LeoObject[] getParameterNames() {
return params;
}
/**
* @return the body
*/
public Bytecode getBody() {
return body;
}
/**
* @return true if this definition inherits from another
*/
public boolean hasParentClass() {
return this.superClass != null;
}
}
<|start_filename|>src/leola/lang/io/IOLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoNamespace;
/**
* The Input/Output Library, handles file manipulation operations
*
* @author Tony
*
*/
public class IOLeolaLibrary implements LeolaLibrary {
private Leola runtime;
/* (non-Javadoc)
* @see leola.frontend.LeolaLibrary#init(leola.frontend.Leola)
*/
@LeolaIgnore
public void init(Leola leola, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = leola;
this.runtime.putIntoNamespace(this, namespace);
}
public boolean isDirectory(String filename) {
return new File(filename).isDirectory();
}
public boolean isFile(String filename) {
return new File(filename).isFile();
}
public boolean rename(String filename, String newname) {
return new File(filename).renameTo(new File(newname));
}
/**
* List the contents of the directory
* @param dir
* @return a list of all the files in the supplied directory
*/
public String[] list(String dir) {
return new File(dir).list();
}
/**
* List the contents of the directory (with the supplied path included
* in the name).
* @param dir
* @return
*/
public String[] listFiles(String dir) {
File[] files = new File(dir).listFiles();
String[] contents = new String[files.length];
for(int i = 0; i < contents.length; i++) {
contents[i] = files[i].getAbsolutePath();
}
return contents;
}
/**
* The current working directory
* @return the current working directory
*/
public static String pwd() {
return System.getProperty("user.dir");
}
public void $includePath(String newPath) {
String[] paths = newPath.split(";");
List<File> newIncludePath = new ArrayList<File>(paths.length);
for(String path : paths) {
newIncludePath.add(new File(path));
}
this.runtime.setIncludePath(newIncludePath);
}
public static final boolean delete(String filename) throws Exception {
File f = new File(filename);
return ( f.delete() );
}
/**
* Copies a source file to the destination. This will error out if the destination already exists.
*
* @param source the source file name
* @param destination the destination file name
* @throws Exception
*/
public static final void copy(String source, String destination) throws Exception {
copy(source, destination, false);
}
/**
* Copies a source file to the destination, overriding the destination file if it already
* exists.
*
* @param source
* @param destination
* @throws Exception
*/
public static final void xcopy(String source, String destination) throws Exception {
copy(source, destination, true);
}
private static final void copy(String filename, String destination, boolean force) throws Exception {
File src = new File(filename);
if ( ! src.exists() ) {
throw new IOException(filename + " doesn't exist!");
}
File dst = new File(destination);
if ( dst.exists() ) {
if ( force ) {
if ( dst.delete() ) {
throw new IOException("Unable to forcefully delete: " + destination);
}
}
else {
throw new IOException(destination + " already exists!");
}
}
FileInputStream istream = new FileInputStream(src);
try {
FileOutputStream ostream = new FileOutputStream(dst);
try {
FileChannel dstChannel = ostream.getChannel();
FileChannel srcChannel = istream.getChannel();
try {
long totalBytesTransferred = 0;
long totalNeededForTransfer = srcChannel.size();
while( totalBytesTransferred < totalNeededForTransfer ) {
totalBytesTransferred += srcChannel.transferTo(totalBytesTransferred, totalNeededForTransfer-totalBytesTransferred, dstChannel);
}
}
finally {
try { srcChannel.close(); } catch(Exception e) {}
try { dstChannel.close(); } catch(Exception e) {}
}
}
finally {
ostream.close();
}
}
finally {
istream.close();
}
}
/**
* Moves the source file to the destination. This will error out
* if the destination file already exists.
*
* @param source
* @param destination
* @throws Exception
*/
public static final void move(String source, String destination) throws Exception {
move(source, destination, false);
}
/**
* Moves the source file to the destination, overriding the destination file
* if it already exists.
*
* @param source
* @param destination
* @throws Exception
*/
public static final void xmove(String source, String destination) throws Exception {
move(source, destination, true);
}
private static final void move(String source, String destination, boolean force) throws Exception {
File src = new File(source);
if ( ! src.exists() ) {
throw new IOException(source + " doesn't exist!");
}
File dst = new File(destination);
if ( dst.exists() ) {
if ( force ) {
if ( dst.delete() ) {
throw new IOException("Unable to forcefully delete: " + destination);
}
}
else {
throw new IOException(destination + " already exists!");
}
}
if ( ! src.renameTo(dst) ) {
throw new IOException("Unable to move: " + source + " to: " + destination );
}
}
/**
* Allocates a new memory buffer.
* @param capacity
* @return
*/
public Buffer newBuffer(int capacity) {
return new Buffer(capacity);
}
/**
* Read the full contents of the file as a String. This will assume the {@link Charset}
* of the default for the JVM.
*
* @param filename
* @return the file contents as a {@link String}
* @throws Exception
*/
public String readFully(String filename) throws Exception {
LeolaFile file = null;
try {
file = fopen(filename, "r");
return file.readFully();
}
finally {
if(file!=null) {
file.close();
}
}
}
/**
* Writes out the String contents to the supplied filename. This will create the file if it doesn't exit.
*
* @param filename
* @param contents
* @param append optional parameter to append the the contents, default to false
* @throws Exception
*/
public void writeFully(String filename, String contents, Boolean append) throws Exception {
LeolaFile file = null;
try {
file = fopen(filename, "rw");
if(append == null || !append.booleanValue()) {
file.setLength(0);
}
file.writeBytes(contents.getBytes());
}
finally {
if(file!=null) {
file.close();
}
}
}
/**
* Opens a file. Standard modes are "r" for open as read only, and "rw" for open as
* read-write.
*
* @param filename
* @param mode - @see {@link RandomAccessFile} for valid mode values.
* @return a file handle
* @throws Exception
*/
public LeolaFile fopen(String filename, String mode) throws Exception {
RandomAccessFile raf = new RandomAccessFile(new File(filename), mode);
return new LeolaFile(raf);
}
/**
* Creates a new {@link FileInputStream}
*
* @param filename
* @return the {@link FileInputStream}
* @throws Exception
*/
public InputStream newFileInputStream(String filename) throws Exception {
return new FileInputStream(filename);
}
/**
* Creates a new {@link FileOutputStream}
*
* @param filename
* @param append if open and start appending to the file. Defaults to false.
* @return the {@link FileOutputStream}
* @throws Exception
*/
public OutputStream newFileOutputStream(String filename, Boolean append) throws Exception {
return new FileOutputStream(filename, append!=null ? append : false);
}
/**
* Converts the string into a {@link File}
*
* @param filename
* @return the {@link File}
*/
public File file(String filename) {
return new File(filename);
}
/**
* The default buffer size
*/
public static final int DEFAULT_BUFFER_SIZE = 2048 * 2;
/**
* Reads in a file and pipes to the supplied {@link OutputStream}.
*
* @param file
* @param oStream
* @return
* @throws IOException
*/
public static long readFile(File file, OutputStream oStream) throws IOException {
FileInputStream iStream = new FileInputStream(file);
FileChannel fileChannel = iStream.getChannel();
long bytesRead = 0;
try {
WritableByteChannel target = Channels.newChannel(oStream);
while(bytesRead < fileChannel.size()) {
bytesRead += fileChannel.transferTo(0, fileChannel.size(), target);
}
}
finally {
iStream.close();
}
return bytesRead;
}
/**
* Writes out a file to disk from the supplied {@link InputStream}.
*
* @param file
* @param iStream
* @return
* @throws IOException
*/
public static long writeFile(File file, InputStream iStream) throws IOException {
FileOutputStream oStream = new FileOutputStream(file);
FileChannel fileChannel = oStream.getChannel();
FileLock lock = fileChannel.lock();
long bytesRead = 0;
long totalBytesRead = 0;
try {
try {
do {
bytesRead = fileChannel.transferFrom(Channels.newChannel(iStream), totalBytesRead, DEFAULT_BUFFER_SIZE);
totalBytesRead += bytesRead;
}
while( bytesRead > 0);
}
finally {
if ( lock != null ) {
lock.release();
}
}
}
finally {
oStream.close();
}
return totalBytesRead;
}
/**
* Copy the input into the output.
*
* @param iStream
* @param oStream
* @param bufferSize - size of the buffer
* @return number of bytes copied.
*
* @throws RepositoryException
*/
public static long streamCopy(InputStream iStream, OutputStream oStream, final int bufferSize) throws IOException {
byte[] buffer = new byte[bufferSize];
long size = streamCopy(iStream, oStream, buffer);
return size;
}
/**
* Copy the input into the output.
*
* @param iStream
* @param oStream
* @param buffer - buffer to be used
* @return number of bytes copied.
*
* @throws RepositoryException
*/
public static long streamCopy(InputStream iStream, OutputStream oStream, byte[] buffer) throws IOException {
long size = 0;
int length = 0;
while( (length = iStream.read(buffer)) >= 0 ) {
oStream.write(buffer, 0, length);
size += length;
}
oStream.flush();
return size;
}
}
<|start_filename|>test/leola/ClassUtilTest.java<|end_filename|>
/*
* see license.txt
*/
package leola;
import leola.vm.types.LeoDouble;
import leola.vm.types.LeoInteger;
import leola.vm.types.LeoLong;
import leola.vm.types.LeoNativeClass;
import leola.vm.types.LeoObject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* @author Tony
*
*/
public class ClassUtilTest {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
static class TestClass {
public void none() {
}
public boolean oneBoolean(boolean b) {
System.out.println(b);
return b;
}
public Boolean oneBoolean(Boolean b) {
System.out.println(b);
return b;
}
public void oneByte(byte i, String s) {
Assert.fail();
}
public byte oneByte(byte b) {
System.out.println(b);
return b;
}
public Byte oneByte(Byte b) {
System.out.println(b);
return b;
}
public void oneByte(String b) {
Assert.fail();
}
public void oneByte(int i, String s) {
Assert.fail();
}
public char oneCharacter(char b) {
System.out.println(b);
return b;
}
public Character oneCharacter(Character b) {
System.out.println(b);
return b;
}
public short oneShort(short b) {
System.out.println(b);
return b;
}
public Short oneShort(Short b) {
System.out.println(b);
return b;
}
public int oneInteger(int b) {
System.out.println(b);
return b;
}
public Integer oneInteger(Integer b) {
System.out.println(b);
return b;
}
public long oneLong(long b) {
System.out.println(b);
return b;
}
public Long oneLong(Long b) {
System.out.println(b);
return b;
}
public double oneDouble(double b) {
System.out.println(b);
return b;
}
public Double oneDouble(Double b) {
System.out.println(b);
return b;
}
public float oneFloat(float b) {
System.out.println(b);
return b;
}
public Float oneFloat(Float b) {
System.out.println(b);
return b;
}
public Float three(Float b, Double d, String str) {
System.out.println(b + ":" + d + ":" + str);
return b;
}
public Float three(Double d, Float b, String str) {
System.out.println(b + ":" + d + ":" + str);
return b;
}
public Float threeScale(Double d, Float b, String str) {
System.out.println(b + ":" + d + ":" + str);
return b;
}
public Float threeScale(Double d, Float b) {
System.out.println(b + ":" + d);
return b;
}
public Double threeScale(Double d) {
System.out.println(d);
return d;
}
public void threeScale() {
System.out.println("void");
}
public Double failType(Double d) {
Assert.fail();
return d;
}
}
@Test
public void test() {
LeoNativeClass nClass = new LeoNativeClass(new TestClass());
final String[] types = {"Byte", "Short", "Integer", "Long", "Double", "Float"};
for(String type : types) {
LeoObject method = nClass.getObject("one" + type);
LeoInteger i = LeoInteger.valueOf(120);
Assert.assertEquals(i.asLong(), method.xcall(i).asLong());
LeoLong l = LeoLong.valueOf(120);
Assert.assertEquals(l.asLong(), method.xcall(l).asLong());
LeoDouble d = LeoDouble.valueOf(120);
Assert.assertEquals(d.asLong(), method.xcall(d).asLong());
LeoDouble d2 = LeoDouble.valueOf(120.1);
Assert.assertEquals(d2.asLong(), method.xcall(d2).asLong());
LeoObject o = LeoObject.valueOf(120.0);
Assert.assertEquals(o.asLong(), method.xcall(o).asLong());
}
LeoObject method = nClass.getObject("three");
method.xcall(LeoObject.valueOf(10.3), LeoObject.valueOf(4), LeoObject.valueOf("hello"));
method.xcall(LeoObject.valueOf(10.3), LeoObject.valueOf(4));
method.xcall(LeoObject.valueOf(10.3));
method.xcall();
method = nClass.getObject("threeScale");
method.xcall(LeoObject.valueOf(10.3), LeoObject.valueOf(4), LeoObject.valueOf("hello"));
method.xcall(LeoObject.valueOf(10.3), LeoObject.valueOf(4));
method.xcall(LeoObject.valueOf(10.3));
method.xcall();
//Assert.assertTrue(nClass.getObject("failType").call(LeoObject.valueOf("blowup")).isError());
Assert.assertTrue(nClass.getObject("failType").call(LeoObject.valueOf("blowup")).isError());
}
}
<|start_filename|>src/leola/ast/RealExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Number expression
*
* @author Tony
*
*/
public class RealExpr extends Expr {
private double value;
/**
* @param value
*/
public RealExpr(double value) {
this.value = value;
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the value
*/
public double getValue() {
return value;
}
}
<|start_filename|>src/leola/lang/sql/Query.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoObject.LeoType;
import leola.vm.types.LeoString;
/**
* @author Tony
*
*/
public class Query {
private Connection conn;
private PreparedStatement stmt;
private ParsedSql parsedSql;
private boolean isPrepared;
/**
* @param conn
* @param parsedSql
*/
public Query(Connection conn, ParsedSql parsedSql) {
super();
this.conn = conn;
this.parsedSql = parsedSql;
this.isPrepared = ! this.parsedSql.getNamedParameters().isEmpty();
}
public PreparedStatement statement() throws Exception {
if ( this.stmt == null ) {
String jdbcStatement = this.parsedSql.toJdbcStatement().toString();
this.stmt = this.conn.prepareStatement(jdbcStatement);
}
return this.stmt;
}
public Query params(LeoMap leoparams) throws Exception {
if(LeoObject.isTrue(leoparams)) {
Map<LeoObject,LeoObject> map = leoparams.getMap();
Map<String, LeoObject> params = new HashMap<String, LeoObject>(map.size());
for(Map.Entry<LeoObject, LeoObject> entry : map.entrySet()) {
String paramName = entry.getKey().toString();
params.put(paramName, entry.getValue());
}
setParameters(statement(), params);
}
return this;
}
private void setParameters(PreparedStatement stmt, Map<String, LeoObject> params) throws Exception {
if ( this.isPrepared ) {
Map<String, ParameterLocation> paramLocations = this.parsedSql.getNamedParams();
for(Map.Entry<String, ParameterLocation> entry : paramLocations.entrySet()) {
String paramName = entry.getKey();
ParameterLocation loc= entry.getValue();
if (! params.containsKey(paramName)) {
throw new IllegalArgumentException("No parameter defined for: " + paramName);
}
LeoObject value = params.get(paramName);
for(int i : loc.getParameterIndexes()) {
if ( value.isOfType(LeoType.NULL)) {
stmt.setNull(i, Types.NULL);
}
else {
stmt.setObject(i, value.getValue());
}
}
}
}
}
public void close() throws Exception {
if ( this.stmt != null ) {
this.stmt.close();
}
}
public void setMaxResults(int maxResults) throws SQLException {
this.stmt.setMaxRows(maxResults);
}
/**
* Executes a Read Only Search
* @return
* @throws Exception
*/
public LeoArray execute() throws Exception {
LeoArray result = null;
ResultSet set = null;
PreparedStatement stmt = statement();
try {
set = stmt.executeQuery();
result = convertResultSet(set);
}
finally {
if ( set != null ) {
set.close();
}
}
return result;
}
/**
* Streams the result set invoking the supplied function every fetchSize.
* @param function
* @param fetchSize
* @throws Exception
*/
public void streamExecute(LeoObject function, Integer fetchSize) throws Exception {
ResultSet set = null;
PreparedStatement stmt = statement();
try {
set = stmt.executeQuery();
streamResultSet(function, set, fetchSize);
}
finally {
if ( set != null ) {
set.close();
}
}
}
/**
* Executes an update
* @return
* @throws Exception
*/
public int update() throws Exception {
int result = 0;
ResultSet set = null;
PreparedStatement stmt = statement();
try {
result = stmt.executeUpdate();
}
finally {
if ( set != null ) {
set.close();
}
}
return result;
}
private void safeExecuteFunction(LeoObject function, LeoObject arg1) {
try {
function.call(arg1);
}
catch (Exception e) {
System.err.println(e);
}
}
/**
* Converts the result set
*
* @param set
* @return
* @throws Exception
*/
private void streamResultSet(LeoObject function, ResultSet set, Integer fetchSize) throws Exception {
ResultSetMetaData meta = set.getMetaData();
int numOfColumns = meta.getColumnCount();
LeoArray result = new LeoArray();
final int pageSize = (fetchSize != null) ? fetchSize : 100;
int currentSize = 0;
while(set.next()) {
LeoMap row = new LeoMap();
for(int i = 1; i <= numOfColumns; i++) {
Object obj = set.getObject(i);
row.put( LeoString.valueOf( meta.getColumnName(i)/*.toLowerCase()*/ ),
LeoObject.valueOf(obj));
}
result.$add(row);
currentSize++;
if(currentSize >= pageSize) {
safeExecuteFunction(function, result);
currentSize = 0;
result = new LeoArray();
}
}
if(currentSize > 0) {
safeExecuteFunction(function, result);
}
}
/**
* Converts the result set
*
* @param set
* @return
* @throws Exception
*/
private LeoArray convertResultSet(ResultSet set) throws Exception {
ResultSetMetaData meta = set.getMetaData();
int numOfColumns = meta.getColumnCount();
LeoArray result = new LeoArray();
while(set.next()) {
LeoMap row = new LeoMap();
for(int i = 1; i <= numOfColumns; i++) {
Object obj = set.getObject(i);
row.put( LeoString.valueOf( meta.getColumnName(i)/*.toLowerCase()*/ ),
LeoObject.valueOf(obj));
}
result.$add(row);
}
return result;
}
}
<|start_filename|>src/leola/lang/ReflectionLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.List;
import leola.vm.ClassDefinitions;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.lib.LeolaMethod;
import leola.vm.lib.LeolaMethodVarargs;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoClass;
import leola.vm.types.LeoClass.Metaclass;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoNativeClass;
import leola.vm.types.LeoNativeFunction;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoScopedObject;
import leola.vm.types.LeoString;
import leola.vm.util.ArrayUtil;
import leola.vm.util.ClassUtil;
/**
* The Reflection API
*
* @author Tony
*
*/
public class ReflectionLeolaLibrary implements LeolaLibrary {
/**
* The runtime
*/
private Leola runtime;
/* (non-Javadoc)
* @see leola.frontend.LeolaLibrary#init(leola.frontend.Leola)
*/
@LeolaIgnore
public void init(Leola runtime, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = runtime;
this.runtime.putIntoNamespace(this, namespace);
}
/**
* @param obj
* @return the type of {@link LeoObject} this is
*/
public String type(LeoObject obj) {
if(obj==null) {
return LeoObject.NULL.getType().name();
}
return obj.getType().name();
}
/**
* Converts the supplied object to a {@link LeoNativeClass}
* @param obj
* @return the {@link LeoNativeClass} representation
*/
public LeoNativeClass asNativeClass(Object obj) {
return new LeoNativeClass(obj);
}
/**
* Reflectively create a new instance of a class.
*
* @param classname
* @param params
* @return Null if not found, the instance if instantiated
*/
@LeolaMethodVarargs
public LeoObject newInstance(LeoObject classname, LeoObject ... params) {
LeoObject result = LeoNull.LEONULL;
ClassDefinitions defs = this.runtime.getGlobalNamespace().getScope().lookupClassDefinitions(classname);
if( defs != null) {
result = defs.newInstance(this.runtime, classname, params);
}
return result;
}
/**
* Retrieves all of the names of the supplied objects attributes.
*
* @param obj
* @return the list of names of attributes
* @throws Exception
*/
public LeoArray instrospectNames(LeoObject obj) throws Exception {
LeoArray result = new LeoArray();
if(obj.isNativeClass()) {
Class<?> aClass = obj.getClass();//obj.getValue().getClass();
List<Method> methods = ClassUtil.getAllDeclaredMethods(aClass);
for(Method m : methods) {
result.add(LeoString.valueOf(m.getName()));
}
List<Field> fields = ClassUtil.getAllDeclaredFields(aClass);
for(Field m : fields) {
result.add(LeoString.valueOf(m.getName()));
}
}
else if(obj.isScopedObject()) {
LeoScopedObject scopedObj = obj.as();
return scopedObj.getPropertyNames();
}
return result;
}
/**
* Introspects the supplied object.
*
* @param obj the object to inspect
* @return the list of attributes the object contains
* @throws Exception
*/
public LeoArray instrospect(LeoObject obj) throws Exception {
LeoArray result = new LeoArray();
if(obj.isNativeClass()) {
Class<?> aClass = obj.getClass();//obj.getValue().getClass();
Object jObj = obj;
List<Method> methods = ClassUtil.getAllDeclaredMethods(aClass);
for(Method m : methods) {
m.setAccessible(true);
boolean isStatic = (m.getModifiers() & Modifier.STATIC) != 0;
if(isStatic) {
result.add(new LeoNativeFunction(m, null));
}
else {
result.add(new LeoNativeFunction(m, jObj));
}
}
List<Field> fields = ClassUtil.getAllDeclaredFields(aClass);
for(Field m : fields) {
m.setAccessible(true);
result.add(new LeoNativeClass(m.get(jObj)));
}
}
else if(obj.isScopedObject()) {
LeoScopedObject scopedObj = obj.as();
return scopedObj.getProperties();
}
return result;
}
/**
* Retrieves the all static methods of the supplied class
*
* @param className
* @return a {@link LeoArray} or {@link LeoNativeFunction}'s that match the supplied methodName
* @throws Exception
*/
public LeoArray getStaticMethods(String className) throws Exception {
Class<?> aClass = Class.forName(className);
List<Method> methods = ClassUtil.getAllDeclaredMethods(aClass);
LeoArray result = new LeoArray(methods.size());
for(Method m : methods) {
boolean isStatic = (m.getModifiers() & Modifier.STATIC) != 0;
if(isStatic) {
result.add(new LeoNativeFunction(m, null));
}
}
return result;
}
/**
* Retrieves the all instance methods of the supplied class
*
* @param instance
* @return a {@link LeoArray} or {@link LeoNativeFunction}'s that match the supplied methodName
* @throws Exception
*/
public LeoArray getStaticMethods(Object instance) throws Exception {
Class<?> aClass = instance.getClass();
List<Method> methods = ClassUtil.getAllDeclaredMethods(aClass);
LeoArray result = new LeoArray(methods.size());
for(Method m : methods) {
boolean isStatic = (m.getModifiers() & Modifier.STATIC) != 0;
if(!isStatic) {
result.add(new LeoNativeFunction(m, instance));
}
}
return result;
}
/**
* Retrieves the static methods of the supplied class
*
* @param className
* @param methodName
* @return a {@link LeoArray} or {@link LeoNativeFunction}'s that match the supplied methodName
* @throws Exception
*/
public LeoArray getStaticMethodsByName(String className, String methodName) throws Exception {
Class<?> aClass = Class.forName(className);
List<Method> methods = ClassUtil.getMethodsByName(aClass, methodName);
LeoArray result = new LeoArray(methods.size());
for(Method m : methods) {
boolean isStatic = (m.getModifiers() & Modifier.STATIC) != 0;
if(isStatic) {
result.add(new LeoNativeFunction(m, null));
}
}
return result;
}
/**
* Retrieves the instance methods of the supplied object
*
* @param instance
* @param methodName
* @return a {@link LeoArray} or {@link LeoNativeFunction}'s that match the supplied methodName
* @throws Exception
*/
public LeoArray getInstanceMethodsByName(Object instance, String methodName) throws Exception {
List<Method> methods = ClassUtil.getMethodsByName(instance.getClass(), methodName);
LeoArray result = new LeoArray(methods.size());
for(Method m : methods) {
boolean isStatic = (m.getModifiers() & Modifier.STATIC) != 0;
if(!isStatic) {
result.add(new LeoNativeFunction(m, instance));
}
}
return result;
}
/**
* Implements a Java Interface
*
* @param interfaceName
* @param leoMethods
* @return the wrapped interface
* @throws Exception
*/
@LeolaMethod(alias="implements")
public LeoObject _implements(final String interfaceName, final LeoObject leoMethods) throws Exception {
Class<?> jClass = Class.forName(interfaceName);
Object obj = Proxy.newProxyInstance(ReflectionLeolaLibrary.class.getClassLoader(), new Class[] {jClass}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
LeoObject[] largs = ArrayUtil.EMPTY_LEOOBJECTS;
if(args!=null && args.length > 0) {
largs = new LeoObject[args.length];
for(int i = 0; i < args.length; i++) {
largs[i] = LeoObject.valueOf(args[i]);
}
}
String methodName = method.getName();
LeoObject leoMethod = leoMethods;
try {
leoMethod = leoMethods.getObject(LeoString.valueOf(methodName));
}
catch(Exception e) {}
if(leoMethod == LeoNull.LEONULL) {
if(methodName.equals("toString")) {
return "Proxy for: " + interfaceName;
}
if(methodName.equals("equals")) {
return proxy.equals(args[0]);
}
if(methodName.equals("hashCode")) {
return proxy.hashCode();
}
}
LeoObject res = leoMethod.xcall(largs);
return LeoObject.toJavaObject(method.getReturnType(), res);
}
});
LeoNativeClass aClass = new LeoNativeClass(obj);
/*
List<Method> methods = ClassUtil.getAllDeclaredMethods(jClass);
for(Method m : methods) {
boolean isPublic= (m.getModifiers() & Modifier.PUBLIC) != 0;
if(isPublic) {
aClass.setMember(LeoString.valueOf(m.getName()), new LeoNativeFunction(m, obj));
}
}*/
return aClass;
}
/**
* Clones the object
* @param obj
* @return the cloned object
*/
public final LeoObject clone(LeoObject obj) {
if(obj==null) {
return LeoNull.LEONULL;
}
return obj.clone();
}
/**
* Calls the function and applies the array as function arguments to this function.
*
* @param func
* @param params
* @return the result from executing the function
*/
@LeolaMethodVarargs
public final LeoObject call(LeoObject func, LeoObject ... params) {
LeoObject result = func.call(params);
return result;
}
/**
* Retrieves the {@link Metaclass} information from the supplied {@link LeoClass}
*
* @param aClass
* @return the {@link Metaclass}
*/
public Metaclass getMetaclass(LeoObject aClass) {
if(aClass==null) return null;
if(aClass.isClass()) {
LeoClass leoClass = aClass.as();
return new Metaclass(leoClass);
}
throw new LeolaRuntimeException(aClass + " is not of LeoClass type.");
}
/**
* Get the {@link LeoNamespace} object
*
* @param namespace
* @return the {@link LeoNamespace}
*/
public LeoObject getNamespace(String namespace) {
if(namespace == null) {
return this.runtime.getGlobalNamespace();
}
return this.runtime.getNamespace(namespace);
}
}
<|start_filename|>src/leola/vm/compiler/Assembler.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.compiler;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import leola.vm.Leola;
import leola.vm.compiler.EmitterScope.ScopeType;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.types.LeoDouble;
import leola.vm.types.LeoInteger;
import leola.vm.types.LeoLong;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
/**
* Leola Bytecode Assembler, basically just a reader for the assemble which is directly translated to the {@link BytecodeEmitter} methods.
*
* @author Tony
*
*/
public class Assembler {
private static final String USAGE = "<usage> leolaasm [-r] <assember file> \n" +
"\t-r -- Runs the file \n";
/* Ensures static initialization of
string/object relationship */
@SuppressWarnings("unused")
private static final LeoObject IGNORE = new LeoLong(0);
/**
* The main entry point into the {@link Assembler}
*
* @param args
* @throws Exception
*/
public static final void main(String [] args) throws Exception {
if(args.length < 1) {
System.out.println(USAGE);
return;
}
String filename = "";
boolean run = false;
if(args.length > 1) {
filename = args[1];
run = true;
}
else {
filename = args[0];
}
Assembler asm = new Assembler();
BytecodeEmitter a = asm.parseFile(filename);
Bytecode code = a.compile();
asm.writeOutput(code, filename + ".lbc");
if(run) {
Leola runtime = new Leola();
try {
LeoObject result = runtime.execute(code);
if(result.isError()) {
System.err.println(result);
}
}
catch(LeolaRuntimeException e) {
System.err.println(e.getLeoError());
}
}
}
/**
*/
public Assembler() {
init();
}
/**
* Writes out the output file.
*
* @param asm
* @param outputfile
* @throws Exception
*/
private void writeOutput(Bytecode bytecode, String outputfile) throws Exception {
RandomAccessFile outputFile = new RandomAccessFile(new File(outputfile), "rw");
try {
bytecode.write(outputFile);
}
finally {
outputFile.close();
}
}
/**
* Parses the assembler file
* @param filename
* @param outputfile
* @return
* @throws Exception
*/
public BytecodeEmitter parseFile(String filename) throws Exception {
return parseInput(new BufferedReader(new FileReader(new File(filename))));
}
/**
* Parses the input assembly.
*
* @param reader
* @return the {@link BytecodeEmitter}
* @throws Exception
*/
public BytecodeEmitter parseInput(BufferedReader reader) throws Exception {
String line = null;
BytecodeEmitter asm = new BytecodeEmitter();
asm.start(ScopeType.GLOBAL_SCOPE);
try {
do {
line = reader.readLine();
if(line != null) {
parseLine(asm, line);
}
}
while(line != null);
}
finally {
reader.close();
}
asm.end();
return asm;
}
/**
* Convenience method of compiling the {@link BytecodeEmitter} from {@link Assembler#parseInput(BufferedReader)}
*
* @param reader
* @return the compiled {@link Bytecode}
* @throws Exception
*/
public Bytecode compile(BufferedReader reader) throws Exception {
BytecodeEmitter asm = parseInput(reader);
return asm.compile();
}
/**
* Parses a line
*
* @param asm
* @param line
* @throws Exception
*/
private final BytecodeEmitter parseLine(BytecodeEmitter asm, String line) throws Exception {
line = parseOutComment(line);
if(line.length() > 0) {
int opcodeIndex = line.indexOf(' ');
if(opcodeIndex > -1) {
String opcode = line.substring(0, opcodeIndex);
Opcode o = opcodes.get(opcode.toUpperCase());
if(o==null) {
throw new LeolaRuntimeException("Unknown opcode: " + opcode);
}
String[] args = line.contains("\"") ? new String[] {line.substring(opcodeIndex)}
: line.substring(opcodeIndex).split(",");
for(int i = 0; i < args.length; i++) args[i] = args[i].trim();
o.invoke(asm, args);
}
/* label */
else if (line.startsWith(":")) {
asm.label(line.substring(1));
}
else {
Opcode o = opcodes.get(line.toUpperCase());
if(o==null) {
throw new LeolaRuntimeException("Unknown opcode: " + line);
}
o.invoke(asm);
}
}
return asm.peek();
}
private String parseOutComment(String line) {
line = line.trim();
int comment = line.indexOf(';');
if(comment > -1) {
/* Constants may have an embedded ; */
if(line.toLowerCase().startsWith(".const")) {
int len = line.length();
boolean inComment = false;
for(int i = ".cons".length(); i < len; i++) {
char c = line.charAt(i);
switch(c) {
case '"': inComment = !inComment; break;
case ';': if(!inComment) {
line = line.substring(0, i);
return line.trim();
}
default: {}
}
}
}
else {
line = line.substring(0, comment);
return line.trim();
}
}
return line;
}
interface Opcode {
void invoke(BytecodeEmitter asm, String ... args);
}
private String mergeString(String[] args) {
String arg1 = args[0].trim();
if(!arg1.endsWith("\"")) {
throw new LeolaRuntimeException("Invalid input: " + arg1);
}
String concat = arg1;
for(int i = 1; i < args.length; i++) {
concat += " " + args[i];
}
String var = concat.substring(1); // remove first "
var = var.substring(0, concat.lastIndexOf('"')-1); // remove last "
return (var);
}
private final Map<String, Opcode> opcodes = new HashMap<String, Assembler.Opcode>();
private void init() {
class Indexes {
int index;
int count;
}
final Stack<Indexes> indexStack = new Stack<Indexes>();
indexStack.add(new Indexes());
/* Pseudo opcodes */
opcodes.put(".CONST", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
String arg1 = args[0].trim();
if( arg1.startsWith("\"") ) {
String var = mergeString(args);
asm.getConstants().store(LeoString.valueOf(var));
}
else {
if(arg1.startsWith("0x")) {
if(arg1.length() > 10) {
asm.getConstants().store(new LeoLong(Long.parseLong(arg1)));
}
else {
asm.getConstants().store(LeoInteger.valueOf(Integer.parseInt(arg1)));
}
}
else if ( arg1.contains(".")) {
asm.getConstants().store(LeoDouble.valueOf(Double.parseDouble(arg1)));
}
else if ( arg1.contains("L") ) {
asm.getConstants().store(new LeoLong(Long.parseLong(arg1)));
}
else {
asm.getConstants().store(LeoInteger.valueOf(Integer.parseInt(arg1)));
}
}
}
});
opcodes.put(".BEGIN", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.start(ScopeType.OBJECT_SCOPE);
}
});
opcodes.put(".END", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.end();
indexStack.pop();
}
});
opcodes.put(".LOCALS", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.allocateLocals(Integer.parseInt(args[0]));
}
});
/* Store operations */
opcodes.put("LOAD_CONST", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.loadconst(Integer.parseInt(args[0]));
}
});
opcodes.put("LOAD_LOCAL", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.loadlocal(Integer.parseInt(args[0]));
}
});
opcodes.put("LOAD_OUTER", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
Outers outers = asm.getOuters();
int outerIndex = Integer.parseInt(args[0]);
/* if this is a new outer, we must create it and
* the index should match
*/
if(outers.getNumberOfOuters() == 0) {
outers.allocate(12);
}
if(outers.getNumberOfOuters() < outerIndex || outers.get(outerIndex) == null) {
Indexes indexes = indexStack.peek();
outers.store(new OuterDesc(indexes.count++, indexStack.size()-1));
}
asm.loadouter(outerIndex);
}
});
opcodes.put("LOAD_NAME", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.loadname(Integer.parseInt(args[0]));
}
});
opcodes.put("PARAM_END", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.paramend();
}
});
opcodes.put("XLOAD_OUTER", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
// Pseudo-Opcode
int outerIndex = Integer.parseInt(args[0]);
Outers outers = asm.getOuters();
Indexes indexes = indexStack.peek();
outers.get(indexes.index++).setIndex(outerIndex);
}
});
opcodes.put("XLOAD_LOCAL", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
// Pseudo-Opcode
int outerIndex = Integer.parseInt(args[0]);
Outers outers = asm.getOuters();
Indexes indexes = indexStack.peek();
outers.get(indexes.index++).setIndex(outerIndex);
}
});
opcodes.put("LOAD_NULL", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.loadnull();
}
});
opcodes.put("LOAD_TRUE", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.loadtrue();
}
});
opcodes.put("LOAD_FALSE", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.loadfalse();
}
});
opcodes.put("STORE_LOCAL", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.storelocal(Integer.parseInt(args[0]));
}
});
opcodes.put("STORE_OUTER", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
Outers outers = asm.getOuters();
int outerIndex = Integer.parseInt(args[0]);
/* if this is a new outer, we must create it and
* the index should match
*/
if(outers.getNumberOfOuters() == 0) {
outers.allocate(12);
}
if(outers.getNumberOfOuters() < outerIndex || outers.get(outerIndex) == null) {
Indexes indexes = indexStack.peek();
outers.store(new OuterDesc(indexes.count++, indexStack.size()-1));
}
asm.storeouter(outerIndex);
}
});
/* stack operators */
opcodes.put("POP", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.pop();
}
});
opcodes.put("OPPOP", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.oppop();
}
});
opcodes.put("DUP", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.dup();
}
});
opcodes.put("RET", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.ret();
}
});
opcodes.put("JMP", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
String label = args[0];
try {
asm.jmp(Integer.parseInt(args[0]));
}
catch(NumberFormatException e) {
asm.jmp(label);
}
}
});
opcodes.put("INVOKE", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
int expandedIndex = -1;
if(args.length>1) {
expandedIndex = Integer.parseInt(args[1]);
}
asm.invoke(Integer.parseInt(args[0]), expandedIndex);
}
});
opcodes.put("TAIL_CALL", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
int expandedIndex = -1;
if(args.length>1) {
expandedIndex = Integer.parseInt(args[1]);
}
asm.tailcall(Integer.parseInt(args[0]), expandedIndex);
}
});
opcodes.put("NEW_OBJ", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
int expandedIndex = -1;
if(args.length>1) {
expandedIndex = Integer.parseInt(args[1]);
}
asm.newobj(Integer.parseInt(args[0]), expandedIndex);
}
});
opcodes.put("NEW_ARRAY", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.newarray(Integer.parseInt(args[0]));
}
});
opcodes.put("NEW_MAP", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.newmap(Integer.parseInt(args[0]));
}
});
opcodes.put("FUNC_DEF", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
/* second parameter is to denote var args */
asm.funcdef(Integer.parseInt(args[0]), args.length > 1);
indexStack.add(new Indexes());
}
});
opcodes.put("GEN_DEF", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
/* second parameter is to denote var args */
asm.gendef(Integer.parseInt(args[0]), args.length > 1);
indexStack.add(new Indexes());
}
});
opcodes.put("CLASS_DEF", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.classdef(Integer.parseInt(args[0]), args.length > 1);
indexStack.add(new Indexes());
}
});
opcodes.put("NAMESPACE_DEF", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.namespacedef();
indexStack.add(new Indexes());
}
});
opcodes.put("YIELD", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.yield();
}
});
opcodes.put("IS_A", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.isa();
}
});
opcodes.put("IFEQ", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
String label = args[0];
try {
asm.ifeq(Integer.parseInt(label));
}
catch(NumberFormatException e) {
asm.ifeq(label);
}
}
});
opcodes.put("BREAK", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.brk(args[0]);
}
});
opcodes.put("CONTINUE", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.cont(args[0]);
}
});
opcodes.put("THROW", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.throw_();
}
});
/* object access */
opcodes.put("GET", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.get();
}
});
opcodes.put("SET", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.set();
}
});
opcodes.put("EGETK", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
String argx = args[0];
if(argx.startsWith("\"")) {
asm.egetk(mergeString(args));
}
else {
asm.egetk(Integer.parseInt(argx));
}
}
});
opcodes.put("GETK", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
String argx = args[0];
if(argx.startsWith("\"")) {
asm.getk(mergeString(args));
}
else {
asm.getk(Integer.parseInt(argx));
}
}
});
opcodes.put("SETK", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
String argx = args[0];
if(argx.startsWith("\"")) {
asm.setk(mergeString(args));
}
else {
asm.setk(Integer.parseInt(argx));
}
}
});
opcodes.put("GET_GLOBAL", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
String arg1 = args[0];
if(arg1.startsWith("\"")) {
String var = mergeString(args);
asm.getglobal(var);
}
else {
asm.getglobal(Integer.parseInt(args[0]));
}
}
});
opcodes.put("SET_GLOBAL", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
String arg1 = args[0];
if(arg1.startsWith("\"")) {
String var = mergeString(args);
asm.getglobal(var);
}
else {
asm.setglobal(Integer.parseInt(args[0]));
}
}
});
/* arithmetic operators */
opcodes.put("ADD", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.add();
}
});
opcodes.put("SUB", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.sub();
}
});
opcodes.put("MUL", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.mul();
}
});
opcodes.put("DIV", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.div();
}
});
opcodes.put("MOD", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.mod();
}
});
opcodes.put("NEG", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.neg();
}
});
opcodes.put("BSL", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.bsl();
}
});
opcodes.put("BSR", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.bsr();
}
});
opcodes.put("BNOT", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.bnot();
}
});
opcodes.put("XOR", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.xor();
}
});
opcodes.put("LOR", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.lor();
}
});
opcodes.put("LAND", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.land();
}
});
opcodes.put("OR", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.or();
}
});
opcodes.put("AND", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.and();
}
});
opcodes.put("NOT", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.not();
}
});
opcodes.put("REQ", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.req();
}
});
opcodes.put("EQ", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.eq();
}
});
opcodes.put("NEQ", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.neq();
}
});
opcodes.put("GT", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.gt();
}
});
opcodes.put("GTE", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.gte();
}
});
opcodes.put("LT", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.lt();
}
});
opcodes.put("LTE", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.lte();
}
});
opcodes.put("LINE", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.line(Integer.parseInt(args[0]));
}
});
opcodes.put("INIT_FINALLY", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
String label = args[0];
try {
asm.initfinally(Integer.parseInt(label));
}
catch(NumberFormatException e) {
asm.initfinally(label);
}
}
});
opcodes.put("INIT_CATCH", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
String label = args[0];
try {
asm.initcatch(Integer.parseInt(label));
}
catch(NumberFormatException e) {
asm.initcatch(label);
}
}
});
opcodes.put("END_CATCH", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.endcatch();
}
});
opcodes.put("END_FINALLY", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.endfinally();
}
});
opcodes.put("END_BLOCK", new Opcode() {
public void invoke(BytecodeEmitter asm, String... args) {
asm.endblock();
}
});
}
}
<|start_filename|>src/leola/vm/types/LeoNativeFunction.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.util.ClassUtil;
/**
* A {@link LeoNativeFunction} is a function or better known as a Closure.
*
* @author Tony
*
*/
public class LeoNativeFunction extends LeoObject {
/**
* Arguments
*/
private final int numberOfArgs;
private final Class<?> clss;
private final Object instance;
private final LeoObject methodName;
private final List<Method> overloads;
/**
* @param overloads
* @param instance
*/
public LeoNativeFunction(List<Method> overloads, Object instance) {
super(LeoType.NATIVE_FUNCTION);
if(overloads.isEmpty()) {
LeoObject.throwNativeMethodError("No native Java methods defined");
}
Method base = overloads.get(0);
this.clss = base.getDeclaringClass();
this.methodName = LeoString.valueOf(base.getName());
this.instance = instance;
this.overloads = overloads;
if(overloads.size() > 1) {
this.numberOfArgs = -1;
}
else {
this.numberOfArgs = base.getParameterTypes().length;
}
}
/**
* @param method
* @param instance
*/
public LeoNativeFunction(Method method, Object instance) {
this(Arrays.asList(method), instance);
}
/**
* @return the clss
*/
public Class<?> getOwnerClass() {
return clss;
}
/**
* @return the instance
*/
public Object getInstance() {
return instance;
}
/**
* @return the methodName
*/
public LeoObject getMethodName() {
return methodName;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#isFunction()
*/
@Override
public boolean isFunction() {
return true;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#isNativeFunction()
*/
@Override
public boolean isNativeFunction() {
return true;
}
/**
* @return the numberOfArgs
*/
public int getNumberOfArgs() {
return numberOfArgs;
}
@Override
public LeoObject call() {
return nativeCall();
}
@Override
public LeoObject call(LeoObject arg1) {
return nativeCall(arg1);
}
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2) {
return nativeCall(arg1, arg2);
}
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2, LeoObject arg3) {
return nativeCall(arg1, arg2, arg3);
}
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2,
LeoObject arg3, LeoObject arg4) {
return nativeCall(arg1, arg2, arg3, arg4);
}
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2,
LeoObject arg3, LeoObject arg4, LeoObject arg5) {
return nativeCall(arg1, arg2, arg3, arg4, arg5);
}
@Override
public LeoObject call(LeoObject[] args) {
return nativeCall(args);
}
/**
* Invokes the native function using Java reflection.
*
* @param args
* @return the result of the function invocation
*/
public LeoObject nativeCall(LeoObject... args) {
Object result = null;
try {
result = ClassUtil.invokeMethod(this.overloads, this.instance, args);
}
catch(LeolaRuntimeException e) {
//throw e;
return ((LeolaRuntimeException)e).getLeoError();
}
catch (Exception e) {
//LeoObject.rethrow(e);
return new LeoError(e);
}
return LeoObject.valueOf(result);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#eq(leola.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
boolean isEquals = (other == this);
if ( !isEquals && other != null ) {
if ( other.isOfType(LeoType.FUNCTION) ) {
LeoNativeFunction function = other.as();
isEquals = function.getNumberOfArgs() == this.numberOfArgs;
}
}
return isEquals;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gt(leola.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lt(leola.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return this;
}
@Override
public void write(DataOutput out) throws IOException {
out.write(this.getType().ordinal());
out.writeBytes(this.methodName.toString());
out.writeBytes(this.clss.getName());
out.writeInt(this.numberOfArgs);
}
}
<|start_filename|>src/leola/ast/ContinueStmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* Empty block
*
* @author Tony
*
*/
public class ContinueStmt extends Stmt {
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
}
<|start_filename|>src/leola/vm/compiler/Compiler.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.compiler;
import leola.ast.ASTNode;
import leola.vm.Leola;
/**
* Compiles an Abstract Syntax Tree into {@link Bytecode}
*
* @author Tony
*
*/
public class Compiler {
private Leola runtime;
/**
* @param runtime
*/
public Compiler(Leola runtime) {
this.runtime = runtime;
}
/**
* Compiles the supplied {@link ASTNode} into {@link Bytecode}
*
* @param node
* @return the {@link Bytecode}
*/
public Bytecode compile(ASTNode node) {
BytecodeGeneratorVisitor gen = new BytecodeGeneratorVisitor(this.runtime, new EmitterScopes());
node.visit(gen);
BytecodeEmitter asm = gen.getAsm();
Bytecode bytecode = asm.compile();
return bytecode;
}
}
<|start_filename|>src/leola/vm/types/LeoNativeClass.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.util.ClassUtil;
/**
* Refers to a Java Class
*
* @author Tony
*
*/
public class LeoNativeClass extends LeoObject {
/**
* Class name
*/
private Class<?> nativeClass;
/**
* The instance of the native class
*/
private Object instance;
/**
* Adds ability to reference the public API of this class
*/
private Map<LeoObject, LeoObject> nativeApi;
private Map<LeoObject, LeoObject> getApiMappings() {
if(this.nativeApi == null) {
synchronized (this) {
if(this.nativeApi == null) {
this.nativeApi = new LeoMap();
}
}
}
return this.nativeApi;
}
private LeoObject getNativeMember(LeoObject key) {
return getNativeMember(this.nativeClass, this.instance, getApiMappings(), key);
}
/**
*/
public LeoNativeClass() {
this(null, null);
}
/**
* @param instance
*/
public LeoNativeClass(Object instance) {
this(instance.getClass(), instance);
}
/**
* @param nativeClass
* @param instance
*/
public LeoNativeClass( Class<?> nativeClass, Object instance) {
super(LeoType.NATIVE_CLASS);
this.nativeClass = nativeClass;
this.instance = instance;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#toString()
*/
@Override
public String toString() {
return this.instance.toString();
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isOfType(java.lang.String)
*/
@Override
public boolean isOfType(String rawType) {
return is(rawType);
}
/**
* @param className
* @return true if the supplied className is of this type
*/
public boolean is(String className) {
boolean result = false;
try {
Class<?> cls = Class.forName(className);
Class<?> currentClass = this.nativeClass;
while(!result && currentClass != null) {
result = cls.getName().equals(currentClass.getName());
currentClass = currentClass.getSuperclass();
}
}
catch(Throwable t) {
}
return result;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isClass()
*/
@Override
public boolean isClass() {
return true;
}
@Override
public boolean isAccessible() {
return true;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isNativeClass()
*/
@Override
public boolean isNativeClass() {
return true;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#setObject(leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public void setObject(LeoObject key, LeoObject value) {
setMember(key, value);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getObject(leola.vm.types.LeoObject)
*/
@Override
public LeoObject xgetObject(LeoObject key) {
return getMember(key);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getObject(leola.vm.types.LeoObject)
*/
@Override
public LeoObject getObject(LeoObject key) {
LeoObject member = getMember(key);
if(member!=null) {
return member;
}
return LeoObject.NULL;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#hasObject(leola.vm.types.LeoObject)
*/
@Override
public boolean hasObject(LeoObject key) {
return getMember(key) != null;
}
/**
* If the underlying native class can be indexed into
* @return true if indexable
*/
private boolean isIndexable() {
return List.class.isAssignableFrom(this.nativeClass) ||
Map.class.isAssignableFrom(this.nativeClass);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$sindex(leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public void $sindex(LeoObject key, LeoObject other) {
Method method = ClassUtil.getMethodByAnnotationAlias(nativeClass, "$sindex");
if(method!=null) {
try {
ClassUtil.invokeMethod(method, instance, new LeoObject[] {key, other});
}
catch (Exception e) {
throw new LeolaRuntimeException(e);
}
}
else if(isIndexable()) {
String functionName = (List.class.isAssignableFrom(this.nativeClass)) ?
"set" : "put";
LeoObject func = getMember(LeoObject.valueOf(functionName));
func.call(key, other);
}
else {
super.$sindex(key, other);
}
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $index(LeoObject other) {
Method method = ClassUtil.getMethodByAnnotationAlias(nativeClass, "$index");
if(method!=null) {
try {
return LeoObject.valueOf( ClassUtil.invokeMethod(method, instance, new LeoObject[] {other}) );
}
catch (Exception e) {
throw new LeolaRuntimeException(e);
}
}
else if(isIndexable()){
LeoObject func = getMember(LeoObject.valueOf("get"));
return func.call(other);
}
return super.$index(other);
}
/**
* Attempt to retrieve a native member of the supplied Java class. This will first check
* the public methods, short of that, it will then check the public data members.
*
* @param member
* @return the member if found.
*/
public LeoObject getMember(LeoObject member) {
LeoObject result = getNativeMember(member);
return result;
}
/**
* Attempts to set the Java objects field. If it isn't found or fails to set
* the field, an exception is thrown.
*
* @param member
* @param value
*/
public void setMember(LeoObject member, LeoObject value) {
String memberName = member.toString();
Field field = getField(memberName);
if ( field != null ) {
try {
field.set(getInstance(), value.getValue(field.getType()));
}
catch(Exception e) {
throwAttributeAccessError(nativeClass, member);
}
}
else {
throwAttributeError(nativeClass, member);
}
}
/**
* @return the nativeClass
*/
public Class<?> getNativeClass() {
return nativeClass;
}
/**
* @param fieldName
* @return returns the field if found, if not found null
*/
public Field getField(String fieldName) {
Field field = ClassUtil.getInheritedField(nativeClass, fieldName);
return field;
}
/**
* @param methodName
* @return all methods defined by the supplied methodName
*/
public List<Method> getMethods(String methodName) {
List<Method> meth = ClassUtil.getMethodsByName(nativeClass, methodName);
return meth;
}
/**
* @return the instance
*/
public Object getInstance() {
return instance;
}
/**
* @param instance the instance to set
*/
public void setInstance(Object instance) {
this.instance = instance;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#add(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $add(LeoObject other) {
if (other.isString()) {
return LeoString.valueOf(toString() + other.toString());
}
return super.$add(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$req(leola.vm.types.LeoObject)
*/
@Override
public boolean $req(LeoObject other) {
return this.instance == other.getValue();
}
/* (non-Javadoc)
* @see leola.types.LeoObject#eq(leola.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
if ( other != null && other.isOfType(LeoType.NATIVE_CLASS)) {
LeoNativeClass otherClass = other.as();
return this.instance.equals(otherClass.instance);
}
return false;
}
@Override
public int hashCode() {
return this.instance.hashCode();
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if(obj instanceof LeoObject) {
return $eq((LeoObject)obj);
}
return this.instance.equals(obj);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gt(leola.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lt(leola.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this.instance;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getValue(java.lang.Class)
*/
@Override
public Object getValue(Class<?> narrowType) {
if(LeoObject.class.equals(narrowType)) {
return this;
}
return narrowType.isInstance(this.instance) ? narrowType.cast(this.instance) : this.instance;
}
@Override
public boolean isAssignable(Class<?> javaType) {
return javaType.isAssignableFrom(this.nativeClass);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
LeoNativeClass nClass = new LeoNativeClass(this.nativeClass, this.instance);
return nClass;
}
@Override
public void write(DataOutput out) throws IOException {
out.write(this.getType().ordinal());
out.writeChars(this.nativeClass.getName());
}
}
<|start_filename|>src/leola/vm/util/ResourceLoader.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import leola.vm.EvalException;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaLibrary;
/**
* Loads external resources based on the current working directory and the include path of the {@link Leola} runtime.
*
* @author Tony
*
*/
public class ResourceLoader {
private static final Set<String> NATIVE_LIB = new HashSet<String>();
static {
NATIVE_LIB.add("so");
NATIVE_LIB.add("a");
NATIVE_LIB.add("dll");
}
/**
* Cache of loaded resources
*/
private Set<String> cache;
/**
* The runtime
*/
private Leola runtime;
/**
* @param runtime
*/
public ResourceLoader(Leola runtime) {
this.runtime = runtime;
this.cache = Collections.synchronizedSet(new HashSet<String>());
}
/**
* Clears all cached resources (allowing them
* to be reloaded)
*/
public void clearCache() {
this.cache.clear();
}
/**
* Removes the supplied resource from the cache (allowing it
* to be reloaded)
*
* @param resource
*/
public void removeFromCache(String resource) {
this.cache.remove(resource);
}
/**
* Loads the resource.
*
* @param runtime
* @param interpreter
* @param resource
* @param loadLibrary
* @throws EvalException
*/
private void loadResource(Leola runtime, String resource, boolean loadLibrary, boolean isFirstLevel, String namespace) throws LeolaRuntimeException {
try {
if ( ! this.cache.contains(resource + ":" + namespace) ) {
/** first try loading this as a LeolaLibrary */
if(!tryLoadingLibrary(runtime, resource, namespace)) {
File libFile = resolveName(runtime, resource, true);
String ext = getExtension(libFile.getName());
/* this is directory - so load any libs if possible */
if (libFile.isDirectory() && isFirstLevel) {
String[] jarFiles = libFile.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith("jar");
}
});
for(String file : jarFiles) {
loadResource(runtime, libFile.getAbsolutePath() + "/" + file, loadLibrary, false, namespace);
}
}
/* this is a leola script file */
else if ( ext.endsWith("leola") || ext.endsWith("leolac") ) {
runtime.eval(libFile, namespace);
}
else {
runtime.errorIfSandboxed();
/* load the jar file */
if (ext.endsWith("jar") ) {
Classpath.addFile(libFile);
if ( loadLibrary ) {
loadLibrary(runtime, libFile, namespace);
}
}
else if (NATIVE_LIB.contains(ext) || ext.equals("") ) {
System.loadLibrary(resource.replace(ext, ""));
}
}
}
/* if this was successfully loaded, add it to the cache */
this.cache.add(resource + ":" + namespace);
}
}
catch(Exception e) {
throw new LeolaRuntimeException(e);
}
}
/**
* Includes the file, it does not look for a {@link LeolaLibrary}.
*
* <p>Uses the global namespace
*
* @param resource
* @throws Exception
*/
public void include(String resource) throws LeolaRuntimeException {
include(this.runtime, resource, Leola.GLOBAL_SCOPE_NAME);
}
/**
* Includes the file, it does not look for a {@link LeolaLibrary}.
*
* @param resource
* @param namespace
* @throws Exception
*/
public void include(String resource, String namespace) throws LeolaRuntimeException {
include(this.runtime, resource, namespace);
}
/**
* Includes the file, it does not look for a {@link LeolaLibrary}.
*
* @param resource
* @param namespace
* @throws Exception
*/
public void include(Leola runtime, String resource, String namespace) throws LeolaRuntimeException {
loadResource(runtime, resource, false, true, namespace);
}
/**
* Loads either a Script, Jar file (if jar it looks for a {@link LeolaLibrary}). It
* first looks on the application path, then on the include path.
*
* <p>Uses the global namespace
*
* @param resource
* @throws IOException
*/
public void require(String resource) throws LeolaRuntimeException {
require(this.runtime, resource, Leola.GLOBAL_SCOPE_NAME);
}
/**
* Loads either a Script, Jar file (if jar it looks for a {@link LeolaLibrary}). It
* first looks on the application path, then on the include path.
*
* @param resource
* @param namespace to use
* @throws IOException
*/
public void require(String resource, String namespace) throws LeolaRuntimeException {
require(this.runtime, resource, namespace);
}
/**
* Loads either a Script, Jar file (if jar it looks for a {@link LeolaLibrary}). It
* first looks on the application path, then on the include path.
*
* @param resource
* @throws IOException
*/
public void require(Leola runtime, String resource, String namespace) throws LeolaRuntimeException {
loadResource(runtime, resource, true, true, namespace);
}
/**
* Attempts to resolve the name
* @param lib
* @return
* @throws Exception
*/
private File resolveName(Leola runtime, String lib, boolean withExt) throws Exception {
File libFile = new File(lib);
if ( ! libFile.isAbsolute() ) {
File wd = runtime.getWorkingDirectory();
List<File> dirs = runtime.getIncludePath();
int i = 0;
for( libFile = new File( wd.getAbsolutePath() + "/" + lib);
! libFile.exists() && i < dirs.size();
libFile = new File( dirs.get(i++).getAbsolutePath() + "/" + lib) ) {
}
if ( ! libFile.exists() /*|| ! libFile.isFile()*/ ) {
if(withExt) {
// prefer the leolac version of the file
libFile = resolveName(runtime, lib + ".leolac", false);
if ( ! libFile.exists() || ! libFile.isFile()) {
libFile = resolveName(runtime, lib + ".leola", false);
}
}
if ( withExt && ( !libFile.exists() /*|| !libFile.isFile() */) ) {
throw new IOException(lib + " was not found!");
}
}
}
return libFile;
}
/**
* loads the jar and attempts to load any {@link LeolaLibrary}s.
*
* @param runtime
* @param file
* @throws Exception
*/
private void loadLibrary(Leola runtime, File file, String namespace) throws Exception {
JarInputStream jarFile = new JarInputStream(new FileInputStream (file));
try {
JarEntry jarEntry;
boolean loaded = false;
while(true) {
jarEntry = jarFile.getNextJarEntry();
if(jarEntry == null) {
break;
}
String className = jarEntry.getName().replaceAll("/", "\\.").replaceAll("\\.class", "");
if ( className.endsWith("LeolaLibrary")) {
loaded = tryLoadingLibrary(runtime, className, namespace) || loaded;
}
}
}
finally {
jarFile.close();
}
// if (! loaded ) {
// throw new IOException("No *LeolaLibrary found in: " + file.getName());
// }
}
/**
* Attempts to load the {@link LeolaLibrary}
* @param runtime
* @param className
* @return
*/
private boolean tryLoadingLibrary(Leola runtime, String className, String namespace) throws Exception {
boolean loaded = false;
if(!runtime.isSandboxed()) {
Class<?> lib = null;
try {
lib = Class.forName(className);
if ( ClassUtil.doesImplement(lib, LeolaLibrary.class) ) {
runtime.loadLibrary(lib, namespace);
loaded = true;
}
}
catch(Exception e) {
}
}
return loaded;
}
private String getExtension(String filename) {
if (filename == null) {
return null;
}
int index = filename.lastIndexOf(".");
if (index == -1) {
return "";
} else {
return filename.substring(index + 1);
}
}
}
<|start_filename|>src/leola/lang/sql/NamedParameter.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.sql;
/**
* A {@link NamedParameter} represents a named parameter and location in a SQL statement.
*
* @author Tony
*
*/
public class NamedParameter {
/**
* Parameter name
*/
private String paramName;
/**
* Start index in the sql statement
*/
private int startIndex;
/**
* End index in the sql statement
*/
private int endIndex;
/**
* @param endIndex
* @param paramName
* @param startIndex
*/
public NamedParameter(String paramName, int startIndex, int endIndex) {
this.endIndex = endIndex;
this.paramName = paramName;
this.startIndex = startIndex;
}
/**
* @return the paramName
*/
public String getParamName() {
return paramName;
}
/**
* @return the startIndex
*/
public int getStartIndex() {
return startIndex;
}
/**
* @return the endIndex
*/
public int getEndIndex() {
return endIndex;
}
}
<|start_filename|>src/leola/ast/SwitchStmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.List;
import leola.vm.EvalException;
import leola.vm.util.Pair;
/**
* Switch Stmt
*
* @author Tony
*
*/
public class SwitchStmt extends Stmt {
private Expr condition;
private List<Pair<Expr, Stmt>> whenStmts;
private Stmt elseStmt;
/**
* @param condition
* @param whenStmts
*/
public SwitchStmt(Expr condition, List<Pair<Expr, Stmt>> whenStmts) {
this(condition, whenStmts, null);
}
/**
* @param condition
* @param whenStmts
* @param elseStmt
*/
public SwitchStmt(Expr condition, List<Pair<Expr, Stmt>> whenStmts, Stmt elseStmt) {
this.condition = becomeParentOf(condition);
this.whenStmts = whenStmts;
this.elseStmt = becomeParentOf(elseStmt);
for(Pair<Expr, Stmt> p : whenStmts) {
becomeParentOf(p.getFirst());
becomeParentOf(p.getSecond());
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the condition
*/
public Expr getCondition() {
return condition;
}
/**
* @return the elseStmt
*/
public Stmt getElseStmt() {
return elseStmt;
}
/**
* @return the whenStmts
*/
public List<Pair<Expr, Stmt>> getWhenStmts() {
return whenStmts;
}
}
<|start_filename|>src/leola/ast/NewExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.List;
import leola.vm.EvalException;
/**
* Instantiates a new Object
*
* @author Tony
*
*/
public class NewExpr extends Expr {
/**
* Class name
*/
private String className;
/**
* The parameters for the constructor
*/
private List<Expr> arguments;
/**
* @param className
* @param arguments
*/
public NewExpr(String className, List<Expr> arguments) {
this.className = className;
this.arguments = arguments;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the className
*/
public String getClassName() {
return className;
}
/**
* @return the arguments
*/
public List<Expr> getArguments() {
return arguments;
}
}
<|start_filename|>src/leola/vm/compiler/TailcallOptimizerVisitor.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.compiler;
import java.util.List;
import leola.ast.ASTNode;
import leola.ast.ASTNodeVisitorAdapter;
import leola.ast.BlockStmt;
import leola.ast.Expr;
import leola.ast.FuncInvocationExpr;
import leola.ast.IfStmt;
import leola.ast.ProgramStmt;
import leola.ast.ReturnStmt;
import leola.ast.Stmt;
import leola.ast.YieldStmt;
import leola.vm.EvalException;
/**
* Scans a function definition to see if it can apply a tail-call optimization
*
* @author Tony
*
*/
public class TailcallOptimizerVisitor extends ASTNodeVisitorAdapter {
private boolean isTerminal;
private String functionName;
private boolean isTailcall;
private FuncInvocationExpr tailCallExpr;
/**
* @param functionName
*/
public TailcallOptimizerVisitor(String functionName) {
this.functionName = functionName;
this.isTailcall = false;
this.isTerminal = false;
}
/**
* @return the isTailcall
*/
public boolean isTailcall() {
return isTailcall;
}
/**
* @return the tailCallExpr
*/
public FuncInvocationExpr getTailCallExpr() {
return tailCallExpr;
}
private void findTerminal(List<Stmt> nodes) throws EvalException {
int size = nodes.size();
if ( size > 0 ) {
this.isTerminal = true;
ASTNode lastStatement = nodes.get(size-1);
lastStatement.visit(this);
}
}
@Override
public void visit(ProgramStmt s) throws EvalException {
findTerminal(s.getStatements());
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.BlockStmt)
*/
@Override
public void visit(BlockStmt s) throws EvalException {
findTerminal(s.getStatements());
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.FuncInvocationExpr)
*/
@Override
public void visit(FuncInvocationExpr s) throws EvalException {
/* if this is a terminal node, and
* it is referencing itself, we can
* do the tail-call optimization
*/
if (this.isTerminal) {
if ( this.functionName.equals(s.getFunctionName())) {
this.isTailcall = true;
this.tailCallExpr = s;
}
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.IfStmt)
*/
@Override
public void visit(IfStmt s) throws EvalException {
s.getStmt().visit(this);
Stmt elseStmt = s.getElseStmt();
if ( elseStmt != null ) {
elseStmt.visit(this);
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ReturnStmt)
*/
@Override
public void visit(ReturnStmt s) throws EvalException {
this.isTerminal = true;
Expr r = s.getExpr();
if ( r != null ) {
r.visit(this);
}
}
/* (non-Javadoc)
* @see leola.ast.ASTNodeVisitor#visit(leola.ast.ReturnStmt)
*/
@Override
public void visit(YieldStmt s) throws EvalException {
this.isTerminal = true;
Expr r = s.getExpr();
if ( r != null ) {
r.visit(this);
}
}
}
<|start_filename|>src/leola/ast/SubscriptSetExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.frontend.tokens.Token;
import leola.vm.EvalException;
/**
* Accounts for setting an array access expressions:
*
* <pre>
* array[10] = "x"
* </pre>
*
* @author Tony
*
*/
public class SubscriptSetExpr extends Expr {
/**
* element index
*/
private Expr object;
private Expr elementIndex;
private Expr value;
private Token operator;
/**
* @param elementIndex
*/
public SubscriptSetExpr(Expr object, Expr elementIndex, Expr value, Token operator) {
this.object = object;
this.elementIndex = becomeParentOf(elementIndex);
this.value = value;
this.operator = operator;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public Expr getObject() {
return object;
}
/**
* @return the elementIndex
*/
public Expr getElementIndex() {
return elementIndex;
}
public Expr getValue() {
return value;
}
public Token getOperator() {
return operator;
}
}
<|start_filename|>src/leola/vm/lib/LeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.lib;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.types.LeoNamespace;
/**
* A library module to be loaded for the interpreter.
*
* @author Tony
*/
public interface LeolaLibrary {
/**
* Initializes the library.
*
* @param leola
* @throws LeolaRuntimeException
*/
@LeolaIgnore
public void init(Leola leola, LeoNamespace namespace) throws LeolaRuntimeException;
}
<|start_filename|>src/leola/lang/sql/ParameterLocation.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.sql;
import java.util.ArrayList;
import java.util.List;
/**
* The location of a parameter within a SQL statement
*
* @author Tony
*
*/
public class ParameterLocation {
/**
* The position within the sql statement
*/
private List<Integer> sqlCharPositions;
/**
* The parameter index as it relates to
* JDBC parameters
*/
private List<Integer> parameterIndexes;
/**
* The parameter name
*/
private String parameterName;
/**
* @param sqlCharPosition
* @param parameterIndex
* @param parameterName
*/
public ParameterLocation(String parameterName) {
this.parameterName = parameterName;
this.sqlCharPositions = new ArrayList<Integer>();
this.parameterIndexes = new ArrayList<Integer>();
}
/**
* @return the sqlCharPositions
*/
public List<Integer> getSqlCharPositions() {
return sqlCharPositions;
}
/**
* @return the parameterIndexes
*/
public List<Integer> getParameterIndexes() {
return parameterIndexes;
}
/**
* @return the parameterName
*/
public String getParameterName() {
return parameterName;
}
/**
* @param position
*/
public void addSqlCharPosition(int position) {
this.sqlCharPositions.add(position);
}
/**
* @param index
*/
public void addParameterIndex(int index) {
this.parameterIndexes.add(index);
}
/**
* Adds all the indexes and sql positions from the other {@link ParameterLocation}.
*
* @param other
*/
public void addParameterLocation(ParameterLocation other) {
if ( ! this.parameterName.equals(other.parameterName)) {
throw new IllegalArgumentException
("The supplied ParameterLocation doesn't have the same parameterName: " + other.parameterName + " vs. " + this.parameterName);
}
this.sqlCharPositions.addAll(other.sqlCharPositions);
this.parameterIndexes.addAll(other.parameterIndexes);
}
}
<|start_filename|>src/leola/lang/ArrayLeolaLibrary.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang;
import java.util.Collections;
import java.util.Comparator;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoObject;
/**
* Standard array library. Most of these functions can be called directly on the {@link LeoArray} instance itself.
*
* @author Tony
*
*/
public class ArrayLeolaLibrary implements LeolaLibrary {
private Leola runtime;
/* (non-Javadoc)
* @see leola.vm.lib.LeolaLibrary#init(leola.vm.Leola)
*/
@Override
@LeolaIgnore
public void init(Leola runtime, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = runtime;
this.runtime.putIntoNamespace(this, namespace);
}
public void foreach(LeoArray array, LeoObject function) {
array.foreach(function);
}
public void add(LeoArray array, LeoObject v) {
array.add(v);
}
public void addAll(LeoArray array, LeoObject values) {
array.addAll(values);
}
public boolean remove(LeoArray array, LeoObject v) {
return array.remove(v);
}
public void removeAll(LeoArray array, LeoObject v) {
array.removeAll(v);
}
public LeoObject get(LeoArray array, int i) {
return array.get(i);
}
public boolean has(LeoArray array, LeoObject v) {
return array.has(v);
}
public LeoObject reverse(LeoArray array) {
return array.reverse();
}
public LeoObject slice(LeoArray array, int start, int end) {
return array.slice(start, end);
}
public LeoObject tail(LeoArray array, int start) {
return array.tail(start);
}
public int size(LeoArray array) {
return array.size();
}
public void clear(LeoArray array) {
array.clear();
}
public LeoArray keep(LeoArray array, LeoArray others) {
LeoArray copy = new LeoArray(array);
copy.retainAll(others);
return copy;
}
public void push(LeoArray array, LeoObject v) {
array.push(v);
}
public LeoObject pop(LeoArray array) {
return array.pop();
}
public LeoObject peek(LeoArray array) {
return array.peek();
}
public boolean empty(LeoArray array) {
return array.empty();
}
public LeoObject rest(LeoArray array) {
return array.rest();
}
public LeoObject first(LeoArray array) {
return array.first();
}
public LeoObject last(LeoArray array) {
return array.last();
}
public LeoObject clone(LeoArray array) {
return array.clone();
}
public LeoObject sort(LeoArray array, final LeoObject comparator) {
Collections.sort(array, new Comparator<LeoObject>() {
@Override
public int compare(LeoObject o1, LeoObject o2) {
LeoObject res = comparator.xcall(o1, o2);
return (Integer)LeoObject.toJavaObject(int.class, res);
}
});
return array;
}
}
<|start_filename|>src/leola/ast/IsExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* IS Expression
*
* @author Tony
*
*/
public class IsExpr extends Expr {
/**
* Expression
*/
private Expr object;
private String className;
/**
* @param object
* @param className
*/
public IsExpr(Expr object, String className) {
this.object = object;
this.className = className;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public Expr getObject() {
return object;
}
/**
* @return the className
*/
public String getClassName() {
return className;
}
}
<|start_filename|>src/leola/vm/compiler/Outers.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.compiler;
import leola.vm.Scope;
import leola.vm.util.ArrayUtil;
/**
* Represents the {@link Outer}s that are stored in a particular {@link Scope}.
*
* @author Tony
*
*/
public class Outers {
private OuterDesc[] outers;
private int size;
/**
* @param symbols
*/
public Outers() {
this.size = 0;
}
/**
* This will allocate a new {@link OuterDesc} array if
* one hasn't alread been allocated.
*
* @return the {@link OuterDesc} array
*/
private OuterDesc[] lazyouters() {
if ( this.outers == null ) {
this.outers = ArrayUtil.newOuterDescArray();
}
return this.outers;
}
/**
* Allocate storage for a pre-determined amount of {@link OuterDesc}s
*
* @param size the number of entries to allocate for
*/
public void allocate(int size) {
if ( this.outers == null ) {
this.outers = new OuterDesc[size];
}
if ( size > this.outers.length ) {
this.outers = ArrayUtil.resize(outers, size );
}
}
/**
* Get an {@link OuterDesc} by its stored index
*
* @param index
* @return the {@link OuterDesc} stored in the index
*/
public OuterDesc get(int index) {
return this.outers[index];
}
/**
* @return the number of outers
*/
public int getNumberOfOuters() {
return this.size;
}
/**
* Store the {@link OuterDesc}
* @param value
* @return the index in which this is stored
*/
public int store(OuterDesc value) {
/* first check and see if this outer exists already */
for(int i = 0; i < this.size; i++) {
OuterDesc v = this.outers[i];
if(v!=null) {
if(v.getIndex()==value.getIndex() &&
v.getUp() == value.getUp()) {
return i;
}
}
}
if ( this.size >= lazyouters().length) {
outers = ArrayUtil.resize(outers, outers.length << 1);
}
this.outers[this.size++] = value;
return this.size-1;
}
}
<|start_filename|>src/leola/vm/types/LeoNull.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* Leola's null object.
*
* @author Tony
*
*/
public class LeoNull extends LeoObject {
/**
* the singleton object
*/
public static final LeoNull LEONULL = new LeoNull();
/**
* @param type
*/
private LeoNull() {
super(LeoType.NULL);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#hashCode()
*/
@Override
public int hashCode() {
return 3;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#toString()
*/
@Override
public String toString() {
return "NULL";
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isTrue()
*/
@Override
public boolean isTrue() {
return false;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#isNull()
*/
@Override
public boolean isNull() {
return true;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#eq(leola.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
return (other != null ) && (other == this);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gt(leola.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lt(leola.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return LEONULL;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getValue(java.lang.Class)
*/
@Override
public Object getValue(Class<?> narrowType) {
return null;
}
@Override
public boolean isAssignable(Class<?> javaType) {
return true;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return this;
}
@Override
public void write(DataOutput out) throws IOException {
out.write(this.getType().ordinal());
}
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the {@link LeoObject}
* @throws IOException
*/
public static LeoNull read(DataInput in) throws IOException {
return LeoNull.LEONULL;
}
}
<|start_filename|>src/leola/vm/types/LeoFunction.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import leola.vm.Leola;
import leola.vm.VM;
import leola.vm.compiler.Bytecode;
/**
* A {@link LeoFunction} is a function or better known as a Closure.
*
* @author Tony
*
*/
public class LeoFunction extends LeoOuterObject {
/**
* The Runtime
*/
protected Leola runtime;
/**
* Arguments
*/
private int numberOfArgs;
/**
* Body
*/
private Bytecode bytecode;
/**
* The environment it was created in
*/
protected LeoObject env;
/**
* @param runtime
* @param env
* @param bytecode
*/
public LeoFunction(Leola runtime, LeoObject env, Bytecode bytecode) {
this(runtime, LeoType.FUNCTION, env, bytecode);
}
/**
* @param runtime
* @param type
* @param env
* @param bytecode
*/
protected LeoFunction(Leola runtime, LeoType type, LeoObject env, Bytecode bytecode) {
super(type, bytecode.numOuters);
this.runtime = runtime;
this.env = env;
this.bytecode = bytecode;
this.numberOfArgs = bytecode.numArgs;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#add(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $add(LeoObject other) {
if (other.isString()) {
return LeoString.valueOf(toString() + other.toString());
}
return super.$add(other);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#isFunction()
*/
@Override
public boolean isFunction() {
return true;
}
/**
* @return the bytecode
*/
public Bytecode getBytecode() {
return bytecode;
}
/**
* @return the numberOfArgs
*/
@Override
public int getNumberOfArgs() {
return numberOfArgs;
}
/**
* @return true if this function has variable arguments
*/
@Override
public boolean hasVarargs() {
return this.bytecode.hasVarargs();
}
@Override
public LeoObject call() {
return this.runtime.getActiveVM().execute(env, this, this.bytecode);
}
@Override
public LeoObject call(LeoObject arg1) {
VM vm = this.runtime.getActiveVM();
if(this.bytecode.hasVarargs()) {
switch(this.bytecode.getVarargIndex()) {
case 0: return vm.execute(env, this, this.bytecode, LeoArray.newLeoArray(arg1));
}
}
return vm.execute(env, this, this.bytecode, arg1);
}
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2) {
VM vm = this.runtime.getActiveVM();
if(this.bytecode.hasVarargs()) {
switch(this.bytecode.getVarargIndex()) {
case 0: return vm.execute(env, this, this.bytecode, LeoArray.newLeoArray(arg1, arg2));
case 1: return vm.execute(env, this, this.bytecode, arg1, LeoArray.newLeoArray(arg2));
}
}
return vm.execute(env, this, this.bytecode, arg1, arg2);
}
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2, LeoObject arg3) {
VM vm = this.runtime.getActiveVM();
if(this.bytecode.hasVarargs()) {
switch(this.bytecode.getVarargIndex()) {
case 0: return vm.execute(env, this, this.bytecode, LeoArray.newLeoArray(arg1, arg2, arg3));
case 1: return vm.execute(env, this, this.bytecode, arg1, LeoArray.newLeoArray(arg2, arg3));
case 2: return vm.execute(env, this, this.bytecode, arg1, arg2, LeoArray.newLeoArray(arg3));
}
}
return vm.execute(env, this, this.bytecode, arg1, arg2, arg3);
}
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2, LeoObject arg3, LeoObject arg4) {
VM vm = this.runtime.getActiveVM();
if(this.bytecode.hasVarargs()) {
switch(this.bytecode.getVarargIndex()) {
case 0: return vm.execute(env, this, this.bytecode, LeoArray.newLeoArray(arg1, arg2, arg3, arg4));
case 1: return vm.execute(env, this, this.bytecode, arg1, LeoArray.newLeoArray(arg2, arg3, arg4));
case 2: return vm.execute(env, this, this.bytecode, arg1, arg2, LeoArray.newLeoArray(arg3, arg4));
case 3: return vm.execute(env, this, this.bytecode, arg1, arg2, arg3, LeoArray.newLeoArray(arg4));
}
}
return vm.execute(env, this, this.bytecode, arg1, arg2, arg3, arg4);
}
@Override
public LeoObject call(LeoObject arg1, LeoObject arg2, LeoObject arg3, LeoObject arg4, LeoObject arg5) {
VM vm = this.runtime.getActiveVM();
if(this.bytecode.hasVarargs()) {
switch(this.bytecode.getVarargIndex()) {
case 0: return vm.execute(env, this, this.bytecode, LeoArray.newLeoArray(arg1, arg2, arg3, arg4, arg5));
case 1: return vm.execute(env, this, this.bytecode, arg1, LeoArray.newLeoArray(arg2, arg3, arg4, arg5));
case 2: return vm.execute(env, this, this.bytecode, arg1, arg2, LeoArray.newLeoArray(arg3, arg4, arg5));
case 3: return vm.execute(env, this, this.bytecode, arg1, arg2, arg3, LeoArray.newLeoArray(arg4, arg5));
case 4: return vm.execute(env, this, this.bytecode, arg1, arg2, arg3, arg4, LeoArray.newLeoArray(arg5));
}
}
return vm.execute(env, this, this.bytecode, arg1, arg2, arg3, arg4, arg5);
}
@Override
public LeoObject call(LeoObject[] args) {
VM vm = this.runtime.getActiveVM();
if(this.bytecode.hasVarargs()) {
int index = this.bytecode.getVarargIndex();
LeoArray varargs = LeoArray.newLeoArray( Arrays.copyOfRange(args, index, args.length) );
LeoObject[] newArgs = new LeoObject[index+1];
System.arraycopy(args, 0, newArgs, 0, index);
newArgs[index] = varargs;
return vm.execute(env, this, this.bytecode, newArgs);
}
return vm.execute(env, this, this.bytecode, args);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#eq(leola.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
boolean isEquals = (other == this);
if ( !isEquals && other != null ) {
if ( other.isOfType(LeoType.FUNCTION) ) {
LeoFunction function = other.as();
isEquals = function.getNumberOfArgs() == this.numberOfArgs;
}
}
return isEquals;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gt(leola.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lt(leola.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return this;
}
@Override
public void write(DataOutput out) throws IOException {
// out.write(this.getType().ordinal());
// this.bytecode.write(out);
// int nouters = this.outers!=null?this.outers.length:0;
// if (nouters>0) {
//// for(int i =0; i < nouters; i++) {
//// LeoObject o = this.outers[i];
//// if ( o == null ) {
//// nouters = i;
//// break;
//// }
//// }
//
// out.writeInt(nouters);
//
//// for(int i =0; i < nouters; i++) {
//// LeoObject o = this.outers[i];
//// o.write(out);
//// }
// }
// else {
// out.writeInt(nouters);
// }
}
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the {@link LeoObject}
* @throws IOException
*/
public static LeoFunction read(Leola runtime, LeoObject env, DataInput in) throws IOException {
Bytecode bytecode = Bytecode.read(env, in);
int nouters = in.readInt();
LeoObject[] outers = new LeoObject[nouters];
for(int i =0; i < nouters; i++) {
outers[i] = LeoObject.read(env, in);
}
LeoFunction function = new LeoFunction(runtime, env, bytecode);
return function;
}
}
<|start_filename|>src/leola/lang/sql/ParsedSql.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.lang.sql;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A Parsed SQL represents a named parameter query that is ready to be passed to JDBC.
*
* @author Tony
*
*/
public class ParsedSql {
/**
* The original SQL
*/
private String originalSql;
/**
* Named Parameters
*/
private Map<String, ParameterLocation> namedParams;
/**
* Named parameters
*/
private List<NamedParameter> parameters;
/**
* Parameter index
*/
private int numOfParams;
/**
* Last compiled parameter list
*/
private int lastNumOfParms;
/**
* JDBC SQL
*/
private StringBuilder jdbcSql;
/**
* @param originalSql
*/
public ParsedSql(String originalSql) {
this.originalSql = originalSql;
this.namedParams = new HashMap<String, ParameterLocation>();
this.parameters = new ArrayList<NamedParameter>();
this.numOfParams = 0;
this.lastNumOfParms = -1; /* Make sure we do our lazy jdbc build the first time */
}
/**
* @return a JDBC compliant SQL statement
*/
public StringBuilder toJdbcStatement() {
if (this.lastNumOfParms < this.numOfParams ) {
this.jdbcSql = new StringBuilder(this.originalSql);
int lastEndIndex = 0; /* The last index that was replaced */
/* Replace each parameter with a question mark */
for(NamedParameter param : this.parameters) {
this.jdbcSql.replace(param.getStartIndex() + lastEndIndex, param.getEndIndex() + lastEndIndex, "?");
lastEndIndex += (param.getStartIndex() - param.getEndIndex()) + 1 /* plus one for question mark length */;
}
this.lastNumOfParms = this.numOfParams;
}
return this.jdbcSql;
}
/**
* @return the originalSql
*/
public String getOriginalSql() {
return originalSql;
}
/**
* @return the namedParams
*/
public Map<String, ParameterLocation> getNamedParams() {
return namedParams;
}
/**
* @return the numOfParams
*/
public int getNumOfParams() {
return numOfParams;
}
/**
* Adds a {@link NamedParameter}.
*
* @param paramName
* @param startIndex
* @param endIndex
*/
public void addNamedParameter(String paramName, int startIndex, int endIndex) {
this.parameters.add(new NamedParameter(paramName, startIndex, endIndex));
/* Increment the number of params */
this.numOfParams++; /* Starts at 1 as in SQL param indexes do */
/* Place in index map */
if ( ! this.namedParams.containsKey(paramName)) {
this.namedParams.put(paramName, new ParameterLocation(paramName) );
}
ParameterLocation location = this.namedParams.get(paramName);
location.addParameterIndex(this.numOfParams);
location.addSqlCharPosition(startIndex);
}
/**
* @return the parameters
*/
public List<NamedParameter> getNamedParameters() {
return parameters;
}
}
<|start_filename|>src/leola/ast/VarDeclStmt.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.vm.EvalException;
/**
* @author Tony
*
*/
public class VarDeclStmt extends Stmt {
private String varName;
private Expr value;
/**
* @param varName
* @param value
*/
public VarDeclStmt(String varName, Expr value) {
this.varName = varName;
this.value = becomeParentOf(value);
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
/**
* @return the varName
*/
public String getVarName() {
return varName;
}
/**
* @return the value
*/
public Expr getValue() {
return value;
}
}
<|start_filename|>src/leola/ast/BinaryExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import leola.frontend.tokens.Token;
import leola.vm.EvalException;
/**
* A Binary expression.
*
* @author Tony
*
*/
public class BinaryExpr extends Expr {
/**
* Expressions
*/
private Expr left, right;
private Token op;
/**
* @param left
* @param right
*/
public BinaryExpr(Expr left, Expr right, Token op) {
this.left = becomeParentOf(left);
this.right = becomeParentOf(right);
this.op =op;
}
/**
* @return the left
*/
public Expr getLeft() {
return left;
}
/**
* @return the right
*/
public Expr getRight() {
return right;
}
/**
* @return the op
*/
public Token getOp() {
return op;
}
/* (non-Javadoc)
* @see leola.ast.ASTNode#visit(leola.ast.ASTNodeVisitor)
*/
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
}
<|start_filename|>src/leola/frontend/ParseException.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.frontend;
import leola.frontend.tokens.Token;
/**
* An exception during parsing
*
* @author Tony
*
*/
public class ParseException extends RuntimeException {
/**
* SUID
*/
private static final long serialVersionUID = 4773494052623080002L;
/**
* Error code
*/
private ErrorCode errorCode;
/**
* The token in which we errored on
*/
private Token token;
public ParseException(Token token) {
this(ErrorCode.UNKNOWN_ERROR, token);
}
/**
* @param errorCode
*/
public ParseException(ErrorCode errorCode, Token token) {
this.errorCode = errorCode;
this.token = token;
}
/**
* @param message
*/
public ParseException(ErrorCode errorCode, Token token, String message) {
super(message);
this.errorCode = errorCode;
this.token = token;
}
/**
* @param cause
*/
public ParseException(ErrorCode errorCode, Token token, Throwable cause) {
super(cause);
this.errorCode = errorCode;
this.token = token;
}
/**
* @param message
* @param cause
*/
public ParseException(ErrorCode errorCode, Token token, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
this.token = token;
}
/**
* @param message
*/
public ParseException(Token token, String message) {
this(ErrorCode.UNKNOWN_ERROR, token, message);
}
/**
* @param cause
*/
public ParseException(Token token, Throwable cause) {
this(ErrorCode.UNKNOWN_ERROR, token, cause);
}
/**
* @param message
* @param cause
*/
public ParseException(Token token, String message, Throwable cause) {
this(ErrorCode.UNKNOWN_ERROR, token, message, cause);
}
/**
* @return the errorCode
*/
public ErrorCode getErrorCode() {
return errorCode;
}
/**
* @return the current token which the {@link ParseException} occurred
*/
public Token getToken() {
return token;
}
}
<|start_filename|>src/leola/vm/types/LeoString.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.types;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaMethod;
import leola.vm.util.ClassUtil;
/**
* A Leola String. For the most part all String operations return a new {@link LeoString} instance, leaving the {@link LeoString}
* more or less immutable. The one exception is the indexing into the string itself:
*
* <pre>
* var aString = "Hello"
* aString[2] = "X"
* println(aString) // HeXllo ; the indexing does an insert
* </pre>
*
* <p>
* This might change in the future, I'm a bit undecided if this is a desirable feature -- furthermore this probably can cause
* issues with the {@link LeoString} interning (due to the original string referencing the LeoString, which if altered would no
* longer match).
*
* @author Tony
*
*/
public class LeoString extends LeoObject {
private static final Map<String, WeakReference<LeoString>> interns = new ConcurrentHashMap<String, WeakReference<LeoString>>();
private static LeoString getString(String ref) {
WeakReference<LeoString> str = interns.get(ref);
return str != null ? str.get() : null;
}
private static LeoString putString(String ref) {
LeoString lStr = new LeoString(ref);
interns.put(ref, new WeakReference<LeoString>(lStr));
return lStr;
}
/**
* Value
*/
private String value;
/**
* @param value
*/
public LeoString(String value) {
this(new StringBuilder(value));
}
/**
* @param value
*/
public LeoString(StringBuilder value) {
super(LeoType.STRING);
this.value = value==null ? "" : value.toString();
}
/**
* Interns the {@link LeoString}.
*
* @param str
* @return
*/
public static LeoString valueOf(String str) {
LeoString lStr = getString(str);
return lStr != null ? lStr : putString(str);
}
/**
*/
public LeoString() {
this(new StringBuilder());
}
/**
* Adds ability to reference the public API of this class
*/
private Map<LeoObject, LeoObject> stringApi;
private Map<LeoObject, LeoObject> getApiMappings() {
if(this.stringApi == null) {
synchronized (this) {
if(this.stringApi == null) {
this.stringApi = new LeoMap();
}
}
}
return this.stringApi;
}
private LeoObject getNativeMethod(LeoObject key) {
return getNativeMethod(this, getApiMappings(), key);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#toLeoString()
*/
@Override
public LeoString toLeoString() {
return this;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#isString()
*/
@Override
public boolean isString() {
return true;
}
@Override
public boolean isAccessible() {
return true;
}
/**
* @return the value
*/
public String getString() {
return value.toString();
}
/* (non-Javadoc)
* @see leola.types.LeoObject#toString()
*/
@Override
public String toString() {
return this.value;
}
/**
* Maps the supplied function to each element in the string.
*
* <pre>
* var result = "hi".map(def(e) return e+"2")
* println(result) // h2i2
* </pre>
*
* @param function
* @return the new mapped {@link LeoString}
*/
public LeoString map(LeoObject function) {
StringBuilder sb = new StringBuilder(length());
int len = length();
for(int i = 0; i < len; i++) {
LeoObject result = function.xcall(charAt(i));
sb.append(result.toString());
}
return LeoString.valueOf(sb.toString());
}
/**
* Returns a sequence consisting of those items from the sequence for which function(item) is true
*
* @param function
* @return the new String
*/
public LeoString filter(LeoObject function) {
StringBuilder sb = new StringBuilder(this.value);
int len = this.value.length();
for(int i = 0; i < len; i++) {
char c = this.value.charAt(i);
LeoString ch = LeoString.valueOf( String.valueOf(c));
if ( LeoObject.isTrue(function.xcall(ch)) ) {
sb.append(c);
}
}
return LeoString.valueOf(sb.toString());
}
/**
* Iterates through the string, invoking the supplied
* function object for each element. The start and end index are [start, end).
*
* <pre>
* "hi".for(0, 1, def(c) println(c))
* // prints:
* // h
*
* </pre>
*
* @param start starting index (inclusive)
* @param end ending index (exclusive)
* @param function
*/
@LeolaMethod(alias="for")
public void _for(int start, int end, LeoObject function) {
int len = length();
for(int i = start; i < len && i < end; i++) {
LeoObject result = function.xcall(charAt(i));
if(LeoObject.isTrue(result)) {
break;
}
}
}
/**
* Iterates through the array, invoking the supplied
* function object for each element
*
* <pre>
* "hi".foreach(def(c) println(c))
* // prints:
* // h
* // i
*
* </pre>
*
* @param function
* @return the {@link LeoObject} returned from the supplied function if returned <code>true</code>
*/
public LeoObject foreach(LeoObject function) {
int len = length();
for(int i = 0; i < len; i++) {
LeoObject result = function.xcall(charAt(i));
if ( LeoObject.isTrue(result) ) {
return result;
}
}
return LeoObject.NULL;
}
/**
* Combines the list of arguments (separating them by the supplied delimiter) and appending them
* to this string.
*
* @param delimiter
* @param args
* @return the joined string
*/
public LeoString join(String delimiter, Object ... args) {
StringBuilder sb = new StringBuilder(this.value);
for(int i = 0; i < args.length; i++) {
sb.append(args[i]);
}
return LeoString.valueOf(sb.toString());
}
/**
* Formats the current string according to {@link String#format(String, Object...)}.
* @param args
* @return the formatted string
*/
public LeoString format(Object ...args) {
return LeoString.valueOf(String.format(this.value, args));
}
/**
* @return a new instance in lower case
*/
public LeoString toLower() {
return LeoString.valueOf(this.value.toLowerCase());
}
/**
* @return a new instance in upper case
*/
public LeoString toUpper() {
return LeoString.valueOf(this.value.toUpperCase());
}
@Override
public LeoObject $add(LeoObject other) {
return append(other);
}
@Override
public LeoObject $add(double other) {
return LeoString.valueOf(other + this.value);
}
@Override
public LeoObject $add(int other) {
return LeoString.valueOf(other + this.value);
}
@Override
public LeoObject $add(long other) {
return LeoString.valueOf(other + this.value);
}
@Override
public LeoObject $sub(LeoObject other) {
return replaceAll(other, LeoObject.valueOf(""));
}
@Override
public LeoObject $index(double other) {
return charAt( (int) other);
}
@Override
public LeoObject $index(int other) {
return charAt(other);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(long)
*/
@Override
public LeoObject $index(long other) {
return charAt( (int)other );
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(leola.vm.types.LeoObject)
*/
@Override
public LeoObject $index(LeoObject other) {
return charAt(other.asInt());
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#$index(leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public void $sindex(LeoObject key, LeoObject other) {
if(key.isNumber()) {
int index = key.asInt();
StringBuilder sb = new StringBuilder(this.value);
sb.insert(index, other.toString());
this.value = sb.toString();
}
else {
String regex = key.toString();
this.value = this.value.replaceAll(regex, other.toString());
}
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#setObject(leola.vm.types.LeoObject, leola.vm.types.LeoObject)
*/
@Override
public void setObject(LeoObject key, LeoObject value) {
this.getApiMappings().put(key, value);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getObject(leola.vm.types.LeoObject)
*/
@Override
public LeoObject xgetObject(LeoObject key) {
return getNativeMethod(key);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getObject(leola.vm.types.LeoObject)
*/
@Override
public LeoObject getObject(LeoObject key) {
if(hasNativeMethod(this, key)) {
return getNativeMethod(key);
}
return LeoObject.NULL;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#hasObject(leola.vm.types.LeoObject)
*/
@Override
public boolean hasObject(LeoObject key) {
return hasNativeMethod(this, key);
}
/**
* Appends to this string.
*
* @param v
* @return
*/
public LeoString append(LeoObject v) {
//this.value.append(v.toString());
return LeoString.valueOf(this.value + v.toString());
}
/**
* inserts a string into the supplied position.
* @param position
* @param v
* @return this string
*/
public LeoString insert(int position, LeoObject v) {
// this.value.insert(position, v.toString());
StringBuilder sb = new StringBuilder(this.value);
sb.insert(position, v.toString());
return LeoString.valueOf(sb.toString());
}
/**
* Determines if this string contains the supplied string (v)
*
* @param v
* @return true if this string contains the supplied string (v)
*/
public boolean contains(LeoObject v) {
return this.value.indexOf(v.toString()) > -1;
}
/**
* The index of the supplied string
* @param v
* @return -1 if the supplied string is not in this string.
*/
public int indexOf(LeoObject v) {
return this.value.indexOf(v.toString());
}
/**
* The rest of the string from position i.
* @param i
* @return
*/
public LeoString rest(int i) {
return new LeoString(this.value.substring(i));
}
/**
* Gets the substring.
*
* @param start
* @param end
* @return
*/
public LeoString substring(int start, int end) {
return new LeoString(this.value.substring(start, end));
}
/**
* Replaces a portion of the string.
*
* @param start
* @param end
* @param v
* @return
*/
public LeoString replace(int start, int end, LeoObject v) {
//this.value.replace(start, end, v.toString());
StringBuilder sb = new StringBuilder(this.value);
sb.replace(start, end, v.toString());
return LeoString.valueOf(sb.toString());
}
/**
* Replaces all occurrences of the supplied string.
*
* @param replaceMe
* @param v
* @return
*/
public LeoString replaceAll(LeoObject replaceMe, LeoObject v) {
return LeoString.valueOf(this.value.replaceAll(replaceMe.toString(), v.toString()));
// String source = replaceMe.toString();
// String replacementString = v.toString();
//
// int sourceLength = source.length();
// int targetLength = replacementString.length();
//
// int index = this.value.indexOf(source);
// while (index != -1) {
// int startIndex = index;
// int endIndex = index + sourceLength;
//
// this.value.replace(startIndex, endIndex, replacementString);
// index += targetLength; // Move to the end of the replacement
// index = this.value.indexOf(source, index);
// }
// return this;
}
/**
* Splits the string by the regex
*
* @param v
* @return a {@link LeoArray}
*/
public LeoArray split(LeoObject v) {
String[] res = this.value.toString().split(v.toString());
LeoArray result = new LeoArray(res.length);
for(int i = 0; i < res.length; i++) {
result.add(LeoString.valueOf(res[i]));
}
return result;
}
public boolean endsWith(LeoObject v) {
String suffix = v.toString();
return startsWith(suffix, length() - suffix.length());
}
public boolean startsWith(LeoObject v) {
return startsWith(v.toString(), 0);
}
public boolean startsWith(String prefix, int toffset) {
int to = toffset;
int po = 0;
int pc = prefix.length();
// Note: toffset might be near -1>>>1.
if ((toffset < 0) || (toffset > this.value.length() - pc)) {
return false;
}
while (--pc >= 0) {
if (this.value.charAt(to++) != prefix.charAt(po++) ) {
return false;
}
}
return true;
}
/**
* Retrieves all of the indexes where 'v' is found in this string.
* @param v
* @return list of all indexes where 'v' is found in this string.
*/
public LeoArray indexesOf(LeoObject v) {
LeoArray results = new LeoArray();
String str = v.toString();
int index = 0;
int result = 0;
while (result > -1) {
result = this.value.indexOf(str, index);
if(result > -1) {
results.add(LeoInteger.valueOf(result));
index = result + 1;
}
}
return results;
}
/**
* @return removes any leading or trailing whitespace characters
*/
public LeoString trim() {
return LeoString.valueOf(this.value.trim());
}
/**
* @return the length of the string
*/
public int length() {
return (this.value != null ) ? this.value.length() : 0;
}
/**
* @return true if the string is "" or NULL
*/
public boolean empty() {
return length() == 0;
}
/**
* @param n
* @return the character at this position
*/
public LeoString charAt(int n) {
return LeoString.valueOf(String.valueOf( this.value.charAt(n) ));
}
/**
* @param n
* @return the integer value of the character at a location
*/
public int byteAt(int n) {
return this.value.charAt(n);
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#hashCode()
*/
@Override
public int hashCode() {
return (this.value != null) ? this.value.hashCode() : super.hashCode();
}
/* (non-Javadoc)
* @see leola.types.LeoObject#eq(leola.types.LeoObject)
*/
@Override
public boolean $eq(LeoObject other) {
boolean result = false;
if ( (other != null ) && other.isString() ) {
String a = this.value;
String b = other.toString();
if ( a != null ) {
result = a.equals(b);
}
else {
result = (b==null);
}
}
return result;
}
/**
* Compares two {@link StringBuilder}s
* @param l
* @param anotherString
* @return
*/
private int compareTo(String l, String anotherString) {
int len1 = l.length();
int len2 = anotherString.length();
int n = Math.min(len1, len2);
int i = 0;
int j = 0;
while (n-- != 0) {
char c1 = l.charAt(i++);
char c2 = anotherString.charAt(j++);
if (c1 != c2) {
return c1 - c2;
}
}
return len1 - len2;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gt(leola.types.LeoObject)
*/
@Override
public boolean $gt(LeoObject other) {
if ( other != null && other.isOfType(LeoType.STRING)) {
LeoString str = other.as();
int c = compareTo(this.value, str.value);
return c > 0;
}
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#gte(leola.types.LeoObject)
*/
@Override
public boolean $gte(LeoObject other) {
if ( other != null && other.isOfType(LeoType.STRING)) {
LeoString str = other.as();
int c = compareTo(this.value, str.value);
return c >= 0;
}
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lt(leola.types.LeoObject)
*/
@Override
public boolean $lt(LeoObject other) {
if ( other != null && other.isOfType(LeoType.STRING)) {
LeoString str = other.as();
int c = compareTo(this.value, str.value);
return c < 0;
}
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#lte(leola.types.LeoObject)
*/
@Override
public boolean $lte(LeoObject other) {
if ( other != null && other.isOfType(LeoType.STRING)) {
LeoString str = other.as();
int c = compareTo(this.value, str.value);
return c <= 0;
}
return false;
}
/* (non-Javadoc)
* @see leola.types.LeoObject#getValue()
*/
@Override
public Object getValue() {
return this.value;
}
private void checkSizeForConversion() {
if ( this.value.length() > 1) {
throw new LeolaRuntimeException
("StringCharError: The supplied LeoString: '" + this.value + "' is larger than 1 character and therefore does not match the native type: char");
}
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#getValue(java.lang.Class)
*/
@Override
public Object getValue(Class<?> type) {
Object resultJavaObj = this.value;
if(ClassUtil.inheritsFrom(type, LeoObject.class) ) {
resultJavaObj = this;
}
else if(ClassUtil.isType(type, ClassUtil.CHAR) ) {
checkSizeForConversion();
resultJavaObj = this.value.charAt(0);
} else if(ClassUtil.isType(type, ClassUtil.BYTE) ) {
checkSizeForConversion();
resultJavaObj = (byte)this.value.charAt(0);
} else if(ClassUtil.isType(type, ClassUtil.SHORT) ) {
checkSizeForConversion();
resultJavaObj = (short)this.value.charAt(0);
} else if(ClassUtil.isType(type, ClassUtil.INT) ) {
checkSizeForConversion();
resultJavaObj = (int)this.value.charAt(0);
} else if(ClassUtil.isType(type, ClassUtil.LONG) ) {
checkSizeForConversion();
resultJavaObj = (long)this.value.charAt(0);
} else if(ClassUtil.isType(type, ClassUtil.FLOAT) ) {
checkSizeForConversion();
resultJavaObj = (float)this.value.charAt(0);
} else if(ClassUtil.isType(type, ClassUtil.DOUBLE) ) {
checkSizeForConversion();
resultJavaObj = (double)this.value.charAt(0);
}
return resultJavaObj;
}
@Override
public boolean isAssignable(Class<?> javaType) {
return String.class.isAssignableFrom(javaType);
}
/* (non-Javadoc)
* @see leola.types.LeoObject#clone()
*/
@Override
public LeoObject clone() {
return this;
}
/* (non-Javadoc)
* @see leola.vm.types.LeoObject#write(java.io.DataOutput)
*/
@Override
public void write(DataOutput out) throws IOException {
out.write(this.getType().ordinal());
out.writeInt(this.value.length());
out.writeBytes(this.value);
}
/**
* Reads from the {@link DataInput} stream, constructing a {@link LeoObject}
*
* @param in
* @return the {@link LeoObject}
* @throws IOException
*/
public static LeoString read(DataInput in) throws IOException {
String str = "";
int length = in.readInt();
if ( length > 0 ) {
byte[] buf = new byte[length];
in.readFully(buf);
str = new String(buf);
}
return LeoString.valueOf(str);
}
}
<|start_filename|>src/leola/frontend/tokens/WordToken.java<|end_filename|>
package leola.frontend.tokens;
import static leola.frontend.tokens.TokenType.IDENTIFIER;
import static leola.frontend.tokens.TokenType.RESERVED_WORDS;
import leola.frontend.Source;
/**
* Word/Identifier token
*
* @author Tony
*
*/
public class WordToken extends Token {
/**
* Determines if the supplied character is valid inside the identifier
* @param c
* @return true if valid identifier character
*/
public static final boolean isValidIdentifierCharacter(char c) {
boolean isValid = Character.isLetterOrDigit(c);
if ( !isValid ) {
switch(c) {
case '$':
case '@':
case '_':
isValid = true;
break;
}
}
return isValid;
}
/**
* Determines if the supplied character is a valid start character for an identifier
*
* @param c
* @return true if valid
*/
public static final boolean isValidStartIdentifierCharacter(char c) {
boolean isValid = Character.isLetter(c);
if ( !isValid ) {
switch(c) {
case '$':
//case '@':
case '_':
isValid = true;
break;
}
}
return isValid;
}
/**
* @param source the source from where to fetch the token's characters.
*/
public WordToken(Source source) {
super(source);
}
/**
* Extract a Leola word token from the source.
*/
@Override
protected void extract() {
StringBuilder textBuffer = new StringBuilder();
char currentChar = currentChar();
// Get the word characters (letter or digit). The scanner has
// already determined that the first character is a letter.
while (isValidIdentifierCharacter(currentChar)) {
textBuffer.append(currentChar);
currentChar = nextChar(); // consume character
}
text = textBuffer.toString();
// Is it a reserved word or an identifier?
type = (RESERVED_WORDS.contains(text))
? TokenType.valueOf(text.toUpperCase()) // reserved word
: IDENTIFIER; // identifier
}
}
<|start_filename|>src/leola/vm/util/Pair.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.util;
/**
* Simple way to group two values together.
*
* @author Tony
*
*/
public class Pair<X, Y> {
/**
* Get the first item
*/
private X first;
/**
* Get the second item
*/
private Y second;
/**
*
* @param first
* @param second
*/
public Pair(X first, Y second) {
this.first=first;
this.second=second;
}
/**
*/
public Pair() {
}
/**
* @param first the first to set
*/
public void setFirst(X first) {
this.first = first;
}
/**
* @return the first
*/
public X getFirst() {
return first;
}
/**
* @param second the second to set
*/
public void setSecond(Y second) {
this.second = second;
}
/**
* @return the second
*/
public Y getSecond() {
return second;
}
}
<|start_filename|>src/leola/vm/exceptions/LeolaRuntimeException.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.exceptions;
import leola.vm.types.LeoError;
import leola.vm.types.LeoObject;
/**
* An evaluation exception, means that a bit of code was not able to be executed as intended.
*
* @author Tony
*
*/
public class LeolaRuntimeException extends RuntimeException {
/**
* SUID
*/
private static final long serialVersionUID = 159371812953160598L;
private LeoError leoError;
/**
*
*/
public LeolaRuntimeException() {
this(new LeoError());
}
/**
* @param error
*/
public LeolaRuntimeException(LeoObject error) {
if(error==null) {
error = new LeoError();
}
else if (!error.isError()) {
error = new LeoError(error);
}
this.leoError = error.as();
}
/**
* @param message
*/
public LeolaRuntimeException(String message) {
super(message);
this.leoError = new LeoError(message);
}
/**
* @param cause
*/
public LeolaRuntimeException(Throwable cause) {
super(cause);
this.leoError = new LeoError(cause.getMessage());
}
/**
* @param message
* @param cause
*/
public LeolaRuntimeException(String message, Throwable cause) {
super(message, cause);
this.leoError = new LeoError(message);
}
/* (non-Javadoc)
* @see java.lang.Throwable#getMessage()
*/
@Override
public String getMessage() {
return this.leoError.toString();
}
/**
* @return the leoError
*/
public LeoError getLeoError() {
return leoError;
}
}
<|start_filename|>src/leola/vm/util/ClassUtil.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaMethod;
import leola.vm.lib.LeolaMethodVarargs;
import leola.vm.types.LeoNativeClass;
import leola.vm.types.LeoNull;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
/**
* Simple utility class for reflection operations
*
* @author Tony
*
*/
public class ClassUtil {
public static final Class<?>[] STRING = { String.class, char.class, Character.class };
public static final Class<?>[] BOOLEAN = { boolean.class, Boolean.class };
public static final Class<?>[] BYTE = { byte.class, Byte.class };
public static final Class<?>[] CHAR = { char.class, Character.class };
public static final Class<?>[] SHORT = { short.class, Short.class };
public static final Class<?>[] INT = { int.class, Integer.class };
public static final Class<?>[] LONG = { long.class, Long.class };
public static final Class<?>[] FLOAT = { float.class, Float.class };
public static final Class<?>[] DOUBLE = { double.class, Double.class };
public static final Class<?>[] INTEGER =
{ byte.class, Byte.class
, short.class, Short.class
, int.class, Integer.class
// , float.class, Float.class
// , double.class, Double.class
// , long.class, Long.class
// , Number.class
};
public static final Class<?>[] NUMBER =
{ byte.class, Byte.class
, short.class, Short.class
, int.class, Integer.class
, float.class, Float.class
, double.class, Double.class
, long.class, Long.class
, Number.class };
/**
* Re-throws the supplied exception as a {@link LeolaRuntimeException}. This will
* first check to see if the supplied exception is a {@link LeolaRuntimeException}, in which
* case it will cast a throw.
*
* @param e
* @throws LeolaRuntimeException
*/
private static void rethrow(Exception e) throws LeolaRuntimeException {
Throwable cause = e.getCause();
/* There are cases where 'cause' is null, which
* is pretty lame
*/
if(cause != null) {
if( cause instanceof LeolaRuntimeException) {
throw (LeolaRuntimeException)cause;
}
throw new LeolaRuntimeException(e.getCause());
}
else {
if(e instanceof LeolaRuntimeException) {
throw (LeolaRuntimeException)e;
}
throw new LeolaRuntimeException(e);
}
}
/**
* Return instructions for the {@link MethodIterator}
*
* @author Tony
*
*/
private static enum ReturnType {
STOP_METHOD_LOOP,
STOP_HIERARCHY_LOOP,
DONT_STOP
;
}
/**
* Iterate through {@link Method} callback.
*
* @author Tony
*
*/
private static interface MethodIterator {
public ReturnType call(Method method) throws LeolaRuntimeException;
}
/**
* Iterates over a class hierarchy invoking the supplied callback function.
*
* @param aClass the class to iterate over
* @param it the callback function. If the {@link MethodIterator} returns <code>true</code>, then the
* iteration stops.
*/
private static void iterateOverHierarchy(Class<?> aClass, MethodIterator it) {
try {
ReturnType returnType = ReturnType.DONT_STOP;
for (Class<?> i = aClass; i != null && i != Object.class; i = i.getSuperclass()) {
for (Method method : i.getDeclaredMethods()) {
/* Only grab public and non-ignored methods */
if ((method.getModifiers() & Modifier.PUBLIC) > 0 &&
!method.isAnnotationPresent(LeolaIgnore.class)) {
returnType = it.call(method);
if(returnType==ReturnType.STOP_METHOD_LOOP) {
break;
}
}
}
if(returnType.equals(ReturnType.STOP_HIERARCHY_LOOP)) {
break;
}
}
}
catch (Exception e) {
}
}
/**
* Retrieves a method by name (grabs the first if overloaded).
*
* @param methodName
* @return the method if found, otherwise null
*/
public static Method getMethodByName(Class<?> aClass, String methodName, Class<?> ... params) {
Method result = null;
try {
result = aClass.getMethod(methodName, params);
}
catch(Exception e) {
}
return (result);
}
/**
* Retrieves all the overloaded methods by the supplied name
*
* @param aClass
* @param methodName
* @return all methods by the given name.
*/
public static List<Method> getMethodsByName(final Class<?> aClass, final String methodName) {
final List<Method> methods = new ArrayList<Method>();
iterateOverHierarchy(aClass, new MethodIterator() {
@Override
public ReturnType call(Method method) {
if(method.getName().equals(methodName)) {
methods.add(method);
}
return methods.isEmpty() ? ReturnType.DONT_STOP :
ReturnType.STOP_HIERARCHY_LOOP;
}
});
return methods;
}
/**
* Retrieves the method names in which have the {@link LeolaMethod} annotation with the {@link LeolaMethod#alias()} of
* the supplied 'methodName'
*
* @param aClass
* @param methodName
* @return all methods that have a {@link LeolaMethod} annotation with the matching alias name
*/
public static List<Method> getMethodsByAnnotationAlias(final Class<?> aClass, final String methodName) {
final List<Method> methods = new ArrayList<Method>();
iterateOverHierarchy(aClass, new MethodIterator() {
@Override
public ReturnType call(Method method) {
if ( method.isAnnotationPresent(LeolaMethod.class) ) {
LeolaMethod methodAlias = method.getAnnotation(LeolaMethod.class);
if(methodAlias.alias().equals(methodName)) {
methods.add(method);
}
}
return methods.isEmpty() ? ReturnType.DONT_STOP :
ReturnType.STOP_HIERARCHY_LOOP;
}
});
return methods;
}
/**
* Retrieves a {@link Method} by looking at the {@link LeolaMethod} annotation's {@link LeolaMethod#alias()}
* value.
*
* @param aClass
* @param methodName
* @return the {@link Method} if found, otherwise <code>null</code>
*/
public static Method getMethodByAnnotationAlias(final Class<?> aClass, final String methodName) {
final AtomicReference<Method> methodRef = new AtomicReference<Method>();
iterateOverHierarchy(aClass, new MethodIterator() {
@Override
public ReturnType call(Method method) {
if ( method.isAnnotationPresent(LeolaMethod.class) ) {
LeolaMethod methodAlias = method.getAnnotation(LeolaMethod.class);
if(methodAlias.alias().equals(methodName)) {
methodRef.set(method);
return ReturnType.STOP_HIERARCHY_LOOP;
}
}
return ReturnType.DONT_STOP;
}
});
return methodRef.get();
}
/**
* Attempts to find the best matching overloaded {@link Method}. If one is found, it executes the
* {@link Method}.
*
* @param overloads
* @param instance
* @param args
* @return the resulting Java object from the method execution.
*/
public static Object invokeMethod(List<Method> overloads, Object instance, LeoObject[] args) {
Method bestMatch = null;
int bestScore = Integer.MIN_VALUE;
/* The common case is one method, so
* let's optimize for it
*/
if(overloads.size() == 1) {
bestMatch = overloads.get(0);
}
else {
/* Look for the best possible score. The score
* is calculated by the following logic:
*
* 1) give a + for parameters that match in type
* 2) give a - for parameters that do not match in type
* 3) give a smaller negative for missing arguments
*/
for(int i = 0; i < overloads.size(); i++) {
Method method = overloads.get(i);
Class<?>[] types = method.getParameterTypes();
if(args!=null) {
int currentScore = 0;
for(int j = 0; j < types.length; j++) {
if(j>=args.length) {
currentScore--; // Nulls will be assumed for missing parameters
}
else {
/* Determine if the supplied argument type is assignable
* to the expected type
*/
if(args[j].isAssignable(types[j]) || types[j].equals(Object.class)) {
currentScore+=3;
}
else {
currentScore-=5;
}
}
}
if(bestScore < currentScore) {
bestScore = currentScore;
bestMatch = method;
}
}
else {
/* If no arguments were passed in, the Java method
* with the highest score should be the one with the
* least amount of parameters
*/
if(bestScore < 0 || types.length < bestScore) {
bestScore = types.length;
bestMatch = method;
}
}
}
}
Object result = invokeMethod(bestMatch, instance, args);
return result;
}
/**
* Invokes the supplied method.
*
* @param method the method to be executed
* @param owner the instance owner of the method
* @param params the parameters to be used
* @return the result of executing the method
* @throws LeolaRuntimeException
*/
public static Object invokeMethod(Method method, Object owner, LeoObject[] params) throws LeolaRuntimeException {
Object result = null;
try {
method.setAccessible(true);
result = tryMethod(owner, method, params);
}
catch (InvocationTargetException e) {
rethrow(e);
}
catch (Exception e) {
LeoObject.throwNativeMethodError("Error executing Java method '" + method.getName() + "'");
}
return result;
}
/**
* Invokes a method reflectively.
*
* @param method the method to be executed
* @param owner the instance owner of the method
* @param params the parameters to be used
* @return the result of executing the method
* @throws LeolaRuntimeException
*/
public static Object invokeMethod(Method method, Object owner, Object[] params) throws LeolaRuntimeException {
Object result = null;
try {
method.setAccessible(true);
result = method.invoke(owner, params);
}
catch(Exception e) {
/* This was a legitimate method invocation, so
* lets bomb out
*/
rethrow(e);
}
return result;
}
/**
* Attempts to invoke the supplied method.
*
* @param owner the instance owner of the method (may be null)
* @param method the method to be executed
* @param params the method parameters
* @return the result of the method execution
*/
private static Object tryMethod(Object owner, Method method, LeoObject[] params)
throws InvocationTargetException, Exception {
Class<?>[] paramTypes = method.getParameterTypes();
Object[] args = new Object[paramTypes.length];
Object varargs = null;
Class<?> arrayType = null;
int startOfVarargs = -1;
boolean hasVarArgs = false;
/* Determine if this Java method has variable arguments;
* if it does, we need to do some special handling of the arguments
* (convert the parameters into an array)
*/
if (method.isAnnotationPresent(LeolaMethodVarargs.class) || method.isVarArgs()) {
startOfVarargs = paramTypes.length - 1;
hasVarArgs = true;
if (startOfVarargs < params.length && startOfVarargs < paramTypes.length) {
arrayType = paramTypes[startOfVarargs].getComponentType();
int varargSize = params.length - startOfVarargs;
varargs = Array.newInstance(arrayType, varargSize);
args[startOfVarargs] = varargs;
}
}
/* We attempt to convert the supplied LeoObject parameters to
* Java parameters.
*/
for(int i = 0; i < paramTypes.length; i++ ) {
/* If we have variable arguments, ensure we convert the
* array elements too
*/
if(hasVarArgs && i>=startOfVarargs && params!=null) {
int varargsIndex = 0;
for(int paramIndex = startOfVarargs; paramIndex < params.length; paramIndex++) {
Object javaArg = LeoObject.toJavaObject(arrayType, params[paramIndex]);
Array.set(varargs, varargsIndex++, javaArg);
}
break;
}
else {
/* Attempt to coerce the the LeoObject parameter
* into the appropriate Java object parameter
*/
Class<?> aCl = paramTypes[i];
/* Leola allows for missing arguments, so
* if it is missing, just use null
*/
LeoObject arg = LeoNull.LEONULL;
if (params != null && i < params.length ) {
arg = params[i];
}
Object javaArg = LeoObject.toJavaObject(aCl, arg);
args[i] = javaArg;
}
}
Object result = method.invoke(owner, args);
return (result);
}
/**
* Sets the Field to the supplied value
*
* @param instance
* @param field
* @param value
*/
public static void setFieldValue(Object instance, Field field, Object value) {
try {
field.setAccessible(true);
field.set(instance, value);
}
catch (IllegalArgumentException | IllegalAccessException e) {
LeoObject.throwAttributeAccessError(instance.getClass(), LeoString.valueOf(field.getName()));
}
}
/**
* Retrieve a data members value.
*
* @param instance the instance of a class
* @param fieldName the data member name, in which to retrieve its value
* @return the value of the field.
*/
public static Object getFieldValue(Object instance, String fieldName) {
Class<?> aClass = instance.getClass();
Object result = null;
try {
Field field = aClass.getField(fieldName);
result = field.get(instance);
} catch(NoSuchFieldException e) {
LeoObject.throwAttributeError(aClass, LeoString.valueOf(fieldName));
} catch (Exception e) {
LeoObject.throwAttributeAccessError(aClass, LeoString.valueOf(fieldName));
}
return result;
}
/**
* Retrieve a class members value.
*
* @param aClass the class in which to retrieve a field
* @param fieldName the class member name, in which to retrieve its value
* @return the value of the field.
*/
public static Object getStaticFieldValue(Class<?> aClass, String fieldName) {
Object result = null;
try {
Field field = aClass.getField(fieldName);
result = field.get(null);
} catch(NoSuchFieldException e) {
LeoObject.throwAttributeError(aClass, LeoString.valueOf(fieldName));
} catch (Exception e) {
LeoObject.throwAttributeAccessError(aClass, LeoString.valueOf(fieldName));
}
return result;
}
/**
* Determines if the supplied class name is a native class.
*
* @param className the fully qualified Java class name
* @return true if the supplied class name is a valid Java class; false otherwise
*/
public static boolean isNativeClass(String className) {
boolean result = false;
try {
Class.forName(className);
result = true;
}
catch(Throwable e) {}
return result;
}
private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<>();
static {
primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
primitiveWrapperMap.put(Byte.TYPE, Byte.class);
primitiveWrapperMap.put(Character.TYPE, Character.class);
primitiveWrapperMap.put(Short.TYPE, Short.class);
primitiveWrapperMap.put(Integer.TYPE, Integer.class);
primitiveWrapperMap.put(Long.TYPE, Long.class);
primitiveWrapperMap.put(Double.TYPE, Double.class);
primitiveWrapperMap.put(Float.TYPE, Float.class);
primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
}
/**
* Maps wrapper <code>Class</code>es to their corresponding primitive types.
*/
private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<>();
static {
for (Iterator<Class<?>> it = primitiveWrapperMap.keySet().iterator(); it.hasNext();) {
Class<?> primitiveClass = it.next();
Class<?> wrapperClass = primitiveWrapperMap.get(primitiveClass);
if (!primitiveClass.equals(wrapperClass)) {
wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
}
}
}
public static Class<?> primitiveToWrapper(Class<?> cls) {
Class<?> convertedClass = cls;
if (cls != null && cls.isPrimitive()) {
convertedClass = primitiveWrapperMap.get(cls);
}
return convertedClass;
}
public static Class<?> wrapperToPrimitive(Class<?> cls) {
return wrapperPrimitiveMap.get(cls);
}
/**
* Determines if the supplied {@link Class} if of any of the supplied {@link Class} types.
*
* @param type the type to check
* @param classes the classes to compare type against
* @return true if type is any of the supplied classes; false otherwise
*/
public static boolean isType(Class<?> type, Class<?> ...classes ) {
boolean result = false;
for(Class<?> c: classes) {
result = result || type.equals(c);
if ( result ) {
break;
}
}
return result;
}
/**
* Determines if the supplied child class inherits from the supplied parent class.
*
* @param child
* @param parent
* @return true if child inherits from parent, false otherwise
*/
public static boolean inheritsFrom(Class<?> child, Class<?> parent) {
for (Class<?> i = child; i != null && i != Object.class; i = i.getSuperclass()) {
if (i.equals(parent)) {
return true;
}
}
return false;
}
/**
* Determines if the supplied testMe class implements the supplied interface.
*
* @param testMe
* @param aInterface
* @return true if the testMe class implements aInterface, false otherwise.
*/
public static boolean doesImplement(Class<?> testMe, Class<?> aInterface) {
for(Class<?> inter : testMe.getInterfaces()) {
if ( inter.equals(aInterface) ) {
return true;
}
}
return false;
}
/**
* Retrieves all of the methods defined in the supplied {@link Class}. This will navigate up the class
* hierarchy up until the Object class is reached.
*
* <p>
* This will not grab any methods annotated with {@link LeolaIgnore}.
*
* @param aClass the class to grab all the public methods from.
* @return the {@link List} of public {@link Method}s.
*/
public static List<Method> getAllDeclaredMethods(Class<?> aClass) {
final List<Method> methods = new ArrayList<Method>();
iterateOverHierarchy(aClass, new MethodIterator() {
@Override
public ReturnType call(Method method) {
methods.add(method);
return ReturnType.DONT_STOP;
}
});
return methods;
}
/**
* Determines if the supplied field is a "Bean" field which is defined by:
*
* 1) is a public field OR..
* 2) has a get/set public method
*
* @param aClass
* @param field
* @return true if the supplied field is a bean field
*/
private static boolean isBeanField(Class<?> aClass, Field field) {
if(field.isAnnotationPresent(LeolaIgnore.class)) {
return false;
}
if((field.getModifiers() & Modifier.PUBLIC) > 0) {
return true;
}
final String fieldName = field.getName();
final String beanName = String.valueOf(fieldName.charAt(0)).toUpperCase() +
(fieldName.length() > 1 ? fieldName.substring(1) : "");
Method setMethod = getMethodByName(aClass, "set" + beanName, field.getType());
if(setMethod == null) {
return false;
}
if(setMethod.isAnnotationPresent(LeolaIgnore.class)) {
return false;
}
if((setMethod.getModifiers() & Modifier.PUBLIC) == 0) {
return false;
}
Method getMethod = getMethodByName(aClass, "get" + beanName, field.getType());
if(getMethod == null) {
return false;
}
if(getMethod.isAnnotationPresent(LeolaIgnore.class)) {
return false;
}
if((getMethod.getModifiers() & Modifier.PUBLIC) == 0) {
return false;
}
return true;
}
/**
* Retrieves all of the Java Bean fields. This will navigate up the class
* hierarchy up until the Object class is reached.
*
* <p>
* This will not grab any fields annotated with {@link LeolaIgnore}.
*
* @param aClass
* @return the list of all Java Bean fields
*/
public static List<Field> getBeanFields(Class<?> aClass) {
List<Field> fields = new ArrayList<Field>();
try {
for(Class<?> i = aClass;
i != null &&
i != Object.class;
i = i.getSuperclass() ) {
for(Field field : i.getDeclaredFields()) {
if(isBeanField(aClass, field)) {
fields.add(field);
}
}
}
}
catch(Exception e) {
/* ignore */
}
return (fields);
}
/**
* Retrieves all of the fields defined in the supplied {@link Class}. This will navigate up the class
* hierarchy up until the Object class is reached.
*
* <p>
* This will not grab any fields annotated with {@link LeolaIgnore}.
*
* @param aClass the class to grab all the public fields from.
* @return the {@link List} of public {@link Field}s.
*/
public static List<Field> getAllDeclaredFields(Class<?> aClass) {
List<Field> methods = new ArrayList<Field>();
try {
for(Class<?> i = aClass;
i != null &&
i != Object.class;
i = i.getSuperclass() ) {
for(Field m : i.getDeclaredFields()) {
/* Don't grab private members */
if( (m.getModifiers() & Modifier.PUBLIC) > 0 &&
! m.isAnnotationPresent(LeolaIgnore.class) ) {
methods.add(m);
}
}
}
}
catch(Exception e) {
/* ignore */
}
return (methods);
}
/**
* Get the method by name and parameter types. It walks the class hierarchy and attempts to
* find the method by using {@link Class#getMethod(String, Class...)}.
*
*
* @param aClass the class to check
* @param methodName the methods name
* @param parameterTypes the parameter types.
*
* @return the {@link Method} if found; otherwise null.
*/
public static Method getInheritedMethodByName(Class<?> aClass, String name, Class<?>[] parameterTypes) {
Method inheritedMethod = null;
for (Class<?> i = aClass; i != null && i != Object.class; i = i.getSuperclass()) {
try {
inheritedMethod = i.getMethod(name, parameterTypes);
if (inheritedMethod != null) {
return inheritedMethod;
}
}
catch (Exception ignore) {
/* Ignore */
}
}
return null;
}
/**
* Get the data member by name. It walks the class hierarchy and attempts to
* find the field.
*
* @param aClass the class to check
* @param fieldName the data member name
* @return the {@link Field} if found; otherwise null.
*/
public static Field getInheritedField(Class<?> aClass, String fieldName) {
for (Class<?> i = aClass; i != null && i != Object.class; i = i.getSuperclass()) {
try {
Field f = i.getField(fieldName);
if (f != null) {
f.setAccessible(true);
return f;
}
}
catch (Exception ignore) {
}
}
return null;
}
/**
* Get the underlying raw {@link Class} of the supplied {@link Type}
*
* @param type
* @return the Class associated with the {@link Type}
*/
public static Class<?> getRawType(Type type) {
if (type instanceof Class<?>) {
return (Class<?>) type;
}
if (type instanceof WildcardType) {
WildcardType wt = (WildcardType) type;
Type[] upperBounds = wt.getUpperBounds();
if (upperBounds != null && upperBounds.length == 1) {
return getRawType(upperBounds[0]);
}
}
if (type instanceof GenericArrayType) {
try {
return Class.forName("[L" + getRawType(((GenericArrayType) type).getGenericComponentType()).getName() + ";");
}
catch (ClassNotFoundException e) {
return new Object[0].getClass();
}
}
if (type instanceof ParameterizedType) {
return (Class<?>) ((ParameterizedType) type).getRawType();
}
if (type instanceof TypeVariable<?>) {
TypeVariable<?> tv = (TypeVariable<?>) type;
Type[] bounds = tv.getBounds();
if (bounds != null && bounds.length == 1) {
return getRawType(bounds[0]);
}
}
return Object.class;
}
/**
* Retrieves the annotation from the method, if it is not on the method, the parent
* is checked. This solves the "inherited annotation" problem for interfaces.
*
* @param annotation the annotation to look for
* @param ownerClass the class in which this method belongs to
* @param method the method which should be probed for annotations
* @return the Annotation instance if found; otherwise null
*/
public static <T extends Annotation> T getAnnotation(Class<T> annotation, Class<?> ownerClass, Method method) {
if ( method == null ) {
return null;
}
if ( method.isAnnotationPresent(annotation) ) {
return method.getAnnotation(annotation);
}
else {
/* Check all the interface Classes to determine if the annotation
* exists
*/
for(Class<?> aInterface : ownerClass.getInterfaces()) {
Method inheritedMethod = getInheritedMethodByName(aInterface, method.getName(), method.getParameterTypes());
if ( inheritedMethod != null ) {
T result = getAnnotation(annotation, aInterface, inheritedMethod);
if ( result != null ) {
return result;
}
}
}
/* Query the parent class for the annotation */
Class<?> superClass = method.getDeclaringClass().getSuperclass();
Method inheritedMethod = getInheritedMethodByName(superClass, method.getName(), method.getParameterTypes());
return getAnnotation(annotation, superClass, inheritedMethod);
}
}
/**
* Creates a new {@link LeoNativeClass} based off of the Java fully qualified name and supplied parameters.
*
* @param className the fully qualified Java class name
* @param params the parameters used to construct the instance
* @return the {@link LeoNativeClass}
* @throws LeolaRuntimeException
*/
public static LeoNativeClass newNativeInstance(String className, LeoObject ... params) throws LeolaRuntimeException {
LeoNativeClass result = null;
/* ensure we always have a valid array */
if ( params == null ) {
params = new LeoObject[0];
}
try {
/* first determine if this is a valid Java class type.
* If it isn't, we can't instantiate this, and return
* an error
*/
Class<?> nativeClass = Class.forName(className);
/* Only allow for constructing non-abstract class types
* - this might change in the future if we decide to add
* Java bytecode creation here
*/
if ( Modifier.isAbstract(nativeClass.getModifiers()) ) {
LeoObject.throwNativeMethodError("Can't instantiate an abstract Java class '" + className + "'");
}
Object instance = null;
for(Constructor<?> constructor : nativeClass.getConstructors()) {
Class<?>[] paramTypes = constructor.getParameterTypes();
if ( paramTypes.length == params.length) {
instance = tryNativeConstructor(constructor, params, paramTypes);
/* if we were able to successfully create the Java instance
* go ahead and wrap it in the LeoNativeClass; we
* are done here now.
*/
if ( instance != null ) {
result = new LeoNativeClass(nativeClass, instance);
break;
}
}
}
/* if we were not able to find a matching constructor, bail out
* and throw an error
*/
if (result == null ) {
LeoObject.throwClassNotFoundError("The Java class '" + className + "' was not found.");
}
}
catch(LeolaRuntimeException e) {
throw e;
}
catch(ClassNotFoundException e) {
LeoObject.throwClassNotFoundError("The Java class '" + className + "' was not found.");
}
catch(Throwable e) {
LeoObject.throwNativeMethodError("Unable to construct Java native type: " + className + " - " + e);
}
return result;
}
/**
* Attempts to instantiate the object
*
* @param constructor
* @param params
* @param paramTypes
* @return the resulting object from executing the constructor
*/
private static Object tryNativeConstructor(Constructor<?> constructor, LeoObject[] params, Class<?>[] paramTypes) {
Object result = null;
try {
Object[] args = new Object[paramTypes.length];
for(int i = 0; i < paramTypes.length; i++ ) {
Class<?> aCl = paramTypes[i];
args[i] = LeoObject.toJavaObject(aCl, params[i]);
}
result = constructor.newInstance(args);
}
catch(InvocationTargetException e) {
rethrow(e);
}
catch(Throwable ignore) {
/* allow to retry */
}
return (result);
}
}
<|start_filename|>src/leola/ast/FuncInvocationExpr.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.ast;
import java.util.List;
import leola.vm.EvalException;
/**
* A Function invocation
*
* @author Tony
*
*/
public class FuncInvocationExpr extends Expr {
private Expr callee;
private List<Expr> arguments;
/**
* @param callee
* @param arguments
*/
public FuncInvocationExpr(Expr callee, List<Expr> arguments) {
super();
this.callee = callee;
this.arguments = arguments;
}
@Override
public void visit(ASTNodeVisitor v) throws EvalException {
v.visit(this);
}
public Expr getCallee() {
return callee;
}
public List<Expr> getArguments() {
return arguments;
}
public String getFunctionName() {
if(this.callee instanceof VarExpr) {
return ((VarExpr)this.callee).getVarName();
}
return "";
}
}
<|start_filename|>src/leola/vm/Scope.java<|end_filename|>
/*
Leola Programming Language
Author: <NAME>
See license.txt
*/
package leola.vm;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaMethod;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoNamespace;
import leola.vm.types.LeoNativeFunction;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
import leola.vm.util.ArrayUtil;
import leola.vm.util.ClassUtil;
/**
* A {@link Scope} represents a lexical scope of variables
*
* @author Tony
*
*/
public class Scope {
public enum ScopeType {
Namespace,
Class
}
/**
* The parent scope
*/
private Scope parent;
/**
* Any class definitions in this
* scope
*/
private ClassDefinitions classDefinitions;
/**
* Any namespace definitions in this
* scope
*/
private NamespaceDefinitions namespaceDefinitions;
/**
* The values stored in this scope
*/
private LeoMap values;
/**
* The type of scope this is
*/
private ScopeType scopeType;
/**
* @param scopeType
* @param parent
*/
public Scope(ScopeType scopeType, Scope parent) {
this.scopeType = scopeType;
this.parent = parent;
}
/**
* This will clear out (i.e., remove) all data elements from this {@link Scope}.
*
* <p>
* This includes:
* <ul>
* <li>The {@link ClassDefinitions}</li>
* <li>The {@link NamespaceDefinitions}</li>
* <li>Invokes {@link Scope#clear()} on the <code>parent</code> scope of this Scope</li>
* <li>Any bound variables within this Scope</li>
* </ul>
* As the name implies, this does remove all allocated objects which will become garbage and
* there before be collected by the JVM GC. Use this method with caution.
*/
public void clear() {
if(hasClassDefinitions()) {
this.classDefinitions.clearDefinitions();
}
if(hasNamespaceDefinitions()) {
this.namespaceDefinitions.clearDefinitions();
}
if(hasParent()) {
this.parent.clear();
}
if(hasObjects()) {
/* Create a new Set here so that we don't get caught in an infinite recursive loop if
* the scopes are self referencing
*/
Set<Map.Entry<LeoObject, LeoObject>> entrySet = new HashSet<Map.Entry<LeoObject,LeoObject>>(this.values.entrySet());
this.values.clear();
for(Map.Entry<LeoObject, LeoObject> entry : entrySet) {
Scope keyScope = entry.getKey().getScope();
if(keyScope != null) {
keyScope.clear();
}
Scope valueScope = entry.getValue().getScope();
if(valueScope != null) {
valueScope.clear();
}
}
}
}
/**
* @return true if this {@link Scope} has a parent {@link Scope} defined.
*/
public boolean hasParent() {
return this.parent != null;
}
/**
* @return true if there are {@link ClassDefinition}s in this {@link Scope}
*/
public boolean hasClassDefinitions() {
return this.classDefinitions != null && this.classDefinitions.hasDefinitions();
}
/**
* @return the classDefinitions
*/
public ClassDefinitions getClassDefinitions() {
if ( this.classDefinitions == null ) {
this.classDefinitions = new ClassDefinitions();
}
return classDefinitions;
}
/**
* @return if this scope has {@link NamespaceDefinitions}
*/
public boolean hasNamespaceDefinitions() {
return this.namespaceDefinitions != null && this.namespaceDefinitions.hasDefinitions();
}
/**
* @return the namespaceDefinitions
*/
public NamespaceDefinitions getNamespaceDefinitions() {
if(this.namespaceDefinitions == null) {
this.namespaceDefinitions = new NamespaceDefinitions();
}
return namespaceDefinitions;
}
/**
* @return the underlying raw values of the {@link Scope}
*/
public LeoObject[] getScopedValues() {
return (this.values != null) ? this.values.vals().getRawArray() : ArrayUtil.EMPTY_LEOOBJECTS;
}
/**
* Recursively attempts to retrieve the value associated with the reference. If it
* isn't found in this scope, it will ask its parent scope.
*
* @param reference
* @return the value if found, otherwise null
*/
public LeoObject getObject(LeoObject reference) {
LeoObject value = (this.values != null) ? this.values.getWithJNull(reference) : null;
if ( value == null && parent != null) {
value = parent.getObject(reference);
}
return value;
}
/**
* Recursively attempts to retrieve the value associated with the reference. If it
* isn't found in this scope, it will ask its parent scope.
*
* @see Scope#getObject(LeoString)
* @param reference
* @return the LeoObject that is linked to the reference, if not found null is returned
*/
public LeoObject getObject(String reference){
return getObject(LeoString.valueOf(reference));
}
/**
* Searches scopes and parent scopes up and until the global scope
*
* @param reference
* @return the value if found, otherwise null;
*/
public LeoObject getObjectNoGlobal(LeoObject reference) {
LeoObject value = (this.values != null) ? this.values.getWithJNull(reference) : null;
if ( value == null && parent != null && !parent.isGlobalScope()) {
value = parent.getObjectNoGlobal(reference);
}
return value;
}
/**
* Searches scopes and parent scopes up and until the global scope
*
* @param reference
* @return the value if found, otherwise null;
*/
public LeoObject getObjectNoGlobal(String reference) {
return getObjectNoGlobal(LeoString.valueOf(reference));
}
/**
* Retrieves a {@link LeoNamespace} by its name
*
* @param reference
* @return the {@link LeoNamespace} if found, otherwise null
*/
public LeoNamespace getNamespace(LeoObject reference) {
LeoNamespace value = (hasNamespaceDefinitions()) ? this.namespaceDefinitions.getNamespace(reference) : null;
if(value == null && parent != null) {
value = parent.getNamespace(reference);
}
return value;
}
/**
* Stores an object in this scope and only this scope. This does
* not traverse the parent scopes to see if a value is already
* held.
*
* @param reference
* @param value
* @return the previously held value, if any
*/
public LeoObject putObject(LeoObject reference, LeoObject value) {
if(this.values==null) {
this.values = new LeoMap();
}
return this.values.put(reference, value);
}
public LeoObject putObject(String reference, LeoObject value) {
return putObject(LeoString.valueOf(reference), value);
}
/**
* Stores an object in this scope, it first checks to see if any parent
* values contain the supplied reference, if it does it will override the existing
* value. This is to account for class data members.
*
* @param reference
* @param value
* @return the previously held value, if any
*/
public LeoObject storeObject(LeoObject reference, LeoObject newValue) {
Scope current = this;
while (current != null) {
// if the value is the the current scope, break out
if (current.values != null && current.values.getWithJNull(reference) != null ) {
break;
}
// We check the parent if and only if:
// 1) there is a parent scope that isn't the global scope
// 2) if this scope is a class, and the parent scope is a class
// 3) if this scope is a namespace
if(current.parent != null && !current.parent.isGlobalScope()) {
if(current.isClassScope()) {
if(!current.parent.isNamespaceScope()) {
current = current.parent;
continue;
}
}
else {
current = current.parent;
continue;
}
}
current = this;
break;
}
return current.putObject(reference, newValue);
}
public LeoObject storeObject(String reference, LeoObject value) {
return storeObject(LeoString.valueOf(reference), value);
}
/**
* Removes an object from this {@link Scope}
*
* @param reference
* @return the {@link LeoObject} previously held by the reference (or null if no value was held
* by this reference).
*/
public LeoObject removeObject(LeoObject reference) {
return (this.values!=null) ? this.values.remove(reference) : null;
}
/**
* Removes an object from this {@link Scope}
*
* @param reference
* @return the {@link LeoObject} previously held by the reference (or null if no value was held
* by this reference).
*/
public LeoObject removeObject(String reference) {
return removeObject(LeoString.valueOf(reference));
}
/**
* @return true if and only if there are stored objects in this {@link Scope}
*/
public boolean hasObjects() {
return (this.values != null) && !this.values.isEmpty();
}
/**
* @return the number of {@link LeoObject}s in this {@link Scope}
*/
public int getNumberOfObjects() {
return (this.values != null) ? this.values.size() : 0;
}
/**
* Retrieves the raw {@link LeoMap} that contains the reference and {@link LeoObject} associations
*
* @return the {@link LeoMap} of the references and values
*/
public LeoMap getRawObjects() {
return this.values;
}
/**
* @return true if this scope is the global scope
*/
public boolean isGlobalScope() {
return parent == null;
}
/**
* @return if this scope belongs to a Namespace
*/
public boolean isNamespaceScope() {
return this.scopeType == ScopeType.Namespace;
}
/**
* @return if this scope belongs to a Class
*/
public boolean isClassScope() {
return this.scopeType == ScopeType.Class;
}
/**
* @return the parent
*/
public Scope getParent() {
return parent;
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
public Scope clone() {
Scope clone = new Scope(this.scopeType, this.parent);
clone.classDefinitions = this.classDefinitions;
clone.namespaceDefinitions = this.namespaceDefinitions;
clone.values = (LeoMap)this.values.clone();
return clone;
}
/**
* Loads the objects methods into the supplied {@link Scope}
*
* @param jObject
*/
public void loadNatives(Object jObject) {
Class<?> aClass = jObject.getClass();
loadClass(aClass, jObject, false);
}
/**
* Loads the static methods of the native class into the supplied {@link Scope}
*
* @param aClass
*/
public void loadStatics(Class<?> aClass) {
loadClass(aClass, null, true);
}
/**
* Loads the class methods into this {@link Scope}
*
* @param aClass the class to look for methods
* @param jObject the instance object (may be null)
* @param onlyStatics if we should only be loading static
*/
private void loadClass(Class<?> aClass, Object jObject, boolean onlyStatics) {
List<Method> methods = ClassUtil.getAllDeclaredMethods(aClass);
/*
* first join all the functions with the same name (group the overloaded
* functions)
*/
Map<String, List<Method>> grouped = new HashMap<String, List<Method>>();
for (Method m : methods) {
boolean isStatic = (m.getModifiers() & Modifier.STATIC) != 0;
if (isStatic || !onlyStatics) {
if (!grouped.containsKey(m.getName())) {
grouped.put(m.getName(), new ArrayList<Method>());
}
grouped.get(m.getName()).add(m);
}
}
/*
* Now iterate over the grouped functions to add them to the scoped
* object
*/
for (List<Method> overloads : grouped.values()) {
if (!overloads.isEmpty()) {
Method m = overloads.get(0);
LeoNativeFunction func = new LeoNativeFunction(overloads, jObject);
if (m.isAnnotationPresent(LeolaMethod.class)) {
storeObject(m.getAnnotation(LeolaMethod.class).alias(), func);
}
else {
storeObject(m.getName(), func);
}
}
}
}
/**
* Looks up a namespace.
*
* @param name
* @return
*/
private LeoNamespace lookupSimpleNamespace(LeoObject name) {
LeoNamespace result = null;
Scope scope = this;
while(scope != null) {
if(scope.hasNamespaceDefinitions()) {
NamespaceDefinitions ndefs = scope.getNamespaceDefinitions();
result = ndefs.getNamespace(name);
if ( result != null ) {
break;
}
}
scope = scope.getParent();
}
return (result);
}
/**
* Looks up name spaces (Ex. io:net:sytem:etc) going from the first namespace to the last (with
* each namespace defining the next namespace.)
*
* @param namespace
* @return the bottom most namespace
*/
public LeoNamespace lookupNamespace(LeoObject namespace) {
LeoNamespace ns = null;
String[] namespaces = namespace.toString().replace(".", ":").split(":");
if ( namespaces.length > 0 ) {
ns = this.lookupSimpleNamespace(LeoString.valueOf(namespaces[0]));
for(int i = 1; i < namespaces.length && ns != null; i++ ) {
Scope scope = ns.getScope();
if ( scope.hasNamespaceDefinitions() ) {
ns = scope.getNamespaceDefinitions().getNamespace(LeoString.valueOf(namespaces[i]));
}
}
}
return ns;
}
/**
* Looks up the appropriate {@link ClassDefinitions} containing the className
*
* @param currentScope
* @param className
* @return the {@link ClassDefinitions} or null if not found
*/
public ClassDefinitions lookupClassDefinitions(Scope currentScope, LeoObject className) {
if ( className == null ) {
throw new LeolaRuntimeException("InvalidClassNameError: The class name can not be empty!");
}
String jclassName = className.toString();
LeoObject lclassName = className;
ClassDefinitions result = null;
String formattedClassName = jclassName.replace(".", ":");
int index = formattedClassName.lastIndexOf(':');
if ( index > -1 ) {
String namespace = formattedClassName.substring(0, index);
LeoNamespace ns = lookupNamespace(LeoString.valueOf(namespace));
if( ns != null ) {
String justClassName = formattedClassName.substring(index + 1);
Scope scope = ns.getScope();
result = checkScopeForDefinitions(scope, LeoString.valueOf(justClassName));
}
}
else {
Scope scope = currentScope;
while(scope != null) {
result = checkScopeForDefinitions(scope, lclassName);
if ( result != null ) {
break;
}
scope = scope.getParent();
}
}
return (result);
}
/**
* Gets the specific {@link ClassDefinition} for the supplied className
*
* @param className - the fully qualified class name
* @return the {@link ClassDefinition} if found
*/
public ClassDefinition lookupClassDefinition(LeoObject className) {
ClassDefinitions defs = lookupClassDefinitions(className);
if(defs != null) {
LeoObject simpleClassName = getClassName(className);
if(defs.hasDefinitions() && defs.containsClass(simpleClassName)) {
return defs.getDefinition(simpleClassName);
}
}
return null;
}
/**
* Looks up the appropriate {@link ClassDefinitions} containing the className.
*
* @param className
* @return the {@link ClassDefinitions} or null if not found
*/
public ClassDefinitions lookupClassDefinitions(LeoObject className) {
return lookupClassDefinitions(this, className);
}
/**
* Gets just the class name, removing any package or namespaces.
*
* @param fullyQualifiedClassName
* @return just the class name (the simple class name).
*/
public LeoObject getClassName(LeoObject fullyQualifiedClassName) {
return LeoString.valueOf(getClassName(fullyQualifiedClassName.toString()));
}
/**
* Gets just the class name, removing any package or namespaces.
*
* @param fullyQualifiedClassName
* @return just the class name (the simple class name).
*/
public String getClassName(String fullyQualifiedClassName) {
String result = fullyQualifiedClassName;
String formattedClassName = fullyQualifiedClassName.replace(".", ":");
int index = formattedClassName.lastIndexOf(':');
if ( index > -1 ) {
String justClassName = formattedClassName.substring(index + 1);
result = justClassName;
}
return result;
}
private ClassDefinitions checkScopeForDefinitions(Scope scope, LeoObject justClassName) {
ClassDefinitions result = null;
if ( scope.hasClassDefinitions() ) {
ClassDefinitions defs = scope.getClassDefinitions();
if ( defs.containsClass(justClassName) ) {
result = defs;
}
}
return result;
}
}
| tonysparks/leola |
<|start_filename|>c_src/mac/keyio_mac.hpp<|end_filename|>
#include <IOKit/hid/IOHIDLib.h>
#include <IOKit/hidsystem/IOHIDShared.h>
#include <unistd.h>
#include <errno.h>
#include <thread>
#include <map>
#include <iostream>
#include <mach/mach_error.h>
int init_sink(void);
int exit_sink(void);
/*
* Key event information that's shared between C++ and Haskell.
*
* type: represents key up or key down
* page: represents IOKit usage page
* usage: represents IOKit usage
*/
struct KeyEvent {
uint64_t type;
uint32_t page;
uint32_t usage;
};
/*
* These are needed to receive unaltered key events from the OS.
*/
static std::thread thread;
static CFRunLoopRef listener_loop;
static std::map<io_service_t,IOHIDDeviceRef> source_device;
static int fd[2];
static char *prod = nullptr;
void print_iokit_error(const char *fname, int freturn = 0) {
std::cerr << fname << " error";
if(freturn) {
//std::cerr << " " << std::hex << freturn;
std::cerr << ": ";
std::cerr << mach_error_string(freturn);
}
std::cerr << std::endl;
}
/*
* We'll register this callback to run whenever an IOHIDDevice
* (representing a keyboard) sends input from the user.
*
* It passes the relevant information into a pipe that will be read
* from with wait_key.
*/
void input_callback(void *context, IOReturn result, void *sender, IOHIDValueRef value) {
struct KeyEvent e;
IOHIDElementRef element = IOHIDValueGetElement(value);
e.type = IOHIDValueGetIntegerValue(value);
e.page = IOHIDElementGetUsagePage(element);
e.usage = IOHIDElementGetUsage(element);
write(fd[1], &e, sizeof(struct KeyEvent));
}
void open_matching_devices(char *product, io_iterator_t iter) {
io_name_t name;
kern_return_t kr;
CFStringRef cfproduct = NULL;
if(product) {
cfproduct = CFStringCreateWithCString(kCFAllocatorDefault, product, CFStringGetSystemEncoding());
if(cfproduct == NULL) {
print_iokit_error("CFStringCreateWithCString");
return;
}
}
CFStringRef cfkarabiner = CFStringCreateWithCString(kCFAllocatorDefault, "Karabiner VirtualHIDKeyboard", CFStringGetSystemEncoding());
if(cfkarabiner == NULL) {
print_iokit_error("CFStringCreateWithCString");
if(product) {
CFRelease(cfproduct);
}
return;
}
for(mach_port_t curr = IOIteratorNext(iter); curr; curr = IOIteratorNext(iter)) {
CFStringRef cfcurr = (CFStringRef)IORegistryEntryCreateCFProperty(curr, CFSTR(kIOHIDProductKey), kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if(cfcurr == NULL) {
print_iokit_error("IORegistryEntryCreateCFProperty");
continue;
}
bool match = (CFStringCompare(cfcurr, cfkarabiner, 0) != kCFCompareEqualTo);
if(product) {
match = match && (CFStringCompare(cfcurr, cfproduct, 0) == kCFCompareEqualTo);
}
CFRelease(cfcurr);
if(!match) continue;
IOHIDDeviceRef dev = IOHIDDeviceCreate(kCFAllocatorDefault, curr);
source_device[curr] = dev;
IOHIDDeviceRegisterInputValueCallback(dev, input_callback, NULL);
kr = IOHIDDeviceOpen(dev, kIOHIDOptionsTypeSeizeDevice);
if(kr != kIOReturnSuccess) {
print_iokit_error("IOHIDDeviceOpen", kr);
}
IOHIDDeviceScheduleWithRunLoop(dev, listener_loop, kCFRunLoopDefaultMode);
}
if(product) {
CFRelease(cfproduct);
}
CFRelease(cfkarabiner);
}
/*
* We'll register this callback to run whenever an IOHIDDevice
* (representing a keyboard) is connected to the OS
*
*/
void matched_callback(void *context, io_iterator_t iter) {
char *product = (char *)context;
open_matching_devices(product, iter);
}
/*
* We'll register this callback to run whenever an IOHIDDevice
* (representing a keyboard) is disconnected from the OS
*
*/
void terminated_callback(void *context, io_iterator_t iter) {
for(mach_port_t curr = IOIteratorNext(iter); curr; curr = IOIteratorNext(iter)) {
source_device.erase(curr);
}
}
/*
* Reads a new key event from the pipe, blocking until a new event is
* ready.
*/
extern "C" int wait_key(struct KeyEvent *e) {
return read(fd[0], e, sizeof(struct KeyEvent)) == sizeof(struct KeyEvent);
}
/*
* For each keyboard, registers an asynchronous callback to run when
* new input from the user is available from that keyboard. Then
* sleeps indefinitely, ready to received asynchronous callbacks.
*/
void monitor_kb(char *product) {
kern_return_t kr;
CFMutableDictionaryRef matching_dictionary = IOServiceMatching(kIOHIDDeviceKey);
if(!matching_dictionary) {
print_iokit_error("IOServiceMatching");
return;
}
UInt32 value;
CFNumberRef cfValue;
value = kHIDPage_GenericDesktop;
cfValue = CFNumberCreate( kCFAllocatorDefault, kCFNumberSInt32Type, &value );
CFDictionarySetValue(matching_dictionary, CFSTR(kIOHIDDeviceUsagePageKey), cfValue);
CFRelease(cfValue);
value = kHIDUsage_GD_Keyboard;
cfValue = CFNumberCreate( kCFAllocatorDefault, kCFNumberSInt32Type, &value );
CFDictionarySetValue(matching_dictionary,CFSTR(kIOHIDDeviceUsageKey),cfValue);
CFRelease(cfValue);
io_iterator_t iter = IO_OBJECT_NULL;
CFRetain(matching_dictionary);
kr = IOServiceGetMatchingServices(kIOMasterPortDefault,
matching_dictionary,
&iter);
if(kr != KERN_SUCCESS) {
print_iokit_error("IOServiceGetMatchingServices", kr);
return;
}
listener_loop = CFRunLoopGetCurrent();
open_matching_devices(product, iter);
IONotificationPortRef notification_port = IONotificationPortCreate(kIOMasterPortDefault);
CFRunLoopSourceRef notification_source = IONotificationPortGetRunLoopSource(notification_port);
CFRunLoopAddSource(listener_loop, notification_source, kCFRunLoopDefaultMode);
CFRetain(matching_dictionary);
kr = IOServiceAddMatchingNotification(notification_port,
kIOMatchedNotification,
matching_dictionary,
matched_callback,
product,
&iter);
if(kr != KERN_SUCCESS) {
print_iokit_error("IOServiceAddMatchingNotification", kr);
return;
}
for(mach_port_t curr = IOIteratorNext(iter); curr; curr = IOIteratorNext(iter)) {}
kr = IOServiceAddMatchingNotification(notification_port,
kIOTerminatedNotification,
matching_dictionary,
terminated_callback,
NULL,
&iter);
if(kr != KERN_SUCCESS) {
print_iokit_error("IOServiceAddMatchingNotification", kr);
return;
}
for(mach_port_t curr = IOIteratorNext(iter); curr; curr = IOIteratorNext(iter)) {}
CFRunLoopRun();
for(std::pair<const io_service_t,IOHIDDeviceRef> p: source_device) {
kr = IOHIDDeviceClose(p.second,kIOHIDOptionsTypeSeizeDevice);
if(kr != KERN_SUCCESS) {
print_iokit_error("IOHIDDeviceClose", kr);
}
}
}
/*
* Opens and seizes input from each keyboard device whose product name
* matches the parameter (if NULL is received, then it opens all
* keyboard devices). Spawns a thread to receive asynchronous input
* and opens a pipe for this thread to send key event data to the main
* thread.
*
* Loads a the karabiner kernel extension that will send key events
* back to the OS.
*/
extern "C" int grab_kb(char *product) {
// Source
if (pipe(fd) == -1) {
std::cerr << "pipe error: " << errno << std::endl;
return errno;
}
if(product) {
prod = (char *)malloc(strlen(product) + 1);
strcpy(prod, product);
}
thread = std::thread{monitor_kb, prod};
// Sink
return init_sink();
}
/*
* Releases the resources needed to receive key events from and send
* key events to the OS.
*/
extern "C" int release_kb() {
int retval = 0;
kern_return_t kr;
// Source
if(thread.joinable()) {
CFRunLoopStop(listener_loop);
thread.join();
} else {
std::cerr << "No thread was running!" << std::endl;
}
if(prod) {
free(prod);
}
if (close(fd[0]) == -1) {
std::cerr << "close error: " << errno << std::endl;
retval = 1;
}
if (close(fd[1]) == -1) {
std::cerr << "close error: " << errno << std::endl;
retval = 1;
}
// Sink
if(exit_sink()) retval = 1;
return retval;
}
<|start_filename|>c_src/mac/list-keyboards.c<|end_filename|>
#include <IOKit/hid/IOHIDLib.h>
#include <IOKit/hidsystem/IOHIDShared.h>
int main() {
CFMutableDictionaryRef matching_dictionary = IOServiceMatching(kIOHIDDeviceKey);
if(!matching_dictionary) {
fprintf(stderr,"IOServiceMatching failed");
return 1;
}
UInt32 value;
CFNumberRef cfValue;
value = kHIDPage_GenericDesktop;
cfValue = CFNumberCreate( kCFAllocatorDefault, kCFNumberSInt32Type, &value );
CFDictionarySetValue(matching_dictionary, CFSTR(kIOHIDDeviceUsagePageKey), cfValue);
CFRelease(cfValue);
value = kHIDUsage_GD_Keyboard;
cfValue = CFNumberCreate( kCFAllocatorDefault, kCFNumberSInt32Type, &value );
CFDictionarySetValue(matching_dictionary,CFSTR(kIOHIDDeviceUsageKey),cfValue);
CFRelease(cfValue);
io_iterator_t iter = IO_OBJECT_NULL;
kern_return_t r = IOServiceGetMatchingServices(kIOMasterPortDefault,
matching_dictionary,
&iter);
if(r != KERN_SUCCESS) {
fprintf(stderr,"IOServiceGetMatchingServices failed");
return r;
}
for(mach_port_t curr = IOIteratorNext(iter); curr; curr = IOIteratorNext(iter)) {
CFTypeRef str = IORegistryEntryCreateCFProperty(curr,
CFSTR("Product"),
kCFAllocatorDefault,
kIOHIDOptionsTypeNone);
CFShow(str);
}
return 0;
}
<|start_filename|>src/KMonad/App/Invocation/Types.hs<|end_filename|>
module KMonad.App.Invocation.Types
( Invoc(..)
, HasInvoc(..)
)
where
import KMonad.Prelude hiding (try)
import KMonad.Args.Parser (itokens, keywordButtons, noKeywordButtons, otokens, symbol)
import KMonad.Args.Types (DefSetting(..), choice, try)
import qualified KMonad.Args.Types as M -- [M]egaparsec functionality
import Options.Applicative
--------------------------------------------------------------------------------
-- $cmd
--
-- The different things KMonad can be instructed to do.
-- | Record describing the instruction to KMonad
data Invoc = Invoc
{ _cfgFile :: FilePath -- ^ Which file to read the config from
, _dryRun :: Bool -- ^ Flag to indicate we are only test-parsing
, _logLvl :: LogLevel -- ^ Level of logging to use
-- All 'KDefCfg' options of a 'KExpr'
, _cmdAllow :: DefSetting -- ^ Allow execution of arbitrary shell-commands?
, _fallThrgh :: DefSetting -- ^ Re-emit unhandled events?
, _initStr :: Maybe DefSetting -- ^ TODO: What does this do?
, _cmpSeq :: Maybe DefSetting -- ^ Key to use for compose-key sequences
, _oToken :: Maybe DefSetting -- ^ How to emit the output
, _iToken :: Maybe DefSetting -- ^ How to capture the input
}
deriving Show
makeClassy ''Invoc
<|start_filename|>src/KMonad/Model.hs<|end_filename|>
module KMonad.Model
( module X )
where
import KMonad.Model.Action as X
import KMonad.Model.Button as X
import KMonad.Model.BEnv as X
<|start_filename|>src/KMonad/Prelude.hs<|end_filename|>
{-# OPTIONS_GHC -Wno-dodgy-imports #-}
{-|
Module : KMonad.Prelude
Description : Code that will be imported into every module
Copyright : (c) <NAME>, 2019
License : MIT
Maintainer : <EMAIL>
Stability : experimental
Portability : non-portable (MPTC with FD, FFI to Linux-only c-code)
-}
module KMonad.Prelude
( module X )
where
import Control.Lens as X
import Control.Monad.Cont as X
import Data.Acquire as X
import GHC.Conc as X (orElse)
import RIO.Text as X (unlines, lines, unpack, pack)
import RIO as X hiding
(-- Not the lens stuff, I want more support for lenses from "Control.Lens"
view, ASetter, ASetter', Lens, Getting, Lens'
, SimpleGetter, lens, over, set, sets, to, (^.)
-- The following line is required for newer stack releases.
-- This is also the reason for the OPTIONS_GHC pragma
, (^..), (^?), preview, (%~), (.~)
-- Some stuff I'd rather default to Text
, unlines, lines
-- Will import these when I need it
, some, many
)
<|start_filename|>src/KMonad/Keyboard/IO/Linux/DeviceSource.hs<|end_filename|>
{-# LANGUAGE DeriveAnyClass #-}
{-|
Module : KMonad.Keyboard.IO.Linux.DeviceSource
Description : Load and acquire a linux /dev/input device
Copyright : (c) <NAME>, 2019
License : MIT
Maintainer : <EMAIL>
Stability : experimental
Portability : portable
-}
module KMonad.Keyboard.IO.Linux.DeviceSource
( deviceSource
, deviceSource64
, KeyEventParser
, decode64
)
where
import KMonad.Prelude
import Foreign.C.Types
import System.Posix
import KMonad.Keyboard.IO.Linux.Types
import KMonad.Util
import qualified Data.Serialize as B (decode)
import qualified RIO.ByteString as B
--------------------------------------------------------------------------------
-- $err
data DeviceSourceError
= IOCtlGrabError FilePath
| IOCtlReleaseError FilePath
| KeyIODecodeError String
deriving Exception
instance Show DeviceSourceError where
show (IOCtlGrabError pth) = "Could not perform IOCTL grab on: " <> pth
show (IOCtlReleaseError pth) = "Could not perform IOCTL release on: " <> pth
show (KeyIODecodeError msg) = "KeyEvent decode failed with msg: " <> msg
makeClassyPrisms ''DeviceSourceError
--------------------------------------------------------------------------------
-- $ffi
foreign import ccall "ioctl_keyboard"
c_ioctl_keyboard :: CInt -> CInt -> IO CInt
-- | Perform an IOCTL operation on an open keyboard handle
ioctl_keyboard :: MonadIO m
=> Fd -- ^ Descriptor to open keyboard file (like /dev/input/eventXX)
-> Bool -- ^ True to grab, False to ungrab
-> m Int -- ^ Return the exit code
ioctl_keyboard (Fd h) b = fromIntegral <$>
liftIO (c_ioctl_keyboard h (if b then 1 else 0))
--------------------------------------------------------------------------------
-- $decoding
-- | A 'KeyEventParser' describes how to read and parse 'LinuxKeyEvent's from
-- the binary data-stream provided by the device-file.
data KeyEventParser = KeyEventParser
{ _nbytes :: !Int
-- ^ Size of 1 input event in bytes
, _prs :: !(B.ByteString -> Either String LinuxKeyEvent)
-- ^ Function to convert bytestring to event
}
makeClassy ''KeyEventParser
-- | Default configuration for parsing keyboard events
defEventParser :: KeyEventParser
defEventParser = KeyEventParser 24 decode64
-- | The KeyEventParser that works on my 64-bit Linux environment
decode64 :: B.ByteString -> Either String LinuxKeyEvent
decode64 bs = (linuxKeyEvent . fliptup) <$> result
where
result :: Either String (Int32, Word16, Word16, Word64, Word64)
result = B.decode . B.reverse $ bs
fliptup (a, b, c, d, e) = (e, d, c, b, a)
--------------------------------------------------------------------------------
-- $types
-- | Configurable components of a DeviceSource
data DeviceSourceCfg = DeviceSourceCfg
{ _pth :: !FilePath -- ^ Path to the event-file
, _parser :: !KeyEventParser -- ^ The method used to decode events
}
makeClassy ''DeviceSourceCfg
-- | Collection of data used to read from linux input.h event stream
data DeviceFile = DeviceFile
{ _cfg :: !DeviceSourceCfg -- ^ Configuration settings
, _fd :: !Fd -- ^ Posix filedescriptor to the device file
, _hdl :: !Handle -- ^ Haskell handle to the device file
}
makeClassy ''DeviceFile
instance HasDeviceSourceCfg DeviceFile where deviceSourceCfg = cfg
instance HasKeyEventParser DeviceFile where keyEventParser = cfg.parser
-- | Open a device file
deviceSource :: HasLogFunc e
=> KeyEventParser -- ^ The method by which to read and decode events
-> FilePath -- ^ The filepath to the device file
-> RIO e (Acquire KeySource)
deviceSource pr pt = mkKeySource (lsOpen pr pt) lsClose lsRead
-- | Open a device file on a standard linux 64 bit architecture
deviceSource64 :: HasLogFunc e
=> FilePath -- ^ The filepath to the device file
-> RIO e (Acquire KeySource)
deviceSource64 = deviceSource defEventParser
--------------------------------------------------------------------------------
-- $io
-- | Open the keyboard, perform an ioctl grab and return a 'DeviceFile'. This
-- can throw an 'IOException' if the file cannot be opened for reading, or an
-- 'IOCtlGrabError' if an ioctl grab could not be properly performed.
lsOpen :: (HasLogFunc e)
=> KeyEventParser -- ^ The method by which to decode events
-> FilePath -- ^ The path to the device file
-> RIO e DeviceFile
lsOpen pr pt = do
h <- liftIO . openFd pt ReadOnly Nothing $
OpenFileFlags False False False False False
hd <- liftIO $ fdToHandle h
logInfo $ "Initiating ioctl grab"
ioctl_keyboard h True `onErr` IOCtlGrabError pt
return $ DeviceFile (DeviceSourceCfg pt pr) h hd
-- | Release the ioctl grab and close the device file. This can throw an
-- 'IOException' if the handle to the device cannot be properly closed, or an
-- 'IOCtlReleaseError' if the ioctl release could not be properly performed.
lsClose :: (HasLogFunc e) => DeviceFile -> RIO e ()
lsClose src = do
logInfo $ "Releasing ioctl grab"
ioctl_keyboard (src^.fd) False `onErr` IOCtlReleaseError (src^.pth)
liftIO . closeFd $ src^.fd
-- | Read a bytestring from an open filehandle and return a parsed event. This
-- can throw a 'KeyIODecodeError' if reading from the 'DeviceFile' fails to
-- yield a parseable sequence of bytes.
lsRead :: (HasLogFunc e) => DeviceFile -> RIO e KeyEvent
lsRead src = do
bts <- B.hGet (src^.hdl) (src^.nbytes)
case (src^.prs $ bts) of
Right p -> case fromLinuxKeyEvent p of
Just e -> return e
Nothing -> lsRead src
Left s -> throwIO $ KeyIODecodeError s
<|start_filename|>c_src/mac/Makefile<|end_filename|>
all: list-keyboards.c
gcc $< -o list-keyboards -framework IOKit -framework CoreFoundation
<|start_filename|>src/KMonad/Keyboard/IO/Windows/LowLevelHookSource.hs<|end_filename|>
{-|
Module : KMonad.Keyboard.IO.Windows.LowLevelHookSource
Description : Load and acquire a windows low-level keyboard hook.
Copyright : (c) <NAME>, 2019
License : MIT
Maintainer : <EMAIL>
Stability : experimental
Portability : portable
-}
module KMonad.Keyboard.IO.Windows.LowLevelHookSource
( llHook
)
where
import KMonad.Prelude
import Foreign.Marshal hiding (void)
import Foreign.Ptr
import Foreign.Storable
import KMonad.Keyboard
import KMonad.Keyboard.IO
import KMonad.Keyboard.IO.Windows.Types
--------------------------------------------------------------------------------
-- | Use the windows c-api to `grab` a keyboard
foreign import ccall "grab_kb"
grab_kb :: IO Word8
-- | Release the keyboard hook
foreign import ccall "release_kb"
release_kb :: IO Word8
-- | Pass a pointer to a buffer to wait_key, when it returns the buffer can be
-- read for the next key event.
foreign import ccall "wait_key"
wait_key :: Ptr WinKeyEvent -> IO ()
--------------------------------------------------------------------------------
-- | Data used to track `connection` to windows process
data LLHook = LLHook
{ _thread :: !(Async Word8) -- ^ The thread-id of the listen-process
, _buffer :: !(Ptr WinKeyEvent) -- ^ Buffer used to communicate with process
}
makeLenses ''LLHook
-- | Return a KeySource using the Windows low-level hook approach.
llHook :: HasLogFunc e => RIO e (Acquire KeySource)
llHook = mkKeySource llOpen llClose llRead
--------------------------------------------------------------------------------
-- | Ask windows to install a hook and allocate the reading-buffer
llOpen :: HasLogFunc e => RIO e LLHook
llOpen = do
logInfo "Registering low-level Windows keyboard hook"
liftIO $ do
tid <- async grab_kb
buf <- mallocBytes $ sizeOf (undefined :: WinKeyEvent)
pure $ LLHook tid buf
-- | Ask windows to unregister the hook and free the data-buffer
llClose :: HasLogFunc e => LLHook -> RIO e ()
llClose ll = do
logInfo "Unregistering low-level Windows keyboard hook"
liftIO $ do
_ <- release_kb
cancel $ ll^.thread -- This might not be necessary, but it is safer
free $ ll^.buffer
-- | Get a new 'KeyEvent' from Windows
--
-- NOTE: This can throw an error if the event fails to convert.
llRead :: HasLogFunc e => LLHook -> RIO e KeyEvent
llRead ll = do
we <- liftIO $ do
wait_key $ ll^.buffer
peek $ ll^.buffer
either throwIO pure $ fromWinKeyEvent we
| gelisam/kmonad |
<|start_filename|>index.spec.js<|end_filename|>
const { createMockInstance, default: otherCreateInstance } = require("./index");
const babelLike = _interopRequireDefault(require("./index"));
const thirdCreateInstance = babelLike.default;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
it("Creates mock instance for class", () => {
class Test {
a() { }
b() { }
}
const mock = createMockInstance(Test);
const mock2 = otherCreateInstance(Test);
const mock3 = thirdCreateInstance(Test);
mock.a();
mock.b("test");
mock2.a();
mock3.b();
expect(mock.a.mock.calls.length).toBe(1);
expect(mock.a).toBeCalled();
expect(mock.b).toBeCalledWith("test");
expect(mock2.a).toBeCalled();
expect(mock3.b).toBeCalled();
});
it("Creates mock instance for function", () => {
function F() { }
F.prototype.a = function () { };
F.prototype.b = function () { };
const mock = createMockInstance(F);
const mock2 = otherCreateInstance(F);
const mock3 = thirdCreateInstance(F);
mock.a();
expect(mock.a.mock.calls.length).toBe(1);
mock.b("test");
expect(mock.a).toBeCalled();
expect(mock.b).toBeCalledWith("test");
mock2.a();
mock3.b();
expect(mock2.a).toBeCalled();
expect(mock3.b).toBeCalled();
}); | darraghoriordan/jest-create-mock-instance |
<|start_filename|>app/scripts/contentscript.js<|end_filename|>
/* eslint-disable no-restricted-syntax, no-await-in-loop */
import React from 'react'
import ReactDOM from 'react-dom'
import { Client } from 'chomex'
import chunkize from 'lodash/chunk'
import find from 'lodash/find'
import ParseGithubURL from 'parse-github-url'
import { log, logError } from './common'
import UpdateNotification from './components/UpdateNotification'
import StarHOC from './components/StarHOC'
const CHUNK_SIZE = 50
const GITHUB_ISSUES_URL_PATTERN = /https:\/\/github\.com\/(.+?)\/issues\/(\d+)/
const GITHUB_ISSUES_LINKS_LIMIT = 1000
let messageClient = new Client(chrome.runtime)
function parseGithubURL (url) {
let parsed = ParseGithubURL(url)
if (parsed && parsed.host === 'github.com' && parsed.owner && parsed.name) {
let { owner, name } = parsed
return { valid: true, owner, name }
}
return { valid: false }
}
function appendStars (tuples) {
/** @type {Array<StarHOC>} */
let stars = []
for (let tuple of tuples) {
let { link, owner, name } = tuple
let starNode = document.createElement('span')
link.parentNode.insertBefore(starNode, link.nextSibling)
ReactDOM.render(<StarHOC
ref={star => stars.push(star)}
owner={owner} name={name}
/>, starNode)
}
return stars
}
async function batchUpdateChunkAsync (chunk) {
let tuples = chunk.map(star => star.tuple)
let { data: tuplesWithStar } = await messageClient.message('/stars/get/batch', { tuples })
for (let star of chunk) {
let tuple = find(tuplesWithStar, star.tuple)
if (tuple.error) {
star.updateError(true)
} else {
star.updateCount(tuple.star)
}
}
}
async function batchUpdateStarsAsync (stars) {
let chunks = chunkize(stars, CHUNK_SIZE)
for (let chunk of chunks) {
try {
await batchUpdateChunkAsync(chunk)
await messageClient.message('/rate-limit')
} catch (error) {
logError(error)
for (let star of chunk) {
star.updateError(true)
}
}
}
}
async function isAwesomeListAsync () {
let parsed = parseGithubURL(window.location.href)
if (!parsed) {
return false
}
let readme = document.querySelector('#readme')
if (!readme) {
return false
}
let { owner, name } = parsed
try {
let { data: isAwesomeList } = await messageClient.message('/awesome-list/check', { owner, name })
if (isAwesomeList) {
log(`🚨 awesome list ${owner}/${name} detected`)
return true
}
return false
} catch (error) {
logError(error)
}
}
async function attachStarsOnLinksAsync (links) {
let tuples = links
.filter(link => !link.hash) // filter out anchors: such as <a href="#foobar" />
.map(link => ({ link, ...parseGithubURL(link.href) }))
.filter(tuple => tuple.valid)
let stars = appendStars(tuples)
await batchUpdateStarsAsync(stars)
}
async function initForReadmeAsync () {
let isAwesomeList = await isAwesomeListAsync()
if (!isAwesomeList) {
return
}
/** @type {Array<HTMLElement>} */
let links = [].slice.call(document.querySelectorAll('#readme li > a'))
await attachStarsOnLinksAsync(links)
}
async function initForGithubIssuesAsync () {
try {
let { data: applyOnGithubIssues } = await messageClient.message('/apply-on-github-issues/get')
if (!applyOnGithubIssues) {
return
}
let isGithubIssues = !!window.location.href.match(GITHUB_ISSUES_URL_PATTERN)
if (!isGithubIssues) {
return
}
/** @type {Array<HTMLElement>} */
let links = [].slice.call(document.querySelectorAll('.comment-body a'))
let limitedLinks = links.slice(0, GITHUB_ISSUES_LINKS_LIMIT)
await attachStarsOnLinksAsync(limitedLinks)
} catch (error) {
logError(error)
}
}
async function initAwesomeStarsAsync () {
return Promise.all([
initForReadmeAsync(),
initForGithubIssuesAsync()
])
}
function showUpdateNotification () {
let $emptyContainer = document.createElement('div')
let $jsFlashContainer = document.getElementById('js-flash-container')
$jsFlashContainer.appendChild($emptyContainer)
ReactDOM.render(<UpdateNotification />, $emptyContainer)
}
async function checkUpdateNotificationSentAsync () {
try {
let { data: updateNotificationSent } = await messageClient.message(
'/update-notification-sent/get'
)
if (!updateNotificationSent) {
showUpdateNotification()
messageClient.message('/update-notification-sent/set', {
updateNotificationSent: true
})
}
} catch (error) {
logError(error)
}
}
checkUpdateNotificationSentAsync()
initAwesomeStarsAsync()
<|start_filename|>app/scripts/components/AccessTokenForm.js<|end_filename|>
import React from 'react'
import PropTypes from 'prop-types'
import { Box, Flex, reflex } from 'reflexbox'
import styled from 'styled-components'
import colors from '../themes/colors'
let ATFContainer = styled(Flex)`
border: 1px solid ${colors.darkGray};
`
let ATFField = styled.input`
border: 2px ${({ hasError }) => (hasError ? colors.red : 'transparent')} solid;
box-sizing: border-box;
font-size: ${({ heightInRem }) => heightInRem * 1.1}rem;
padding: ${({ heightInRem }) => heightInRem * 0.5}rem;
width: 100%;
`
let BaseATFButtonContainer = styled.div`
background: ${colors.white};
display: flex;
align-items: center;
justify-content: center;
padding: ${({ heightInRem }) => heightInRem * 0.25}rem;
`
let ATFButtonContainer = reflex(BaseATFButtonContainer)
let ATFButton = styled.button`
box-sizing: border-box;
background-color: ${({ disabled }) => (disabled ? colors.lightGray : colors.darkGray)};
border: 1px solid ${({ disabled }) => (disabled ? colors.lightGray : colors.darkGray)};
color: ${colors.white};
font-size: ${props => props.heightInRem}rem;
height: 100%;
padding: 0.25rem;
text-transform: uppercase;
width: 100%;
`
class AccessTokenForm extends React.Component {
state = { accessToken: '' }
componentWillReceiveProps ({ accessToken }) {
this.setState({ accessToken })
}
updateAccessToken = (accessToken) => {
this.setState({ accessToken })
}
render () {
let { heightInRem, hasError, saving, onSubmit } = this.props
let { accessToken } = this.state
return (
<ATFContainer>
<Box w={3 / 4}>
<ATFField
type='text'
value={accessToken}
onChange={e => this.updateAccessToken(e.target.value)}
heightInRem={heightInRem}
hasError={hasError}
/>
</Box>
<ATFButtonContainer w={1 / 4} heightInRem={heightInRem}>
<ATFButton
disabled={saving}
onClick={() => onSubmit(accessToken)}
heightInRem={heightInRem}
>Save</ATFButton>
</ATFButtonContainer>
</ATFContainer>
)
}
}
AccessTokenForm.propTypes = {
accessToken: PropTypes.string,
heightInRem: PropTypes.number,
hasError: PropTypes.bool,
onSubmit: PropTypes.func,
saving: PropTypes.bool
}
AccessTokenForm.defaultProps = {
accessToken: '',
heightInRem: 1,
hasError: false,
onSubmit: () => {},
saving: false
}
export default AccessTokenForm
<|start_filename|>app/scripts/background/chromeStorageService.js<|end_filename|>
import ChromePromise from 'chrome-promise/constructor'
import get from 'lodash/get'
import DIConstants from '../constants'
class ChromeStorageService {
KEY_UPDATE_NOTIFICATION_SENT = 'UPDATE_NOTIFICATION_SENT'
KEY_APPLY_ON_GITHUB_ISSUES = 'APPLY_ON_GITHUB_ISSUES'
/**
* @param {AwilixContainer.cradle} ctx
*/
constructor (ctx) {
this.log = ctx[DIConstants.LOG]
this.chromePromise = new ChromePromise()
}
/**
* @param {string} key
* @param {*} defaultValue
* @return {Promise<*>}
*/
async loadAsync (key, defaultValue = null) {
let valueInStorage = await this.chromePromise.storage.local.get(key)
let valueOrDefaultValue = get(valueInStorage, key, defaultValue)
this.log('📤 load', key, 'from Chrome storage:', valueOrDefaultValue)
return valueOrDefaultValue
}
/**
* @param {string} key
* @param {*} value
* @return {Promise<void>}
*/
async saveAsync (key, value) {
let payload = { [key]: value }
this.log('📥 save', key, 'to Chrome storage:', value)
return this.chromePromise.storage.local.set(payload)
}
}
export default ChromeStorageService
<|start_filename|>.storybook/webpack.config.js<|end_filename|>
const path = require('path');
module.exports = (storybookBaseConfig, configType) => {
storybookBaseConfig.module.rules.push({
test: /\.svg$/,
loader: require.resolve('file-loader'),
});
storybookBaseConfig.resolve.extensions.push('.svg');
return storybookBaseConfig;
};
<|start_filename|>app/scripts/components/UpdateNotification.js<|end_filename|>
import React from 'react'
import { version } from '../../../package.json'
export default () => (
<div>
<div className='flash flash-full flash-notice'>
<div className='container'>
<button
className='flash-close js-flash-close'
type='button'
aria-label='Dismiss this message'
>
<svg
aria-hidden='true'
className='octicon octicon-x'
height='16'
version='1.1'
viewBox='0 0 12 16'
width='12'
>
<path
fillRule='evenodd'
d='M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z'
/>
</svg>
</button>
<strong>{'Awesome Stars'}</strong>
{' has been updated to '}
<strong>{version}</strong>
{'! For more information, please check out CHANGELOG at '}
<strong>
<a href='https://github.com/henry40408/awesome-stars/releases'>
{'GitHub Releases'}
</a>
</strong>
{'.'}
</div>
</div>
</div>
)
<|start_filename|>app/stories/index.js<|end_filename|>
import React from 'react'
import { action } from '@storybook/addon-actions'
import { withKnobs, boolean, number } from '@storybook/addon-knobs'
import { storiesOf, addDecorator } from '@storybook/react'
import styled from 'styled-components'
import AccessTokenForm from '../scripts/components/AccessTokenForm'
import RateLimit from '../scripts/components/RateLimit'
import Star from '../scripts/components/Star'
import UpdateNotification from '../scripts/components/UpdateNotification'
const MAXIMUM = 5000
addDecorator(withKnobs)
const RateLimitContainer = styled.div`
background-color: ${({ inverse }) => (inverse ? 'black' : 'white')};
padding: 1rem 0;
`
storiesOf('RateLimit', module).add('default', () => {
const inverse = boolean('Inverse', false)
return (
<RateLimitContainer inverse={inverse}>
<RateLimit
hasError={boolean('Has error?',false)}
inverse={inverse}
remaining={number('Remaining', MAXIMUM)}
total={number('Total', MAXIMUM)}
heightInRem={number('Height in rem', 1)}
/>
</RateLimitContainer>
)
})
storiesOf('AccessTokenForm', module).add('default', () => (
<AccessTokenForm
accessToken='accessToken'
heightInRem={number('Height in rem', 1)}
hasError={boolean('Has error?', false)}
onSubmit={accessToken => action(`access token submitted: ${accessToken}`)}
saving={boolean('Saving', false)}
/>
))
storiesOf('Star', module).add('default', () => (
<Star
count={number('Count', 1000)}
hasError={boolean('Has error?', false)}
loading={boolean('Loading', false)}
/>
))
storiesOf('UpdateNotification', module).add('default', () => <UpdateNotification />)
<|start_filename|>app/_locales/zh_TW/messages.json<|end_filename|>
{
"appDescription": {
"message": "Awesome Stars 讓你可以直接在 Awesome List 上看到專案的星星數",
"description": "The description of the application"
},
"applyOnGithubIssues": {
"message": "在 GitHub Issues 上顯示星星",
"description": "Content menu item"
},
"blue": {
"message": "藍色",
"description": "Color"
},
"colorForLess": {
"message": "低於 $COUNT$ 會顯示 $COLOR$",
"description": "Option page string",
"placeholders": {
"color": {
"content": "$1",
"example": "Blue"
},
"count": {
"content": "$2",
"example": "1,000"
}
}
},
"colorForMore": {
"message": "高於 $COUNT$ 會顯示 $COLOR$",
"description": "Option page string",
"placeholders": {
"color": {
"content": "$1",
"example": "Orange"
},
"count": {
"content": "$2",
"example": "10,000"
}
}
},
"colorForRange": {
"message": "介於 $MIN$ 與 $MAX$ 會顯示$COLOR$",
"description": "Option page string",
"placeholders": {
"color": {
"content": "$1",
"example": "White"
},
"min": {
"content": "$2",
"example": "1,000"
},
"max": {
"content": "$3",
"example": "4,999"
}
}
},
"ifYouDontHaveOneYet": {
"message": "如果你還沒有申請過 access token,",
"description": "Option page string"
},
"getAnAccessToken": {
"message": "請前往 GitHub 產生一組",
"description": "Option page string"
},
"githubDocumentation": {
"message": "GitHub 文件",
"description": "Option page string"
},
"menuRateLimit": {
"message": "請求配額: $REMAINING$ / $LIMIT$ ($RATIO$)",
"description": "Rate limit on context menu",
"placeholders": {
"remaining": {
"content": "$1",
"example": "5,000"
},
"limit": {
"content": "$2",
"example": "5,000"
},
"ratio": {
"content": "$3",
"example": "100%"
}
}
},
"opHowHotAreThoseStars": {
"message": "不同顏色的星星代表什麼意思?",
"description": "Option page string"
},
"opHowHotAreThoseStarsDescription": {
"message": "目前共有四種顏色,Awesome Stars 會根據星星的數量變換星星標籤的顏色:",
"description": "Option page string"
},
"orange": {
"message": "橘色",
"description": "Color"
},
"rateLimit": {
"message": "請求配額",
"description": "Option page string"
},
"rateLimitDescription": {
"message": "透過 Basic Auth 或 OAuth(包括 access token),我們一小時內可以可以對 GitHub 送出 5,000 次請求。",
"description": "Option page string"
},
"pleaseDoNotSelectAnyScopes": {
"message": "產生時請不要選擇任何的 scope!",
"description": "Option page string"
},
"setupAccessToken": {
"message": "設定 access token",
"description": "Option page string"
},
"white": {
"message": "白色",
"description": "Color"
},
"whyDoYouNeedAnAccessToken": {
"message": "為什麼你會需要 Access Token?",
"description": "Option page string"
},
"whyDoYouNeedAnAccessTokenDescription1": {
"message": "根據 ",
"description": "Option page string"
},
"whyDoYouNeedAnAccessTokenDescription2": {
"message": ",在沒有經過 Basic Auth 或 OAuth 認證的情況下,同一個 IP、一小時內只能發出 60 次請求。一項 awesome list 專案表列的專案數量往往超過這個數目,因此 Awesome Stars 需要一組 access token 才能正常運作。",
"description": "Option page string"
},
"yellow": {
"message": "黃色",
"description": "Color"
}
}
<|start_filename|>app/scripts/common.js<|end_filename|>
import format from 'date-fns/format'
function currentTimestamp () {
return format(new Date(), 'YYYY-MM-DDTHH:mm:ssZ')
}
export function log (...args) {
if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line no-console
console.log(currentTimestamp(), ...args)
}
}
export function logError (...args) {
// eslint-disable-next-line no-console
console.error(currentTimestamp(), '❌', ...args)
}
<|start_filename|>app/scripts/constants.js<|end_filename|>
/**
* R: Repository
* S: Service
*/
export default {
MESSAGE_ROUTER: Symbol('router'),
R_ACCESS_TOKEN: Symbol('access token repository'),
S_CHROME_STORAGE: Symbol('chrome storage service'),
S_COMMON: Symbol('common service'),
S_CONTEXT_MENU: Symbol('context menu service'),
S_GITHUB: Symbol('github service'),
LOG: Symbol('log function')
}
<|start_filename|>app/scripts/components/OptionPage.js<|end_filename|>
import React from 'react'
import { Client } from 'chomex'
import { Box, Flex } from 'reflexbox'
import styled from 'styled-components'
import { version } from '../../../package.json'
import colors from '../themes/colors'
import AccessTokenForm from '../components/AccessTokenForm'
import RateLimit from '../components/RateLimit'
import { logError } from '../common'
let Container = styled(Flex)`
font-family: 'Roboto', Helvetica, sans-serif;
font-weight: light;
max-width: 960px;
`
let Header = styled(Box)`
font-family: 'Roboto Slab', sans-serif;
letter-spacing: 0.0625rem;
text-align: center;
& > h1 {
font-size: 2rem;
letter-spacing: 0.1rem;
text-transform: uppercase;
}
& > h2 {
font-size: 1rem;
}
`
let Main = styled(Box)`
margin: 0 0 1rem;
h3,
h4 {
font-family: 'Roboto Slab', sans-serif;
margin: 0.75rem 0;
}
p {
line-height: 1.5;
margin: 0.5rem 0;
}
`
let Footer = styled(Box)`
font-family: 'Roboto Slab', sans-serif;
text-align: center;
line-height: 1.5;
`
let ColorList = styled.ul`
list-style: none;
padding: 0;
& > li::before {
content: '-';
margin: 0 1rem 0 0;
}
& > li {
line-height: 1.618;
}
`
let ColorItem = styled.li`
color: ${({ color }) => color || colors.white};
`
let StarsCurve = styled.img`
margin: -7.5rem 0 0;
`
let AlertText = styled.span`
color: ${colors.red};
`
let CapitalizedH3 = styled.h3`
text-transform: capitalize;
`
function capitalize (str) {
return str.replace(/\b\w/, l => l.toUpperCase())
}
class OptionPage extends React.Component {
constructor (props) {
super(props)
this.client = new Client(chrome.runtime)
}
state = {
accessToken: '',
hasError: false,
limit: 0,
remaining: 0,
saving: false
}
componentDidMount () {
this._loadInitialDataAsync()
}
_getMessage = (messageName, subsitutions = []) => (
chrome.i18n.getMessage(messageName, subsitutions)
)
_loadAccessTokenAsync = async () => {
let { data: accessToken } = await this.client.message('/access-token/get')
return { accessToken }
}
_loadInitialDataAsync = async () => {
try {
this.setState({ saving: true })
let { accessToken } = await this._loadAccessTokenAsync()
let { limit, remaining } = await this._loadRateLimitAsync()
this.setState({ accessToken, hasError: false, limit, remaining, saving: false })
} catch (error) {
logError(error)
this.setState({ hasError: true })
} finally {
this.setState({ saving: false })
}
}
_loadRateLimitAsync = async () => {
let { data: { remaining, limit } } = await this.client.message('/rate-limit')
return { limit, remaining }
}
_saveAccessTokenAsync = async (accessToken) => {
try {
this.setState({ saving: true })
await this.client.message('/access-token/set', { accessToken })
this.setState({ accessToken })
let { invalid, limit, remaining } = await this._loadRateLimitAsync()
this.setState({ hasError: false, invalid, limit, remaining, saving: false })
} catch (error) {
logError(error)
this.setState({ hasError: true })
} finally {
this.setState({ saving: false })
}
}
renderLeftPane = () => (
<Box w={[58 / 60, 26 / 60, 28 / 60]} p={2}>
<h3>{this._getMessage('opHowHotAreThoseStars')}</h3>
<p>{this._getMessage('opHowHotAreThoseStarsDescription')}</p>
<ColorList>
<ColorItem color={colors.lightBlue}>{
this._getMessage('colorForLess', [
capitalize(this._getMessage('blue')),
'1,000'
])
}</ColorItem>
<ColorItem color={colors.white}>{
this._getMessage('colorForRange', [
capitalize(this._getMessage('white')),
'1,000',
'4,999'
])
}</ColorItem>
<ColorItem color={colors.yellow}>{
this._getMessage('colorForRange', [
capitalize(this._getMessage('yellow')),
'5,000',
'9,999'
])
}</ColorItem>
<ColorItem color={colors.orange}>{
this._getMessage('colorForMore', [
capitalize(this._getMessage('orange')),
'10,000'
])
}</ColorItem>
</ColorList>
<StarsCurve src='../../images/stars-curve.svg' alt='Stars Curve' width='100%' />
</Box>
)
renderRightPane = () => {
let { accessToken, hasError, remaining, limit, saving } = this.state
return (
<Box w={[58 / 60, 26 / 60, 28 / 60]} p={2}>
<CapitalizedH3>{this._getMessage('setupAccessToken')}</CapitalizedH3>
<AccessTokenForm
accessToken={accessToken}
hasError={hasError}
onSubmit={this._saveAccessTokenAsync}
saving={saving}
/>
<p>
{this._getMessage('ifYouDontHaveOneYet')}
<a href='https://github.com/settings/tokens/new?description=Awesome%20Stars'>
{this._getMessage('getAnAccessToken')}
</a>
<br />
<AlertText>{this._getMessage('pleaseDoNotSelectAnyScopes')}</AlertText>
</p>
<h3>{this._getMessage('rateLimit')}</h3>
<RateLimit
inverse
hasError={hasError}
remaining={remaining}
total={limit}
heightInRem={2.5}
/>
<p>
<small>{this._getMessage('rateLimitDescription')}</small>
</p>
<h4>{this._getMessage('whyDoYouNeedAnAccessToken')}</h4>
<p>
<small>
{this._getMessage('whyDoYouNeedAnAccessTokenDescription1')}
<a href='https://developer.github.com/v3/#rate-limiting'>
{this._getMessage('githubDocumentation')}
</a>
{this._getMessage('whyDoYouNeedAnAccessTokenDescription2')}
</small>
</p>
</Box>
)
}
render () {
return (
<Container column>
<Header p={2}>
<img src='../../images/options-logo.png' alt='Awesome Stars logo' />
<h1>{this._getMessage('appName')}</h1>
<h2>{this._getMessage('appDescription')}</h2>
</Header>
<Main>
<Flex wrap w={1}>
{this.renderLeftPane()}
{this.renderRightPane()}
</Flex>
</Main>
<Footer p={2}>
<small>
{new Date().getFullYear()} All rights reserved. Made by <NAME> with ❤.<br />
{`Version ${version}`}
</small>
</Footer>
</Container>
)
}
}
export default OptionPage
<|start_filename|>app/scripts/background/contextMenuService.js<|end_filename|>
import includes from 'lodash/includes'
class ContextMenuService {
MENU_RATE_LIMIT = 'rateLimit'
MENU_APPLY_ON_GITHUB_ISSUES = 'applyOnGithubIssues'
constructor (ctx) {
this.menuIds = []
}
upsert (id, options) {
if (!includes(this.menuIds, id)) {
chrome.contextMenus.create({id, ...options})
this.menuIds.push(id)
}
chrome.contextMenus.update(id, options)
}
}
export default ContextMenuService
<|start_filename|>app/scripts/background/messageRouter.js<|end_filename|>
import { Router } from 'chomex'
import ChromePromise from 'chrome-promise/constructor'
import DIConstants from '../constants'
class MessageRouter {
constructor (ctx) {
/** @type {AccessTokenRepository} */
this.accessToken = ctx[DIConstants.R_ACCESS_TOKEN]
/** @type {GithubService} */
this.github = ctx[DIConstants.S_GITHUB]
/** @type {ChromeStorageService} */
this.storage = ctx[DIConstants.S_CHROME_STORAGE]
this.chromePromise = new ChromePromise()
this.log = ctx[DIConstants.LOG]
this.messageRouter = new Router()
this.registerAll()
this.github.fetchRateLimitAsync()
}
register (route, fnAsync) {
return this.messageRouter.on(route, async (message) => {
this.log('📣', route, 'called with', message)
try {
return { status: 200, data: await fnAsync(message) }
} catch (error) {
return { status: 500, error: error.message }
}
})
}
registerAll () {
this.register('/access-token/get', async () => this.accessToken.loadAsync())
this.register('/access-token/set', async (message) => {
let { accessToken: token } = message
return this.accessToken.saveAsync(token)
})
this.register('/awesome-list/check', async (message) => {
let { owner, name } = message
let tabs = await this.chromePromise.tabs.query({ active: true })
if (tabs.length > 0) {
let { id } = tabs[0]
chrome.pageAction.show(id)
}
return this.github.isAwesomeListAsync({ owner, name })
})
this.register('/rate-limit', async () => this.github.fetchRateLimitAsync())
this.register('/stars/get/batch', async (message) => {
let { tuples } = message
return this.github.fetchMultipleStarCountAsync(tuples)
})
this.register('/update-notification-sent/get', async () =>
this.storage.loadAsync(this.storage.KEY_UPDATE_NOTIFICATION_SENT)
)
this.register('/update-notification-sent/set', async (message) => {
let { updateNotificationSent } = message
return this.storage.saveAsync(
this.storage.KEY_UPDATE_NOTIFICATION_SENT,
updateNotificationSent
)
})
this.register('/apply-on-github-issues/get', async () =>
this.storage.loadAsync(this.storage.KEY_APPLY_ON_GITHUB_ISSUES, false)
)
this.register('/apply-on-github-issues/set', async (message) => {
let { applyOnGithubIssues } = message
return this.storage.saveAsync(
this.storage.KEY_APPLY_ON_GITHUB_ISSUES,
applyOnGithubIssues
)
})
}
start () {
chrome.runtime.onMessage.addListener(this.messageRouter.listener())
}
}
export default MessageRouter
<|start_filename|>app/scripts/themes/colors.js<|end_filename|>
export default {
blue: '#4a94fa',
darkGray: '#222222',
gray: '#3f3f3f',
green: '#d4fc45',
lightBlue: '#c4f7ff',
lightGray: '#999999',
orange: '#ecab20',
red: '#ff3e00',
white: '#ffffff',
yellow: '#f9ef14'
}
<|start_filename|>app/scripts/background/accessTokenRepository.js<|end_filename|>
import DIConstants from '../constants'
class AccessTokenRepository {
KEY_ACCESS_TOKEN = 'ACCESS_TOKEN'
constructor (ctx) {
/** @type {ChromeStorageService} */
this.storage = ctx[DIConstants.S_CHROME_STORAGE]
this.changed = false
}
/**
* @return {Promise<string|null>}
*/
async loadAsync () {
return this.storage.loadAsync(this.KEY_ACCESS_TOKEN, '')
}
/**
* @param {string} accessToken
*/
async saveAsync (accessToken) {
await this.storage.saveAsync(this.KEY_ACCESS_TOKEN, accessToken)
this.changed = true
}
}
export default AccessTokenRepository
<|start_filename|>app/_locales/en/messages.json<|end_filename|>
{
"appName": {
"message": "Awesome Stars",
"description": "The name of the application"
},
"appShortName": {
"message": "aws_stars",
"description": "The short_name (maximum of 12 characters recommended) is a short version of the app's name."
},
"appDescription": {
"message": "Awesome Stars is a chrome extension that shows you stars of repository on awesome list.",
"description": "The description of the application"
},
"applyOnGithubIssues": {
"message": "Apply on GitHub Issues",
"description": "Content menu item"
},
"pageActionTitle": {
"message": "Awesome Stars",
"description": "The title of the browser action button"
},
"blue": {
"message": "blue",
"description": "Color"
},
"colorForLess": {
"message": "$COLOR$ for less than $COUNT$.",
"description": "Option page string",
"placeholders": {
"color": {
"content": "$1",
"example": "Blue"
},
"count": {
"content": "$2",
"example": "1,000"
}
}
},
"colorForMore": {
"message": "$COLOR$ for more than $COUNT$.",
"description": "Option page string",
"placeholders": {
"color": {
"content": "$1",
"example": "Orange"
},
"count": {
"content": "$2",
"example": "10,000"
}
}
},
"colorForRange": {
"message": "$COLOR$ for $MIN$ to $MAX$.",
"description": "Option page string",
"placeholders": {
"color": {
"content": "$1",
"example": "White"
},
"min": {
"content": "$2",
"example": "1,000"
},
"max": {
"content": "$3",
"example": "4,999"
}
}
},
"ifYouDontHaveOneYet": {
"message": "If you don't have one yet, ",
"description": "Option page string"
},
"getAnAccessToken": {
"message": "get an access token",
"description": "Option page string"
},
"githubDocumentation": {
"message": "GitHub documentation",
"description": "Option page string"
},
"menuRateLimit": {
"message": "Rate Limit: $REMAINING$ / $LIMIT$ ($RATIO$)",
"description": "Rate limit on context menu",
"placeholders": {
"remaining": {
"content": "$1",
"example": "5,000"
},
"limit": {
"content": "$2",
"example": "5,000"
},
"ratio": {
"content": "$3",
"example": "100%"
}
}
},
"opHowHotAreThoseStars": {
"message": "How Hot are Those Stars?",
"description": "Option page string"
},
"opHowHotAreThoseStarsDescription": {
"message": "There are four levels for the stars of repository. Awesome Stars changes its color according to star count:",
"description": "Option page string"
},
"orange": {
"message": "orange",
"description": "Color"
},
"rateLimit": {
"message": "Rate Limit",
"description": "Option page string"
},
"rateLimitDescription": {
"message": "For requests using Basic Authentication or OAuth (including access token), you can make up to 5,000 requests per hour.",
"description": "Option page string"
},
"pleaseDoNotSelectAnyScopes": {
"message": "Please DO NOT select any scopes!",
"description": "Option page string"
},
"setupAccessToken": {
"message": "setup access token",
"description": "Option page string"
},
"white": {
"message": "white",
"description": "Color"
},
"whyDoYouNeedAnAccessToken": {
"message": "Why do You Need an Access Token?",
"description": "Option page string"
},
"whyDoYouNeedAnAccessTokenDescription1": {
"message": "According to ",
"description": "Option page string"
},
"whyDoYouNeedAnAccessTokenDescription2": {
"message": ". For unauthenticated requests, the rate limit allows you to make up to 60 requests per hour. Unauthenticated requests are associated with your IP address, and not the user making requests. Awesome Stars can only works properly with an access token.",
"description": "Option page string"
},
"yellow": {
"message": "yellow",
"description": "Color"
}
}
<|start_filename|>app/scripts/options.js<|end_filename|>
import React from 'react'
import ReactDOM from 'react-dom'
import { injectGlobal } from 'styled-components'
import colors from './themes/colors'
import OptionPage from './components/OptionPage'
// eslint-disable-next-line no-unused-expressions
injectGlobal`
html,
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
}
body {
background-image: url('../images/options-background.svg');
color: ${colors.white};
}
a {
color: ${colors.orange};
}
#container {
align-items: center;
display: flex;
min-height: 100vh;
justify-content: center;
width: 100vw;
}
`
ReactDOM.render(<OptionPage />, document.getElementById('container'))
<|start_filename|>app/scripts/components/Star.js<|end_filename|>
/* eslint-disable global-require */
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import colors from '../themes/colors'
let blueStar
let orangeStar
let whiteStar
let yellowStar
if (chrome && chrome.extension && chrome.extension.getURL) {
blueStar = chrome.extension.getURL('images/star-blue.svg')
orangeStar = chrome.extension.getURL('images/star-orange.svg')
whiteStar = chrome.extension.getURL('images/star-white.svg')
yellowStar = chrome.extension.getURL('images/star-yellow.svg')
} else {
blueStar = require('../../images/star-blue.svg')
orangeStar = require('../../images/star-orange.svg')
whiteStar = require('../../images/star-white.svg')
yellowStar = require('../../images/star-yellow.svg')
}
let starIcons = {
[colors.blue]: blueStar,
[colors.orange]: orangeStar,
[colors.white]: whiteStar,
[colors.yellow]: yellowStar
}
let StarBadge = styled.span`
background-color: ${colors.gray};
border-radius: 0.75rem;
font-size: 0.75rem;
margin: 0 0 0 0.25rem;
padding: 0.25rem 0.5rem;
`
let StarIcon = styled.img`
background-color: transparent !important;
margin: 0 0.25rem 0 0;
`
let StarText = styled.span`
color: ${({ color }) => color};
`
class Star extends React.Component {
static propTypes = {
count: PropTypes.number,
hasError: PropTypes.bool,
loading: PropTypes.bool
}
static defaultProps = {
count: 0,
hasError: false,
loading: false
}
colorsFromCount = (count) => {
switch (true) {
case count >= 10000:
return { star: colors.orange, text: colors.orange }
case count < 10000 && count >= 5000:
return { star: colors.yellow, text: colors.yellow }
case count < 5000 && count >= 1000:
return { star: colors.white, text: colors.white }
default:
return { star: colors.blue, text: colors.lightBlue }
}
}
renderAlt = (starColor) => {
let { hasError } = this.props
if (hasError) {
return 'something went wrong'
}
return `${starColor} star`
}
renderText = () => {
let formatter = new Intl.NumberFormat('en-US')
let { count, hasError, loading } = this.props
if (loading) {
return '...'
}
if (hasError) {
return '\u26A0'
}
return formatter.format(count)
}
render () {
let { count } = this.props
let { star: starColor, text: textColor } = this.colorsFromCount(count)
return (
<StarBadge>
<StarIcon src={starIcons[starColor]} alt={this.renderAlt(starColor)} />
<StarText color={textColor}>{this.renderText()}</StarText>
</StarBadge>
)
}
}
export default Star
<|start_filename|>app/scripts/background/githubService.js<|end_filename|>
import ApolloClient from 'apollo-boost'
import { cacheAdapterEnhancer } from 'axios-extensions'
import axios from 'axios/index'
import gql from 'graphql-tag'
import includes from 'lodash/includes'
import set from 'lodash/set'
import LRU from 'lru-cache'
import DIConstants from '../constants'
class GithubService {
AWESOME_LIST_URL = 'https://raw.githubusercontent.com/sindresorhus/awesome/master/readme.md'
LRU_MAX_AGE = 60 * 60 * 1000 // = 1 hour
RATE_LIMIT_THRESHOLD = 0.5
constructor (ctx) {
this.log = ctx[DIConstants.LOG]
/** @type {AccessTokenRepository} */
this.accessToken = ctx[DIConstants.R_ACCESS_TOKEN]
/** @type {ContextMenuService} */
this.contextMenu = ctx[DIConstants.S_CONTEXT_MENU]
/** @type {ApolloClient} */
this.apolloClient = null
/** @type {AxiosInstance} */
this.restfulClient = null
let defaultCache = LRU({ maxAge: this.LRU_MAX_AGE })
/** @type {AxiosInstance} */
this.rawRestfulClient = axios.create({
baseURL: `https://api.github.com`,
adapter: cacheAdapterEnhancer(axios.defaults.adapter, { defaultCache })
})
}
async _buildClients () {
/** @type {string} */
let token = await this.accessToken.loadAsync()
if (!this.apolloClient || !this.restfulClient || this.accessToken.changed) {
let headers = {}
let request = async () => {}
if (token) {
headers = { ...headers, Authorization: `Bearer ${token}` }
request = async operation => operation.setContext({ headers })
}
// suppress any GraphQL errors
let onError = ({ response }) => set(response, 'errors', [])
/** @type {ApolloClient} */
this.apolloClient = new ApolloClient({
uri: 'https://api.github.com/graphql',
request,
onError
})
let defaultCache = LRU({ maxAge: this.LRU_MAX_AGE })
/** @type {AxiosInstance} */
this.restfulClient = axios.create({
baseURL: 'https://api.github.com',
headers,
adapter: cacheAdapterEnhancer(axios.defaults.adapter, { defaultCache })
})
this.accessToken.changed = false
}
}
async fetchAwesomeListAsync () {
let { data: awesomeList } = await this.rawRestfulClient.get(this.AWESOME_LIST_URL)
let awesomeListSize = (awesomeList.length / 1024).toFixed(3)
this.log('📄 fetch awesome list', awesomeListSize, 'KB(s)')
return awesomeList
}
async fetchRateLimitAsync () {
await this._buildClients()
let numberFormatter = new Intl.NumberFormat('en-US')
let percentFormatter = new Intl.NumberFormat('en-US', { style: 'percent' })
let { remaining, limit } = await this.selectRateLimitAsync()
this.log('🚦 rate limit:', { remaining, limit })
let title = chrome.i18n.getMessage('menuRateLimit', [
numberFormatter.format(remaining),
numberFormatter.format(limit),
percentFormatter.format(remaining / limit)
])
this.contextMenu.upsert(this.contextMenu.MENU_RATE_LIMIT, { title })
return { remaining, limit }
}
async selectRateLimitAsync () {
let [graphql, restful] = await Promise.all([
this._fetchGraphQLRateLimitAsync(),
this._fetchRESTfulRateLimitAsync()
])
let { remaining: restfulRemaining } = restful
let { remaining: graphqlRemaining } = graphql
let { remaining, limit } = restfulRemaining < graphqlRemaining ? restful : graphql
return { remaining, limit }
}
async _fetchGraphQLRateLimitAsync () {
let query = gql`query RateLimit { rateLimit { remaining limit } }`
let response = await this.apolloClient.query({ query })
let { rateLimit: { remaining, limit } } = response.data
return { remaining, limit }
}
async _fetchRESTfulRateLimitAsync () {
let response = await this.restfulClient.get('/rate_limit')
let { rate: { remaining, limit } } = response.data
return { remaining, limit }
}
async fetchMultipleStarCountAsync (tuples) {
await this._checkRateLimitAsync()
let cues = GithubService._buildCuesFromTuples(tuples)
let query = GithubService._buildGraphQLQueryFromCues(cues)
let { data } = await this.apolloClient.query({ query })
if (process.env.NODE_ENV === 'development') {
let entries = Object.entries(data).filter(tuple => !!tuple[1])
this.log('🌀', entries.length, 'repositorie(s) fetched')
}
return this._buildTuplesFromGraphQLResponseAsync(cues, data)
}
async _checkRateLimitAsync () {
// threshold to prevent the extension to use all rate limit
let { remaining, limit } = await this.fetchRateLimitAsync()
if (limit === 0 || remaining / limit <= this.RATE_LIMIT_THRESHOLD) {
throw new Error(
`rate limit ${remaining}/${limit} is below threshold ${this.RATE_LIMIT_THRESHOLD}`
)
}
}
static _buildCuesFromTuples (tuples) {
return tuples.map((tuple, index) => ({ alias: `repository${index}`, ...tuple }))
}
static _buildGraphQLQueryFromCues (cues) {
return gql`query Repositories {
${cues.map(GithubService._buildGraphQLFromCue).join('\n')}
}`
}
static _buildGraphQLFromCue (cue) {
let { alias, owner, name } = cue
return `${alias}: repository(owner: "${owner}", name: "${name}") {
owner { login }
name
stargazers { totalCount }
}`
}
async _buildTuplesFromGraphQLResponseAsync (cues, data) {
return Promise.all(cues.map(async cue => {
let { alias, owner, name } = cue
if (data[alias]) {
let { stargazers: { totalCount } } = data[alias]
return { owner, name, star: totalCount }
}
// repository not found, possibly renamed
let maybeStar = await this._fetchStarCountFromRESTfulAPIAsync(owner, name)
return { owner, name, ...maybeStar }
}))
}
async _fetchStarCountFromRESTfulAPIAsync (owner, name) {
try {
this.log('🆖 missing repository', owner, name, 'found, fallback to RESTful')
let response = await this.restfulClient.get(`https://api.github.com/repos/${owner}/${name}`)
let { data } = response
let { stargazers_count: stargazersCount } = data
return { star: parseInt(stargazersCount, 10) }
} catch (error) {
return { error: error.message }
}
}
async isAwesomeListAsync ({ owner, name }) {
let awesomeList = await this.fetchAwesomeListAsync()
return includes(awesomeList, `${owner}/${name}`)
}
}
export default GithubService
<|start_filename|>app/scripts/background.js<|end_filename|>
import * as awilix from 'awilix'
import { version } from '../../package.json'
import { log } from './common'
import DIConstants from './constants'
import AccessTokenRepository from './background/accessTokenRepository'
import ChromeStorageService from './background/chromeStorageService'
import ContextMenuService from './background/contextMenuService'
import GithubService from './background/githubService'
import MessageRouter from './background/messageRouter'
if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line global-require,import/no-extraneous-dependencies
require('chromereload/devonly')
}
/** @type {AwilixContainer} */
let container = awilix.createContainer({
injectionMode: awilix.InjectionMode.PROXY
})
container.register({
[DIConstants.LOG]: awilix.asValue(log),
[DIConstants.MESSAGE_ROUTER]: awilix.asClass(MessageRouter).singleton(),
[DIConstants.R_ACCESS_TOKEN]: awilix.asClass(AccessTokenRepository).singleton(),
[DIConstants.S_CHROME_STORAGE]: awilix.asClass(ChromeStorageService),
[DIConstants.S_CONTEXT_MENU]: awilix.asClass(ContextMenuService).singleton(),
[DIConstants.S_GITHUB]: awilix.asClass(GithubService)
})
/** @type {ChromeStorageService} */
let storageService = container.resolve(DIConstants.S_CHROME_STORAGE)
/** @type {MessageRouter} */
let messageRouter = container.resolve(DIConstants.MESSAGE_ROUTER)
/** @type {ContextMenuService} */
let contextMenuService = container.resolve(DIConstants.S_CONTEXT_MENU)
async function applyOnGithubIssuesClickListener () {
let checked = !await storageService.loadAsync(storageService.KEY_APPLY_ON_GITHUB_ISSUES)
await storageService.saveAsync(storageService.KEY_APPLY_ON_GITHUB_ISSUES, checked)
contextMenuService.upsert(contextMenuService.MENU_APPLY_ON_GITHUB_ISSUES, { checked })
}
async function initializeExtensionAsync () {
chrome.runtime.onInstalled.addListener(async (reason, previousVersion) => {
let isUpdate = reason === 'update' && previousVersion !== version
if (process.env.NODE_ENV === 'development') {
// chrome.runtime.openOptionsPage()
}
// reset update notification state...
// 1. in development environment
// 2. when extension is successfully upgraded
if (process.env.NODE_ENV === 'development' || isUpdate) {
return storageService.saveAsync(storageService.KEY_UPDATE_NOTIFICATION_SENT, false)
}
return true
})
let checked = !!await storageService.loadAsync(storageService.KEY_APPLY_ON_GITHUB_ISSUES)
contextMenuService.upsert(contextMenuService.MENU_RATE_LIMIT, {
type: 'normal',
contexts: ['page_action'],
title: 'Rate Limit: N/A',
enabled: false
})
contextMenuService.upsert(contextMenuService.MENU_APPLY_ON_GITHUB_ISSUES, {
type: 'checkbox',
title: chrome.i18n.getMessage('applyOnGithubIssues'),
contexts: ['page_action'],
onclick: applyOnGithubIssuesClickListener,
checked
})
}
function main () {
initializeExtensionAsync()
messageRouter.start()
}
main()
<|start_filename|>app/scripts/components/RateLimit.js<|end_filename|>
import React from 'react'
import PropTypes from 'prop-types'
import { Flex, reflex } from 'reflexbox'
import styled, { keyframes } from 'styled-components'
import colors from '../themes/colors'
let RLFillColor = ({ percentage }) => {
if (percentage >= 50) {
return colors.green
} else if (percentage > 2 && percentage < 50) {
return colors.yellow
}
return colors.red
}
let RLFilling = ({ percentage }) => keyframes`
from {
background-color: ${colors.red};
width: 0%;
}
to {
background-color: ${RLFillColor({ percentage })};
width: ${percentage}%;
}
`
let BaseRLMeterContainer = styled.div`
border: 1px white solid;
height: ${({ heightInRem }) => heightInRem}rem;
`
let RLMeterContainer = reflex(BaseRLMeterContainer)
let BaseRLMeter = styled.div`
animation: 1.618s ease 0s 1 normal forwards running
${({ percentage }) => RLFilling({ percentage })};
height: 100%;
width: ${({ percentage }) => percentage}%;
`
let RLMeter = reflex(BaseRLMeter)
let BaseRLNumber = styled.div`
color: ${({ inverse }) => (inverse ? colors.white : colors.darkGray)};
font-size: ${({ heightInRem }) => heightInRem * (heightInRem > 1 ? 0.5 : 0.9)}rem;
display: flex;
align-items: center;
justify-content: center;
`
let RLNumber = reflex(BaseRLNumber)
let RateLimit = ({ heightInRem, hasError, inverse, remaining, total }) => {
let formatter = new Intl.NumberFormat('en-US')
let ratio = 0
let formatted = 'N/A'
if (!hasError) {
ratio = total === 0 ? 0 : remaining / total
formatted = formatter.format(remaining)
}
return (
<Flex>
<RLMeterContainer w={3 / 4} heightInRem={heightInRem}>
<RLMeter inverse={inverse} percentage={ratio * 100} />
</RLMeterContainer>
<RLNumber w={1 / 4} heightInRem={heightInRem} inverse={inverse}>
{formatted}
</RLNumber>
</Flex>
)
}
RateLimit.propTypes = {
heightInRem: PropTypes.number,
hasError: PropTypes.bool,
inverse: PropTypes.bool,
remaining: PropTypes.number,
total: PropTypes.number
}
RateLimit.defaultProps = {
heightInRem: 1,
hasError: false,
inverse: false,
remaining: 0,
total: 0
}
module.exports = RateLimit
<|start_filename|>app/scripts/components/StarHOC.js<|end_filename|>
import React from 'react'
import PropTypes from 'prop-types'
import Star from './Star'
class StarHOC extends React.Component {
static propTypes = {
owner: PropTypes.string.isRequired,
name: PropTypes.string.isRequired
}
state = { count: 0, hasError: false, loading: true }
get tuple () {
return {
owner: this.props.owner,
name: this.props.name
}
}
updateCount = count => {
this.setState({ count, loading: false })
}
updateError = hasError => {
this.setState({ hasError, loading: false })
}
render () {
let { count, hasError, loading } = this.state
return <Star count={count} hasError={hasError} loading={loading} />
}
}
export default StarHOC
<|start_filename|>tasks/images.js<|end_filename|>
import gulp from 'gulp'
import gulpif from 'gulp-if'
import imagemin from 'gulp-imagemin'
import livereload from 'gulp-livereload'
import args from './lib/args'
gulp.task('images', () => {
return gulp.src('app/images/**/*')
.pipe(gulpif(args.production, imagemin()))
.pipe(gulp.dest(`dist/${args.vendor}/images`))
.pipe(gulpif(args.watch, livereload()))
}) | andriyor/awesome-stars |
<|start_filename|>cli/cli_parser.hpp<|end_filename|>
/* Copyright (c) 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <functional>
#include <string>
#include <unordered_map>
#include <utility>
namespace Fossilize
{
class CLIParser;
struct CLICallbacks
{
void add(const char *cli, const std::function<void(CLIParser &)> &func)
{
callbacks[cli] = func;
}
std::unordered_map<std::string, std::function<void(CLIParser &)>> callbacks;
std::function<void()> error_handler;
std::function<void(const char *)> default_handler;
};
class CLIParser
{
public:
CLIParser(CLICallbacks cbs_, int argc_, char *argv_[]);
bool parse();
void end();
unsigned next_uint();
int next_sint();
double next_double();
const char *next_string();
bool is_ended_state() const
{
return ended_state;
}
void ignore_unknown_arguments()
{
unknown_argument_is_default = true;
}
private:
CLICallbacks cbs;
int argc;
char **argv;
bool ended_state = false;
bool unknown_argument_is_default = false;
};
}
<|start_filename|>cli/fossilize_convert_db.cpp<|end_filename|>
/* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "fossilize_db.hpp"
#include <memory>
#include <vector>
#include "layer/utils.hpp"
#include <cstdlib>
using namespace Fossilize;
static void print_help()
{
LOGI("Usage: fossilize-convert-db input-db output-db\n");
}
int main(int argc, char *argv[])
{
if (argc != 3)
{
print_help();
return EXIT_FAILURE;
}
auto input_db = std::unique_ptr<DatabaseInterface>(create_database(argv[1], DatabaseMode::ReadOnly));
auto output_db = std::unique_ptr<DatabaseInterface>(create_database(argv[2], DatabaseMode::OverWrite));
if (!input_db || !input_db->prepare())
{
LOGE("Failed to load database: %s\n", argv[1]);
return EXIT_FAILURE;
}
if (!output_db || !output_db->prepare())
{
LOGE("Failed to open database for writing: %s\n", argv[2]);
return EXIT_FAILURE;
}
for (unsigned i = 0; i < RESOURCE_COUNT; i++)
{
auto tag = static_cast<ResourceTag>(i);
size_t hash_count = 0;
if (!input_db->get_hash_list_for_resource_tag(tag, &hash_count, nullptr))
return EXIT_FAILURE;
std::vector<Hash> hashes(hash_count);
if (!input_db->get_hash_list_for_resource_tag(tag, &hash_count, hashes.data()))
return EXIT_FAILURE;
for (auto &hash : hashes)
{
size_t blob_size = 0;
if (!input_db->read_entry(tag, hash, &blob_size, nullptr, PAYLOAD_READ_NO_FLAGS))
return EXIT_FAILURE;
std::vector<uint8_t> blob(blob_size);
if (!input_db->read_entry(tag, hash, &blob_size, blob.data(), PAYLOAD_READ_NO_FLAGS))
return EXIT_FAILURE;
if (!output_db->write_entry(tag, hash, blob.data(), blob.size(),
PAYLOAD_WRITE_COMPUTE_CHECKSUM_BIT |
PAYLOAD_WRITE_COMPRESS_BIT |
PAYLOAD_WRITE_BEST_COMPRESSION_BIT))
{
return EXIT_FAILURE;
}
}
}
}
<|start_filename|>cli/fossilize_merge_db.cpp<|end_filename|>
/* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "fossilize_db.hpp"
#include <memory>
#include <vector>
#include "layer/utils.hpp"
#include <cstdlib>
using namespace Fossilize;
static void print_help()
{
LOGI("Usage: fossilize-merge-db append.foz [input1.foz] [input2.foz] ...\n");
}
int main(int argc, char **argv)
{
std::vector<const char *> inputs;
if (argc < 3)
{
print_help();
return EXIT_FAILURE;
}
for (int i = 2; i < argc; i++)
inputs.push_back(argv[i]);
if (!merge_concurrent_databases(argv[1], inputs.data(), inputs.size()))
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
| kakra/Fossilize |
<|start_filename|>src/test/java/com/sangupta/bloomfilter/TestBitArrays.java<|end_filename|>
/**
*
* bloomfilter - Bloom filters for Java
* Copyright (c) 2014-2015, <NAME>
*
* http://sangupta.com/projects/bloomfilter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.sangupta.bloomfilter;
import java.io.File;
import java.io.IOException;
import junit.framework.Assert;
import org.junit.Test;
import com.sangupta.bloomfilter.core.BitArray;
import com.sangupta.bloomfilter.core.FastBitArray;
import com.sangupta.bloomfilter.core.FileBackedBitArray;
import com.sangupta.bloomfilter.core.JavaBitSetArray;
import com.sangupta.bloomfilter.core.MMapFileBackedBitArray;
/**
* JUnit tests for various implementations of {@link BitArray}s like
* {@link FileBackedBitArray}, {@link JavaBitSetArray} and {@link FastBitArray}
*
* @author sangupta
* @since 1.0
*/
public class TestBitArrays {
private static final int MILLION_ELEMENTS = 1 * 1000 * 1000;
@Test
public void testJavaBitArray() {
BitArray bitArray = new JavaBitSetArray(MILLION_ELEMENTS);
testArray(bitArray, MILLION_ELEMENTS);
}
@Test
public void testFileBackedBitArray() {
FileBackedBitArray bitArray = null;
try {
File file = File.createTempFile("bitarray", ".bits");
file.deleteOnExit();
bitArray = new FileBackedBitArray(file, MILLION_ELEMENTS);
testArray(bitArray, MILLION_ELEMENTS / 1000);
} catch(Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
} finally {
if(bitArray != null) {
try {
bitArray.close();
} catch (IOException e) {
// eat up
}
}
}
}
@Test
public void testMMapFileBackedBitArray() {
MMapFileBackedBitArray bitArray = null;
try {
File file = File.createTempFile("bitarray", ".bits");
file.deleteOnExit();
bitArray = new MMapFileBackedBitArray(file, MILLION_ELEMENTS);
testArray(bitArray, MILLION_ELEMENTS);
} catch(Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
} finally {
if(bitArray != null) {
try {
bitArray.close();
} catch (IOException e) {
// eat up
}
}
}
}
private void testArray(BitArray bitArray, int maxElements) {
// start iterating
for(int index = 0; index < maxElements; index++) {
Assert.assertFalse(bitArray.getBit(index));
bitArray.setBit(index);
Assert.assertTrue(bitArray.getBit(index));
bitArray.clearBit(index);
Assert.assertFalse(bitArray.getBit(index));
}
}
} | sangupta/bloomfilter |
<|start_filename|>apprtc.go<|end_filename|>
package main
import (
"crypto/hmac"
"crypto/sha1"
"crypto/tls"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
"github.com/daozhao/apprtc-go/collider"
// "reflect"
)
/*
const (
CERT = "./mycert.pem"
KEY = "./mycert.key"
wssHostPort = "8089"
wssHost = "192.168.2.30"
PORT = 8888
)
*/
var TURN_SERVER_OVERRIDE string
const STUN_SERVER_FMT = `
{
"urls": [
"stun:%s"
]
}
`
const TURN_SERVER_FMT = `
{
"urls": [
"turn:%s?transport=udp"
],
"username": "%s",
"credential": "%s"
}
`
const TURN_SERVER_FMT_TEST = `
{
"urls": [
"turn:%s?transport=udp"
],
"credential": "%s:%s"
}
`
var TURN_BASE_URL string = "https://computeengineondemand.appspot.com"
var TURN_URL_TEMPLATE string = `"%s/turn?username=%s&key=%s"`
var CEOD_KEY string = "4080218913"
var ICE_SERVER_BASE_URL string = "https://"
var ICE_SERVER_URL_TEMPLATE string = `"%s://%s/iceconfig?key=%s"`
var ICE_SERVER_API_KEY string = "4080218913" //os.environ.get('ICE_SERVER_API_KEY')
var CALLSTATS_PARAMS string = `{"appSecret": "none", "appId": "none"}`
/*
{
'appId': os.environ.get('CALLSTATS_APP_ID'),
'appSecret': os.environ.get('CALLSTATS_APP_SECRET')
}`
*/
/*
var WSS_INSTANCE_HOST_KEY string = "host_port_pair"
var WSS_INSTANCE_NAME_KEY string = "vm_name"
var WSS_INSTANCE_ZONE_KEY string = "zone"
var WSS_INSTANCES string = `[{
# WSS_INSTANCE_HOST_KEY: 'apprtc-ws.webrtc.org:443',
WSS_INSTANCE_HOST_KEY: '192.168.2.97:8089',
WSS_INSTANCE_NAME_KEY: 'wsserver-std',
WSS_INSTANCE_ZONE_KEY: 'us-central1-a'
}, {
# WSS_INSTANCE_HOST_KEY: 'apprtc-ws-2.webrtc.org:443',
WSS_INSTANCE_HOST_KEY: '192.168.2.97:8089',
WSS_INSTANCE_NAME_KEY: 'wsserver-std-2',
WSS_INSTANCE_ZONE_KEY: 'us-central1-f'
}]`
*/
const (
RESPONSE_ERROR = "ERROR"
RESPONSE_ROOM_FULL = "FULL"
RESPONSE_UNKNOWN_ROOM = "UNKNOWN_ROOM"
RESPONSE_UNKNOWN_CLIENT = "UNKNOWN_CLIENT"
RESPONSE_DUPLICATE_CLIENT = "DUPLICATE_CLIENT"
RESPONSE_SUCCESS = "SUCCESS"
RESPONSE_INVALID_REQUEST = "INVALID_REQUEST"
LOOPBACK_CLIENT_ID = "LOOPBACK_CLIENT_ID"
)
type Client struct {
Id string
is_initiator bool
messages []string
messageLen int
}
func NewClient(clientId string, initiator bool) *Client {
return &Client{Id: clientId, is_initiator: initiator, messages: make([]string, 10), messageLen: 0}
}
func (c *Client) AddMessage(msg string) {
if c.messageLen < len(c.messages) {
c.messages[c.messageLen] = msg
c.messageLen = c.messageLen + 1
}
//c.messages = append(c.messages,msg)
}
func (c *Client) CleanMessage() {
c.messageLen = 0
}
func (c *Client) GetMessages() []string {
return c.messages[0:c.messageLen]
}
func (c *Client) SetInitiator(initiator bool) {
c.is_initiator = initiator
}
/*
*/
type Room struct {
Id string
clients map[string]*Client
}
//
func NewRoom(roomId string) *Room {
return &Room{Id: roomId, clients: make(map[string]*Client)}
}
//
func (r *Room) AddClient(c *Client) {
r.clients[c.Id] = c
}
//
func (r *Room) RemoveClient(client_id string) {
_, ok := r.clients[client_id]
if ok {
delete(r.clients, client_id)
}
}
func (r *Room) HasClient(client_id string) bool {
_, ok := r.clients[client_id]
return ok
}
func (r *Room) GetClient(client_id string) (*Client, bool) {
client, ok := r.clients[client_id]
if ok {
return client, true
}
return nil, false
}
func (r *Room) GetOtherClient(client_id string) (*Client, bool) {
for key, client := range r.clients {
if key != client_id {
return client, true
}
}
return nil, false
}
func (r *Room) GetOccupancy() int {
return len(r.clients)
}
func (r *Room) GetStatus() []string {
var result []string
var i int = 0
result = make([]string, len(r.clients))
for key, _ := range r.clients {
result[i] = key
i = i + 1
}
return result
// abc := map[string]int{
// "a": 1,
// "b": 2,
// "c": 3,
// }
// keys := reflect.ValueOf(abc).MapKeys()
// fmt.Println(keys) // [a b c]
}
var RoomList map[string]*Room
func getRequest(r *http.Request, key, def string) string {
value := r.Form.Get(key)
if len(value) == 0 {
return def
}
return value
}
func getWssParameters(r *http.Request) (string, string) {
// wssHostPortPair := r.Form.Get("wshpp")
// isTLS := isTLS(r)
// wssTLS := getRequest(r, "wstls", strconv.FormatBool(isTLS))
// // http://127.0.0.1:8080/?wstls=false&wshpp=192.168.2.97:4443
// if len(wssHostPortPair) == 0 {
// log.Println("getWssParameters, r.Host:", r.Host)
// wssHostPortPair = r.Host
// if len(wssHost) > 0 {
// wssHostPortPair = wssHost //+ ":" + strconv.Itoa(wssHostPort) // "192.168.2.30:8089"
// }
// }
// log.Println("r:",r)
// if strings.Index(r.Scheme,"http://") == 0 {
// wssTLS = "false"
// }
// wssTLS = "false"
var wssUrl, wssPostUrl string
// if strings.EqualFold(wssTLS, "false") {
if !isTLS(r) {
// wssUrl = "ws://" + r.Host + ":" + strconv.Itoa(wsHostPort) + "/ws"
// wssPostUrl = "http://" + r.Host + ":" + strconv.Itoa(httpHostPort)
wssUrl = "ws://" + r.Host + "/ws"
wssPostUrl = "http://" + r.Host
} else {
// wssUrl = "wss://" + r.Host + ":" + strconv.Itoa(wssHostPort) + "/ws"
// wssPostUrl = "https://" + r.Host + ":" + strconv.Itoa(httpHostPort)
wssUrl = "wss://" + r.Host + "/ws"
wssPostUrl = "https://" + r.Host
}
return wssUrl, wssPostUrl
}
func roomPageHandler(w http.ResponseWriter, r *http.Request) {
log.Println("roomPageHandler host:", r.Host, "url:", r.URL.RequestURI(), " path:", r.URL.Path, " raw query:", r.URL.RawQuery)
room_id := strings.Replace(r.URL.Path, "/r/", "", 1)
room_id = strings.Replace(room_id, "/", "", -1)
//todo: 检查房间是否已经超过两人。
log.Println("room page room_id:", room_id)
t, err := template.ParseFiles("./html/index_template.html")
// t, err := template.ParseFiles("./html/params.html")
if err != nil {
log.Println(err)
log.Println("index template render error:",err.Error())
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
room, ok := RoomList[room_id]
if ok {
if room.GetOccupancy() >= 2 {
t, err = template.ParseFiles("./html/full_template.html")
if err!=nil{
log.Println("full template render error:",err.Error())
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
t.Execute(w, nil)
return
}
}
data := getRoomParameters(r, room_id, "", nil)
t.Execute(w, data)
// t.Execute(w, nil)
}
func addClientToRoom(r *http.Request, room_id, client_id string, is_loopback bool) (map[string]interface{}, bool) {
room, ok := RoomList[room_id]
if !ok {
room = NewRoom(room_id)
RoomList[room_id] = room
}
var is_initiator bool
var messages []string
error := ""
occupancy := room.GetOccupancy()
if occupancy >= 2 {
error = RESPONSE_ROOM_FULL
}
if room.HasClient(client_id) {
error = RESPONSE_DUPLICATE_CLIENT
}
if 0 == occupancy {
is_initiator = true
room.AddClient(NewClient(client_id, is_initiator))
if is_loopback {
room.AddClient(NewClient(LOOPBACK_CLIENT_ID, false))
}
messages = make([]string, 0)
} else {
is_initiator = false
other_client, _ := room.GetOtherClient(client_id)
messages = other_client.GetMessages()
room.AddClient(NewClient(client_id, is_initiator))
other_client.CleanMessage()
log.Println("addClientToRoom message:", messages)
}
var params map[string]interface{}
params = make(map[string]interface{})
params["error"] = error
params["is_initiator"] = is_initiator
params["messages"] = messages
params["room_state"] = room.GetStatus()
return params, (len(error) == 0)
}
func joinPageHandler(w http.ResponseWriter, r *http.Request) {
log.Println("joinPageHandler host:", r.Host, "url:", r.URL.RequestURI(), " path:", r.URL.Path, " raw query:", r.URL.RawQuery)
log.Println("joinPageHandler host:", r.Host, "TLS:", r.TLS, " path:", r.URL.Path, " raw query:", r.URL.RawQuery)
room_id := strings.Replace(r.URL.Path, "/join/", "", 1)
room_id = strings.Replace(room_id, "/", "", -1)
log.Println("join page room_id:", room_id)
client_id := fmt.Sprintf("%d", rand.Intn(1000000000))
is_loopback := (getRequest(r, "debug", "") == "loopback")
result, ok := addClientToRoom(r, room_id, client_id, is_loopback)
var resultStr string
var returnData map[string]interface{}
var params map[string]interface{}
if !ok {
log.Println("Error adding client to room:", result["error"], ", room_state=", result["room_state"])
resultStr, _ = result["error"].(string)
returnData = make(map[string]interface{})
//return
} else {
resultStr = "SUCCESS"
is_initiator := strconv.FormatBool(result["is_initiator"].(bool))
log.Println("joinPageHandler is_initiator:", result["is_initiator"], " String:", is_initiator)
returnData = getRoomParameters(r, room_id, client_id, is_initiator)
returnData["messages"] = result["messages"]
// returnData["is_initiator"] = "true"
}
params = make(map[string]interface{})
params["result"] = resultStr
params["params"] = returnData
//todo 输出json数据返回
enc := json.NewEncoder(w)
enc.Encode(¶ms)
}
func removeClientFromRoom(room_id, client_id string) map[string]interface{} {
log.Println("removeClientFromRoom room:", room_id, " client:", client_id)
var result map[string]interface{}
result = make(map[string]interface{})
room, ok := RoomList[room_id]
if !ok {
log.Println("removeClientFromRoom: Unknow room:", room_id)
result["error"] = RESPONSE_UNKNOWN_ROOM
result["room_state"] = ""
return result
}
if !room.HasClient(client_id) {
log.Println("removeClientFromRoom: Unknow client:", client_id)
result["error"] = RESPONSE_UNKNOWN_CLIENT
result["room_state"] = room.GetStatus()
return result
}
room.RemoveClient(client_id)
room.RemoveClient(LOOPBACK_CLIENT_ID)
if room.GetOccupancy() > 0 {
client, _ := room.GetOtherClient(client_id)
client.SetInitiator(true)
} else {
delete(RoomList, room_id)
}
result["error"] = ""
result["room_state"] = room.GetStatus()
return result
}
func leavePageHandler(w http.ResponseWriter, r *http.Request) {
log.Println("leavePageHandler host:", r.Host, "url:", r.URL.RequestURI(), " path:", r.URL.Path, " raw query:", r.URL.RawQuery)
//room_id := strings.Replace(r.URL.Path,"/leave/","",1)
var room_id, client_id string
url := strings.Split(r.URL.Path, "/")
log.Println("url array:", url)
if len(url) >= 3 {
room_id = url[2]
client_id = url[3]
// fmt.Sscanf(r.URL.Path, "/leave/%s/", &room_id, &client_id)
//log.Println("leave room:",room_id," client:",client_id)
result := removeClientFromRoom(room_id, client_id)
//result := removeClientFromRoom(strconv.Itoa(room_id), strconv.Itoa(client_id))
if len(result["error"].(string)) == 0 {
log.Println("Room:", room_id, " has state ", result["room_state"])
}
}
}
func saveMessageFromClient(room_id, client_id, message_json string) map[string]interface{} {
log.Println("saveMessageFrom room:", room_id, " client:", client_id, " msg:", message_json)
var result map[string]interface{}
result = make(map[string]interface{})
room, ok := RoomList[room_id]
result["saved"] = false
if !ok {
log.Println("saveMessageFromClient: Unknow room:", room_id)
result["error"] = RESPONSE_UNKNOWN_ROOM
return result
}
client, has := room.GetClient(client_id)
if !has {
log.Println("saveMessageFromclient: Unknow client:", client_id)
result["error"] = RESPONSE_UNKNOWN_CLIENT
return result
}
if room.GetOccupancy() > 1 {
result["error"] = ""
return result
}
client.AddMessage(message_json)
result["error"] = ""
result["saved"] = true
return result
}
func messagePageHandler(w http.ResponseWriter, r *http.Request) {
log.Println("messagePageHandler host:", r.Host, "url:", r.URL.RequestURI(), " path:", r.URL.Path, " raw query:", r.URL.RawQuery)
var room_id, client_id string
url := strings.Split(r.URL.Path, "/")
log.Println("url array:", url)
if len(url) >= 3 {
room_id = url[2]
client_id = url[3]
body, err := ioutil.ReadAll(r.Body)
if err != nil {
}
message_json := string(body)
result := saveMessageFromClient(room_id, client_id, message_json)
if !result["saved"].(bool) {
_, wss_post_url := getWssParameters(r)
resp, err := http.Post(wss_post_url+"/"+room_id+"/"+client_id, "application/x-www-form-urlencoded", strings.NewReader(message_json))
if err != nil {
fmt.Println(err)
}
if resp.StatusCode != 200 {
log.Println("Failed to send message to collider:", resp.StatusCode)
}
}
var params map[string]interface{}
params = make(map[string]interface{})
params["result"] = RESPONSE_SUCCESS
enc := json.NewEncoder(w)
enc.Encode(¶ms)
}
}
func paramsPageHandler(w http.ResponseWriter, r *http.Request) {
log.Println("paramsPageHandler host:", r.Host, "url:", r.URL.RequestURI(), " path:", r.URL.Path, " raw query:", r.URL.RawQuery)
data := getRoomParameters(r, "", "", nil)
enc := json.NewEncoder(w)
enc.Encode(&data)
}
func paramsHTMLPageHandler(w http.ResponseWriter, r *http.Request) {
log.Println("paramsHTMLPageHandler host:", r.Host, "url:", r.URL.RequestURI(), " path:", r.URL.Path, " raw query:", r.URL.RawQuery)
t, _ := template.ParseFiles("./html/params.html")
t.Execute(w, nil)
}
func aPageHandler(w http.ResponseWriter, r *http.Request) {
log.Println("aPageHandler host:", r.Host, "url:", r.URL.RequestURI(), " path:", r.URL.Path, " raw query:", r.URL.RawQuery)
}
func iceconfigPageHandler(w http.ResponseWriter, r *http.Request) {
turnServer := ""
if len(*flagstun) > 0 {
turnServer += fmt.Sprintf(STUN_SERVER_FMT, *flagstun)
}
if len(*flagturn) > 0 {
if len(turnServer) > 0 {
turnServer += ","
}
username, password := getTurnAuth()
turnServer += fmt.Sprintf(TURN_SERVER_FMT, *flagturn, username, password)
// turnServer += fmt.Sprintf(TURN_SERVER_FMT, *flagturn, "teninefingers", "4080218913")
}
turnServer = `{"iceServers":[` + turnServer + "]}"
log.Println("turnServer:", turnServer)
var dat interface{}
if err := json.Unmarshal([]byte(turnServer), &dat); err != nil {
log.Println("json.Unmarshal error:", err)
return
}
// params :=
enc := json.NewEncoder(w)
enc.Encode(&dat)
}
func getTurnAuth() (username, password string) {
if len(*flagTurnSecret) > 0 {
timestamp := time.Now().Unix() + 60*60
turnUsername := strconv.Itoa(int(timestamp)) + ":" + *flagTurnUser
expectedMAC := Hmac(*flagTurnSecret, turnUsername)
return turnUsername, expectedMAC
}
return *flagTurnUser, *flagTurnPassword
}
func Hmac(key, data string) string {
// https://stackoverflow.com/questions/30745153/turn-server-for-webrtc-with-rest-api-authentication?noredirect=1&lq=1
// key: my_secret
// user: 1433895918506:my_user_name
// 1Dj9XZ5fwvKS6YoQZOoORcFnXaI
hmac := hmac.New(sha1.New, []byte(key))
hmac.Write([]byte(data))
return base64.StdEncoding.EncodeToString(hmac.Sum(nil))
// return base64.StdEncoding.EncodeToString(hmac.Sum([]byte("")))
}
func computePageHandler(w http.ResponseWriter, r *http.Request) {
log.Println("computePagehandler host:", r.Host, "url:", r.URL.RequestURI(), " path:", r.URL.Path, " raw query:", r.URL.RawQuery)
}
func mainPageHandler(w http.ResponseWriter, r *http.Request) {
// if r.URL.Path == "/" {
// http.Redirect(w, r, "/login/index", http.StatusFound)
// }
log.Println("host:", r.Host, "url:", r.URL.RequestURI(), " path:", r.URL.Path, " raw query:", r.URL.RawQuery)
t, err := template.ParseFiles("./html/index_template.html")
// t, err := template.ParseFiles("./html/params.html")
if err != nil {
log.Println(err)
}
data := getRoomParameters(r, "", "", nil)
t.Execute(w, data)
// t.Execute(w, nil)
}
func isTLS(r *http.Request) bool {
return (r.TLS != nil)
}
func getRoomParameters(r *http.Request, room_id, client_id string, is_initiator interface{}) map[string]interface{} {
var data map[string]interface{}
data = make(map[string]interface{})
data["error_messages"] = []string{}
data["warning_messages"] = []string{}
data["is_loopback"] = false // json.dumps(debug == 'loopback'),
data["pc_config"] = template.JS(`{"iceServers": [], "rtcpMuxPolicy": "require", "bundlePolicy": "max-bundle"}`) //json.dumps(pc_config),
data["pc_constraints"] = template.JS(`{"optional": []}`) // json.dumps(pc_constraints),
data["offer_options"] = template.JS("{}") //json.dumps(offer_options),
data["media_constraints"] = template.JS(`{"video": {"optional": [{"minWidth": "1280"}, {"minHeight": "720"}], "mandatory": {}}, "audio": true}`)
// var dat []map[string]interface{}
var dat interface{}
if err := json.Unmarshal([]byte(TURN_SERVER_OVERRIDE), &dat); err != nil {
log.Println("json.Unmarshal error:", err)
}
// log.Println(dat)
data["turn_server_override"] = dat // template.JS(strings.Replace(TURN_SERVER_OVERRIDE,"\n","",-1) )
username := fmt.Sprintf("%d", rand.Intn(1000000000)) //todo:
if len(client_id) > 0 {
username = client_id
}
data["turn_url"] = template.JS(fmt.Sprintf(TURN_URL_TEMPLATE, TURN_BASE_URL, username, CEOD_KEY))
// ice_server_base_url := getRequest(r, "ts", ICE_SERVER_BASE_URL)
if isTLS(r) {
// data["ice_server_url"] = template.JS(fmt.Sprintf(ICE_SERVER_URL_TEMPLATE, "https", r.Host, httpsHostPort, ICE_SERVER_API_KEY))
data["ice_server_url"] = template.JS(fmt.Sprintf(ICE_SERVER_URL_TEMPLATE, "https", r.Host, ICE_SERVER_API_KEY))
} else {
// data["ice_server_url"] = template.JS(fmt.Sprintf(ICE_SERVER_URL_TEMPLATE, "http", r.Host, httpHostPort, ICE_SERVER_API_KEY))
data["ice_server_url"] = template.JS(fmt.Sprintf(ICE_SERVER_URL_TEMPLATE, "http", r.Host, ICE_SERVER_API_KEY))
}
data["ice_server_transports"] = getRequest(r, "tt", "")
var dtls, include_loopback_js string
debug := getRequest(r, "debug", "")
if strings.EqualFold(debug, "loopback") {
dtls = "false"
include_loopback_js = "<script src=\"/js/loopback.js\"></script>"
} else {
dtls = "true"
include_loopback_js = ""
}
data["include_loopback_js"] = include_loopback_js
data["ddtls"] = dtls
include_rtstats_js := ""
//todo:
//include_rtstats_js = "<script src=\"/js/rtstats.js\"></script><script src=\"/pako/pako.min.js\"></script>"
data["include_rtstats_js"] = include_rtstats_js
wss_url, wss_post_url := getWssParameters(r)
data["wss_url"] = template.URL(wss_url)
data["wss_post_url"] = template.URL(wss_post_url)
// bypass_join_confirmation = 'BYPASS_JOIN_CONFIRMATION' in os.environ and os.environ['BYPASS_JOIN_CONFIRMATION'] == 'True'
bypass_join_confirmation := false
data["bypass_join_confirmation"] = bypass_join_confirmation
data["version_info"] = template.JS(`{"time": "Thu Feb 9 15:54:29 2017 +0800", "branch": "master", "gitHash": "9d2692c3a32b1213584ec01cb5f12d462cb82d3e"}`)
data["callstats_params"] = template.JS(strings.Replace(CALLSTATS_PARAMS, "\n", "", -1))
if len(room_id) > 0 {
var room_link string
if isTLS(r) {
room_link = "https://" + r.Host + "/r/" + room_id + "?" + r.URL.RawQuery
} else {
room_link = "http://" + r.Host + "/r/" + room_id + "?" + r.URL.RawQuery
}
// room_link := r.Host + "/r/" + room_id + "?" + r.URL.RawQuery
// log.Println("host:",r.Host," url:",r.URL.String," uri:",r.URL.RequestURI)
data["room_id"] = room_id
data["room_link"] = template.URL(room_link)
}
if len(client_id) > 0 {
data["client_id"] = client_id
}
if is_initiator != nil {
data["is_initiator"] = is_initiator
}
return data
}
// var useTls bool
var wssHostPort int
var wsHostPort int
var httpsHostPort int
var httpHostPort int
// var wssHost string
// var flagUseTls = flag.Bool("tls", true, "whether TLS is used")
// var flagWssHostPort = flag.Int("wssport", 1443, "The TCP port that the server listens on")
// var flagWsHostPort = flag.Int("wsport", 2443, "The TCP port that the server listens on")
var flagHttpsHostPort = flag.Int("httpsport", 8888, "The https port that the server listens on")
var flagHttpHostPort = flag.Int("httpport", 8080, "The http port that the server listens on")
// var flagWssHost = flag.String("host", "192.168.2.30", "Enter your hostname or host ip")
var flagstun = flag.String("stun", "", "Enter stun server ip:port,for example 192.168.2.170:3478,default is null")
var flagturn = flag.String("turn", "", "Enter turn server ip:port,for example 192.168.2.170:3478,default is null")
var flagTurnUser = flag.String("turn-username", "", "Enter turn server username,default is null")
var flagTurnPassword = flag.String("turn-password", "", "Enter turn server user password,default is null")
var flagTurnSecret = flag.String("turn-static-auth-secret", "", "Enter turn server static auth secret,default is null")
var roomSrv = flag.String("room-server", "https://appr.tc", "The origin of the room server")
var CERT = flag.String("cert", "./mycert.pem", "cert pem file ")
var KEY = flag.String("key", "./mycert.key", "cert key file ")
var ice_server_url string
func main() {
flag.Parse()
// useTls = *flagUseTls
// wssHostPort = *flagWssHostPort
// wsHostPort = *flagWsHostPort
httpsHostPort = *flagHttpsHostPort
httpHostPort = *flagHttpHostPort
// wssHost = *flagWssHost
if len(*flagturn) > 0 {
if len(*flagTurnUser) == 0 {
log.Printf("If set turn server,must has turn-username")
return
}
if len(*flagTurnPassword) == 0 && len(*flagTurnSecret) == 0 {
log.Printf("If set turn server,must set turn-password or turn-static-auth-secret")
return
}
}
// TURN_SERVER_OVERRIDE += "["
// if len(*flagstun) > 0 {
// TURN_SERVER_OVERRIDE += fmt.Sprintf(STUN_SERVER_FMT, *flagstun)
// }
// if len(*flagturn) > 0 {
// if len(TURN_SERVER_OVERRIDE) > 0 {
// TURN_SERVER_OVERRIDE += ","
// }
// TURN_SERVER_OVERRIDE += fmt.Sprintf(TURN_SERVER_FMT, *flagturn)
// }
TURN_SERVER_OVERRIDE = "[" + TURN_SERVER_OVERRIDE + "]"
// log.Printf("TURN_SERVER_OVERRIDE:%s", TURN_SERVER_OVERRIDE)
RoomList = make(map[string]*Room)
WebServeMux := http.NewServeMux()
WebServeMux.Handle("/css/", http.FileServer(http.Dir("./")))
WebServeMux.Handle("/js/", http.FileServer(http.Dir("./")))
WebServeMux.Handle("/images/", http.FileServer(http.Dir("./")))
WebServeMux.Handle("/callstats/", http.FileServer(http.Dir("./")))
WebServeMux.Handle("/favicon.ico", http.FileServer(http.Dir("./")))
WebServeMux.Handle("/manifest.json", http.FileServer(http.Dir("./html/")))
WebServeMux.HandleFunc("/r/", roomPageHandler)
WebServeMux.HandleFunc("/join/", joinPageHandler)
WebServeMux.HandleFunc("/leave/", leavePageHandler)
WebServeMux.HandleFunc("/message/", messagePageHandler)
WebServeMux.HandleFunc("/params.html", paramsHTMLPageHandler)
WebServeMux.HandleFunc("/params.htm" , paramsHTMLPageHandler)
WebServeMux.HandleFunc("/params", paramsPageHandler)
WebServeMux.HandleFunc("/params/", paramsPageHandler)
WebServeMux.HandleFunc("/a/", aPageHandler)
WebServeMux.HandleFunc("/compute/", computePageHandler)
WebServeMux.HandleFunc("/iceconfig", iceconfigPageHandler)
WebServeMux.HandleFunc("/iceconfig/", iceconfigPageHandler)
WebServeMux.HandleFunc("/", mainPageHandler)
c := collider.NewCollider(*roomSrv)
c.AddHandle(WebServeMux)
// go c.Run(wssHostPort, wsHostPort, *CERT, *KEY)
var e error
httpsPstr := ":" + strconv.Itoa(httpsHostPort)
httpPstr := ":" + strconv.Itoa(httpHostPort)
// log.Println("Starting webrtc demo on port:", webHostPort, " tls:", useTls)
// 1Dj9XZ5fwvKS6YoQZOoORcFnXaI=
// log.Println("hmac:", Hmac("my_secret", "1433895918506:my_user_name"))
if len(*CERT) > 0 && len(*KEY) > 0 {
config := &tls.Config{
// Only allow ciphers that support forward secrecy for iOS9 compatibility:
// https://developer.apple.com/library/prerelease/ios/technotes/App-Transport-Security-Technote/
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
},
PreferServerCipherSuites: true,
}
log.Println("Starting webrtc demo on https port:", httpsHostPort)
server := &http.Server{Addr: httpsPstr, Handler: WebServeMux, TLSConfig: config}
go server.ListenAndServeTLS(*CERT, *KEY)
}
log.Println("Starting webrtc demo on http port:", httpHostPort)
e = http.ListenAndServe(httpPstr, WebServeMux)
if e != nil {
log.Fatal("Run: " + e.Error())
}
// http.ListenAndServe(":8888", nil)
}
| daozhao/apprtc-go |
<|start_filename|>.yo-rc.json<|end_filename|>
{
"generator-awesome-list": {
"promptValues": {
"username": "Darko Lukic",
"email": "<EMAIL>"
}
}
} | lukicdarkoo/awesome-webots |
<|start_filename|>src/dcp1/handle_args.h<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
#ifndef __DCOPY_HANDLE_ARGS_H
#define __DCOPY_HANDLE_ARGS_H
#include "common.h"
void DCOPY_parse_path_args(char** argv, int optind, int argc);
void DCOPY_free_path_args(void);
void DCOPY_enqueue_work_objects(CIRCLE_handle* handle);
#endif /* __DCOPY_HANDLE_ARGS_H */
<|start_filename|>test/legacy/dtar_tests/dir/log.h<|end_filename|>
#ifndef LOG_H
#define LOG_H
#include <stdio.h>
#include <time.h>
typedef enum {
DTAR_LOG_FATAL = 1,
DTAR_LOG_ERR = 2,
DTAR_LOG_WARN = 3,
DTAR_LOG_INFO = 4,
DTAR_LOG_DBG = 5
} DTAR_loglevel;
// fprintf(DTAR_debug_stream,"[%s] ", timestamp);
#define LOG(level, ...) do { \
if (level <= DTAR_debug_level) { \
char timestamp[256]; \
time_t ltime = time(NULL); \
struct tm *ttime = localtime(<ime); \
strftime(timestamp, sizeof(timestamp), \
"%Y-%m-%dT%H:%M:%S", ttime); \
if(level == DTAR_LOG_DBG) { \
fprintf(DTAR_debug_stream,"[%s] [%d] [%s:%d] ", \
timestamp, CIRCLE_global_rank, \
__FILE__, __LINE__); \
} else { \
fprintf(DTAR_debug_stream,"[%s] [%d] [%s:%d] ", \
timestamp, CIRCLE_global_rank, \
__FILE__, __LINE__); \
} \
fprintf(DTAR_debug_stream, __VA_ARGS__); \
fprintf(DTAR_debug_stream, "\n"); \
fflush(DTAR_debug_stream); \
} \
} while (0)
extern int CIRCLE_global_rank;
extern FILE* DTAR_debug_stream;
extern DTAR_loglevel DTAR_debug_level;
#endif /* LOG_H */
<|start_filename|>cmake/FindCART.cmake<|end_filename|>
# - Try to find cart libs
# Once done this will define
# cart_FOUND - System has libcart
# cart_INCLUDE_DIRS - cart include directories
# cart_LIBRARIES - The libraries needed to use cart
# gurt_LIBRARIES - The libraries needed to use gurt (part of cart)
FIND_PATH(WITH_CART_PREFIX
NAMES cart/include
)
FIND_LIBRARY(CART_LIBRARIES
NAMES cart
HINTS ${WITH_CART_PREFIX}/lib
)
FIND_LIBRARY(GURT_LIBRARIES
NAMES gurt
HINTS ${WITH_CART_PREFIX}/lib
)
FIND_PATH(CART_INCLUDE_DIRS
NAMES cart/types.h
HINTS ${WITH_CART_PREFIX}/include
)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(CART DEFAULT_MSG
CART_LIBRARIES
CART_INCLUDE_DIRS
)
# Hide these vars from ccmake GUI
MARK_AS_ADVANCED(
CART_LIBRARIES
GURT_LIBRARIES
CART_INCLUDE_DIRS
)
<|start_filename|>src/dgrep/dgrep.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <ctype.h>
#include "dgrep.h"
#include "log.h"
int DGREP_global_rank;
FILE *DGREP_debug_stream;
DGREP_loglevel DGREP_debug_level;
char *DGREP_PATH;
char *DGREP_ARGS;
void
DGREP_start(CIRCLE_handle *handle)
{
handle->enqueue(DGREP_PATH);
}
void
DGREP_search(CIRCLE_handle *handle)
{
DIR *current_dir;
char temp[CIRCLE_MAX_STRING_LEN];
char stat_temp[CIRCLE_MAX_STRING_LEN];
struct dirent *current_ent;
struct stat st;
/* Pop an item off the queue */
handle->dequeue(temp);
/* Try and stat it, checking to see if it is a link */
if(lstat(temp,&st) != EXIT_SUCCESS)
{
LOG(DGREP_LOG_ERR, "Error: Couldn't stat \"%s\"", temp);
return;
}
/* Check to see if it is a directory. If so, put its children in the queue */
else if(S_ISDIR(st.st_mode) && !(S_ISLNK(st.st_mode)))
{
current_dir = opendir(temp);
if(!current_dir)
{
LOG(DGREP_LOG_ERR, "Unable to open dir");
}
else
{
/* Read in each directory entry */
while((current_ent = readdir(current_dir)) != NULL)
{
/* We don't care about . or .. */
if((strncmp(current_ent->d_name,".",2)) && (strncmp(current_ent->d_name,"..",3)))
{
strcpy(stat_temp,temp);
strcat(stat_temp,"/");
strcat(stat_temp,current_ent->d_name);
handle->enqueue(&stat_temp[0]);
}
}
}
closedir(current_dir);
}
else if(S_ISREG(st.st_mode)) {
FILE *fp;
char cmd[CIRCLE_MAX_STRING_LEN + 10];
char out[1035];
sprintf(cmd, "grep %s %s", DGREP_ARGS, temp);
fp = popen(cmd, "r");
if (fp == NULL) {
printf("Failed to run command\n" );
}
while (fgets(out, sizeof(out) - 1, fp) != NULL) {
printf("%s", out);
}
pclose(fp);
}
}
void
print_usage(char *prog)
{
fprintf(stdout, "Usage: %s -p <path> -a <pattern>\n", prog);
}
int
main (int argc, char **argv)
{
int index;
int c;
int args_flag = 0;
int path_flag = 0;
DGREP_debug_stream = stdout;
DGREP_debug_level = DGREP_LOG_DBG;
opterr = 0;
while((c = getopt(argc, argv, "p:a:")) != -1)
{
switch(c)
{
case 'a':
DGREP_ARGS = optarg;
args_flag = 1;
break;
case 'p':
DGREP_PATH = realpath(optarg, NULL);
path_flag = 1;
break;
case '?':
if (optopt == 'p' || optopt == 'a')
fprintf(stderr, "Error: Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf(stderr, "Error: Unknown option `-%c'.\n", optopt);
else
fprintf(stderr,
"Error: Unknown option character `\\x%x'.\n",
optopt);
exit(EXIT_FAILURE);
default:
abort();
}
}
for (index = optind; index < argc; index++)
{
print_usage(argv[0]);
fprintf(stdout, "Error: Non-option argument %s\n", argv[index]);
exit(EXIT_FAILURE);
}
if(path_flag == 0)
{
print_usage(argv[0]);
fprintf(stdout, "Error: You must specify a starting path name.\n");
exit(EXIT_FAILURE);
}
if(args_flag == 0)
{
print_usage(argv[0]);
fprintf(stdout, "Error: You must specify a pattern to search on.\n");
exit(EXIT_FAILURE);
}
DGREP_global_rank = CIRCLE_init(argc, argv, CIRCLE_DEFAULT_FLAGS);
CIRCLE_cb_create (&DGREP_start);
CIRCLE_cb_process(&DGREP_search);
CIRCLE_begin();
CIRCLE_finalize();
exit(EXIT_SUCCESS);
}
/* EOF */
<|start_filename|>cmake/FindLibCap.cmake<|end_filename|>
# - Try to find libcap
# Once done this will define
# LibCap_FOUND - System has libcap
# LibCap_INCLUDE_DIRS - The libcap include directories
# LibCap_LIBRARIES - The libraries needed to use libcap
FIND_LIBRARY(LibCap_LIBRARIES
NAMES cap
)
FIND_PATH(LibCap_INCLUDE_DIRS
NAMES sys/capability.h
)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibCap DEFAULT_MSG
LibCap_LIBRARIES
LibCap_INCLUDE_DIRS
)
# Hide these vars from ccmake GUI
MARK_AS_ADVANCED(
LibCap_LIBRARIES
LibCap_INCLUDE_DIRS
)
<|start_filename|>src/common/mfu_progress.h<|end_filename|>
/* enable C++ codes to include this header directly */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef MFU_PROGRESS_H
#define MFU_PROGRESS_H
#include "mpi.h"
/* function prototype for progress callback
* vals - array of current values summed across ranks
* count - number of elements in vals array
* complete - number of ranks that are complete
* ranks - number of ranks involved
* secs - number of seconds since start was called */
typedef void (*mfu_progress_fn)(const uint64_t* vals, int count, int complete, int ranks, double secs);
/* (opaque) struct that holds state for progress message reporting */
typedef struct {
MPI_Comm comm; /* dup'ed communicator to execute bcast/reduce */
MPI_Request bcast_req; /* request for outstanding bcast */
MPI_Request reduce_req; /* request for outstanding reduce */
double time_start; /* time when start was called */
double time_last; /* time when last report was requested */
double timeout; /* number of seconds between reports */
int keep_going; /* flag indicating whether any process is still working */
int count; /* number of items in values arrays */
uint64_t* values; /* array holding contribution to global sum from local proc */
uint64_t* global_vals; /* array to hold global sum across ranks */
mfu_progress_fn progfn; /* callback function to execute to print progress message */
} mfu_progress;
/* start progress timer and return newly allocated structure
* to track its state
* secs - IN number of seconds between progress messages
* count - IN number of uint64_t values to sum in each message
* comm - IN communicator to dup on which to execute ibcast/ireduce
* progfn - IN callback to invoke to print progress message */
mfu_progress* mfu_progress_start(int secs, int count, MPI_Comm comm, mfu_progress_fn progfn);
/* update progress across all processes in work loop,
* vals - IN update contribution of this process to global sum
* prg - IN pointer to struct returned in start */
void mfu_progress_update(uint64_t* vals, mfu_progress* prg);
/* continue broadcasting progress until all processes have completed,
* and free structure allocated in start
* vals - IN array with latest contribution from this process to global sum
* pprg - IN address of pointer to struct returned in start */
void mfu_progress_complete(uint64_t* vals, mfu_progress** pprg);
#endif /* MFU_PROGRESS_H */
/* enable C++ codes to include this header directly */
#ifdef __cplusplus
} /* extern "C" */
#endif
<|start_filename|>src/common/mfu_pred.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <libgen.h>
#include <fnmatch.h>
#include <sys/time.h>
#include <regex.h>
#include "mfu.h"
#include "mfu_flist_internal.h"
#include "mfu_pred.h"
static uint64_t NSECS_IN_MIN = (uint64_t) (1000000000ULL * 60ULL);
static uint64_t NSECS_IN_DAY = (uint64_t) (1000000000ULL * 60ULL * 60ULL * 24ULL);
static void parse_number(const char* str, int* cmp, uint64_t* val)
{
if (str[0] == '+') {
/* check whether id is greater than target */
*cmp = 1;
*val = (uint64_t) atoi(&str[1]);
} else if (str[0] == '-') {
/* check whether id is less than target */
*cmp = -1;
*val = (uint64_t) atoi(&str[1]);
} else {
/* check whether id is equal to target */
*cmp = 0;
*val = (uint64_t) atoi(str);
}
}
mfu_pred* mfu_pred_new(void)
{
mfu_pred* p = (mfu_pred*) MFU_MALLOC(sizeof(mfu_pred));
p->f = NULL;
p->arg = NULL;
p->next = NULL;
return p;
}
void mfu_pred_add(mfu_pred* head, mfu_pred_fn predicate, void* arg)
{
if (head) {
mfu_pred* p = head;
while (p->next) {
p = p->next;
}
p->next = (mfu_pred*) MFU_MALLOC(sizeof(mfu_pred));
p = p->next;
p->f = predicate;
p->arg = arg;
p->next = NULL;
}
}
/* free memory allocated in list of predicates */
void mfu_pred_free (mfu_pred** phead)
{
if (phead != NULL) {
mfu_pred* cur = *phead;
while (cur) {
mfu_pred* next = cur->next;
if (cur->arg != NULL) {
mfu_free(&cur->arg);
}
mfu_free(&cur);
cur = next;
}
*phead = NULL;
}
}
int mfu_pred_execute (mfu_flist flist, uint64_t idx, const mfu_pred* root)
{
const mfu_pred* p = root;
while (p) {
if (p->f != NULL) {
int ret = p->f(flist, idx, p->arg);
if (ret <= 0) {
return ret;
}
}
p = p->next;
}
return 1;
}
/* captures current time and returns it in an mfu_pred_times structure,
* must be freed by caller with mfu_free */
mfu_pred_times* mfu_pred_now(void)
{
/* get our rank */
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
/* capture current time for any time based queries,
* to get a consistent value, capture and bcast from rank 0 */
uint64_t times[2];
if (rank == 0) {
struct timeval tv;
gettimeofday(&tv, NULL);
times[0] = (uint64_t) tv.tv_sec;
times[1] = (uint64_t) tv.tv_usec;
}
MPI_Bcast(times, 2, MPI_UINT64_T, 0, MPI_COMM_WORLD);
/* copy time values into a newly allocated mfu_pred_times struct */
mfu_pred_times* t = (mfu_pred_times*) MFU_MALLOC(sizeof(mfu_pred_times));
t->secs = times[0];
t->nsecs = times[1] * 1000;
return t;
}
/* given a find-like number string (N, +N, -N) and a base times structure,
* allocate and return a structure that records a comparison to this base time */
mfu_pred_times_rel* mfu_pred_relative(const char* str, const mfu_pred_times* t)
{
/* parse time string */
int cmp;
uint64_t val;
parse_number((const char*)str, &cmp, &val);
mfu_pred_times_rel* r = (mfu_pred_times_rel*) MFU_MALLOC(sizeof(mfu_pred_times_rel));
r->direction = cmp;
r->magnitude = val;
r->t.secs = t->secs;
r->t.nsecs = t->nsecs;
return r;
}
int MFU_PRED_TYPE (mfu_flist flist, uint64_t idx, void* arg)
{
mode_t type = *((mode_t*)arg);
mode_t mode = (mode_t) mfu_flist_file_get_mode(flist, idx);
return (mode & S_IFMT) == type;
}
int MFU_PRED_NAME (mfu_flist flist, uint64_t idx, void* arg)
{
char* pattern = (char*) arg;
const char* name = mfu_flist_file_get_name(flist, idx);
char* tmpname = MFU_STRDUP(name);
int ret = fnmatch(pattern, basename(tmpname), FNM_PERIOD) ? 0 : 1;
mfu_free(&tmpname);
return ret;
}
int MFU_PRED_PATH (mfu_flist flist, uint64_t idx, void* arg)
{
char* pattern = (char*) arg;
const char* name = mfu_flist_file_get_name(flist, idx);
int ret = fnmatch(pattern, name, FNM_PERIOD) ? 0 : 1;
return ret;
}
int MFU_PRED_REGEX (mfu_flist flist, uint64_t idx, void* arg)
{
/* run regex on full path */
regex_t* regex = (regex_t*) arg;
const char* name = mfu_flist_file_get_name(flist, idx);
int regex_return = regexec(regex, name, 0, NULL, 0);
int ret = (regex_return == 0) ? 1 : 0;
return ret;
}
int MFU_PRED_GID (mfu_flist flist, uint64_t idx, void* arg)
{
uint64_t id = mfu_flist_file_get_gid(flist, idx);
int cmp;
uint64_t val;
parse_number((char*)arg, &cmp, &val);
int ret = 0;
if (cmp > 0) {
/* check whether id is greater than target */
if (id > val) {
ret = 1;
}
} else if (cmp < 0) {
/* check whether id is less than target */
if (id < val) {
ret = 1;
}
} else {
/* check whether id is equal to target */
if (id == val) {
ret = 1;
}
}
return ret;
}
int MFU_PRED_GROUP (mfu_flist flist, uint64_t idx, void* arg)
{
char* pattern = (char*) arg;
const char* str = mfu_flist_file_get_groupname(flist, idx);
int ret = 0;
if (strcmp(str, pattern) == 0) {
ret = 1;
}
return ret;
}
int MFU_PRED_UID (mfu_flist flist, uint64_t idx, void* arg)
{
uint64_t id = mfu_flist_file_get_uid(flist, idx);
int cmp;
uint64_t val;
parse_number((char*)arg, &cmp, &val);
int ret = 0;
if (cmp > 0) {
/* check whether id is greater than target */
if (id > val) {
ret = 1;
}
} else if (cmp < 0) {
/* check whether id is less than target */
if (id < val) {
ret = 1;
}
} else {
/* check whether id is equal to target */
if (id == val) {
ret = 1;
}
}
return ret;
}
int MFU_PRED_USER (mfu_flist flist, uint64_t idx, void* arg)
{
char* pattern = (char*) arg;
const char* str = mfu_flist_file_get_username(flist, idx);
int ret = 0;
if (strcmp(str, pattern) == 0) {
ret = 1;
}
return ret;
}
int MFU_PRED_SIZE (mfu_flist flist, uint64_t idx, void* arg)
{
int ret = 0;
uint64_t size = mfu_flist_file_get_size(flist, idx);
char* str = (char*) arg;
unsigned long long bytes;
if (str[0] == '+') {
/* check whether size is greater than target */
mfu_abtoull(&str[1], &bytes);
if (size > (uint64_t)bytes) {
ret = 1;
}
} else if (str[0] == '-') {
/* check whether size is less than target */
mfu_abtoull(&str[1], &bytes);
if (size < (uint64_t)bytes) {
ret = 1;
}
} else {
/* check whether size is equal to target */
mfu_abtoull(str, &bytes);
if (size == (uint64_t)bytes) {
ret = 1;
}
}
return ret;
}
static int check_time (uint64_t secs, uint64_t nsecs, uint64_t units, void* arg)
{
mfu_pred_times_rel* r = (mfu_pred_times_rel*) arg;
/* compute age of item in integer number of days */
uint64_t item_nsecs = secs * 1000000000 + nsecs;
uint64_t now_nsecs = r->t.secs * 1000000000 + r->t.nsecs;
uint64_t age_nsecs = 0;
if (item_nsecs < now_nsecs) {
age_nsecs = now_nsecs - item_nsecs;
}
uint64_t age = age_nsecs / units;
/* parse parameter from user */
int cmp = r->direction;
uint64_t val = r->magnitude;
int ret = 0;
if (cmp > 0) {
/* check whether age is greater than target */
if (age > val) {
ret = 1;
}
} else if (cmp < 0) {
/* check whether age is less than target */
if (age < val) {
ret = 1;
}
} else {
/* check whether age is equal to target */
if (age == val) {
ret = 1;
}
}
return ret;
}
int MFU_PRED_AMIN (mfu_flist flist, uint64_t idx, void* arg)
{
/* get timestamp from item */
uint64_t secs = mfu_flist_file_get_atime(flist, idx);
uint64_t nsecs = mfu_flist_file_get_atime_nsec(flist, idx);
return check_time(secs, nsecs, NSECS_IN_MIN, arg);
}
int MFU_PRED_MMIN (mfu_flist flist, uint64_t idx, void* arg)
{
/* get timestamp from item */
uint64_t secs = mfu_flist_file_get_mtime(flist, idx);
uint64_t nsecs = mfu_flist_file_get_mtime_nsec(flist, idx);
return check_time(secs, nsecs, NSECS_IN_MIN, arg);
}
int MFU_PRED_CMIN (mfu_flist flist, uint64_t idx, void* arg)
{
/* get timestamp from item */
uint64_t secs = mfu_flist_file_get_ctime(flist, idx);
uint64_t nsecs = mfu_flist_file_get_ctime_nsec(flist, idx);
return check_time(secs, nsecs, NSECS_IN_MIN, arg);
}
int MFU_PRED_ATIME (mfu_flist flist, uint64_t idx, void* arg)
{
/* get timestamp from item */
uint64_t secs = mfu_flist_file_get_atime(flist, idx);
uint64_t nsecs = mfu_flist_file_get_atime_nsec(flist, idx);
return check_time(secs, nsecs, NSECS_IN_DAY, arg);
}
int MFU_PRED_MTIME (mfu_flist flist, uint64_t idx, void* arg)
{
/* get timestamp from item */
uint64_t secs = mfu_flist_file_get_mtime(flist, idx);
uint64_t nsecs = mfu_flist_file_get_mtime_nsec(flist, idx);
return check_time(secs, nsecs, NSECS_IN_DAY, arg);
}
int MFU_PRED_CTIME (mfu_flist flist, uint64_t idx, void* arg)
{
/* get timestamp from item */
uint64_t secs = mfu_flist_file_get_ctime(flist, idx);
uint64_t nsecs = mfu_flist_file_get_ctime_nsec(flist, idx);
return check_time(secs, nsecs, NSECS_IN_DAY, arg);
}
int MFU_PRED_ANEWER (mfu_flist flist, uint64_t idx, void * arg)
{
uint64_t secs = mfu_flist_file_get_atime(flist, idx);
uint64_t nsecs = mfu_flist_file_get_atime_nsec(flist, idx);
mfu_pred_times* times = (mfu_pred_times*) arg;
if (secs > times->secs ||
(secs == times->secs && nsecs > times->nsecs))
{
return 1;
} else {
return 0;
}
}
int MFU_PRED_MNEWER (mfu_flist flist, uint64_t idx, void * arg)
{
uint64_t secs = mfu_flist_file_get_mtime(flist, idx);
uint64_t nsecs = mfu_flist_file_get_mtime_nsec(flist, idx);
mfu_pred_times* times = (mfu_pred_times*) arg;
if (secs > times->secs ||
(secs == times->secs && nsecs > times->nsecs))
{
return 1;
} else {
return 0;
}
}
int MFU_PRED_CNEWER (mfu_flist flist, uint64_t idx, void * arg)
{
uint64_t secs = mfu_flist_file_get_ctime(flist, idx);
uint64_t nsecs = mfu_flist_file_get_ctime_nsec(flist, idx);
mfu_pred_times* times = (mfu_pred_times*) arg;
if (secs > times->secs ||
(secs == times->secs && nsecs > times->nsecs))
{
return 1;
} else {
return 0;
}
}
<|start_filename|>src/dcp1/cleanup.c<|end_filename|>
/*
* This file contains the logic to truncate the the destination as well as
* preserve permissions and ownership. Since it would be redundant, we only
* pay attention to the first chunk of each file and pass the rest along.
* See the file "COPYING" for the full license governing this code.
*/
#include "cleanup.h"
#include "dcp1.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <utime.h>
/** Options specified by the user. */
extern DCOPY_options_t DCOPY_user_opts;
static void DCOPY_truncate_file(DCOPY_operation_t* op, \
CIRCLE_handle* handle)
{
char dest_path_recursive[PATH_MAX];
char dest_path_file_to_file[PATH_MAX];
if(op->dest_base_appendix == NULL) {
sprintf(dest_path_recursive, "%s/%s", \
DCOPY_user_opts.dest_path, \
op->operand + op->source_base_offset + 1);
strncpy(dest_path_file_to_file, DCOPY_user_opts.dest_path, PATH_MAX);
}
else {
sprintf(dest_path_recursive, "%s/%s/%s", \
DCOPY_user_opts.dest_path, \
op->dest_base_appendix, \
op->operand + op->source_base_offset + 1);
sprintf(dest_path_file_to_file, "%s/%s", \
DCOPY_user_opts.dest_path, \
op->dest_base_appendix);
}
MFU_LOG(MFU_LOG_DBG, "Truncating file to `%" PRId64 "'.", op->file_size);
/*
* Try the recursive file before file-to-file. The cast below requires us
* to have a maximum file_size of 2^63, not 2^64.
*/
if(truncate64(dest_path_recursive, op->file_size) < 0) {
if(truncate64(dest_path_file_to_file, op->file_size) < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to truncate destination file: %s (errno=%d %s)",
dest_path_recursive, errno, strerror(errno));
DCOPY_retry_failed_operation(COPY, handle, op);
return;
}
}
}
void DCOPY_do_cleanup(DCOPY_operation_t* op, \
CIRCLE_handle* handle)
{
char* newop;
/*
* Truncate file on last chunk (synchronous mode can write past end of file)
*/
int64_t bytes_written = (int64_t)(op->chunk + 1) * (int64_t)DCOPY_user_opts.chunk_size;
if(bytes_written >= op->file_size) {
/* truncate file to appropriate size, to do this before
* setting permissions in case file does not have write permission */
DCOPY_truncate_file(op, handle);
/* since we still may access the file in the compare step,
* delay setting permissions and timestamps until final phase */
}
/*
* Add work item to compare source and destination if user requested it.
*/
if(DCOPY_user_opts.compare) {
newop = DCOPY_encode_operation(COMPARE, op->chunk, op->operand, \
op->source_base_offset, \
op->dest_base_appendix, op->file_size);
handle->enqueue(newop);
free(newop);
}
return;
}
/* EOF */
<|start_filename|>src/common/mfu_bz2.h<|end_filename|>
#ifndef MFU_BZ2_H
#define MFU_BZ2_H
int mfu_compress_bz2(const char* src_name, const char* dst_name, int b_size);
int mfu_decompress_bz2(const char* src_name, const char* dst_name);
/****************
* Private internal functions
***************/
#include "sys/types.h"
int mfu_create_fully_striped(const char* name, mode_t mode);
#endif /* MFU_BZ2_H */
<|start_filename|>src/common/mfu_compress_bz2_libcircle.c<|end_filename|>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#define _LARGEFILE64_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysinfo.h>
#include <string.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "mpi.h"
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <utime.h>
#include <bzlib.h>
#include <inttypes.h>
#include <errno.h>
#include "libcircle.h"
#include "mfu.h"
#include "mfu_bz2.h"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
struct block_info {
unsigned int length;
int rank;
int64_t offset;
int64_t sno;
};
static struct block_info* my_blocks;
static int64_t blocks_processed = 0;
static char** a;
static int64_t my_prev_blocks = 0;
static int64_t blocks_pn_pw;
static int64_t block_size;
static int64_t comp_buff_size;
static int64_t blocks_done = 0;
static int64_t wave_blocks;
static int64_t tot_blocks;
static int bc_size;
static int64_t filesize;
static char* src_name;
static char* dst_name;
static int fd;
static int fd_out;
static int64_t my_tot_blocks = 0;
/* To use libcircle, this function creates work for compression.
* It simply puts the all the block numbers for the file in the queue. */
static void DBz2_Enqueue(CIRCLE_handle* handle)
{
char* newop;
for (int i = 0; i < wave_blocks; i++) {
/* compute block id */
int64_t block_no = (int64_t)i + (int64_t)blocks_done;
if (block_no >= tot_blocks) {
break;
}
/* encode block id as string */
newop = (char*)MFU_MALLOC(sizeof(char) * 10);
sprintf(newop, "%" PRId64, block_no);
/* enqueue this block */
handle->enqueue(newop);
MFU_LOG(MFU_LOG_INFO, "Blocks queued=%" PRId64 "\n", block_no);
mfu_free(&newop);
}
}
/* process each compression block */
static void DBz2_Dequeue(CIRCLE_handle* handle)
{
/* used to check whether memory is full because the number of blocks
to be processed in a wave have been completed for this wave */
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
/* dequeue an item */
char newop[10];
handle->dequeue(newop);
/* extract block id */
int64_t block_no;
sscanf(newop, "%" PRId64, &block_no);
/* compute starting offset in source file to read from */
off_t pos = block_no * block_size;
/* seek to offset in source file for this block */
off_t lseek_rc = mfu_lseek(src_name, fd, pos, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek in source file: %s offset=%lx errno=%d (%s)",
src_name, pos, errno, strerror(errno));
//rc = MFU_FAILURE;
//continue;
MPI_Abort(MPI_COMM_WORLD, 1);
}
/* compute number of bytes to read from input file */
size_t nread = (size_t) block_size;
size_t remainder = (size_t) (filesize - pos);
if (remainder < nread) {
nread = remainder;
}
/* allocate a buffer to hold data from file */
char* ibuf = MFU_MALLOC(nread);
/* read block from input file */
ssize_t inSize = mfu_read(src_name, fd, ibuf, nread);
if (inSize != nread) {
MFU_LOG(MFU_LOG_ERR, "Failed to read from source file: %s offset=%lx got=%d expected=%d errno=%d (%s)",
src_name, pos, inSize, nread, errno, strerror(errno));
//rc = MFU_FAILURE;
//continue;
MPI_Abort(MPI_COMM_WORLD, 1);
}
/* Guaranteed max output size after compression for bz2 */
unsigned int outSize = (unsigned int)comp_buff_size;
/* compress block from read buffer into next compression buffer */
int ret = BZ2_bzBuffToBuffCompress(a[blocks_processed], &outSize, ibuf, (int)inSize, bc_size, 0, 30);
if (ret != 0) {
MFU_LOG(MFU_LOG_ERR, "Error in compression for rank %d", rank);
//rc = MFU_FAILURE;
//continue;
MPI_Abort(MPI_COMM_WORLD, 1);
}
/* set metadata for the compressed block */
my_blocks[my_tot_blocks].sno = block_no;
my_blocks[my_tot_blocks].length = outSize;
my_blocks[my_tot_blocks].rank = rank;
/* increment count of blocks we have processed */
blocks_processed++;
my_tot_blocks++;
MFU_LOG(MFU_LOG_INFO, "Processed block %" PRId64 ",num processed=%" PRId64 ",rank=%d, blocks per wave=%" PRId64 "\n", block_no, blocks_processed, rank, blocks_pn_pw);
/* free read buffer */
mfu_free(&ibuf);
}
static void find_wave_size(int64_t size, int opts_memory)
{
/* get process memory limit from rlimit, if one is set */
struct rlimit limit;
getrlimit(RLIMIT_DATA, &limit);
MFU_LOG(MFU_LOG_INFO, "The limit is %lld %lld\n", (long long)limit.rlim_cur, (long long)limit.rlim_max);
/* identify free memory on the node */
struct sysinfo info;
sysinfo(&info);
MFU_LOG(MFU_LOG_INFO, "The free and total ram are:%lu,%lu", info.freeram, info.totalram);
MFU_LOG(MFU_LOG_INFO, "The block size is:%" PRId64, size);
/* TODO: what about other procs on the same node? */
/* set our memory limit to minimum of rlimit and free memory */
int64_t mem_limit = info.freeram;
if ((unsigned long)limit.rlim_cur < info.freeram) {
mem_limit = (int64_t)limit.rlim_cur;
}
/* go lower still if user gave us a lower limit */
if (opts_memory > 0 && opts_memory < mem_limit) {
mem_limit = (int64_t)opts_memory;
}
/* memory is computed as the mem_limit is max memory for a process.
* We leave 2% of totalram free, then 8*size +400*1024 is the
* memory required to do compression, keep 128B for variables,etc.
* The block itself must be in memory before compression. */
int64_t wave_size_approx = mem_limit - (int64_t)info.totalram * 2 / 100 - 8 * size - 400 * 1024 - 128 - size;
int64_t waves_blocks_approx = wave_size_approx / comp_buff_size;
int64_t wave_size = wave_size_approx - 2 * tot_blocks * sizeof(struct block_info);
blocks_pn_pw = (int64_t)(0.4 * wave_size / comp_buff_size);
if (blocks_pn_pw > 800) {
blocks_pn_pw = 800;
}
//int blocks_n_w=(int)blocks_pn_pw;
/* find minimum across all processes */
MPI_Allreduce(&blocks_pn_pw, &wave_blocks, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD);
}
int mfu_compress_bz2_libcircle(const char* src, const char* dst, int b_size, ssize_t opts_memory)
{
int rc = MFU_SUCCESS;
/* copy source and target file names */
src_name = MFU_STRDUP(src);
dst_name = MFU_STRDUP(dst);
/* get rank and size of the communicator */
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
/* read stat info for source file */
struct stat st;
int stat_flag = 1;
filesize = 0;
if (rank == 0) {
/* stat file to get file size */
int lstat_rc = mfu_lstat(src_name, &st);
if (lstat_rc == 0) {
filesize = (int64_t) st.st_size;
} else {
/* failed to stat file for file size */
stat_flag = 0;
MFU_LOG(MFU_LOG_ERR, "Failed to stat file: %s errno=%d (%s)",
src_name, errno, strerror(errno));
}
}
/* broadcast filesize to all ranks */
MPI_Bcast(&stat_flag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&filesize, 1, MPI_INT64_T, 0, MPI_COMM_WORLD);
/* check that we could stat file */
if (! stat_flag) {
mfu_free(&src_name);
mfu_free(&dst_name);
return MFU_FAILURE;
}
/* open the source file for reading */
fd = mfu_open(src_name, O_RDONLY);
if (fd < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open file for reading: %s errno=%d (%s)",
src_name, errno, strerror(errno));
}
/* check that all processes were able to open the file */
if (! mfu_alltrue(fd >= 0, MPI_COMM_WORLD)) {
/* some process failed to open so bail with error,
* if we opened ok, close file */
if (fd >= 0) {
mfu_close(src_name, fd);
}
mfu_free(&src_name);
mfu_free(&dst_name);
return MFU_FAILURE;
}
/* open destination file for writing */
fd_out = mfu_create_fully_striped(dst_name, FILE_MODE);
if (fd_out < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open file for writing: %s errno=%d (%s)",
dst_name, errno, strerror(errno));
}
/* check that all processes were able to open the file */
if (! mfu_alltrue(fd_out >= 0, MPI_COMM_WORLD)) {
/* some process failed to open so bail with error,
* if we opened ok, close file */
if (fd_out >= 0) {
mfu_close(dst_name, fd_out);
}
mfu_free(&src_name);
mfu_free(&dst_name);
mfu_close(src_name, fd);
return MFU_FAILURE;
}
/* ensure that b_size is in range of [1,9] */
if (b_size < 1) {
b_size = 1;
}
if (b_size > 9) {
b_size = 9;
}
bc_size = b_size;
/* compute block size in bytes */
block_size = (int64_t)b_size * 100 * 1000;
/* compute total number of blocks in the file */
tot_blocks = filesize / block_size;
if (tot_blocks * block_size < filesize) {
tot_blocks++;
}
/* given original data of size B, BZ2 compressed data can take up to B * 1.01 + 600 bytes,
* we use 2% to be on safe side */
comp_buff_size = (int64_t) (1.02 * (double)block_size + 600.0);
/* compute number of blocks we can handle in a wave
* based on allowed memory per process */
find_wave_size(block_size, opts_memory);
blocks_processed = 0;
my_prev_blocks = 0;
blocks_done = 0;
my_tot_blocks = 0;
/* compute number of waves to finish file */
int64_t num_waves = tot_blocks / wave_blocks;
if (num_waves * wave_blocks < tot_blocks) {
num_waves += 1;
}
/* stores metadata of all blocks processed by this process */
my_blocks = (struct block_info*)MFU_MALLOC(sizeof(struct block_info) * blocks_pn_pw * num_waves);
struct block_info** this_wave_blocks = (struct block_info**)MFU_MALLOC(sizeof(struct block_info*)*wave_blocks);
MPI_Datatype metatype, oldtypes[3];
MPI_Aint offsets[3], extent, lb;
int blockcounts[3];
offsets[0] = 0;
oldtypes[0] = MPI_UNSIGNED;
blockcounts[0] = 1;
MPI_Type_get_extent(MPI_UNSIGNED, &lb, &extent);
offsets[1] = extent;
oldtypes[1] = MPI_INT;
blockcounts[1] = 1;
MPI_Type_get_extent(MPI_INT, &lb, &extent);
offsets[2] = extent + offsets[1];
oldtypes[2] = MPI_INT64_T;
blockcounts[2] = 2;
MPI_Type_create_struct(3, blockcounts, offsets, oldtypes, &metatype);
MPI_Type_commit(&metatype);
struct block_info rbuf[wave_blocks];
/* allocate a compression buffer for each block */
a = (char**)MFU_MALLOC(sizeof(char*) * wave_blocks);
for (int i = 0; i < wave_blocks; i++) {
a[i] = (char*)MFU_MALLOC(comp_buff_size);
//memset(a[i],1,comp_buff_size*sizeof(char));
}
/* Call libcircle in a loop to work each wave as a single instance of libcircle */
int64_t last_offset = 0;
for (blocks_done = 0; blocks_done < tot_blocks; blocks_done += wave_blocks) {
/* compute number of blocks in this wave */
int blocks_for_wave = wave_blocks;
int blocks_remaining = tot_blocks - blocks_done;
if (blocks_remaining < blocks_for_wave) {
blocks_for_wave = blocks_remaining;
}
/* execute libcircle to compress blocks */
CIRCLE_init(0, NULL, CIRCLE_DEFAULT_FLAGS);
CIRCLE_cb_create(&DBz2_Enqueue);
CIRCLE_cb_process(&DBz2_Dequeue);
CIRCLE_begin();
CIRCLE_finalize();
/* gather the number of blocks processed by each process in this wave */
int rcount[size];
MPI_Gather(&blocks_processed, 1, MPI_INT, rcount, 1, MPI_INT, 0, MPI_COMM_WORLD);
/* actual number of blocks processed by all processes in this wave */
int64_t actual_wave_blocks = 0;
for (int k = 0; k < size; k++) {
actual_wave_blocks += (int64_t)rcount[k];
}
/* compute displacements array for gatherv */
int displs[size];
displs[0] = 0;
for (int k = 1; k < size; k++) {
displs[k] = displs[k - 1] + rcount[k - 1];
}
/* Gather metadata of all blocks processed in this wave */
MPI_Gatherv(&my_blocks[my_prev_blocks], blocks_processed, metatype, rbuf, rcount, displs, metatype, 0, MPI_COMM_WORLD);
/* compute the offset of all blocks processed in current wave */
if (rank == 0) {
for (int k = 0; k < actual_wave_blocks; k++) {
this_wave_blocks[rbuf[k].sno - blocks_done] = &rbuf[k];
}
this_wave_blocks[0]->offset = last_offset;
for (int k = 1; k < actual_wave_blocks; k++) {
this_wave_blocks[k]->offset = this_wave_blocks[k - 1]->offset + this_wave_blocks[k - 1]->length;
}
last_offset = this_wave_blocks[actual_wave_blocks - 1]->offset + this_wave_blocks[actual_wave_blocks - 1]->length;
}
/* provide info about the offset of coressponding blocks to process that processed it */
MPI_Scatterv(&rbuf, rcount, displs, metatype, &my_blocks[my_prev_blocks], blocks_processed, metatype, 0, MPI_COMM_WORLD);
/* Each process writes out the blocks it processed in current wave at the correct offset */
for (int k = 0; k < blocks_processed; k++) {
/* compute offset into compressed file for our block */
off_t pos = my_blocks[my_prev_blocks + k].offset;
/* seek to position in destination file for this block */
off_t lseek_rc = mfu_lseek(dst_name, fd_out, pos, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek to compressed block in target file: %s offset=%lx errno=%d (%s)",
dst_name, pos, errno, strerror(errno));
rc = MFU_FAILURE;
}
/* write out block */
size_t my_length = (size_t) my_blocks[my_prev_blocks + k].length;
ssize_t nwritten = mfu_write(dst_name, fd_out, a[k], my_length);
if (nwritten != my_length) {
MFU_LOG(MFU_LOG_ERR, "Failed to write compressed block to target file: %s offset=%lx got=%d expected=%d errno=%d (%s)",
dst_name, pos, nwritten, my_length, errno, strerror(errno));
rc = MFU_FAILURE;
}
}
my_prev_blocks = my_tot_blocks;
blocks_processed = 0;
}
/* free buffers used to hold compressed data */
for (int i = 0; i < wave_blocks; i++) {
mfu_free(&a[i]);
}
mfu_free(&a);
/* End of all waves */
MPI_Barrier(MPI_COMM_WORLD);
/* Broadcast offset of start of trailer */
MPI_Bcast(&last_offset, 1, MPI_UNSIGNED_LONG, 0, MPI_COMM_WORLD);
/* Each process writes the offset of all blocks processed by it at corect location in trailer */
for (int k = 0; k < my_tot_blocks; k++) {
/* seek to metadata location for this block */
off_t pos = last_offset + my_blocks[k].sno * 16;
off_t lseek_rc = mfu_lseek(dst_name, fd_out, pos, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek to block metadata in target file: %s offset=%lx errno=%d (%s)",
dst_name, pos, errno, strerror(errno));
rc = MFU_FAILURE;
}
/* write offset of block in destination file */
int64_t my_offset = my_blocks[k].offset;
int64_t net_offset = mfu_hton64(my_offset);
ssize_t nwritten = mfu_write(dst_name, fd_out, &net_offset, 8);
if (nwritten != 8) {
MFU_LOG(MFU_LOG_ERR, "Failed to write block offset to target file: %s pos=%lx got=%d expected=%d errno=%d (%s)",
dst_name, pos, nwritten, 8, errno, strerror(errno));
rc = MFU_FAILURE;
}
/* write length of block in destination file */
int64_t my_length = my_blocks[k].length;
int64_t net_length = mfu_hton64(my_length);
nwritten = mfu_write(dst_name, fd_out, &net_length, 8);
if (nwritten != 8) {
MFU_LOG(MFU_LOG_ERR, "Failed to write block length to target file: %s pos=%lx got=%d expected=%d errno=%d (%s)",
dst_name, pos+8, nwritten, 8, errno, strerror(errno));
rc = MFU_FAILURE;
}
}
/* root writes the locaion of trailer start to last 8 bytes of the file */
if (rank == 0) {
/* convert header fields to network order */
uint64_t footer[6];
footer[0] = mfu_hton64(last_offset); /* offset to start of block metadata */
footer[1] = mfu_hton64(tot_blocks); /* number of blocks in the file */
footer[2] = mfu_hton64(block_size); /* max size of uncompressed block */
footer[3] = mfu_hton64(filesize); /* size with all blocks decompressed */
footer[4] = mfu_hton64(1); /* file version number */
footer[5] = mfu_hton64(0x3141314131413141); /* magic number (repeating pi: 3.141) */
/* seek to position to write footer */
off_t pos = last_offset + tot_blocks * 16;
off_t lseek_rc = mfu_lseek(dst_name, fd_out, pos, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek to footer in target file: %s offset=%lx errno=%d (%s)",
dst_name, pos, errno, strerror(errno));
rc = MFU_FAILURE;
}
/* write footer */
size_t footer_size = 6 * 8;
ssize_t nwritten = mfu_write(dst_name, fd_out, footer, footer_size);
if (nwritten != footer_size) {
MFU_LOG(MFU_LOG_ERR, "Failed to write footer to target file: %s pos=%lx got=%d expected=%d errno=%d (%s)",
dst_name, pos, nwritten, footer_size, errno, strerror(errno));
rc = MFU_FAILURE;
}
}
MPI_Barrier(MPI_COMM_WORLD);
/* free memory for compress blocks */
mfu_free(&this_wave_blocks);
mfu_free(&my_blocks);
/* close source and target files */
mfu_fsync(dst_name, fd_out);
mfu_close(dst_name, fd_out);
mfu_close(src_name, fd);
/* ensure that everyone has closed and synced before updating timestamps */
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 0) {
/* set mode and group */
mfu_chmod(dst_name, st.st_mode);
mfu_lchown(dst_name, st.st_uid, st.st_gid);
/* set timestamps, mode, and group */
struct utimbuf uTimBuf;
uTimBuf.actime = st.st_atime;
uTimBuf.modtime = st.st_mtime;
utime(dst_name, &uTimBuf);
}
mfu_free(&src_name);
mfu_free(&dst_name);
return rc;
}
<|start_filename|>src/dparallel/dparallel.c<|end_filename|>
#include <stdlib.h>
#include "dparallel.h"
/** The debug stream for all logging messages. */
FILE* DPARALLEL_debug_stream;
/** The current log level of library logging output. */
enum DPARALLEL_loglevel DPARALLEL_debug_level;
/** The rank value of the current node. */
int32_t DPARALLEL_global_rank;
char* DPARALLEL_readline()
{
char* buf = (char*) malloc(sizeof(char) * CIRCLE_MAX_STRING_LEN);
if(fgets(buf, CIRCLE_MAX_STRING_LEN, stdin) != NULL) {
return buf;
}
else {
free(buf);
return 0;
}
}
void DPARALLEL_process(CIRCLE_handle* handle)
{
if(DPARALLEL_global_rank == 0) {
char* new_cmd = DPARALLEL_readline();
if(new_cmd != 0) {
LOG(DPARALLEL_LOG_DBG, "Enqueueing command `%s'.", new_cmd);
handle->enqueue(new_cmd);
free(new_cmd);
return;
}
}
char cmd[CIRCLE_MAX_STRING_LEN];
handle->dequeue(cmd);
int ret = system(cmd);
LOG(DPARALLEL_LOG_DBG, "Command `%s' returned `%d'.", cmd, ret);
return;
}
int main(void)
{
DPARALLEL_debug_level = DPARALLEL_LOG_DBG;
DPARALLEL_debug_stream = stderr;
CIRCLE_init(0, NULL, CIRCLE_DEFAULT_FLAGS);
CIRCLE_cb_process(&DPARALLEL_process);
CIRCLE_begin();
CIRCLE_finalize();
}
/* EOF */
<|start_filename|>src/common/mfu_bz2.c<|end_filename|>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/* for statfs */
#include <sys/vfs.h>
/* for LL_SUPER_MAGIC */
#if LUSTRE_SUPPORT
#include <lustre/lustre_user.h>
#endif /* LUSTRE_SUPPORT */
#include "mpi.h"
#include "mfu.h"
int mfu_compress_bz2_libcircle(const char* src_name, const char* dst_name, int b_size, ssize_t opts_memory);
int mfu_compress_bz2_static(const char* src_name, const char* dst_name, int b_size);
int mfu_decompress_bz2_libcircle(const char* src_name, const char* dst_name);
int mfu_decompress_bz2_static(const char* src_name, const char* dst_name);
int mfu_compress_bz2(const char* src_name, const char* dst_name, int b_size)
{
//return mfu_compress_bz2_libcircle(src_name, dst_name, b_size, 0);
return mfu_compress_bz2_static(src_name, dst_name, b_size);
}
int mfu_decompress_bz2(const char* src_name, const char* dst_name)
{
//return mfu_decompress_bz2_libcircle(src_name, dst_name);
return mfu_decompress_bz2_static(src_name, dst_name);
}
static int mfu_create_output(const char* name, mode_t mode)
{
/* get our rank */
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
/* The file for output is opened and options set */
int fd = -1;
if (rank == 0) {
/* open file */
fd = mfu_open(name, O_WRONLY | O_CREAT | O_TRUNC, mode);
if (fd < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open file for writing: %s errno=%d (%s)",
name, errno, strerror(errno));
}
}
/* wait for rank 0 to finish operations */
MPI_Barrier(MPI_COMM_WORLD);
/* have rest of ranks open the file */
if (rank != 0) {
fd = mfu_open(name, O_WRONLY);
if (fd < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open file for writing: %s errno=%d (%s)",
name, errno, strerror(errno));
}
}
return fd;
}
int mfu_create_fully_striped(const char* name, mode_t mode)
{
/* get our rank */
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#if LUSTRE_SUPPORT
/* have rank 0 check whether the file will be on Lustre */
int on_lustre = 0;
if (rank == 0) {
/* get directory path for file */
mfu_path* dirpath = mfu_path_from_str(name);
mfu_path_dirname(dirpath);
char* dirstr = mfu_path_strdup(dirpath);
/* statfs the directory */
errno = 0;
struct statfs fs_stat;
if (statfs(dirstr, &fs_stat) == 0) {
/* set to 1 if this path is on lustre, 0 otherwise */
on_lustre = (fs_stat.f_type == LL_SUPER_MAGIC);
} else {
MFU_LOG(MFU_LOG_ERR, "Failed to statfs: `%s' errno=%d (%s)",
dirstr, errno, strerror(errno));
}
/* free the directory name */
mfu_free(&dirstr);
mfu_path_delete(&dirpath);
}
/* broadcast result from rank 0 */
MPI_Bcast(&on_lustre, 1, MPI_INT, 0, MPI_COMM_WORLD);
/* if on lustre, set striping while opening file,
* otherwise fallback to something basic */
int fd = -1;
if (on_lustre) {
/* have rank 0 create the file with striping */
if (rank == 0) {
mfu_stripe_set(name, 1024*1024, -1);
}
/* wait for rank 0 to finish operations */
MPI_Barrier(MPI_COMM_WORLD);
/* open the file */
fd = mfu_open(name, O_WRONLY);
if (fd < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open file for writing: %s errno=%d (%s)",
name, errno, strerror(errno));
}
} else {
fd = mfu_create_output(name, mode);
}
#else
int fd = mfu_create_output(name, mode);
#endif
return fd;
}
<|start_filename|>src/dparallel/dparallel.h<|end_filename|>
#ifndef _DPARALLEL_DPARALLEL_H
#define _DPARALLEL_DPARALLEL_H
#include <libcircle.h>
#include "log.h"
#include <limits.h>
#include <stdlib.h>
#include <string.h>
char* DPARALLEL_readline(void);
void DPARALLEL_process(CIRCLE_handle* handle);
#endif /* _DPARALLEL_DPARALLEL_H */
<|start_filename|>src/dcp1/cleanup.h<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
#ifndef __DCP_CLEANUP_H
#define __DCP_CLEANUP_H
#include "common.h"
void DCOPY_do_cleanup(DCOPY_operation_t* op,
CIRCLE_handle* handle);
#endif /* __DCP_CLEANUP_H */
<|start_filename|>src/dcp1/dcp1.h<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
#ifndef __DCP_H_
#define __DCP_H_
#include "common.h"
void DCOPY_print_usage(void);
#endif /* __DCP_H_ */
<|start_filename|>test/tests/test_dcp/checkfiemap.c<|end_filename|>
/* GPL HEADER START
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 only,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is included
* in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; If not, see http://www.gnu.org/licenses
*
* Please visit http://www.xyratex.com/contact if you need additional
* information or have any questions.
*
* GPL HEADER END
*/
/*
* Copyright 2013 Xyratex Technology Limited
*
* Author: <NAME> <<EMAIL>>
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <getopt.h>
#ifndef HAVE_FIEMAP
# include <linux/types.h>
# include <linux/fiemap.h>
#endif
#ifndef FS_IOC_FIEMAP
# define FS_IOC_FIEMAP (_IOWR('f', 11, struct fiemap))
#endif
#define ONEMB 1048576
static int __check_fiemap(int fd, long long orig_size, int test)
{
/* This buffer is enougth for 1MB length file */
union { struct fiemap f; char c[4096]; } fiemap_buf;
struct fiemap *fiemap = &fiemap_buf.f;
struct fiemap_extent *fm_extents = &fiemap->fm_extents[0];
unsigned int count = (sizeof(fiemap_buf) - sizeof(*fiemap)) /
sizeof(*fm_extents);
unsigned int i = 0;
long long file_size = 0;
memset(&fiemap_buf, 0, sizeof(fiemap_buf));
fiemap->fm_start = 0;
fiemap->fm_flags = FIEMAP_FLAG_SYNC;
fiemap->fm_extent_count = count;
fiemap->fm_length = FIEMAP_MAX_OFFSET;
if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0) {
fprintf(stderr, "error while ioctl %i\n", errno);
return -1;
}
if (test)
return 0;
for (i = 0; i < fiemap->fm_mapped_extents; i++) {
printf("extent in "
"offset %lu, length %lu\n"
"flags: %x\n",
(unsigned long)fm_extents[i].fe_logical,
(unsigned long)fm_extents[i].fe_length,
fm_extents[i].fe_flags);
if (fm_extents[i].fe_flags & FIEMAP_EXTENT_UNWRITTEN) {
fprintf(stderr, "Unwritten extent\n");
return -2;
} else {
file_size += fm_extents[i].fe_length;
}
}
printf("file size %lli, original size %lli\n", file_size, orig_size);
return file_size != orig_size;
}
/* This test executes fiemap ioctl and check
* a) there are no file ranges marked with FIEMAP_EXTENT_UNWRITTEN
* b) data ranges sizes sum is equal to given in second param */
static int check_fiemap(int fd, long long orig_size) {
return __check_fiemap(fd, orig_size, 0);
}
static int test_fiemap_support(int fd) {
return __check_fiemap(fd, 0, 1);
}
int main(int argc, char **argv)
{
int c;
struct option long_opts[] = {
{ .name = "test", .has_arg = required_argument, .val = 't' },
{ .name = NULL }
};
char *filename = NULL;
int fd;
int rc;
optind = 0;
while ((c = getopt_long(argc, argv, "t", long_opts, NULL)) != -1) {
switch (c) {
case 't':
filename = optarg;
fd = open(filename, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "cannot open %s for reading, error %i\n",
argv[optind], errno);
return -1;
}
return test_fiemap_support(fd);
default:
fprintf(stderr, "error: %s: option '%s' unrecognized\n",
argv[0], argv[optind - 1]);
return -1;
}
}
if (optind != argc - 2) {
fprintf(stderr, "Usage: %s <filename> <filesize>\n", argv[0]);
return -1;
}
fd = open(argv[optind], O_RDONLY);
if (fd < 0) {
fprintf(stderr, "cannot open %s for reading, error %i\n",
argv[optind], errno);
return -1;
}
fprintf(stderr, "fd: %i\n", fd);
rc = check_fiemap(fd, atoll(argv[optind + 1]));
if (close(fd) < 0)
fprintf(stderr, "closing %s, error %i", argv[optind], errno);
return rc;
}
<|start_filename|>src/dcp1/treewalk.c<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
/*
* This file contains the logic to walk all of the source objects and place
* them on the queue.
*
* In the case of directories, we'll simply read the contents of a directory
* and place each sub-object back on the queue to be treewalked again. In the
* case of files, we chunk up each file and place it on the queue as another
* libcircle action to be later processed by the COPY and CLEANUP stages.
*/
#include "treewalk.h"
#include "dcp1.h"
#include <dirent.h>
#include <errno.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/time.h>
/** Options specified by the user. */
extern DCOPY_options_t DCOPY_user_opts;
/** Statistics to gather for summary output. */
extern DCOPY_statistics_t DCOPY_statistics;
/* given path, return level within directory tree */
static int compute_depth(const char* path)
{
const char* c;
int depth = 0;
for (c = path; *c != '\0'; c++) {
if (*c == '/') {
depth++;
}
}
return depth;
}
/**
* This function copies a link.
*/
static void DCOPY_stat_process_link(DCOPY_operation_t* op,
const struct stat64* statbuf,
CIRCLE_handle* handle)
{
/* increment our link count by one */
DCOPY_statistics.total_links++;
/* get source and destination paths */
const char* src_path = op->operand;
const char* dest_path = op->dest_full_path;
/* read link and terminate string with NUL character */
char path[PATH_MAX + 1];
ssize_t rc = mfu_readlink(src_path, path, sizeof(path) - 1);
if(rc < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to read link `%s' readlink() errno=%d %s",
src_path, errno, strerror(errno)
);
return;
}
/* ensure that string ends with NUL */
path[rc] = '\0';
/* create new link */
int symrc = mfu_symlink(path, dest_path);
if(symrc < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to create link `%s' symlink() errno=%d %s",
dest_path, errno, strerror(errno)
);
return;
}
/* set permissions on link */
if (DCOPY_user_opts.preserve) {
DCOPY_copy_xattrs(op, statbuf, dest_path);
DCOPY_copy_ownership(statbuf, dest_path);
DCOPY_copy_permissions(statbuf, dest_path);
}
return;
}
/**
* This function inputs a file and creates chunk operations that get placed
* onto the libcircle queue for future processing by the copy stage.
*/
static void DCOPY_stat_process_file(DCOPY_operation_t* op,
const struct stat64* statbuf,
CIRCLE_handle* handle)
{
/* increment our file count by one */
DCOPY_statistics.total_files++;
/* get file size, and increment total bytes */
int64_t file_size = (int64_t)statbuf->st_size;
DCOPY_statistics.total_size += file_size;
/* compute number of chunks */
int64_t num_chunks = file_size / (int64_t)DCOPY_user_opts.chunk_size;
MFU_LOG(MFU_LOG_DBG, "File `%s' size is `%" PRId64 \
"' with chunks `%" PRId64 "' (total `%" PRId64 "')", \
op->operand, file_size, num_chunks, \
num_chunks * (int64_t)DCOPY_user_opts.chunk_size);
const char* dest_path = op->dest_full_path;
/* since file systems like Lustre require xattrs to be set before file is opened,
* we first create it with mknod and then set xattrs */
/* create file with mknod
* for regular files, dev argument is supposed to be ignored,
* see makedev() to create valid dev */
dev_t dev;
memset(&dev, 0, sizeof(dev_t));
int mknod_rc = mfu_mknod(dest_path, DCOPY_DEF_PERMS_FILE | S_IFREG, dev);
if(mknod_rc < 0) {
if(errno == EEXIST) {
/* TODO: should we unlink and mknod again in this case? */
}
MFU_LOG(MFU_LOG_DBG, "File `%s' mknod() errno=%d %s",
dest_path, errno, strerror(errno)
);
}
/* copy extended attributes, important to do this first before
* writing data because some attributes tell file system how to
* stripe data, e.g., Lustre */
if (DCOPY_user_opts.preserve) {
DCOPY_copy_xattrs(op, statbuf, dest_path);
}
/* Encode and enqueue each chunk of the file for processing later. */
int64_t chunk_index = 0;
while(chunk_index < num_chunks) {
char* newop = DCOPY_encode_operation(COPY, chunk_index, op->operand, \
op->source_base_offset, \
op->dest_base_appendix, file_size);
handle->enqueue(newop);
free(newop);
chunk_index++;
}
/* Encode and enqueue the last partial chunk. */
if((num_chunks * (int64_t)DCOPY_user_opts.chunk_size) < file_size || num_chunks == 0) {
char* newop = DCOPY_encode_operation(COPY, chunk_index, op->operand, \
op->source_base_offset, \
op->dest_base_appendix, file_size);
handle->enqueue(newop);
free(newop);
}
}
/**
* This function reads the contents of a directory and generates appropriate
* libcircle operations for every object in the directory. It then places those
* operations on the libcircle queue and returns.
*/
static void DCOPY_stat_process_dir(DCOPY_operation_t* op,
const struct stat64* statbuf,
CIRCLE_handle* handle)
{
/* increment our directory count by one */
DCOPY_statistics.total_dirs++;
/* get destination path */
const char* dest_path = op->dest_full_path;
/* first, create the destination directory */
MFU_LOG(MFU_LOG_DBG, "Creating directory `%s'", dest_path);
int rc = mfu_mkdir(dest_path, DCOPY_DEF_PERMS_DIR);
if(rc != 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to create directory `%s' (errno=%d %s)", \
dest_path, errno, strerror(errno));
return;
}
/* copy extended attributes on directory */
if (DCOPY_user_opts.preserve) {
DCOPY_copy_xattrs(op, statbuf, dest_path);
}
/* iterate through source directory and add items to queue */
DIR* curr_dir = mfu_opendir(op->operand);
if(curr_dir == NULL) {
/* failed to open directory */
MFU_LOG(MFU_LOG_ERR, "Unable to open dir `%s' errno=%d %s", \
op->operand, errno, strerror(errno));
DCOPY_retry_failed_operation(TREEWALK, handle, op);
return;
}
else {
struct dirent* curr_ent;
while((curr_ent = mfu_readdir(curr_dir)) != NULL) {
char* curr_dir_name = curr_ent->d_name;
/* We don't care about . or .. */
if((strncmp(curr_dir_name, ".", 2)) && (strncmp(curr_dir_name, "..", 3))) {
/* build new object name */
char newop_path[PATH_MAX];
sprintf(newop_path, "%s/%s", op->operand, curr_dir_name);
MFU_LOG(MFU_LOG_DBG, "Stat operation is enqueueing `%s'", newop_path);
/* Distributed recursion here. */
char* newop = DCOPY_encode_operation(TREEWALK, 0, newop_path, \
op->source_base_offset, op->dest_base_appendix, op->file_size);
handle->enqueue(newop);
free(newop);
}
}
}
mfu_closedir(curr_dir);
return;
}
/**
* This is the entry point for the "file stat stage". This function is called
* from the jump table required for the main libcircle callbacks.
*/
void DCOPY_do_treewalk(DCOPY_operation_t* op,
CIRCLE_handle* handle)
{
struct stat64 statbuf;
const char* path = op->operand;
/* stat the item */
if(mfu_lstat64(path, &statbuf) < 0) {
/* this may happen while trying to stat whose parent directory
* does not have execute bit set */
MFU_LOG(MFU_LOG_WARN, "stat failed, skipping file `%s' errno=%d %s", path, errno, strerror(errno));
//DCOPY_retry_failed_operation(TREEWALK, handle, op);
return;
}
/* get the file mode */
mode_t mode = statbuf.st_mode;
/* first check that we handle this file type */
if(! S_ISDIR(mode) &&
! S_ISREG(mode) &&
! S_ISLNK(mode))
{
if (S_ISCHR(mode)) {
MFU_LOG(MFU_LOG_ERR, "Encountered an unsupported file type S_ISCHR at `%s'", path);
} else if (S_ISBLK(mode)) {
MFU_LOG(MFU_LOG_ERR, "Encountered an unsupported file type S_ISBLK at `%s'", path);
} else if (S_ISFIFO(mode)) {
MFU_LOG(MFU_LOG_ERR, "Encountered an unsupported file type S_ISFIFO at `%s'", path);
} else if (S_ISSOCK(mode)) {
MFU_LOG(MFU_LOG_ERR, "Encountered an unsupported file type S_ISSOCK at `%s'", path);
} else {
MFU_LOG(MFU_LOG_ERR, "Encountered an unsupported file type mode=%x at `%s'", mode, path);
}
return;
}
/* TODO: Does access query the file system? If so, it will be more
* efficient to do this check locally, e.g., get info like group
* lists once and then do all checks by hand */
/* skip files that aren't readable */
if(S_ISREG(mode) && mfu_access(path, R_OK) < 0) {
MFU_LOG(MFU_LOG_WARN, "Skipping unreadable file `%s' errno=%d %s", path, errno, strerror(errno));
return;
}
/* skip directories that aren't readable */
if(S_ISDIR(mode) && mfu_access(path, R_OK) < 0) {
MFU_LOG(MFU_LOG_WARN, "Skipping unreadable directory `%s' errno=%d %s", path, errno, strerror(errno));
return;
}
/* create new element to record file path and stat info */
DCOPY_stat_elem_t* elem = (DCOPY_stat_elem_t*) MFU_MALLOC(sizeof(DCOPY_stat_elem_t));
elem->file = MFU_STRDUP(op->dest_full_path);
elem->sb = (struct stat64*) MFU_MALLOC(sizeof(struct stat64));
elem->depth = compute_depth(op->dest_full_path);
memcpy(elem->sb, &statbuf, sizeof(struct stat64));
elem->next = NULL;
/* append element to tail of linked list */
if (DCOPY_list_head == NULL) {
DCOPY_list_head = elem;
}
if (DCOPY_list_tail != NULL) {
DCOPY_list_tail->next = elem;
}
DCOPY_list_tail = elem;
/* handle item depending on its type */
if(S_ISDIR(mode)) {
/* MFU_LOG(MFU_LOG_DBG, "Stat operation found a directory at `%s'", path); */
DCOPY_stat_process_dir(op, &statbuf, handle);
}
else if(S_ISREG(mode)) {
/* MFU_LOG(MFU_LOG_DBG, "Stat operation found a file at `%s'", path); */
DCOPY_stat_process_file(op, &statbuf, handle);
}
else if(S_ISLNK(mode)) {
/* MFU_LOG(MFU_LOG_DBG, "Stat operation found a link at `%s'", path); */
DCOPY_stat_process_link(op, &statbuf, handle);
}
else {
MFU_LOG(MFU_LOG_ERR, "Encountered an unsupported file type mode=%x at `%s'", mode, path);
DCOPY_retry_failed_operation(TREEWALK, handle, op);
return;
}
}
/* EOF */
<|start_filename|>src/common/mfu_bz2_static.c<|end_filename|>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#define _LARGEFILE64_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysinfo.h>
#include <string.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "mpi.h"
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <utime.h>
#include <bzlib.h>
#include <inttypes.h>
#include <errno.h>
#include "libcircle.h"
#include "mfu.h"
#include "mfu_bz2.h"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
int mfu_compress_bz2_static(const char* src_name, const char* dst_name, int b_size)
{
int rc = MFU_SUCCESS;
/* get rank and size of communicator */
int rank, ranks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &ranks);
/* read stat info for source file */
struct stat st;
int stat_flag = 1;
int64_t filesize = 0;
if (rank == 0) {
/* stat file to get file size */
int lstat_rc = mfu_lstat(src_name, &st);
if (lstat_rc == 0) {
filesize = (int64_t) st.st_size;
} else {
/* failed to stat file for file size */
stat_flag = 0;
MFU_LOG(MFU_LOG_ERR, "Failed to stat file: %s errno=%d (%s)",
src_name, errno, strerror(errno));
}
}
/* broadcast filesize to all ranks */
MPI_Bcast(&stat_flag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&filesize, 1, MPI_INT64_T, 0, MPI_COMM_WORLD);
/* check that we could stat file */
if (! stat_flag) {
return MFU_FAILURE;
}
/* ensure that b_size is in range of [1,9] */
if (b_size < 1) {
b_size = 1;
}
if (b_size > 9) {
b_size = 9;
}
/* compute block size in bytes */
int64_t bwt_size = (int64_t)b_size * 100 * 1000;
/* slice file into integer number of blocks based on bwt size */
int64_t max_block_size = 10 * 1024 * 1024;
int64_t bwt_per_block = max_block_size / bwt_size;
int64_t block_size = bwt_per_block * bwt_size;
/* compute total number of blocks in the file */
int64_t tot_blocks = filesize / block_size;
if (tot_blocks * block_size < filesize) {
tot_blocks++;
}
/* compute max number of blocks this process will handle */
int64_t blocks_per_rank = tot_blocks / ranks;
if (blocks_per_rank * ranks < tot_blocks) {
blocks_per_rank++;
}
/* open the source file for reading */
int fd = mfu_open(src_name, O_RDONLY | O_LARGEFILE);
if (fd < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open file for reading: %s errno=%d (%s)",
src_name, errno, strerror(errno));
}
/* check that all processes were able to open the file */
if (! mfu_alltrue(fd >= 0, MPI_COMM_WORLD)) {
/* some process failed to open so bail with error,
* if we opened ok, close file */
if (fd >= 0) {
mfu_close(src_name, fd);
}
return MFU_FAILURE;
}
/* open destination file for writing */
int fd_out = mfu_create_fully_striped(dst_name, FILE_MODE);
if (fd_out < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open file for writing: %s errno=%d (%s)",
dst_name, errno, strerror(errno));
}
/* check that all processes were able to open the file */
if (! mfu_alltrue(fd_out >= 0, MPI_COMM_WORLD)) {
/* some process failed to open so bail with error,
* if we opened ok, close file */
if (fd_out >= 0) {
mfu_close(dst_name, fd_out);
}
mfu_close(src_name, fd);
return MFU_FAILURE;
}
/* given original data of size B, BZ2 compressed data can take up to B * 1.01 + 600 bytes,
* we use 2% to be on safe side */
int64_t comp_buff_size = (int64_t) (1.02 * (double)block_size + 600.0);
/* define amount of memory to use for compressing data */
size_t bufsize = 128 * 1024 * 1024;
if (bufsize < (size_t)comp_buff_size) {
bufsize = (size_t)comp_buff_size;
}
/* compute number of blocks we can fit in buffer */
uint64_t blocks_per_buffer = bufsize / comp_buff_size;
/* compute number of waves to finish file */
int64_t blocks_per_wave = ranks * blocks_per_buffer;
int64_t num_waves = tot_blocks / blocks_per_wave;
if (num_waves * blocks_per_wave < tot_blocks) {
num_waves += 1;
}
/* allocate array to track offsets into compressed file where we
* write each of our compressed blocks */
uint64_t* my_offsets = (uint64_t*) MFU_MALLOC(blocks_per_rank * sizeof(uint64_t));
uint64_t* my_lengths = (uint64_t*) MFU_MALLOC(blocks_per_rank * sizeof(uint64_t));
/* array to store offsets and totals of each set of blocks */
uint64_t* block_lengths = (uint64_t*) MFU_MALLOC(blocks_per_buffer * sizeof(int64_t));
uint64_t* block_offsets = (uint64_t*) MFU_MALLOC(blocks_per_buffer * sizeof(int64_t));
uint64_t* block_totals = (uint64_t*) MFU_MALLOC(blocks_per_buffer * sizeof(int64_t));
/* allocate a compression buffer for each block */
char** a = (char**) MFU_MALLOC(blocks_per_buffer * sizeof(char*));
for (int i = 0; i < blocks_per_buffer; i++) {
a[i] = (char*) MFU_MALLOC(comp_buff_size * sizeof(char));
}
/* allocate buffer to read data from source file */
char* ibuf = (char*) MFU_MALLOC(sizeof(char) * block_size);
/* Call libcircle in a loop to work each wave as a single instance of libcircle */
int64_t my_blocks = 0;
int64_t last_offset = 0;
int64_t blocks_processed = 0;
for (int64_t blocks_done = 0; blocks_done < tot_blocks; blocks_done += blocks_per_wave) {
/* initialize our counts to 0 for this wave */
for (int k = 0; k < blocks_per_buffer; k++) {
block_lengths[k] = 0;
block_offsets[k] = 0;
}
/* compress blocks */
for (int k = 0; k < blocks_per_buffer; k++) {
/* compute block number for this process */
int64_t block_no = blocks_processed + rank;
/* compute starting offset in source file to read from */
off_t pos = block_no * block_size;
if (pos < filesize) {
/* seek to offset in source file for this block */
off_t lseek_rc = mfu_lseek(src_name, fd, pos, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek in source file: %s offset=%lx errno=%d (%s)",
src_name, pos, errno, strerror(errno));
rc = MFU_FAILURE;
continue;
}
/* compute number of bytes to read from input file */
size_t nread = (size_t) block_size;
size_t remainder = (size_t) (filesize - pos);
if (remainder < nread) {
nread = remainder;
}
/* read block from input file */
ssize_t inSize = mfu_read(src_name, fd, ibuf, nread);
if (inSize != nread) {
MFU_LOG(MFU_LOG_ERR, "Failed to read from source file: %s offset=%lx got=%d expected=%d errno=%d (%s)",
src_name, pos, inSize, nread, errno, strerror(errno));
rc = MFU_FAILURE;
continue;
}
/* Guaranteed max output size after compression for bz2 */
unsigned int outSize = (unsigned int)comp_buff_size;
/* compress block from read buffer into next compression buffer */
int ret = BZ2_bzBuffToBuffCompress(a[k], &outSize, ibuf, (int)inSize, b_size, 0, 30);
if (ret != 0) {
MFU_LOG(MFU_LOG_ERR, "Error in compression for rank %d", rank);
rc = MFU_FAILURE;
continue;
}
/* return size of buffer */
block_lengths[k] = (uint64_t) outSize;
}
blocks_processed += ranks;
}
/* execute scan and allreduce to compute offsets in compressed file
* for each of our blocks in this wave */
MPI_Exscan(block_lengths, block_offsets, blocks_per_buffer, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(block_lengths, block_totals, blocks_per_buffer, MPI_UINT64_T, MPI_SUM, MPI_COMM_WORLD);
/* Each process writes out the blocks it processed in current wave at the correct offset */
for (int k = 0; k < blocks_per_buffer; k++) {
/* write out our block if we have one,
* this assumes a compressed block with consume
* at least 1 byte, which is ensured by BZ2 */
if (block_lengths[k] > 0) {
/* compute offset into compressed file for our block */
off_t pos = last_offset + block_offsets[k];
/* record our offset */
my_offsets[my_blocks] = mfu_hton64((uint64_t)pos);
my_lengths[my_blocks] = mfu_hton64(block_lengths[k]);
my_blocks++;
/* seek to position in destination file for this block */
off_t lseek_rc = mfu_lseek(dst_name, fd_out, pos, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek to compressed block in target file: %s offset=%lx errno=%d (%s)",
dst_name, pos, errno, strerror(errno));
rc = MFU_FAILURE;
}
/* write out block */
ssize_t nwritten = mfu_write(dst_name, fd_out, a[k], block_lengths[k]);
if (nwritten != block_lengths[k]) {
MFU_LOG(MFU_LOG_ERR, "Failed to write compressed block to target file: %s offset=%lx got=%d expected=%d errno=%d (%s)",
dst_name, pos, nwritten, block_lengths[k], errno, strerror(errno));
rc = MFU_FAILURE;
}
}
/* update offset for next set of blocks */
last_offset += block_totals[k];
}
}
/* End of all waves */
MPI_Barrier(MPI_COMM_WORLD);
/*
size_t footer_offset_size = 10 * 1024 * 1024;
size_t single_pair_size = 16 * ranks;
if (footer_offset_size < single_pair_size) {
footer_offset_size = single_pair_size;
}
int64_t pairs_per_gather_step = footer_offset_size / single_pair_size;
for (i = 0; i < pairs_per_gather_step; i++) {
}
*/
/* TODO: gather these in larger blocks to rank 0 for writing,
* tight interleaving as written will not perform well with
* byte range locking on lustre */
/* Each process writes the offset of all blocks processed by it at corect location in trailer */
for (int k = 0; k < my_blocks; k++) {
/* seek to metadata location for this block */
int64_t block_no = ranks * k + rank;
off_t pos = last_offset + block_no * 16;
off_t lseek_rc = mfu_lseek(dst_name, fd_out, pos, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek to block metadata in target file: %s offset=%lx errno=%d (%s)",
dst_name, pos, errno, strerror(errno));
rc = MFU_FAILURE;
}
/* write offset of block in destination file */
ssize_t nwritten = mfu_write(dst_name, fd_out, &my_offsets[k], 8);
if (nwritten != 8) {
MFU_LOG(MFU_LOG_ERR, "Failed to write block offset to target file: %s pos=%lx got=%d expected=%d errno=%d (%s)",
dst_name, pos, nwritten, 8, errno, strerror(errno));
rc = MFU_FAILURE;
}
/* write length of block in destination file */
nwritten = mfu_write(dst_name, fd_out, &my_lengths[k], 8);
if (nwritten != 8) {
MFU_LOG(MFU_LOG_ERR, "Failed to write block length to target file: %s pos=%lx got=%d expected=%d errno=%d (%s)",
dst_name, pos+8, nwritten, 8, errno, strerror(errno));
rc = MFU_FAILURE;
}
}
/* root writes the locaion of trailer start to last 8 bytes of the file */
if (rank == 0) {
/* convert header fields to network order */
uint64_t footer[6];
footer[0] = mfu_hton64(last_offset); /* offset to start of block metadata */
footer[1] = mfu_hton64(tot_blocks); /* number of blocks in the file */
footer[2] = mfu_hton64(block_size); /* max size of uncompressed block */
footer[3] = mfu_hton64(filesize); /* size with all blocks decompressed */
footer[4] = mfu_hton64(1); /* file version number */
footer[5] = mfu_hton64(0x3141314131413141); /* magic number (repeating pi: 3.141) */
/* seek to position to write footer */
off_t pos = last_offset + tot_blocks * 16;
off_t lseek_rc = mfu_lseek(dst_name, fd_out, pos, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek to footer in target file: %s offset=%lx errno=%d (%s)",
dst_name, pos, errno, strerror(errno));
rc = MFU_FAILURE;
}
/* write footer */
size_t footer_size = 6 * 8;
ssize_t nwritten = mfu_write(dst_name, fd_out, footer, footer_size);
if (nwritten != footer_size) {
MFU_LOG(MFU_LOG_ERR, "Failed to write footer to target file: %s pos=%lx got=%d expected=%d errno=%d (%s)",
dst_name, pos, nwritten, footer_size, errno, strerror(errno));
rc = MFU_FAILURE;
}
}
MPI_Barrier(MPI_COMM_WORLD);
/* free read buffer */
mfu_free(&ibuf);
/* free memory regions used to store compress blocks */
for (int i = 0; i < blocks_per_buffer; i++) {
mfu_free(&a[i]);
}
mfu_free(&a);
mfu_free(&block_totals);
mfu_free(&block_offsets);
mfu_free(&block_lengths);
mfu_free(&my_lengths);
mfu_free(&my_offsets);
/* close source and target files */
mfu_fsync(dst_name, fd_out);
mfu_close(dst_name, fd_out);
mfu_close(src_name, fd);
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 0) {
/* set mode and group */
mfu_chmod(dst_name, st.st_mode);
mfu_lchown(dst_name, st.st_uid, st.st_gid);
/* set timestamps, mode, and group */
struct utimbuf uTimBuf;
uTimBuf.actime = st.st_atime;
uTimBuf.modtime = st.st_mtime;
utime(dst_name, &uTimBuf);
}
/* check that all processes wrote successfully */
if (! mfu_alltrue(rc == MFU_SUCCESS, MPI_COMM_WORLD)) {
/* TODO: delete target file? */
rc = MFU_FAILURE;
}
return rc;
}
int mfu_decompress_bz2_static(const char* src_name, const char* dst_name)
{
int rc = MFU_SUCCESS;
/* get rank and size of communicator */
int rank, ranks;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &ranks);
/* open compressed file for reading */
int fd = mfu_open(src_name, O_RDONLY | O_LARGEFILE);
if (fd < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open file for reading: %s errno=%d (%s)",
src_name, errno, strerror(errno));
}
/* check that all processes were able to open the file */
if (! mfu_alltrue(fd >= 0, MPI_COMM_WORLD)) {
/* some process failed to open so bail with error,
* if we opened ok, close file */
if (fd >= 0) {
mfu_close(src_name, fd);
}
return MFU_FAILURE;
}
/* assume that we'll read the footer */
int footer_flag = 1;
/* have arnk 0 read footer from file */
struct stat st;
uint64_t footer[7] = {0};
if (rank == 0) {
/* seek to read footer from end of file */
size_t footer_size = 6 * 8;
off_t lseek_rc = mfu_lseek(src_name, fd, -footer_size, SEEK_END);
if (lseek_rc == (off_t)-1) {
/* failed to seek to position to read footer */
footer_flag = 0;
MFU_LOG(MFU_LOG_ERR, "Failed to seek to read footer: %s errno=%d (%s)",
src_name, errno, strerror(errno));
}
/* read footer from end of file */
uint64_t file_footer[6] = {0};
ssize_t read_rc = mfu_read(src_name, fd, file_footer, footer_size);
if (read_rc == footer_size) {
/* got the footer, convert fields from network to host order */
footer[0] = mfu_ntoh64(file_footer[0]);
footer[1] = mfu_ntoh64(file_footer[1]);
footer[2] = mfu_ntoh64(file_footer[2]);
footer[3] = mfu_ntoh64(file_footer[3]);
footer[4] = mfu_ntoh64(file_footer[4]);
footer[5] = mfu_ntoh64(file_footer[5]);
} else {
/* failed to read footer */
footer_flag = 0;
MFU_LOG(MFU_LOG_ERR, "Failed to read footer: %s errno=%d (%s)",
src_name, errno, strerror(errno));
}
/* get size of file */
int lstat_rc = mfu_lstat(src_name, &st);
if (lstat_rc == 0) {
footer[6] = (uint64_t) st.st_size;
} else {
/* failed to stat file for file size */
footer_flag = 0;
MFU_LOG(MFU_LOG_ERR, "Failed to stat file: %s errno=%d (%s)",
src_name, errno, strerror(errno));
}
}
/* broadcast footer to all ranks */
MPI_Bcast(&footer_flag, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&footer, 8, MPI_UINT64_T, 0, MPI_COMM_WORLD);
/* check whether we read the footer successfully */
if (! footer_flag) {
/* failed to read footer for some reason */
mfu_close(src_name, fd);
return MFU_FAILURE;
}
/* extract values from footer into local variables */
int64_t block_meta = (int64_t)footer[0]; /* offset to start of block metadata */
int64_t block_total = (int64_t)footer[1]; /* number of blocks */
int64_t block_size = (int64_t)footer[2]; /* max uncompressed size of a block */
int64_t data_size = (int64_t)footer[3]; /* uncompressed size of all blocks */
uint64_t version = footer[4]; /* dbz2 file format footer version */
uint64_t magic = footer[5]; /* dbz2 file format magic value */
int64_t filesize = (int64_t)footer[6]; /* file size of compressed file */
/* check that we got correct magic value */
if (magic != 0x3141314131413141) {
if (rank == 0) {
MFU_LOG(MFU_LOG_ERR, "Source file does not seem to be a dbz2 file: %s",
src_name);
}
mfu_close(src_name, fd);
return MFU_FAILURE;
}
/* check that we got correct version number */
if (version != 1) {
if (rank == 0) {
MFU_LOG(MFU_LOG_ERR, "Source dbz2 file has unsupported version (%llu): %s",
(unsigned long long)version, src_name);
}
mfu_close(src_name, fd);
return MFU_FAILURE;
}
/* open destination file for writing */
int fd_out = mfu_create_fully_striped(dst_name, FILE_MODE);
if (fd_out < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open file for writing: %s errno=%d (%s)",
dst_name, errno, strerror(errno));
}
/* check that all processes were able to open the file */
if (! mfu_alltrue(fd_out >= 0, MPI_COMM_WORLD)) {
/* some process failed to open so bail with error,
* if we opened ok, close file */
if (fd_out >= 0) {
mfu_close(dst_name, fd_out);
}
mfu_close(src_name, fd);
return MFU_FAILURE;
}
/* for an uncompressed block of size block_size, BZ2 compression
* may compressed this to block_size * 1.01 + 600. User 2% for
* some breathing room when allocating buffer to read in compressed
* block */
size_t bufsize = (size_t) ((double)block_size * 1.02 + 600.0);
char* obuf = (char*) MFU_MALLOC(bufsize);
char* ibuf = (char*) MFU_MALLOC(bufsize);
int64_t processed_blocks = 0;
while (processed_blocks < block_total) {
/* compute block id we'll process in this loop */
int64_t block_no = processed_blocks + rank;
/* read block, decompress, write to target file if in range */
if (block_no < block_total) {
/* seek to metadata for this block */
off_t pos = (off_t) (block_meta + block_no * 16);
off_t lseek_rc = mfu_lseek(src_name, fd, pos, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek to block metadata in source file: %s offset=%lx errno=%d (%s)",
src_name, pos, errno, strerror(errno));
rc = MFU_FAILURE;
break;
}
/* read offset of block */
uint64_t net_offset;
ssize_t nread = mfu_read(src_name, fd, &net_offset, 8);
if (nread != 8) {
MFU_LOG(MFU_LOG_ERR, "Failed to read block offset from source file: %s offset=%lx got=%d expected=%d errno=%d (%s)",
src_name, pos, nread, 8, errno, strerror(errno));
rc = MFU_FAILURE;
break;
}
/* read length of block */
uint64_t net_length;
nread = mfu_read(src_name, fd, &net_length, 8);
if (nread != 8) {
MFU_LOG(MFU_LOG_ERR, "Failed to read block length from source file: %s offset=%lx got=%d expected=%d errno=%d (%s)",
src_name, pos+8, nread, 8, errno, strerror(errno));
rc = MFU_FAILURE;
break;
}
/* convert values from network to host order */
int64_t offset = mfu_ntoh64(net_offset);
int64_t length = mfu_ntoh64(net_length);
/* compute max size of buffer to hold uncompressed data:
* BZ2 scheme requires block_size + 1% + 600 bytes */
unsigned int outSize = (unsigned int)block_size;
/* seek to start of compressed block in source file */
lseek_rc = mfu_lseek(src_name, fd, offset, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek to block in source file: %s offset=%lx errno=%d (%s)",
src_name, offset, errno, strerror(errno));
rc = MFU_FAILURE;
break;
}
/* Read compressed block from source file */
ssize_t inSize = mfu_read(src_name, fd, (char*)ibuf, length);
if (inSize != (ssize_t)length) {
MFU_LOG(MFU_LOG_ERR, "Failed to read block from source file: %s offset=%lx got=%d expected=%d errno=%d (%s)",
src_name, offset, inSize, length, errno, strerror(errno));
rc = MFU_FAILURE;
break;
}
/* Perform decompression */
int ret = BZ2_bzBuffToBuffDecompress(obuf, &outSize, ibuf, inSize, 0, 0);
if (ret != 0) {
MFU_LOG(MFU_LOG_ERR, "Error in decompression");
rc = MFU_FAILURE;
break;
}
/* compute offset to start of uncompressed block in target file */
int64_t in_offset = block_no * block_size;
/* seek to position to write block in target file */
lseek_rc = mfu_lseek(dst_name, fd_out, in_offset, SEEK_SET);
if (lseek_rc == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Failed to seek to block in target file: %s offset=%lx errno=%d (%s)",
dst_name, in_offset, errno, strerror(errno));
rc = MFU_FAILURE;
break;
}
/* write decompressed block to target file */
ssize_t nwritten = mfu_write(dst_name, fd_out, obuf, outSize);
if (nwritten != outSize) {
MFU_LOG(MFU_LOG_ERR, "Failed to write block in target file: %s offset=%lx got=%d expected=%d errno=%d (%s)",
dst_name, in_offset, nwritten, outSize, errno, strerror(errno));
rc = MFU_FAILURE;
break;
}
}
processed_blocks += ranks;
}
/* wait for everyone to finish */
MPI_Barrier(MPI_COMM_WORLD);
/* free buffers */
mfu_free(&ibuf);
mfu_free(&obuf);
/* close source and target files */
mfu_fsync(dst_name, fd_out);
mfu_close(dst_name, fd_out);
mfu_close(src_name, fd);
MPI_Barrier(MPI_COMM_WORLD);
/* have rank 0 set meta data on target file */
if (rank == 0) {
/* set mode and group on file */
mfu_chmod(dst_name, st.st_mode);
mfu_lchown(dst_name, st.st_uid, st.st_gid);
/* set timestamps on file */
struct utimbuf uTimBuf;
uTimBuf.actime = st.st_atime;
uTimBuf.modtime = st.st_mtime;
utime(dst_name, &uTimBuf);
}
/* check that all processes wrote successfully */
if (! mfu_alltrue(rc == MFU_SUCCESS, MPI_COMM_WORLD)) {
/* TODO: delete target file? */
rc = MFU_FAILURE;
}
return rc;
}
<|start_filename|>src/common/mfu.h<|end_filename|>
/* enable C++ codes to include this header directly */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef MFU_H
#define MFU_H
#define MFU_SUCCESS (0)
#define MFU_FAILURE (1)
/* TODO: ugly hack until we get a configure test */
// HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
#define HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC 1
// HAVE_STRUCT_STAT_ST_MTIME_N
// HAVE_STRUCT_STAT_ST_UMTIME
// HAVE_STRUCT_STAT_ST_MTIME_USEC
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 500
#endif
#include <limits.h>
#include "mfu_util.h"
#include "mfu_path.h"
#include "mfu_io.h"
#include "mfu_param_path.h"
#include "mfu_flist.h"
#include "mfu_pred.h"
#include "mfu_progress.h"
#include "mfu_bz2.h"
#endif /* MFU_H */
/* enable C++ codes to include this header directly */
#ifdef __cplusplus
} /* extern "C" */
#endif
<|start_filename|>src/common/mfu_path.h<|end_filename|>
#ifndef MFU_PATH_H
#define MFU_PATH_H
#include <stdarg.h>
#include <sys/types.h>
/* TODO: for formatted strings, use special %| character (or something
* similar) to denote directories in portable way */
/* Stores path as a linked list, breaking path at each directory marker
* and terminating NUL. Can append and insert paths or cut and slice
* them. Can initialize a path from a string and extract a path into
* a string. Path consists of a number of components indexed from 0.
*
* Examples:
* * root directory "/" consists of a path with two components both of
* which are empty strings */
/*
=========================================
This file defines the data structure for a path,
which is an double-linked list of elements,
where each element contains a component (char string).
=========================================
*/
/*
=========================================
Define hash and element structures
=========================================
*/
struct mfu_path_elem_struct;
/* define the structure for a path element */
typedef struct mfu_path_elem_struct {
char* component; /* pointer to strdup'd component string */
size_t chars; /* number of chars in component */
struct mfu_path_elem_struct* next; /* pointer to next element */
struct mfu_path_elem_struct* prev; /* pointer to previous element */
} mfu_path_elem;
/* define the structure for a path object */
typedef struct {
int components; /* number of components in path */
size_t chars; /* number of chars in path */
mfu_path_elem* head; /* pointer to first element */
mfu_path_elem* tail; /* pointer to last element */
} mfu_path;
/*
=========================================
Allocate and delete path objects
=========================================
*/
/* allocates a new path */
mfu_path* mfu_path_new(void);
/* allocates a path from string */
mfu_path* mfu_path_from_str(const char* str);
/* allocates a path from formatted string */
mfu_path* mfu_path_from_strf(const char* format, ...);
/* allocates and returns a copy of path */
mfu_path* mfu_path_dup(const mfu_path* path);
/* frees a path and sets path pointer to NULL */
int mfu_path_delete(mfu_path** ptr_path);
/*
=========================================
get size and string functions
=========================================
*/
/* returns 1 if path has 0 components, 0 otherwise */
int mfu_path_is_null(const mfu_path* path);
/* return number of components in path */
int mfu_path_components(const mfu_path* path);
/* return number of characters needed to store path
* (excludes terminating NUL) */
size_t mfu_path_strlen(const mfu_path* path);
/* copy string into user buffer, abort if buffer is too small,
* return number of bytes written */
size_t mfu_path_strcpy(char* buf, size_t n, const mfu_path* path);
/* allocate memory and return path in string form,
* caller is responsible for freeing string with mfu_free() */
char* mfu_path_strdup(const mfu_path* path);
/*
=========================================
insert, append, prepend functions
=========================================
*/
/* inserts path2 so head element in path2 starts at specified offset
* in path1, e.g.,
* 0 - before first element of path1
* N-1 - before last element of path1
* N - after last element of path1 */
int mfu_path_insert(mfu_path* path1, int offset, const mfu_path* ptr_path2);
/* prepends path2 to path1 */
int mfu_path_prepend(mfu_path* path1, const mfu_path* ptr_path2);
/* appends path2 to path1 */
int mfu_path_append(mfu_path* path1, const mfu_path* ptr_path2);
/* inserts components in string so first component in string starts
* at specified offset in path, e.g.,
* 0 - before first element of path
* N-1 - before last element of path
* N - after last element of path */
int mfu_path_insert_str(mfu_path* path, int offset, const char* str);
/* prepends components in string to path */
int mfu_path_prepend_str(mfu_path* path, const char* str);
/* appends components in string to path */
int mfu_path_append_str(mfu_path* path, const char* str);
/* inserts components in string so first component in string starts
* at specified offset in path, e.g.,
* 0 - before first element of path
* N-1 - before last element of path
* N - after last element of path */
int mfu_path_insert_strf(mfu_path* path, int offset, const char* format, ...);
/* prepends components in string to path */
int mfu_path_prepend_strf(mfu_path* path, const char* format, ...);
/* adds new components to end of path using printf-like formatting */
int mfu_path_append_strf(mfu_path* path, const char* format, ...);
/*
=========================================
cut, slice, and subpath functions
=========================================
*/
/* keeps upto length components of path starting at specified location
* and discards the rest, offset can be negative to count
* from back, a negative length copies the remainder of the string */
int mfu_path_slice(mfu_path* path, int offset, int length);
/* drops last component from path */
int mfu_path_dirname(mfu_path* path);
/* only leaves last component of path */
int mfu_path_basename(mfu_path* path);
/* copies upto length components of path starting at specified location
* and returns subpath as new path, offset can be negative to count
* from back, a negative length copies the remainder of the string */
mfu_path* mfu_path_sub(mfu_path* path, int offset, int length);
/* chops path at specified location and returns remainder as new path,
* offset can be negative to count from back of path */
mfu_path* mfu_path_cut(mfu_path* path, int offset);
/*
=========================================
simplify and resolve functions
=========================================
*/
/* removes consecutive '/', '.', '..', and trailing '/' */
int mfu_path_reduce(mfu_path* path);
/* creates path from string, calls reduce, calls path_strdup,
* and deletes path, caller must free returned string with mfu_free */
char* mfu_path_strdup_reduce_str(const char* str);
/* same as above, but prepend curr working dir if path not absolute */
char* mfu_path_strdup_abs_reduce_str(const char* str);
/* return 1 if path starts with an empty string, 0 otherwise */
int mfu_path_is_absolute(const mfu_path* path);
/* value returned by mfu_path_cmp */
typedef enum {
MFU_PATH_EQUAL = 0, /* src and dest paths are same */
MFU_PATH_SRC_CHILD, /* src is contained within dest */
MFU_PATH_DEST_CHILD, /* dest is contained within child */
MFU_PATH_DIFF, /* src and dest are different and one does not contain the other */
} mfu_path_result;
/* compare two paths and return one of above results */
mfu_path_result mfu_path_cmp(const mfu_path* src, const mfu_path* dest);
/* compute and return relative path from src to dst */
mfu_path* mfu_path_relative(const mfu_path* src, const mfu_path* dst);
#endif /* MFU_PATH_H */
<|start_filename|>src/dcp1/common.c<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
#include "common.h"
#include "handle_args.h"
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
/** Where we should keep statistics related to this file copy. */
DCOPY_statistics_t DCOPY_statistics;
/** Where we should store options specified by the user. */
DCOPY_options_t DCOPY_user_opts;
/** Cache most recent open file descriptor to avoid opening / closing the same file */
DCOPY_file_cache_t DCOPY_src_cache;
DCOPY_file_cache_t DCOPY_dst_cache;
/** What rank the current process is. */
int DCOPY_global_rank;
/** Chunksize */
size_t DCOPY_chunksize;
size_t DCOPY_blocksize;
/* variables to track linked list */
DCOPY_stat_elem_t* DCOPY_list_head = NULL;
DCOPY_stat_elem_t* DCOPY_list_tail = NULL;
/** A table of function pointers used for core operation. */
void (*DCOPY_jump_table[5])(DCOPY_operation_t* op, CIRCLE_handle* handle);
void DCOPY_retry_failed_operation(DCOPY_operation_code_t target, \
CIRCLE_handle* handle, \
DCOPY_operation_t* op)
{
char* new_op;
if(DCOPY_user_opts.reliable_filesystem) {
MFU_LOG(MFU_LOG_ERR, "Not retrying failed operation. " \
"Reliable filesystem is specified. (op=%d chunk=%ld src=%s dst=%s)",
target, op->chunk, op->operand, op->dest_full_path);
DCOPY_abort(EXIT_FAILURE);
}
else {
MFU_LOG(MFU_LOG_INFO, "Attempting to retry operation.");
new_op = DCOPY_encode_operation(target, op->chunk, op->operand, \
op->source_base_offset, \
op->dest_base_appendix, op->file_size);
handle->enqueue(new_op);
mfu_free(&new_op);
}
return;
}
/**
* Encode an operation code for use on the distributed queue structure.
*/
char* DCOPY_encode_operation(DCOPY_operation_code_t code, \
int64_t chunk, \
char* operand, \
uint16_t source_base_offset, \
char* dest_base_appendix, \
int64_t file_size)
{
/*
* FIXME: This requires architecture changes in libcircle -- a redesign of
* internal queue data structures to allow void* types as queue elements
* instead of null terminated strings. Ignoring this problem by commenting
* out this check will likely cause silent data corruption.
*/
/* allocate memory to encode op */
char* op = (char*) MFU_MALLOC(CIRCLE_MAX_STRING_LEN);
/* set pointer to next byte to write to and record number of bytes left */
char* ptr = op;
size_t remaining = CIRCLE_MAX_STRING_LEN;
/* encode operation and get number of bytes required to do so */
size_t len = strlen(operand);
int written = snprintf(ptr, remaining, "%" PRId64 ":%" PRId64 ":%" PRIu16 ":%d:%d:%s", \
file_size, chunk, source_base_offset, code, (int)len, operand);
/* snprintf returns number of bytes written excluding terminating NUL,
* so if we're equal, we'd write one byte too many */
if((size_t)written >= remaining) {
MFU_LOG(MFU_LOG_ERR, \
"Exceeded libcircle message size due to large file path. " \
"This is a known bug in dcp that we intend to fix. Sorry!");
DCOPY_abort(EXIT_FAILURE);
}
/* update pointer and number of bytes remaining,
* note that we don't include the terminating NUL in this case */
ptr += written;
remaining -= (size_t) written;
/* tack on destination base appendix if we have one */
if(dest_base_appendix) {
len = strlen(dest_base_appendix);
written = snprintf(ptr, remaining, ":%d:%s", (int)len, dest_base_appendix);
/* snprintf returns number of bytes written excluding terminating NUL,
* so if we're equal, we'd write one byte too many */
if((size_t)written >= remaining) {
MFU_LOG(MFU_LOG_ERR, \
"Exceeded libcircle message size due to large file path. " \
"This is a known bug in dcp that we intend to fix. Sorry!");
DCOPY_abort(EXIT_FAILURE);
}
/* update pointer and number of bytes remaining,
* note that we don't include the terminating NUL in this case */
ptr += written;
remaining -= (size_t) written;
}
return op;
}
/**
* Decode the operation code from a message on the distributed queue structure.
*/
DCOPY_operation_t* DCOPY_decode_operation(char* op)
{
DCOPY_operation_t* ret = (DCOPY_operation_t*) malloc(sizeof(DCOPY_operation_t));
if(sscanf(strtok(op, ":"), "%" SCNd64, &(ret->file_size)) != 1) {
MFU_LOG(MFU_LOG_ERR, "Could not decode file size attribute");
DCOPY_abort(EXIT_FAILURE);
}
if(sscanf(strtok(NULL, ":"), "%" SCNd64, &(ret->chunk)) != 1) {
MFU_LOG(MFU_LOG_ERR, "Could not decode chunk index attribute");
DCOPY_abort(EXIT_FAILURE);
}
if(sscanf(strtok(NULL, ":"), "%" SCNu16, &(ret->source_base_offset)) != 1) {
MFU_LOG(MFU_LOG_ERR, "Could not decode source base offset attribute");
DCOPY_abort(EXIT_FAILURE);
}
if(sscanf(strtok(NULL, ":"), "%d", (int*) &(ret->code)) != 1) {
MFU_LOG(MFU_LOG_ERR, "Could not decode stage code attribute");
DCOPY_abort(EXIT_FAILURE);
}
/* get number of characters in operand string */
int op_len;
char* str = strtok(NULL, ":");
if(sscanf(str, "%d", &op_len) != 1) {
MFU_LOG(MFU_LOG_ERR, "Could not decode operand string length");
DCOPY_abort(EXIT_FAILURE);
}
/* skip over digits and trailing ':' to get pointer to operand */
char* operand = str + strlen(str) + 1;
ret->operand = operand;
/* if operand ends with ':', then the dest_base_appendix is next */
int dest_base_exists = 0;
if(operand[op_len] == ':') {
dest_base_exists = 1;
}
/* NUL-terminate the operand string */
operand[op_len] = '\0';
ret->dest_base_appendix = NULL;
if(dest_base_exists) {
/* get pointer to first character of dest_base_len */
str = operand + op_len + 1;
/* tokenize length and scan it in */
int dest_len;
str = strtok(str, ":");
if(sscanf(str, "%d", &dest_len) != 1) {
MFU_LOG(MFU_LOG_ERR, "Could not decode destination base appendix string length");
DCOPY_abort(EXIT_FAILURE);
}
/* skip over digits and trailing ':' to get pointer to
* destination base, and NUL-terminate the string */
char* base = str + strlen(str) + 1;
ret->dest_base_appendix = base;
base[dest_len] = '\0';
}
/* get pointer to first character past source base path, if one exists */
const char* last_component = NULL;
if(ret->source_base_offset < op_len) {
last_component = ret->operand + ret->source_base_offset + 1;
}
/* build destination object name */
int written;
char dest_path_recursive[PATH_MAX];
if(ret->dest_base_appendix == NULL) {
if (last_component == NULL) {
written = snprintf(dest_path_recursive, sizeof(dest_path_recursive),
"%s", DCOPY_user_opts.dest_path);
} else {
written = snprintf(dest_path_recursive, sizeof(dest_path_recursive),
"%s/%s", DCOPY_user_opts.dest_path, last_component);
}
}
else {
if (last_component == NULL) {
written = snprintf(dest_path_recursive, sizeof(dest_path_recursive),
"%s/%s", DCOPY_user_opts.dest_path, ret->dest_base_appendix);
} else {
written = snprintf(dest_path_recursive, sizeof(dest_path_recursive),
"%s/%s/%s", DCOPY_user_opts.dest_path, ret->dest_base_appendix, last_component);
}
}
/* fail if we would have overwritten the buffer */
if((size_t)written >= sizeof(dest_path_recursive)) {
MFU_LOG(MFU_LOG_ERR, "Destination path buffer too small");
DCOPY_abort(EXIT_FAILURE);
}
/* record destination path in operation descriptor */
ret->dest_full_path = MFU_STRDUP(dest_path_recursive);
if(ret->dest_full_path == NULL) {
MFU_LOG(MFU_LOG_ERR, "Failed to allocate full destination path");
DCOPY_abort(EXIT_FAILURE);
}
return ret;
}
/* given the address of a pointer to an operation_t struct,
* free associated memory and set pointer to NULL */
void DCOPY_opt_free(DCOPY_operation_t** optptr)
{
if(optptr != NULL) {
/* get pointer to operation_t struct */
DCOPY_operation_t* opt = (*optptr);
if(opt != NULL) {
/* free memory and then the object itself */
mfu_free(&opt->dest_full_path);
mfu_free(&opt);
}
/* set caller's pointer to NULL to catch bugs */
*optptr = NULL;
}
return;
}
int DCOPY_open_file(const char* file, int read_flag, DCOPY_file_cache_t* cache)
{
int newfd = -1;
/* see if we have a cached file descriptor */
char* name = cache->name;
if (name != NULL) {
/* we have a cached file descriptor */
int fd = cache->fd;
if (strcmp(name, file) == 0 && cache->read == read_flag) {
/* the file we're trying to open matches name and read/write mode,
* so just return the cached descriptor */
return fd;
} else {
/* the file we're trying to open is different,
* close the old file and delete the name */
mfu_close(name, fd);
mfu_free(&cache->name);
}
}
/* open the new file */
if (read_flag) {
int flags = O_RDONLY;
if (DCOPY_user_opts.synchronous) {
flags |= O_DIRECT;
}
newfd = mfu_open(file, flags);
} else {
int flags = O_WRONLY | O_CREAT;
if (DCOPY_user_opts.synchronous) {
flags |= O_DIRECT;
}
newfd = mfu_open(file, flags, DCOPY_DEF_PERMS_FILE);
}
/* cache the file descriptor */
if (newfd != -1) {
cache->name = MFU_STRDUP(file);
cache->fd = newfd;
cache->read = read_flag;
}
return newfd;
}
int DCOPY_close_file(DCOPY_file_cache_t* cache)
{
int rc = 0;
/* close file if we have one */
char* name = cache->name;
if (name != NULL) {
/* TODO: if open for write, fsync? */
int fd = cache->fd;
rc = mfu_close(name, fd);
mfu_free(&cache->name);
}
return rc;
}
/* copy all extended attributes from op->operand to dest_path */
void DCOPY_copy_xattrs(
DCOPY_operation_t* op,
const struct stat64* statbuf,
const char* dest_path)
{
#if DCOPY_USE_XATTRS
/* get source file name */
char* src_path = op->operand;
/* start with a reasonable buffer, we'll allocate more as needed */
size_t list_bufsize = 1204;
char* list = (char*) MFU_MALLOC(list_bufsize);
/* get list, if list_size == ERANGE, try again */
ssize_t list_size;
int got_list = 0;
/* get current estimate for list size */
while(! got_list) {
list_size = llistxattr(src_path, list, list_bufsize);
if(list_size < 0) {
if(errno == ERANGE) {
/* buffer is too small, free our current buffer
* and call it again with size==0 to get new size */
mfu_free(&list);
list_bufsize = 0;
}
else if(errno == ENOTSUP) {
/* this is common enough that we silently ignore it */
break;
}
else {
/* this is a real error */
MFU_LOG(MFU_LOG_ERR, "Failed to get list of extended attributes on %s llistxattr() errno=%d %s",
src_path, errno, strerror(errno)
);
break;
}
}
else {
if(list_size > 0 && list_bufsize == 0) {
/* called llistxattr with size==0 and got back positive
* number indicating size of buffer we need to allocate */
list_bufsize = (size_t) list_size;
list = (char*) MFU_MALLOC(list_bufsize);
}
else {
/* got our list, it's size is in list_size, which may be 0 */
got_list = 1;
}
}
}
/* iterate over list and copy values to new object lgetxattr/lsetxattr */
if(got_list) {
char* name = list;
while(name < list + list_size) {
/* start with a reasonable buffer,
* allocate something bigger as needed */
size_t val_bufsize = 1024;
void* val = (void*) MFU_MALLOC(val_bufsize);
/* lookup value for name */
ssize_t val_size;
int got_val = 0;
while(! got_val) {
val_size = lgetxattr(src_path, name, val, val_bufsize);
if(val_size < 0) {
if(errno == ERANGE) {
/* buffer is too small, free our current buffer
* and call it again with size==0 to get new size */
mfu_free(&val);
val_bufsize = 0;
}
else if(errno == ENOATTR) {
/* source object no longer has this attribute,
* maybe deleted out from under us */
break;
}
else {
/* this is a real error */
MFU_LOG(MFU_LOG_ERR, "Failed to get value for name=%s on %s llistxattr() errno=%d %s",
name, src_path, errno, strerror(errno)
);
break;
}
}
else {
if(val_size > 0 && val_bufsize == 0) {
/* called lgetxattr with size==0 and got back positive
* number indicating size of buffer we need to allocate */
val_bufsize = (size_t) val_size;
val = (void*) MFU_MALLOC(val_bufsize);
}
else {
/* got our value, it's size is in val_size, which may be 0 */
got_val = 1;
}
}
}
/* set attribute on destination object */
if(got_val) {
int setrc = lsetxattr(dest_path, name, val, (size_t) val_size, 0);
if(setrc != 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to set value for name=%s on %s llistxattr() errno=%d %s",
name, dest_path, errno, strerror(errno)
);
}
}
/* free value string */
mfu_free(&val);
val_bufsize = 0;
/* jump to next name */
size_t namelen = strlen(name) + 1;
name += namelen;
}
}
/* free space allocated for list */
mfu_free(&list);
list_bufsize = 0;
return;
#endif /* DCOPY_USE_XATTR */
}
void DCOPY_copy_ownership(
const struct stat64* statbuf,
const char* dest_path)
{
/* note that we use lchown to change ownership of link itself, it path happens to be a link */
if(mfu_lchown(dest_path, statbuf->st_uid, statbuf->st_gid) != 0) {
/* TODO: are there other EPERM conditions we do want to report? */
/* since the user running dcp may not be the owner of the
* file, we could hit an EPERM error here, and the file
* will be left with the effective uid and gid of the dcp
* process, don't bother reporting an error for that case */
if (errno != EPERM) {
MFU_LOG(MFU_LOG_ERR, "Failed to change ownership on %s lchown() errno=%d %s",
dest_path, errno, strerror(errno)
);
}
}
return;
}
/* TODO: condionally set setuid and setgid bits? */
void DCOPY_copy_permissions(
const struct stat64* statbuf,
const char* dest_path)
{
/* change mode */
if(! S_ISLNK(statbuf->st_mode)) {
if(mfu_chmod(dest_path, statbuf->st_mode) != 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to change permissions on %s chmod() errno=%d %s",
dest_path, errno, strerror(errno)
);
}
}
return;
}
void DCOPY_copy_timestamps(
const struct stat64* statbuf,
const char* dest_path)
{
/* read atime, mtime, and ctime second values from stat */
uint64_t atime_sec = (uint64_t) statbuf->st_atime;
uint64_t mtime_sec = (uint64_t) statbuf->st_mtime;
uint64_t ctime_sec = (uint64_t) statbuf->st_ctime;
/* now read nanoseconds if we can */
uint64_t atime_nsec, mtime_nsec, ctime_nsec;
#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
atime_nsec = (uint64_t) statbuf->st_atimespec.tv_nsec;
ctime_nsec = (uint64_t) statbuf->st_ctimespec.tv_nsec;
mtime_nsec = (uint64_t) statbuf->st_mtimespec.tv_nsec;
#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
atime_nsec = (uint64_t) statbuf->st_atim.tv_nsec;
ctime_nsec = (uint64_t) statbuf->st_ctim.tv_nsec;
mtime_nsec = (uint64_t) statbuf->st_mtim.tv_nsec;
#elif HAVE_STRUCT_STAT_ST_MTIME_N
atime_nsec = (uint64_t) statbuf->st_atime_n;
ctime_nsec = (uint64_t) statbuf->st_ctime_n;
mtime_nsec = (uint64_t) statbuf->st_mtime_n;
#elif HAVE_STRUCT_STAT_ST_UMTIME
atime_nsec = (uint64_t) statbuf->st_uatime * 1000;
ctime_nsec = (uint64_t) statbuf->st_uctime * 1000;
mtime_nsec = (uint64_t) statbuf->st_umtime * 1000;
#elif HAVE_STRUCT_STAT_ST_MTIME_USEC
atime_nsec = (uint64_t) statbuf->st_atime_usec * 1000;
ctime_nsec = (uint64_t) statbuf->st_ctime_usec * 1000;
mtime_nsec = (uint64_t) statbuf->st_mtime_usec * 1000;
#else
atime_nsec = 0;
ctime_nsec = 0;
mtime_nsec = 0;
#endif
/* fill in time structures */
struct timespec times[2];
times[0].tv_sec = (time_t) atime_sec;
times[0].tv_nsec = (long) atime_nsec;
times[1].tv_sec = (time_t) mtime_sec;
times[1].tv_nsec = (long) mtime_nsec;
/* set times with nanosecond precision using utimensat,
* assume path is relative to current working directory,
* if it's not absolute, and set times on link (not target file)
* if dest_path refers to a link */
if(utimensat(AT_FDCWD, dest_path, times, AT_SYMLINK_NOFOLLOW) != 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to change timestamps on %s utime() errno=%d %s",
dest_path, errno, strerror(errno)
);
}
#if 0
/* TODO: see stat-time.h and get_stat_atime/mtime/ctime to read sub-second times,
* and use utimensat to set sub-second times */
/* as last step, change timestamps */
if(! S_ISLNK(statbuf->st_mode)) {
struct utimbuf times;
times.actime = statbuf->st_atime;
times.modtime = statbuf->st_mtime;
if(utime(dest_path, ×) != 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to change timestamps on %s utime() errno=%d %s",
dest_path, errno, strerror(errno)
);
}
}
else {
struct timeval tv[2];
tv[0].tv_sec = statbuf->st_atime;
tv[0].tv_usec = 0;
tv[1].tv_sec = statbuf->st_mtime;
tv[1].tv_usec = 0;
if(lutimes(dest_path, tv) != 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to change timestamps on %s utime() errno=%d %s",
dest_path, errno, strerror(errno)
);
}
}
#endif
return;
}
/* called by single process upon detection of a problem */
void DCOPY_abort(int code)
{
MPI_Abort(MPI_COMM_WORLD, code);
exit(code);
}
/* called globally by all procs to exit */
void DCOPY_exit(int code)
{
/* CIRCLE_finalize or will this hang? */
mfu_finalize();
MPI_Finalize();
exit(code);
}
/* EOF */
<|start_filename|>src/dcp1/copy.c<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
#include "copy.h"
#include "treewalk.h"
#include "dcp1.h"
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <inttypes.h>
/** Options specified by the user. */
extern DCOPY_options_t DCOPY_user_opts;
/** Statistics to gather for summary output. */
extern DCOPY_statistics_t DCOPY_statistics;
/** Cache most recent open file descriptors. */
extern DCOPY_file_cache_t DCOPY_file_cache;
/*
* Encode and enqueue the cleanup stage for this chunk so the file is
* truncated and (if specified via getopt) permissions are preserved.
*/
static void DCOPY_enqueue_cleanup_stage(DCOPY_operation_t* op,
CIRCLE_handle* handle)
{
char* newop;
newop = DCOPY_encode_operation(CLEANUP, op->chunk, op->operand,
op->source_base_offset,
op->dest_base_appendix, op->file_size);
handle->enqueue(newop);
free(newop);
}
/*
* Perform the actual copy on this chunk and increment the global statistics
* counter.
*/
static int DCOPY_perform_copy(DCOPY_operation_t* op,
int in_fd,
int out_fd,
off_t offset)
{
/* seek to offset in source file */
if(mfu_lseek(op->operand, in_fd, offset, SEEK_SET) == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Couldn't seek in source path `%s' errno=%d %s", \
op->operand, errno, strerror(errno));
/* Handle operation requeue in parent function. */
return -1;
}
/* seek to offset in destination file */
if(mfu_lseek(op->dest_full_path, out_fd, offset, SEEK_SET) == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Couldn't seek in destination path `%s' errno=%d %s", \
op->dest_full_path, errno, strerror(errno));
/* Handle operation requeue in parent function. */
return -1;
}
/* get buffer */
size_t buf_size = DCOPY_user_opts.block_size;
void* buf = DCOPY_user_opts.block_buf1;
/* write data */
size_t total_bytes = 0;
size_t chunk_size = DCOPY_user_opts.chunk_size;
while(total_bytes <= chunk_size) {
/* determine number of bytes that we can read = max(buf size, remaining chunk) */
size_t left_to_read = chunk_size - total_bytes;
if(left_to_read > buf_size) {
left_to_read = buf_size;
}
/* read data from source file */
ssize_t num_of_bytes_read = mfu_read(op->operand, in_fd, buf, left_to_read);
/* check for EOF */
if(!num_of_bytes_read) {
break;
}
/* compute number of bytes to write */
size_t bytes_to_write = (size_t) num_of_bytes_read;
if(DCOPY_user_opts.synchronous) {
/* O_DIRECT requires particular write sizes,
* ok to write beyond end of file so long as
* we truncate in cleanup step */
size_t remainder = buf_size - (size_t) num_of_bytes_read;
if(remainder > 0) {
/* zero out the end of the buffer for security,
* don't want to leave data from another file at end of
* current file if we fail before truncating */
char* bufzero = ((char*)buf + num_of_bytes_read);
memset(bufzero, 0, remainder);
}
/* assumes buf_size is magic size for O_DIRECT */
bytes_to_write = buf_size;
}
/* write data to destination file */
ssize_t num_of_bytes_written = mfu_write(op->dest_full_path, out_fd, buf,
bytes_to_write);
/* check that we wrote the same number of bytes that we read */
if(num_of_bytes_written < 0) {
MFU_LOG(MFU_LOG_ERR, "Write error when copying from `%s' to `%s' errno=%d %s",
op->operand, op->dest_full_path, errno, strerror(errno));
/* Handle operation requeue in parent function. */
return -1;
}
/* check that we wrote the same number of bytes that we read */
if((size_t)num_of_bytes_written != bytes_to_write) {
MFU_LOG(MFU_LOG_ERR, "Write error when copying from `%s' to `%s'",
op->operand, op->dest_full_path);
/* Handle operation requeue in parent function. */
return -1;
}
/* add bytes to our total (use bytes read,
* which may be less than number written) */
total_bytes += (size_t) num_of_bytes_read;
}
#if 0
/* force data to file system */
if(total_bytes > 0) {
mfu_fsync(op->dest_full_path, out_fd);
}
#endif
/* Increment the global counter. */
DCOPY_statistics.total_bytes_copied += (int64_t) total_bytes;
MFU_LOG(MFU_LOG_DBG, "Wrote `%zu' bytes at segment `%" PRId64 \
"', offset `%" PRId64 "' (`%" PRId64 "' total)",
total_bytes, op->chunk, (int64_t)DCOPY_user_opts.chunk_size * op->chunk,
DCOPY_statistics.total_bytes_copied);
return 1;
}
/* The entrance point to the copy operation. */
void DCOPY_do_copy(DCOPY_operation_t* op,
CIRCLE_handle* handle)
{
/* open the input file */
int in_fd = DCOPY_open_file(op->operand, 1, &DCOPY_src_cache);
if(in_fd < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open input file `%s' errno=%d %s",
op->operand, errno, strerror(errno));
DCOPY_retry_failed_operation(COPY, handle, op);
return;
}
/* compute starting byte offset */
off_t chunk_size = (off_t) DCOPY_user_opts.chunk_size;
off_t offset = chunk_size * op->chunk;
/* hint that we'll read from file sequentially */
// posix_fadvise(in_fd, offset, chunk_size, POSIX_FADV_SEQUENTIAL);
/* open the output file */
int out_fd = DCOPY_open_file(op->dest_full_path, 0, &DCOPY_dst_cache);
if(out_fd < 0) {
/* If the force option is specified, try to unlink the destination and
* reopen before doing the optional requeue. */
if(DCOPY_user_opts.force) {
mfu_unlink(op->dest_full_path);
out_fd = DCOPY_open_file(op->dest_full_path, 0, &DCOPY_dst_cache);
}
/* requeue operation */
if(out_fd < 0) {
MFU_LOG(MFU_LOG_ERR, "Failed to open output file `%s' errno=%d %s",
op->dest_full_path, errno, strerror(errno));
DCOPY_retry_failed_operation(COPY, handle, op);
return;
}
}
/* copy data */
if(DCOPY_perform_copy(op, in_fd, out_fd, offset) < 0) {
/* we already reported an error in perform_copy */
DCOPY_retry_failed_operation(COPY, handle, op);
return;
}
DCOPY_enqueue_cleanup_stage(op, handle);
return;
}
/* EOF */
<|start_filename|>cmake/FindGPFS.cmake<|end_filename|>
# - Try to find libgpfs
# Once done this will define
# GPFS_FOUND - System has libgpfs
# GPFS_INCLUDE_DIRS - The libgpfs include directories
# GPFS_LIBRARIES - The libraries needed to use libgpfs
FIND_PATH(WITH_GPFS_PREFIX
NAMES include/gpfs.h
)
FIND_LIBRARY(GPFS_LIBRARIES
NAMES gpfs
HINTS ${WITH_GPFS_PREFIX}/lib
)
FIND_PATH(GPFS_INCLUDE_DIRS
NAMES gpfs.h
HINTS ${WITH_GPFS_PREFIX}/include
)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(GPFS DEFAULT_MSG
GPFS_LIBRARIES
GPFS_INCLUDE_DIRS
)
# Hide these vars from ccmake GUI
MARK_AS_ADVANCED(
GPFS_LIBRARIES
GPFS_INCLUDE_DIRS
)
<|start_filename|>src/common/mfu_path.c<|end_filename|>
/* Defines a double linked list representing a file path. */
#include "mfu.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdint.h>
/*
=========================================
Private functions
=========================================
*/
static inline int mfu_path_elem_init(mfu_path_elem* elem)
{
elem->component = NULL;
elem->chars = 0;
elem->next = NULL;
elem->prev = NULL;
return MFU_SUCCESS;
}
static inline int mfu_path_init(mfu_path* path)
{
path->components = 0;
path->chars = 0;
path->head = NULL;
path->tail = NULL;
return MFU_SUCCESS;
}
/* allocate and initialize a new path element */
static mfu_path_elem* mfu_path_elem_alloc(void)
{
mfu_path_elem* elem = (mfu_path_elem*) malloc(sizeof(mfu_path_elem));
if (elem != NULL) {
mfu_path_elem_init(elem);
}
else {
MFU_ABORT(-1, "Failed to allocate memory for path element");
}
return elem;
}
/* free a path element */
static int mfu_path_elem_free(mfu_path_elem** ptr_elem)
{
if (ptr_elem != NULL) {
/* got an address to the pointer of an element,
* dereference to get pointer to elem */
mfu_path_elem* elem = *ptr_elem;
if (elem != NULL) {
/* free the component which was strdup'ed */
mfu_free(&(elem->component));
}
}
/* free the element structure itself */
mfu_free(ptr_elem);
return MFU_SUCCESS;
}
/* allocate a new path */
static mfu_path* mfu_path_alloc(void)
{
mfu_path* path = (mfu_path*) malloc(sizeof(mfu_path));
if (path != NULL) {
mfu_path_init(path);
}
else {
MFU_ABORT(-1, "Failed to allocate memory for path object");
}
return path;
}
/* allocate and return a duplicate of specified elememnt,
* only copies value not next and previoud pointers */
static mfu_path_elem* mfu_path_elem_dup(const mfu_path_elem* elem)
{
/* check that element is not NULL */
if (elem == NULL) {
return NULL;
}
/* allocate new element */
mfu_path_elem* dup_elem = mfu_path_elem_alloc();
if (dup_elem == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path element");
}
/* set component and chars fields (next and prev will be set later) */
dup_elem->component = strdup(elem->component);
dup_elem->chars = elem->chars;
return dup_elem;
}
/* return element at specified offset in path
* 0 - points to first element
* N-1 - points to last element */
static mfu_path_elem* mfu_path_elem_index(const mfu_path* path, int idx)
{
/* check that we got a path */
if (path == NULL) {
MFU_ABORT(-1, "Assert that path are not NULL");
}
/* check that index is in range */
if (idx < 0 || idx >= path->components) {
MFU_ABORT(-1, "Offset %d is out of range [0,%d)",
idx, path->components
);
}
/* scan until we find element at specified index */
mfu_path_elem* current = NULL;
if (path->components > 0) {
int i;
int from_head = idx;
int from_tail = path->components - idx - 1;
if (from_head <= from_tail) {
/* shorter to start at head and go forwards */
current = path->head;
for (i = 0; i < from_head; i++) {
current = current->next;
}
}
else {
/* shorter to start at tail and go backwards */
current = path->tail;
for (i = 0; i < from_tail; i++) {
current = current->prev;
}
}
}
return current;
}
/* insert element at specified offset in path
* 0 - before first element
* N-1 - before last element
* N - after last element */
static int mfu_path_elem_insert(mfu_path* path, int offset, mfu_path_elem* elem)
{
/* check that we got a path and element */
if (path == NULL || elem == NULL) {
MFU_ABORT(-1, "Assert that path and elem are not NULL");
}
/* check that offset is in range */
if (offset < 0 || offset > path->components) {
MFU_ABORT(-1, "Offset %d is out of range",
offset, path->components
);
}
/* if offset equals number of components, insert after last element */
if (offset == path->components) {
/* attach to path */
path->components++;
path->chars += elem->chars;
/* get pointer to tail element and point to element as new tail */
mfu_path_elem* tail = path->tail;
path->tail = elem;
/* tie element to tail */
elem->prev = tail;
elem->next = NULL;
/* fix up old tail element */
if (tail != NULL) {
/* tie last element to new element */
tail->next = elem;
}
else {
/* if tail is NULL, this is the only element in path, so set head */
path->head = elem;
}
return MFU_SUCCESS;
}
/* otherwise, insert element before current element */
/* lookup element at specified offset */
mfu_path_elem* current = mfu_path_elem_index(path, offset);
/* attach to path */
path->components++;
path->chars += elem->chars;
/* insert element before current */
if (current != NULL) {
/* get pointer to element before current */
mfu_path_elem* prev = current->prev;
elem->prev = prev;
elem->next = current;
if (prev != NULL) {
/* tie previous element to new element */
prev->next = elem;
}
else {
/* if prev is NULL, this element is the new head of the path */
path->head = elem;
}
current->prev = elem;
}
else {
/* if current is NULL, this is the only element in the path */
path->head = elem;
path->tail = elem;
elem->prev = NULL;
elem->next = NULL;
}
return MFU_SUCCESS;
}
/* extract specified element from path */
static int mfu_path_elem_extract(mfu_path* path, mfu_path_elem* elem)
{
/* check that we got a path and element */
if (path == NULL || elem == NULL) {
/* nothing to do in this case */
MFU_ABORT(-1, "Assert that path and elem are not NULL");
}
/* TODO: would be nice to verify that elem is part of path */
/* subtract component and number of chars from path */
path->components--;
path->chars -= elem->chars;
/* lookup address of elements of next and previous items */
mfu_path_elem* prev = elem->prev;
mfu_path_elem* next = elem->next;
/* fix up element that comes before */
if (prev != NULL) {
/* there's an item before this one, tie it to next item */
prev->next = next;
}
else {
/* we're the first item, point head to next item */
path->head = next;
}
/* fix up element that comes after */
if (next != NULL) {
/* there's an item after this one, tie it to previous item */
next->prev = prev;
}
else {
/* we're the last item, point tail to previous item */
path->tail = prev;
}
return MFU_SUCCESS;
}
/* allocates and returns a string filled in with formatted text,
* assumes that caller has called va_start before and will call va_end
* after */
static char* mfu_path_alloc_strf(const char* format, va_list args1, va_list args2)
{
/* get length of component string */
size_t chars = (size_t) vsnprintf(NULL, 0, format, args1);
/* allocate space to hold string, add one for the terminating NUL */
size_t len = chars + 1;
char* str = (char*) malloc(len);
if (str == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path component string");
}
/* copy formatted string into new memory */
vsnprintf(str, len, format, args2);
/* return string */
return str;
}
/*
=========================================
Allocate and delete path objects
=========================================
*/
/* allocate a new path */
mfu_path* mfu_path_new()
{
mfu_path* path = mfu_path_alloc();
if (path == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path object");
}
return path;
}
/* allocates a path from string */
mfu_path* mfu_path_from_str(const char* str)
{
/* allocate a path object */
mfu_path* path = mfu_path_alloc();
if (path == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path object");
}
/* check that str is not NULL */
if (str != NULL) {
/* iterate through components of string */
const char* start = str;
const char* end = str;
while (1) {
/* scan end until we stop on a '/' or '\0' character */
while (*end != '/' && *end != '\0') {
end++;
}
/* compute number of bytes to copy this component
* (including terminating NULL) */
size_t buflen = (size_t)(end - start + 1);
char* buf = (char*) malloc(buflen);
if (buf == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for component string");
}
/* copy characters into string buffer and add terminating NUL */
size_t chars = buflen - 1;
if (chars > 0) {
strncpy(buf, start, chars);
}
buf[chars] = '\0';
/* allocate new element */
mfu_path_elem* elem = mfu_path_elem_alloc();
if (elem == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path component");
}
/* record string in element */
elem->component = buf;
elem->chars = chars;
/* add element to path */
mfu_path_elem_insert(path, path->components, elem);
if (*end != '\0') {
/* advance to next character */
end++;
start = end;
}
else {
/* stop, we've hit the end of the input string */
break;
}
}
}
return path;
}
/* allocates a path from formatted string */
mfu_path* mfu_path_from_strf(const char* format, ...)
{
/* allocate formatted string */
va_list args1, args2;
va_start(args1, format);
va_start(args2, format);
char* str = mfu_path_alloc_strf(format, args1, args2);
va_end(args2);
va_end(args1);
if (str == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path component string");
}
/* create path from string */
mfu_path* path = mfu_path_from_str(str);
/* free the string */
mfu_free(&str);
return path;
}
/* duplicate a path */
mfu_path* mfu_path_dup(const mfu_path* path)
{
/* easy if path is NULL */
if (path == NULL) {
return NULL;
}
/* allocate a new path */
mfu_path* dup_path = mfu_path_new();
if (dup_path == NULL) {
MFU_ABORT(-1, "Failed to allocate path object");
}
/* get pointer to first element and delete elements in list */
mfu_path_elem* current = path->head;
while (current != NULL) {
/* get pointer to element after current, delete current,
* and set current to next */
mfu_path_elem* dup_elem = mfu_path_elem_dup(current);
if (dup_elem == NULL) {
MFU_ABORT(-1, "Failed to allocate path element object");
}
/* insert new element at end of path */
mfu_path_elem_insert(dup_path, dup_path->components, dup_elem);
/* advance to next element */
current = current->next;
}
return dup_path;
}
/* free a path */
int mfu_path_delete(mfu_path** ptr_path)
{
if (ptr_path != NULL) {
/* got an address to the pointer of a path object,
* dereference to get pointer to path */
mfu_path* path = *ptr_path;
if (path != NULL) {
/* get pointer to first element and delete elements in list */
mfu_path_elem* current = path->head;
while (current != NULL) {
/* get pointer to element after current, delete current,
* and set current to next */
mfu_path_elem* next = current->next;
mfu_path_elem_free(¤t);
current = next;
}
}
}
/* free the path object itself */
mfu_free(ptr_path);
return MFU_SUCCESS;
}
/*
=========================================
get size and string functions
=========================================
*/
/* returns 1 if path has 0 components, 0 otherwise */
int mfu_path_is_null(const mfu_path* path)
{
if (path != NULL) {
int components = path->components;
if (components > 0) {
return 0;
}
}
return 1;
}
/* return number of components in path */
int mfu_path_components(const mfu_path* path)
{
if (path != NULL) {
int components = path->components;
return components;
}
return 0;
}
/* return number of characters needed to store path
* (not including terminating NUL) */
size_t mfu_path_strlen(const mfu_path* path)
{
if (path != NULL) {
int components = path->components;
if (components > 0) {
/* special case for root directory, we want to print "/"
* not the empty string */
mfu_path_elem* head = path->head;
if (components == 1 && strcmp(head->component, "") == 0) {
/* if we only one component and it is the empty string,
* print this as the root directory */
return 1;
}
/* otherwise, need a '/' between components so include
* this in our count */
size_t slashes = (size_t)(components - 1);
size_t chars = path->chars;
size_t len = slashes + chars;
return len;
}
}
return 0;
}
/* copies path into buf, caller must ensure buf is large enough */
static int mfu_path_strcpy_internal(char* buf, const mfu_path* path)
{
/* special case for root directory,
* we want to print "/" not the empty string */
int components = path->components;
if (components == 1 && strcmp(path->head->component, "") == 0) {
/* got the root directory, just print "/" */
strcpy(buf, "/");
return MFU_SUCCESS;
}
/* copy contents into string buffer */
char* ptr = buf;
mfu_path_elem* current = path->head;
while (current != NULL) {
/* copy component to buffer */
char* component = current->component;
size_t chars = current->chars;
memcpy((void*)ptr, (void*)component, chars);
ptr += chars;
/* if there is another component, add a slash */
mfu_path_elem* next = current->next;
if (next != NULL) {
*ptr = '/';
ptr++;
}
/* move to next component */
current = next;
}
/* terminate the string */
*ptr = '\0';
return MFU_SUCCESS;
}
/* copy string into user buffer, abort if buffer is too small */
size_t mfu_path_strcpy(char* buf, size_t n, const mfu_path* path)
{
/* check that we have a pointer to a path */
if (path == NULL) {
MFU_ABORT(-1, "Cannot copy NULL pointer to string");
}
/* we can't copy a NULL path */
if (mfu_path_is_null(path)) {
MFU_ABORT(-1, "Cannot copy a NULL path to string");
}
/* get length of path */
size_t len = mfu_path_strlen(path) + 1;
/* if user buffer is too small, abort */
if (n < len) {
MFU_ABORT(-1, "User buffer of %d bytes is too small to hold string of %d bytes",
n, len, __LINE__
);
}
/* copy contents into string buffer */
mfu_path_strcpy_internal(buf, path);
/* return number of bytes we copied to buffer */
return len;
}
/* allocate memory and return path in string form */
char* mfu_path_strdup(const mfu_path* path)
{
/* if we have no pointer to a path object return NULL */
if (path == NULL) {
return NULL;
}
/* if we have no components return NULL */
if (path->components <= 0) {
return NULL;
}
/* compute number of bytes we need to allocate and allocate string */
size_t buflen = mfu_path_strlen(path) + 1;
char* buf = (char*) malloc(buflen);
if (buf == NULL) {
MFU_ABORT(-1, "Failed to allocate buffer for path");
}
/* copy contents into string buffer */
mfu_path_strcpy_internal(buf, path);
/* return new string to caller */
return buf;
}
/*
=========================================
insert, append, prepend functions
=========================================
*/
/* integrates path2 so head element in path2 starts at specified offset
* in path1 and deletes path2, e.g.,
* 0 - before first element
* N-1 - before last element
* N - after last element */
static int mfu_path_combine(mfu_path* path1, int offset, mfu_path** ptr_path2)
{
if (path1 != NULL) {
/* check that offset is in range */
int components = path1->components;
if (offset < 0 || offset > components) {
MFU_ABORT(-1, "Offset %d is out of range [0,%d]",
offset, components
);
}
if (ptr_path2 != NULL) {
/* got an address to the pointer of a path object,
* dereference to get pointer to path */
mfu_path* path2 = *ptr_path2;
if (path2 != NULL) {
/* get pointer to head and tail of path2 */
mfu_path_elem* head2 = path2->head;
mfu_path_elem* tail2 = path2->tail;
/* if offset equals number of components, insert after last element,
* otherwise, insert element before specified element */
if (offset == components) {
/* get pointer to tail of path1 */
mfu_path_elem* tail1 = path1->tail;
if (tail1 != NULL) {
/* join tail of path1 to head of path2 */
tail1->next = head2;
}
else {
/* path1 has no items, set head to head of path2 */
path1->head = head2;
}
/* if path2 has a head element, tie it to tail of path1 */
if (head2 != NULL) {
head2->prev = tail1;
}
/* set new tail of path1 */
path1->tail = tail2;
}
else {
/* lookup element at specified offset */
mfu_path_elem* current = mfu_path_elem_index(path1, offset);
/* get pointer to element before current */
mfu_path_elem* prev = current->prev;
/* tie previous element to head of path2 */
if (prev != NULL) {
/* tie previous element to new element */
prev->next = head2;
}
else {
/* if prev is NULL, head of path2 will be new head of path1 */
path1->head = head2;
}
/* tie current to tail of path2 */
current->prev = tail2;
/* tie head of path2 to previous */
if (head2 != NULL) {
head2->prev = prev;
}
/* tie tail of path2 to current */
if (tail2 != NULL) {
tail2->next = current;
}
}
/* add component and character counts to first path */
path1->components += path2->components;
path1->chars += path2->chars;
}
}
/* free the path2 struct */
mfu_free(ptr_path2);
}
else {
MFU_ABORT(-1, "Cannot attach a path to a NULL path");
}
return MFU_SUCCESS;
}
/* inserts path2 so head element in path2 starts at specified offset
* in path1, e.g.,
* 0 - before first element of path1
* N-1 - before last element of path1
* N - after last element of path1 */
int mfu_path_insert(mfu_path* path1, int offset, const mfu_path* path2)
{
int rc = MFU_SUCCESS;
if (path1 != NULL) {
/* make a copy of path2, and combint at specified offset in path1,
* combine deletes copy of path2 */
mfu_path* path2_copy = mfu_path_dup(path2);
rc = mfu_path_combine(path1, offset, &path2_copy);
}
else {
MFU_ABORT(-1, "Cannot attach a path to a NULL path");
}
return rc;
}
/* prepends path2 to path1 */
int mfu_path_prepend(mfu_path* path1, const mfu_path* path2)
{
int rc = mfu_path_insert(path1, 0, path2);
return rc;
}
/* appends path2 to path1 */
int mfu_path_append(mfu_path* path1, const mfu_path* path2)
{
int rc = MFU_SUCCESS;
if (path1 != NULL) {
rc = mfu_path_insert(path1, path1->components, path2);
}
else {
MFU_ABORT(-1, "Cannot attach a path to a NULL path");
}
return rc;
}
/* inserts components in string so first component in string starts
* at specified offset in path, e.g.,
* 0 - before first element of path
* N-1 - before last element of path
* N - after last element of path */
int mfu_path_insert_str(mfu_path* path, int offset, const char* str)
{
/* verify that we got a path as input */
if (path == NULL) {
MFU_ABORT(-1, "Cannot insert string to a NULL path");
}
/* create a path from this string */
mfu_path* newpath = mfu_path_from_str(str);
if (newpath == NULL) {
MFU_ABORT(-1, "Failed to allocate path for insertion");
}
/* attach newpath to original path */
int rc = mfu_path_combine(path, offset, &newpath);
return rc;
}
/* prepends components in string to path */
int mfu_path_prepend_str(mfu_path* path, const char* str)
{
int rc = mfu_path_insert_str(path, 0, str);
return rc;
}
/* appends components in string to path */
int mfu_path_append_str(mfu_path* path, const char* str)
{
int rc = MFU_SUCCESS;
if (path != NULL) {
rc = mfu_path_insert_str(path, path->components, str);
}
else {
MFU_ABORT(-1, "Cannot attach string to a NULL path");
}
return rc;
}
/* inserts components in string so first component in string starts
* at specified offset in path, e.g.,
* 0 - before first element of path
* N-1 - before last element of path
* N - after last element of path */
int mfu_path_insert_strf(mfu_path* path, int offset, const char* format, ...)
{
/* verify that we got a path as input */
if (path == NULL) {
MFU_ABORT(-1, "Cannot append string to a NULL path");
}
/* allocate formatted string */
va_list args1, args2;
va_start(args1, format);
va_start(args2, format);
char* str = mfu_path_alloc_strf(format, args1, args2);
va_end(args2);
va_end(args1);
if (str == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path component string");
}
/* attach str to path */
int rc = mfu_path_insert_str(path, offset, str);
/* free the string */
mfu_free(&str);
return rc;
}
/* prepends components in string to path */
int mfu_path_prepend_strf(mfu_path* path, const char* format, ...)
{
/* verify that we got a path as input */
if (path == NULL) {
MFU_ABORT(-1, "Cannot append string to a NULL path");
}
/* allocate formatted string */
va_list args1, args2;
va_start(args1, format);
va_start(args2, format);
char* str = mfu_path_alloc_strf(format, args1, args2);
va_end(args2);
va_end(args1);
if (str == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path component string");
}
/* attach str to path */
int rc = mfu_path_insert_str(path, 0, str);
/* free the string */
mfu_free(&str);
return rc;
}
/* adds a new component to end of path using printf-like formatting */
int mfu_path_append_strf(mfu_path* path, const char* format, ...)
{
/* verify that we got a path as input */
if (path == NULL) {
MFU_ABORT(-1, "Cannot append string to a NULL path");
}
/* allocate formatted string */
va_list args1, args2;
va_start(args1, format);
va_start(args2, format);
char* str = mfu_path_alloc_strf(format, args1, args2);
va_end(args2);
va_end(args1);
if (str == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path component string");
}
/* attach str to path */
int rc = mfu_path_insert_str(path, path->components, str);
/* free the string */
mfu_free(&str);
return rc;
}
/*
=========================================
cut, slice, and subpath functions
=========================================
*/
/* keeps upto length components of path starting at specified location
* and discards the rest, offset can be negative to count
* from back, a negative length copies the remainder of the string */
int mfu_path_slice(mfu_path* path, int offset, int length)
{
/* check that we have a path */
if (path == NULL) {
return MFU_SUCCESS;
}
/* force offset into range */
int components = path->components;
if (components > 0) {
while (offset < 0) {
offset += components;
}
while (offset >= components) {
offset -= components;
}
}
else {
/* nothing left to slice */
return MFU_SUCCESS;
}
/* lookup first element to be head of new path */
mfu_path_elem* current = mfu_path_elem_index(path, offset);
/* delete any items before this one */
mfu_path_elem* elem = current->prev;
while (elem != NULL) {
mfu_path_elem* prev = elem->prev;
mfu_path_elem_free(&elem);
elem = prev;
}
/* remember our starting element and intialize tail to NULL */
mfu_path_elem* head = current;
mfu_path_elem* tail = NULL;
/* step through length elements or to the end of the list,
* a negative length means we step until end of list */
components = 0;
size_t chars = 0;
while ((length < 0 || length > 0) && current != NULL) {
/* count number of components and characters in list and
* update tail */
components++;
chars += current->chars;
tail = current;
/* advance to next element */
current = current->next;
if (length > 0) {
length--;
}
}
/* current now points to first element to be cut,
* delete it and all trailing items */
while (current != NULL) {
mfu_path_elem* next = current->next;
mfu_path_elem_free(¤t);
current = next;
}
/* set new path members */
path->components = components;
path->chars = chars;
if (components > 0) {
/* we have some components, update head and tail, terminate the list */
path->head = head;
path->tail = tail;
head->prev = NULL;
tail->next = NULL;
}
else {
/* otherwise, we have no items in the path */
path->head = NULL;
path->tail = NULL;
}
return MFU_SUCCESS;
}
/* drops last component from path */
int mfu_path_dirname(mfu_path* path)
{
int components = mfu_path_components(path);
if (components > 0) {
int rc = mfu_path_slice(path, 0, components - 1);
return rc;
}
return MFU_SUCCESS;
}
/* only leaves last component of path */
int mfu_path_basename(mfu_path* path)
{
int rc = mfu_path_slice(path, -1, 1);
return rc;
}
/* copies upto length components of path starting at specified location
* and returns subpath as new path, offset can be negative to count
* from back, a negative length copies the remainder of the string */
mfu_path* mfu_path_sub(mfu_path* path, int offset, int length)
{
/* check that we have a path */
if (path == NULL) {
return NULL;
}
/* force offset into range */
int components = path->components;
if (components > 0) {
while (offset < 0) {
offset += components;
}
while (offset >= components) {
offset -= components;
}
}
else {
/* in this case, unless length == 0, we'll fail check below,
* and if length == 0, we'll return an empty path */
offset = 0;
}
/* allocate and initialize an empty path object */
mfu_path* newpath = mfu_path_alloc();
if (newpath == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path object");
}
/* return the empty path if source path is empty */
if (components == 0) {
return newpath;
}
/* lookup first element to be head of new path */
mfu_path_elem* current = mfu_path_elem_index(path, offset);
/* copy elements from path and attach to newpath */
while ((length < 0 || length > 0) && current != NULL) {
/* duplicate element */
mfu_path_elem* elem = mfu_path_elem_dup(current);
if (elem == NULL) {
MFU_ABORT(-1, "Failed to duplicate element of path object");
}
/* insert element into newpath */
mfu_path_elem_insert(newpath, newpath->components, elem);
/* advance to next element */
current = current->next;
if (length > 0) {
length--;
}
}
/* return our newly constructed path */
return newpath;
}
/* chops path at specified location and returns remainder as new path,
* offset can be negative to count from back */
mfu_path* mfu_path_cut(mfu_path* path, int offset)
{
/* check that we have a path */
if (path == NULL) {
return NULL;
}
/* allocate and initialize an empty path object */
mfu_path* newpath = mfu_path_alloc();
if (newpath == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for path object");
}
/* if path is empty, return an empty path */
int components = path->components;
if (components == 0) {
return newpath;
}
/* force offset into range */
while (offset < 0) {
offset += components;
}
while (offset >= components) {
offset -= components;
}
/* lookup first element to be head of new path */
mfu_path_elem* current = mfu_path_elem_index(path, offset);
/* set head and tail of newpath2 */
newpath->head = current;
newpath->tail = path->tail;
/* set tail (and head) of path */
if (current != NULL) {
/* get element before current to be new tail */
mfu_path_elem* prev = current->prev;
/* cut current from previous element */
current->prev = NULL;
if (prev != NULL) {
/* cut previous element from current */
prev->next = NULL;
}
else {
/* if there is no element before current,
* we cut the first element, so update head */
path->head = NULL;
}
/* set previous element as new tail for path */
path->tail = prev;
}
else {
/* current is NULL, meaning path is empty */
path->head = NULL;
path->tail = NULL;
}
/* finally, cycle through newpath, subtract counts from path
* and add to newpath */
while (current != NULL) {
/* subtract counts from path */
path->components--;
path->chars -= current->chars;
/* add counts to newpath */
newpath->components++;
newpath->chars += current->chars;
/* advance to next element */
current = current->next;
}
/* return our newly constructed path */
return newpath;
}
/*
=========================================
simplify and resolve functions
=========================================
*/
/* removes consecutive '/', '.', '..', and trailing '/' */
int mfu_path_reduce(mfu_path* path)
{
/* check that we got a path */
if (path == NULL) {
/* nothing to do in this case */
return MFU_SUCCESS;
}
/* now iterate through and remove any "." and empty strings,
* we go from back to front to handle paths like "./" */
mfu_path_elem* current = path->tail;
while (current != NULL) {
/* get pointer to previous element */
mfu_path_elem* prev = current->prev;
/* check whether component string matches "." or "" */
char* component = current->component;
if (strcmp(component, ".") == 0) {
/* pull element out of path and delete it */
mfu_path_elem_extract(path, current);
mfu_path_elem_free(¤t);
}
else if (strcmp(component, "") == 0 && current != path->head) {
/* head is allowed to be empty string so that we don't chop leading '/' */
/* pull element out of path and delete it */
mfu_path_elem_extract(path, current);
mfu_path_elem_free(¤t);
}
/* advance to previous item */
current = prev;
}
/* now remove any ".." and any preceding component */
current = path->head;
while (current != NULL) {
/* get pointer to previous and next elements */
mfu_path_elem* prev = current->prev;
mfu_path_elem* next = current->next;
/* check whether component string matches ".." */
char* component = current->component;
if (strcmp(component, "..") == 0) {
/* pull current and previous elements out of path and delete them */
if (prev != NULL) {
/* check that previous is not "..", since we go front to back,
* previous ".." shouldn't exist unless it couldn't be popped */
char* prev_component = prev->component;
if (strcmp(prev_component, "..") != 0) {
/* check that item is not empty, only empty strings left
* should be one at very beginning of string */
if (strcmp(prev_component, "") != 0) {
/* delete previous element */
mfu_path_elem_extract(path, prev);
mfu_path_elem_free(&prev);
/* delete current element */
mfu_path_elem_extract(path, current);
mfu_path_elem_free(¤t);
}
else {
/* trying to pop past root directory, just drop the ".." */
//MFU_ABORT(-1, "Cannot pop past root directory");
mfu_path_elem_extract(path, current);
mfu_path_elem_free(¤t);
}
}
else {
/* previous is also "..", so keep going */
}
}
else {
/* we got some path like "../foo", leave it in this form */
}
}
/* advance to next item */
current = next;
}
return MFU_SUCCESS;
}
/* creates path from string, calls reduce, calls path_strdup,
* and deletes path, caller must free returned string with mfu_free */
char* mfu_path_strdup_reduce_str(const char* str)
{
mfu_path* path = mfu_path_from_str(str);
mfu_path_reduce(path);
char* newstr = mfu_path_strdup(path);
mfu_path_delete(&path);
return newstr;
}
/* same as above, but prepend curr working dir if path not absolute */
char* mfu_path_strdup_abs_reduce_str(const char* str)
{
mfu_path* path = mfu_path_from_str(str);
if (! mfu_path_is_absolute(path)) {
char cwd[PATH_MAX];
mfu_getcwd(cwd, PATH_MAX);
mfu_path_prepend_str(path, cwd);
}
mfu_path_reduce(path);
char* newstr = mfu_path_strdup(path);
mfu_path_delete(&path);
return newstr;
}
/* return 1 if path starts with an empty string, 0 otherwise */
int mfu_path_is_absolute(const mfu_path* path)
{
if (path != NULL) {
if (path->components > 0) {
const mfu_path_elem* head = path->head;
const char* component = head->component;
if (strcmp(component, "") == 0) {
return 1;
}
}
}
return 0;
}
/* given a path, create a copy, prepernd curr working dir if path
* not absolute, and reduce it */
mfu_path* mfu_path_abs_reduce(const mfu_path* path)
{
mfu_path* newpath = mfu_path_dup(path);
if (! mfu_path_is_absolute(newpath)) {
char cwd[PATH_MAX];
mfu_getcwd(cwd, PATH_MAX);
mfu_path_prepend_str(newpath, cwd);
}
mfu_path_reduce(newpath);
return newpath;
}
mfu_path_result mfu_path_cmp(const mfu_path* src, const mfu_path* dst)
{
/* check that we got pointers to both src and dst */
if (src == NULL || dst == NULL) {
/* if one is NULL but not both, consider them to be different */
if (src != NULL || dst != NULL) {
return MFU_PATH_DIFF;
}
/* both values are NULL, so consider them to be equal */
return MFU_PATH_EQUAL;
}
/* check that src and dst aren't NULL paths */
int src_null = mfu_path_is_null(src);
int dst_null = mfu_path_is_null(dst);
if (src_null || dst_null) {
/* if one is NULL but not both, consider them to be different */
if ((! src_null) || (! dst_null)) {
return MFU_PATH_DIFF;
}
/* both values are NULL, so consider them to be equal */
return MFU_PATH_EQUAL;
}
/* force source and destination to absolute form and reduce them */
mfu_path* abs_src = mfu_path_abs_reduce(src);
mfu_path* abs_dst = mfu_path_abs_reduce(dst);
/* get pointers to start of parent and child */
mfu_path_result result = MFU_PATH_EQUAL;
mfu_path_elem* src_elem = abs_src->head;
mfu_path_elem* dst_elem = abs_dst->head;
while (src_elem != NULL && dst_elem != NULL) {
/* compare strings for this element */
const char* src_component = src_elem->component;
const char* dst_component = dst_elem->component;
if (strcmp(src_component, dst_component) != 0) {
/* found a component in src that's not in dst */
result = MFU_PATH_DIFF;
break;
}
/* advance to compare next element */
src_elem = src_elem->next;
dst_elem = dst_elem->next;
}
/* if everything is equal so far, but we've run out of components,
* check to see if one is contained within the other */
if (result == MFU_PATH_EQUAL) {
if (src_elem == NULL && dst_elem != NULL) {
/* dst is contained within source */
result = MFU_PATH_DEST_CHILD;
} else if (src_elem != NULL && dst_elem == NULL) {
/* src is contained within dst */
result = MFU_PATH_SRC_CHILD;
}
}
mfu_path_delete(&abs_src);
mfu_path_delete(&abs_dst);
return result;
}
/* compute and return relative path from src to dst */
mfu_path* mfu_path_relative(const mfu_path* src, const mfu_path* dst)
{
/* check that we don't have NULL pointers */
if (src == NULL || dst == NULL) {
MFU_ABORT(-1, "Either src or dst pointer is NULL");
}
/* we can't get to a NULL path from a non-NULL path */
int src_components = src->components;
int dst_components = dst->components;
if (src_components > 0 && dst_components == 0) {
MFU_ABORT(-1, "Cannot get from non-NULL path to NULL path");
}
/* allocate a new path to record relative path */
mfu_path* rel = mfu_path_new();
if (rel == NULL) {
MFU_ABORT(-1, "Failed to allocate memory for relative path");
}
/* walk down both paths until we find the first location where they
* differ */
const mfu_path_elem* src_elem = src->head;
const mfu_path_elem* dst_elem = dst->head;
while (1) {
/* check that we have valid src and dst elements */
if (src_elem == NULL) {
break;
}
if (dst_elem == NULL) {
break;
}
/* check that the current component is the same */
const char* src_component = src_elem->component;
const char* dst_component = dst_elem->component;
if (strcmp(src_component, dst_component) != 0) {
break;
}
/* go to next component */
src_elem = src_elem->next;
dst_elem = dst_elem->next;
}
/* if there is anything left in source, we need to pop back */
while (src_elem != NULL) {
/* pop back one level, and go to next element */
mfu_path_append_str(rel, "..");
src_elem = src_elem->next;
}
/* now tack on any items left from dst */
while (dst_elem != NULL) {
const char* dst_component = dst_elem->component;
mfu_path_append_str(rel, dst_component);
dst_elem = dst_elem->next;
}
return rel;
}
/*
=========================================
I/O routines with paths
=========================================
*/
#if 0
/* tests whether the file or directory is readable */
int mfu_path_is_readable(const mfu_path* file)
{
/* convert to string and delegate to I/O routine */
char* file_str = mfu_path_strdup(file);
int rc = mfu_file_is_readable(file_str);
mfu_free(&file_str);
return rc;
}
/* tests whether the file or directory is writeable */
int mfu_path_is_writeable(const mfu_path* file)
{
/* convert to string and delegate to I/O routine */
char* file_str = mfu_path_strdup(file);
int rc = mfu_file_is_writable(file_str);
mfu_free(&file_str);
return rc;
}
#endif
#if 0
#ifndef HIDE_TV
/*
=========================================
Pretty print for TotalView debug window
=========================================
*/
/* This enables a nicer display when diving on a path variable
* under the TotalView debugger. It requires TV 8.8 or later. */
#include "tv_data_display.h"
static int TV_ttf_display_type(const mfu_path* path)
{
if (path == NULL) {
/* empty path, nothing to display here */
return TV_ttf_format_ok;
}
if (mfu_path_is_null(path)) {
/* empty path, nothing to display here */
return TV_ttf_format_ok;
}
/* print path in string form */
char* str = mfu_path_strdup(path);
TV_ttf_add_row("path", TV_ttf_type_ascii_string, str);
mfu_free(&str);
return TV_ttf_format_ok;
}
#endif /* HIDE_TV */
#endif
<|start_filename|>cmake/FindLibCircle.cmake<|end_filename|>
# - Try to find libcircle
# Once done this will define
# LibCircle_FOUND - System has libcircle
# LibCircle_INCLUDE_DIRS - The libcircle include directories
# LibCircle_LIBRARIES - The libraries needed to use libcircle
FIND_PATH(WITH_LibCircle_PREFIX
NAMES include/libcircle.h
)
FIND_LIBRARY(LibCircle_LIBRARIES
NAMES circle
HINTS ${WITH_LibCircle_PREFIX}/lib
)
FIND_PATH(LibCircle_INCLUDE_DIRS
NAMES libcircle.h
HINTS ${WITH_LibCircle_PREFIX}/include
)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibCircle DEFAULT_MSG
LibCircle_LIBRARIES
LibCircle_INCLUDE_DIRS
)
# Hide these vars from ccmake GUI
MARK_AS_ADVANCED(
LibCircle_LIBRARIES
LibCircle_INCLUDE_DIRS
)
<|start_filename|>cmake/MFU_ADD_TOOL.cmake<|end_filename|>
FUNCTION(MFU_ADD_TOOL name)
ADD_EXECUTABLE(${name} ${name}.c)
TARGET_LINK_LIBRARIES(${name} mfu m)
SET_TARGET_PROPERTIES(${name} PROPERTIES C_STANDARD 99)
INSTALL(TARGETS ${name} DESTINATION ${CMAKE_INSTALL_BINDIR})
ENDFUNCTION(MFU_ADD_TOOL name)
<|start_filename|>cmake/FindDTCMP.cmake<|end_filename|>
# - Try to find libdtcmp
# Once done this will define
# DTCMP_FOUND - System has libdtcmp
# DTCMP_INCLUDE_DIRS - The libdtcmp include directories
# DTCMP_LIBRARIES - The libraries needed to use libdtcmp
FIND_PATH(WITH_DTCMP_PREFIX
NAMES include/dtcmp.h
)
FIND_LIBRARY(DTCMP_LIBRARIES
NAMES dtcmp
HINTS ${WITH_DTCMP_PREFIX}/lib
)
FIND_PATH(DTCMP_INCLUDE_DIRS
NAMES dtcmp.h
HINTS ${WITH_DTCMP_PREFIX}/include
)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(DTCMP DEFAULT_MSG
DTCMP_LIBRARIES
DTCMP_INCLUDE_DIRS
)
# Hide these vars from ccmake GUI
MARK_AS_ADVANCED(
DTCMP_LIBRARIES
DTCMP_INCLUDE_DIRS
)
<|start_filename|>src/common/mfu_progress.c<|end_filename|>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mfu.h"
/* start progress timer */
mfu_progress* mfu_progress_start(int secs, int count, MPI_Comm comm, mfu_progress_fn progfn)
{
/* we disable progress messages if given a timeout of 0 secs */
if (secs == 0) {
return NULL;
}
mfu_progress* prg = NULL;
/* fallback to a NOP if non-blocking collectives aren't available */
#if MPI_VERSION >= 3
/* allocate a new structure */
prg = (mfu_progress*) MFU_MALLOC(sizeof(mfu_progress));
/* dup input communicator so our non-blocking collectives
* don't interfere with caller's MPI communication */
MPI_Comm_dup(comm, &prg->comm);
/* initialize broadcast and reduce requests to NULL */
prg->bcast_req = MPI_REQUEST_NULL;
prg->reduce_req = MPI_REQUEST_NULL;
/* we'll keep executing bcast/reduce iterations until
* all processes call complete */
prg->keep_going = 1;
/* record number of items to sum in progress updates */
prg->count = count;
/* allocate space to hold local and global values in reduction,
* grab one extra space to hold completion status flags across procs */
size_t bytes = (count + 1) * sizeof(uint64_t);
prg->values = (uint64_t*) MFU_MALLOC(bytes);
prg->global_vals = (uint64_t*) MFU_MALLOC(bytes);
/* record function to call to print progress */
prg->progfn = progfn;
/* set start time, initialize last time we reported, and timeout */
prg->time_start = MPI_Wtime();
prg->time_last = prg->time_start;
prg->timeout = (double) secs;
/* post buffer for incoming bcast */
int rank;
MPI_Comm_rank(prg->comm, &rank);
if (rank != 0) {
MPI_Ibcast(&(prg->keep_going), 1, MPI_INT, 0, prg->comm, &(prg->bcast_req));
}
#endif
return prg;
}
/* fallback to a NOP if non-blocking collectives aren't available */
#if MPI_VERSION >= 3
static void mfu_progress_reduce(uint64_t complete, uint64_t* vals, mfu_progress* prg)
{
/* set our complete flag to indicate whether we have finished */
prg->values[0] = complete;
/* update our local count value to contribute in reduction */
memcpy(&prg->values[1], vals, prg->count * sizeof(uint64_t));
/* initiate the reduction */
MPI_Ireduce(prg->values, prg->global_vals, prg->count + 1,
MPI_UINT64_T, MPI_SUM, 0, prg->comm, &(prg->reduce_req));
}
#endif
/* update progress across all processes in work loop */
void mfu_progress_update(uint64_t* vals, mfu_progress* prg)
{
/* return immediately if progress messages are disabled */
if (prg == NULL) {
return;
}
/* fallback to a NOP if non-blocking collectives aren't available */
#if MPI_VERSION >= 3
int rank, ranks;
MPI_Comm_rank(prg->comm, &rank);
MPI_Comm_size(prg->comm, &ranks);
int bcast_done = 0;
int reduce_done = 0;
if (rank == 0) {
/* if there are no bcast or reduce requests outstanding,
* check whether it is time to send one */
if (prg->bcast_req == MPI_REQUEST_NULL && prg->reduce_req == MPI_REQUEST_NULL) {
/* get current time and compute number of seconds since
* we last printed a message */
double now = MPI_Wtime();
double time_diff = now - prg->time_last;
/* if timeout hasn't expired do nothing, return from function */
if (time_diff < prg->timeout) {
return;
}
/* signal other procs that it's time for a reduction */
MPI_Ibcast(&(prg->keep_going), 1, MPI_INT, 0, prg->comm, &(prg->bcast_req));
/* set our complete flag to 0 to indicate that we have not finished,
* and contribute our current values */
mfu_progress_reduce(0, vals, prg);
/* reset the timer after requesting progress */
prg->time_last = MPI_Wtime();
} else {
/* got an outstanding bcast or reduce, check to see if it's done */
MPI_Test(&(prg->bcast_req), &bcast_done, MPI_STATUS_IGNORE);
MPI_Test(&(prg->bcast_req), &bcast_done, MPI_STATUS_IGNORE);
MPI_Test(&(prg->bcast_req), &bcast_done, MPI_STATUS_IGNORE);
MPI_Test(&(prg->reduce_req), &reduce_done, MPI_STATUS_IGNORE);
MPI_Test(&(prg->reduce_req), &reduce_done, MPI_STATUS_IGNORE);
MPI_Test(&(prg->reduce_req), &reduce_done, MPI_STATUS_IGNORE);
/* print new progress message when bcast and reduce have completed */
if (bcast_done && reduce_done) {
/* print progress message */
if (prg->progfn) {
double now = MPI_Wtime();
double secs = now - prg->time_start;
(*prg->progfn)(&prg->global_vals[1], prg->count, (int)prg->global_vals[0], ranks, secs);
}
}
}
} else {
/* we may have a reduce already outstanding,
* wait for it to complete before we start a new one,
* if there is no outstanding reduce, this sets the flag to 1 */
MPI_Test(&(prg->reduce_req), &reduce_done, MPI_STATUS_IGNORE);
MPI_Test(&(prg->reduce_req), &reduce_done, MPI_STATUS_IGNORE);
MPI_Test(&(prg->reduce_req), &reduce_done, MPI_STATUS_IGNORE);
/* make progress on any outstanding bcast */
MPI_Test(&(prg->bcast_req), &bcast_done, MPI_STATUS_IGNORE);
MPI_Test(&(prg->bcast_req), &bcast_done, MPI_STATUS_IGNORE);
MPI_Test(&(prg->bcast_req), &bcast_done, MPI_STATUS_IGNORE);
/* get current time and compute number of seconds since
* we last reported a message */
double now = MPI_Wtime();
double time_diff = now - prg->time_last;
/* if timeout hasn't expired do nothing, return from function */
if (time_diff < prg->timeout) {
return;
}
/* wait for rank 0 to signal us with a bcast */
if (!reduce_done || !bcast_done) {
/* not done, keep waiting */
return;
}
/* to get here, the bcast must have completed,
* so call reduce to contribute our current values */
/* set our complete flag to 0 to indicate that we have not finished,
* and contribute our current values */
mfu_progress_reduce(0, vals, prg);
/* reset the timer after reporting progress */
prg->time_last = MPI_Wtime();
/* since we are not in complete,
* we can infer that keep_going must be 1,
* so initiate new bcast for another bcast/reduce iteration */
MPI_Ibcast(&(prg->keep_going), 1, MPI_INT, 0, prg->comm, &(prg->bcast_req));
}
#endif
}
/* continue broadcasting progress until all processes have completed */
void mfu_progress_complete(uint64_t* vals, mfu_progress** pprg)
{
mfu_progress* prg = *pprg;
/* return immediately if progress messages are disabled */
if (prg == NULL) {
return;
}
/* fallback to a NOP if non-blocking collectives aren't available */
#if MPI_VERSION >= 3
int rank, ranks;
MPI_Comm_rank(prg->comm, &rank);
MPI_Comm_size(prg->comm, &ranks);
if (rank == 0) {
while (1) {
/* send a bcast/request pair */
if (prg->bcast_req == MPI_REQUEST_NULL && prg->reduce_req == MPI_REQUEST_NULL) {
/* initiate a new bcast/reduce iteration */
MPI_Ibcast(&(prg->keep_going), 1, MPI_INT, 0, prg->comm, &(prg->bcast_req));
/* we have reached complete, so set our complete flag to 1,
* and contribute our current values */
mfu_progress_reduce(1, vals, prg);
} else {
/* if there are outstanding reqs then wait for bcast
* and reduce to finish */
MPI_Wait(&(prg->bcast_req), MPI_STATUS_IGNORE);
MPI_Wait(&(prg->reduce_req), MPI_STATUS_IGNORE);
/* once outstanding bcast finishes in which we
* set keep_going == 0, we can stop */
if (prg->keep_going == 0) {
break;
}
/* print progress message */
if (prg->progfn) {
/* skip printing anything if we finish before the
* first timeout would expire */
double now = MPI_Wtime();
double secs = now - prg->time_start;
if (secs >= prg->timeout) {
(*prg->progfn)(&prg->global_vals[1], prg->count, (int)prg->global_vals[0], ranks, secs);
}
}
/* when all processes are complete, this will sum
* to the number of ranks */
if (prg->global_vals[0] == ranks) {
/* all procs are done, tell them we can
* stop with next bcast/reduce iteration */
prg->keep_going = 0;
}
}
}
} else {
/* when rank != 0 */
while (1) {
/* if have an outstanding reduce, wait for that to finish
* if not, this will return immediately */
MPI_Wait(&(prg->reduce_req), MPI_STATUS_IGNORE);
/* wait for bcast to finish */
MPI_Wait(&(prg->bcast_req), MPI_STATUS_IGNORE);
/* we have reached complete, so set our complete flag to 1,
* and contribute our current values */
mfu_progress_reduce(1, vals, prg);
/* if keep_going flag is set then wait for another bcast */
if (prg->keep_going) {
MPI_Ibcast(&(prg->keep_going), 1, MPI_INT, 0, prg->comm, &(prg->bcast_req));
} else {
/* everyone is finished, wait on the reduce we just started */
MPI_Wait(&(prg->reduce_req), MPI_STATUS_IGNORE);
break;
}
}
}
/* release communicator we dup'ed during start */
MPI_Comm_free(&prg->comm);
/* free memory allocated to hold reduction data */
mfu_free(&prg->values);
mfu_free(&prg->global_vals);
/* free our structure */
mfu_free(pprg);
#endif
}
<|start_filename|>src/dcp1/treewalk.h<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
#ifndef __DCP_TREEWALK_H
#define __DCP_TREEWALK_H
#include "common.h"
void DCOPY_do_treewalk(DCOPY_operation_t* op,
CIRCLE_handle* handle);
#endif /* __DCP_TREEWALK_H */
<|start_filename|>src/dcp1/compare.c<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
#include "compare.h"
#include "dcp1.h"
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
/** Options specified by the user. */
extern DCOPY_options_t DCOPY_user_opts;
/** Statistics to gather for summary output. */
extern DCOPY_statistics_t DCOPY_statistics;
/*
* Perform the compare on this chunk.
*/
static int DCOPY_perform_compare(DCOPY_operation_t* op,
int in_fd,
int out_fd,
off_t offset)
{
/* seek to offset in source file */
if(mfu_lseek(op->operand, in_fd, offset, SEEK_SET) == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Couldn't seek in source path `%s' errno=%d %s",
op->operand, errno, strerror(errno));
/* Handle operation requeue in parent function. */
return -1;
}
/* seek to offset in destination file */
if(mfu_lseek(op->dest_full_path, out_fd, offset, SEEK_SET) == (off_t)-1) {
MFU_LOG(MFU_LOG_ERR, "Couldn't seek in destination path `%s' errno=%d %s",
op->dest_full_path, errno, strerror(errno));
return -1;
}
/* get buffer info */
size_t buf_size = DCOPY_user_opts.block_size;
void* src_buf = DCOPY_user_opts.block_buf1;
void* dest_buf = DCOPY_user_opts.block_buf2;
/* compare bytes */
size_t total_bytes = 0;
size_t chunk_size = DCOPY_user_opts.chunk_size;
while(total_bytes <= chunk_size) {
/* determine number of bytes that we can read = max(buf size, remaining chunk) */
size_t left_to_read = chunk_size - total_bytes;
if (left_to_read > buf_size) {
left_to_read = buf_size;
}
/* read data from source and destination */
ssize_t num_of_in_bytes = mfu_read(op->operand, in_fd, src_buf, left_to_read);
ssize_t num_of_out_bytes = mfu_read(op->dest_full_path, out_fd, dest_buf, left_to_read);
/* check that we got the same number of bytes from each */
if(num_of_in_bytes != num_of_out_bytes) {
MFU_LOG(MFU_LOG_DBG, "Source byte count `%zu' does not match " \
"destination byte count '%zu' of total file size `%zu'",
num_of_in_bytes, num_of_out_bytes, op->file_size);
return -1;
}
/* check for EOF */
if(!num_of_in_bytes) {
break;
}
/* check that buffers are the same */
if(memcmp(src_buf, dest_buf, (size_t) num_of_in_bytes) != 0) {
MFU_LOG(MFU_LOG_ERR, "Compare mismatch when copying from file `%s'",
op->operand);
return -1;
}
/* add bytes to our total */
total_bytes += (size_t) num_of_in_bytes;
}
return 1;
}
/* The entrance point to the compare operation. */
void DCOPY_do_compare(DCOPY_operation_t* op,
CIRCLE_handle* handle)
{
/* open source file */
//int in_fd = mfu_open(op->operand, O_RDONLY | O_NOATIME);
int in_fd = DCOPY_open_file(op->operand, 1, &DCOPY_src_cache);
if(in_fd < 0) {
/* seems like we should retry the COMPARE here, may be overkill to COPY */
MFU_LOG(MFU_LOG_ERR, "Failed to open source file for compare `%s' errno=%d %s",
op->operand, errno, strerror(errno));
DCOPY_retry_failed_operation(COPY, handle, op);
return;
}
/* compute starting byte offset */
off_t chunk_size = (off_t) DCOPY_user_opts.chunk_size;
off_t offset = chunk_size * op->chunk;
/* hint that we'll read from file sequentially */
posix_fadvise(in_fd, offset, chunk_size, POSIX_FADV_SEQUENTIAL);
/* open destination file */
//int out_fd = mfu_open(op->dest_full_path, O_RDONLY | O_NOATIME);
int out_fd = DCOPY_open_file(op->dest_full_path, 1, &DCOPY_dst_cache);
if(out_fd < 0) {
/* assume destination file does not exist, try copy again */
MFU_LOG(MFU_LOG_ERR, "Failed to open destination file for compare " \
"`%s' errno=%d %s", op->dest_full_path, errno, strerror(errno));
DCOPY_retry_failed_operation(COPY, handle, op);
return;
}
/* hint that we'll read from file sequentially */
posix_fadvise(out_fd, offset, chunk_size, POSIX_FADV_SEQUENTIAL);
/* compare bytes */
if(DCOPY_perform_compare(op, in_fd, out_fd, offset) < 0) {
/* found incorrect data, try copy again */
MFU_LOG(MFU_LOG_ERR, "Corrupt data detected, retrying copy from `%s' to `%s'",
op->operand, op->dest_full_path);
DCOPY_retry_failed_operation(COPY, handle, op);
return;
}
#if 0
/* close destination file */
if(mfu_close(op->dest_full_path, out_fd) < 0) {
MFU_LOG(MFU_LOG_DBG, "Close on destination file failed `%s' errno=%d %s",
op->dest_full_path, errno, strerror(errno));
}
/* close source file */
if(mfu_close(op->operand, in_fd) < 0) {
MFU_LOG(MFU_LOG_DBG, "Close on source file failed `%s' errno=%d %s",
op->operand, errno, strerror(errno));
}
#endif
return;
}
/* EOF */
<|start_filename|>src/common/mfu_pred.h<|end_filename|>
/* enable C++ codes to include this header directly */
#ifdef __cplusplus
extern "C" {
#endif
#ifndef MFU_PRED_H
#define MFU_PRED_H
#include "mfu.h"
/* defines a structure that can hold the time since Linux epoch
* with nanosecond resolution */
typedef struct mfu_pred_times_t {
uint64_t secs; /* seconds since Linux epoch */
uint64_t nsecs; /* nanoseconds since last second */
} mfu_pred_times;
/* defines a structure that can hold the time since Linux epoch
* with nanosecond resolution as well as a comparison value */
typedef struct mfu_pred_times_rel_t {
int direction; /* -1 (less than), 0 (equal), 1 (greater than) */
uint64_t magnitude; /* value */
mfu_pred_times t; /* base time to be compared against */
} mfu_pred_times_rel;
/* allocate a new predicate list */
mfu_pred* mfu_pred_new(void);
/* free a predicate list, sets pointer to mfu_pred to NULL on return */
void mfu_pred_free(mfu_pred**);
/* add predicate function to chain,
* arg is optional and its meaning depends on the test being added,
* if not NULL, it should be allocated such that it can be
* freed via mfu_free() during call to mfu_pred_free() */
void mfu_pred_add(mfu_pred* pred, mfu_pred_fn predicate, void* arg);
/* execute predicate chain against specified flist item,
* returns 1 if item satisfies predicate, 0 if not, and -1 if error */
int mfu_pred_execute(mfu_flist flist, uint64_t idx, const mfu_pred*);
/* captures current time and returns it in an mfu_pred_times structure,
* must be freed by caller with mfu_free */
mfu_pred_times* mfu_pred_now(void);
/* given a find-like number string (N, +N, -N) and a base times structure,
* allocate and return a structure that records a comparison to this base time,
* N (exactly N), +N (greater than N), -N (less than N) */
mfu_pred_times_rel* mfu_pred_relative(const char* str, const mfu_pred_times* t);
/* --------------------------
* Predefined predicates
* -------------------------- */
/* find-like tests against file list elements */
/* tests file name of element, using shell pattern matching,
* arg to mfu_pred_add should be a copy of the pattern string */
int MFU_PRED_NAME(mfu_flist flist, uint64_t idx, void* arg);
/* tests full path of element, using shell pattern matching,
* arg to mfu_pred_add should be a copy of the pattern string */
int MFU_PRED_PATH(mfu_flist flist, uint64_t idx, void* arg);
/* tests full path of element, using regexec(),
* arg to mfu_pred_add should be a copy of the compiled regex */
int MFU_PRED_REGEX(mfu_flist flist, uint64_t idx, void* arg);
/* tests the numeric group id of an element,
* arg to mfu_pred_add should be a copy of the number as a string,
* +N and -N notation can be used to check open ended ranges */
int MFU_PRED_GID(mfu_flist flist, uint64_t idx, void* arg);
/* tests the group name of an element,
* arg to mfu_pred_add should be a copy of the name as a string */
int MFU_PRED_GROUP(mfu_flist flist, uint64_t idx, void* arg);
/* tests the numeric user id of an element,
* arg to mfu_pred_add should be a copy of the number as a string,
* +N and -N notation can be used to check open ended ranges */
int MFU_PRED_UID(mfu_flist flist, uint64_t idx, void* arg);
/* tests the user name of an element,
* arg to mfu_pred_add should be a copy of the name as a string */
int MFU_PRED_USER (mfu_flist flist, uint64_t idx, void* arg);
/* tests the size of an element, if element is a regular file,
* arg to mfu_pred_add should be a copy of the size as a string,
* +N and -N notation can be used to check open ended ranges,
* units may also be appended, e.g., "+2GB" */
int MFU_PRED_SIZE (mfu_flist flist, uint64_t idx, void* arg);
/* tests whether the element was accessed in the last N minutes,
* arg to mfu_pred_add should be a struct returned from mfu_pred_relative */
int MFU_PRED_AMIN(mfu_flist flist, uint64_t idx, void* arg);
/* tests whether the element was modified in the last N minutes,
* arg to mfu_pred_add should be a struct returned from mfu_pred_relative */
int MFU_PRED_MMIN(mfu_flist flist, uint64_t idx, void* arg);
/* tests whether the element status was changed in the last N minutes,
* arg to mfu_pred_add should be a struct returned from mfu_pred_relative */
int MFU_PRED_CMIN(mfu_flist flist, uint64_t idx, void* arg);
/* tests whether the element was accessed in the last N days (24 hours),
* arg to mfu_pred_add should be a struct returned from mfu_pred_relative */
int MFU_PRED_ATIME(mfu_flist flist, uint64_t idx, void* arg);
/* tests whether the element was modified in the last N days (24 hours),
* arg to mfu_pred_add should be a struct returned from mfu_pred_relative */
int MFU_PRED_MTIME(mfu_flist flist, uint64_t idx, void* arg);
/* tests whether the element status was changed in the last N days (24 hours),
* arg to mfu_pred_add should be a struct returned from mfu_pred_relative */
int MFU_PRED_CTIME(mfu_flist flist, uint64_t idx, void* arg);
/* tests whether the element was accessed more recently than the specified time,
* arg to mfu_pred_add should be a copy of a mfu_pred_times struct */
int MFU_PRED_ANEWER(mfu_flist flist, uint64_t idx, void* arg);
/* tests whether the element was modified more recently than the specified time,
* arg to mfu_pred_add should be a copy of a mfu_pred_times struct */
int MFU_PRED_MNEWER(mfu_flist flist, uint64_t idx, void* arg);
/* tests whether the status of the element was changed more recently than the specified time,
* arg to mfu_pred_add should be a copy of a mfu_pred_times struct */
int MFU_PRED_CNEWER(mfu_flist flist, uint64_t idx, void* arg);
/* tests the type of the element,
* arg to mfu_pred_add should be a copy of a type string,
* where the type string is:
* "d" - directory
* "f" - regular file
* "l" - symlink */
int MFU_PRED_TYPE(mfu_flist flist, uint64_t idx, void* arg);
#endif /* MFU_PRED_H */
/* enable C++ codes to include this header directly */
#ifdef __cplusplus
} /* extern "C" */
#endif
<|start_filename|>src/dgrep/dgrep.h<|end_filename|>
#ifndef DGREP_H
#define DGREP_H
#include <libcircle.h>
void DGREP_start(CIRCLE_handle *handle);
void DGREP_search(CIRCLE_handle *handle);
void print_usage(char *prog);
#endif /* DGREP_H */
<|start_filename|>src/dcp1/copy.h<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
#ifndef __DCP_COPY_H
#define __DCP_COPY_H
#include "common.h"
void DCOPY_do_copy(DCOPY_operation_t* op,
CIRCLE_handle* handle);
#endif /* __DCP_COPY_H */
<|start_filename|>src/dgrep/log.h<|end_filename|>
#ifndef LOG_H
#define LOG_H
#include <stdio.h>
typedef enum
{
DGREP_LOG_FATAL = 1,
DGREP_LOG_ERR = 2,
DGREP_LOG_WARN = 3,
DGREP_LOG_INFO = 4,
DGREP_LOG_DBG = 5
} DGREP_loglevel;
#define LOG(level, ...) do { \
if (level <= DGREP_debug_level) { \
fprintf(DGREP_debug_stream,"%d:%s:%d:", DGREP_global_rank, __FILE__, __LINE__); \
fprintf(DGREP_debug_stream, __VA_ARGS__); \
fprintf(DGREP_debug_stream, "\n"); \
fflush(DGREP_debug_stream); \
} \
} while (0)
extern int DGREP_global_rank;
extern FILE *DGREP_debug_stream;
extern DGREP_loglevel DGREP_debug_level;
#endif /* LOG_H */
<|start_filename|>src/dcp1/compare.h<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
#ifndef __DCP_COMPARE_H
#define __DCP_COMPARE_H
#include "common.h"
void DCOPY_do_compare(DCOPY_operation_t* op,
CIRCLE_handle* handle);
#endif /* __DCP_COMPARE_H */
<|start_filename|>src/dparallel/log.h<|end_filename|>
#ifndef _DPARALLEL_LOG_H
#define _DPARALLEL_LOG_H
#include "dparallel.h"
#include <stdio.h>
#include <stdint.h>
#include <time.h>
typedef enum DPARALLEL_loglevel { DPARALLEL_LOG_FATAL = 1,
DPARALLEL_LOG_ERR = 2,
DPARALLEL_LOG_WARN = 3,
DPARALLEL_LOG_INFO = 4,
DPARALLEL_LOG_DBG = 5
} DPARALLEL_loglevel;
#define LOG(level, ...) do { \
if (level <= DPARALLEL_debug_level) { \
fprintf(DPARALLEL_debug_stream, "%d:%d:%s:%d:", (int)time(NULL), \
DPARALLEL_global_rank, __FILE__, __LINE__); \
fprintf(DPARALLEL_debug_stream, __VA_ARGS__); \
fprintf(DPARALLEL_debug_stream, "\n"); \
fflush(DPARALLEL_debug_stream); \
} \
} while (0)
extern FILE* DPARALLEL_debug_stream;
extern enum DPARALLEL_loglevel DPARALLEL_debug_level;
extern int32_t DPARALLEL_global_rank;
#endif /* _DPARALLEL_LOG_H */
<|start_filename|>src/common/strmap.h<|end_filename|>
#ifndef STRMAP_H
#define STRMAP_H
/* Stores a set of key/value pairs, where key and value are both
* stored as strings. */
#include <stdarg.h>
#include <sys/types.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
#define STRMAP_SUCCESS (0)
/*
=========================================
Define AVL tree data structures
=========================================
*/
/* Even though the structure is defined here,
* consider these types to be opaque and only
* use functions in this file to modify them. */
/* define the structure for an element of a hash */
typedef struct strmap_node_struct {
const char* key; /* pointer to key string */
size_t key_len; /* number of characters in key string (including terminating NUL) */
const char* value; /* pointer to value string */
size_t value_len; /* number of characters in value string (including terminating NUL) */
int height; /* max height of subtree rooted at this node */
struct strmap_node_struct* parent; /* pointer to parent node */
struct strmap_node_struct* left; /* pointer to left child */
struct strmap_node_struct* right; /* pointer to right child */
} strmap_node;
/* structure to track root of a tree */
typedef struct strmap_struct {
strmap_node* root; /* pointer to the root node in the tree */
size_t len; /* sum of characters in all key/value strings (including terminating NULs) */
uint64_t size; /* number of nodes in the tree */
} strmap;
/*
=========================================
Allocate and delete map objects
=========================================
*/
/* allocates a new map */
strmap* strmap_new(void);
/* copies entries from src into dst */
void strmap_merge(strmap* dst, const strmap* src);
/* frees a map */
void strmap_delete(strmap** map);
/*
=========================================
iterate over key/value pairs
=========================================
*/
/* return first node in map */
const strmap_node* strmap_node_first(const strmap* map);
/* return last node in map */
const strmap_node* strmap_node_last(const strmap* map);
/* get the previous node in map */
const strmap_node* strmap_node_previous(const strmap_node* node);
/* the next node in map */
const strmap_node* strmap_node_next(const strmap_node* node);
/* returns pointer to key string */
const char* strmap_node_key(const strmap_node* node);
/* returns pointer to value string */
const char* strmap_node_value(const strmap_node* node);
/*
=========================================
set, get, and unset key/value pairs
=========================================
*/
/* return number of key/value pairs in map */
uint64_t strmap_size(const strmap* map);
/* insert key/value into map, overwrites existing key */
int strmap_set(strmap* map, const char* key, const char* value);
/* insert key/value into map as "key=value" with printf formatting,
* overwrites existing key */
int strmap_setf(strmap* map, const char* format, ...);
/* returns pointer to value string if found, NULL otherwise */
const char* strmap_get(const strmap* map, const char* key);
/* returns pointer to value string if found, NULL otherwise,
* key can use printf formatting */
const char* strmap_getf(strmap* map, const char* format, ...);
/* deletes specified key */
int strmap_unset(strmap* map, const char* key);
/* deletes specified key using printf formatting */
int strmap_unsetf(strmap* map, const char* format, ...);
#define strmap_foreach(strmap, node) \
for ((node) = strmap_node_first(strmap); \
(node) != NULL; \
(node) = strmap_node_next(node))
/*
=========================================
pack and unpack data structure into array of bytes
=========================================
*/
#if 0
/* returns number of bytes needed to pack map */
size_t strmap_pack_size(const strmap* map);
/* pack map into buffer starting at specified memory location */
size_t strmap_pack(void* buf, const strmap* map);
/* unpack map stored at buf into tree, returns number of bytes read */
size_t strmap_unpack(const void* buf, strmap* map);
/* print map to stdout for debugging */
void strmap_print(const strmap* map);
#endif
#ifdef __cplusplus
}
#endif
#endif /* STRMAP_H */
<|start_filename|>src/dcp1/common.h<|end_filename|>
/* See the file "COPYING" for the full license governing this code. */
#ifndef __COMMON_H_
#define __COMMON_H_
/* Make sure we're using 64 bit file handling. */
#ifdef _FILE_OFFSET_BITS
#undef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64
#endif
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE 1
#endif
#ifndef __USE_LARGEFILE64
#define __USE_LARGEFILE64
#endif
#ifndef _LARGEFILE_SOURCE
#define _LARGEFILE_SOURCE
#endif
/* Enable posix extensions (popen). */
#ifndef _BSD_SOURCE
#define _BSD_SOURCE 1
#endif
/* For O_NOATIME support */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "mpi.h"
#include "mfu.h"
#include "mfu_util.h"
#include <libcircle.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <utime.h>
#if DCOPY_USE_XATTRS
#include <sys/xattr.h>
/*
* Newer versions of attr deprecated attr/xattr.h which defines ENOATTR as a
* ENODATA. Add the definition to keep compatibility.
*/
#ifndef ENOATTR
#define ENOATTR ENODATA
#endif
#endif /* DCOPY_USE_XATTRS */
/* default mode to create new files or directories */
#define DCOPY_DEF_PERMS_FILE (S_IRUSR | S_IWUSR)
#define DCOPY_DEF_PERMS_DIR (S_IRWXU)
/*
* This is the size of each chunk to be processed (in bytes).
*/
#define DCOPY_CHUNK_SIZE (1*1024*1024)
/* buffer size to read/write data to file system */
#define FD_BLOCK_SIZE (1*1024*1024)
/*
* FIXME: Is this description correct?
*
* This is the size of the buffer used to copy from the fd page cache to L1
* cache before the buffer is copied back down into the destination fd page
* cache.
*/
#define FD_PAGE_CACHE_SIZE (32768)
#ifndef PATH_MAX
#define PATH_MAX (4096)
#endif
#ifndef _POSIX_ARG_MAX
#define MAX_ARGS 4096
#else
#define MAX_ARGS _POSIX_ARG_MAX
#endif
typedef enum {
TREEWALK, COPY, CLEANUP, COMPARE
} DCOPY_operation_code_t;
typedef struct {
/*
* The total file size.
*/
int64_t file_size;
/*
* The chunk number this operation is associated with.
*/
int64_t chunk;
/*
* This offset represents the index into the operand path that gives the
* starting index of the root path to copy from.
*/
uint16_t source_base_offset;
/* The operation type. */
DCOPY_operation_code_t code;
/* The full source path. */
char* operand;
/*
* If the destination already existed before this copy started, we want to
* copy the files to a location inside the destination. This is to keep
* track of the path inside the destination.
*/
char* dest_base_appendix;
/* the full dest path */
char* dest_full_path;
} DCOPY_operation_t;
typedef struct {
int64_t total_dirs; /* sum of all directories */
int64_t total_files; /* sum of all files */
int64_t total_links; /* sum of all symlinks */
int64_t total_size; /* sum of all file sizes */
int64_t total_bytes_copied; /* total bytes written */
time_t time_started;
time_t time_ended;
double wtime_started;
double wtime_ended;
} DCOPY_statistics_t;
typedef struct {
int copy_into_dir;
char* dest_path;
bool compare;
bool force;
bool preserve;
bool reliable_filesystem;
bool synchronous;
size_t chunk_size; /* size to chunk files by */
size_t block_size; /* block size to read/write to file system */
char* block_buf1;
char* block_buf2;
} DCOPY_options_t;
/* cache open file descriptor to avoid
* opening / closing the same file */
typedef struct {
char* name;
int read;
int fd;
} DCOPY_file_cache_t;
/** Cache most recent open file descriptor to avoid opening / closing the same file */
extern DCOPY_file_cache_t DCOPY_src_cache;
extern DCOPY_file_cache_t DCOPY_dst_cache;
/* struct for elements in linked list */
typedef struct list_elem {
char* file; /* file name */
struct stat64* sb; /* stat info */
int depth;
struct list_elem* next; /* pointer to next item */
} DCOPY_stat_elem_t;
extern int DCOPY_global_rank;
extern size_t DCOPY_chunksize;
extern size_t DCOPY_blocksize;
extern DCOPY_stat_elem_t* DCOPY_list_head;
extern DCOPY_stat_elem_t* DCOPY_list_tail;
DCOPY_operation_t* DCOPY_decode_operation(char* op);
void DCOPY_opt_free(DCOPY_operation_t** opt);
char* DCOPY_encode_operation(DCOPY_operation_code_t code, \
int64_t chunk, \
char* operand, \
uint16_t source_base_offset, \
char* dest_base_appendix, \
int64_t file_size);
void DCOPY_retry_failed_operation(DCOPY_operation_code_t target, \
CIRCLE_handle* handle, \
DCOPY_operation_t* op);
int DCOPY_open_source(
const char* file
);
int DCOPY_open_file(
const char* file,
int read,
DCOPY_file_cache_t* cache
);
int DCOPY_close_file(
DCOPY_file_cache_t* cache
);
void DCOPY_copy_xattrs(
DCOPY_operation_t* op,
const struct stat64* statbuf,
const char* dest_path
);
void DCOPY_copy_ownership(
const struct stat64* statbuf,
const char* dest_path
);
void DCOPY_copy_permissions(
const struct stat64* statbuf,
const char* dest_path
);
void DCOPY_copy_timestamps(
const struct stat64* statbuf,
const char* dest_path
);
/* called by single process upon detection of a problem */
void DCOPY_abort(
int code
) __attribute__((noreturn));
/* called globally by all procs to exit */
void DCOPY_exit(
int code
);
#endif /* __COMMON_H_ */
| sjtbham/mpifileutils |
<|start_filename|>src/main/java/fr/i360matt/citronDB/utils/TableCache.java<|end_filename|>
package fr.i360matt.citronDB.utils;
import java.lang.reflect.Field;
public class TableCache {
private final String insertSQL;
public TableCache (final String name, final Field[] fields) {
final StringBuilder sb_columns = new StringBuilder();
final StringBuilder sb_interro = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
if (i > 0) {
sb_columns.append(',');
sb_interro.append(',');
}
sb_columns.append(fields[i].getName());
sb_interro.append('?');
}
this.insertSQL = "INSERT INTO `" + name + "` (" + sb_columns + ") VALUES (" + sb_interro + ')';
}
public final String getInsertSQL () {
return this.insertSQL;
}
}
<|start_filename|>src/main/java/fr/i360matt/citronDB/api/TableManager.java<|end_filename|>
package fr.i360matt.citronDB.api;
import com.esotericsoftware.reflectasm.ConstructorAccess;
import com.esotericsoftware.reflectasm.FieldAccess;
import fr.i360matt.citronDB.api.annotations.Primary;
import fr.i360matt.citronDB.api.annotations.Unique;
import fr.i360matt.citronDB.utils.ColumnType;
import fr.i360matt.citronDB.utils.TableCache;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;
public class TableManager <D> {
public final Database database;
public final String name;
private final TableCache tableCache;
private final FieldAccess fieldAccess;
private final ConstructorAccess constructorAccess;
public final Class<D> defaultInstance;
public final Map<String, Object> defaultAsMap;
public TableManager (final Database database, final String name, final Class<D> struct) {
this.database = database;
this.name = name;
this.tableCache = new TableCache(name, struct.getFields());
this.fieldAccess = FieldAccess.get(struct);
this.constructorAccess = ConstructorAccess.get(struct);
this.defaultInstance = struct;
this.defaultAsMap = new HashMap<>();
final D def = (D) this.constructorAccess.newInstance();
final Field[] fields = this.fieldAccess.getFields();
for (int i = 0; i < this.fieldAccess.getFieldCount(); i++) {
this.defaultAsMap.put(fields[i].getName(), this.fieldAccess.get(def, i));
}
}
public final void createTable () {
createTable(false);
}
public final void createTable (final boolean update) {
final Field[] fields = this.defaultInstance.getFields();
if (fields.length == 0)
return;
boolean hasPrimary = false;
final StringBuilder resSQL = new StringBuilder();
resSQL.append("CREATE TABLE IF NOT EXISTS `");
resSQL.append(this.name);
resSQL.append("` (");
for (int i = 0; i < fields.length; i++) {
final Field field = fields[i];
if (field.getAnnotation(Unique.class) != null) {
if (i > 0) resSQL.append(',');
resSQL.append(ColumnType.getFormat(field, false));
} else if (!hasPrimary) {
if (field.getAnnotation(Primary.class) != null) {
hasPrimary = true;
if (i > 0) resSQL.append(',');
resSQL.append(ColumnType.getFormat(field, false));
}
} else {
resSQL.append(',');
resSQL.append(ColumnType.getFormat(field, false));
}
}
resSQL.append(')');
try (final Statement stmt = this.database.getStatementWithException()) {
final int status = stmt.executeUpdate(resSQL.toString());
if (update && status == 0) {
// if the table has not been created above,
// we must apply the new structure by an ALTER.
updateStructure();
}
} catch (final SQLException e) {
e.printStackTrace();
}
}
public final void deleteTable () {
try (final Statement stmt = this.database.getStatementWithException();) {
stmt.execute("DROP TABLE IF EXISTS `" + this.name + "`");
} catch (final SQLException e) {
e.printStackTrace();
}
}
public void updateStructure () {
final String sql = "SELECT * FROM `" + this.name + "` WHERE 1 = 0;";
try (
final Statement stmt = this.database.getStatementWithException();
final ResultSet rs = stmt.executeQuery(sql);
) {
final ResultSetMetaData meta = rs.getMetaData();
final List<String> distant = new ArrayList<>();
for (int i = 0; i < meta.getColumnCount(); i++)
distant.add(meta.getColumnName(i + 1));
rs.close();
Field[] local = this.defaultInstance.getFields();
if (local.length == 0 || distant.size() == 0) {
stmt.close();
return;
}
final StringBuilder resSQL = new StringBuilder();
resSQL.append("ALTER TABLE `");
resSQL.append(this.name);
resSQL.append("` ");
boolean firstWasAdded = false;
for (final Field field : local) {
if (!distant.contains(field.getName())) {
if (!firstWasAdded) {
resSQL.append("ADD(");
firstWasAdded = true;
} else {
resSQL.append(',');
}
resSQL.append(ColumnType.getFormat(field, false));
}
}
if (firstWasAdded) {
// if there are minimum one column
resSQL.append(')');
stmt.execute(resSQL.toString());
}
} catch (final SQLException e) {
e.printStackTrace();
}
}
public final void insert (final D line) {
final Field[] fields = defaultInstance.getFields();
if (fields.length >= 1) {
try (final PreparedStatement stmt = this.database.getConnection().prepareStatement(this.tableCache.getInsertSQL())) {
for (int i = 0; i < fields.length; i++)
stmt.setObject(i + 1, fieldAccess.get(line, i));
stmt.executeUpdate();
} catch (final SQLException e) {
e.printStackTrace();
}
}
}
public final void insert (final Map<String, Object> datas) {
if (datas.size() >= 1) {
final StringBuilder resSQL = new StringBuilder();
resSQL.append("INSERT INTO `");
resSQL.append(this.name);
resSQL.append("` (");
final StringBuilder preformat = new StringBuilder();
final Object[] values = new Object[datas.size()];
int ind = 0;
for (final Map.Entry<String, Object> entry : defaultAsMap.entrySet()) {
Object value = datas.get(entry.getKey());
if (value != null)
value = defaultAsMap.get(entry.getKey());
values[ind] = value;
if (ind > 0) {
resSQL.append(',');
preformat.append(',');
}
resSQL.append(value);
preformat.append('?');
ind++;
}
resSQL.append(") VALUES (");
resSQL.append(preformat);
resSQL.append(')');
try (final PreparedStatement stmt = this.database.getConnection().prepareStatement(resSQL.toString())) {
for (int i = 0; i < values.length; i++)
stmt.setObject(i + 1, values[i]);
stmt.executeUpdate();
} catch (final SQLException e) {
e.printStackTrace();
}
}
}
public final void remove (final Map<String, Object> datas) {
if (datas.size() > 0) {
final StringBuilder resSQL = new StringBuilder();
resSQL.append("DELETE FROM `");
resSQL.append(this.name);
resSQL.append("` WHERE ");
final Object[] values = new Object[datas.size()];
int ind = 0;
for (final String key : datas.keySet()) {
values[ind] = key;
if (ind > 0)
resSQL.append(',');
resSQL.append('`');
resSQL.append(key);
resSQL.append("`=?");
ind++;
}
try (final PreparedStatement stmt = this.database.getConnection().prepareStatement(resSQL.toString())) {
for (int i = 0; i < values.length; i++)
stmt.setObject(i+1, values[i]);
stmt.executeUpdate();
} catch (final SQLException e) {
e.printStackTrace();
}
}
}
public final boolean exist (final Map<String, Object> pattern) {
try (
final PreparedStatement statement = this.whereStatement(pattern);
final ResultSet rs = statement.executeQuery();
) {
return rs.next();
} catch (final SQLException e) {
e.printStackTrace();
return false;
}
}
public final Set<D> getLines (final Map<String, Object> pattern) {
return getLines(pattern, Integer.MAX_VALUE);
}
public final D getLine (final Map<String, Object> pattern) {
if (pattern.size() > 0) {
try (
final PreparedStatement statement = this.whereStatement(pattern);
final ResultSet rs = statement.executeQuery();
) {
final ResultSetMetaData data = rs.getMetaData();
if (rs.next()) {
final D content = (D) this.constructorAccess.newInstance();
for (int c = 1; c <= data.getColumnCount(); c++) {
final Object obj = rs.getObject(c);
if (obj != null) {
this.fieldAccess.set(content, data.getColumnName(c), obj);
}
}
return content;
}
} catch (final SQLException e) {
e.printStackTrace();
}
}
return null;
}
public final Set<D> getLines (final Map<String, Object> pattern, int limit) {
final Set<D> res = new HashSet<>();
if (pattern.size() > 0) {
final StringBuilder resSQL = new StringBuilder();
resSQL.append("SELECT ");
resSQL.append(limit);
resSQL.append(" FROM `");
resSQL.append(this.name);
resSQL.append("` WHERE ");
final Object[] values = new Object[pattern.size()];
int ind = 0;
for (final Map.Entry<String, Object> entry : pattern.entrySet()) {
values[ind] = entry.getValue();
if (ind > 0)
resSQL.append(",AND ");
resSQL.append(entry.getKey());
resSQL.append("=?");
ind++;
}
try (final PreparedStatement stmt = this.database.getConnection().prepareStatement(resSQL.toString())) {
for (int i = 0; i < values.length; i++)
stmt.setObject(i+1, values[i]);
try (final ResultSet rs = stmt.executeQuery()) {
final ResultSetMetaData data = rs.getMetaData();
while (limit-- > 0 && rs.next()) {
final D content = (D) this.constructorAccess.newInstance();
for (int c = 1; c <= data.getColumnCount(); c++) {
final Object obj = rs.getObject(c);
if (obj != null)
this.fieldAccess.set(content, data.getColumnName(c), obj);
}
res.add(content);
}
}
} catch (final SQLException e) {
e.printStackTrace();
}
}
return res;
}
public final void update (final Map<String, Object> pattern, final Map<String, Object> replacement) {
if (replacement.size() > 0 && pattern.size() > 0) {
final StringBuilder resSQL = new StringBuilder();
resSQL.append("UPDATE `");
resSQL.append(this.name);
resSQL.append("` SET ");
final Object[] replaceValues = new Object[replacement.size()];
final Object[] patternValues = new Object[pattern.size()];
int ind = 0;
for (final Map.Entry<String, Object> entry : replacement.entrySet()) {
replaceValues[ind] = entry.getValue();
if (ind > 0)
resSQL.append(',');
resSQL.append(entry.getKey());
resSQL.append("=?");
ind++;
}
resSQL.append(" WHERE ");
ind = 0;
for (final Map.Entry<String, Object> entry : pattern.entrySet()) {
patternValues[ind] = entry.getValue();
if (ind > 0)
resSQL.append(",AND ");
resSQL.append(entry.getKey());
resSQL.append("=?");
ind++;
}
try (final PreparedStatement stmt = this.database.getConnection().prepareStatement(resSQL.toString())) {
int i = 1;
for (final Object val : replaceValues)
stmt.setObject(i++, val);
for (final Object val : patternValues)
stmt.setObject(i++, val);
stmt.executeUpdate();
} catch (final SQLException e) {
e.printStackTrace();
}
}
}
// ______________________________________________________________________________________ //
private PreparedStatement whereStatement (final Map<String, Object> pattern) throws SQLException {
final StringBuilder resSQL = new StringBuilder();
resSQL.append("SELECT * FROM `");
resSQL.append(this.name);
resSQL.append("` WHERE ");
final Object[] values = new Object[pattern.size()];
int ind = 0;
for (final Map.Entry<String, Object> entry : pattern.entrySet()) {
resSQL.append(entry.getKey());
values[ind] = entry.getValue();
if (ind > 0)
resSQL.append(" AND ");
resSQL.append("=?");
ind++;
}
final PreparedStatement stmt = this.database.getConnection().prepareStatement(resSQL.toString());
for (int i = 0; i < values.length; i++)
stmt.setObject(i+1, values[i]);
return stmt;
}
}
<|start_filename|>src/main/java/fr/i360matt/citronDB/utils/ColumnType.java<|end_filename|>
package fr.i360matt.citronDB.utils;
import fr.i360matt.citronDB.api.annotations.Primary;
import fr.i360matt.citronDB.api.annotations.Size;
import fr.i360matt.citronDB.api.annotations.Unique;
import java.lang.reflect.Field;
public class ColumnType {
public static String getFormat (final Field field) {
return getFormat(field, true);
}
public static String getFormat (final Field field, final Boolean withSpecial) {
final String special;
if (field.getAnnotation(Unique.class) != null)
special = "UNIQUE";
else if (field.getAnnotation(Primary.class) != null)
special = "PRIMARY";
else
special = null;
int size = 0;
Size annotSize;
if ((annotSize = field.getAnnotation(Size.class)) != null) {
size = annotSize.size();
}
final StringBuilder res = new StringBuilder();
final Class<?> type = field.getType();
if (type == int.class) {
if (size > 255) size = 255;
res.append("INT");
} else if (type == long.class) {
if (size > 255) size = 255;
res.append("BIGINT");
} else if (type == float.class) {
if (size > 255) size = 255;
res.append("FLOAT");
} else if (type == double.class) {
if (size > 255) size = 255;
res.append("DOUBLE");
} else if (type == boolean.class) {
if (size > 0) size = 0;
res.append("BOOLEAN");
} else if (type == String.class) {
res.append( (size > 1) ? "VARCHAR" : "TEXT" );
} else {
res.append("BLOB");
}
if (size > 0)
res.append("(").append(size).append(")");
if (withSpecial && special != null)
res.append(" ").append(special);
return field.getName() + " " + res;
}
}
<|start_filename|>src/main/java/fr/i360matt/citronDB/api/Database.java<|end_filename|>
package fr.i360matt.citronDB.api;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
private final MysqlDataSource datas = new MysqlDataSource() {{
try {
this.setServerTimezone("UTC");
} catch (final SQLException e) {
e.printStackTrace();
}
}};
private Connection connection;
public final Database setHost (final String host) { this.datas.setServerName(host); return this; }
public final Database setPort (final int port) { this.datas.setPort(port); return this; }
public final Database setDbName (final String databaseName) { this.datas.setDatabaseName(databaseName); return this; }
public final Database setUsername (final String username) { this.datas.setUser(username); return this; }
public final Database setPassword (final String password) { this.datas.setPassword(password); return this; }
public final Database connect () {
try {
this.connection = datas.getConnection();
} catch (final SQLException e) {
e.printStackTrace();
}
return this;
}
public final Database connectWithException () throws SQLException {
this.connection = datas.getConnection();
return this;
}
public final void close () {
try {
this.connection.close();
} catch (final SQLException e) {
e.printStackTrace();
}
}
public final void closeWithException () throws SQLException {
this.connection.close();
}
public final Connection getConnection () {
return connection;
}
public final Statement getStatement () {
try {
return connection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public final Statement getStatementWithException () throws SQLException {
return connection.createStatement();
}
public final <D> TableManager<D> getTable (final String name, final Class<D> struct) {
return new TableManager<>(this, name, struct);
}
}
<|start_filename|>src/main/java/fr/i360matt/citronDB/api/annotations/Size.java<|end_filename|>
package fr.i360matt.citronDB.api.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Size {
int size () default 1024;
}
<|start_filename|>src/main/test/SomeTests.java<|end_filename|>
import fr.i360matt.citronDB.api.Database;
import fr.i360matt.citronDB.api.annotations.Size;
import fr.i360matt.citronDB.api.annotations.Unique;
import fr.i360matt.citronDB.api.TableManager;
public class SomeTests {
public static class ExampleStucture {
@Unique()
@Size
public String test = "truc";
public String truc = "jaaj";
}
public static void main (final String[] args) {
Database db2 = new Database() {{
setHost("127.0.0.1");
setPort(3306);
setDbName("social");
setUsername("root");
setPassword("");
connect();
}};
/*
ExampleStucture ah = new ExampleStucture();
ah.caillou = 56;
tableManager.insert(ah);
*/
TableManager<ExampleStucture> tableManager = db2.getTable("uneTable", ExampleStucture.class);
tableManager.createTable(true);
// will create the table, or if existe, update these.
DebugTime debugTime = new DebugTime();
debugTime.start();
for (int i = 0; i < 100_000; i++) {
ExampleStucture inst = new ExampleStucture();
inst.test = "Woaaw";
tableManager.insert(inst);
}
debugTime.printElapsed();
}
}
<|start_filename|>src/main/test/DebugTime.java<|end_filename|>
public class DebugTime {
private long start;
public void start () {
start = System.nanoTime();
}
public void printElapsed () {
long stop = System.nanoTime();
// deepcode ignore SystemPrintln: < for test only >
System.out.println("Ptn: " + (stop-start));
}
}
| 360matt/CitronDB |
<|start_filename|>LMW/Shared/Library/Mosquitto-1.4.2/config.h<|end_filename|>
/* ============================================================
* Control compile time options.
* ============================================================
*
* Compile time options have moved to config.mk.
*/
/* ============================================================
* Compatibility defines
*
* Generally for Windows native support.
* ============================================================ */
#ifdef WIN32
#define snprintf sprintf_s
# ifndef strcasecmp
# define strcasecmp strcmpi
# endif
#define strtok_r strtok_s
#define strerror_r(e, b, l) strerror_s(b, l, e)
#endif
#define uthash_malloc(sz) _mosquitto_malloc(sz)
#define uthash_free(ptr,sz) _mosquitto_free(ptr)
| k-zen/LMW |
<|start_filename|>test/event-failures.js<|end_filename|>
var assert = require('assert');
var test = global.it;
var Prober = require('../index');
test('Prober detecting failures by event', function(end) {
var events = [];
var mockEmitter = {
on: function (eventName) {
events.push(eventName);
}
};
var failureEvent = 'failureEvent';
var successEvent = 'successEvent';
var prober = new Prober({
detectFailuresBy: Prober.detectBy.EVENT,
backend: mockEmitter,
window: 1,
failureEvent: failureEvent,
successEvent: successEvent
});
assert.equal(events.length, 2);
assert.deepEqual(events, [failureEvent, successEvent]);
// failures detected by events do not have a callback
// argument so calling it will throw and thus not trigger
// the actual callback to probe.
// instead we just do a side effect and the emitter will
// emit success & failure events which get probed
try {
prober.probe(function(callback) {
callback();
}, assert.fail, assert.fail);
} catch (err) { /*ignore*/ }
assert.ok(!prober.isHealthy());
end();
});
<|start_filename|>bit-ring.js<|end_filename|>
function BitRing(capacity) {
this.capacity = capacity;
this.bits = new Uint8ClampedArray(capacity);
this.pos = 0;
this.length = 0;
this._count = 0;
}
// Update the count and set or clear the next bit in the ring
BitRing.prototype.push = function(bool) {
var num = bool === true ? 1 : 0;
this._count += num - this.bits[this.pos];
this.bits[this.pos] = num;
this.pos = (this.pos + 1) % this.capacity;
if (this.length < this.capacity) {
this.length++;
}
};
// Return the number of bits set
BitRing.prototype.count = function() {
return this._count;
};
module.exports = BitRing;
<|start_filename|>benchmark.js<|end_filename|>
var Benchmark = require('benchmark');
var BitRing = require('./bit-ring');
var Prober = require('./index');
var suite = new Benchmark.Suite();
var prober = new Prober();
var healthy = function(callback) {
callback();
};
var error = new Error('unhealthy');
var unhealthy = function(callback) {
callback(error);
};
var bitRing = new BitRing(10);
suite.add('probe healthy', function() {
prober.probe(healthy);
}).add('probe unhealthy', function() {
prober.probe(unhealthy);
}).add('bitRing', function() {
bitRing.count();
bitRing.push(true);
bitRing.count();
}).on('cycle', function(event) {
console.log(String(event.target));
}).run();
<|start_filename|>package.json<|end_filename|>
{
"name": "airlock",
"version": "2.2.0",
"description": "A prober to probe HTTP based backends for health",
"keywords": [],
"author": "Raynos <<EMAIL>>",
"repository": "git://github.com/uber/airlock.git",
"main": "index",
"homepage": "https://github.com/uber/airlock",
"bugs": {
"url": "https://github.com/uber/airlock/issues",
"email": "<EMAIL>"
},
"collaborators": [
{
"name": "<NAME>"
},
{
"name": "markyen"
}
],
"dependencies": {},
"devDependencies": {
"benchmark": "^1.0.0",
"istanbul": "~0.1.46",
"lodash.times": "~2.4.1",
"mocha": "~1.15.1",
"time-mock": "~0.1.2"
},
"scripts": {
"test": "npm run jshint && mocha --reporter tap ./test 2>&1 | tee ./test/test.js.tap",
"jshint": "jshint --verbose .",
"cover": "istanbul cover --report none --print detail _mocha -- test --reporter tap",
"view-cover": "istanbul report html && open ./coverage/index.html"
},
"engine": {
"node": ">= 0.8.x"
}
}
<|start_filename|>test/index.js<|end_filename|>
var assert = require('assert');
var timer = require('time-mock');
var times = require('lodash.times');
var test = global.it;
var Prober = require('../index');
var exampleTchannelIsUnhealthyFunc = function isUnhealthy(err, resp) {
if (err) {
// not an exhaustive list, just an example
var serverErrTypes = [
'tchannel.request.timeout',
'tchannel.connection.close',
'tchannel.connection.reset',
'tchannel.connection.unknown-reset'
];
return serverErrTypes.indexOf(err.type) !== -1;
}
if (resp) {
// not an exhaustive list, just an example
var respServerErrTypes = [
'tchannel.busy'
];
return resp.ok === false && respServerErrTypes.indexOf(resp.type) !== -1;
}
return false;
};
test('Prober is a function', function (end) {
assert.equal(typeof Prober, 'function');
end();
});
test('Prober should make request with no previous probes', function(end) {
var wasCalled;
var prober = new Prober();
prober.probe(function() { wasCalled = true; });
assert.ok(wasCalled);
end();
});
test('can disabled prober', function (end) {
var prober = new Prober({ enabled: false });
assert.equal(prober.enabled, false);
end();
});
test('can reset to enable or disable prober', function(end) {
var prober = new Prober();
assert.equal(prober.enabled, true);
prober.setEnabled(false);
assert.equal(prober.enabled, false);
try {
prober.setEnabled("false");
} catch(e) {
assert(e.name === 'AssertionError');
assert.equal(prober.enabled, false);
}
prober.setEnabled(true);
assert.equal(prober.enabled, true);
end();
});
test('Prober should make request when amount of healthy probes are less than window', function(end) {
var prober = new Prober();
times(prober.threshold, function() { prober.ok(); });
var wasCalled;
prober.probe(function() { wasCalled = true; });
assert.ok(wasCalled);
end();
});
test('should make request when amount of unhealthy probes are less than window', function(end) {
var prober = new Prober();
times(prober.threshold, function() { prober.notok(); });
var wasCalled;
prober.probe(function() { wasCalled = true; });
assert.ok(wasCalled);
end();
});
test('should make request when amount of healthy requests is above threshold', function(end) {
var prober = new Prober();
times(prober.threshold, function() { prober.ok(); });
times(prober.window - prober.threshold, function() { prober.notok(); });
var wasCalled;
prober.probe(function() { wasCalled = true; });
assert.ok(wasCalled);
end();
});
test('should bypass backend request when amount of unhealthy requests is above threshold', function(end) {
var prober = new Prober();
times(prober.threshold, function() { prober.notok(); });
times(prober.window - prober.threshold, function() { prober.ok(); });
var backendWasCalled = false;
var callbackWasCalled = false;
prober.probe(
function() { backendWasCalled = true; },
function() { callbackWasCalled = true; });
assert.ok(!prober.isHealthy());
assert.ok(!backendWasCalled);
assert.ok(callbackWasCalled);
end();
});
test('should bypass backend request until coming back to health', function(end) {
var prober = new Prober();
times(prober.window, function() { prober.notok(); });
times(prober.threshold, function() {
assert.ok(!prober.isHealthy());
prober.probe(assert.fail);
prober.ok();
});
// After healthy threshold has been hit, backend should be healthy
assert.ok(prober.isHealthy());
var wasCalled = false;
prober.probe(function() { wasCalled = true; });
assert.ok(wasCalled);
end();
});
test('should be healthy after returning to health', function(end) {
var prober = new Prober();
times(prober.window, function() { prober.notok(); });
times(prober.threshold - 1, function() { prober.ok(); });
prober.probe(function() { });
assert.ok(!prober.isHealthy());
// Returns backend back to health
prober.ok();
assert.ok(prober.isHealthy());
end();
});
test('should be unhealthy after getting sick', function(end) {
var prober = new Prober();
times(prober.threshold, function() { prober.ok(); });
times(prober.window - prober.threshold, function() { prober.notok(); });
prober.probe(function() { });
assert.ok(prober.isHealthy());
// Gets sick
prober.notok();
assert.ok(!prober.isHealthy());
end();
});
test('should have default wait period after becoming sick', function(end) {
var prober = new Prober();
// Set to healthy
times(prober.window, function() { prober.ok(); });
// Close to becoming sick
times(prober.window - prober.threshold, function() { prober.notok(); });
assert.ok(prober.isHealthy());
prober.notok();
assert.ok(prober.isSick());
assert.equal(prober.waitPeriod, prober.defaultWaitPeriod);
end();
});
test('should allow backend request only after wait period', function(end) {
// create a fake timer.
var clock = timer(Date.now());
var prober = new Prober({
// overwrite now to be a fake Date.now() based on our clock
now: clock.now
});
prober.waitPeriod = prober.maxWaitPeriod / 2;
// Set to healthy
times(prober.window, function() { prober.ok(); });
// Will set wait period to twice as long
times(prober.window - prober.threshold + 2, function() { prober.notok(); });
// Should not call `assert.fail`
prober.probe(assert.fail);
// Simulate time after wait period
clock.advance(prober.waitPeriod);
var called = false;
prober.probe(function () {
called = true;
});
// Backend request was made
assert.ok(called);
end();
});
test('should be unhealthy after request err', function(end) {
var prober = new Prober();
prober.threshold = 1;
prober.window = 1;
prober.probe(function(fn) {
fn(new Error('Some kind of bad going on'));
});
assert.ok(prober.isSick());
end();
});
test('should be unhealthy after HTTP request server err', function(end) {
var prober = new Prober();
prober.threshold = 1;
prober.window = 1;
prober.probe(function(fn) {
fn(null, {
statusCode: 500
});
});
assert.ok(prober.isSick());
end();
});
test('should be healthy after HTTP request client err', function(end) {
var prober = new Prober();
prober.threshold = 1;
prober.window = 1;
prober.probe(function(fn) {
fn(null, {
statusCode: 400
});
});
assert.ok(prober.isHealthy());
end();
});
test('should be healthy after tchannel request server success', function(end) {
var prober = new Prober({
threshold: 1,
window: 1,
isUnhealthyFunc: exampleTchannelIsUnhealthyFunc
});
prober.probe(function(fn) {
fn(null, {
ok: true,
body: {}
});
});
assert.ok(prober.isHealthy());
end();
});
test('should be unhealthy after tchannel request server err', function(end) {
var prober = new Prober({
threshold: 1,
window: 1,
isUnhealthyFunc: exampleTchannelIsUnhealthyFunc
});
prober.probe(function(fn) {
fn({ type: 'tchannel.request.timeout' });
});
assert.ok(prober.isSick());
end();
});
test('should be unhealthy after tchannel request server err from resp', function(end) {
var prober = new Prober({
threshold: 1,
window: 1,
isUnhealthyFunc: exampleTchannelIsUnhealthyFunc
});
prober.probe(function(fn) {
fn(null, {
ok: false,
type: 'tchannel.busy'
});
});
assert.ok(prober.isSick());
end();
});
test('should be healthy after custom handling expected error', function(end) {
var prober = new Prober();
prober.threshold = 1;
prober.window = 1;
prober.customProbe(function(fn) {
fn(new Error('Some kind of bad going on'));
}, function() {
prober.ok();
});
assert.ok(prober.isHealthy());
end();
});
<|start_filename|>test/bit-ring.js<|end_filename|>
var assert = require('assert');
var BitRing = require('../bit-ring');
var test = global.it;
test('empty bit ring', function(end) {
var bitRing = new BitRing(3);
assert.equal(bitRing.length, 0);
assert.equal(bitRing.count(), 0);
end();
});
test('set bit', function(end) {
var bitRing = new BitRing(3);
bitRing.push(true);
assert.equal(bitRing.length, 1);
assert.equal(bitRing.count(), 1);
end();
});
test('clear bit', function(end) {
var bitRing = new BitRing(3);
bitRing.push(true);
bitRing.push(true);
assert.equal(bitRing.length, 2);
assert.equal(bitRing.count(), 2);
bitRing.push(false);
assert.equal(bitRing.length, 3);
assert.equal(bitRing.count(), 2);
bitRing.push(false);
assert.equal(bitRing.length, 3);
assert.equal(bitRing.count(), 1);
end();
});
<|start_filename|>index.js<|end_filename|>
var assert = require('assert');
var BitRing = require('./bit-ring');
var defaults = {
title: 'general',
threshold: 6,
window: 10,
defaultWaitPeriod: 1000,
maxWaitPeriod: 60 * 1000,
isUnhealthyFunc: function isUnhealthy(err, resp) {
// default is for HTTP, tchannel/other protocal needs to pass in different function
return err || resp && !isNaN(resp.statusCode) && resp.statusCode >= 500;
}
};
function Prober(options) {
if (!(this instanceof Prober)) {
return new Prober(options);
}
options = options || {};
this.title = options.title || defaults.title;
this.threshold = options.threshold || defaults.threshold;
this.window = options.window || defaults.window;
this.now = options.now || Date.now;
this.defaultWaitPeriod = options.defaultWaitPeriod ||
defaults.defaultWaitPeriod;
this.maxWaitPeriod = options.maxWaitPeriod || defaults.maxWaitPeriod;
this.enabled = 'enabled' in options ? options.enabled : true;
var detectFailuresBy = options.detectFailuresBy || Prober.detectBy.CALLBACK;
this.detectFailuresByCallback =
(detectFailuresBy === Prober.detectBy.CALLBACK) ||
(detectFailuresBy === Prober.detectBy.BOTH);
this.detectFailuresByEvent =
(detectFailuresBy === Prober.detectBy.EVENT) ||
(detectFailuresBy === Prober.detectBy.BOTH);
this.logger = options.logger || null;
this.bitRing = new BitRing(this.window);
this.waitPeriod = this.defaultWaitPeriod;
this.lastBackendRequest = this.now();
this.statsd = options.statsd || null;
this.isUnhealthyFunc = typeof options.isUnhealthyFunc === 'function' &&
options.isUnhealthyFunc || defaults.isUnhealthyFunc;
if (this.detectFailuresByEvent) {
if (!options.backend) {
if (this.logger) {
this.logger.warn('Prober missing backend from' +
' initialization options');
}
return;
}
options.backend.on(options.failureEvent, this.notok.bind(this));
options.backend.on(options.successEvent, this.ok.bind(this));
}
}
Prober.detectBy = {
CALLBACK: 'callback',
EVENT: 'event',
BOTH: 'both'
};
Prober.prototype.isHealthy = function isHealthy() {
return this.bitRing.length < this.window ||
this.bitRing.count() >= this.threshold;
};
Prober.prototype.isSick = function isSick() {
return !this.isHealthy();
};
Prober.prototype.notok = function notok() {
if (!this.enabled) {
return;
}
this._addProbe(false);
if (this.statsd) {
this.statsd.increment('prober.' + this.title + '.probe.notok');
}
};
Prober.prototype.setEnabled = function setEnabled(enabled) {
assert(typeof enabled === 'boolean', 'setEnabled() takes a boolean');
this.enabled = enabled;
};
Prober.prototype.notOk = Prober.prototype.notok;
Prober.prototype.ok = function ok() {
if (!this.enabled) {
return;
}
this._addProbe(true);
if (this.statsd) {
this.statsd.increment('prober.' + this.title + '.probe.ok');
}
};
Prober.prototype.setLogger = function setLogger(logger) {
this.logger = logger;
};
Prober.prototype.probe = function probe(request, bypass, callback) {
var self = this;
if (!callback) {
callback = bypass;
}
var wrappedCallback;
if (this.detectFailuresByCallback) {
wrappedCallback = function(err, resp) {
if (self.isUnhealthyFunc(err, resp)) {
self.notok();
} else {
self.ok();
}
if (callback && typeof callback === 'function') {
callback.apply(null, arguments);
}
};
}
this.customProbe(request, bypass, wrappedCallback);
};
Prober.prototype.customProbe = function probe(request, bypass, callback) {
if (!callback) {
callback = bypass;
}
if (!this.enabled) {
return request(callback);
}
// If the backend is healthy, or it's been enough time
// that we should check to see if the backend is no longer
// sick, then make a request to the backend.
if (this.isHealthy() || this._isPityProbe()) {
if (this.statsd) {
this.statsd.increment('prober.' + this.title +
'.request.performed');
}
try {
request(callback);
this.lastBackendRequest = this.now();
} catch (err) {
this.lastBackendRequest = this.now();
this.notok();
throw err;
}
} else {
if (this.statsd) {
this.statsd.increment('prober.' + this.title + '.request.bypassed');
}
if (bypass && typeof bypass === 'function') {
bypass(new Error(this.title + ' backend is unhealthy'));
}
}
};
Prober.prototype._addProbe = function addProbe(isOk) {
var logger = this.logger;
var statsd = this.statsd;
var wasHealthy = this.isHealthy();
this.bitRing.push(isOk);
var isHealthy = this.isHealthy();
if (wasHealthy && !isHealthy) {
if (logger) {
logger.warn(this.title + ' has gotten sick');
}
if (statsd) {
this.statsd.increment('prober.' + this.title + '.health.sick');
}
} else if (!wasHealthy && isHealthy) {
this.waitPeriod = this.defaultWaitPeriod;
if (logger) {
logger.warn(this.title + ' has returned to health');
}
if (statsd) {
this.statsd.increment('prober.' + this.title + '.health.recovered');
}
} else if (!wasHealthy && !isHealthy) {
if (statsd) {
this.statsd.increment('prober.' + this.title +
'.health.still-sick');
}
if (isOk) {
this.waitPeriod /= 2;
if (logger) {
logger.warn(this.title + ' is still sick but last probe was ' +
'healthy. Decreased wait period to ' +
this.waitPeriod + 'ms');
}
} else {
this.waitPeriod *= 2;
if (this.waitPeriod > this.maxWaitPeriod) {
this.waitPeriod = this.maxWaitPeriod;
if (logger) {
logger.warn(this.title + ' is still sick. Wait period is ' +
'at its max, ' + this.waitPeriod + 'ms');
}
} else if (logger) {
logger.warn(this.title + ' is still sick. Increased wait ' +
'period to ' + this.waitPeriod + 'ms');
}
}
} else if (statsd) {
this.statsd.increment('prober.' + this.title + '.health.still-healthy');
}
};
Prober.prototype._isPityProbe = function _isPityProbe() {
return this.lastBackendRequest && this.now() >=
(this.lastBackendRequest + this.waitPeriod);
};
module.exports = Prober;
<|start_filename|>test/event-and-callback.js<|end_filename|>
var assert = require('assert');
var test = global.it;
var Prober = require('../index');
test('Prober detecting failures by both callback and event', function(end) {
var prober = new Prober({
detectFailuresBy: Prober.detectBy.BOTH,
backend: {
on: function() {}
},
failureEvent: '',
successEvent: ''
});
var called = false;
prober.probe(function(callback) { callback(); }, assert.fail, function () {
called = true;
});
assert.ok(called);
end();
});
| fakeNetflix/uber-repo-airlock |
<|start_filename|>public/wp-content/plugins/wordfence/js/perf.1533058343.js<|end_filename|>
jQuery(document).ready(function(){
if(typeof(performance) !== 'undefined'){
var timing = {
fetchStart: false,
domainLookupStart: false,
domainLookupEnd: false,
connectStart: false,
connectEnd: false,
requestStart: false,
responseStart: false,
responseEnd: false
};
for(var k in timing){
timing[k] = performance.timing[k];
}
timing['domReady'] = new Date().getTime();
jQuery(window).load(function(){
timing['URL'] = document.URL;
timing['loaded'] = new Date().getTime();
var fields = ['fetchStart', 'domainLookupStart', 'domainLookupEnd', 'connectStart', 'connectEnd', 'requestStart', 'responseStart', 'responseEnd', 'domReady', 'loaded'];
for(var i = fields.length - 1; i >= 1; i--){
timing[fields[i]] -= timing[fields[i - 1]];
}
timing['fetchStart'] = 0;
timing['action'] = 'wordfence_perfLog';
jQuery.ajax({
type: 'POST',
url: wordfenceAjaxURL,
dataType: 'json',
data: timing,
success: function(json){},
error: function(){}
});
});
}
});
| jacwebii/heroku-wp |
<|start_filename|>Dockerfile<|end_filename|>
FROM registry.cn-hangzhou.aliyuncs.com/kennylee/maven
MAINTAINER hf-hf <<EMAIL>>
WORKDIR /app
ADD . /tmp
RUN cd /tmp && mvn install -Dmaven.test.skip=true \
&& mv target/mail-micro-service.jar /app/app.jar
# 若使用外部配置文件,请将配置都放入config目录,并放开下方的注释
# ADD ./config/ /app/
RUN rm -rf /tmp && rm -rf ~/.m2
ENTRYPOINT exec java -Dfile.encoding=UTF8 \
-Duser.timezone=GMT+08 \
-jar /app/app.jar
<|start_filename|>src/main/java/top/hunfan/mail/roundrobin/RoundRobin.java<|end_filename|>
package top.hunfan.mail.roundrobin;
/**
* 轮询接口
* @author hf-hf
* @date 2018/12/27 10:17
*/
public interface RoundRobin {
Invoker select();
}
<|start_filename|>src/main/java/top/hunfan/mail/roundrobin/RoundRobinFactory.java<|end_filename|>
package top.hunfan.mail.roundrobin;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
/**
* 轮询方式工厂
* @author hf-hf
* @date 2018/12/27 11:19
*/
public class RoundRobinFactory {
public static final String NORMAL = "normal";
public static final String WEIGHTED = "weighted";
public static RoundRobin create(String type, final Collection<Properties> properties){
switch (type){
case WEIGHTED:
Map<Invoker, Integer> invokerMap = new HashMap<>(properties.size());
properties.stream().forEach(pro -> {
invokerMap.put(new Invoker() {
@Override
public Boolean isAvailable() {
return Boolean.valueOf(pro.getProperty("mail.isAvailable"));
}
@Override
public String id() {
return pro.getProperty("mail.id");
}
}, Integer.valueOf(pro.getProperty("mail.weight")));
});
return new WeightedRoundRobin(invokerMap);
case NORMAL:
List<Invoker> invokerList = properties.stream().map(pro -> new Invoker() {
@Override
public Boolean isAvailable() {
return Boolean.valueOf(pro.getProperty("mail.isAvailable"));
}
@Override
public String id() {
return pro.getProperty("mail.id");
}
}).collect(Collectors.toList());
return new NormalRoundRobin(invokerList);
default:
return null;
}
}
}
<|start_filename|>src/main/java/top/hunfan/mail/roundrobin/NormalRoundRobin.java<|end_filename|>
package top.hunfan.mail.roundrobin;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 标准轮询
* @author hf-hf
* @date 2018/12/27 9:51
*/
public class NormalRoundRobin extends AbstractRoundRobin {
private final AtomicInteger position = new AtomicInteger();
public NormalRoundRobin(List<Invoker> invokers) {
nodes = new ArrayList<>(invokers.size());
invokers.forEach(invoker -> nodes.add(new Node(invoker)));
}
@Override
public Invoker select() {
if (!checkNodes())
return null;
int index = position.updateAndGet(p -> p + 1 < nodes.size() ? p + 1 : 0);
return nodes.get(index).invoker;
}
}
<|start_filename|>src/test/java/top/mail/MailLocalhostTest.java<|end_filename|>
package top.mail;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import lombok.extern.slf4j.Slf4j;
import top.hunfan.mail.MailMicroServiceApplication;
import top.hunfan.mail.utils.MailUtil;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MailMicroServiceApplication.class)
public class MailLocalhostTest {
private static final String MAIL_URL = "http://127.0.0.1:12345/api/v0.0.1/mail/send";
private static final String EQUAL_SIGN = "=";
//发送多收件人,使用;分隔收件人邮箱
private static final String TEST_MAIL = "<EMAIL>";
private static final String PARAM_SEPARATOR = "&";
@Test
public void testSendTextMaiLocal1() {
StringBuilder builder = new StringBuilder(MAIL_URL);
builder.append("to")
.append(EQUAL_SIGN)
.append(TEST_MAIL)
.append(PARAM_SEPARATOR)
.append("title")
.append("我是没有附件的主题")
.append(PARAM_SEPARATOR)
.append("content")
.append("我是没有附件的内容");
RestTemplate rest = new RestTemplate();
assertTrue(rest.postForObject(builder.toString(), null, Boolean.class));
}
@Test
public void testSendAttachmentMailLocal() throws Throwable {
File folder = new File("F://");
if (!folder.exists() || !folder.isDirectory()) {
FileUtils.forceMkdir(folder);
}
File attachmentFile = new File(folder, "1.txt");
if (attachmentFile.exists() && attachmentFile.isFile()) {
FileUtils.forceDelete(attachmentFile);
}
FileUtils.writeStringToFile(attachmentFile, "hello \r\n mail \r\n" +
RandomStringUtils.random(10), "utf8");
attachmentFile.createNewFile();
MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
param.add("to", TEST_MAIL);
param.add("title", RandomStringUtils.random(5));
param.add("content", RandomStringUtils.random(256));
param.add("attachmentName", RandomStringUtils.random(4) + ".txt");
FileSystemResource resource = new FileSystemResource(attachmentFile);
param.add("attachmentFile", resource);
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param);
RestTemplate rest = new RestTemplate();
ResponseEntity<Boolean> response = rest.exchange(MAIL_URL, HttpMethod.POST,
httpEntity, Boolean.class);
assertTrue(response.getBody());
}
@Test
public void parallelSendTest(){
String to = TEST_MAIL;
String subject = "并发邮件主题";
String content = "并发邮件内容";
List<CompletableFuture<Boolean>> tasks = Arrays.asList(new int[]{1, 2, 3}).stream()
.map(n -> CompletableFuture.supplyAsync(() -> {
for(int i= 0;i < 3;i++){
MailUtil.getInstance().send(to, subject + n, content + n);
if(i == 2){
log.debug(Thread.currentThread().getId() + " finish!");
}
}
return true;
})).collect(Collectors.toList());
tasks.stream().map(CompletableFuture::join)
.forEach(r -> log.debug(r + ""));
}
}
<|start_filename|>src/main/java/top/hunfan/mail/MailMicroServiceApplication.java<|end_filename|>
package top.hunfan.mail;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages="top.hunfan.mail.**")
public class MailMicroServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MailMicroServiceApplication.class, args);
}
}
<|start_filename|>src/main/java/top/hunfan/mail/aspect/MailSendLogAspect.java<|end_filename|>
package top.hunfan.mail.aspect;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.persistence.Column;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import top.hunfan.mail.domain.Constants;
import top.hunfan.mail.domain.R;
import top.hunfan.mail.entity.po.MailSendLog;
import top.hunfan.mail.service.MailSendLogService;
import top.hunfan.mail.utils.StringTools;
import top.hunfan.mail.utils.ThreadLocalUtils;
/**
* 邮件发送日志切面
* @author hf-hf
* @date 2019/1/9 14:15
*/
@Slf4j
@Aspect
@Component
@Order(2)
public class MailSendLogAspect {
/**
* 定义线程池
* @author hf-hf
* @date 2019/1/10 11:56
*/
private final ExecutorService SAVE_LOG_EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);
@Autowired
private MailSendLogService sendLogService;
/**
* 定义切点
* @author hf-hf
* @date 2019/1/10 11:56
*/
@Pointcut("execution(public * top.hunfan.mail.service.MailService.send(..)) ")
public void log(){
}
@AfterReturning(returning="result", pointcut="log()")
public void doAfterReturning(JoinPoint joinPoint, R result) {
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = sra.getRequest();
// 下面两个数组中,参数值和参数名的个数和位置是一一对应的。
// 参数值
Object[] args = joinPoint.getArgs();
// 参数名
String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
// 异步存储日志
CompletableFuture.runAsync(new SaveLogThread(sendLogService, args, argNames,
ThreadLocalUtils.get(Constants.CURRENT_MAIL_FROM), request.getRemoteHost(),
result.getCode(), result.getMessage()), SAVE_LOG_EXECUTOR_SERVICE);
log.debug("方法返回值:" + result);
}
/**
* 保存日志线程
* @author hf-hf
* @date 2019/1/10 11:52
*/
@AllArgsConstructor
public static class SaveLogThread extends Thread{
private MailSendLogService sendLogService;
private Object[] args;
private String[] argNames;
private String form;
private String ip;
private Integer code;
private String message;
@Override
public void run() {
ThreadLocalUtils.remove(Constants.CURRENT_MAIL_FROM);
MailSendLog sendLog = new MailSendLog();
for(int i=0;i < argNames.length;i++){
if("attachmentFile".equals(argNames[i])){
continue;
}
Field field = ReflectionUtils.findField(sendLog.getClass(), argNames[i]);
Column column = field.getAnnotation(Column.class);
field.setAccessible(true);
String objStr = null == column ? StringTools.asString(args[i])
: StringTools.asString(args[i], column.length());
if(null != objStr){
try {
field.set(sendLog, objStr);
} catch (IllegalAccessException e) {
}
}
}
sendLog.setForm(this.form);
sendLog.setIp(this.ip);
sendLog.setSentCode(this.code);
sendLog.setSentMessage(this.message);
sendLog.setCreateTime(new Date());
sendLogService.save(sendLog);
}
}
}
<|start_filename|>src/main/java/top/hunfan/mail/utils/ApplicationContextUtils.java<|end_filename|>
package top.hunfan.mail.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring 上下文容器获取类
* @ClassName ApplicationContextUtils
* @Description
* @author hf-hf
* @date 2017年7月5日 下午2:26:45
*/
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext ac;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtils.ac = applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) ac.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
return ac.getBean(requiredType);
}
}
<|start_filename|>src/main/java/top/hunfan/mail/repository/MailSendLogRepository.java<|end_filename|>
package top.hunfan.mail.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import top.hunfan.mail.entity.po.MailSendLog;
public interface MailSendLogRepository extends JpaRepository<MailSendLog, Integer> {
}
<|start_filename|>src/main/java/top/hunfan/mail/service/MailService.java<|end_filename|>
package top.hunfan.mail.service;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.hunfan.mail.domain.R;
import top.hunfan.mail.utils.MailUtil;
/**
* 邮件服务
* @author hf-hf
* @date 2018/12/26 16:13
*/
@Service
public class MailService {
@Value("${file.folder}")
private String fileFolder;
/**
* 发送邮件
* @author hf-hf
* @date 2018/12/26 16:14
* @param to 收件人
* @param title 标题
* @param content 内容
* @param attachmentFile 附件
* @throws Throwable
*/
public boolean sendMail(String to, String title, String content, String attachmentName,
MultipartFile attachmentFile) throws Throwable {
File tempFile = null;
if (attachmentFile != null) {
File tempFolder = new File(fileFolder);
if (!tempFolder.exists() || !tempFolder.isDirectory()) {
FileUtils.forceMkdir(tempFolder);
}
//attachmentFile.getOriginalFilename() + RandomStringUtils.randomNumeric(5)
tempFile = new File(fileFolder, attachmentName);
tempFile.createNewFile();
attachmentFile.transferTo(tempFile);
}
return MailUtil.getInstance().send(to, title, content, tempFile);
}
/**
* 发送邮件
* @author hf-hf
* @date 2018/12/26 16:14
* @param to 收件人
* @param title 标题
* @param content 内容
* @param attachmentFile 附件
*/
public R send(String to, String title, String content, String attachmentName,
MultipartFile attachmentFile){
try {
return R.operate(sendMail(to, title, content,
attachmentName, attachmentFile));
} catch (Throwable e){
return R.fail(e.getMessage());
}
}
}
<|start_filename|>src/main/java/top/hunfan/mail/roundrobin/Invoker.java<|end_filename|>
package top.hunfan.mail.roundrobin;
/**
* 调用程序
* @author hf-hf
* @date 2018/12/27 10:17
*/
public interface Invoker {
/**
* 是否可用
*/
Boolean isAvailable();
/**
* 标识
*/
String id();
}
<|start_filename|>src/main/java/top/hunfan/mail/utils/MailManager.java<|end_filename|>
package top.hunfan.mail.utils;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
/**
* 负载均衡
* @author hf-hf
* @date 2018/12/27 14:40
*/
public class MailManager {
public static Map<String, Properties> propertiesMap = new ConcurrentHashMap<>();
public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();
public static void putProperties(String key, Properties properties){
propertiesMap.put(key, properties);
}
public static void putSession(String key, Session session){
sessionMap.put(key, session);
}
public static void putBoth(String key, Properties properties){
putProperties(key, properties);
// 此处要用 Session#getInstance,Session#getDefaultInstance 为单例
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(properties.getProperty("mail.username"),
properties.getProperty("mail.password"));
}
});
if(null != properties.getProperty("mail.debug")){
session.setDebug(Boolean.valueOf(properties.getProperty("mail.debug")));
}
putSession(key, session);
}
public static void putBoth(Object key, Properties properties){
putBoth(String.valueOf(key), properties);
}
public static Session getSession(String key){
return sessionMap.get(key);
}
public static Properties getProperties(String key){
return propertiesMap.get(key);
}
}
<|start_filename|>src/main/java/top/hunfan/mail/entity/po/MailSendLog.java<|end_filename|>
package top.hunfan.mail.entity.po;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
/**
* 邮件日志
* @author hf-hf
* @date 2019/1/8 15:35
*/
@Entity
@Table(name = "mail_send_log")
@Data
public class MailSendLog {
@Id
@GeneratedValue
private int id;
@Column(name = "form", length = 100)
private String form;
@Column(name = "to", length = 100)
private String to;
@Column(name = "title", length = 20)
private String title;
@Column(name = "content", length = 300)
private String content;
@Column(name = "attachmentName", length = 20)
private String attachmentName;
@Column(name = "ip", length = 20)
private String ip;
/**
* 发送状态
* ex:success:200,fail:500
*/
@Column(name = "sent_code", length = 3)
private Integer sentCode;
@Column(name = "sent_message", length = 20)
private String sentMessage;
/**
* 创建时间
* 默认年月日时分秒 @Temporal(TemporalType.TIMESTAMP)
*/
@Column(name = "createTime")
private Date createTime;
}
<|start_filename|>src/main/java/top/hunfan/mail/utils/MailUtil.java<|end_filename|>
package top.hunfan.mail.utils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import lombok.extern.slf4j.Slf4j;
import top.hunfan.mail.domain.Constants;
import top.hunfan.mail.roundrobin.RoundRobin;
import top.hunfan.mail.roundrobin.RoundRobinFactory;
/**
* 邮件发送,支持多邮箱配置、轮询、加权轮询
* @author hf-hf
* @date 2018/12/27 10:58
*/
@Slf4j
public class MailUtil {
private static final String MAIL_PROPERTIES = "mail%d.properties";
private static final String CHART_SET_UTF8 = "UTF-8";
private static final String CONTENT_TYPE_HTML = "text/html; charset=UTF-8";
private static final String READ_SYSTEM_PATH_FILE = "READ_SYSTEM_PATH_FILE";
private static final String READ_CLASS_PATH_FILE = "READ_CLASS_PATH_FILE";
private boolean initComplete = false;
private RoundRobin roundRobin;
/**
* 通过单例对象获取
* @author hf-hf
* @date 2018/12/27 14:59
* @param roundRobinType 轮询类型
*/
private MailUtil(String roundRobinType) {
//优先读取外部配置文件
readConfigFiles(READ_SYSTEM_PATH_FILE);
if(MailManager.propertiesMap.isEmpty()){
log.info("read system path is null");
readConfigFiles(READ_CLASS_PATH_FILE);
}
if(!MailManager.propertiesMap.isEmpty()){
roundRobin = RoundRobinFactory.create(roundRobinType,
MailManager.propertiesMap.values());
}
if(null != roundRobin){
initComplete = true;
}
log.info("load mail properties finish,success count={}", MailManager.propertiesMap.size());
}
/**
* 读取外部配置
* @param fileName
* @return
*/
private InputStream readSystemPath(String fileName){
String path = System.getProperty("user.dir") + File.separator + fileName;
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(path));
} catch (FileNotFoundException e) {
// ignore
}
return in;
}
/**
* 读取内部文件
* @author hf-hf
* @date 2018/12/29 9:25
*/
private InputStream readClassPath(String fileName){
return this.getClass().getClassLoader().getResourceAsStream(fileName);
}
/**
* 读取配置文件
* @author hf-hf
* @date 2018/12/29 9:34
*/
private void readConfigFiles(String readPath){
InputStream in = null;
Properties properties = null;
String fileName = "";
for (int i = 0; ; i++) {
fileName = String.format(MAIL_PROPERTIES, i);
in = READ_SYSTEM_PATH_FILE.equals(readPath)
? readSystemPath(fileName) : readClassPath(fileName);
if (in == null) {
break;
}
log.info("load " + fileName);
try (Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
properties = new Properties();
properties.load(reader);
if(!checkMailConifg(properties)){
//throw new PropertyException(readPath + " " + fileName + "config error!");
log.info(readPath + " " + fileName + "config error!");
break;
}
MailManager.putBoth(properties.get("mail.id"), properties);
} catch (Exception e) {
log.error("load " + readPath + " " + fileName + "error!",e);
} finally {
try {
in.close();
} catch (IOException e) {
log.error("in close error", e);
}
}
}
}
/**
* 校验mail配置项
* @author hf-hf
* @date 2018/12/28 16:03
*/
private boolean checkMailConifg(Properties properties){
if(null == properties.get("mail.id")){
log.error("mail id is not null!");
return false;
}
if(null == properties.get("mail.username")
|| "".equals(properties.get("mail.username"))){
log.error("mail username is not null!");
return false;
}
if(null == properties.get("mail.password")
|| "".equals(properties.get("mail.password"))){
log.error("mail password is not null!");
return false;
}
if(null != properties.get("mail.weight")
&& !(StringUtils.isNumeric((String) properties.get("mail.weight")))){
log.error("mail weight requirement is number!");
return false;
}
if(null == properties.getProperty("mail.isAvailable")){
log.error("mail isAvailable is not null!");
return false;
}
try {
Boolean tmp = Boolean.valueOf((String) properties.get("mail.isAvailable"));
} catch (Exception e){
log.error("mail isAvailable requirement is boolean!");
return false;
}
return true;
}
/**
* 发送邮件
* @param to 收件人,多个收件人用 {@code ;} 分隔
* @param subject 主题
* @param content 内容
* @return 如果邮件发送成功,则返回 {@code true},否则返回 {@code false}
*/
public boolean send(String to, String subject, String content) {
return send(to, null, null, subject,
content, null, null);
}
/**
* 发送邮件
* @param to 收件人,多个收件人用 {@code ;} 分隔
* @param subject 主题
* @param content 内容
* @param attachment 附件
* @return 如果邮件发送成功,则返回 {@code true},否则返回 {@code false}
*/
public boolean send(String to, String subject, String content, File attachment) {
File[] attachments = null;
if(null != attachment){
attachments = new File[]{attachment};
}
return send(to, null, null, subject,
content, null, attachments);
}
/**
* 发送邮件(负载均衡)
*
* @param key 负载均衡key
* @param to 收件人,多个收件人用 {@code ;} 分隔
* @param cc 抄送人,多个抄送人用 {@code ;} 分隔
* @param bcc 密送人,多个密送人用 {@code ;} 分隔
* @param subject 主题
* @param content 内容,可引用内嵌图片,引用方式:{@code <img src="cid:内嵌图片文件名" />}
* @param images 内嵌图片
* @param attachments 附件
* @return 如果邮件发送成功,则返回 {@code true},否则返回 {@code false}
*/
public boolean sendByLoadBalance(String key, String to, String cc,
String bcc, String subject, String content,
File[] images, File[] attachments){
log.info("loadBalanceKey={}", key);
Properties properties = MailManager.getProperties(key);
log.info("properties={}", properties);
Session session = MailManager.getSession(key);
MimeMessage message = new MimeMessage(session);
String username = properties.getProperty("mail.username");
ThreadLocalUtils.put(Constants.CURRENT_MAIL_FROM, username);
try {
message.setFrom(new InternetAddress(username));
addRecipients(message, Message.RecipientType.TO, to);
if (cc != null) {
addRecipients(message, Message.RecipientType.CC, cc);
}
if (bcc != null) {
addRecipients(message, Message.RecipientType.BCC, bcc);
}
message.setSubject(subject, CHART_SET_UTF8);
// 最外层部分
MimeMultipart wrapPart = new MimeMultipart("mixed");
MimeMultipart htmlWithImageMultipart = new MimeMultipart("related");
// 文本部分
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(content, CONTENT_TYPE_HTML);
htmlWithImageMultipart.addBodyPart(htmlPart);
// 内嵌图片部分
addImages(images, htmlWithImageMultipart);
MimeBodyPart htmlWithImageBodyPart = new MimeBodyPart();
htmlWithImageBodyPart.setContent(htmlWithImageMultipart);
wrapPart.addBodyPart(htmlWithImageBodyPart);
// 附件部分
addAttachments(attachments, wrapPart);
message.setContent(wrapPart);
Transport.send(message);
return true;
} catch (Exception e) {
log.error("sendByLoadBalance error!", e.getMessage(),
"loadBalanceKey={}, properties={}, to={}, cc={}, "
+ "bcc={}, subject={}, content={}, images={}, attachments={}",
key, properties, to, cc,
bcc, subject, content, images, attachments, e);
}
return false;
}
/**
* 发送邮件
*
* @param to 收件人,多个收件人用 {@code ;} 分隔
* @param cc 抄送人,多个抄送人用 {@code ;} 分隔
* @param bcc 密送人,多个密送人用 {@code ;} 分隔
* @param subject 主题
* @param content 内容,可引用内嵌图片,引用方式:{@code <img src="cid:内嵌图片文件名" />}
* @param images 内嵌图片
* @param attachments 附件
* @return 如果邮件发送成功,则返回 {@code true},否则返回 {@code false}
*/
public boolean send(String to, String cc, String bcc,
String subject, String content,
File[] images, File[] attachments) {
if(!initComplete){
throw new ExceptionInInitializerError("mail init error!");
}
// 负载均衡实现
String key = roundRobin.select().id();
if(StringUtils.isEmpty(key)){
//TODO invoker降级,移除
throw new RuntimeException("轮询异常!");
}
return sendByLoadBalance(key, to, cc, bcc, subject, content, images, attachments);
}
/**
* 追加附件
* @author hf-hf
* @date 2018/12/27 16:53
* @param attachments
* @param wrapPart
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
private void addAttachments(File[] attachments, MimeMultipart wrapPart)
throws MessagingException, UnsupportedEncodingException {
if (null != attachments && attachments.length > 0) {
for (int i = 0; i < attachments.length; i++) {
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new FileDataSource(attachments[i]));
String fileName = dataHandler.getName();
attachmentBodyPart.setDataHandler(dataHandler);
// 显示指定文件名(防止文件名乱码)
attachmentBodyPart.setFileName(MimeUtility.encodeText(fileName));
wrapPart.addBodyPart(attachmentBodyPart);
}
}
}
/**
* 追加内嵌图片
* @author hf-hf
* @date 2018/12/27 16:53
* @param images
* @param multipart
* @throws MessagingException
*/
private void addImages(File[] images, MimeMultipart multipart) throws MessagingException {
if (null != images && images.length > 0) {
for (int i = 0; i < images.length; i++) {
MimeBodyPart imagePart = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new FileDataSource(images[i]));
imagePart.setDataHandler(dataHandler);
imagePart.setContentID(images[i].getName());
multipart.addBodyPart(imagePart);
}
}
}
/**
* 追加发件人
* @author hf-hf
* @date 2018/12/27 15:36
*/
private void addRecipients(MimeMessage message, Message.RecipientType type,
String recipients) throws MessagingException {
String[] addresses = recipients.split(";");
for (int i = 0; i < addresses.length; i++) {
message.addRecipients(type, addresses[i]);
}
}
/**
* 静态内部类
*/
private static class MailUtilHolder {
private static Environment env = ApplicationContextUtils.getBean("environment");
private static final MailUtil instance =
new MailUtil(env.getProperty("mail.roundrobin.type"));
}
/**
* 获取邮件发送工具
* @return
*/
public static final MailUtil getInstance() {
return MailUtilHolder.instance;
}
}
<|start_filename|>src/main/java/top/hunfan/mail/roundrobin/AbstractRoundRobin.java<|end_filename|>
package top.hunfan.mail.roundrobin;
import java.util.List;
/**
* 抽象轮询
* @author hf-hf
* @date 2018/12/27 10:17
*/
abstract class AbstractRoundRobin implements RoundRobin {
protected List<Node> nodes;
protected boolean checkNodes(){
return nodes != null && nodes.size() > 0;
}
class Node implements Comparable<Node> {
final Invoker invoker;
Integer weight;
Integer effectiveWeight;
Integer currentWeight;
public Node(Invoker invoker) {
this.invoker = invoker;
this.currentWeight = 0;
}
Node(Invoker invoker, Integer weight) {
this.invoker = invoker;
this.weight = weight;
this.effectiveWeight = weight;
this.currentWeight = 0;
}
@Override
public int compareTo(Node o) {
return currentWeight > o.currentWeight ? 1 : (currentWeight.equals(o.currentWeight) ? 0 : -1);
}
/**
* 调用成功升级
*/
public void onSuccess() {
if (effectiveWeight < this.weight){
effectiveWeight++;
}
}
/**
* 调用异常服务降级
*/
public void onFail() {
effectiveWeight--;
}
}
}
<|start_filename|>src/main/java/top/hunfan/mail/web/MailApiController.java<|end_filename|>
package top.hunfan.mail.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.hunfan.mail.domain.R;
import top.hunfan.mail.service.MailSendLogService;
import top.hunfan.mail.service.MailService;
/**
* 邮件api
* @author hf-hf
* @date 2018/12/26 16:17
*/
@RestController
@RequestMapping(value = "/mail")
public class MailApiController {
@Autowired
private MailService service;
@Autowired
private MailSendLogService sendLogService;
@RequestMapping(value = "/send", method = RequestMethod.POST)
public R sendMail(String to, String title, String content, String attachmentName,
MultipartFile attachmentFile) {
return service.send(to, title, content, attachmentName, attachmentFile);
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public R list(int page, int size) {
return R.success(sendLogService.findByPage(page, size));
}
@RequestMapping(value = "/clean", method = RequestMethod.POST)
public R clean() {
sendLogService.clean();
return R.success();
}
}
<|start_filename|>src/test/java/top/mail/H2DatabaseTest.java<|end_filename|>
package top.mail;
import java.util.Date;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import lombok.extern.slf4j.Slf4j;
import top.hunfan.mail.MailMicroServiceApplication;
import top.hunfan.mail.domain.Code;
import top.hunfan.mail.entity.po.MailSendLog;
import top.hunfan.mail.repository.MailSendLogRepository;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MailMicroServiceApplication.class)
public class H2DatabaseTest {
@Autowired
private MailSendLogRepository mailSendLogRepository;
@Test
public void save(){
MailSendLog mailSendLog = new MailSendLog();
mailSendLog.setForm("123<EMAIL>");
mailSendLog.setTo("<EMAIL>");
mailSendLog.setTitle("测试");
mailSendLog.setContent("12321");
mailSendLog.setAttachmentName("123.jpg");
mailSendLog.setIp("127.0.0.1");
mailSendLog.setSentCode(Code.SUCCEED.getCode());
mailSendLog.setCreateTime(new Date());
MailSendLog save = mailSendLogRepository.save(mailSendLog);
Assert.notNull(save,"save error!");
}
@Test
public void findAll(){
Page<MailSendLog> list = mailSendLogRepository.findAll(PageRequest.of(0, 1));
Assert.notNull(list,"findAll error!");
}
}
<|start_filename|>src/main/java/top/hunfan/mail/service/MailSendLogService.java<|end_filename|>
package top.hunfan.mail.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.hunfan.mail.entity.po.MailSendLog;
import top.hunfan.mail.repository.MailSendLogRepository;
/**
* 邮件发送日志
* @author hf-hf
* @date 2019/1/9 14:09
*/
@Service
public class MailSendLogService {
@Autowired
private MailSendLogRepository sendLogRepository;
public Page<MailSendLog> findByPage(int page, int size){
Sort sort = new Sort(Sort.Direction.DESC, "id");
return sendLogRepository.findAll(PageRequest.of(page, size, sort));
}
public void clean(){
sendLogRepository.deleteAll();
}
public void delete(Integer id){
sendLogRepository.deleteById(id);
}
public MailSendLog save(MailSendLog mailSendLog){
return sendLogRepository.save(mailSendLog);
}
}
<|start_filename|>src/main/java/top/hunfan/mail/utils/ThreadLocalUtils.java<|end_filename|>
package top.hunfan.mail.utils;
import java.util.HashMap;
import java.util.Map;
/**
* ThreadLocal工具类
* @author hf-hf
* @date 2019/1/11 16:15
*/
public class ThreadLocalUtils {
private static final ThreadLocal<Map<String, Object>> local = ThreadLocal.withInitial(() -> new HashMap<>());
public static <T> T put(String key, T value) {
local.get().put(key, value);
return value;
}
public static void remove(String key) {
local.get().remove(key);
}
public static void clear() {
local.remove();
}
@SuppressWarnings("unchecked")
public static <T> T get(String key) {
return ((T) local.get().get(key));
}
}
<|start_filename|>src/main/java/top/hunfan/mail/domain/R.java<|end_filename|>
package top.hunfan.mail.domain;
import java.io.Serializable;
import lombok.Data;
/**
* 统一返回值
* @author hf-hf
* @date 2018/12/29 10:27
*/
@Data
public class R implements Serializable {
/**
* 返回码
*/
private int code = Code.SUCCEED.getCode();
/**
* 返回信息
*/
private String message = Code.SUCCEED.getMessage();
/**
* 返回数据
*/
private Object data;
public static R success() {
return success(null);
}
public static R success(Object data) {
return new R(Code.SUCCEED.getCode(), Code.SUCCEED.getMessage(), data);
}
public static R fail() {
return new R(Code.FAILED.getCode(), Code.FAILED.getMessage());
}
public static R fail(String message) {
return new R(Code.FAILED.getCode(), message);
}
public static R operate(boolean isSucceed) {
return isSucceed ? success() : fail();
}
public R() {
}
public R(int code, String message) {
this.code = code;
this.message = message;
}
public R(int code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
}
<|start_filename|>src/main/resources/static/css/style.css<|end_filename|>
body {
margin : 0;
}
.title {
border-bottom: 1px solid;
padding: 5px 20px;
margin-bottom: 24px;
font-weight: bold;
font-size : 14px;
}
.title > button {
float:right;
margin-left: 5px;
}
#mail-titles {
vertical-align: top;
display: inline-block;
}
#mail-titles .active {
color: #D68900;
}
#mail-titles > div {
#border-bottom: 1px solid #ddd;
padding: 5px 5px 5px 20px;
word-break: break-all;
}
#mail {
margin : 0;
width : 75%;
display: inline-block;
border-left: 1px solid #ddd;
overflow: hidden;
}
#mail > table td {
padding: 10px;
word-break: break-all;
}
.label {
width : 80px;
color: #666;
}
.mail-record {
border-top: 1px solid #808080;
}
.record {
height: 50px;
width: 280px;
font-size: 12px;
color: #808080;
#border: 1px solid #808080;
position: relative;
padding-left: 10px;
padding-right: 10px;
}
.mail-title {
position: absolute;
left: 0;
bottom: 7px;
width: 200px;
text-overflow:ellipsis;
white-space: nowrap;
overflow: hidden;
}
.mail-to {
position: absolute;
left: 0;
top: 7px;
width: 200px;
text-overflow:ellipsis;
white-space: nowrap;
overflow: hidden;
}
/*.mail-to:hover {*/
/*height: auto;*/
/*word-break:break-all;*/
/*white-space: pre-wrap;*/
/*text-decoration: none;*/
/*}*/
.mail-date {
position: absolute;
right: 0;
top: 7px;
}
.mail-status {
position: absolute;
right: 0;
bottom: 7px;
}
.title > select {
float:right;
height: 23px;
}
<|start_filename|>src/main/java/top/hunfan/mail/domain/Constants.java<|end_filename|>
package top.hunfan.mail.domain;
/**
* 常量类
* @author hf-hf
* @date 2019/1/13 16:16
*/
public class Constants {
/**
* 当前邮件发件人
*/
public static final String CURRENT_MAIL_FROM = "CURRENT_MAIL_FROM";
}
<|start_filename|>src/main/java/top/hunfan/mail/domain/Code.java<|end_filename|>
package top.hunfan.mail.domain;
/**
* 响应异常代码
* @author hf-hf
* @date 2018/12/29 10:27
*/
public enum Code {
/**
* 200 成功
*/
SUCCEED(200, "发送成功"),
/**
* 500 失败
*/
FAILED(500, "发送失败");
/**
* 业务异常编码
*/
private int code;
/**
* 异常信息
*/
private String message;
Code(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
<|start_filename|>src/main/java/top/hunfan/mail/utils/StringTools.java<|end_filename|>
package top.hunfan.mail.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
/**
* 字符串工具类
* @author hf-hf
* @date 2019/1/9 15:31
*/
public class StringTools {
private static final String YEAR_MONTH_DAY_HOUR_MINUTE_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static NumberFormat doubleFormat;
private static Map<String, DateFormat> formatterMap = new HashMap<>();
public static boolean isNull(Object obj) {
return obj == null;
}
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
} else if (obj instanceof List) {
return ((List)obj).isEmpty();
} else if (obj instanceof Map) {
return ((Map)obj).isEmpty();
} else {
return obj.toString().trim().length() == 0;
}
}
public static String doubleToStr(double obj, int maxFractionDigits) {
NumberFormat df = getDoubleFormat(false, maxFractionDigits);
synchronized(df) {
return df.format(obj);
}
}
private static NumberFormat getDoubleFormat(boolean showGroup, int maxFractionDigits) {
if (doubleFormat == null) {
doubleFormat = NumberFormat.getNumberInstance();
}
doubleFormat.setGroupingUsed(showGroup);
doubleFormat.setMaximumFractionDigits(maxFractionDigits);
return doubleFormat;
}
public static String dateToStr(Date date) {
return asString(date, YEAR_MONTH_DAY_HOUR_MINUTE_PATTERN);
}
public static String asString(Object obj, int maxLength){
String objStr = asString(obj);
if(null == objStr || objStr.length() <= maxLength){
return objStr;
}
return objStr.substring(0, maxLength);
}
public static String asString(Object obj) {
if (isNull(obj)) {
return null;
} else if (isEmpty(obj)) {
return "";
} else if (obj instanceof Date) {
return dateToStr((Date)obj);
} else if (obj instanceof Double) {
return doubleToStr(((Double)obj).doubleValue(), 6);
} else {
try {
String value = ReadXlobStr(obj);
if (value != null) {
return value;
}
} catch (Exception var2) {
return var2.getMessage();
}
return obj.toString();
}
}
public static String asString(Date date, String format) {
return asString(date, format, TimeZone.getDefault().getID());
}
public static String asString(Date date, String format, String timeZone) {
String strDate = "";
if (date != null) {
DateFormat df = getDateFormat(format, timeZone);
synchronized(df) {
strDate = df.format(date);
}
}
return strDate;
}
private static DateFormat getDateFormat(String format, String timeZone) {
DateFormat df = formatterMap.get(format + "_" + timeZone);
if (df == null) {
df = new SimpleDateFormat(format);
df.setTimeZone(TimeZone.getTimeZone(timeZone));
formatterMap.put(format + "_" + timeZone, df);
}
return df;
}
public static String ReadXlobStr(Object xlob) throws SQLException, IOException {
StringBuffer result = new StringBuffer();
BufferedReader reader = null;
if (xlob instanceof Blob) {
reader = new BufferedReader(new InputStreamReader(((Blob)xlob).getBinaryStream()));
} else {
if (!(xlob instanceof Clob)) {
return null;
}
reader = new BufferedReader(((Clob)xlob).getCharacterStream());
}
if (reader != null) {
for(String line = reader.readLine(); line != null; line = reader.readLine()) {
result.append(line).append("\n");
}
}
return result.toString();
}
}
| hf-hf/mail-micro-service |
<|start_filename|>src/main/java/com/currencycloud/client/model/WithdrawalAccounts.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class WithdrawalAccounts extends PaginatedData {
private List<WithdrawalAccount> withdrawalAccounts;
public List<WithdrawalAccount> getWithdrawalAccounts() {
return withdrawalAccounts;
}
@Override
public String toString() {
return String.format("{\"withdrawal_accounts\":%s, \"pagination\":%s}", withdrawalAccounts, pagination);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/exception/NotFoundException.java<|end_filename|>
package com.currencycloud.client.exception;
import com.currencycloud.client.model.ResponseException;
/** Thrown when a 404 HTTP response is returned. */
public class NotFoundException extends ApiException {
protected NotFoundException(ResponseException e) {
super(e);
}
}
<|start_filename|>src/test/java/com/currencycloud/examples/CurrencyCloudCookbook.java<|end_filename|>
package com.currencycloud.examples;
import com.currencycloud.client.CurrencyCloudClient;
import com.currencycloud.client.backoff.BackOff;
import com.currencycloud.client.backoff.BackOffResult;
import com.currencycloud.client.exception.CurrencyCloudException;
import com.currencycloud.client.model.*;
import java.math.BigDecimal;
import java.util.*;
/**
* This is a Java SDK implementation of the examples in the
* <a href="https://connect.currencycloud.com/documentation/getting-started/cookbook">Currency Cloud API v2.0 Cookbook</a>.
* All API calls are wrapped in try/catch blocks and executed using an exponential backoff-and-retry policy.
*
* The default parameters used are:
* - BackOff.<T>builder().withMaxAttempts - Maximum number of retries set to 7
* - BackOff.<T>builder().withBase - Minimum wait time in milliseconds set to a random value between 125 and 750
* - BackOff.<T>builder().withCap - Maximum wait time in milliseconds set to a random value between 60000 and 90000
* - BackOff.<T>builder().withExceptionType(TooManyRequestsException.class) - TooManyRequestsException. All other
* exceptions are rethrown
*
* Please see BackOffTest.java for a comprehensive set of test cases
*/
public class CurrencyCloudCookbook {
public static void main(String[] args) throws Exception {
// Please provide your login id and api key here to run this example.
runCookBook("<EMAIL>", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
}
public static void runCookBook(String loginId, String apiKey) {
/*
* 1. Generate an authentication token. This authentication token will be used in all subsequent calls and
* will expire after 30mins of inactivity after login. Token requests are limited to 10 calls/min. Individual
* contacts will be locked out of the account after 4 unsuccessful login attempts.
*/
CurrencyCloudClient client = new CurrencyCloudClient(CurrencyCloudClient.Environment.demo, loginId, apiKey);
try {
final BackOffResult<Void> authenticateResult = BackOff.<Void>builder()
.withTask(() -> {
client.authenticate();
return null;
})
.execute();
} catch (Exception e) {
e.printStackTrace();
}
/*
* 2. Get a quote for the requested currency based on the spread table of the currently logged in contact. If
* delivery date is not supplied it will default to a deal which settles in 2 working days.
*/
DetailedRate detailedRate = null;
try {
final BackOffResult<DetailedRate> detailedRateResult = BackOff.<DetailedRate>builder()
.withTask(() -> client.detailedRates(
"EUR",
"GBP",
"buy",
new BigDecimal("12345.67"),
null,
null
)
)
.execute();
detailedRate = detailedRateResult.data.orElse(null);
System.out.println("Single Detailed Rate: " + detailedRate.toString());
} catch (Exception e) {
e.printStackTrace();
}
/*
* 3. We are happy with the rate and now wish to create the conversion. A successful response means that the
* currency conversion has been executed and the amount of sold funds need to arrive at Currencycloud by the
* settlement_date. The funds will be available for payment after the conversion has settled on the conversion_date.
*/
Conversion conversion = null;
try {
final BackOffResult<Conversion> conversionResult = BackOff.<Conversion>builder()
.withTask(() -> {
Conversion conversionTemp = Conversion.create();
conversionTemp.setBuyCurrency("EUR");
conversionTemp.setSellCurrency("GBP");
conversionTemp.setFixedSide("buy");
conversionTemp.setAmount(new BigDecimal("12345.67"));
conversionTemp.setReason("Invoice Payment");
conversionTemp.setTermAgreement(true);
return client.createConversion(conversionTemp);
})
.execute();
conversion = conversionResult.data.orElse(null);
} catch (CurrencyCloudException e) {
e.printStackTrace();
}
System.out.println(conversion.toString());
/*
* 4. Create a new beneficiary. Some of the optional parameters may be required depending on the currency and
* the country of the beneficiary and beneficiary bank. Please use the /reference/beneficiary_required_details
* call to know which fields would be required.
*/
List<Map<String, String>> beneficiaryRequiredDetails = null;
try {
final BackOffResult<List<Map<String, String>>> beneficiaryRequiredDetailsResult = BackOff.<List<Map<String, String>>>builder()
.withTask(() -> client.beneficiaryRequiredDetails("EUR", "IT", "IT"))
.execute();
beneficiaryRequiredDetails = beneficiaryRequiredDetailsResult.data.orElse(null);
} catch (CurrencyCloudException e) {
e.printStackTrace();
}
System.out.println(beneficiaryRequiredDetails.toString());
/*
* We know the IBAN and BIC/SWIFT numbers for the beneficiary, so we can use these details.
*/
Beneficiary beneficiary = null;
try {
final BackOffResult<Beneficiary> beneficiaryResult = BackOff.<Beneficiary>builder()
.withTask(() -> {
Beneficiary beneficiaryObj = Beneficiary.create("Antica Salumeria Pane 1864", "IT", "EUR", "Fortunato Pane");
beneficiaryObj.setBeneficiaryCountry("IT");
beneficiaryObj.setBicSwift("BKRAITMM");
beneficiaryObj.setIban("IT40L2798279187CC4WJAU999QH");
List<String> beneficiaryAddress = new ArrayList<String>();
beneficiaryAddress.add("Via Luigi Settembrini n° 111");
beneficiaryAddress.add("80138, Naples, Italy");
beneficiaryObj.setBeneficiaryAddress(beneficiaryAddress);
return client.createBeneficiary(beneficiaryObj);
})
.execute();
beneficiary = beneficiaryResult.data.orElse(null);
} catch (CurrencyCloudException e) {
e.printStackTrace();
}
System.out.println(beneficiary.toString());
/*
* Validate this beneficiary before we attempt a payment to avoid payment failures.
*/
final Beneficiary beneficiaryTemp = beneficiary;
try {
final BackOffResult<Void> validateBeneficiaryResult = BackOff.<Void>builder()
.withTask(() -> {
System.out.println(client.validateBeneficiary(beneficiaryTemp).toString());
return null;
})
.execute();
} catch (CurrencyCloudException e) {
e.printStackTrace();
}
/*
* 5. Provide details of the Payer and Pay
*/
Payer payer = null;
try {
final BackOffResult<Payer> payerResult = BackOff.<Payer>builder()
.withTask(() -> {
List<String> payerAddress = new ArrayList<String>();
payerAddress.add("12 Steward St");
payerAddress.add("London E1 6FQ");
return Payer.create(
"individual",
"Currencycloud Ltd.",
"Guido",
"Bianco",
payerAddress,
"London",
"GB",
new Date()
);
})
.execute();
payer = payerResult.data.orElse(null);
} catch (Exception e) {
e.printStackTrace();
}
/*
* Finally, we create a payment to send the funds to the beneficiary. Currencycloud will execute the payment
* when the related conversion settles.
*/
final Payer payerTemp = payer;
final Payment paymentTemp = Payment.create(
"EUR",
beneficiary.getId(),
new BigDecimal("12345.67"),
"Invoice Payment",
"Invoice 1234",
null,
"regular",
conversion.getId(),
null
);
Payment payment = null;
try {
final BackOffResult<Payment> paymentResult = BackOff.<Payment>builder()
.withTask(() -> client.createPayment(paymentTemp, payerTemp))
.execute();
payment = paymentResult.data.orElse(null);
} catch (CurrencyCloudException e) {
e.printStackTrace();
}
System.out.println(payment.toString());
/*
* 6. All sessions must come to an end, either manually using this call, or the session will automatically
* timeout after 30 minutes of inactivity. If the session is no longer required, it is best practice to close
* the session rather than leaving it to time-out. A successful response will return a 200 code with a blank body.
*/
try {
final BackOffResult<Void> endSessionResult = BackOff.<Void>builder()
.withTask(() -> {
client.endSession();
return null;
})
.execute();
} catch (CurrencyCloudException e) {
e.printStackTrace();
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ConversionCancellation.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ConversionCancellation implements Entity {
private String id;
private String accountId;
private String contactId;
private String eventAccountId;
private String eventContactId;
private String conversionId;
private String eventType;
private BigDecimal amount;
private String currency;
private String notes;
private Date eventDateTime;
protected ConversionCancellation() { }
private ConversionCancellation(String id) {
this.id = id;
}
public static ConversionCancellation create() {
return new ConversionCancellation();
}
public static ConversionCancellation create(String id) {
return new ConversionCancellation(id);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContactId() {
return contactId;
}
public void setContactId(String contactId) {
this.contactId = contactId;
}
public String getEventAccountId() {
return eventAccountId;
}
public void setEventAccountId(String eventAccountId) {
this.eventAccountId = eventAccountId;
}
public String getEventContactId() {
return eventContactId;
}
public void setEventContactId(String eventContactId) {
this.eventContactId = eventContactId;
}
public String getConversionId() {
return conversionId;
}
public void setConversionId(String conversionId) {
this.conversionId = conversionId;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Date getEventDateTime() {
return eventDateTime;
}
public void setEventDateTime(Date eventDateTime) {
this.eventDateTime = eventDateTime;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("accountId", accountId);
map.put("contactId", contactId);
map.put("eventAccountId", eventAccountId);
map.put("eventContactId", eventContactId);
map.put("conversionId", conversionId);
map.put("eventType", eventType);
map.put("amount", amount);
map.put("currency", currency);
map.put("notes", notes);
map.put("eventDateTime", eventDateTime);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentConfirmation.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentConfirmation implements Entity {
private String id;
private String paymentId;
private String accountId;
private String shortReference;
private String status;
private String confirmationUrl;
private Date createdAt;
private Date updatedAt;
private Date expiresAt;
protected PaymentConfirmation() {}
private PaymentConfirmation(String id) {
this.id = id;
}
public static PaymentConfirmation create() {
return new PaymentConfirmation();
}
public static PaymentConfirmation create(String id) {
return new PaymentConfirmation(id);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPaymentId() {
return paymentId;
}
public void setPaymentId(String paymentId) {
this.paymentId = paymentId;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getShortReference() {
return shortReference;
}
public void setShortReference(String shortReference) {
this.shortReference = shortReference;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getConfirmationUrl() {
return confirmationUrl;
}
public void setConfirmationUrl(String confirmationUrl) {
this.confirmationUrl = confirmationUrl;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Date getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(Date expiresAt) {
this.expiresAt = expiresAt;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("paymentId", paymentId);
map.put("accountId", accountId);
map.put("shortReference", shortReference);
map.put("status", status);
map.put("confirmationUrl", confirmationUrl);
map.put("createdAt", createdAt);
map.put("updatedAt", updatedAt);
map.put("expiresAt", expiresAt);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/test/java/com/currencycloud/client/ConcurrencyTest.java<|end_filename|>
package com.currencycloud.client;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Test multiple threads attempting to access a single instance of the CurrencyCloudClient class.
*
*/
public class ConcurrencyTest extends BetamaxTestSupport {
private CurrencyCloudClient client;
private String loginId = "<EMAIL>";
private String apiKey = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
private int numIterations = 512;
private int numThreads = 256;
@Before
public void prepareClient() {
client = prepareTestClient(loginId, apiKey, null);
}
@Before
@After
public void methodName() { log.debug("------------------------- " + name.getMethodName() + " -------------------------"); }
@Test
public void testConcurrentAccess() throws Exception {
ThreadSupport[] threads = new ThreadSupport[numThreads];
int counter = 0;
for (ThreadSupport thread : threads) {
thread = new ThreadSupport(counter, client, "deadbeef-dead-beef-dead-" + String.format("%1$012d", counter), numIterations);
thread.start();
threads[counter++] = thread;
}
long l = System.currentTimeMillis();
for (ThreadSupport thread : threads) {
thread.join();
}
System.out.println("Concurrency test finsihed succesfully in " + (System.currentTimeMillis() - l) + " msecs");
}
/**
*
* Class to simulate multiple threads accessing a single CurrencyCloudClient instance.
*
*/
private class ThreadSupport extends Thread {
private final String contactId;
private final int threadId;
private final int iterations;
private final Logger log = LoggerFactory.getLogger(CurrencyCloudClient.class);
private final CurrencyCloudClient client;
ThreadSupport(int threadId, CurrencyCloudClient client, String contactId) {
this.client = client;
this.threadId = threadId;
this.contactId = contactId;
this.iterations = 1000;
}
ThreadSupport(int threadId, CurrencyCloudClient client, String contactId, int iterations) {
this.client = client;
this.threadId = threadId;
this.contactId = contactId;
this.iterations = 1000;
assert iterations > 0;
}
@Override
public void run() {
System.out.println("ThreadSupport \"" + threadId + "\" running.");
int i=0;
while (i < iterations) {
try {
client.onBehalfOfDo(contactId, new Runnable() {
@Override
public void run() {
String onBehalfOf = client.getOnBehalfOf();
/**
* It is always expected that \"threadId\" = 12th last characters of onBehalf to ensure that the Runnable for that Thread is running
*/
assertThat(threadId, equalTo(Integer.parseInt(onBehalfOf.substring(onBehalfOf.length() - 12, onBehalfOf.length()))));
}
});
i++;
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ErrorMessage.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.exception.ApiException;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class ErrorMessage {
private String field;
private String code;
private String message;
private Map<String, Object> params;
protected ErrorMessage() { }
public ErrorMessage(String field, String code, String message, Map<String, Object> params) {
this.field = field;
this.code = code;
this.message = message;
this.params = params;
}
/** @return The error message code */
public String getCode() {
return code;
}
/** @return The error message in English */
public String getMessage() {
return message;
}
/** @return The field whose validation failed.
* Note that this is only populated in {@link ApiException} and subclasses,
* while it is always null in {@link ResponseException}. */
public String getField() {
return field;
}
/** @return Error parameters (may be used eg. for rendering the error message in other languages */
public Map<String, Object> getParams() {
return params;
}
@Override
public String toString() {
return String.format("ErrorMessage{code='%s', message='%s', params=%s}", code, message, params);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Currencies.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Currencies {
private List<Currency> currencies;
public List<Currency> getCurrencies() {
return currencies;
}
@Override
public String toString() {
return String.format("{\"currencies\":%s}", currencies);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Conversions.java<|end_filename|>
package com.currencycloud.client.model;
import java.util.List;
public class Conversions extends PaginatedData {
private List<Conversion> conversions;
public List<Conversion> getConversions() {
return conversions;
}
@Override
public String toString() {
return String.format("{\"conversions\":%s, \"pagination\":%s}", conversions, pagination);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Currency.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Currency {
private String code;
private Integer decimalPlaces;
private String name;
private Boolean onlineTrading;
private Boolean canBuy;
private Boolean canSell;
public String getCode() {
return code;
}
public Integer getDecimalPlaces() {
return decimalPlaces;
}
public String getName() {
return name;
}
public Boolean getOnlineTrading() {
return onlineTrading;
}
public Boolean getCanBuy() {
return canBuy;
}
public Boolean getCanSell() {
return canSell;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("code", code);
map.put("decimalPlaces", decimalPlaces);
map.put("name", name);
map.put("onlineTrading", onlineTrading);
map.put("canBuy", canBuy);
map.put("canSell", canSell);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentReport.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentReport implements Entity {
private String id;
private String shortReference;
private String description;
private SearchParams searchParams;
private String reportType;
private String status;
private String failureReason;
private Date expirationDate;
private String reportUrl;
private String accountId;
private String contactId;
private Date createdAt;
private Date updatedAt;
private String currency;
private BigDecimal amountFrom;
private BigDecimal amountTo;
private Date paymentDateFrom;
private Date paymentDateTo;
private Date transferredAtFrom;
private Date transferredAtTo;
private Date createdAtFrom;
private Date createdAtTo;
private Date updatedAtFrom;
private Date updatedAtTo;
private String beneficiaryId;
private String conversionId;
private Boolean withDeleted;
private String paymentGroupId;
private String uniqueRequestId;
private String scope;
protected PaymentReport() {}
public static PaymentReport create() { return new PaymentReport(); }
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getShortReference() {
return shortReference;
}
public void setShortReference(String shortReference) {
this.shortReference = shortReference;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public SearchParams getSearchParams() {
return searchParams;
}
public void setSearchParams(SearchParams searchParams) {
this.searchParams = searchParams;
}
public String getReportType() {
return reportType;
}
public void setReportType(String reportType) {
this.reportType = reportType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getFailureReason() {
return failureReason;
}
public void setFailureReason(String failureReason) {
this.failureReason = failureReason;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public String getReportUrl() {
return reportUrl;
}
public void setReportUrl(String reportUrl) {
this.reportUrl = reportUrl;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getContactId() {
return contactId;
}
public void setContactId(String contactId) {
this.contactId = contactId;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public BigDecimal getAmountFrom() {
return amountFrom;
}
public void setAmountFrom(BigDecimal amountFrom) {
this.amountFrom = amountFrom;
}
public BigDecimal getAmountTo() {
return amountTo;
}
public void setAmountTo(BigDecimal amountTo) {
this.amountTo = amountTo;
}
public Date getPaymentDateFrom() {
return paymentDateFrom;
}
public void setPaymentDateFrom(Date paymentDateFrom) {
this.paymentDateFrom = paymentDateFrom;
}
public Date getPaymentDateTo() {
return paymentDateTo;
}
public void setPaymentDateTo(Date paymentDateTo) {
this.paymentDateTo = paymentDateTo;
}
public Date getTransferredAtFrom() {
return transferredAtFrom;
}
public void setTransferredAtFrom(Date transferredAtFrom) {
this.transferredAtFrom = transferredAtFrom;
}
public Date getTransferredAtTo() {
return transferredAtTo;
}
public void setTransferredAtTo(Date transferredAtTo) {
this.transferredAtTo = transferredAtTo;
}
public Date getCreatedAtFrom() {
return createdAtFrom;
}
public void setCreatedAtFrom(Date createdAtFrom) {
this.createdAtFrom = createdAtFrom;
}
public Date getCreatedAtTo() {
return createdAtTo;
}
public void setCreatedAtTo(Date createdAtTo) {
this.createdAtTo = createdAtTo;
}
public Date getUpdatedAtFrom() {
return updatedAtFrom;
}
public void setUpdatedAtFrom(Date updatedAtFrom) {
this.updatedAtFrom = updatedAtFrom;
}
public Date getUpdatedAtTo() {
return updatedAtTo;
}
public void setUpdatedAtTo(Date updatedAtTo) {
this.updatedAtTo = updatedAtTo;
}
public String getBeneficiaryId() {
return beneficiaryId;
}
public void setBeneficiaryId(String beneficiaryId) {
this.beneficiaryId = beneficiaryId;
}
public String getConversionId() {
return conversionId;
}
public void setConversionId(String conversionId) {
this.conversionId = conversionId;
}
public Boolean getWithDeleted() {
return withDeleted;
}
public void setWithDeleted(Boolean withDeleted) {
this.withDeleted = withDeleted;
}
public String getPaymentGroupId() {
return paymentGroupId;
}
public void setPaymentGroupId(String paymentGroupId) {
this.paymentGroupId = paymentGroupId;
}
public String getUniqueRequestId() {
return uniqueRequestId;
}
public void setUniqueRequestId(String uniqueRequestId) {
this.uniqueRequestId = uniqueRequestId;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("shortReference", shortReference);
map.put("description", description);
map.put("searchParams", searchParams);
map.put("reportType", reportType);
map.put("status", status);
map.put("failureReason", failureReason);
map.put("expirationDate", expirationDate);
map.put("reportUrl", reportUrl);
map.put("accountId", accountId);
map.put("contactId", contactId);
map.put("createdAt", createdAt);
map.put("updatedAt", updatedAt);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
/* ToDo: Not the most efficient way to handle SearchParams. To be improved in a future release */
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class SearchParams {
public SearchParams() { }
private String description;
private String currency;
private BigDecimal amountFrom;
private BigDecimal amountTo;
private String status;
private Date paymentDateFrom;
private Date paymentDateTo;
private Date transferredAtFrom;
private Date transferredAtTo;
private Date createdAtFrom;
private Date createdAtTo;
private Date updatedAtFrom;
private Date updatedAtTo;
private String beneficiaryId;
private String conversionId;
private Boolean withDeleted;
private String paymentGroupId;
private String uniqueRequestId;
private String scope;
public String getDescription() {
return description;
}
public String getCurrency() {
return currency;
}
public BigDecimal getAmountFrom() {
return amountFrom;
}
public BigDecimal getAmountTo() {
return amountTo;
}
public String getStatus() {
return status;
}
public Date getPaymentDateFrom() {
return paymentDateFrom;
}
public Date getPaymentDateTo() {
return paymentDateTo;
}
public Date getTransferredAtFrom() {
return transferredAtFrom;
}
public Date getTransferredAtTo() {
return transferredAtTo;
}
public Date getCreatedAtFrom() {
return createdAtFrom;
}
public Date getCreatedAtTo() {
return createdAtTo;
}
public Date getUpdatedAtFrom() {
return updatedAtFrom;
}
public Date getUpdatedAtTo() {
return updatedAtTo;
}
public String getBeneficiaryId() {
return beneficiaryId;
}
public String getConversionId() {
return conversionId;
}
public Boolean getWithDeleted() {
return withDeleted;
}
public String getPaymentGroupId() {
return paymentGroupId;
}
public String getUniqueRequestId() {
return uniqueRequestId;
}
public String getScope() {
return scope;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("description", description);
map.put("currency", currency);
map.put("amountFrom", amountFrom);
map.put("amountTo", amountTo);
map.put("status", status);
map.put("paymentDateFrom", paymentDateFrom);
map.put("paymentDateTo", paymentDateTo);
map.put("transferredAtFrom", transferredAtFrom);
map.put("transferredAtTo", transferredAtTo);
map.put("createdAtFrom", createdAtFrom);
map.put("createdAtTo", createdAtTo);
map.put("updatedAtFrom", updatedAtFrom);
map.put("updatedAtTo", updatedAtTo);
map.put("beneficiaryId", beneficiaryId);
map.put("conversionId", conversionId);
map.put("withDeleted", withDeleted);
map.put("paymentGroupId", paymentGroupId);
map.put("uniqueRequestId", uniqueRequestId);
map.put("scope", scope);
map.values().removeIf(Objects::isNull);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/WithdrawalAccount.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class WithdrawalAccount implements Entity {
private String id;
private String accountName;
private String accountHolderName;
private Date accountHolderDob;
private String routingCode;
private String accountNumber;
private String currency;
private String accountId;
protected WithdrawalAccount() { }
public static WithdrawalAccount create() {
return new WithdrawalAccount();
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getAccountHolderName() {
return accountHolderName;
}
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
public Date getAccountHolderDOB() {
return accountHolderDob;
}
public void setAccountHolderDOB(Date accountHolderDob) {
this.accountHolderDob = accountHolderDob;
}
public String getRoutingCode() {
return routingCode;
}
public void setRoutingCode(String routingCode) {
this.routingCode = routingCode;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber (String accountNumber) {
this.accountNumber = accountNumber;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("accountName", accountName);
map.put("accountHolderName", accountHolderName);
map.put("accountHolderDob", accountHolderDob);
map.put("routingCode", routingCode);
map.put("accountNumber", accountNumber);
map.put("currency", currency);
map.put("accountId", accountId);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Entity.java<|end_filename|>
package com.currencycloud.client.model;
public interface Entity {
String getId();
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Beneficiary.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.currencycloud.client.dirty.DirtyWatcherDeserializer;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonDeserialize(converter = DirtyWatcherDeserializer.Beneficiary.class)
public class Beneficiary implements Entity {
private String id;
private String bankAccountHolderName;
private String name;
private String email;
private Boolean defaultBeneficiary;
private String creatorContactId;
private Date createdAt;
private Date updatedAt;
private List<String> paymentTypes;
private String bankCountry;
private String bankName;
private String currency;
private String accountNumber;
private String bankAccountType;
private List<String> beneficiaryAddress;
private String beneficiaryCountry;
private String beneficiaryEntityType;
private String beneficiaryCompanyName;
private String beneficiaryFirstName;
private String beneficiaryLastName;
private String beneficiaryCity;
private String beneficiaryPostcode;
private String beneficiaryStateOrProvince;
private Date beneficiaryDateOfBirth;
private String beneficiaryIdentificationType;
private String beneficiaryIdentificationValue;
private String beneficiaryExternalReference;
@JsonProperty("routing_code_type_1")
private String routingCodeType1;
@JsonProperty("routing_code_value_1")
private String routingCodeValue1;
@JsonProperty("routing_code_type_2")
private String routingCodeType2;
@JsonProperty("routing_code_value_2")
private String routingCodeValue2;
private String bicSwift;
private String iban;
private List<String> bankAddress;
private String scope;
protected Beneficiary() { }
private Beneficiary(String id) {
this.id = id;
}
private Beneficiary(String bankCountry, String currency, String beneficiaryCountry) {
this.bankCountry = bankCountry;
this.currency = currency;
this.beneficiaryCountry = beneficiaryCountry;
}
private Beneficiary(String bankAccountHolderName, String bankCountry, String currency, String name) {
this.bankAccountHolderName = bankAccountHolderName;
this.bankCountry = bankCountry;
this.currency = currency;
this.name = name;
}
public static Beneficiary create() {
return new Beneficiary();
}
/**
* Creates a Beneficiary with all the required properties for the create beneficiary method. Note that this
* is just a simple helper factory method and can be used for any other purpose.
*/
public static Beneficiary create(String bankAccountHolderName, String bankCountry, String currency, String name) {
return new Beneficiary(bankAccountHolderName, bankCountry, currency, name);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBankAccountHolderName() {
return bankAccountHolderName;
}
public void setBankAccountHolderName(String bankAccountHolderName) {
this.bankAccountHolderName = bankAccountHolderName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getDefaultBeneficiary() {
return defaultBeneficiary;
}
public void setDefaultBeneficiary(Boolean defaultBeneficiary) {
this.defaultBeneficiary = defaultBeneficiary;
}
public String getCreatorContactId() {
return creatorContactId;
}
public void setCreatorContactId(String creatorContactId) {
this.creatorContactId = creatorContactId;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public List<String> getPaymentTypes() {
return paymentTypes;
}
public void setPaymentTypes(List<String> paymentTypes) {
this.paymentTypes = paymentTypes;
}
public String getBankCountry() {
return bankCountry;
}
public void setBankCountry(String bankCountry) {
this.bankCountry = bankCountry;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getBankAccountType() {
return bankAccountType;
}
public void setBankAccountType(String bankAccountType) {
this.bankAccountType = bankAccountType;
}
public List<String> getBeneficiaryAddress() {
return beneficiaryAddress;
}
public void setBeneficiaryAddress(List<String> beneficiaryAddress) {
this.beneficiaryAddress = beneficiaryAddress;
}
public String getBeneficiaryCountry() {
return beneficiaryCountry;
}
public void setBeneficiaryCountry(String beneficiaryCountry) {
this.beneficiaryCountry = beneficiaryCountry;
}
public String getBeneficiaryEntityType() {
return beneficiaryEntityType;
}
public void setBeneficiaryEntityType(String beneficiaryEntityType) {
this.beneficiaryEntityType = beneficiaryEntityType;
}
public String getBeneficiaryCompanyName() {
return beneficiaryCompanyName;
}
public void setBeneficiaryCompanyName(String beneficiaryCompanyName) {
this.beneficiaryCompanyName = beneficiaryCompanyName;
}
public String getBeneficiaryFirstName() {
return beneficiaryFirstName;
}
public void setBeneficiaryFirstName(String beneficiaryFirstName) {
this.beneficiaryFirstName = beneficiaryFirstName;
}
public String getBeneficiaryLastName() {
return beneficiaryLastName;
}
public void setBeneficiaryLastName(String beneficiaryLastName) {
this.beneficiaryLastName = beneficiaryLastName;
}
public String getBeneficiaryCity() {
return beneficiaryCity;
}
public void setBeneficiaryCity(String beneficiaryCity) {
this.beneficiaryCity = beneficiaryCity;
}
public String getBeneficiaryPostcode() {
return beneficiaryPostcode;
}
public void setBeneficiaryPostcode(String beneficiaryPostcode) {
this.beneficiaryPostcode = beneficiaryPostcode;
}
public String getBeneficiaryStateOrProvince() {
return beneficiaryStateOrProvince;
}
public void setBeneficiaryStateOrProvince(String beneficiaryStateOrProvince) {
this.beneficiaryStateOrProvince = beneficiaryStateOrProvince;
}
public Date getBeneficiaryDateOfBirth() {
return beneficiaryDateOfBirth;
}
public void setBeneficiaryDateOfBirth(Date beneficiaryDateOfBirth) {
this.beneficiaryDateOfBirth = beneficiaryDateOfBirth;
}
public String getBeneficiaryIdentificationType() {
return beneficiaryIdentificationType;
}
public void setBeneficiaryIdentificationType(String beneficiaryIdentificationType) {
this.beneficiaryIdentificationType = beneficiaryIdentificationType;
}
public String getBeneficiaryIdentificationValue() {
return beneficiaryIdentificationValue;
}
public void setBeneficiaryIdentificationValue(String beneficiaryIdentificationValue) {
this.beneficiaryIdentificationValue = beneficiaryIdentificationValue;
}
public String getRoutingCodeType1() {
return routingCodeType1;
}
public void setRoutingCodeType1(String routingCodeType1) {
this.routingCodeType1 = routingCodeType1;
}
public String getRoutingCodeValue1() {
return routingCodeValue1;
}
public void setRoutingCodeValue1(String routingCodeValue1) {
this.routingCodeValue1 = routingCodeValue1;
}
public String getRoutingCodeType2() {
return routingCodeType2;
}
public void setRoutingCodeType2(String routingCodeType2) {
this.routingCodeType2 = routingCodeType2;
}
public String getRoutingCodeValue2() {
return routingCodeValue2;
}
public void setRoutingCodeValue2(String routingCodeValue2) {
this.routingCodeValue2 = routingCodeValue2;
}
public String getBicSwift() {
return bicSwift;
}
public void setBicSwift(String bicSwift) {
this.bicSwift = bicSwift;
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public List<String> getBankAddress() {
return bankAddress;
}
public void setBankAddress(List<String> bankAddress) {
this.bankAddress = bankAddress;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getBeneficiaryExternalReference() {
return beneficiaryExternalReference;
}
public void setBeneficiaryExternalReference(String beneficiaryExternalReference) {
this.beneficiaryExternalReference = beneficiaryExternalReference;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("bankAccountHolderName", bankAccountHolderName);
map.put("name", name);
map.put("email", email);
map.put("defaultBeneficiary", defaultBeneficiary);
map.put("creatorContactId", creatorContactId);
map.put("createdAt", createdAt);
map.put("updatedAt", updatedAt);
map.put("paymentTypes", paymentTypes);
map.put("bankCountry", bankCountry);
map.put("bankName", bankName);
map.put("currency", currency);
map.put("accountNumber", accountNumber);
map.put("routingCodeType1", routingCodeType1);
map.put("bankAccountType", bankAccountType);
map.put("beneficiaryAddress", beneficiaryAddress);
map.put("beneficiaryCountry", beneficiaryCountry);
map.put("beneficiaryEntityType", beneficiaryEntityType);
map.put("beneficiaryCompanyName", beneficiaryCompanyName);
map.put("beneficiaryFirstName", beneficiaryFirstName);
map.put("beneficiaryLastName", beneficiaryLastName);
map.put("beneficiaryCity", beneficiaryCity);
map.put("beneficiaryPostcode", beneficiaryPostcode);
map.put("beneficiaryStateOrProvince", beneficiaryStateOrProvince);
map.put("beneficiaryDateOfBirth", beneficiaryDateOfBirth);
map.put("beneficiaryIdentificationType", beneficiaryIdentificationType);
map.put("beneficiaryIdentificationValue", beneficiaryIdentificationValue);
map.put("routingCodeValue1", routingCodeValue1);
map.put("routingCodeType2", routingCodeType2);
map.put("routingCodeValue2", routingCodeValue2);
map.put("bicSwift", bicSwift);
map.put("iban", iban);
map.put("bankAddress", bankAddress);
map.put("beneficiaryExternalReference", beneficiaryExternalReference);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/test/java/com/currencycloud/client/BetamaxTestSupport.java<|end_filename|>
package com.currencycloud.client;
import co.freeside.betamax.Recorder;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class BetamaxTestSupport extends JsonTestSupport {
public static final Logger log = LoggerFactory.getLogger(CurrencyCloudClient.class);
@Rule
public final TestName name = new TestName();
@Rule
public Recorder createRecorder() {
Recorder recorder = new Recorder();
String tc = this.getClass().getSimpleName();
recorder.setTapeRoot(new File(recorder.getTapeRoot(), (tc).substring(0, tc.length() - "Test".length())));
return recorder;
}
protected CurrencyCloudClient prepareTestClient(String loginId, String apiKey, String authToken) {
CurrencyCloudClient client = new CurrencyCloudClient("http://localhost:5555", loginId, apiKey);
client.setAuthToken(authToken);
return client;
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ConversionSplit.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ConversionSplit implements Entity {
private String id;
private BigDecimal amount;
private ConversionSplitDetails parentConversion;
private ConversionSplitDetails childConversion;
protected ConversionSplit() {
}
private ConversionSplit(String id, BigDecimal amount) {
this.id = id;
this.amount = amount;
}
public static ConversionSplit create() {
return new ConversionSplit();
}
public static ConversionSplit create(String id, BigDecimal amount) {
return new ConversionSplit(id, amount);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public ConversionSplitDetails getParentConversion() {
return parentConversion;
}
public void setParentConversion(ConversionSplitDetails parentConversion) {
this.parentConversion = parentConversion;
}
public ConversionSplitDetails getChildConversion() {
return childConversion;
}
public void setChildConversion(ConversionSplitDetails childConversion) {
this.childConversion = childConversion;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("parentConversion", parentConversion);
map.put("childConversion", childConversion);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/test/java/com/currencycloud/client/AuthenticationTest.java<|end_filename|>
package com.currencycloud.client;
import co.freeside.betamax.Betamax;
import co.freeside.betamax.MatchRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.junit.MatcherAssert.assertThat;
public class AuthenticationTest extends BetamaxTestSupport {
@Before
@After
public void methodName() { log.debug("------------------------- " + name.getMethodName() + " -------------------------"); }
@Test
@Betamax(tape = "happens_lazily", match = {MatchRule.method, MatchRule.uri, MatchRule.body, MatchRule.headers})
public void testHappensLazily() throws Exception {
CurrencyCloudClient client = prepareTestClient("<EMAIL>", "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", null);
assertThat(client.findBeneficiaries(null, null), notNullValue());
assertThat(client.getAuthToken(), equalTo("<PASSWORD>"));
}
@Test
@Betamax(tape = "can_use_just_a_token", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanUseJustAToken() throws Exception {
CurrencyCloudClient client = prepareTestClient(null, null, "<PASSWORD>");
assertThat(client.findBeneficiaries(null, null), notNullValue());
}
@Test
@Betamax(tape = "can_be_closed", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanBeClosed() throws Exception {
CurrencyCloudClient client = prepareTestClient(
"<EMAIL>",
"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
null
);
client.authenticate();
client.endSession();
}
@Test
@Betamax(tape = "handles_session_timeout_error", match = {MatchRule.method, MatchRule.uri, MatchRule.body, MatchRule.headers})
public void testHandlesSessionTimeoutError() throws Exception {
CurrencyCloudClient client = prepareTestClient(
"<EMAIL>",
"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
"3068d3ff160ab0636648d98b4e4e10ad"
);
client.findBeneficiaries(null, null);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/DetailedRate.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DetailedRate {
private Date settlementCutOffTime;
private List<String> currencyPair;
private String clientBuyCurrency;
private String clientSellCurrency;
private BigDecimal clientBuyAmount;
private BigDecimal clientSellAmount;
private String fixedSide;
private BigDecimal midMarketRate;
private BigDecimal coreRate;
private BigDecimal partnerRate;
private BigDecimal clientRate;
private Boolean depositRequired;
private BigDecimal depositAmount;
private String depositCurrency;
private Date conversionDate;
protected DetailedRate() { }
public static DetailedRate create() {
return new DetailedRate();
}
public Date getSettlementCutOffTime() {
return settlementCutOffTime;
}
public List<String> getCurrencyPair() {
return currencyPair;
}
public void setCurrencyPair(List<String> currencyPair) {
this.currencyPair = currencyPair;
}
public String getClientBuyCurrency() {
return clientBuyCurrency;
}
public void setClientBuyCurrency(String clientBuyCurrency) {
this.clientBuyCurrency = clientBuyCurrency;
}
public String getClientSellCurrency() {
return clientSellCurrency;
}
public void setClientSellCurrency(String clientSellCurrency) {
this.clientSellCurrency = clientSellCurrency;
}
public BigDecimal getClientBuyAmount() {
return clientBuyAmount;
}
public void setClientBuyAmount(BigDecimal clientBuyAmount) {
this.clientBuyAmount = clientBuyAmount;
}
public BigDecimal getClientSellAmount() {
return clientSellAmount;
}
public void setClientSellAmount(BigDecimal clientSellAmount) {
this.clientSellAmount = clientSellAmount;
}
public String getFixedSide() {
return fixedSide;
}
public void setFixedSide(String fixedSide) {
this.fixedSide = fixedSide;
}
public BigDecimal getMidMarketRate() {
return midMarketRate;
}
public BigDecimal getCoreRate() {
return coreRate;
}
public BigDecimal getPartnerRate() {
return partnerRate;
}
public BigDecimal getClientRate() {
return clientRate;
}
public Boolean getDepositRequired() {
return depositRequired;
}
public BigDecimal getDepositAmount() {
return depositAmount;
}
public String getDepositCurrency() {
return depositCurrency;
}
public void setConversionDate(Date conversionDate) {
this.conversionDate = conversionDate;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("settlementCutOffTime", settlementCutOffTime);
map.put("currencyPair", currencyPair);
map.put("clientBuyCurrency", clientBuyCurrency);
map.put("clientSellCurrency", clientSellCurrency);
map.put("clientBuyAmount", clientBuyAmount);
map.put("clientSellAmount", clientSellAmount);
map.put("fixedSide", fixedSide);
map.put("midMarketRate", midMarketRate);
map.put("coreRate", coreRate);
map.put("partnerRate", partnerRate);
map.put("clientRate", clientRate);
map.put("depositRequired", depositRequired);
map.put("depositAmount", depositAmount);
map.put("depositCurrency", depositCurrency);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Payments.java<|end_filename|>
package com.currencycloud.client.model;
import java.util.List;
public class Payments extends PaginatedData {
private List<Payment> payments;
public List<Payment> getPayments() {
return payments;
}
@Override
public String toString() {
return String.format("{\"payments\":%s, \"pagination\":%s}", payments, pagination);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/BankDetails.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BankDetails {
private String identifierType;
private String identifierValue;
private String accountNumber;
private String bicSwift;
private String bankName;
private String bankBranch;
private String bankAddress;
private String bankCity;
private String bankState;
private String bankPostCode;
private String bankCountry;
@JsonProperty("bank_country_ISO")
private String bankCountryISO;
private String currency;
public String getIdentifierValue() {
return identifierValue;
}
public String getIdentifierType() {
return identifierType;
}
public String getAccountNumber() {
return accountNumber;
}
public String getBicSwift() {
return bicSwift;
}
public String getBankName() {
return bankName;
}
public String getBankBranch() {
return bankBranch;
}
public String getBankAddress() {
return bankAddress;
}
public String getBankCity() {
return bankCity;
}
public String getBankState() {
return bankState;
}
public String getBankPostCode() {
return bankPostCode;
}
public String getBankCountry() {
return bankCountry;
}
public String getBankCountryISO() {
return bankCountryISO;
}
public String getCurrency() {
return currency;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("identifierValue", identifierValue);
map.put("identifierType", identifierType);
map.put("accountNumber", accountNumber);
map.put("bicSwift", bicSwift);
map.put("bankName", bankName);
map.put("bankBranch", bankBranch);
map.put("bankAddress", bankAddress);
map.put("bankCity", bankCity);
map.put("bankState", bankState);
map.put("bankPostCode", bankPostCode);
map.put("bankCountry", bankCountry);
map.put("bankCountryISO", bankCountryISO);
map.put("currency", currency);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/test/java/com/currencycloud/client/JsonTestSupport.java<|end_filename|>
package com.currencycloud.client;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class JsonTestSupport {
private final SimpleDateFormat timeFormat;
private final SimpleDateFormat dateFormat;
public JsonTestSupport() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
timeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
protected Date parseDateTime(String str) {
try {
return timeFormat.parse(str);
} catch (ParseException e) {
throw new RuntimeException("Cannot parse time: " + str);
}
}
protected Date parseDate(String str) {
try {
return dateFormat.parse(str);
} catch (ParseException e) {
throw new RuntimeException("Cannot parse date: " + str);
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Rates.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Rates {
@JsonProperty
private Map<String, List<BigDecimal>> rates;
@JsonProperty
private List<String> unavailable;
public Rate getRate(String currencyPair) {
return Rate.create(rates.get(currencyPair));
}
public List<String> getUnavailable() {
return unavailable;
}
public Collection<String> getCurrencyPairs() {
return rates.keySet();
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("rates", rates);
map.put("unavailable", unavailable);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/test/java/com/currencycloud/client/CurrencyCloudClientSessionTest.java<|end_filename|>
package com.currencycloud.client;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
public class CurrencyCloudClientSessionTest {
@Test
public void testRaisesAnErrorIfTheEnvironmentIsNotSet() throws Exception {
try {
CurrencyCloudClient client = new CurrencyCloudClient((CurrencyCloudClient.Environment) null, null, null);
client.authenticate();
throw new AssertionError("Should have failed.");
} catch (NullPointerException ignored) { }
}
@Test
public void testRaisesAnErrorIfTheLoginIdIsNotSet() throws Exception {
CurrencyCloudClient client = new CurrencyCloudClient(CurrencyCloudClient.Environment.demo, null, null);
try {
client.authenticate();
throw new AssertionError("Should have failed.");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("apiKey must be set"));
}
}
@Test
public void testRaisesAnErrorIfTheApiKeyIsNotSet() throws Exception {
CurrencyCloudClient client = new CurrencyCloudClient(CurrencyCloudClient.Environment.demo, "<EMAIL>", null);
try {
client.authenticate();
throw new AssertionError("Should have failed.");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("apiKey"));
assertThat(e.getMessage(), containsString("must be set"));
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Contact.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.currencycloud.client.dirty.DirtyWatcherDeserializer;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import javax.annotation.Nullable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonDeserialize(converter = DirtyWatcherDeserializer.Contact.class)
public class Contact implements Entity {
private String loginId;
private String id;
private String yourReference;
private String firstName;
private String lastName;
private String accountId;
private String accountName;
private String status;
private String phoneNumber;
private String mobilePhoneNumber;
private String locale;
private String timezone;
private String emailAddress;
private Date dateOfBirth;
private Date createdAt;
private Date updatedAt;
protected Contact() { }
private Contact(
String accountId,
String firstName,
String lastName,
String emailAddress,
String phoneNumber,
@Nullable String yourReference,
@Nullable String mobilePhoneNumber,
@Nullable String loginId,
@Nullable String status,
@Nullable String locale,
@Nullable String timezone,
@Nullable Date dateOfBirth
) {
this.accountId = accountId;
this.firstName = firstName;
this.lastName = lastName;
this.emailAddress = emailAddress;
this.phoneNumber = phoneNumber;
this.yourReference = yourReference;
this.mobilePhoneNumber = mobilePhoneNumber;
this.loginId = loginId;
this.status = status;
this.locale = locale;
this.timezone = timezone;
this.dateOfBirth = dateOfBirth;
}
public static Contact create() {
return new Contact();
}
/**
* Creates a contact as expected by the
* {@link com.currencycloud.client.CurrencyCloudClient#createContact(Contact)} method.
*/
public static Contact create(
String accountId,
String firstName,
String lastName,
String emailAddress,
String phoneNumber,
@Nullable String yourReference,
@Nullable String mobilePhoneNumber,
@Nullable String loginId,
@Nullable String status,
@Nullable String locale,
@Nullable String timezone,
@Nullable Date dateOfBirth
) {
return new Contact(
accountId,
firstName,
lastName,
emailAddress,
phoneNumber,
yourReference,
mobilePhoneNumber,
loginId,
status,
locale,
timezone,
dateOfBirth
);
}
/**
* Creates a contact as expected by the
* {@link com.currencycloud.client.CurrencyCloudClient#createContact(Contact)} method,
* using only required parameters.
*/
public static Contact create(
String accountId,
String firstName,
String lastName,
String emailAddress,
String phoneNumber
) {
return new Contact(
accountId, firstName, lastName, emailAddress, phoneNumber, null, null, null, null, null, null, null
);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLoginId() {
return loginId;
}
public void setLoginId(String loginId) {
this.loginId = loginId;
}
public String getYourReference() {
return yourReference;
}
public void setYourReference(String yourReference) {
this.yourReference = yourReference;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("loginId", loginId);
map.put("id", id);
map.put("yourReference", yourReference);
map.put("firstName", firstName);
map.put("lastName", lastName);
map.put("accountId", accountId);
map.put("accountName", accountName);
map.put("status", status);
map.put("phoneNumber", phoneNumber);
map.put("mobilePhoneNumber", mobilePhoneNumber);
map.put("locale", locale);
map.put("timezone", timezone);
map.put("emailAddress", emailAddress);
map.put("dateOfBirth", dateOfBirth);
map.put("createdAt", createdAt);
map.put("updatedAt", updatedAt);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/SettlementAccount.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SettlementAccount {
private String bankAccountHolderName;
private List<String> beneficiaryAddress = new ArrayList<String>();
private String beneficiaryCountry;
private String bankName;
private List<String> bankAddress = new ArrayList<String>();
private String bankCountry;
private String currency;
private String bicSwift;
private String iban;
private String accountNumber;
@JsonProperty("routing_code_type_1")
private String routingCodeType1;
@JsonProperty("routing_code_value_1")
private String routingCodeValue1;
@JsonProperty("routing_code_type_2")
private String routingCodeType2;
@JsonProperty("routing_code_value_2")
private String routingCodeValue2;
public String getBankAccountHolderName() {
return bankAccountHolderName;
}
public List<String> getBeneficiaryAddress() {
return beneficiaryAddress;
}
public String getBeneficiaryCountry() {
return beneficiaryCountry;
}
public String getBankName() {
return bankName;
}
public List<String> getBankAddress() {
return bankAddress;
}
public String getBankCountry() {
return bankCountry;
}
public String getCurrency() {
return currency;
}
public String getBicSwift() {
return bicSwift;
}
public String getIban() {
return iban;
}
public String getAccountNumber() {
return accountNumber;
}
public String getRoutingCodeType1() {
return routingCodeType1;
}
public String getRoutingCodeValue1() {
return routingCodeValue1;
}
public String getRoutingCodeType2() {
return routingCodeType2;
}
public String getRoutingCodeValue2() {
return routingCodeValue2;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("bankAccountHolderName", bankAccountHolderName);
map.put("beneficiaryAddress", beneficiaryAddress);
map.put("beneficiaryCountry", beneficiaryCountry);
map.put("bankName", bankName);
map.put("bankAddress", bankAddress);
map.put("bankCountry", bankCountry);
map.put("currency", currency);
map.put("bicSwift", bicSwift);
map.put("iban", iban);
map.put("accountNumber", accountNumber);
map.put("routingCodeType1", routingCodeType1);
map.put("routingCodeValue1", routingCodeValue1);
map.put("routingCodeType2", routingCodeType2);
map.put("routingCodeValue2", routingCodeValue2);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/test/java/com/currencycloud/client/ErrorTest.java<|end_filename|>
package com.currencycloud.client;
import co.freeside.betamax.Betamax;
import co.freeside.betamax.MatchRule;
import com.currencycloud.client.exception.*;
import com.currencycloud.client.model.ErrorMessage;
import org.eclipse.jetty.io.WriterOutputStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "UnnecessaryBoxing"})
public class ErrorTest extends BetamaxTestSupport {
private String loginId = "<EMAIL>";
private String apiKey = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
@Before
@After
public void methodName() { log.debug("------------------------- " + name.getMethodName() + " -------------------------"); }
@Test
@Betamax(tape = "contains_full_details_for_api_error", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testContainsFullDetailsForApiError() throws Exception {
loginId = "non-existent-login-id";
apiKey = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
BadRequestException error = testFailedLogin("auth_invalid_user_login_details", 400, BadRequestException.class);
ErrorMessage errorMessage = error.getErrors().get(0);
assertThat(errorMessage.getField(), equalTo("api_key"));
assertThat(errorMessage.getCode(), equalTo("api_key_length_is_invalid"));
assertThat(errorMessage.getMessage(), equalTo("api_key should be 64 character(s) long"));
assertThat(errorMessage.getParams().get("length"), instanceOf(Integer.class));
assertThat((Integer) errorMessage.getParams().get("length"), equalTo(Integer.valueOf(64)));
String expectedErrorPattern = interpolate(
readFile("/errors/contains_full_details_for_api_error.yaml"),
buildMap("error.platform", CurrencyCloudException.PLATFORM)
);
assertThat(error.toString().replaceAll("\r\n|\r|\n", " "), equalTo(expectedErrorPattern.replaceAll("\r\n|\r|\n", " ")));
}
@Test
@Betamax(tape = "is_raised_on_a_bad_request", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testIsRaisedOnABadRequest() throws Exception {
loginId = "non-existent-login-id";
apiKey = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
BadRequestException error = testFailedLogin("auth_invalid_user_login_details", 400, BadRequestException.class);
ErrorMessage errorMessage = error.getErrors().get(0);
assertThat(errorMessage.getField(), equalTo("api_key"));
assertThat(errorMessage.getCode(), equalTo("api_key_length_is_invalid"));
assertThat(errorMessage.getMessage(), equalTo("api_key should be 64 character(s) long"));
assertThat(errorMessage.getParams().get("length"), instanceOf(Integer.class));
assertThat((Integer)errorMessage.getParams().get("length"), equalTo(Integer.valueOf(64)));
}
@Test
@Betamax(tape = "is_raised_on_incorrect_authentication_details", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testIsRaisedOnIncorrectAuthenticationDetails() throws Exception {
loginId = "non-existent-login-id";
apiKey = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
AuthenticationException error = testFailedLogin("auth_failed", 401, AuthenticationException.class);
assertThat(error.getErrors().size(), equalTo(1));
assertThat(error.getErrors().get(0).getField(), equalTo("username"));
assertThat(error.getErrors().get(0).getCode(), equalTo("invalid_supplied_credentials"));
assertThat(error.getErrors().get(0).getMessage(), equalTo("Authentication failed with the supplied credentials"));
assertThat(error.getErrors().get(0).getParams(), anEmptyMap());
}
@Test
public void testIsRaisedOnUnexpectedError() throws Exception {
// No Betamax here. The call will fail with java.net.ConnectException
// because there is (hopefully) no server at localhost:5555.
CurrencyCloudClient client = prepareTestClient(loginId, apiKey, null);
try {
client.authenticate();
throw new AssertionError("Should have failed");
} catch (UnexpectedException error) {
String expectedErrorPattern = interpolate(
readFile("/errors/is_raised_on_unexpected_error.yaml"),
buildMap("error.platform", CurrencyCloudException.PLATFORM)
);
assertThat(error.toString().replaceAll("\r\n|\r|\n", " ").substring(0, 320), equalTo(expectedErrorPattern.replaceAll("\r\n|\r|\n", " ").substring(0, 320)));
}
}
@Test
@Betamax(tape = "is_raised_on_a_forbidden_request", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testIsRaisedOnAForbiddenRequest() throws Exception {
ForbiddenException error = testFailedLogin("auth_failed", 403, ForbiddenException.class);
assertThat(error.getErrorCode(), equalTo("auth_failed"));
assertThat(error.getResponse().statusCode, equalTo(403));
ErrorMessage errorMessage = error.getErrors().get(0);
assertThat(errorMessage.getField(), equalTo("username"));
assertThat(errorMessage.getCode(), equalTo("invalid_supplied_credentials"));
assertThat(errorMessage.getMessage(), equalTo("Authentication failed with the supplied credentials"));
assertThat(errorMessage.getParams(), is(anEmptyMap()));
}
@Test
@Betamax(tape = "is_raised_when_a_resource_is_not_found", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testIsRaisedWhenAResourceIsNotFound() throws Exception {
CurrencyCloudClient client = prepareTestClient(loginId, apiKey, "656485646b068f6e9c81e3d885fa54f5");
try {
client.retrieveBeneficiary("081596c9-02de-483e-9f2a-4cf55dcdf98c");
assertThat("Should fail.", false);
} catch (NotFoundException error) {
assertThat(error.getErrorCode(), equalTo("beneficiary_not_found"));
assertThat(error.getResponse().statusCode, equalTo(404));
assertThat(error.getErrors().size(), equalTo(1));
ErrorMessage errorMessage = error.getErrors().get(0);
assertThat(errorMessage.getField(), equalTo("id"));
assertThat(errorMessage.getCode(), equalTo("beneficiary_not_found"));
assertThat(errorMessage.getMessage(), equalTo("Beneficiary was not found for this id"));
assertThat(errorMessage.getParams(), is(anEmptyMap()));
}
}
@Test
@Betamax(tape = "is_raised_on_an_internal_server_error", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testIsRaisedOnAnInternalServerError() throws Exception {
InternalApplicationException error = testFailedLogin("internal_application_error", 500, InternalApplicationException.class);
ErrorMessage errorMessage = error.getErrors().get(0);
assertThat(errorMessage.getField(), equalTo("base"));
assertThat(errorMessage.getCode(), equalTo("internal_application_error"));
assertThat(errorMessage.getMessage(), equalTo("A general application error occurred"));
assertThat(errorMessage.getParams(), hasEntry("request_id", (Object)2771875643610572878L));
}
@Test
@Betamax(tape = "is_raised_when_too_many_requests_have_been_issued", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testIsRaisedWhenTooManyRequestsHaveBeenIssued() throws Exception {
loginId = "<EMAIL>";
TooManyRequestsException error = testFailedLogin("too_many_requests", 429, TooManyRequestsException.class);
ErrorMessage errorMessage = error.getErrors().get(0);
assertThat(errorMessage.getField(), equalTo("base"));
assertThat(errorMessage.getCode(), equalTo("too_many_requests"));
assertThat(errorMessage.getMessage(), equalTo("Too many requests have been made to the api. Please refer to the Developer Center for more information"));
assertThat(errorMessage.getParams(), is(anEmptyMap()));
}
private <E extends ApiException> E testFailedLogin(String errorCode, int httpStatusCode, Class<E> exceptionClass) {
CurrencyCloudClient client = prepareTestClient(loginId, apiKey, null);
try {
client.authenticate();
throw new AssertionError("Should have failed");
} catch (ApiException error) {
assertThat(error, instanceOf(exceptionClass));
assertThat(error.getResponse().statusCode, equalTo(httpStatusCode));
assertThat(error.getErrorCode(), equalTo(errorCode));
assertThat(error.getErrors().size(), equalTo(1));
return exceptionClass.cast(error);
}
}
private String readFile(String file) throws IOException {
try (
BufferedReader input = new BufferedReader(new InputStreamReader(ErrorTest.class.getResourceAsStream(file)));
StringWriter writer = new StringWriter();
PrintStream printStream = new PrintStream(new WriterOutputStream(writer))
) {
String line;
while ((line = input.readLine()) != null) {
printStream.println(line);
}
return writer.toString();
}
}
private String interpolate(String string, Map<String, String> vars) {
for (String var : vars.keySet()) {
string = string.replace(String.format("${%s}", var), vars.get(var));
}
return string;
}
private Map<String, String> buildMap(String ... str) {
Map<String, String> map = new HashMap<>();
for (int i = 0; i < str.length; i++) {
map.put(str[i], str[++i]);
}
return map;
}
}
<|start_filename|>src/main/java/com/currencycloud/client/dirty/DirtyWatcherDeserializer.java<|end_filename|>
package com.currencycloud.client.dirty;
import com.currencycloud.client.model.Entity;
import com.fasterxml.jackson.databind.util.StdConverter;
import net.sf.cglib.proxy.Enhancer;
public abstract class DirtyWatcherDeserializer<E extends Entity> extends StdConverter<E, E> {
@SuppressWarnings("unchecked")
@Override
public E convert(E watched) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(watched.getClass());
enhancer.setCallback(new ModificationTracker(watched));
//noinspection unchecked
return (E) enhancer.create();
}
public static class Account extends DirtyWatcherDeserializer<com.currencycloud.client.model.Account> {}
public static class Contact extends DirtyWatcherDeserializer<com.currencycloud.client.model.Contact> {}
public static class Beneficiary extends DirtyWatcherDeserializer<com.currencycloud.client.model.Beneficiary> {}
public static class Payment extends DirtyWatcherDeserializer<com.currencycloud.client.model.Payment> {}
public static class Payer extends DirtyWatcherDeserializer<com.currencycloud.client.model.Payer> {}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Transfers.java<|end_filename|>
package com.currencycloud.client.model;
import java.util.List;
public class Transfers extends PaginatedData {
private List<Transfer> transfers;
public List<Transfer> getTransfers() {
return transfers;
}
@Override
public String toString() {
return String.format("{\"transfers\":%s, \"pagination\":%s}", transfers, pagination);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/dirty/ModificationTracker.java<|end_filename|>
package com.currencycloud.client.dirty;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class ModificationTracker implements MethodInterceptor {
private final Object watched;
private Map<String, Object> dirtyProperties = new HashMap<>();
public Map<String, Object> getDirtyProperties() {
return dirtyProperties;
}
public ModificationTracker(Object watched) {
this.watched = watched;
}
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
String property = ReflectionUtils.getPropertyFromSetter(method);
if (property != null) {
Method getter;
try {
getter = ReflectionUtils.getGetterFromProperty(obj.getClass(), property);
} catch (NoSuchMethodException e) {
throw new RuntimeException("A probable bug in the Currencycloud SDK: no getter found for setter " + method, e);
}
Object prevPropertyValue = getter.invoke(obj);
Object newPropertyValue = args[0];
if (!Objects.equals(prevPropertyValue, newPropertyValue)) {
dirtyProperties.put(property, newPropertyValue);
}
}
return method.invoke(watched, args);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ConversionSplitHistory.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ConversionSplitHistory implements Entity {
private String id;
private ConversionSplitDetails parentConversion;
private ConversionSplitDetails originConversion;
private List<ConversionSplitDetails> childConversions;
protected ConversionSplitHistory() {
}
private ConversionSplitHistory(String id) {
this.id = id;
}
public static ConversionSplitHistory create() {
return new ConversionSplitHistory();
}
public static ConversionSplitHistory create(String id) {
return new ConversionSplitHistory(id);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ConversionSplitDetails getParentConversion() {
return parentConversion;
}
public void setParentConversion(ConversionSplitDetails parentConversion) {
this.parentConversion = parentConversion;
}
public ConversionSplitDetails getOriginConversion() {
return originConversion;
}
public void setOriginConversion(ConversionSplitDetails originConversion) {
this.originConversion = originConversion;
}
public List<ConversionSplitDetails> getChildConversions() {
return childConversions;
}
public void setChildConversions(List<ConversionSplitDetails> childConversions) {
this.childConversions = childConversions;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("parentConversion", parentConversion);
map.put("originConversion", originConversion);
map.put("childConversions", childConversions);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/AccountPaymentChargesSettings.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AccountPaymentChargesSettings {
@JsonProperty("payment_charges_settings")
private List<AccountPaymentChargesSetting> paymentChargesSettings;
public List<AccountPaymentChargesSetting> getPaymentChargesSettings() {
return paymentChargesSettings;
}
@Override
public String toString() {
return String.format("{\"payment_charges_settings\":%s}", paymentChargesSettings);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Pagination.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Pagination {
private Integer totalEntries;
private Integer totalPages;
private Integer currentPage;
private Integer perPage;
private Integer previousPage;
private Integer nextPage;
private String order;
private SortOrder orderAscDesc;
public Pagination() {
}
public Pagination(Integer currentPage, Integer perPage, String order, SortOrder orderAscDesc) {
this.currentPage = currentPage;
this.perPage = perPage;
this.order = order;
this.orderAscDesc = orderAscDesc;
}
public Integer getTotalEntries() {
return totalEntries;
}
public Integer getTotalPages() {
return totalPages;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPage() {
return getCurrentPage();
}
public void setPage(Integer page) {
setCurrentPage(page);
}
public Integer getPerPage() {
return perPage;
}
public void setPerPage(Integer perPage) {
this.perPage = perPage;
}
public Integer getPreviousPage() {
return previousPage;
}
public Integer getNextPage() {
return nextPage;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public SortOrder getOrderAscDesc() {
return orderAscDesc;
}
public void setOrderAscDesc(SortOrder orderAscDesc) {
this.orderAscDesc = orderAscDesc;
}
public static Builder builder() {
return new Builder();
}
public static Pagination first() {
return builder().limit(1).build();
}
public enum SortOrder {asc, desc;}
public static class Builder {
private Integer currentPage;
private Integer perPage;
private String order;
private SortOrder orderAscDesc;
protected Builder() {
}
public Builder pages(Integer currentPage, Integer perPage) {
this.currentPage = currentPage;
this.perPage = perPage;
return this;
}
public Builder limit(Integer perPage) {
this.perPage = perPage;
return this;
}
public Builder order(String order) {
this.order = order;
return this;
}
public Builder order(String order, SortOrder orderAscDesc) {
this.order = order;
this.orderAscDesc = orderAscDesc;
return this;
}
public Pagination build() {
return new Pagination(currentPage, perPage, order, orderAscDesc);
}
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("totalEntries", totalEntries);
map.put("totalPages", totalPages);
map.put("currentPage", currentPage);
map.put("perPage", perPage);
map.put("previousPage", previousPage);
map.put("nextPage", nextPage);
map.put("order", order);
map.put("orderAscDesc", orderAscDesc);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/FundingAccounts.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class FundingAccounts extends PaginatedData {
private List<FundingAccount> fundingAccounts;
public List<FundingAccount> getFundingAccounts() {
return fundingAccounts;
}
@Override
public String toString() {
return String.format("{\"fundingAccounts\":%s, \"pagination\":%s}", fundingAccounts, pagination);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Beneficiaries.java<|end_filename|>
package com.currencycloud.client.model;
import java.util.List;
public class Beneficiaries extends PaginatedData {
private List<Beneficiary> beneficiaries;
public List<Beneficiary> getBeneficiaries() {
return beneficiaries;
}
@Override
public String toString() {
return String.format("{\"beneficiaries\":%s, \"pagination\":%s}", beneficiaries, pagination);
}
}
<|start_filename|>src/test/java/com/currencycloud/client/WithdrawalAccountsTest.java<|end_filename|>
package com.currencycloud.client;
import co.freeside.betamax.Betamax;
import co.freeside.betamax.MatchRule;
import com.currencycloud.client.model.*;
import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
public class WithdrawalAccountsTest extends BetamaxTestSupport {
private CurrencyCloudClient client;
@Before
public void prepareClient() {
client = prepareTestClient(null, null, "47abdf69f25ea4e8f57a7a7b54fbc42e");
}
@Before
@After
public void methodName() {
log.debug("------------------------- " + name.getMethodName() + " -------------------------");
}
@Test
@Betamax(tape = "can_find", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanFindWithdrawalAccount() throws Exception {
WithdrawalAccounts withdrawalAccounts = client.findWithdrawalAccounts("72970a7c-7921-431c-b95f-3438724ba16f", null);
List<WithdrawalAccount> accounts = withdrawalAccounts.getWithdrawalAccounts();
Pagination pagination = withdrawalAccounts.getPagination();
assertThat(accounts.size(), is(1));
WithdrawalAccount account = accounts.get(0);
assertThat(account, is(notNullValue()));
assertThat(account.getId(), equalTo("0886ac00-6ab6-41a6-b0e1-8d3faf2e0de2"));
assertThat(account.getAccountName(), equalTo("currencycloud"));
assertThat(account.getAccountHolderName(), equalTo("The Currency Cloud"));
assertThat(account.getAccountHolderDOB(), CoreMatchers.is(nullValue(Date.class)));
assertThat(account.getRoutingCode(), equalTo("123456789"));
assertThat(account.getAccountNumber(), equalTo("01234567890"));
assertThat(account.getCurrency(), equalTo("USD"));
assertThat(account.getAccountId(), equalTo("72970a7c-7921-431c-b95f-3438724ba16f"));
assertThat(pagination.getTotalEntries(), equalTo(1));
assertThat(pagination.getTotalPages(), equalTo(1));
assertThat(pagination.getCurrentPage(), equalTo(1));
assertThat(pagination.getPerPage(), equalTo(25));
assertThat(pagination.getPreviousPage(), equalTo(-1));
assertThat(pagination.getNextPage(), equalTo(-1));
assertThat(pagination.getOrder(), equalTo("created_at"));
assertThat(pagination.getOrderAscDesc(), equalTo(Pagination.SortOrder.asc));
}
@Test
@Betamax(tape = "can_find2", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanFindWithdrawalAccount2() throws Exception {
WithdrawalAccounts withdrawalAccounts = client.findWithdrawalAccounts(null, null);
List<WithdrawalAccount> accounts = withdrawalAccounts.getWithdrawalAccounts();
Pagination pagination = withdrawalAccounts.getPagination();
assertThat(accounts.size(), is(2));
WithdrawalAccount account1 = accounts.get(0);
assertThat(account1, is(notNullValue()));
assertThat(account1.getId(), equalTo("0886ac00-6ab6-41a6-b0e1-8d3faf2e0de2"));
assertThat(account1.getAccountName(), equalTo("currencycloud"));
assertThat(account1.getAccountHolderName(), equalTo("The Currency Cloud"));
assertThat(account1.getAccountHolderDOB(), CoreMatchers.is(nullValue(Date.class)));
assertThat(account1.getRoutingCode(), equalTo("123456789"));
assertThat(account1.getAccountNumber(), equalTo("01234567890"));
assertThat(account1.getCurrency(), equalTo("USD"));
assertThat(account1.getAccountId(), equalTo("72970a7c-7921-<KEY>"));
WithdrawalAccount account2 = accounts.get(1);
assertThat(account2, is(notNullValue()));
assertThat(account2.getId(), equalTo("0886ac00-6ab6-41a6-b0e1-8d3faf2e0de3"));
assertThat(account2.getAccountName(), equalTo("currencycloud2"));
assertThat(account2.getAccountHolderName(), equalTo("The Currency Cloud 2"));
assertThat(account2.getAccountHolderDOB(), equalTo(parseDate("1990-07-20")));
assertThat(account2.getRoutingCode(), equalTo("223456789"));
assertThat(account2.getAccountNumber(), equalTo("01234567892"));
assertThat(account2.getCurrency(), equalTo("GBP"));
assertThat(account2.getAccountId(), equalTo("72970a7c-7921-431c-b95f-3438724ba16e"));
assertThat(pagination.getTotalEntries(), equalTo(2));
assertThat(pagination.getTotalPages(), equalTo(1));
assertThat(pagination.getCurrentPage(), equalTo(1));
assertThat(pagination.getPerPage(), equalTo(25));
assertThat(pagination.getPreviousPage(), equalTo(-1));
assertThat(pagination.getNextPage(), equalTo(-1));
assertThat(pagination.getOrder(), equalTo("created_at"));
assertThat(pagination.getOrderAscDesc(), equalTo(Pagination.SortOrder.asc));
}
@Test
@Betamax(tape = "pull_funds", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanPullFunds() throws Exception {
WithdrawalAccountFunds funds = client.withdrawalAccountsPullFunds("0886ac00-6ab6-41a6-b0e1-8d3faf2e0de2",
"PullFunds1", new BigDecimal(100.0));
assertThat(funds.getId(), equalTo("e2e6b7aa-c9e8-4625-96a6-b97d4baab758"));
assertThat(funds.getWithdrawalAccountId(), equalTo("0886ac00-6ab6-41a6-b0e1-8d3faf2e0de2"));
assertThat(funds.getAmount(), equalTo(new BigDecimal("100.00")));
assertThat(funds.getReference(), equalTo("PullFunds1"));
assertThat(funds.getCreatedAt(), equalTo(parseDateTime("2020-06-29T08:02:31+00:00")));
}
}
<|start_filename|>src/main/java/com/currencycloud/client/AuthenticateInterceptor.java<|end_filename|>
package com.currencycloud.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import si.mazi.rescu.Interceptor;
import javax.ws.rs.HeaderParam;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
abstract class AuthenticateInterceptor implements Interceptor {
protected final Logger log = LoggerFactory.getLogger(getClass());
protected CurrencyCloudClient client;
public AuthenticateInterceptor(CurrencyCloudClient client) {
this.client = client;
}
protected boolean mayAutoAuthenticate(Method method) {
return method.getAnnotation(NoAutoAuth.class) == null;
}
protected void replaceAuthToken(Method method, Object[] args) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int iParam = 0; iParam < parameterAnnotations.length; iParam++) {
Annotation[] paramAnns = parameterAnnotations[iParam];
for (Annotation paramAnn : paramAnns) {
if (paramAnn instanceof HeaderParam) {
if ("X-Auth-Token".equals(((HeaderParam) paramAnn).value())) {
args[iParam] = client.getAuthToken();
log.trace("Using {} as auth token.", client.getAuthToken());
return;
}
}
}
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentPurposeCode.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentPurposeCode {
private String currency;
private String entityType;
private String purposeCode;
private String purposeDescription;
private String bankAccountCountry;
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getEntityType() {
return entityType;
}
public void setEntityType(String entityType) {
this.entityType = entityType;
}
public String getPurposeCode() {
return purposeCode;
}
public void setPurposeCode(String purposeCode) {
this.purposeCode = purposeCode;
}
public String getPurposeDescription() {
return purposeDescription;
}
public void setPurposeDescription(String purposeDescription) {
this.purposeDescription = purposeDescription;
}
public String getBankAccountCountry() {
return bankAccountCountry;
}
public void setBankAccountCountry(String bankAccountCountry) {
this.bankAccountCountry = bankAccountCountry;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("bankAccountCountry", bankAccountCountry);
map.put("currency", currency);
map.put("entityType", entityType);
map.put("purposeCode", purposeCode);
map.put("purposeDescription", purposeDescription);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ReportRequests.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class ReportRequests extends PaginatedData {
@JsonProperty("report_requests")
private List<ReportRequest> reportRequests;
public List<ReportRequest> getReportRequests() {
return reportRequests;
}
@Override
public String toString() {
return String.format("{\"report_requests\":%s, \"pagination\":%s}", reportRequests, pagination);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentFeeRules.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentFeeRules {
@JsonProperty("payment_fee_rules")
private List<PaymentFeeRule> payment_fee_rules;
public List<PaymentFeeRule> getPaymentFeeRules() {
return payment_fee_rules;
}
@Override
public String toString() {
return String.format("{\"payment_fee_rules\":%s}", payment_fee_rules);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/Utils.java<|end_filename|>
package com.currencycloud.client;
import java.util.List;
public enum Utils {
;
public static final String dateFormat = "yyyy-MM-dd'T'HH:mm:ssX";
public static String join(Iterable<String> strings, String separator) {
if (strings == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (String string : strings) {
if (sb.length() > 0) {
sb.append(separator);
}
sb.append(string);
}
return sb.toString();
}
public static String joinInverse(List<String> strings, String separator) {
if (strings == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = strings.size() - 1; i >= 0; i--) {
String string = strings.get(i);
if (sb.length() > 0) {
sb.append(separator);
}
sb.append(string);
}
return sb.toString();
}
public static Throwable getRootCause(Throwable t) {
while (t.getCause() != null) {
t = t.getCause();
}
return t;
}
}
<|start_filename|>src/test/java/com/currencycloud/client/CurrencyCloudClientOnBehalfOfTest.java<|end_filename|>
package com.currencycloud.client;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class CurrencyCloudClientOnBehalfOfTest {
protected CurrencyCloudClient client = new CurrencyCloudClient("http://localhost:5555", null, null);
@Test
public void testSetsTheValueOnTheSessionAndRemovesItWhenDone() throws Exception {
final String obo = "c6ece846-6df1-461d-acaa-b42a6aa74045";
assertThat(client.getOnBehalfOf(), nullValue());
client.onBehalfOfDo(obo, new Runnable() {
@Override
public void run() {
assertThat(client.getOnBehalfOf(), equalTo(obo));
}
});
assertThat(client.getOnBehalfOf(), nullValue());
}
@Test
public void testStillRemovesTheValueFromTheSessionOnError() throws Exception {
final String obo = "c6ece846-6df1-461d-acaa-b42a6aa74045";
assertThat(client.getOnBehalfOf(), nullValue());
try {
client.onBehalfOfDo(obo, new Runnable() {
@Override
public void run() {
assertThat(client.getOnBehalfOf(), equalTo(obo));
throw new RuntimeException("Completed Expected error");
}
});
} catch (RuntimeException e) {
assertThat(e.getMessage(), equalTo("Completed Expected error"));
}
assertThat(client.getOnBehalfOf(), nullValue());
}
@Test
public void testPreventsReentrantUsage() throws Exception {
final String obo = "c6ece846-6df1-461d-acaa-b42a6aa74045";
assertThat(client.getOnBehalfOf(), nullValue());
try {
client.onBehalfOfDo(obo, new Runnable() {
@Override
public void run() {
client.onBehalfOfDo("f57b2d33-652c-4589-a8ff-7762add2706d", new Runnable() {
@Override public void run() {
throw new AssertionError("Should raise exception");
}
});
}
});
} catch (IllegalStateException e) {
assertThat(e.getMessage(), containsString("Can't nest on-behalf-of calls"));
}
assertThat(client.getOnBehalfOf(), nullValue());
}
@Test
public void testPreventsIllegalIdFormat() throws Exception {
assertThat(client.getOnBehalfOf(), nullValue());
try {
client.onBehalfOfDo("<NAME>", new Runnable() {
@Override
public void run() {
throw new AssertionError("Should raise exception");
}
});
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("is not a UUID"));
}
assertThat(client.getOnBehalfOf(), nullValue());
}
}
<|start_filename|>src/main/java/com/currencycloud/client/AutoAuthenticator.java<|end_filename|>
package com.currencycloud.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
class AutoAuthenticator extends AuthenticateInterceptor {
private static final Logger log = LoggerFactory.getLogger(AutoAuthenticator.class);
AutoAuthenticator(CurrencyCloudClient client) {
super(client);
}
@Override
public Object aroundInvoke(InvocationHandler invocationHandler, Object proxy, Method method, Object[] args)
throws Throwable {
if (client.getAuthToken() == null && mayAutoAuthenticate(method)) {
log.trace("Attempting lazy authentication for {}.", method);
client.authenticate();
replaceAuthToken(method, args);
}
return invocationHandler.invoke(proxy, method, args);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaginatedData.java<|end_filename|>
package com.currencycloud.client.model;
public class PaginatedData {
protected Pagination pagination;
public Pagination getPagination() {
return pagination;
}
}
<|start_filename|>src/main/java/com/currencycloud/client/backoff/BackOff.java<|end_filename|>
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 <NAME>
* With additions and modifications by Currencycloud, 2018
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.currencycloud.client.backoff;
import com.currencycloud.client.CurrencyCloudClient;
import com.currencycloud.client.exception.ApiException;
import com.currencycloud.client.exception.TooManyRequestsException;
import com.currencycloud.client.model.ResponseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* Executes a task with an exponential backoff retry policy.
*
* Upon failure (i.e. an exception is thrown from the task) it will wait (backoff) a random period of time, increasing
* exponetially on each retry until success or maxAttempts is reached. If the task is successful, it returns immediately.
* The task's return value (if any) is stored in the data field of the result object {@link BackOffResult}.
*
* {@link BackOff} objects are created via the Builder class, configuring the relevant fields and supplying the task,
* which can then be executed with the BackOff.builder().execute() method.
*
* @param <T> The return type of the task executed with exponential backoff.
*/
public class BackOff<T> {
protected static final int DEFAULT_MAX_ATTEMPTS = 7;
protected static final int DEFAULT_WAIT_CAP_MILLIS = new Random().nextInt(30000) + 60000;
protected static final int DEFAULT_WAIT_BASE_MILLIS = new Random().nextInt(625) + 125;
private final int cap;
private final int base;
private final int maxAttempts;
private final Class exceptionType;
private final Callable<T> task;
private final Consumer<Exception> exceptionHandler;
private final Predicate<T> forceRetry;
private static final Logger log = LoggerFactory.getLogger(CurrencyCloudClient.class);
private BackOff(final int cap, final int base, final int maxAttempts, final Class<? extends ApiException> exceptionType,
final Callable<T> task, final Consumer<Exception> exceptionHandler, final Predicate<T> forceRetry) {
this.cap = cap;
this.base = base;
this.maxAttempts = maxAttempts;
this.exceptionType = exceptionType;
this.task = Objects.requireNonNull(task);
this.exceptionHandler = Objects.requireNonNull(exceptionHandler);
this.forceRetry = Objects.requireNonNull(forceRetry);
}
public static <T> Builder<T> builder() {
return new Builder<>();
}
/**
* Executes the given task configured via the builder.
*/
public BackOffResult<T> execute() {
return execute(attempt -> attempt < maxAttempts, 0);
}
/**
* Executes the given task.
*/
protected BackOffResult<T> execute(final Predicate<Integer> predicate, final int attempt) {
int curAttempt = attempt;
do {
try {
log.trace("curAttempt: " + curAttempt);
final T result = task.call();
if (forceRetry.test(result)) {
log.trace("throwing new Retry exception");
throw new ApiException(new ResponseException());
}
log.trace("return SUCCESSFUL");
return new BackOffResult<>(result, BackOffResultStatus.SUCCESSFUL);
} catch (final Exception e) {
log.trace("exceptionType: " + exceptionType.getSimpleName() + " | exception thrown: " + e.getClass().getSimpleName());
if (e.getClass() == exceptionType) {
exceptionHandler.accept(e);
doWait(curAttempt);
} else {
throw new RuntimeException(e);
}
}
} while (predicate.test(curAttempt++));
log.trace("return EXCEEDED_MAX_ATTEMPTS");
return new BackOffResult<>(BackOffResultStatus.EXCEEDED_MAX_ATTEMPTS);
}
private void doWait(final int attempt) {
try {
final int waitTime = getWaitTimeWithJitter(cap, base, attempt);
log.trace("waitTime: " + String.format("%.3f", (double) waitTime/1000) + " sec");
Thread.sleep(waitTime);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
}
protected static int getWaitTime(final int cap, final int base, final int n) {
final int expWait = ((int) Math.pow(2, n)) * base;
return expWait <= 0 ? cap : Math.min(cap, expWait);
}
protected static int getWaitTimeWithJitter(final int cap, final int base, final int n) {
return ThreadLocalRandom.current().nextInt(0, getWaitTime(cap, base, n));
}
public static final class Builder<T> {
private int cap = DEFAULT_WAIT_CAP_MILLIS;
private int base = DEFAULT_WAIT_BASE_MILLIS;
private int maxAttempts = DEFAULT_MAX_ATTEMPTS;
private Class exceptionType = TooManyRequestsException.class;
private Callable<T> task = () -> null;
private Consumer<Exception> exceptionHandler = e -> { };
private Predicate<T> retryIf = t -> false;
private Builder() {
}
@SuppressWarnings("unchecked")
public BackOff<T> build() {
return new BackOff<>(cap, base, maxAttempts, this.exceptionType, task, exceptionHandler, retryIf);
}
/**
* Executes the {@link BackOff} produced by this builder.
*
* @return A {@link BackOffResult} containing the return data of the task and the status.
*/
public BackOffResult<T> execute() {
return build().execute();
}
/**
* The max wait time, in milliseconds, before retrying. Value must be larger than 0.
* Default is 90 secs
*/
public Builder<T> withCap(final int cap) {
this.cap = cap;
assert cap > 0;
log.debug("withCap: " + cap);
return this;
}
/**
* The base wait time, in milliseconds, before retrying. Value must be larger than 0.
* Default is 125 msecs
*/
public Builder<T> withBase(final int base) {
this.base = base;
assert base > 0;
log.debug("withBase: " + base);
return this;
}
/**
* The maximum number of retry attempts. Value must be larger than 0.
* Default is 7 attempts
*/
public Builder<T> withMaxAttempts(final int maxAttempts) {
this.maxAttempts = maxAttempts;
assert maxAttempts > 0;
log.debug("withMaxAttempts: " + maxAttempts);
return this;
}
/**
* The exception type to retry. All others are executed normally without retrying.
* Default is TooManyRequestsException
*/
public Builder<T> withExceptionType(final Class<? extends ApiException> exceptionType) {
this.exceptionType = exceptionType;
log.debug("withExceptionType: " + exceptionType.getSimpleName());
return this;
}
/**
* The task to perform, which will be retried with backoff if it encounters exceptionType exception.
*/
public Builder<T> withTask(final Callable<T> task) {
this.task = Objects.requireNonNull(task);
log.debug("withTask");
return this;
}
/**
* Additional exception handling logic. The task will still be retried after the exception is handled, but this
* allows for things like logging the exception, updating application state, etc.
*/
public Builder<T> withExceptionHandler(final Consumer<Exception> exceptionHandler) {
this.exceptionHandler = Objects.requireNonNull(exceptionHandler);
log.debug("withExceptionHandler");
return this;
}
/**
* Used mainly for testing (hence package-private) to force retry of the main task even if it did not throw
* an exception.
*/
Builder<T> retryIf(final Predicate<T> retryIf) {
this.retryIf = Objects.requireNonNull(retryIf);
log.debug("forceRetry");
return this;
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/ExceptionTransformer.java<|end_filename|>
package com.currencycloud.client;
import com.currencycloud.client.exception.ApiException;
import com.currencycloud.client.exception.UnexpectedException;
import com.currencycloud.client.model.ResponseException;
import si.mazi.rescu.Interceptor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
class ExceptionTransformer implements Interceptor {
@Override
public Object aroundInvoke(InvocationHandler invocationHandler, Object proxy, Method method, Object[] args)
throws Throwable {
try {
return invocationHandler.invoke(proxy, method, args);
} catch (ResponseException e) {
throw ApiException.create(e);
} catch (ApiException | UnexpectedException e) {
throw e;
} catch (Throwable t) {
throw new UnexpectedException("Error invoking " + method, t);
}
}
}
<|start_filename|>src/test/java/com/currencycloud/client/dirty/UpdateTest.java<|end_filename|>
package com.currencycloud.client.dirty;
import co.freeside.betamax.Betamax;
import co.freeside.betamax.MatchRule;
import com.currencycloud.client.BetamaxTestSupport;
import com.currencycloud.client.CurrencyCloudClient;
import com.currencycloud.client.model.Beneficiaries;
import com.currencycloud.client.model.Beneficiary;
import org.junit.Test;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.junit.MatcherAssert.assertThat;
public class UpdateTest extends BetamaxTestSupport {
@Test
@Betamax(tape = "only_updates_changed_records", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void onlyUpdatesChangedRecords() throws Exception {
CurrencyCloudClient client = prepareTestClient(null, null, "e5070d4a16c5ffe4ed9fb268a2a716be");
Beneficiary beneficiary = client.retrieveBeneficiary("081596c9-02de-483e-9f2a-4cf55dcdf98c");
assertThat(beneficiary.getBankAccountHolderName(), equalTo("Test User"));
assertThat(beneficiary.getEmail(), is(nullValue()));
assertThat(beneficiary.getCurrency(), equalTo("GBP"));
beneficiary.setBankAccountHolderName("Test User 2");
beneficiary.setEmail("<EMAIL>");
beneficiary.setCurrency("GBP"); // doesn't change
// The following will fail (with a HTTP 403 from Betamax and a message "tape is read only") if the request body
// doesn't match the one in the yaml file.
client.updateBeneficiary(beneficiary);
}
@Test
@Betamax(tape = "does_nothing_if_nothing_has_changed", match = {MatchRule.method, MatchRule.uri})
public void shouldDoNothingIfNothingHasChanged() throws Exception {
CurrencyCloudClient client = prepareTestClient(null, null, "e5070d4a16c5ffe4ed9fb268a2a716be");
Beneficiary beneficiary = client.retrieveBeneficiary("081596c9-02de-483e-9f2a-4cf55dcdf98c");
assertThat(beneficiary.getCurrency(), equalTo("GBP"));
beneficiary.setCurrency("GBP"); // doesn't change
client.updateBeneficiary(beneficiary); // No matching request in the yaml
}
@Test
@Betamax(tape = "does_nothing_if_nothing_has_changed_from_collection", match = {MatchRule.method, MatchRule.uri})
public void shouldDoNothingIfNothingHasChangedFromCollection() throws Exception {
CurrencyCloudClient client = prepareTestClient(null, null, "e5070d4a16c5ffe4ed9fb268a2a716be");
Beneficiaries beneficiaries = client.findBeneficiaries(null, null);
Beneficiary beneficiary = beneficiaries.getBeneficiaries().get(0);
assertThat(beneficiary.getCurrency(), equalTo("GBP"));
beneficiary.setCurrency("GBP"); // doesn't change
client.updateBeneficiary(beneficiary); // No matching request in the yaml
}
}
<|start_filename|>src/main/java/com/currencycloud/client/logging/LogSecretsFilter.java<|end_filename|>
package com.currencycloud.client.logging;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import java.util.Arrays;
import java.util.Collection;
/**
* This can be used to help avoid logging sensitive data in application logs, if you are using logback.
* Add the filter class="com.currencycloud.client.logging.LogSecretsFilter" to your appender configuration
* in logback.xml
*
* Note that this depends on Logback, so the project must use Logback as the slf4j logging provider.
*/
public class LogSecretsFilter extends Filter<ILoggingEvent> {
private static final Collection<String> forbiddens = Arrays.asList("X-Auth-Token", "authToken", "auth_token", "api_key", "apiKey");
@Override
public FilterReply decide(ILoggingEvent event) {
String formattedMessage = event.getFormattedMessage();
for (String forbidden : forbiddens) {
if (formattedMessage.contains(forbidden)) {
return FilterReply.DENY;
}
}
return FilterReply.NEUTRAL;
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PayerRequiredDetail.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PayerRequiredDetail {
private String payerEntityType;
private String paymentType;
private List<Map<String, String>> requiredFields = new ArrayList<>();
private String payerIdentificationType;
public String getPayerEntityType() {
return payerEntityType;
}
public String getPaymentType() {
return paymentType;
}
public List<Map<String, String>> getRequiredFields() {
return requiredFields;
}
public String getPayerIdentificationType() {
return payerIdentificationType;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("payerEntityType", payerEntityType);
map.put("paymentType", paymentType);
map.put("requiredFields", requiredFields);
map.put("payerIdentificationType", payerIdentificationType);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/test/resources/BetamaxConfig.groovy<|end_filename|>
import co.freeside.betamax.TapeMode
betamax {
tapeRoot = new File('src/test/resources/betamax/tapes')
proxyPort = 5555
proxyTimeout = 3000
defaultMode = TapeMode.READ_ONLY
ignoreHosts = []
ignoreLocalhost = false
sslSupport = true
}
<|start_filename|>src/main/java/com/currencycloud/client/model/SettlementAccounts.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SettlementAccounts {
private List<SettlementAccount> settlementAccounts;
public List<SettlementAccount> getSettlementAccounts() {
return settlementAccounts;
}
@Override
public String toString() {
return String.format("{\"settlementAccounts\":%s}", settlementAccounts);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentFeeRule.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentFeeRule {
private String paymentType;
private String chargeType;
private BigDecimal feeAmount;
private String feeCurrency;
private String paymentFeeId;
private String paymentFeeName;
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getChargeType() {
return chargeType;
}
public void setChargeType(String chargeType) {
this.chargeType = chargeType;
}
public BigDecimal getFeeAmount() {
return feeAmount;
}
public void SetFeeAmount(BigDecimal feeAmount) {
this.feeAmount = feeAmount;
}
public String getFeeCurrency() {
return feeCurrency;
}
public void setFeeCurrency(String feeCurrency) {
this.feeCurrency = feeCurrency;
}
public String getPaymentFeeId() {
return paymentFeeId;
}
public void setPaymentFeeId(String paymentFeeId) {
this.paymentFeeId = paymentFeeId;
}
public String getPaymentFeeName() {
return paymentFeeName;
}
public void setPaymentFeeName(String paymentFeeName) {
this.paymentFeeName = paymentFeeName;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("paymentType", paymentType);
map.put("chargeType", chargeType);
map.put("feeAmount", feeAmount);
map.put("feeCurrency", feeCurrency);
map.put("paymentFeeId", paymentFeeId);
map.put("paymentFeeName", paymentFeeName);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentTrackingInfo.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentTrackingInfo {
private String uetr;
private TransactionStatus transactionStatus;
private Date initiationTime;
private Date completionTime;
private Date lastUpdateTime;
private List<PaymentEvent> paymentEvents;
public String getUetr() {
return uetr;
}
public void setUetr(String uetr) {
this.uetr = uetr;
}
public TransactionStatus getTransactionStatus() {
return transactionStatus;
}
public void setTransactionStatus(TransactionStatus transactionStatus) {
this.transactionStatus = transactionStatus;
}
public Date getInitiationTime() {
return initiationTime;
}
public void setInitiationTime(Date initiationTime) {
this.initiationTime = initiationTime;
}
public Date getCompletionTime() {
return completionTime;
}
public void setCompletionTime(Date completionTime) {
this.completionTime = completionTime;
}
public Date getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public List<PaymentEvent> getPaymentEvents() {
return paymentEvents;
}
public void setPaymentEvents(List<PaymentEvent> paymentEvents) {
this.paymentEvents = paymentEvents;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("uetr", uetr);
map.put("transactionStatus", transactionStatus);
map.put("initiationTime", initiationTime);
map.put("completionTime", completionTime);
map.put("lastUpdateTime", lastUpdateTime);
map.put("paymentEvents", paymentEvents);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public static final class TransactionStatus {
private String status;
private String reason;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
}
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public static final class PaymentEvent {
private String trackerEventType;
private Boolean valid;
private TransactionStatus transactionStatus;
private Date fundsAvailable;
private String forwardedToAgent;
private String from;
private String to;
private String originator;
private SerialParties serialParties;
private Date senderAcknowledgementReceipt;
private Amount instructedAmount;
private Amount confirmedAmount;
private Amount interbankSettlementAmount;
private Date interbankSettlementDate;
private Amount chargeAmount;
private String chargeType;
private ForeignExchangeDetails foreignExchangeDetails;
private Date lastUpdateTime;
public String getTrackerEventType() {
return trackerEventType;
}
public void setTracker_event_type(String trackerEventType) {
this.trackerEventType = trackerEventType;
}
public Boolean getValid() {
return valid;
}
public void setValid(Boolean valid) {
this.valid = valid;
}
public TransactionStatus getTransactionStatus() {
return transactionStatus;
}
public void setTransactionStatus(TransactionStatus transactionStatus) {
this.transactionStatus = transactionStatus;
}
public Date getFundsAvailable() {
return fundsAvailable;
}
public void setFundsAvailable(Date fundsAvailable) {
this.fundsAvailable = fundsAvailable;
}
public String getForwardedToAgent() {
return forwardedToAgent;
}
public void setForwardedToAgent(String forwardedToAgent) {
this.forwardedToAgent = forwardedToAgent;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getOriginator() {
return originator;
}
public void setOriginator(String originator) {
this.originator = originator;
}
public SerialParties getSerialParties() {
return serialParties;
}
public void setSerialParties(SerialParties serialParties) {
this.serialParties = serialParties;
}
public Date getSenderAcknowledgementReceipt() {
return senderAcknowledgementReceipt;
}
public void setSenderAcknowledgementReceipt(Date senderAcknowledgementReceipt) {
this.senderAcknowledgementReceipt = senderAcknowledgementReceipt;
}
public Amount getInstructedAmount() {
return instructedAmount;
}
public void setInstructedAmount(Amount instructedAmount) {
this.instructedAmount = instructedAmount;
}
public Amount getConfirmedAmount() {
return confirmedAmount;
}
public void setConfirmedAmount(Amount confirmedAmount) {
this.confirmedAmount = confirmedAmount;
}
public Amount getInterbankSettlementAmount() {
return interbankSettlementAmount;
}
public void setInterbankSettlementAmount(Amount interbankSettlementAmount) {
this.interbankSettlementAmount = interbankSettlementAmount;
}
public Date getInterbankSettlementDate() {
return interbankSettlementDate;
}
public void setInterbankSettlementDate(Date interbankSettlementDate) {
this.interbankSettlementDate = interbankSettlementDate;
}
public Amount getChargeAmount() {
return chargeAmount;
}
public void setChargeAmount(Amount chargeAmount) {
this.chargeAmount = chargeAmount;
}
public String getChargeType() {
return chargeType;
}
public void setChargeType(String chargeType) {
this.chargeType = chargeType;
}
public ForeignExchangeDetails getForeignExchangeDetails() {
return foreignExchangeDetails;
}
public void setForeignExchangeDetails(ForeignExchangeDetails foreignExchangeDetails) {
this.foreignExchangeDetails = foreignExchangeDetails;
}
public Date getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
}
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public static final class SerialParties {
private String debtor;
private String debtorAgent;
private String intermediaryAgent1;
private String instructingReimbursementAgent;
private String creditorAgent;
private String creditor;
public String getDebtor() {
return debtor;
}
public void setDebtor(String debtor) {
this.debtor = debtor;
}
public String getDebtorAgent() {
return debtorAgent;
}
public void setDebtorAgent(String debtorAgent) {
this.debtorAgent = debtorAgent;
}
public String getIntermediaryAgent1() {
return intermediaryAgent1;
}
public void setIntermediaryAgent1(String intermediaryAgent1) {
this.intermediaryAgent1 = intermediaryAgent1;
}
public String getInstructingReimbursementAgent() {
return instructingReimbursementAgent;
}
public void setInstructingReimbursementAgent(String instructingReimbursementAgent) {
this.instructingReimbursementAgent = instructingReimbursementAgent;
}
public String getCreditorAgent() {
return creditorAgent;
}
public void setCreditorAgent(String creditorAgent) {
this.creditorAgent = creditorAgent;
}
public String getCreditor() {
return creditor;
}
public void setCreditor(String creditor) {
this.creditor = creditor;
}
}
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public static final class Amount {
private String currency;
private BigDecimal amount;
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
}
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public static final class ForeignExchangeDetails {
private String sourceCurrency;
private String targetCurrency;
private BigDecimal rate;
public String getSourceCurrency() {
return sourceCurrency;
}
public void setSourceCurrency(String sourceCurrency) {
this.sourceCurrency = sourceCurrency;
}
public String getTargetCurrency() {
return targetCurrency;
}
public void setTargetCurrency(String targetCurrency) {
this.targetCurrency = targetCurrency;
}
public BigDecimal getRate() {
return rate;
}
public void setRate(BigDecimal rate) {
this.rate = rate;
}
}
}
<|start_filename|>src/test/java/com/currencycloud/client/dirty/ReflectionUtilsTest.java<|end_filename|>
package com.currencycloud.client.dirty;
import com.currencycloud.client.model.Account;
import com.currencycloud.client.model.Beneficiary;
import org.hamcrest.Matchers;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;
import static com.currencycloud.client.dirty.ReflectionUtils.*;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.junit.MatcherAssert.assertThat;
public class ReflectionUtilsTest {
@Test
public void shouldRecognizeSetters() throws Exception {
assertThat(isSetter(Object.class.getMethod("toString")), equalTo(false));
assertThat(isSetter(Account.class.getMethod("getStatus")), equalTo(false));
assertThat(isSetter(Account.class.getMethod("setBrand", String.class)), equalTo(true));
assertThat(isSetter(AtomicInteger.class.getMethod("set", int.class)), equalTo(false));
}
@Test
public void shouldGetPropertyFromSetterMethod() throws Exception {
assertThat(getPropertyFromSetter(Object.class.getMethod("toString")), is(nullValue()));
assertThat(getPropertyFromSetter(Account.class.getMethod("getStatus")), is(nullValue()));
assertThat(getPropertyFromSetter(Account.class.getMethod("setBrand", String.class)), equalTo("brand"));
assertThat(getPropertyFromSetter(AtomicInteger.class.getMethod("set", int.class)), is(nullValue()));
}
@Test
public void shouldReturnCorrectGetter() throws Exception {
shouldReturnCorrectGetter(Account.class, "status", "getStatus", String.class);
shouldReturnCorrectGetter(Beneficiary.class, "defaultBeneficiary", "getDefaultBeneficiary", Boolean.class);
}
private void shouldReturnCorrectGetter(
Class<?> clazz,
String property,
String getterName,
Class<?> getterType
) throws NoSuchMethodException {
Method getter = getGetterFromProperty(clazz, property);
assertThat(getter, is(not(nullValue())));
assertThat(getter.getName(), equalTo(getterName));
assertThat(getter.getReturnType(), Matchers.<Class>equalTo(getterType));
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Contacts.java<|end_filename|>
package com.currencycloud.client.model;
import java.util.List;
public class Contacts extends PaginatedData {
private List<Contact> contacts;
public List<Contact> getContacts() {
return contacts;
}
@Override
public String toString() {
return String.format("{\"contacts\":%s, \"pagination\":%s}", contacts, pagination);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentSubmission.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentSubmission {
private String status;
private String submissionRef;
private String mt103;
protected PaymentSubmission() { }
private PaymentSubmission(String status,
String submissionRef,
String mt103) {
this.status = status;
this.submissionRef = submissionRef;
this.mt103 = mt103;
}
public static PaymentSubmission create() {
return new PaymentSubmission();
}
/** Creates a new {@link PaymentSubmission} that can be used as a return value for the
* {@link com.currencycloud.client.CurrencyCloudClient#retrievePaymentSubmission(String)} method.
*/
public static PaymentSubmission create(
String status,
String submissionRef,
String mt103
) {
return new PaymentSubmission(status, submissionRef, mt103);
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSubmissionRef() {
return submissionRef;
}
public void setSubmissionRef(String submissionRef) {
this.submissionRef = submissionRef;
}
public String getMt103() {
return mt103;
}
public void setMt103(String mt103) {
this.mt103 = mt103;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("status", status);
map.put("submissionRef", submissionRef);
map.put("mt103", mt103);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/SenderDetails.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SenderDetails implements Entity {
private String id;
private BigDecimal amount;
private String currency;
private String additionalInformation;
private Date valueDate;
private String sender;
private String receivingAccountNumber;
private String receivingAccountIban;
private Date createdAt;
private Date updatedAt;
protected SenderDetails() {}
private SenderDetails(String id) {
this.id = id;
}
public static SenderDetails create() {
return new SenderDetails();
}
public static SenderDetails create(String id) {
return new SenderDetails(id);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getAdditionalInformation() {
return additionalInformation;
}
public void setAdditionalInformation(String additionalInformation) {
this.additionalInformation = additionalInformation;
}
public Date getValueDate() {
return valueDate;
}
public void setValueDate(Date valueDate) {
this.valueDate = valueDate;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceivingAccountNumber() {
return receivingAccountNumber;
}
public void setReceivingAccountNumber(String receivingAccountNumber) {
this.receivingAccountNumber = receivingAccountNumber;
}
public String getReceivingAccountIban() {
return receivingAccountIban;
}
public void setReceivingAccountIban(String receivingAccountIban) {
this.receivingAccountIban = receivingAccountIban;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("amount", amount);
map.put("currency", currency);
map.put("additionalInformation", additionalInformation);
map.put("valueDate", valueDate);
map.put("sender", sender);
map.put("receivingAccountNumber", receivingAccountNumber);
map.put("receivingAccountIban", receivingAccountIban);
map.put("createdAt", createdAt);
map.put("updatedAt", updatedAt);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ReportRequest.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ReportRequest implements Entity {
private String id;
private String shortReference;
private String description;
private SearchParams searchParams;
private String reportType;
private String status;
private String failureReason;
private Date expirationDate;
private String reportUrl;
private String accountId;
private String contactId;
private Date createdAt;
private Date updatedAt;
private Date createdAtFrom;
private Date createdAtTo;
private Date expirationDateFrom;
private Date expirationDateTo;
protected ReportRequest() {}
public static ReportRequest create() { return new ReportRequest(); }
private ReportRequest(String id) {
this.id = id;
}
public static ReportRequest create(String id) {
return new ReportRequest(id);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getShortReference() {
return shortReference;
}
public void setShortReference(String shortReference) {
this.shortReference = shortReference;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public SearchParams getSearchParams() {
return searchParams;
}
public void setSearchParams(SearchParams searchParams) {
this.searchParams = searchParams;
}
public String getReportType() {
return reportType;
}
public void setReportType(String reportType) {
this.reportType = reportType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getFailureReason() {
return failureReason;
}
public void setFailureReason(String failureReason) {
this.failureReason = failureReason;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public String getReportUrl() {
return reportUrl;
}
public void setReportUrl(String reportUrl) {
this.reportUrl = reportUrl;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getContactId() {
return contactId;
}
public void setContactId(String contactId) {
this.contactId = contactId;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Date getCreatedAtFrom() {
return createdAtFrom;
}
public void setCreatedAtFrom(Date createdAtFrom) {
this.createdAtFrom = createdAtFrom;
}
public Date getCreatedAtTo() {
return createdAtTo;
}
public void setCreatedAtTo(Date createdAtTo) {
this.createdAtTo = createdAtTo;
}
public Date getExpirationDateFrom() {
return expirationDateFrom;
}
public void setExpirationDateFrom(Date expirationDateFrom) {
this.expirationDateFrom = expirationDateFrom;
}
public Date getExpirationDateTo() {
return expirationDateTo;
}
public void setExpirationDateTo(Date expirationDateTo) {
this.expirationDateTo = expirationDateTo;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("shortReference", shortReference);
map.put("description", description);
map.put("searchParams", searchParams);
map.put("reportType", reportType);
map.put("status", status);
map.put("failureReason", failureReason);
map.put("expirationDate", expirationDate);
map.put("reportUrl", reportUrl);
map.put("accountId", accountId);
map.put("contactId", contactId);
map.put("createdAt", createdAt);
map.put("updatedAt", updatedAt);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
/* ToDo: Not the most efficient way to handle SearchParams. To be improved in a future release */
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class SearchParams {
public SearchParams() { }
private String description;
private String currency;
private BigDecimal amountFrom;
private BigDecimal amountTo;
private String status;
private Date paymentDateFrom;
private Date paymentDateTo;
private Date transferredAtFrom;
private Date transferredAtTo;
private Date createdAtFrom;
private Date createdAtTo;
private Date updatedAtFrom;
private Date updatedAtTo;
private String beneficiaryId;
private String conversionId;
private Boolean withDeleted;
private String paymentGroupId;
private String uniqueRequestId;
private String scope;
private String buyCurrency;
private String sellCurrency;
private BigDecimal clientBuyAmountFrom;
private BigDecimal clientBuyAmountTo;
private BigDecimal clientSellAmountFrom;
private BigDecimal clientSellAmountTo;
private BigDecimal partnerBuyAmountFrom;
private BigDecimal partnerBuyAmountTo;
private BigDecimal partnerSellAmountFrom;
private BigDecimal partnerSellAmountTo;
private String clientStatus;
private Date conversionDateFrom;
private Date conversionDateTo;
private Date settlementDateFrom;
private Date settlementDateTo;
public String getDescription() {
return description;
}
public String getCurrency() {
return currency;
}
public BigDecimal getAmountFrom() {
return amountFrom;
}
public BigDecimal getAmountTo() {
return amountTo;
}
public String getStatus() {
return status;
}
public Date getPaymentDateFrom() {
return paymentDateFrom;
}
public Date getPaymentDateTo() {
return paymentDateTo;
}
public Date getTransferredAtFrom() {
return transferredAtFrom;
}
public Date getTransferredAtTo() {
return transferredAtTo;
}
public Date getCreatedAtFrom() {
return createdAtFrom;
}
public Date getCreatedAtTo() {
return createdAtTo;
}
public Date getUpdatedAtFrom() {
return updatedAtFrom;
}
public Date getUpdatedAtTo() {
return updatedAtTo;
}
public String getBeneficiaryId() {
return beneficiaryId;
}
public String getConversionId() {
return conversionId;
}
public Boolean getWithDeleted() {
return withDeleted;
}
public String getPaymentGroupId() {
return paymentGroupId;
}
public String getUniqueRequestId() {
return uniqueRequestId;
}
public String getScope() {
return scope;
}
public String getBuyCurrency() {
return buyCurrency;
}
public String getSellCurrency() {
return sellCurrency;
}
public BigDecimal getClientBuyAmountFrom() {
return clientBuyAmountFrom;
}
public BigDecimal getClientBuyAmountTo() {
return clientBuyAmountTo;
}
public BigDecimal getClientSellAmountFrom() {
return clientSellAmountFrom;
}
public BigDecimal getClientSellAmountTo() {
return clientSellAmountTo;
}
public BigDecimal getPartnerBuyAmountFrom() {
return partnerBuyAmountFrom;
}
public BigDecimal getPartnerBuyAmountTo() {
return partnerBuyAmountTo;
}
public BigDecimal getPartnerSellAmountFrom() {
return partnerSellAmountFrom;
}
public BigDecimal getPartnerSellAmountTo() {
return partnerSellAmountTo;
}
public String getClientStatus() {
return clientStatus;
}
public Date getConversionDateFrom() {
return conversionDateFrom;
}
public Date getConversionDateTo() {
return conversionDateTo;
}
public Date getSettlementDateFrom() {
return settlementDateFrom;
}
public Date getSettlementDateTo() {
return settlementDateTo;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("description", description);
map.put("buyCurrency", buyCurrency);
map.put("sellCurrency", sellCurrency);
map.put("clientBuyAmountFrom", clientBuyAmountFrom);
map.put("clientBuyAmountTo", clientBuyAmountTo);
map.put("clientSellAmountFrom", clientSellAmountFrom);
map.put("clientSellAmountTo", clientSellAmountTo);
map.put("partnerBuyAmountFrom", partnerBuyAmountFrom);
map.put("partnerBuyAmountTo", partnerBuyAmountTo);
map.put("partnerSellAmountFrom", partnerSellAmountFrom);
map.put("partnerSellAmountTo", partnerSellAmountTo);
map.put("clientStatus", clientStatus);
map.put("conversionDateFrom", conversionDateFrom);
map.put("conversionDateTo", conversionDateTo);
map.put("settlementDateFrom", settlementDateFrom);
map.put("settlementDateTo", settlementDateTo);
map.put("createdAtFrom", createdAtFrom);
map.put("createdAtTo", createdAtTo);
map.put("updatedAtFrom", updatedAtFrom);
map.put("updatedAtTo", updatedAtTo);
map.put("uniqueRequestId", uniqueRequestId);
map.put("scope", scope);
map.put("currency", currency);
map.put("amountFrom", amountFrom);
map.put("amountTo", amountTo);
map.put("status", status);
map.put("paymentDateFrom", paymentDateFrom);
map.put("paymentDateTo", paymentDateTo);
map.put("transferredAtFrom", transferredAtFrom);
map.put("transferredAtTo", transferredAtTo);
map.put("beneficiaryId", beneficiaryId);
map.put("conversionId", conversionId);
map.put("withDeleted", withDeleted);
map.put("paymentGroupId", paymentGroupId);
map.values().removeIf(Objects::isNull);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Balances.java<|end_filename|>
package com.currencycloud.client.model;
import java.util.List;
public class Balances extends PaginatedData {
private List<Balance> balances;
public List<Balance> getBalances() {
return balances;
}
@Override
public String toString() {
return String.format("{\"balances\":%s, \"pagination\":%s}", balances, pagination);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/AuthenticateResponse.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AuthenticateResponse {
private String authToken;
public String getAuthToken() {
return authToken;
}
}
<|start_filename|>src/main/java/com/currencycloud/client/exception/ForbiddenException.java<|end_filename|>
package com.currencycloud.client.exception;
import com.currencycloud.client.model.ResponseException;
/** Thrown when a 403 HTTP response is returned. */
public class ForbiddenException extends ApiException {
protected ForbiddenException(ResponseException e) {
super(e);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/exception/ApiException.java<|end_filename|>
package com.currencycloud.client.exception;
import com.currencycloud.client.Utils;
import com.currencycloud.client.model.ErrorMessage;
import com.currencycloud.client.model.ResponseException;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import si.mazi.rescu.InvocationAware;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ApiException extends CurrencyCloudException {
private final String errorCode;
private final List<ErrorMessage> errors;
private final Response response;
protected <E extends Throwable & InvocationAware> ApiException(
String message,
E cause,
String errorCode,
List<ErrorMessage> errors,
Response response
) {
super(message, cause);
this.errorCode = errorCode;
this.errors = errors;
this.response = response;
}
public ApiException(ResponseException e) {
this(collectMessages(e), e, e.getErrorCode(), new ArrayList<ErrorMessage>(), new Response(e.getHttpStatusCode(), e.getResponseHeaders()));
if (e.getErrorMessages() != null) {
for (Map.Entry<String, List<ErrorMessage>> entry : e.getErrorMessages().entrySet()) {
List<ErrorMessage> emsgs = entry.getValue();
for (ErrorMessage em : emsgs) {
errors.add(new ErrorMessage(entry.getKey(), em.getCode(), em.getMessage(), em.getParams()));
}
}
}
}
static String collectMessages(ResponseException e) {
if (e.getErrorMessages() == null) {
return e.getMessage();
}
StringBuilder sb = new StringBuilder();
for (List<ErrorMessage> msgs : e.getErrorMessages().values()) {
for (ErrorMessage msg : msgs) {
if (sb.length() > 0) {
sb.append("; ");
}
sb.append(msg.getMessage());
}
}
return sb.toString();
}
public static ApiException create(ResponseException e) {
switch (e.getHttpStatusCode()) {
case 400: return new BadRequestException(e);
case 401: return new AuthenticationException(e);
case 403: return new ForbiddenException(e);
case 404: return new NotFoundException(e);
case 429: return new TooManyRequestsException(e);
case 500: return new InternalApplicationException(e);
}
return new ApiException(e);
}
public Response getResponse() {
return response;
}
public String getErrorCode() {
return errorCode;
}
public List<ErrorMessage> getErrors() {
return errors;
}
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonPropertyOrder({"statusCode", "date", "requestId"})
public static class Response {
/** The HTTP response status code (eg. 404 for Not Found). */
public final int statusCode;
/** The request ID, as returned by the server. */
public final String requestId;
/** The request date/time, as returned by the server. */
public final String date;
private Response(int statusCode, Map<String, List<String>> responseHeaders) {
this.statusCode = statusCode;
this.requestId = get(responseHeaders, "X-Request-Id");
this.date = get(responseHeaders, "Date");
}
private static String get(Map<String, List<String>> responseHeaders, String date) {
if (responseHeaders != null) {
List<String> all = responseHeaders.get(date);
if (all != null && !all.isEmpty()) {
return Utils.joinInverse(all, ", ");
}
}
return null;
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/WithdrawalAccountFunds.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class WithdrawalAccountFunds implements Entity {
private String id;
private String withdrawalAccountId;
private String reference;
private Date createdAt;
private BigDecimal amount;
protected WithdrawalAccountFunds() {
}
public static WithdrawalAccountFunds create() {
return new WithdrawalAccountFunds();
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getWithdrawalAccountId() {
return withdrawalAccountId;
}
public void setWithdrawalAccountId(String withdrawalAccountId) {
this.withdrawalAccountId = withdrawalAccountId;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("withdrawalAccountId", withdrawalAccountId);
map.put("reference", reference);
map.put("createdAt", createdAt);
map.put("amount", amount);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentAuthorisation.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentAuthorisation {
private String paymentId;
private String paymentStatus;
private Boolean updated;
private int authStepsTaken;
private int authStepsRequired;
private String shortReference;
private String error;
protected PaymentAuthorisation() {}
private PaymentAuthorisation(String paymentId) {
this.paymentId = paymentId;
}
public String getPaymentId() {
return paymentId;
}
public void setPaymentId(String paymentId) {
this.paymentId = paymentId;
}
public String getPaymentStatus() {
return paymentStatus;
}
public void setPaymentStatus(String paymentStatus) {
this.paymentStatus = paymentStatus;
}
public boolean isUpdated() {
return updated;
}
public void setUpdated(boolean updated) {
this.updated = updated;
}
public int getAuthStepsTaken() {
return authStepsTaken;
}
public void setAuthStepsTaken(int authorisationStepsTaken) {
this.authStepsTaken = authorisationStepsTaken;
}
public int getAuthStepsRequired() {
return authStepsRequired;
}
public void setAuthStepsRequired(int authorisationStepsRequired) {
this.authStepsRequired = authorisationStepsRequired;
}
public String getShortReference() {
return shortReference;
}
public void setShortReference(String shortReference) {
this.shortReference = shortReference;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("paymentId", paymentId);
map.put("paymentStatus", paymentStatus);
map.put("updated", updated);
map.put("authStepsTaken", authStepsTaken);
map.put("authStepsRequired", authStepsRequired);
map.put("shortReference", shortReference);
map.put("error", error);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/exception/BadRequestException.java<|end_filename|>
package com.currencycloud.client.exception;
import com.currencycloud.client.model.ResponseException;
/** Thrown when a 400 HTTP response is returned. */
public class BadRequestException extends ApiException {
protected BadRequestException(ResponseException e) {
super(e);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PayerRequiredDetails.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PayerRequiredDetails {
@JsonProperty("details")
private List<PayerRequiredDetail> payerRequiredDetails;
public List<PayerRequiredDetail> getPayerRequiredDetails() {
return payerRequiredDetails;
}
@Override
public String toString() {
return String.format("{\"details\":%s}", payerRequiredDetails);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ConversionProfitAndLosses.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class ConversionProfitAndLosses extends PaginatedData {
@JsonProperty("conversion_profit_and_losses")
private List<ConversionProfitAndLoss> conversionProfitAndLosses;
public List<ConversionProfitAndLoss> getConversionProfitAndLosses() {
return conversionProfitAndLosses;
}
@Override
public String toString() {
return String.format("{\"conversion_profit_and_losses\":%s, \"pagination\":%s}", conversionProfitAndLosses, pagination);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Transaction.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Transaction implements Entity {
private String id;
private String balanceId;
private String accountId;
private String currency;
private BigDecimal amount;
private BigDecimal balanceAmount;
private String type;
private String action;
private String relatedEntityType;
private String relatedEntityId;
private String relatedEntityShortReference;
private String status;
private String reason;
private Date settlesAt;
private Date createdAt;
private Date updatedAt;
private Date completedAt;
private BigDecimal amountFrom;
private BigDecimal amountTo;
private Date settlesAtFrom;
private Date settlesAtTo;
private Date createdAtFrom;
private Date createdAtTo;
private Date updatedAtFrom;
private Date updatedAtTo;
private Date completedAtFrom;
private Date completedAtTo;
private String beneficiaryId;
private String currencyPair;
private String scope;
protected Transaction() { }
private Transaction(
String currency,
BigDecimal amount,
String action,
String relatedEntityType,
String relatedEntityId,
String relatedEntityShortReference,
String status,
String type,
String reason
) {
this.currency = currency;
this.amount = amount;
this.action = action;
this.relatedEntityType = relatedEntityType;
this.relatedEntityId = relatedEntityId;
this.relatedEntityShortReference = relatedEntityShortReference;
this.status = status;
this.type = type;
this.reason = reason;
}
public static Transaction create() {
return new Transaction();
}
/**
* Creates a new {@link Transaction} that can be used as a parameter for the
* {@link com.currencycloud.client.CurrencyCloudClient#findTransactions} method.
*/
public static Transaction createExample(
String currency,
BigDecimal amount,
String action,
String relatedEntityType,
String relatedEntityId,
String relatedEntityShortReference,
String status,
String type,
String reason
) {
return new Transaction(
currency,
amount,
action,
relatedEntityType,
relatedEntityId,
relatedEntityShortReference,
status,
type,
reason
);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBalanceId() {
return balanceId;
}
public void setBalanceId(String balanceId) {
this.balanceId = balanceId;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public BigDecimal getBalanceAmount() {
return balanceAmount;
}
public void setBalanceAmount(BigDecimal balanceAmount) {
this.balanceAmount = balanceAmount;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getRelatedEntityType() {
return relatedEntityType;
}
public void setRelatedEntityType(String relatedEntityType) {
this.relatedEntityType = relatedEntityType;
}
public String getRelatedEntityId() {
return relatedEntityId;
}
public void setRelatedEntityId(String relatedEntityId) {
this.relatedEntityId = relatedEntityId;
}
public String getRelatedEntityShortReference() {
return relatedEntityShortReference;
}
public void setRelatedEntityShortReference(String relatedEntityShortReference) {
this.relatedEntityShortReference = relatedEntityShortReference;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public Date getSettlesAt() {
return settlesAt;
}
public void setSettlesAt(Date settlesAt) {
this.settlesAt = settlesAt;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Date getCompletedAt() {
return completedAt;
}
public void setCompletedAt(Date completedAt) {
this.completedAt = completedAt;
}
public BigDecimal getAmountFrom() {
return amountFrom;
}
public void setAmountFrom(BigDecimal amountFrom) {
this.amountFrom = amountFrom;
}
public BigDecimal getAmountTo() {
return amountTo;
}
public void setAmountTo(BigDecimal amountTo) {
this.amountTo = amountTo;
}
public Date getSettlesAtFrom() {
return settlesAtFrom;
}
public void setSettlesAtFrom(Date settlesAtFrom) {
this.settlesAtFrom = settlesAtFrom;
}
public Date getSettlesAtTo() {
return settlesAtTo;
}
public void setSettlesAtTo(Date settlesAtTo) {
this.settlesAtTo = settlesAtTo;
}
public Date getCreatedAtFrom() {
return createdAtFrom;
}
public void setCreatedAtFrom(Date createdAtFrom) {
this.createdAtFrom = createdAtFrom;
}
public Date getCreatedAtTo() {
return createdAtTo;
}
public void setCreatedAtTo(Date createdAtTo) {
this.createdAtTo = createdAtTo;
}
public Date getUpdatedAtFrom() {
return updatedAtFrom;
}
public void setUpdatedAtFrom(Date updatedAtFrom) {
this.updatedAtFrom = updatedAtFrom;
}
public Date getUpdatedAtTo() {
return updatedAtTo;
}
public void setUpdatedAtTo(Date updatedAtTo) {
this.updatedAtTo = updatedAtTo;
}
public Date getCompletedAtFrom() {
return completedAtFrom;
}
public void setCompletedAtFrom(Date completedAtFrom) {
this.completedAtFrom = completedAtFrom;
}
public Date getCompletedAtTo() {
return completedAtTo;
}
public void setCompletedAtTo(Date completedAtTo) {
this.completedAtTo = completedAtTo;
}
public String getBeneficiaryId() {
return beneficiaryId;
}
public void setBeneficiaryId(String beneficiaryId) {
this.beneficiaryId = beneficiaryId;
}
public String getCurrencyPair() {
return currencyPair;
}
public void setCurrencyPair(String currencyPair) {
this.currencyPair = currencyPair;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("balanceId", balanceId);
map.put("accountId", accountId);
map.put("currency", currency);
map.put("amount", amount);
map.put("balanceAmount", balanceAmount);
map.put("type", type);
map.put("action", action);
map.put("relatedEntityType", relatedEntityType);
map.put("relatedEntityId", relatedEntityId);
map.put("relatedEntityShortReference", relatedEntityShortReference);
map.put("status", status);
map.put("reason", reason);
map.put("settlesAt", settlesAt);
map.put("createdAt", createdAt);
map.put("updatedAt", updatedAt);
map.put("completedAt", completedAt);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/test/java/com/currencycloud/client/DeserialisationTest.java<|end_filename|>
package com.currencycloud.client;
import com.currencycloud.client.model.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class DeserialisationTest extends JsonTestSupport {
@Test
public void testContact() throws Exception {
Contact contact = readJson(Contact.class);
assertThat(contact.getLoginId(), equalTo("john.smith"));
assertThat(contact.getId(), equalTo("543477161-91de-012f-e284-1e0030c7f352"));
assertThat(contact.getYourReference(), equalTo("ACME12345"));
assertThat(contact.getFirstName(), equalTo("John"));
assertThat(contact.getLastName(), equalTo("Smith"));
assertThat(contact.getAccountId(), equalTo("87077161-91de-012f-e284-1e0030c7f352"));
assertThat(contact.getAccountName(), equalTo("Company PLC"));
assertThat(contact.getStatus(), equalTo("enabled"));
assertThat(contact.getPhoneNumber(), equalTo("06554 87845"));
assertThat(contact.getMobilePhoneNumber(), equalTo("07564 534 54"));
assertThat(contact.getLocale(), equalTo("en-US"));
assertThat(contact.getTimezone(), equalTo("Europe/London"));
assertThat(contact.getEmailAddress(), equalTo("<EMAIL>"));
assertThat(contact.getDateOfBirth(), equalTo(parseDate("1980-01-22")));
assertThat(contact.getCreatedAt(), equalTo(parseDateTime("2014-01-12T00:00:00+00:00")));
assertThat(contact.getUpdatedAt(), equalTo(parseDateTime("2014-01-12T00:00:00+00:00")));
}
@Test
public void testPayer() throws Exception {
Payer payer = readJson(Payer.class);
assertThat(payer.getId(), equalTo("543477161-91de-012f-e284-1e0030c7f3123"));
assertThat(payer.getLegalEntityType(), equalTo("company"));
assertThat(payer.getCompanyName(), equalTo("Acme Corporation"));
assertThat(payer.getFirstName(), equalTo(""));
assertThat(payer.getLastName(), equalTo(""));
assertThat(payer.getAddress(), equalTo(Arrays.asList("164 Bishopsgate", "London")));
assertThat(payer.getCity(), equalTo("London"));
assertThat(payer.getStateOrProvince(), equalTo(""));
assertThat(payer.getCountry(), equalTo("GB"));
assertThat(payer.getIdentificationType(), equalTo("incorporation_number"));
assertThat(payer.getIdentificationValue(), equalTo("123123"));
assertThat(payer.getPostcode(), equalTo("EC2M 4LX"));
assertThat(payer.getDateOfBirth(), equalTo(parseDateTime("2014-01-12T12:24:19+00:00")));
assertThat(payer.getCreatedAt(), equalTo(parseDateTime("2014-01-12T12:24:19+00:00")));
assertThat(payer.getUpdatedAt(), equalTo(parseDateTime("2014-01-12T12:24:19+00:00")));
}
@Test
public void testPayment() throws Exception {
Payment payment = readJson(Payment.class);
assertThat(payment.getId(), equalTo("543477161-91de-012f-e284-1e0030c7f3123"));
assertThat(payment.getShortReference(), equalTo("140416-GGJBNQ001"));
assertThat(payment.getBeneficiaryId(), equalTo("543477161-91de-012f-e284-1e0030c7f352"));
assertThat(payment.getConversionId(), equalTo("049bab6d-fe2a-42e1-be0f-531c59f838ea"));
assertThat(payment.getAmount(), equalTo(new BigDecimal("1250000.00")));
assertThat(payment.getCurrency(), equalTo("GBP"));
assertThat(payment.getStatus(), equalTo("ready_to_send"));
assertThat(payment.getPaymentType(), equalTo("regular"));
assertThat(payment.getReference(), equalTo("INVOICE 9876"));
assertThat(payment.getReason(), equalTo("Salary for March"));
assertThat(payment.getPaymentDate(), equalTo(parseDateTime("2014-01-12T00:00:00+00:00")));
assertThat(payment.getTransferredAt(), equalTo(parseDateTime("2014-01-12T13:00:00+00:00")));
assertThat(payment.getAuthorisationStepsRequired(), equalTo(0));
assertThat(payment.getCreatorContactId(), equalTo("ab3477161-91de-012f-e284-1e0030c7f35c"));
assertThat(payment.getLastUpdaterContactId(), equalTo("ab3477161-91de-012f-e284-1e0030c7f35c"));
assertThat(payment.getFailureReason(), equalTo(""));
assertThat(payment.getPayerId(), equalTo(""));
assertThat(payment.getCreatedAt(), equalTo(parseDateTime("2014-01-12T12:24:19+00:00")));
assertThat(payment.getUpdatedAt(), equalTo(parseDateTime("2014-01-12T12:24:19+00:00")));
}
@Test
public void testTransactions() throws Exception {
Transactions transactions = readJson(Transactions.class);
assertThat(transactions.getPagination(), not(nullValue()));
List<Transaction> txs = transactions.getTransactions();
assertThat(txs, hasSize(1));
Transaction tx = txs.iterator().next();
assertThat(tx.getId(), equalTo("c5a990eb-d4d7-482f-bfb1-695261fb1e4d"));
assertThat(tx.getBalanceId(), equalTo("c5f1f54e-d6d8-4140-8110-f5b99bbc80c3"));
assertThat(tx.getAccountId(), equalTo("7b9757a8-eee9-4572-86e6-77f4d711eaa6"));
assertThat(tx.getCurrency(), equalTo("USD"));
assertThat(tx.getAmount(), equalTo(new BigDecimal("1000.00")));
assertThat(tx.getBalanceAmount(), equalTo(new BigDecimal("2000.00")));
assertThat(tx.getType(), equalTo("credit"));
assertThat(tx.getAction(), equalTo("conversion"));
assertThat(tx.getRelatedEntityType(), equalTo("conversion"));
assertThat(tx.getRelatedEntityId(), equalTo("e93e322f-93aa-4d31-b050-449da723db0b"));
assertThat(tx.getRelatedEntityShortReference(), equalTo("140416-GGJBNQ001"));
assertThat(tx.getStatus(), equalTo("completed"));
assertThat(tx.getReason(), equalTo("Reason for Transaction"));
assertThat(tx.getSettlesAt(), equalTo(parseDateTime("2014-01-12T12:24:19+00:00")));
assertThat(tx.getCreatedAt(), equalTo(parseDateTime("2014-01-12T12:24:19+00:00")));
assertThat(tx.getUpdatedAt(), equalTo(parseDateTime("2014-01-12T12:24:19+00:00")));
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test
public void testException() throws Exception {
ResponseException ex = readJson(ResponseException.class);
assertThat(ex.getErrorCode(), equalTo("account_create_failed"));
Map<String, List<ErrorMessage>> messages = ex.getErrorMessages();
assertThat(messages, aMapWithSize(3));
List<ErrorMessage> legalEntityType = messages.get("legal_entity_type");
assertThat(legalEntityType, hasSize(2));
ErrorMessage range = legalEntityType.get(1);
assertThat(range.getCode(), CoreMatchers.equalTo("legal_entity_type_not_in_range"));
assertThat(range.getParams(), aMapWithSize(1));
assertThat(range.getParams(), hasEntry("range", (Object)"individual, company"));
}
@Test
public void testBeneficiary() throws Exception {
Beneficiary beneficiary = readJson(Beneficiary.class);
assertThat(beneficiary.getBeneficiaryAddress(), equalTo(Collections.singletonList("London, UK")));
assertThat(beneficiary.getBankAddress(), equalTo(Arrays.asList("KAISERSTRASSE 16", "60261 FRANKFURT AM MAIN")));
}
public static <T> T readJson(Class<T> type) throws java.io.IOException {
URL jsonUrl = DeserialisationTest.class.getResource(String.format("/json/%s.json", type.getSimpleName()));
return new ObjectMapper().readValue(jsonUrl, type);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/Reauthenticator.java<|end_filename|>
package com.currencycloud.client;
import com.currencycloud.client.exception.AuthenticationException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
class Reauthenticator extends AuthenticateInterceptor {
Reauthenticator(CurrencyCloudClient client) {
super(client);
}
@Override
public Object aroundInvoke(InvocationHandler invocationHandler, Object proxy, Method method, Object[] args)
throws Throwable {
int reattemptsLeft = mayAutoAuthenticate(method) ? 2 : 0;
do {
try {
log.trace("Attempting {}; will retry {} times after this.", method.getName(), reattemptsLeft);
replaceAuthToken(method, args);
return invocationHandler.invoke(proxy, method, args);
} catch (AuthenticationException e) {
log.info( "Attempt at {} failed with {}", method.getName(), e.toString());
if (reattemptsLeft-- <= 0) {
throw e;
}
log.info("Reauthenticating.");
client.authenticate();
log.trace("client.authToken = {}", client.getAuthToken());
}
} while (true);
}
}
<|start_filename|>src/test/java/com/currencycloud/client/UtilsTest.java<|end_filename|>
package com.currencycloud.client;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
public class UtilsTest {
@Test
public void returnsRootCauseForChain() throws Exception {
NullPointerException root = new NullPointerException();
assertThat(
Utils.getRootCause(new RuntimeException(new IllegalArgumentException(root))),
equalTo((Throwable) root)
);
}
@Test
public void returnsRootCauseForCauseless() throws Exception {
RuntimeException e = new RuntimeException();
assertThat(Utils.getRootCause(e), equalTo((Throwable)e));
}
}
<|start_filename|>src/main/java/com/currencycloud/client/dirty/ModifiedValueProvider.java<|end_filename|>
package com.currencycloud.client.dirty;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class ModifiedValueProvider implements MethodInterceptor {
private Map<String, Object> properties = new HashMap<>();
public ModifiedValueProvider(Map<String, Object> properties) {
this.properties = properties;
}
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
if (ReflectionUtils.isGetter(method)) {
return properties.get(ReflectionUtils.getPropertyFromGetter(method));
} else {
return proxy.invokeSuper(obj, args);
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentFees.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentFees {
@JsonProperty("payment_fees")
private List<PaymentFee> paymentFees;
public List<PaymentFee> getPaymentFees() {
return paymentFees;
}
public void setPaymentFees(List<PaymentFee> paymentFees) {
this.paymentFees = paymentFees;
}
@Override
public String toString() {
return String.format("{\"payment_fees\":%s}", paymentFees);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/dirty/ReflectionUtils.java<|end_filename|>
package com.currencycloud.client.dirty;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
public class ReflectionUtils {
public static boolean isSetter(Method method) {
return method.getName().startsWith("set")
&& method.getName().length() > 3
&& method.getParameterTypes().length == 1
&& method.getReturnType().equals(Void.TYPE);
}
public static boolean isGetter(Method method) {
return method.getName().startsWith("get")
&& method.getName().length() > 3
&& method.getParameterTypes().length == 0
&& !method.getReturnType().equals(Void.TYPE);
}
@Nullable
public static String getPropertyFromSetter(Method method) {
if (!isSetter(method)) {
return null;
}
char[] chars = method.getName().substring(3).toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
@Nullable
public static String getPropertyFromGetter(Method method) {
if (!isGetter(method)) {
return null;
}
char[] chars = method.getName().substring(3).toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
return new String(chars);
}
public static Method getGetterFromProperty(Class<?> clazz, String property)
throws NoSuchMethodException {
char[] chars = property.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
return clazz.getMethod("get" + new String(chars));
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Payer.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.currencycloud.client.dirty.DirtyWatcherDeserializer;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.*;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonDeserialize(converter = DirtyWatcherDeserializer.Payer.class)
public class Payer implements Entity {
private String id;
private String legalEntityType;
private String companyName;
private String firstName;
private String lastName;
private List<String> address = new ArrayList<>();
private String city;
private String stateOrProvince;
private String country;
private String identificationType;
private String identificationValue;
private String postcode;
private Date dateOfBirth;
private Date createdAt;
private Date updatedAt;
protected Payer() { }
private Payer(String entityType,
String companyName,
String firstName,
String lastName,
List<String> address,
String city,
String country,
String postcode,
String stateOrProvince,
Date dateOfBirth,
String identificationType,
String identificationValue
) {
this.legalEntityType = entityType;
this.companyName = companyName;
this.firstName = firstName;
this.lastName = lastName;
this.country = country;
this.city = city;
this.address = address;
this.postcode = postcode;
this.stateOrProvince = stateOrProvince;
this.dateOfBirth = dateOfBirth;
this.identificationType = identificationType;
this.identificationValue = identificationValue;
}
public static Payer create() {
return new Payer();
}
public static Payer create(String entityType,
String companyName,
String firstName,
String lastName,
List<String> address,
String city,
String country,
String postcode,
String stateOrProvince,
Date dateOfBirth,
String identificationType,
String identificationValue
) {
return new Payer(entityType,
companyName,
firstName,
lastName,
address,
city,
country,
postcode,
stateOrProvince,
dateOfBirth,
identificationType,
identificationValue
);
}
/**
* Create payer with minimum set of required attributes
* @param entityType
* @param companyName
* @param firstName
* @param lastName
* @param address
* @param city
* @param country
* @param dateOfBirth
*/
public static Payer create(String entityType,
String companyName,
String firstName,
String lastName,
List<String> address,
String city,
String country,
Date dateOfBirth
) {
return new Payer(entityType,
companyName,
firstName,
lastName,
address,
city,
country,
null,
null,
dateOfBirth,
null,
null
);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLegalEntityType() {
return legalEntityType;
}
public void setLegalEntityType(String legalEntityType) {
this.legalEntityType = legalEntityType;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<String> getAddress() {
return address;
}
public void setAddress(List<String> address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStateOrProvince() {
return stateOrProvince;
}
public void setStateOrProvince(String stateOrProvince) {
this.stateOrProvince = stateOrProvince;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getIdentificationType() {
return identificationType;
}
public void setIdentificationType(String identificationType) {
this.identificationType = identificationType;
}
public String getIdentificationValue() {
return identificationValue;
}
public void setIdentificationValue(String identificationValue) {
this.identificationValue = identificationValue;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("legalEntityType", legalEntityType);
map.put("companyName", companyName);
map.put("firstName", firstName);
map.put("lastName", lastName);
map.put("address", address);
map.put("city", city);
map.put("stateOrProvince", stateOrProvince);
map.put("country", country);
map.put("identificationType", identificationType);
map.put("identificationValue", identificationValue);
map.put("postcode", postcode);
map.put("dateOfBirth", dateOfBirth);
map.put("createdAt", createdAt);
map.put("updatedAt", updatedAt);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/exception/UnexpectedException.java<|end_filename|>
package com.currencycloud.client.exception;
import com.currencycloud.client.Utils;
/** Thrown when an unhandled error occurs. */
public class UnexpectedException extends CurrencyCloudException {
public UnexpectedException(String message, Throwable cause) {
super(message, cause);
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public String getInnerError() {
Throwable cause = super.getCause();
return cause == null ? null : Utils.getRootCause(cause).toString();
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ConversionDateChangeDetails.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ConversionDateChangeDetails implements Entity {
private String id;
private Date initialValueDate;
private Date currentValueDate;
private Date initialDeliveryDate;
private Date currentDeliveryDate;
private BigDecimal totalProfitAndLoss;
private String floatingCurrency;
@JsonProperty("changes")
private List<DateChange> dateChanges;
protected ConversionDateChangeDetails() {
this.dateChanges = new ArrayList<>();
}
private ConversionDateChangeDetails(String id) {
this.id = id;
this.dateChanges = new ArrayList<>();
}
public static ConversionDateChangeDetails create() {
return new ConversionDateChangeDetails();
}
public static ConversionDateChangeDetails create(String id) {
return new ConversionDateChangeDetails(id);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getInitialValueDate() {
return initialValueDate;
}
public void setInitialValueDate(Date initialValueDate) {
this.initialValueDate = initialValueDate;
}
public Date getCurrentValueDate() {
return currentValueDate;
}
public void setCurrentValueDate(Date currentValueDate) {
this.currentValueDate = currentValueDate;
}
public Date getInitialDeliveryDate() {
return initialDeliveryDate;
}
public void setInitialDeliveryDate(Date initialDeliveryDate) {
this.initialDeliveryDate = initialDeliveryDate;
}
public Date getCurrentDeliveryDate() {
return currentDeliveryDate;
}
public void setCurrentDeliveryDate(Date currentDeliveryDate) {
this.currentDeliveryDate = currentDeliveryDate;
}
public BigDecimal getTotalProfitAndLoss() {
return totalProfitAndLoss;
}
public void setTotalProfitAndLoss(BigDecimal totalProfitAndLoss) {
this.totalProfitAndLoss = totalProfitAndLoss;
}
public String getFloatingCurrency() {
return floatingCurrency;
}
public void setFloatingCurrency(String floatingCurrency) {
this.floatingCurrency = floatingCurrency;
}
public List<DateChange> getDateChanges() {
return dateChanges;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("initialValueDate", initialValueDate);
map.put("currentValueDate", currentValueDate);
map.put("initialDeliveryDate", initialDeliveryDate);
map.put("currentDeliveryDate", currentDeliveryDate);
map.put("totalProfitAndLoss", totalProfitAndLoss);
map.put("floatingCurrency", floatingCurrency);
map.put("dateChanges", dateChanges);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class DateChange {
private Date requestedValueDate;
private Date newValueDate;
private Date newDeliveryDate;
private BigDecimal profitAndLoss;
private BigDecimal adminFee;
private String type;
private String status;
private DateChange() { }
public Date getRequestedValueDate() {
return requestedValueDate;
}
public void setRequestedValueDate(Date requestedValueDate) {
this.requestedValueDate = requestedValueDate;
}
public Date getNewValueDate() {
return newValueDate;
}
public void setNewValueDate(Date newValueDate) {
this.newValueDate = newValueDate;
}
public Date getNewDeliveryDate() {
return newDeliveryDate;
}
public void setNewDeliveryDate(Date newDeliveryDate) {
this.newDeliveryDate = newDeliveryDate;
}
public BigDecimal getProfitAndLoss() {
return profitAndLoss;
}
public void setProfitAndLoss(BigDecimal profitAndLoss) {
this.profitAndLoss = profitAndLoss;
}
public BigDecimal getAdminFee() {
return adminFee;
}
public void setAdminFee(BigDecimal adminFee) {
this.adminFee = adminFee;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("requestedValueDate", requestedValueDate);
map.put("newValueDate", newValueDate);
map.put("newDeliveryDate", newDeliveryDate);
map.put("profitAndLoss", profitAndLoss);
map.put("adminFee", adminFee);
map.put("type", type);
map.put("status", status);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Transactions.java<|end_filename|>
package com.currencycloud.client.model;
import java.util.List;
public class Transactions extends PaginatedData {
private List<Transaction> transactions;
public List<Transaction> getTransactions() {
return transactions;
}
@Override
public String toString() {
return String.format("{\"transactions\":%s, \"pagination\":%s}", transactions, pagination);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentDates.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentDates {
private Date firstPaymentDate;
private Map<Date, String> invalidPaymentDates;
public Date getFirstPaymentDate() {
return firstPaymentDate;
}
public Map<Date, String> getInvalidPaymentDates() {
return invalidPaymentDates;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("firstPaymentDate", firstPaymentDate);
map.put("invalidPaymentDates", invalidPaymentDates);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Accounts.java<|end_filename|>
package com.currencycloud.client.model;
import java.util.List;
public class Accounts extends PaginatedData {
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
@Override
public String toString() {
return String.format("{\"accounts\":%s, \"pagination\":%s}", accounts, pagination);
}
}
<|start_filename|>src/test/resources/json/Beneficiary.json<|end_filename|>
{
"id": "5d38d2e3-c634-4e9c-9fcc-4331063e21f8",
"bank_account_holder_name": "Acme GmbH",
"name": "<NAME>",
"email": null,
"payment_types": [
"regular"
],
"beneficiary_address": [
"London, UK"
],
"beneficiary_country": "DE",
"beneficiary_entity_type": null,
"beneficiary_company_name": null,
"beneficiary_first_name": null,
"beneficiary_last_name": null,
"beneficiary_city": null,
"beneficiary_postcode": null,
"beneficiary_state_or_province": null,
"beneficiary_date_of_birth": null,
"beneficiary_identification_type": null,
"beneficiary_identification_value": null,
"bank_country": "DE",
"bank_name": "COMMERZBANK AG",
"bank_account_type": null,
"currency": "EUR",
"account_number": null,
"routing_code_type_1": null,
"routing_code_value_1": null,
"routing_code_type_2": null,
"routing_code_value_2": null,
"bic_swift": "COBADEFF",
"iban": "DE89370400440532013000",
"default_beneficiary": "false",
"creator_contact_id": "fdc9d10e-3265-4af0-ac5d-d8313f2cfb81",
"bank_address": [
"KAISERSTRASSE 16",
"60261 FRANKFURT AM MAIN"
],
"created_at": "2015-05-25T12:08:51+00:00",
"updated_at": "2015-05-25T12:08:51+00:00"
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ResponseException.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import si.mazi.rescu.HttpResponseAware;
import si.mazi.rescu.HttpStatusExceptionSupport;
import si.mazi.rescu.InvocationAware;
import si.mazi.rescu.RestInvocation;
import java.util.List;
import java.util.Map;
/**
* ResponseException instances are created and populated by the rescu library: When the HTTP response code
* differs from 200, the response body json is interpreted as a ResponseException.
*
* Note that this works because ResponseException is declared on the HTTP API interface methods
* ({@link com.currencycloud.client.CurrencyCloud}), and it is mapped to json using Jackson annotations.
*/
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class ResponseException extends HttpStatusExceptionSupport implements InvocationAware, HttpResponseAware {
private String errorCode;
private Map<String, List<ErrorMessage>> errorMessages;
private RestInvocation invocation;
private Map<String, List<String>> headers;
public String getErrorCode() {
return errorCode;
}
/**
* A map of error messages where the key is the field/parameter whose value cause the error, and the value
* contains the error message details.
*
* @see ErrorMessage
*/
public Map<String, List<ErrorMessage>> getErrorMessages() {
return errorMessages;
}
@Override
public void setInvocation(RestInvocation invocation) {
this.invocation = invocation;
}
public RestInvocation getInvocation() {
return invocation;
}
@Override
public void setResponseHeaders(Map<String, List<String>> headers) {
this.headers = headers;
}
@Override
public Map<String, List<String>> getResponseHeaders() {
return headers;
}
@Override
public String toString() {
return String.format("ResponseException{errorCode='%s', errorMessages=%s}", errorCode, errorMessages);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/Balance.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Balance implements Entity {
private String id;
private String accountId;
private String currency;
private BigDecimal amount;
private Date createdAt;
private Date updatedAt;
private BigDecimal amountFrom;
private BigDecimal amountTo;
private Date asAtDate;
private String scope;
protected Balance() { }
public static Balance create() {
return new Balance();
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public BigDecimal getAmountFrom() {
return amountFrom;
}
public void setAmountFrom(BigDecimal amountFrom) {
this.amountFrom = amountFrom;
}
public BigDecimal getAmountTo() {
return amountTo;
}
public void setAmountTo(BigDecimal amountTo) {
this.amountTo = amountTo;
}
public Date getAsAtDate() {
return asAtDate;
}
public void setAsAtDate(Date asAtDate) {
this.asAtDate = asAtDate;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("accountId", accountId);
map.put("currency", currency);
map.put("amount", amount);
map.put("createdAt", createdAt);
map.put("updatedAt", updatedAt);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/exception/AuthenticationException.java<|end_filename|>
package com.currencycloud.client.exception;
import com.currencycloud.client.model.ResponseException;
/** Thrown when a 401 HTTP response is returned. */
public class AuthenticationException extends ApiException {
protected AuthenticationException(ResponseException e) {
super(e);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/FundingAccount.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class FundingAccount implements Entity {
private String id;
private String accountId;
private String accountNumber;
private String accountNumberType;
private String accountHolderName;
private String bankName;
private String bankAddress;
private String bankCountry;
private String currency;
private String paymentType;
private String routingCode;
private String routingCodeType;
private Date createdAt;
private Date updatedAt;
protected FundingAccount() {
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountNumberType() {
return accountNumberType;
}
public void setAccountNumberType(String accountNumberType) {
this.accountNumberType = accountNumberType;
}
public String getAccountHolderName() {
return accountHolderName;
}
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getBankAddress() {
return bankAddress;
}
public void setBankAddress(String bankAddress) {
this.bankAddress = bankAddress;
}
public String getBankCountry() {
return bankCountry;
}
public void setBankCountry(String bankCountry) {
this.bankCountry = bankCountry;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getRoutingCode() {
return routingCode;
}
public void setRoutingCode(String routingCode) {
this.routingCode = routingCode;
}
public String getRoutingCodeType() {
return routingCodeType;
}
public void setRoutingCodeType(String routingCodeType) {
this.routingCodeType = routingCodeType;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("accountId", accountId);
map.put("accountNumber", accountNumber);
map.put("accountNumberTYpe", accountNumberType);
map.put("accountHolderName", accountHolderName);
map.put("bankName", bankName);
map.put("bankAddress", bankAddress);
map.put("bankCountry", bankCountry);
map.put("currency", currency);
map.put("paymentType", paymentType);
map.put("routingCode", routingCode);
map.put("routingCodeType", routingCodeType);
map.put("createdAt", createdAt);
map.put("updatedAt", updatedAt);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ConversionDateChange.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ConversionDateChange implements Entity {
private String id;
private String conversionId;
private BigDecimal amount;
private String currency;
private Date newConversionDate;
private Date newSettlementDate;
private Date oldConversionDate;
private Date oldSettlementDate;
private Date eventDateTime;
protected ConversionDateChange() { }
private ConversionDateChange(String id, Date newSettlementDate) {
this.id = id;
this.newSettlementDate = newSettlementDate;
}
public static ConversionDateChange create() {
return new ConversionDateChange();
}
public static ConversionDateChange create(String id, Date newSettlementDate) {
return new ConversionDateChange(id, newSettlementDate);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getConversionId() {
return conversionId;
}
public void setConversionId(String conversionId) {
this.conversionId = conversionId;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Date getNewConversionDate() {
return newConversionDate;
}
public void setNewConversionDate(Date newConversionDate) {
this.newConversionDate = newConversionDate;
}
public Date getNewSettlementDate() {
return newSettlementDate;
}
public void setNewSettlementDate(Date newSettlementDate) {
this.newSettlementDate = newSettlementDate;
}
public Date getOldConversionDate() {
return oldConversionDate;
}
public void setOldConversionDate(Date oldConversionDate) {
this.oldConversionDate = oldConversionDate;
}
public Date getOldSettlementDate() {
return oldSettlementDate;
}
public void setOldSettlementDate(Date oldSettlementDate) {
this.oldSettlementDate = oldSettlementDate;
}
public Date getEventDateTime() {
return eventDateTime;
}
public void setEventDateTime(Date eventDateTime) {
this.eventDateTime = eventDateTime;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("conversionId", conversionId);
map.put("amount", amount);
map.put("currency", currency);
map.put("newConversionDate", newConversionDate);
map.put("newSettlementDate", newSettlementDate);
map.put("oldConversionDate", oldConversionDate);
map.put("oldSettlementDate", oldSettlementDate);
map.put("eventDateTime", eventDateTime);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/PaymentAuthorisations.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class PaymentAuthorisations {
@JsonProperty("authorisations")
private List<PaymentAuthorisation> paymentAuthorisations;
public List<PaymentAuthorisation> getPaymentAuthorisations() {
return paymentAuthorisations;
}
@Override
public String toString() {
return String.format("{\"authorisations\":%s}", paymentAuthorisations);
}
}
<|start_filename|>src/test/java/com/currencycloud/client/TransactionsTest.java<|end_filename|>
package com.currencycloud.client;
import co.freeside.betamax.Betamax;
import co.freeside.betamax.MatchRule;
import com.currencycloud.client.model.*;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class TransactionsTest extends BetamaxTestSupport {
private CurrencyCloudClient client;
@Before
public void prepareClient() {
client = prepareTestClient(null, null, "334cbfdb9ba9bfb6ffd499b0c6af6b12");
}
@Before
@After
public void methodName() { log.debug("------------------------- " + name.getMethodName() + " -------------------------"); }
@Test
@Betamax(tape = "can_find", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanFind() throws Exception {
Transactions transactionsData = client.findTransactions(null, null);
List<Transaction> transactions = transactionsData.getTransactions();
Transaction transaction = transactions.iterator().next();
Pagination pagination = transactionsData.getPagination();
assertThat(transactions, notNullValue());
assertThat(transactions.size(), Matchers.equalTo(pagination.getTotalEntries()));
assertThat(transactions.get(0).getId(), Matchers.equalTo("85280ea5-ba77-414b-af1f-18283d4f140c"));
assertThat(transactions.get(1).getId(), Matchers.equalTo("1d6b5786-b080-4571-87c3-5b053e519387"));
assertThat(transactions.get(2).getId(), Matchers.equalTo("70a479eb-a301-43d0-a241-5a9652e24079"));
assertThat(transaction.getId(), Matchers.equalTo("85280ea5-ba77-414b-af1f-18283d4f140c"));
assertThat(transaction.getBalanceId(), Matchers.equalTo("209ca23c-6ac3-442f-a666-aacd98b33c8b"));
assertThat(transaction.getAccountId(), Matchers.equalTo("72970a7c-7921-431c-b95f-3438724ba16f"));
assertThat(transaction.getCurrency(), Matchers.equalTo("USD"));
assertThat(transaction.getAmount(), Matchers.equalTo(new BigDecimal("100000.00")));
assertThat(transaction.getBalanceAmount(), Matchers.equalTo(new BigDecimal("100000.00")));
assertThat(transaction.getType(), equalTo("credit"));
assertThat(transaction.getRelatedEntityType(), equalTo("inbound_funds"));
assertThat(transaction.getRelatedEntityId(), equalTo("85ab4e71-5a94-48eb-8ce6-9b829e102195"));
assertThat(transaction.getRelatedEntityShortReference(), is(emptyOrNullString()));
assertThat(transaction.getStatus(), equalTo("completed"));
assertThat(transaction.getReason(), is(emptyOrNullString()));
assertThat(transaction.getSettlesAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(transaction.getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(transaction.getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(transaction.getCompletedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(transaction.getAction(), equalTo("funding"));
assertThat(pagination.getPerPage(), Matchers.equalTo(25));
assertThat(pagination.getOrder(), Matchers.equalTo("default"));
assertThat(pagination.getTotalEntries(), Matchers.equalTo(3));
assertThat(pagination.getCurrentPage(), Matchers.equalTo(1));
assertThat(pagination.getNextPage(), Matchers.equalTo(-1));
assertThat(pagination.getPreviousPage(), Matchers.equalTo(-1));
}
@Test
@Betamax(tape = "can_retrieve", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanRetrieve() throws Exception {
Transaction transaction = client.retrieveTransaction("85280ea5-ba77-414b-af1f-18283d4f140c");
assertThat(transaction.getId(), equalTo("85280ea5-ba77-414b-af1f-18283d4f140c"));
assertThat(transaction.getBalanceId(), equalTo("209ca23c-6ac3-442f-a666-aacd98b33c8b"));
assertThat(transaction.getAccountId(), equalTo("72970a7c-7921-431c-b95f-3438724ba16f"));
assertThat(transaction.getCurrency(), equalTo("USD"));
assertThat(transaction.getAmount(), equalTo(new BigDecimal("100000.00")));
assertThat(transaction.getBalanceAmount(), equalTo(new BigDecimal("100000.00")));
assertThat(transaction.getType(), equalTo("credit"));
assertThat(transaction.getRelatedEntityType(), equalTo("inbound_funds"));
assertThat(transaction.getRelatedEntityId(), equalTo("85ab4e71-5a94-48eb-8ce6-9b829e102195"));
assertThat(transaction.getRelatedEntityShortReference(), is(emptyOrNullString()));
assertThat(transaction.getStatus(), equalTo("completed"));
assertThat(transaction.getReason(), is(emptyOrNullString()));
assertThat(transaction.getSettlesAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(transaction.getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(transaction.getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(transaction.getCompletedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(transaction.getAction(), equalTo("funding"));
}
@Test
@Betamax(tape = "can_retrieve_sender_details", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanRetrieveSenderDetails() throws Exception {
SenderDetails details = client.retrieveSenderDetails("e68301d3-5b04-4c1d-8f8b-13a9b8437040");
assertThat(details.getId(), equalTo("e68301d3-5b04-4c1d-8f8b-13a9b8437040"));
assertThat(details.getAmount(), equalTo(new BigDecimal("1701.51")));
assertThat(details.getCurrency(), equalTo("EUR"));
assertThat(details.getAdditionalInformation(), equalTo("USTRD-0001"));
assertThat(details.getValueDate(), equalTo(parseDateTime("2018-07-04T00:00:00+00:00")));
assertThat(details.getSender(), equalTo("FR7615589290001234567890113, CMBRFR2BARK, Debtor, FR, Centre ville"));
assertThat(details.getReceivingAccountNumber(), is(emptyOrNullString()));
assertThat(details.getReceivingAccountIban(), equalTo("GB99OXPH94665099600083"));
assertThat(details.getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(details.getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
}
}
<|start_filename|>src/test/java/com/currencycloud/client/ReportingTest.java<|end_filename|>
package com.currencycloud.client;
import co.freeside.betamax.Betamax;
import co.freeside.betamax.MatchRule;
import com.currencycloud.client.model.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
public class ReportingTest extends BetamaxTestSupport {
private CurrencyCloudClient client;
@Before
public void prepareClient() {
client = prepareTestClient(null, null, "334cbfdb9ba9bfb6ffd499b0c6af6b12");
}
@Before
@After
public void methodName() { log.debug("------------------------- " + name.getMethodName() + " -------------------------"); }
@Test
@Betamax(tape = "can_generate_conversion_report", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanGenerateConversionReport() throws Exception {
ConversionReport conversionReport = ConversionReport.create();
conversionReport.setDescription("Conversion test report");
conversionReport.setBuyCurrency("CAD");
conversionReport.setSellCurrency("GBP");
conversionReport.setUniqueRequestId("46aca410-ce74-4303-8f79-e0e95cfd9262");
ConversionReport report = client.createConversionReport(conversionReport);
assertThat(report.getId(), equalTo("de5c215d-93e2-4b24-bdc8-bffbcd80c60f"));
assertThat(report.getShortReference(), equalTo("RP-3934236-BZCXEW"));
assertThat(report.getContactId(), equalTo("590cea0d-0daa-48dc-882b-049107c1471f"));
assertThat(report.getDescription(),equalTo("Conversion test report"));
assertThat(report.getReportUrl(), emptyOrNullString());
assertThat(report.getSearchParams().getBuyCurrency(), equalTo("CAD"));
assertThat(report.getSearchParams().getSellCurrency(), equalTo("GBP"));
assertThat(report.getSearchParams().getUniqueRequestId(), equalTo("46aca410-ce74-4303-8f79-e0e95cfd9262"));
assertThat(report.getSearchParams().getScope(), equalTo("own"));
assertThat(report.getReportType(), equalTo("conversion"));
assertThat(report.getAccountId(), equalTo("<KEY>"));
assertThat(report.getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(report.getFailureReason(), emptyOrNullString());
assertThat(report.getStatus(), equalTo("processing"));
assertThat(report.getExpirationDate(), nullValue());
assertThat(report.getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
}
@Test
@Betamax(tape = "can_generate_payment_report", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanGeneratePaymentReport() throws Exception {
PaymentReport paymentReport = PaymentReport.create();
paymentReport.setDescription("Payment test report");
paymentReport.setCurrency("EUR");
paymentReport.setUniqueRequestId("94985dc8-1df3-4f8a-ba23-d00cf284708d");
paymentReport.setAmountFrom(new BigDecimal("0.00"));
paymentReport.setAmountTo(new BigDecimal("99999.99"));
paymentReport.setCreatedAtFrom(new GregorianCalendar(2018, Calendar.JANUARY, 1).getTime());
paymentReport.setCreatedAtTo(new GregorianCalendar(2018, Calendar.DECEMBER, 31).getTime());
PaymentReport report = client.createPaymentReport(paymentReport);
assertThat(report.getId(), equalTo("39a0ebd1-13b3-4d38-a196-745e5944f169"));
assertThat(report.getShortReference(), equalTo("RP-6846174-EQFOHU"));
assertThat(report.getContactId(), equalTo("590cea0d-0daa-48dc-882b-049107c1471f"));
assertThat(report.getDescription(),equalTo("Payment test report"));
assertThat(report.getReportUrl(), emptyOrNullString());
assertThat(report.getSearchParams().getCurrency(), equalTo("EUR"));
assertThat(report.getSearchParams().getAmountFrom(), equalTo(new BigDecimal("0.00")));
assertThat(report.getSearchParams().getAmountTo(), equalTo(new BigDecimal("99999.99")));
assertThat(report.getSearchParams().getCreatedAtFrom(), equalTo(parseDate("2018-01-01")));
assertThat(report.getSearchParams().getCreatedAtTo(), equalTo(parseDate("2018-12-31")));
assertThat(report.getSearchParams().getScope(), equalTo("own"));
assertThat(report.getSearchParams().getUniqueRequestId(), equalTo("94985dc8-1df3-4f8a-ba23-d00cf284708d"));
assertThat(report.getReportType(), equalTo("payment"));
assertThat(report.getAccountId(), equalTo("<KEY>"));
assertThat(report.getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(report.getFailureReason(), emptyOrNullString());
assertThat(report.getStatus(), equalTo("processing"));
assertThat(report.getExpirationDate(), nullValue());
assertThat(report.getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
}
@Test
@Betamax(tape = "can_find", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanFindReportRequests() throws Exception {
ReportRequests reportRequestsData = client.findReportRequests(null, null);
List<ReportRequest> reports = reportRequestsData.getReportRequests();
Pagination pagination = reportRequestsData.getPagination();
System.out.println("TEST: " + reportRequestsData.toString());
assertThat(reports, not(nullValue()));
assertThat(pagination.getTotalEntries(), equalTo(reports.size()));
assertThat(reports.size(), is(2));
assertThat(reports.get(0).getId(), equalTo("de5c215d-93e2-4b24-bdc8-bffbcd80c60f"));
assertThat(reports.get(0).getShortReference(), equalTo("RP-3934236-BZCXEW"));
assertThat(reports.get(0).getContactId(), equalTo("590cea0d-0daa-48dc-882b-049107c1471f"));
assertThat(reports.get(0).getDescription(),equalTo("Conversion test report"));
assertThat(reports.get(0).getReportUrl(), not(emptyOrNullString()));
assertThat(reports.get(0).getSearchParams().getBuyCurrency(), equalTo("CAD"));
assertThat(reports.get(0).getSearchParams().getSellCurrency(), equalTo("GBP"));
assertThat(reports.get(0).getSearchParams().getUniqueRequestId(), equalTo("46aca410-ce74-4303-8f79-e0e95cfd9262"));
assertThat(reports.get(0).getSearchParams().getScope(), equalTo("own"));
assertThat(reports.get(0).getReportType(), equalTo("conversion"));
assertThat(reports.get(0).getAccountId(), equalTo("e277c9f9-679f-454f-8367-274b3ff977ff"));
assertThat(reports.get(0).getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(reports.get(0).getFailureReason(), emptyOrNullString());
assertThat(reports.get(0).getStatus(), equalTo("completed"));
assertThat(reports.get(0).getExpirationDate(), equalTo(parseDate("2018-01-31")));
assertThat(reports.get(0).getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(reports.get(1).getId(), equalTo("39a0ebd1-13b3-4d38-a196-745e5944f169"));
assertThat(reports.get(1).getShortReference(), equalTo("RP-6846174-EQFOHU"));
assertThat(reports.get(1).getContactId(), equalTo("590cea0d-0daa-48dc-882b-049107c1471f"));
assertThat(reports.get(1).getDescription(),equalTo("Payment test report"));
assertThat(reports.get(1).getReportUrl(), not(emptyOrNullString()));
assertThat(reports.get(1).getSearchParams().getCurrency(), equalTo("EUR"));
assertThat(reports.get(1).getSearchParams().getAmountFrom(), equalTo(new BigDecimal("0.00")));
assertThat(reports.get(1).getSearchParams().getAmountTo(), equalTo(new BigDecimal("99999.99")));
assertThat(reports.get(1).getSearchParams().getCreatedAtFrom(), equalTo(parseDate("2018-01-01")));
assertThat(reports.get(1).getSearchParams().getCreatedAtTo(), equalTo(parseDate("2018-12-31")));
assertThat(reports.get(1).getSearchParams().getScope(), equalTo("own"));
assertThat(reports.get(1).getSearchParams().getUniqueRequestId(), equalTo("94985dc8-1df3-4f8a-ba23-d00cf284708d"));
assertThat(reports.get(1).getReportType(), equalTo("payment"));
assertThat(reports.get(1).getAccountId(), equalTo("e277c9f9-679f-454f-8367-274b3ff977ff"));
assertThat(reports.get(1).getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(reports.get(1).getFailureReason(), emptyOrNullString());
assertThat(reports.get(1).getStatus(), equalTo("completed"));
assertThat(reports.get(1).getExpirationDate(), equalTo(parseDate("2018-01-31")));
assertThat(reports.get(1).getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
}
@Test
@Betamax(tape = "can_retrieve", match = {MatchRule.method, MatchRule.uri, MatchRule.body})
public void testCanRetrieveReportRequest() throws Exception {
ReportRequest report = client.retrieveReportRequests("de5c215d-93e2-4b24-bdc8-bffbcd80c60f");
assertThat(report.getId(), equalTo("de5c215d-93e2-4b24-bdc8-bffbcd80c60f"));
assertThat(report.getShortReference(), equalTo("RP-3934236-BZCXEW"));
assertThat(report.getContactId(), equalTo("590cea0d-0daa-48dc-882b-049107c1471f"));
assertThat(report.getDescription(),equalTo("Conversion test report"));
assertThat(report.getReportUrl(), not(emptyOrNullString()));
assertThat(report.getSearchParams().getBuyCurrency(), equalTo("CAD"));
assertThat(report.getSearchParams().getSellCurrency(), equalTo("GBP"));
assertThat(report.getSearchParams().getUniqueRequestId(), equalTo("46aca410-ce74-4303-8f79-e0e95cfd9262"));
assertThat(report.getSearchParams().getScope(), equalTo("own"));
assertThat(report.getReportType(), equalTo("conversion"));
assertThat(report.getAccountId(), equalTo("e277c9f9-679f-454f-8367-274b3ff977ff"));
assertThat(report.getCreatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
assertThat(report.getFailureReason(), emptyOrNullString());
assertThat(report.getStatus(), equalTo("completed"));
assertThat(report.getExpirationDate(), equalTo(parseDate("2018-01-31")));
assertThat(report.getUpdatedAt(), equalTo(parseDateTime("2018-01-01T12:34:56+00:00")));
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ConversionProfitAndLoss.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ConversionProfitAndLoss implements Entity {
private String id;
private String accountId;
private String contactId;
private String eventAccountId;
private String eventContactId;
private String conversionId;
private String eventType;
private BigDecimal amount;
private String currency;
private String notes;
private Date eventDateTime;
private Date eventDateTimeFrom;
private Date eventDateTimeTo;
private BigDecimal amountFrom;
private BigDecimal amountTo;
private String scope;
protected ConversionProfitAndLoss() {}
public static ConversionProfitAndLoss create() {
return new ConversionProfitAndLoss();
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getContactId() {
return contactId;
}
public void setContactId(String contactId) {
this.contactId = contactId;
}
public String getEventAccountId() {
return eventAccountId;
}
public void setEventAccountId(String eventAccountId) {
this.eventAccountId = eventAccountId;
}
public String getEventContactId() {
return eventContactId;
}
public void setEventContactId(String eventContactId) {
this.eventContactId = eventContactId;
}
public String getConversionId() {
return conversionId;
}
public void setConversionId(String conversionId) {
this.conversionId = conversionId;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Date getEventDateTime() {
return eventDateTime;
}
public void setEventDateTime(Date eventDateTime) {
this.eventDateTime = eventDateTime;
}
public Date getEventDateTimeFrom() {
return eventDateTimeFrom;
}
public void setEventDateTimeFrom(Date eventDateTimeFrom) {
this.eventDateTimeFrom = eventDateTimeFrom;
}
public Date getEventDateTimeTo() {
return eventDateTimeTo;
}
public void setEventDateTimeTo(Date eventDateTimeTo) {
this.eventDateTimeTo = eventDateTimeTo;
}
public BigDecimal getAmountFrom() {
return amountFrom;
}
public void setAmountFrom(BigDecimal amountFrom) {
this.amountFrom = amountFrom;
}
public BigDecimal getAmountTo() {
return amountTo;
}
public void setAmountTo(BigDecimal amountTo) {
this.amountTo = amountTo;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("accountId", accountId);
map.put("contactId", contactId);
map.put("eventAccountId", eventAccountId);
map.put("eventContactId", eventContactId);
map.put("conversionId", conversionId);
map.put("eventType", eventType);
map.put("amount", amount);
map.put("currency", currency);
map.put("notes", notes);
map.put("eventDateTime", eventDateTime);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/MarginBalanceTopUp.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MarginBalanceTopUp {
private String accountId;
private String currency;
private BigDecimal transferredAmount;
private Date transferCompletedAt;
public String getAccountId() {
return accountId;
}
public String getCurrency() {
return currency;
}
public BigDecimal getTransferredAmount() {
return transferredAmount;
}
public Date getTransferCompletedAt() {
return transferCompletedAt;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("accountId", accountId);
map.put("currency", currency);
map.put("transferredAmount", transferredAmount);
map.put("transferCompletedAt", transferCompletedAt);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/BeneficiaryRequiredDetails.java<|end_filename|>
package com.currencycloud.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BeneficiaryRequiredDetails {
private List<Map<String, String>> details;
public List<Map<String, String>> getDetails() {
return details;
}
@Override
public String toString() {
return String.format("{\"details\":%s}", details);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/exception/InternalApplicationException.java<|end_filename|>
package com.currencycloud.client.exception;
import com.currencycloud.client.model.ResponseException;
/** Thrown when a 500 HTTP response is returned. */
public class InternalApplicationException extends ApiException {
protected InternalApplicationException(ResponseException e) {
super(e);
}
}
<|start_filename|>src/main/java/com/currencycloud/client/model/ConversionSplitDetails.java<|end_filename|>
package com.currencycloud.client.model;
import com.currencycloud.client.Utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ConversionSplitDetails implements Entity {
private String id;
private String shortReference;
private BigDecimal sellAmount;
private String sellCurrency;
private BigDecimal buyAmount;
private String buyCurrency;
private Date settlementDate;
private Date conversionDate;
private String status;
protected ConversionSplitDetails() { }
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getShortReference() {
return shortReference;
}
public void setShortReference(String shortReference) {
this.shortReference = shortReference;
}
public BigDecimal getSellAmount() {
return sellAmount;
}
public void setSellAmount(BigDecimal sellAmount) {
this.sellAmount = sellAmount;
}
public String getSellCurrency() {
return sellCurrency;
}
public void setSellCurrency(String sellCurrency) {
this.sellCurrency = sellCurrency;
}
public BigDecimal getBuyAmount() {
return buyAmount;
}
public void setBuyAmount(BigDecimal buyAmount) {
this.buyAmount = buyAmount;
}
public String getBuyCurrency() {
return buyCurrency;
}
public void setBuyCurrency(String buyCurrency) {
this.buyCurrency = buyCurrency;
}
public Date getSettlementDate() {
return settlementDate;
}
public void setSettlementDate(Date settlementDate) {
this.settlementDate = settlementDate;
}
public Date getConversionDate() {
return conversionDate;
}
public void setConversionDate(Date conversionDate) {
this.conversionDate = conversionDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
final ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setDateFormat(new SimpleDateFormat(Utils.dateFormat));
Map<String, Object> map = new HashMap<>();
map.put("id", id);
map.put("shortReference", shortReference);
map.put("sellAmount", sellAmount);
map.put("sellCurrency", sellCurrency);
map.put("buyAmount", buyAmount);
map.put("buyCurrency", buyCurrency);
map.put("settlementDate", settlementDate);
map.put("conversionDate", conversionDate);
map.put("status", status);
try {
return objectMapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
return String.format("{\"error\": \"%s\"}", e.getMessage());
}
}
}
<|start_filename|>src/main/java/com/currencycloud/client/exception/CurrencyCloudException.java<|end_filename|>
package com.currencycloud.client.exception;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import si.mazi.rescu.InvocationAware;
import si.mazi.rescu.RestInvocation;
import javax.annotation.Nullable;
import javax.ws.rs.FormParam;
import javax.ws.rs.QueryParam;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* This is the root of the Currency Cloud Exception hierarchy. It provides some information about the
* HTTP request and the server response. The {@link #toString()} method returns YAML-formatted data.
*/
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonPropertyOrder({"exceptionType", "platform", "request", "response", "errorCode", "errors"})
public abstract class CurrencyCloudException extends RuntimeException {
private static final Logger log = LoggerFactory.getLogger(ApiException.class);
private static final YAMLFactory YAML_FACTORY = new YAMLFactory();
public static final String PLATFORM = String.format(
"Java %s (%s)",
System.getProperty("java.version"),
System.getProperty("java.vendor")
);
private static final JacksonAnnotationIntrospector IGNORE_EXCEPTION_PROPERTIES = new JacksonAnnotationIntrospector() {
@Override
public boolean hasIgnoreMarker(final AnnotatedMember m) {
Class<?> declaringClass = m.getDeclaringClass();
return declaringClass.isAssignableFrom(RuntimeException.class)
|| super.hasIgnoreMarker(m);
}
};
private Request request;
private String exceptionType;
protected CurrencyCloudException(String message, Throwable cause) {
super(message, cause);
if (cause instanceof InvocationAware) {
setInvocation(((InvocationAware)cause).getInvocation());
}
this.exceptionType = getClass().getSimpleName();
}
protected void setInvocation(@Nullable RestInvocation invocation) {
if (invocation != null) {
Map<String, String> params = new LinkedHashMap<>();
for (Class<? extends Annotation> paramAnn : Arrays.asList(FormParam.class, QueryParam.class)) {
params.putAll(invocation.getParamsMap().get(paramAnn).asHttpHeaders());
}
this.request = new Request(params, invocation.getHttpMethod(), invocation.getInvocationUrl());
}
}
public Request getRequest() {
return request;
}
/**
* @return the root type of exception that was thrown
*/
public String getExceptionType() {
return exceptionType;
}
/** @return The runtime environment of the client, eg. "Java 1.7" */
public String getPlatform() {
return PLATFORM;
}
/**
* @return YAML-formatted exception data
*/
@Override
public String toString() {
try (
StringWriter out = new StringWriter();
PrintWriter writer = new PrintWriter(out)
) {
ObjectMapper mapper = new ObjectMapper(YAML_FACTORY);
mapper.setAnnotationIntrospector(IGNORE_EXCEPTION_PROPERTIES);
mapper.writeValue(writer, this);
return out.toString();
} catch (Exception e) {
log.warn("Error formatting exception as YAML: " + e);
return super.toString();
}
}
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public static class Request {
/** The parameters that were sent in the request (GET or POST) */
public final Map<String, String> parameters;
/** The HTTP method in lowercase (get, post, ...) */
public final String verb;
/** The full URL of the request */
public final String url;
private Request(Map<String, String> parameters, String httpMethod, String url) {
this.parameters = parameters;
this.verb = httpMethod.toLowerCase();
this.url = url;
}
}
}
| romanczukrobert/currencycloud-java |
<|start_filename|>vendor/github.com/valyala/fasthttp/uri.go<|end_filename|>
package fasthttp
import (
"bytes"
"errors"
"fmt"
"io"
"strconv"
"sync"
)
// AcquireURI returns an empty URI instance from the pool.
//
// Release the URI with ReleaseURI after the URI is no longer needed.
// This allows reducing GC load.
func AcquireURI() *URI {
return uriPool.Get().(*URI)
}
// ReleaseURI releases the URI acquired via AcquireURI.
//
// The released URI mustn't be used after releasing it, otherwise data races
// may occur.
func ReleaseURI(u *URI) {
u.Reset()
uriPool.Put(u)
}
var uriPool = &sync.Pool{
New: func() interface{} {
return &URI{}
},
}
// URI represents URI :) .
//
// It is forbidden copying URI instances. Create new instance and use CopyTo
// instead.
//
// URI instance MUST NOT be used from concurrently running goroutines.
type URI struct {
noCopy noCopy //nolint:unused,structcheck
pathOriginal []byte
scheme []byte
path []byte
queryString []byte
hash []byte
host []byte
queryArgs Args
parsedQueryArgs bool
// Path values are sent as-is without normalization
//
// Disabled path normalization may be useful for proxying incoming requests
// to servers that are expecting paths to be forwarded as-is.
//
// By default path values are normalized, i.e.
// extra slashes are removed, special characters are encoded.
DisablePathNormalizing bool
fullURI []byte
requestURI []byte
username []byte
password []byte
}
// CopyTo copies uri contents to dst.
func (u *URI) CopyTo(dst *URI) {
dst.Reset()
dst.pathOriginal = append(dst.pathOriginal[:0], u.pathOriginal...)
dst.scheme = append(dst.scheme[:0], u.scheme...)
dst.path = append(dst.path[:0], u.path...)
dst.queryString = append(dst.queryString[:0], u.queryString...)
dst.hash = append(dst.hash[:0], u.hash...)
dst.host = append(dst.host[:0], u.host...)
dst.username = append(dst.username[:0], u.username...)
dst.password = append(dst.password[:0], u.password...)
u.queryArgs.CopyTo(&dst.queryArgs)
dst.parsedQueryArgs = u.parsedQueryArgs
dst.DisablePathNormalizing = u.DisablePathNormalizing
// fullURI and requestURI shouldn't be copied, since they are created
// from scratch on each FullURI() and RequestURI() call.
}
// Hash returns URI hash, i.e. qwe of http://aaa.com/foo/bar?baz=123#qwe .
//
// The returned bytes are valid until the next URI method call.
func (u *URI) Hash() []byte {
return u.hash
}
// SetHash sets URI hash.
func (u *URI) SetHash(hash string) {
u.hash = append(u.hash[:0], hash...)
}
// SetHashBytes sets URI hash.
func (u *URI) SetHashBytes(hash []byte) {
u.hash = append(u.hash[:0], hash...)
}
// Username returns URI username
//
// The returned bytes are valid until the next URI method call.
func (u *URI) Username() []byte {
return u.username
}
// SetUsername sets URI username.
func (u *URI) SetUsername(username string) {
u.username = append(u.username[:0], username...)
}
// SetUsernameBytes sets URI username.
func (u *URI) SetUsernameBytes(username []byte) {
u.username = append(u.username[:0], username...)
}
// Password returns URI password
//
// The returned bytes are valid until the next URI method call.
func (u *URI) Password() []byte {
return u.password
}
// SetPassword sets URI password.
func (u *URI) SetPassword(password string) {
u.password = append(u.password[:0], password...)
}
// SetPasswordBytes sets URI password.
func (u *URI) SetPasswordBytes(password []byte) {
u.password = append(u.password[:0], password...)
}
// QueryString returns URI query string,
// i.e. baz=123 of http://aaa.com/foo/bar?baz=123#qwe .
//
// The returned bytes are valid until the next URI method call.
func (u *URI) QueryString() []byte {
return u.queryString
}
// SetQueryString sets URI query string.
func (u *URI) SetQueryString(queryString string) {
u.queryString = append(u.queryString[:0], queryString...)
u.parsedQueryArgs = false
}
// SetQueryStringBytes sets URI query string.
func (u *URI) SetQueryStringBytes(queryString []byte) {
u.queryString = append(u.queryString[:0], queryString...)
u.parsedQueryArgs = false
}
// Path returns URI path, i.e. /foo/bar of http://aaa.com/foo/bar?baz=123#qwe .
//
// The returned path is always urldecoded and normalized,
// i.e. '//f%20obar/baz/../zzz' becomes '/f obar/zzz'.
//
// The returned bytes are valid until the next URI method call.
func (u *URI) Path() []byte {
path := u.path
if len(path) == 0 {
path = strSlash
}
return path
}
// SetPath sets URI path.
func (u *URI) SetPath(path string) {
u.pathOriginal = append(u.pathOriginal[:0], path...)
u.path = normalizePath(u.path, u.pathOriginal)
}
// SetPathBytes sets URI path.
func (u *URI) SetPathBytes(path []byte) {
u.pathOriginal = append(u.pathOriginal[:0], path...)
u.path = normalizePath(u.path, u.pathOriginal)
}
// PathOriginal returns the original path from requestURI passed to URI.Parse().
//
// The returned bytes are valid until the next URI method call.
func (u *URI) PathOriginal() []byte {
return u.pathOriginal
}
// Scheme returns URI scheme, i.e. http of http://aaa.com/foo/bar?baz=123#qwe .
//
// Returned scheme is always lowercased.
//
// The returned bytes are valid until the next URI method call.
func (u *URI) Scheme() []byte {
scheme := u.scheme
if len(scheme) == 0 {
scheme = strHTTP
}
return scheme
}
// SetScheme sets URI scheme, i.e. http, https, ftp, etc.
func (u *URI) SetScheme(scheme string) {
u.scheme = append(u.scheme[:0], scheme...)
lowercaseBytes(u.scheme)
}
// SetSchemeBytes sets URI scheme, i.e. http, https, ftp, etc.
func (u *URI) SetSchemeBytes(scheme []byte) {
u.scheme = append(u.scheme[:0], scheme...)
lowercaseBytes(u.scheme)
}
// Reset clears uri.
func (u *URI) Reset() {
u.pathOriginal = u.pathOriginal[:0]
u.scheme = u.scheme[:0]
u.path = u.path[:0]
u.queryString = u.queryString[:0]
u.hash = u.hash[:0]
u.username = u.username[:0]
u.password = u.password[:0]
u.host = u.host[:0]
u.queryArgs.Reset()
u.parsedQueryArgs = false
u.DisablePathNormalizing = false
// There is no need in u.fullURI = u.fullURI[:0], since full uri
// is calculated on each call to FullURI().
// There is no need in u.requestURI = u.requestURI[:0], since requestURI
// is calculated on each call to RequestURI().
}
// Host returns host part, i.e. aaa.com of http://aaa.com/foo/bar?baz=123#qwe .
//
// Host is always lowercased.
//
// The returned bytes are valid until the next URI method call.
func (u *URI) Host() []byte {
return u.host
}
// SetHost sets host for the uri.
func (u *URI) SetHost(host string) {
u.host = append(u.host[:0], host...)
lowercaseBytes(u.host)
}
// SetHostBytes sets host for the uri.
func (u *URI) SetHostBytes(host []byte) {
u.host = append(u.host[:0], host...)
lowercaseBytes(u.host)
}
var (
ErrorInvalidURI = errors.New("invalid uri")
)
// Parse initializes URI from the given host and uri.
//
// host may be nil. In this case uri must contain fully qualified uri,
// i.e. with scheme and host. http is assumed if scheme is omitted.
//
// uri may contain e.g. RequestURI without scheme and host if host is non-empty.
func (u *URI) Parse(host, uri []byte) error {
return u.parse(host, uri, false)
}
func (u *URI) parse(host, uri []byte, isTLS bool) error {
u.Reset()
if stringContainsCTLByte(uri) {
return ErrorInvalidURI
}
if len(host) == 0 || bytes.Contains(uri, strColonSlashSlash) {
scheme, newHost, newURI := splitHostURI(host, uri)
u.scheme = append(u.scheme, scheme...)
lowercaseBytes(u.scheme)
host = newHost
uri = newURI
}
if isTLS {
u.scheme = append(u.scheme[:0], strHTTPS...)
}
if n := bytes.IndexByte(host, '@'); n >= 0 {
auth := host[:n]
host = host[n+1:]
if n := bytes.IndexByte(auth, ':'); n >= 0 {
u.username = append(u.username[:0], auth[:n]...)
u.password = append(u.password[:0], auth[n+1:]...)
} else {
u.username = append(u.username[:0], auth...)
u.password = u.password[:0]
}
}
u.host = append(u.host, host...)
if parsedHost, err := parseHost(u.host); err != nil {
return err
} else {
u.host = parsedHost
}
lowercaseBytes(u.host)
b := uri
queryIndex := bytes.IndexByte(b, '?')
fragmentIndex := bytes.IndexByte(b, '#')
// Ignore query in fragment part
if fragmentIndex >= 0 && queryIndex > fragmentIndex {
queryIndex = -1
}
if queryIndex < 0 && fragmentIndex < 0 {
u.pathOriginal = append(u.pathOriginal, b...)
u.path = normalizePath(u.path, u.pathOriginal)
return nil
}
if queryIndex >= 0 {
// Path is everything up to the start of the query
u.pathOriginal = append(u.pathOriginal, b[:queryIndex]...)
u.path = normalizePath(u.path, u.pathOriginal)
if fragmentIndex < 0 {
u.queryString = append(u.queryString, b[queryIndex+1:]...)
} else {
u.queryString = append(u.queryString, b[queryIndex+1:fragmentIndex]...)
u.hash = append(u.hash, b[fragmentIndex+1:]...)
}
return nil
}
// fragmentIndex >= 0 && queryIndex < 0
// Path is up to the start of fragment
u.pathOriginal = append(u.pathOriginal, b[:fragmentIndex]...)
u.path = normalizePath(u.path, u.pathOriginal)
u.hash = append(u.hash, b[fragmentIndex+1:]...)
return nil
}
// parseHost parses host as an authority without user
// information. That is, as host[:port].
//
// Based on https://github.com/golang/go/blob/8ac5cbe05d61df0a7a7c9a38ff33305d4dcfea32/src/net/url/url.go#L619
//
// The host is parsed and unescaped in place overwriting the contents of the host parameter.
func parseHost(host []byte) ([]byte, error) {
if len(host) > 0 && host[0] == '[' {
// Parse an IP-Literal in RFC 3986 and RFC 6874.
// E.g., "[fe80::1]", "[fe80::1%25en0]", "[fe80::1]:80".
i := bytes.LastIndexByte(host, ']')
if i < 0 {
return nil, errors.New("missing ']' in host")
}
colonPort := host[i+1:]
if !validOptionalPort(colonPort) {
return nil, fmt.Errorf("invalid port %q after host", colonPort)
}
// RFC 6874 defines that %25 (%-encoded percent) introduces
// the zone identifier, and the zone identifier can use basically
// any %-encoding it likes. That's different from the host, which
// can only %-encode non-ASCII bytes.
// We do impose some restrictions on the zone, to avoid stupidity
// like newlines.
zone := bytes.Index(host[:i], []byte("%25"))
if zone >= 0 {
host1, err := unescape(host[:zone], encodeHost)
if err != nil {
return nil, err
}
host2, err := unescape(host[zone:i], encodeZone)
if err != nil {
return nil, err
}
host3, err := unescape(host[i:], encodeHost)
if err != nil {
return nil, err
}
return append(host1, append(host2, host3...)...), nil
}
} else if i := bytes.LastIndexByte(host, ':'); i != -1 {
colonPort := host[i:]
if !validOptionalPort(colonPort) {
return nil, fmt.Errorf("invalid port %q after host", colonPort)
}
}
var err error
if host, err = unescape(host, encodeHost); err != nil {
return nil, err
}
return host, nil
}
type encoding int
const (
encodeHost encoding = 1 + iota
encodeZone
)
type EscapeError string
func (e EscapeError) Error() string {
return "invalid URL escape " + strconv.Quote(string(e))
}
type InvalidHostError string
func (e InvalidHostError) Error() string {
return "invalid character " + strconv.Quote(string(e)) + " in host name"
}
// unescape unescapes a string; the mode specifies
// which section of the URL string is being unescaped.
//
// Based on https://github.com/golang/go/blob/8ac5cbe05d61df0a7a7c9a38ff33305d4dcfea32/src/net/url/url.go#L199
//
// Unescapes in place overwriting the contents of s and returning it.
func unescape(s []byte, mode encoding) ([]byte, error) {
// Count %, check that they're well-formed.
n := 0
for i := 0; i < len(s); {
switch s[i] {
case '%':
n++
if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
s = s[i:]
if len(s) > 3 {
s = s[:3]
}
return nil, EscapeError(s)
}
// Per https://tools.ietf.org/html/rfc3986#page-21
// in the host component %-encoding can only be used
// for non-ASCII bytes.
// But https://tools.ietf.org/html/rfc6874#section-2
// introduces %25 being allowed to escape a percent sign
// in IPv6 scoped-address literals. Yay.
if mode == encodeHost && unhex(s[i+1]) < 8 && !bytes.Equal(s[i:i+3], []byte("%25")) {
return nil, EscapeError(s[i : i+3])
}
if mode == encodeZone {
// RFC 6874 says basically "anything goes" for zone identifiers
// and that even non-ASCII can be redundantly escaped,
// but it seems prudent to restrict %-escaped bytes here to those
// that are valid host name bytes in their unescaped form.
// That is, you can use escaping in the zone identifier but not
// to introduce bytes you couldn't just write directly.
// But Windows puts spaces here! Yay.
v := unhex(s[i+1])<<4 | unhex(s[i+2])
if !bytes.Equal(s[i:i+3], []byte("%25")) && v != ' ' && shouldEscape(v, encodeHost) {
return nil, EscapeError(s[i : i+3])
}
}
i += 3
default:
if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) {
return nil, InvalidHostError(s[i : i+1])
}
i++
}
}
if n == 0 {
return s, nil
}
t := s[:0]
for i := 0; i < len(s); i++ {
switch s[i] {
case '%':
t = append(t, unhex(s[i+1])<<4|unhex(s[i+2]))
i += 2
default:
t = append(t, s[i])
}
}
return t, nil
}
// Return true if the specified character should be escaped when
// appearing in a URL string, according to RFC 3986.
//
// Please be informed that for now shouldEscape does not check all
// reserved characters correctly. See golang.org/issue/5684.
//
// Based on https://github.com/golang/go/blob/8ac5cbe05d61df0a7a7c9a38ff33305d4dcfea32/src/net/url/url.go#L100
func shouldEscape(c byte, mode encoding) bool {
// §2.3 Unreserved characters (alphanum)
if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' {
return false
}
if mode == encodeHost || mode == encodeZone {
// §3.2.2 Host allows
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
// as part of reg-name.
// We add : because we include :port as part of host.
// We add [ ] because we include [ipv6]:port as part of host.
// We add < > because they're the only characters left that
// we could possibly allow, and Parse will reject them if we
// escape them (because hosts can't use %-encoding for
// ASCII bytes).
switch c {
case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"':
return false
}
}
if c == '-' || c == '_' || c == '.' || c == '~' { // §2.3 Unreserved characters (mark)
return false
}
// Everything else must be escaped.
return true
}
func ishex(c byte) bool {
switch {
case '0' <= c && c <= '9':
return true
case 'a' <= c && c <= 'f':
return true
case 'A' <= c && c <= 'F':
return true
}
return false
}
func unhex(c byte) byte {
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
// validOptionalPort reports whether port is either an empty string
// or matches /^:\d*$/
func validOptionalPort(port []byte) bool {
if len(port) == 0 {
return true
}
if port[0] != ':' {
return false
}
for _, b := range port[1:] {
if b < '0' || b > '9' {
return false
}
}
return true
}
func normalizePath(dst, src []byte) []byte {
dst = dst[:0]
dst = addLeadingSlash(dst, src)
dst = decodeArgAppendNoPlus(dst, src)
// remove duplicate slashes
b := dst
bSize := len(b)
for {
n := bytes.Index(b, strSlashSlash)
if n < 0 {
break
}
b = b[n:]
copy(b, b[1:])
b = b[:len(b)-1]
bSize--
}
dst = dst[:bSize]
// remove /./ parts
b = dst
for {
n := bytes.Index(b, strSlashDotSlash)
if n < 0 {
break
}
nn := n + len(strSlashDotSlash) - 1
copy(b[n:], b[nn:])
b = b[:len(b)-nn+n]
}
// remove /foo/../ parts
for {
n := bytes.Index(b, strSlashDotDotSlash)
if n < 0 {
break
}
nn := bytes.LastIndexByte(b[:n], '/')
if nn < 0 {
nn = 0
}
n += len(strSlashDotDotSlash) - 1
copy(b[nn:], b[n:])
b = b[:len(b)-n+nn]
}
// remove trailing /foo/..
n := bytes.LastIndex(b, strSlashDotDot)
if n >= 0 && n+len(strSlashDotDot) == len(b) {
nn := bytes.LastIndexByte(b[:n], '/')
if nn < 0 {
return append(dst[:0], strSlash...)
}
b = b[:nn+1]
}
return b
}
// RequestURI returns RequestURI - i.e. URI without Scheme and Host.
func (u *URI) RequestURI() []byte {
var dst []byte
if u.DisablePathNormalizing {
dst = append(u.requestURI[:0], u.PathOriginal()...)
} else {
dst = appendQuotedPath(u.requestURI[:0], u.Path())
}
if u.parsedQueryArgs && u.queryArgs.Len() > 0 {
dst = append(dst, '?')
dst = u.queryArgs.AppendBytes(dst)
} else if len(u.queryString) > 0 {
dst = append(dst, '?')
dst = append(dst, u.queryString...)
}
u.requestURI = dst
return u.requestURI
}
// LastPathSegment returns the last part of uri path after '/'.
//
// Examples:
//
// * For /foo/bar/baz.html path returns baz.html.
// * For /foo/bar/ returns empty byte slice.
// * For /foobar.js returns foobar.js.
//
// The returned bytes are valid until the next URI method call.
func (u *URI) LastPathSegment() []byte {
path := u.Path()
n := bytes.LastIndexByte(path, '/')
if n < 0 {
return path
}
return path[n+1:]
}
// Update updates uri.
//
// The following newURI types are accepted:
//
// * Absolute, i.e. http://foobar.com/aaa/bb?cc . In this case the original
// uri is replaced by newURI.
// * Absolute without scheme, i.e. //foobar.com/aaa/bb?cc. In this case
// the original scheme is preserved.
// * Missing host, i.e. /aaa/bb?cc . In this case only RequestURI part
// of the original uri is replaced.
// * Relative path, i.e. xx?yy=abc . In this case the original RequestURI
// is updated according to the new relative path.
func (u *URI) Update(newURI string) {
u.UpdateBytes(s2b(newURI))
}
// UpdateBytes updates uri.
//
// The following newURI types are accepted:
//
// * Absolute, i.e. http://foobar.com/aaa/bb?cc . In this case the original
// uri is replaced by newURI.
// * Absolute without scheme, i.e. //foobar.com/aaa/bb?cc. In this case
// the original scheme is preserved.
// * Missing host, i.e. /aaa/bb?cc . In this case only RequestURI part
// of the original uri is replaced.
// * Relative path, i.e. xx?yy=abc . In this case the original RequestURI
// is updated according to the new relative path.
func (u *URI) UpdateBytes(newURI []byte) {
u.requestURI = u.updateBytes(newURI, u.requestURI)
}
func (u *URI) updateBytes(newURI, buf []byte) []byte {
if len(newURI) == 0 {
return buf
}
n := bytes.Index(newURI, strSlashSlash)
if n >= 0 {
// absolute uri
var b [32]byte
schemeOriginal := b[:0]
if len(u.scheme) > 0 {
schemeOriginal = append([]byte(nil), u.scheme...)
}
if err := u.Parse(nil, newURI); err != nil {
return nil
}
if len(schemeOriginal) > 0 && len(u.scheme) == 0 {
u.scheme = append(u.scheme[:0], schemeOriginal...)
}
return buf
}
if newURI[0] == '/' {
// uri without host
buf = u.appendSchemeHost(buf[:0])
buf = append(buf, newURI...)
if err := u.Parse(nil, buf); err != nil {
return nil
}
return buf
}
// relative path
switch newURI[0] {
case '?':
// query string only update
u.SetQueryStringBytes(newURI[1:])
return append(buf[:0], u.FullURI()...)
case '#':
// update only hash
u.SetHashBytes(newURI[1:])
return append(buf[:0], u.FullURI()...)
default:
// update the last path part after the slash
path := u.Path()
n = bytes.LastIndexByte(path, '/')
if n < 0 {
panic(fmt.Sprintf("BUG: path must contain at least one slash: %s %s", u.Path(), newURI))
}
buf = u.appendSchemeHost(buf[:0])
buf = appendQuotedPath(buf, path[:n+1])
buf = append(buf, newURI...)
if err := u.Parse(nil, buf); err != nil {
return nil
}
return buf
}
}
// FullURI returns full uri in the form {Scheme}://{Host}{RequestURI}#{Hash}.
//
// The returned bytes are valid until the next URI method call.
func (u *URI) FullURI() []byte {
u.fullURI = u.AppendBytes(u.fullURI[:0])
return u.fullURI
}
// AppendBytes appends full uri to dst and returns the extended dst.
func (u *URI) AppendBytes(dst []byte) []byte {
dst = u.appendSchemeHost(dst)
dst = append(dst, u.RequestURI()...)
if len(u.hash) > 0 {
dst = append(dst, '#')
dst = append(dst, u.hash...)
}
return dst
}
func (u *URI) appendSchemeHost(dst []byte) []byte {
dst = append(dst, u.Scheme()...)
dst = append(dst, strColonSlashSlash...)
return append(dst, u.Host()...)
}
// WriteTo writes full uri to w.
//
// WriteTo implements io.WriterTo interface.
func (u *URI) WriteTo(w io.Writer) (int64, error) {
n, err := w.Write(u.FullURI())
return int64(n), err
}
// String returns full uri.
func (u *URI) String() string {
return string(u.FullURI())
}
func splitHostURI(host, uri []byte) ([]byte, []byte, []byte) {
n := bytes.Index(uri, strSlashSlash)
if n < 0 {
return strHTTP, host, uri
}
scheme := uri[:n]
if bytes.IndexByte(scheme, '/') >= 0 {
return strHTTP, host, uri
}
if len(scheme) > 0 && scheme[len(scheme)-1] == ':' {
scheme = scheme[:len(scheme)-1]
}
n += len(strSlashSlash)
uri = uri[n:]
n = bytes.IndexByte(uri, '/')
nq := bytes.IndexByte(uri, '?')
if nq >= 0 && nq < n {
// A hack for urls like foobar.com?a=b/xyz
n = nq
} else if n < 0 {
// A hack for bogus urls like foobar.com?a=b without
// slash after host.
if nq >= 0 {
return scheme, uri[:nq], uri[nq:]
}
return scheme, uri, strSlash
}
return scheme, uri[:n], uri[n:]
}
// QueryArgs returns query args.
//
// The returned args are valid until the next URI method call.
func (u *URI) QueryArgs() *Args {
u.parseQueryArgs()
return &u.queryArgs
}
func (u *URI) parseQueryArgs() {
if u.parsedQueryArgs {
return
}
u.queryArgs.ParseBytes(u.queryString)
u.parsedQueryArgs = true
}
// stringContainsCTLByte reports whether s contains any ASCII control character.
func stringContainsCTLByte(s []byte) bool {
for i := 0; i < len(s); i++ {
b := s[i]
if b < ' ' || b == 0x7f {
return true
}
}
return false
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/codepipeline.go<|end_filename|>
package events
// CodePipelineJob has been incorrectly assigned as CodePipelineEvent
// - https://github.com/aws/aws-lambda-go/issues/244
// This maintains backwards compatability until a v2 release
type CodePipelineEvent = CodePipelineJobEvent
<|start_filename|>vendor/github.com/aws/aws-lambda-go/lambda/handler.go<|end_filename|>
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package lambda
import (
"context"
"encoding/json"
"fmt"
"reflect"
"github.com/aws/aws-lambda-go/lambda/handlertrace"
)
type Handler interface {
Invoke(ctx context.Context, payload []byte) ([]byte, error)
}
// lambdaHandler is the generic function type
type lambdaHandler func(context.Context, []byte) (interface{}, error)
// Invoke calls the handler, and serializes the response.
// If the underlying handler returned an error, or an error occurs during serialization, error is returned.
func (handler lambdaHandler) Invoke(ctx context.Context, payload []byte) ([]byte, error) {
response, err := handler(ctx, payload)
if err != nil {
return nil, err
}
responseBytes, err := json.Marshal(response)
if err != nil {
return nil, err
}
return responseBytes, nil
}
func errorHandler(e error) lambdaHandler {
return func(ctx context.Context, event []byte) (interface{}, error) {
return nil, e
}
}
func validateArguments(handler reflect.Type) (bool, error) {
handlerTakesContext := false
if handler.NumIn() > 2 {
return false, fmt.Errorf("handlers may not take more than two arguments, but handler takes %d", handler.NumIn())
} else if handler.NumIn() > 0 {
contextType := reflect.TypeOf((*context.Context)(nil)).Elem()
argumentType := handler.In(0)
handlerTakesContext = argumentType.Implements(contextType)
if handler.NumIn() > 1 && !handlerTakesContext {
return false, fmt.Errorf("handler takes two arguments, but the first is not Context. got %s", argumentType.Kind())
}
}
return handlerTakesContext, nil
}
func validateReturns(handler reflect.Type) error {
errorType := reflect.TypeOf((*error)(nil)).Elem()
switch n := handler.NumOut(); {
case n > 2:
return fmt.Errorf("handler may not return more than two values")
case n > 1:
if !handler.Out(1).Implements(errorType) {
return fmt.Errorf("handler returns two values, but the second does not implement error")
}
case n == 1:
if !handler.Out(0).Implements(errorType) {
return fmt.Errorf("handler returns a single value, but it does not implement error")
}
}
return nil
}
// NewHandler creates a base lambda handler from the given handler function. The
// returned Handler performs JSON serialization and deserialization, and
// delegates to the input handler function. The handler function parameter must
// satisfy the rules documented by Start. If handlerFunc is not a valid
// handler, the returned Handler simply reports the validation error.
func NewHandler(handlerFunc interface{}) Handler {
if handlerFunc == nil {
return errorHandler(fmt.Errorf("handler is nil"))
}
handler := reflect.ValueOf(handlerFunc)
handlerType := reflect.TypeOf(handlerFunc)
if handlerType.Kind() != reflect.Func {
return errorHandler(fmt.Errorf("handler kind %s is not %s", handlerType.Kind(), reflect.Func))
}
takesContext, err := validateArguments(handlerType)
if err != nil {
return errorHandler(err)
}
if err := validateReturns(handlerType); err != nil {
return errorHandler(err)
}
return lambdaHandler(func(ctx context.Context, payload []byte) (interface{}, error) {
trace := handlertrace.FromContext(ctx)
// construct arguments
var args []reflect.Value
if takesContext {
args = append(args, reflect.ValueOf(ctx))
}
if (handlerType.NumIn() == 1 && !takesContext) || handlerType.NumIn() == 2 {
eventType := handlerType.In(handlerType.NumIn() - 1)
event := reflect.New(eventType)
if err := json.Unmarshal(payload, event.Interface()); err != nil {
return nil, err
}
if nil != trace.RequestEvent {
trace.RequestEvent(ctx, event.Elem().Interface())
}
args = append(args, event.Elem())
}
response := handler.Call(args)
// convert return values into (interface{}, error)
var err error
if len(response) > 0 {
if errVal, ok := response[len(response)-1].Interface().(error); ok {
err = errVal
}
}
var val interface{}
if len(response) > 1 {
val = response[0].Interface()
if nil != trace.ResponseEvent {
trace.ResponseEvent(ctx, val)
}
}
return val, err
})
}
<|start_filename|>vendor/github.com/valyala/fasthttp/tcpdialer.go<|end_filename|>
package fasthttp
import (
"context"
"errors"
"net"
"strconv"
"sync"
"sync/atomic"
"time"
)
// Dial dials the given TCP addr using tcp4.
//
// This function has the following additional features comparing to net.Dial:
//
// * It reduces load on DNS resolver by caching resolved TCP addressed
// for DNSCacheDuration.
// * It dials all the resolved TCP addresses in round-robin manner until
// connection is established. This may be useful if certain addresses
// are temporarily unreachable.
// * It returns ErrDialTimeout if connection cannot be established during
// DefaultDialTimeout seconds. Use DialTimeout for customizing dial timeout.
//
// This dialer is intended for custom code wrapping before passing
// to Client.Dial or HostClient.Dial.
//
// For instance, per-host counters and/or limits may be implemented
// by such wrappers.
//
// The addr passed to the function must contain port. Example addr values:
//
// * foobar.baz:443
// * foo.bar:80
// * aaa.com:8080
func Dial(addr string) (net.Conn, error) {
return defaultDialer.Dial(addr)
}
// DialTimeout dials the given TCP addr using tcp4 using the given timeout.
//
// This function has the following additional features comparing to net.Dial:
//
// * It reduces load on DNS resolver by caching resolved TCP addressed
// for DNSCacheDuration.
// * It dials all the resolved TCP addresses in round-robin manner until
// connection is established. This may be useful if certain addresses
// are temporarily unreachable.
//
// This dialer is intended for custom code wrapping before passing
// to Client.Dial or HostClient.Dial.
//
// For instance, per-host counters and/or limits may be implemented
// by such wrappers.
//
// The addr passed to the function must contain port. Example addr values:
//
// * foobar.baz:443
// * foo.bar:80
// * aaa.com:8080
func DialTimeout(addr string, timeout time.Duration) (net.Conn, error) {
return defaultDialer.DialTimeout(addr, timeout)
}
// DialDualStack dials the given TCP addr using both tcp4 and tcp6.
//
// This function has the following additional features comparing to net.Dial:
//
// * It reduces load on DNS resolver by caching resolved TCP addressed
// for DNSCacheDuration.
// * It dials all the resolved TCP addresses in round-robin manner until
// connection is established. This may be useful if certain addresses
// are temporarily unreachable.
// * It returns ErrDialTimeout if connection cannot be established during
// DefaultDialTimeout seconds. Use DialDualStackTimeout for custom dial
// timeout.
//
// This dialer is intended for custom code wrapping before passing
// to Client.Dial or HostClient.Dial.
//
// For instance, per-host counters and/or limits may be implemented
// by such wrappers.
//
// The addr passed to the function must contain port. Example addr values:
//
// * foobar.baz:443
// * foo.bar:80
// * aaa.com:8080
func DialDualStack(addr string) (net.Conn, error) {
return defaultDialer.DialDualStack(addr)
}
// DialDualStackTimeout dials the given TCP addr using both tcp4 and tcp6
// using the given timeout.
//
// This function has the following additional features comparing to net.Dial:
//
// * It reduces load on DNS resolver by caching resolved TCP addressed
// for DNSCacheDuration.
// * It dials all the resolved TCP addresses in round-robin manner until
// connection is established. This may be useful if certain addresses
// are temporarily unreachable.
//
// This dialer is intended for custom code wrapping before passing
// to Client.Dial or HostClient.Dial.
//
// For instance, per-host counters and/or limits may be implemented
// by such wrappers.
//
// The addr passed to the function must contain port. Example addr values:
//
// * foobar.baz:443
// * foo.bar:80
// * aaa.com:8080
func DialDualStackTimeout(addr string, timeout time.Duration) (net.Conn, error) {
return defaultDialer.DialDualStackTimeout(addr, timeout)
}
var (
defaultDialer = &TCPDialer{Concurrency: 1000}
)
// Resolver represents interface of the tcp resolver.
type Resolver interface {
LookupIPAddr(context.Context, string) (names []net.IPAddr, err error)
}
// TCPDialer contains options to control a group of Dial calls.
type TCPDialer struct {
// Concurrency controls the maximum number of concurrent Dails
// that can be performed using this object.
// Setting this to 0 means unlimited.
//
// WARNING: This can only be changed before the first Dial.
// Changes made after the first Dial will not affect anything.
Concurrency int
// LocalAddr is the local address to use when dialing an
// address.
// If nil, a local address is automatically chosen.
LocalAddr *net.TCPAddr
// This may be used to override DNS resolving policy, like this:
// var dialer = &fasthttp.TCPDialer{
// Resolver: &net.Resolver{
// PreferGo: true,
// StrictErrors: false,
// Dial: func (ctx context.Context, network, address string) (net.Conn, error) {
// d := net.Dialer{}
// return d.DialContext(ctx, "udp", "8.8.8.8:53")
// },
// },
// }
Resolver Resolver
// DNSCacheDuration may be used to override the default DNS cache duration (DefaultDNSCacheDuration)
DNSCacheDuration time.Duration
tcpAddrsMap sync.Map
concurrencyCh chan struct{}
once sync.Once
}
// Dial dials the given TCP addr using tcp4.
//
// This function has the following additional features comparing to net.Dial:
//
// * It reduces load on DNS resolver by caching resolved TCP addressed
// for DNSCacheDuration.
// * It dials all the resolved TCP addresses in round-robin manner until
// connection is established. This may be useful if certain addresses
// are temporarily unreachable.
// * It returns ErrDialTimeout if connection cannot be established during
// DefaultDialTimeout seconds. Use DialTimeout for customizing dial timeout.
//
// This dialer is intended for custom code wrapping before passing
// to Client.Dial or HostClient.Dial.
//
// For instance, per-host counters and/or limits may be implemented
// by such wrappers.
//
// The addr passed to the function must contain port. Example addr values:
//
// * foobar.baz:443
// * foo.bar:80
// * aaa.com:8080
func (d *TCPDialer) Dial(addr string) (net.Conn, error) {
return d.dial(addr, false, DefaultDialTimeout)
}
// DialTimeout dials the given TCP addr using tcp4 using the given timeout.
//
// This function has the following additional features comparing to net.Dial:
//
// * It reduces load on DNS resolver by caching resolved TCP addressed
// for DNSCacheDuration.
// * It dials all the resolved TCP addresses in round-robin manner until
// connection is established. This may be useful if certain addresses
// are temporarily unreachable.
//
// This dialer is intended for custom code wrapping before passing
// to Client.Dial or HostClient.Dial.
//
// For instance, per-host counters and/or limits may be implemented
// by such wrappers.
//
// The addr passed to the function must contain port. Example addr values:
//
// * foobar.baz:443
// * foo.bar:80
// * aaa.com:8080
func (d *TCPDialer) DialTimeout(addr string, timeout time.Duration) (net.Conn, error) {
return d.dial(addr, false, timeout)
}
// DialDualStack dials the given TCP addr using both tcp4 and tcp6.
//
// This function has the following additional features comparing to net.Dial:
//
// * It reduces load on DNS resolver by caching resolved TCP addressed
// for DNSCacheDuration.
// * It dials all the resolved TCP addresses in round-robin manner until
// connection is established. This may be useful if certain addresses
// are temporarily unreachable.
// * It returns ErrDialTimeout if connection cannot be established during
// DefaultDialTimeout seconds. Use DialDualStackTimeout for custom dial
// timeout.
//
// This dialer is intended for custom code wrapping before passing
// to Client.Dial or HostClient.Dial.
//
// For instance, per-host counters and/or limits may be implemented
// by such wrappers.
//
// The addr passed to the function must contain port. Example addr values:
//
// * foobar.baz:443
// * foo.bar:80
// * aaa.com:8080
func (d *TCPDialer) DialDualStack(addr string) (net.Conn, error) {
return d.dial(addr, true, DefaultDialTimeout)
}
// DialDualStackTimeout dials the given TCP addr using both tcp4 and tcp6
// using the given timeout.
//
// This function has the following additional features comparing to net.Dial:
//
// * It reduces load on DNS resolver by caching resolved TCP addressed
// for DNSCacheDuration.
// * It dials all the resolved TCP addresses in round-robin manner until
// connection is established. This may be useful if certain addresses
// are temporarily unreachable.
//
// This dialer is intended for custom code wrapping before passing
// to Client.Dial or HostClient.Dial.
//
// For instance, per-host counters and/or limits may be implemented
// by such wrappers.
//
// The addr passed to the function must contain port. Example addr values:
//
// * foobar.baz:443
// * foo.bar:80
// * aaa.com:8080
func (d *TCPDialer) DialDualStackTimeout(addr string, timeout time.Duration) (net.Conn, error) {
return d.dial(addr, true, timeout)
}
func (d *TCPDialer) dial(addr string, dualStack bool, timeout time.Duration) (net.Conn, error) {
d.once.Do(func() {
if d.Concurrency > 0 {
d.concurrencyCh = make(chan struct{}, d.Concurrency)
}
if d.DNSCacheDuration == 0 {
d.DNSCacheDuration = DefaultDNSCacheDuration
}
go d.tcpAddrsClean()
})
addrs, idx, err := d.getTCPAddrs(addr, dualStack)
if err != nil {
return nil, err
}
network := "tcp4"
if dualStack {
network = "tcp"
}
var conn net.Conn
n := uint32(len(addrs))
deadline := time.Now().Add(timeout)
for n > 0 {
conn, err = d.tryDial(network, &addrs[idx%n], deadline, d.concurrencyCh)
if err == nil {
return conn, nil
}
if err == ErrDialTimeout {
return nil, err
}
idx++
n--
}
return nil, err
}
func (d *TCPDialer) tryDial(network string, addr *net.TCPAddr, deadline time.Time, concurrencyCh chan struct{}) (net.Conn, error) {
timeout := -time.Since(deadline)
if timeout <= 0 {
return nil, ErrDialTimeout
}
if concurrencyCh != nil {
select {
case concurrencyCh <- struct{}{}:
default:
tc := AcquireTimer(timeout)
isTimeout := false
select {
case concurrencyCh <- struct{}{}:
case <-tc.C:
isTimeout = true
}
ReleaseTimer(tc)
if isTimeout {
return nil, ErrDialTimeout
}
}
defer func() { <-concurrencyCh }()
}
dialer := net.Dialer{}
if d.LocalAddr != nil {
dialer.LocalAddr = d.LocalAddr
}
ctx, cancel_ctx := context.WithDeadline(context.Background(), deadline)
defer cancel_ctx()
conn, err := dialer.DialContext(ctx, network, addr.String())
if err != nil && ctx.Err() == context.DeadlineExceeded {
return nil, ErrDialTimeout
}
return conn, err
}
// ErrDialTimeout is returned when TCP dialing is timed out.
var ErrDialTimeout = errors.New("dialing to the given TCP address timed out")
// DefaultDialTimeout is timeout used by Dial and DialDualStack
// for establishing TCP connections.
const DefaultDialTimeout = 3 * time.Second
type tcpAddrEntry struct {
addrs []net.TCPAddr
addrsIdx uint32
resolveTime time.Time
pending bool
}
// DefaultDNSCacheDuration is the duration for caching resolved TCP addresses
// by Dial* functions.
const DefaultDNSCacheDuration = time.Minute
func (d *TCPDialer) tcpAddrsClean() {
expireDuration := 2 * d.DNSCacheDuration
for {
time.Sleep(time.Second)
t := time.Now()
d.tcpAddrsMap.Range(func(k, v interface{}) bool {
if e, ok := v.(*tcpAddrEntry); ok && t.Sub(e.resolveTime) > expireDuration {
d.tcpAddrsMap.Delete(k)
}
return true
})
}
}
func (d *TCPDialer) getTCPAddrs(addr string, dualStack bool) ([]net.TCPAddr, uint32, error) {
item, exist := d.tcpAddrsMap.Load(addr)
e, ok := item.(*tcpAddrEntry)
if exist && ok && e != nil && !e.pending && time.Since(e.resolveTime) > d.DNSCacheDuration {
e.pending = true
e = nil
}
if e == nil {
addrs, err := resolveTCPAddrs(addr, dualStack, d.Resolver)
if err != nil {
item, exist := d.tcpAddrsMap.Load(addr)
e, ok = item.(*tcpAddrEntry)
if exist && ok && e != nil && e.pending {
e.pending = false
}
return nil, 0, err
}
e = &tcpAddrEntry{
addrs: addrs,
resolveTime: time.Now(),
}
d.tcpAddrsMap.Store(addr, e)
}
idx := atomic.AddUint32(&e.addrsIdx, 1)
return e.addrs, idx, nil
}
func resolveTCPAddrs(addr string, dualStack bool, resolver Resolver) ([]net.TCPAddr, error) {
host, portS, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
port, err := strconv.Atoi(portS)
if err != nil {
return nil, err
}
if resolver == nil {
resolver = net.DefaultResolver
}
ctx := context.Background()
ipaddrs, err := resolver.LookupIPAddr(ctx, host)
if err != nil {
return nil, err
}
n := len(ipaddrs)
addrs := make([]net.TCPAddr, 0, n)
for i := 0; i < n; i++ {
ip := ipaddrs[i]
if !dualStack && ip.IP.To4() == nil {
continue
}
addrs = append(addrs, net.TCPAddr{
IP: ip.IP,
Port: port,
Zone: ip.Zone,
})
}
if len(addrs) == 0 {
return nil, errNoDNSEntries
}
return addrs, nil
}
var errNoDNSEntries = errors.New("couldn't find DNS entries for the given domain. Try using DialDualStack")
<|start_filename|>vendor/github.com/aws/aws-lambda-go/lambda/entry.go<|end_filename|>
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package lambda
import (
"context"
"errors"
"log"
"os"
)
// Start takes a handler and talks to an internal Lambda endpoint to pass requests to the handler. If the
// handler does not match one of the supported types an appropriate error message will be returned to the caller.
// Start blocks, and does not return after being called.
//
// Rules:
//
// * handler must be a function
// * handler may take between 0 and two arguments.
// * if there are two arguments, the first argument must satisfy the "context.Context" interface.
// * handler may return between 0 and two arguments.
// * if there are two return values, the second argument must be an error.
// * if there is one return value it must be an error.
//
// Valid function signatures:
//
// func ()
// func () error
// func (TIn) error
// func () (TOut, error)
// func (TIn) (TOut, error)
// func (context.Context) error
// func (context.Context, TIn) error
// func (context.Context) (TOut, error)
// func (context.Context, TIn) (TOut, error)
//
// Where "TIn" and "TOut" are types compatible with the "encoding/json" standard library.
// See https://golang.org/pkg/encoding/json/#Unmarshal for how deserialization behaves
func Start(handler interface{}) {
StartWithContext(context.Background(), handler)
}
// StartWithContext is the same as Start except sets the base context for the function.
func StartWithContext(ctx context.Context, handler interface{}) {
StartHandlerWithContext(ctx, NewHandler(handler))
}
// StartHandler takes in a Handler wrapper interface which can be implemented either by a
// custom function or a struct.
//
// Handler implementation requires a single "Invoke()" function:
//
// func Invoke(context.Context, []byte) ([]byte, error)
func StartHandler(handler Handler) {
StartHandlerWithContext(context.Background(), handler)
}
type startFunction struct {
env string
f func(ctx context.Context, envValue string, handler Handler) error
}
var (
// This allows users to save a little bit of coldstart time in the download, by the dependencies brought in for RPC support.
// The tradeoff is dropping compatibility with the go1.x runtime, functions must be "Custom Runtime" instead.
// To drop the rpc dependencies, compile with `-tags lambda.norpc`
rpcStartFunction = &startFunction{
env: "_LAMBDA_SERVER_PORT",
f: func(c context.Context, p string, h Handler) error {
return errors.New("_LAMBDA_SERVER_PORT was present but the function was compiled without RPC support")
},
}
runtimeAPIStartFunction = &startFunction{
env: "AWS_LAMBDA_RUNTIME_API",
f: startRuntimeAPILoop,
}
startFunctions = []*startFunction{rpcStartFunction, runtimeAPIStartFunction}
// This allows end to end testing of the Start functions, by tests overwriting this function to keep the program alive
logFatalf = log.Fatalf
)
// StartHandlerWithContext is the same as StartHandler except sets the base context for the function.
//
// Handler implementation requires a single "Invoke()" function:
//
// func Invoke(context.Context, []byte) ([]byte, error)
func StartHandlerWithContext(ctx context.Context, handler Handler) {
var keys []string
for _, start := range startFunctions {
config := os.Getenv(start.env)
if config != "" {
// in normal operation, the start function never returns
// if it does, exit!, this triggers a restart of the lambda function
err := start.f(ctx, config, handler)
logFatalf("%v", err)
}
keys = append(keys, start.env)
}
logFatalf("expected AWS Lambda environment variables %s are not defined", keys)
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/ecr_scan.go<|end_filename|>
package events
type ECRScanEvent struct {
Version string `json:"version"`
ID string `json:"id"`
DetailType string `json:"detail-type"`
Source string `json:"source"`
Time string `json:"time"`
Region string `json:"region"`
Resources []string `json:"resources"`
Account string `json:"account"`
Detail ECRScanEventDetailType `json:"detail"`
}
type ECRScanEventDetailType struct {
ScanStatus string `json:"scan-status"`
RepositoryName string `json:"repository-name"`
FindingSeverityCounts ECRScanEventFindingSeverityCounts `json:"finding-severity-counts"`
ImageDigest string `json:"image-digest"`
ImageTags []string `json:"image-tags"`
}
type ECRScanEventFindingSeverityCounts struct {
Critical int64 `json:"CRITICAL"`
High int64 `json:"HIGH"`
Medium int64 `json:"MEDIUM"`
Low int64 `json:"LOW"`
Informational int64 `json:"INFORMATIONAL"`
Undefined int64 `json:"UNDEFINED"`
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/sns.go<|end_filename|>
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
import (
"time"
)
type SNSEvent struct {
Records []SNSEventRecord `json:"Records"`
}
type SNSEventRecord struct {
EventVersion string `json:"EventVersion"`
EventSubscriptionArn string `json:"EventSubscriptionArn"` //nolint: stylecheck
EventSource string `json:"EventSource"`
SNS SNSEntity `json:"Sns"`
}
type SNSEntity struct {
Signature string `json:"Signature"`
MessageID string `json:"MessageId"`
Type string `json:"Type"`
TopicArn string `json:"TopicArn"` //nolint: stylecheck
MessageAttributes map[string]interface{} `json:"MessageAttributes"`
SignatureVersion string `json:"SignatureVersion"`
Timestamp time.Time `json:"Timestamp"`
SigningCertURL string `json:"SigningCertUrl"`
Message string `json:"Message"`
UnsubscribeURL string `json:"UnsubscribeUrl"`
Subject string `json:"Subject"`
}
type CloudWatchAlarmSNSPayload struct {
AlarmName string `json:"AlarmName"`
AlarmDescription string `json:"AlarmDescription"`
AWSAccountID string `json:"AWSAccountId"`
NewStateValue string `json:"NewStateValue"`
NewStateReason string `json:"NewStateReason"`
StateChangeTime string `json:"StateChangeTime"`
Region string `json:"Region"`
AlarmARN string `json:"AlarmArn"`
OldStateValue string `json:"OldStateValue"`
Trigger CloudWatchAlarmTrigger `json:"Trigger"`
}
type CloudWatchAlarmTrigger struct {
Period int64 `json:"Period"`
EvaluationPeriods int64 `json:"EvaluationPeriods"`
ComparisonOperator string `json:"ComparisonOperator"`
Threshold float64 `json:"Threshold"`
TreatMissingData string `json:"TreatMissingData"`
EvaluateLowSampleCountPercentile string `json:"EvaluateLowSampleCountPercentile"`
Metrics []CloudWatchMetricDataQuery `json:"Metrics,omitempty"`
MetricName string `json:"MetricName,omitempty"`
Namespace string `json:"Namespace,omitempty"`
StatisticType string `json:"StatisticType,omitempty"`
Statistic string `json:"Statistic,omitempty"`
Unit string `json:"Unit,omitempty"`
Dimensions []CloudWatchDimension `json:"Dimensions,omitempty"`
}
type CloudWatchMetricDataQuery struct {
Expression string `json:"Expression,omitempty"`
ID string `json:"Id"`
Label string `json:"Label,omitempty"`
MetricStat CloudWatchMetricStat `json:"MetricStat,omitempty"`
Period int64 `json:"Period,omitempty"`
ReturnData bool `json:"ReturnData,omitempty"`
}
type CloudWatchMetricStat struct {
Metric CloudWatchMetric `json:"Metric"`
Period int64 `json:"Period"`
Stat string `json:"Stat"`
Unit string `json:"Unit,omitempty"`
}
type CloudWatchMetric struct {
Dimensions []CloudWatchDimension `json:"Dimensions,omitempty"`
MetricName string `json:"MetricName,omitempty"`
Namespace string `json:"Namespace,omitempty"`
}
type CloudWatchDimension struct {
Name string `json:"name"`
Value string `json:"value"`
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/s3.go<|end_filename|>
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
import (
"encoding/json"
"net/url"
"time"
)
// S3Event which wrap an array of S3EventRecord
type S3Event struct {
Records []S3EventRecord `json:"Records"`
}
// S3EventRecord which wrap record data
type S3EventRecord struct {
EventVersion string `json:"eventVersion"`
EventSource string `json:"eventSource"`
AWSRegion string `json:"awsRegion"`
EventTime time.Time `json:"eventTime"`
EventName string `json:"eventName"`
PrincipalID S3UserIdentity `json:"userIdentity"`
RequestParameters S3RequestParameters `json:"requestParameters"`
ResponseElements map[string]string `json:"responseElements"`
S3 S3Entity `json:"s3"`
}
type S3UserIdentity struct {
PrincipalID string `json:"principalId"`
}
type S3RequestParameters struct {
SourceIPAddress string `json:"sourceIPAddress"`
}
type S3Entity struct {
SchemaVersion string `json:"s3SchemaVersion"`
ConfigurationID string `json:"configurationId"`
Bucket S3Bucket `json:"bucket"`
Object S3Object `json:"object"`
}
type S3Bucket struct {
Name string `json:"name"`
OwnerIdentity S3UserIdentity `json:"ownerIdentity"`
Arn string `json:"arn"` //nolint: stylecheck
}
type S3Object struct {
Key string `json:"key"`
Size int64 `json:"size,omitempty"`
URLDecodedKey string `json:"urlDecodedKey"`
VersionID string `json:"versionId"`
ETag string `json:"eTag"`
Sequencer string `json:"sequencer"`
}
func (o *S3Object) UnmarshalJSON(data []byte) error {
type rawS3Object S3Object
if err := json.Unmarshal(data, (*rawS3Object)(o)); err != nil {
return err
}
key, err := url.QueryUnescape(o.Key)
if err != nil {
return err
}
o.URLDecodedKey = key
return nil
}
type S3TestEvent struct {
Service string `json:"Service"`
Bucket string `json:"Bucket"`
Event string `json:"Event"`
Time time.Time `json:"Time"`
RequestID string `json:"RequestId"`
HostID string `json:"HostId"`
}
<|start_filename|>vendor/github.com/aws/aws-sdk-go-v2/service/s3/types/errors.go<|end_filename|>
// Code generated by smithy-go-codegen DO NOT EDIT.
package types
import (
"fmt"
smithy "github.com/aws/smithy-go"
)
// The requested bucket name is not available. The bucket namespace is shared by
// all users of the system. Select a different name and try again.
type BucketAlreadyExists struct {
Message *string
noSmithyDocumentSerde
}
func (e *BucketAlreadyExists) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *BucketAlreadyExists) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *BucketAlreadyExists) ErrorCode() string { return "BucketAlreadyExists" }
func (e *BucketAlreadyExists) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The bucket you tried to create already exists, and you own it. Amazon S3 returns
// this error in all Amazon Web Services Regions except in the North Virginia
// Region. For legacy compatibility, if you re-create an existing bucket that you
// already own in the North Virginia Region, Amazon S3 returns 200 OK and resets
// the bucket access control lists (ACLs).
type BucketAlreadyOwnedByYou struct {
Message *string
noSmithyDocumentSerde
}
func (e *BucketAlreadyOwnedByYou) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *BucketAlreadyOwnedByYou) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *BucketAlreadyOwnedByYou) ErrorCode() string { return "BucketAlreadyOwnedByYou" }
func (e *BucketAlreadyOwnedByYou) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// Object is archived and inaccessible until restored.
type InvalidObjectState struct {
Message *string
StorageClass StorageClass
AccessTier IntelligentTieringAccessTier
noSmithyDocumentSerde
}
func (e *InvalidObjectState) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *InvalidObjectState) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *InvalidObjectState) ErrorCode() string { return "InvalidObjectState" }
func (e *InvalidObjectState) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The specified bucket does not exist.
type NoSuchBucket struct {
Message *string
noSmithyDocumentSerde
}
func (e *NoSuchBucket) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *NoSuchBucket) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *NoSuchBucket) ErrorCode() string { return "NoSuchBucket" }
func (e *NoSuchBucket) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The specified key does not exist.
type NoSuchKey struct {
Message *string
noSmithyDocumentSerde
}
func (e *NoSuchKey) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *NoSuchKey) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *NoSuchKey) ErrorCode() string { return "NoSuchKey" }
func (e *NoSuchKey) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The specified multipart upload does not exist.
type NoSuchUpload struct {
Message *string
noSmithyDocumentSerde
}
func (e *NoSuchUpload) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *NoSuchUpload) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *NoSuchUpload) ErrorCode() string { return "NoSuchUpload" }
func (e *NoSuchUpload) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The specified content does not exist.
type NotFound struct {
Message *string
noSmithyDocumentSerde
}
func (e *NotFound) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *NotFound) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *NotFound) ErrorCode() string { return "NotFound" }
func (e *NotFound) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// This action is not allowed against this storage tier.
type ObjectAlreadyInActiveTierError struct {
Message *string
noSmithyDocumentSerde
}
func (e *ObjectAlreadyInActiveTierError) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *ObjectAlreadyInActiveTierError) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *ObjectAlreadyInActiveTierError) ErrorCode() string { return "ObjectAlreadyInActiveTierError" }
func (e *ObjectAlreadyInActiveTierError) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The source object of the COPY action is not in the active tier and is only
// stored in Amazon S3 Glacier.
type ObjectNotInActiveTierError struct {
Message *string
noSmithyDocumentSerde
}
func (e *ObjectNotInActiveTierError) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *ObjectNotInActiveTierError) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *ObjectNotInActiveTierError) ErrorCode() string { return "ObjectNotInActiveTierError" }
func (e *ObjectNotInActiveTierError) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
<|start_filename|>vendor/github.com/andybalholm/brotli/cluster_command.go<|end_filename|>
package brotli
/* Copyright 2013 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
/* Computes the bit cost reduction by combining out[idx1] and out[idx2] and if
it is below a threshold, stores the pair (idx1, idx2) in the *pairs queue. */
func compareAndPushToQueueCommand(out []histogramCommand, cluster_size []uint32, idx1 uint32, idx2 uint32, max_num_pairs uint, pairs []histogramPair, num_pairs *uint) {
var is_good_pair bool = false
var p histogramPair
p.idx2 = 0
p.idx1 = p.idx2
p.cost_combo = 0
p.cost_diff = p.cost_combo
if idx1 == idx2 {
return
}
if idx2 < idx1 {
var t uint32 = idx2
idx2 = idx1
idx1 = t
}
p.idx1 = idx1
p.idx2 = idx2
p.cost_diff = 0.5 * clusterCostDiff(uint(cluster_size[idx1]), uint(cluster_size[idx2]))
p.cost_diff -= out[idx1].bit_cost_
p.cost_diff -= out[idx2].bit_cost_
if out[idx1].total_count_ == 0 {
p.cost_combo = out[idx2].bit_cost_
is_good_pair = true
} else if out[idx2].total_count_ == 0 {
p.cost_combo = out[idx1].bit_cost_
is_good_pair = true
} else {
var threshold float64
if *num_pairs == 0 {
threshold = 1e99
} else {
threshold = brotli_max_double(0.0, pairs[0].cost_diff)
}
var combo histogramCommand = out[idx1]
var cost_combo float64
histogramAddHistogramCommand(&combo, &out[idx2])
cost_combo = populationCostCommand(&combo)
if cost_combo < threshold-p.cost_diff {
p.cost_combo = cost_combo
is_good_pair = true
}
}
if is_good_pair {
p.cost_diff += p.cost_combo
if *num_pairs > 0 && histogramPairIsLess(&pairs[0], &p) {
/* Replace the top of the queue if needed. */
if *num_pairs < max_num_pairs {
pairs[*num_pairs] = pairs[0]
(*num_pairs)++
}
pairs[0] = p
} else if *num_pairs < max_num_pairs {
pairs[*num_pairs] = p
(*num_pairs)++
}
}
}
func histogramCombineCommand(out []histogramCommand, cluster_size []uint32, symbols []uint32, clusters []uint32, pairs []histogramPair, num_clusters uint, symbols_size uint, max_clusters uint, max_num_pairs uint) uint {
var cost_diff_threshold float64 = 0.0
var min_cluster_size uint = 1
var num_pairs uint = 0
{
/* We maintain a vector of histogram pairs, with the property that the pair
with the maximum bit cost reduction is the first. */
var idx1 uint
for idx1 = 0; idx1 < num_clusters; idx1++ {
var idx2 uint
for idx2 = idx1 + 1; idx2 < num_clusters; idx2++ {
compareAndPushToQueueCommand(out, cluster_size, clusters[idx1], clusters[idx2], max_num_pairs, pairs[0:], &num_pairs)
}
}
}
for num_clusters > min_cluster_size {
var best_idx1 uint32
var best_idx2 uint32
var i uint
if pairs[0].cost_diff >= cost_diff_threshold {
cost_diff_threshold = 1e99
min_cluster_size = max_clusters
continue
}
/* Take the best pair from the top of heap. */
best_idx1 = pairs[0].idx1
best_idx2 = pairs[0].idx2
histogramAddHistogramCommand(&out[best_idx1], &out[best_idx2])
out[best_idx1].bit_cost_ = pairs[0].cost_combo
cluster_size[best_idx1] += cluster_size[best_idx2]
for i = 0; i < symbols_size; i++ {
if symbols[i] == best_idx2 {
symbols[i] = best_idx1
}
}
for i = 0; i < num_clusters; i++ {
if clusters[i] == best_idx2 {
copy(clusters[i:], clusters[i+1:][:num_clusters-i-1])
break
}
}
num_clusters--
{
/* Remove pairs intersecting the just combined best pair. */
var copy_to_idx uint = 0
for i = 0; i < num_pairs; i++ {
var p *histogramPair = &pairs[i]
if p.idx1 == best_idx1 || p.idx2 == best_idx1 || p.idx1 == best_idx2 || p.idx2 == best_idx2 {
/* Remove invalid pair from the queue. */
continue
}
if histogramPairIsLess(&pairs[0], p) {
/* Replace the top of the queue if needed. */
var front histogramPair = pairs[0]
pairs[0] = *p
pairs[copy_to_idx] = front
} else {
pairs[copy_to_idx] = *p
}
copy_to_idx++
}
num_pairs = copy_to_idx
}
/* Push new pairs formed with the combined histogram to the heap. */
for i = 0; i < num_clusters; i++ {
compareAndPushToQueueCommand(out, cluster_size, best_idx1, clusters[i], max_num_pairs, pairs[0:], &num_pairs)
}
}
return num_clusters
}
/* What is the bit cost of moving histogram from cur_symbol to candidate. */
func histogramBitCostDistanceCommand(histogram *histogramCommand, candidate *histogramCommand) float64 {
if histogram.total_count_ == 0 {
return 0.0
} else {
var tmp histogramCommand = *histogram
histogramAddHistogramCommand(&tmp, candidate)
return populationCostCommand(&tmp) - candidate.bit_cost_
}
}
<|start_filename|>vendor/github.com/aws/aws-sdk-go-v2/service/s3/internal/v4a/error.go<|end_filename|>
package v4a
import "fmt"
// SigningError indicates an error condition occurred while performing SigV4a signing
type SigningError struct {
Err error
}
func (e *SigningError) Error() string {
return fmt.Sprintf("failed to sign request: %v", e.Err)
}
// Unwrap returns the underlying error cause
func (e *SigningError) Unwrap() error {
return e.Err
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/activemq.go<|end_filename|>
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
type ActiveMQEvent struct {
EventSource string `json:"eventSource"`
EventSourceARN string `json:"eventSourceArn"`
Messages []ActiveMQMessage `json:"messages"`
}
type ActiveMQMessage struct {
MessageID string `json:"messageID"`
MessageType string `json:"messageType"`
Timestamp int64 `json:"timestamp"`
DeliveryMode int `json:"deliveryMode"`
CorrelationID string `json:"correlationID"`
ReplyTo string `json:"replyTo"`
Destination ActiveMQDestination `json:"destination"`
Redelivered bool `json:"redelivered"`
Type string `json:"type"`
Expiration int64 `json:"expiration"`
Priority int `json:"priority"`
Data string `json:"data"`
BrokerInTime int64 `json:"brokerInTime"`
BrokerOutTime int64 `json:"brokerOutTime"`
}
type ActiveMQDestination struct {
PhysicalName string `json:"physicalName"`
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/rabbitmq.go<|end_filename|>
package events
type RabbitMQEvent struct {
EventSource string `json:"eventSource"`
EventSourceARN string `json:"eventSourceArn"`
MessagesByQueue map[string][]RabbitMQMessage `json:"rmqMessagesByQueue"`
}
type RabbitMQMessage struct {
BasicProperties RabbitMQBasicProperties `json:"basicProperties"`
Data string `json:"data"`
Redelivered bool `json:"redelivered"`
}
type RabbitMQBasicProperties struct {
ContentType string `json:"contentType"`
ContentEncoding *string `json:"contentEncoding"`
Headers map[string]interface{} `json:"headers"` // Application or header exchange table
DeliveryMode uint8 `json:"deliveryMode"`
Priority uint8 `json:"priority"`
CorrelationID *string `json:"correlationId"`
ReplyTo *string `json:"replyTo"`
Expiration string `json:"expiration"`
MessageID *string `json:"messageId"`
Timestamp string `json:"timestamp"`
Type *string `json:"type"`
UserID string `json:"userId"`
AppID *string `json:"appId"`
ClusterID *string `json:"clusterId"`
BodySize uint64 `json:"bodySize"`
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/clientvpn.go<|end_filename|>
package events
type ClientVPNConnectionHandlerRequest struct {
ConnectionID string `json:"connection-id"`
EndpointID string `json:"endpoint-id"`
CommonName string `json:"common-name"`
Username string `json:"username"`
OSPlatform string `json:"platform"`
OSPlatformVersion string `json:"platform-version"`
PublicIP string `json:"public-ip"`
ClientOpenVPNVersion string `json:"client-openvpn-version"`
SchemaVersion string `json:"schema-version"`
}
type ClientVPNConnectionHandlerResponse struct {
Allow bool `json:"allow"`
ErrorMsgOnFailedPostureCompliance string `json:"error-msg-on-failed-posture-compliance"`
PostureComplianceStatuses []string `json:"posture-compliance-statuses"`
SchemaVersion string `json:"schema-version"`
}
<|start_filename|>vendor/github.com/aws/aws-sdk-go/service/xray/doc.go<|end_filename|>
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package xray provides the client and types for making API
// requests to AWS X-Ray.
//
// Amazon Web Services X-Ray provides APIs for managing debug traces and retrieving
// service maps and other data created by processing those traces.
//
// See https://docs.aws.amazon.com/goto/WebAPI/xray-2016-04-12 for more information on this service.
//
// See xray package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/xray/
//
// Using the Client
//
// To contact AWS X-Ray with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the AWS X-Ray client XRay for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/xray/#New
package xray
<|start_filename|>vendor/github.com/awslabs/aws-lambda-go-api-proxy/core/responsev2.go<|end_filename|>
// Package core provides utility methods that help convert proxy events
// into an http.Request and http.ResponseWriter
package core
import (
"bytes"
"encoding/base64"
"errors"
"net/http"
"strings"
"unicode/utf8"
"github.com/aws/aws-lambda-go/events"
)
// ProxyResponseWriterV2 implements http.ResponseWriter and adds the method
// necessary to return an events.APIGatewayProxyResponse object
type ProxyResponseWriterV2 struct {
headers http.Header
body bytes.Buffer
status int
observers []chan<- bool
}
// NewProxyResponseWriter returns a new ProxyResponseWriter object.
// The object is initialized with an empty map of headers and a
// status code of -1
func NewProxyResponseWriterV2() *ProxyResponseWriterV2 {
return &ProxyResponseWriterV2{
headers: make(http.Header),
status: defaultStatusCode,
observers: make([]chan<- bool, 0),
}
}
func (r *ProxyResponseWriterV2) CloseNotify() <-chan bool {
ch := make(chan bool, 1)
r.observers = append(r.observers, ch)
return ch
}
func (r *ProxyResponseWriterV2) notifyClosed() {
for _, v := range r.observers {
v <- true
}
}
// Header implementation from the http.ResponseWriter interface.
func (r *ProxyResponseWriterV2) Header() http.Header {
return r.headers
}
// Write sets the response body in the object. If no status code
// was set before with the WriteHeader method it sets the status
// for the response to 200 OK.
func (r *ProxyResponseWriterV2) Write(body []byte) (int, error) {
if r.status == defaultStatusCode {
r.status = http.StatusOK
}
// if the content type header is not set when we write the body we try to
// detect one and set it by default. If the content type cannot be detected
// it is automatically set to "application/octet-stream" by the
// DetectContentType method
if r.Header().Get(contentTypeHeaderKey) == "" {
r.Header().Add(contentTypeHeaderKey, http.DetectContentType(body))
}
return (&r.body).Write(body)
}
// WriteHeader sets a status code for the response. This method is used
// for error responses.
func (r *ProxyResponseWriterV2) WriteHeader(status int) {
r.status = status
}
// GetProxyResponse converts the data passed to the response writer into
// an events.APIGatewayProxyResponse object.
// Returns a populated proxy response object. If the response is invalid, for example
// has no headers or an invalid status code returns an error.
func (r *ProxyResponseWriterV2) GetProxyResponse() (events.APIGatewayV2HTTPResponse, error) {
r.notifyClosed()
if r.status == defaultStatusCode {
return events.APIGatewayV2HTTPResponse{}, errors.New("Status code not set on response")
}
var output string
isBase64 := false
bb := (&r.body).Bytes()
if utf8.Valid(bb) {
output = string(bb)
} else {
output = base64.StdEncoding.EncodeToString(bb)
isBase64 = true
}
headers := make(map[string]string)
for headerKey, headerValue := range http.Header(r.headers) {
headers[headerKey] = strings.Join(headerValue, ",")
}
return events.APIGatewayV2HTTPResponse{
StatusCode: r.status,
Headers: headers,
Body: output,
IsBase64Encoded: isBase64,
}, nil
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/iot.go<|end_filename|>
package events
// IoTCustomAuthorizerRequest contains data coming in to a custom IoT device gateway authorizer function.
type IoTCustomAuthorizerRequest struct {
HTTPContext *IoTHTTPContext `json:"httpContext,omitempty"`
MQTTContext *IoTMQTTContext `json:"mqttContext,omitempty"`
TLSContext *IoTTLSContext `json:"tlsContext,omitempty"`
AuthorizationToken string `json:"token"`
TokenSignature string `json:"tokenSignature"`
}
type IoTHTTPContext struct {
Headers map[string]string `json:"headers,omitempty"`
QueryString string `json:"queryString"`
}
type IoTMQTTContext struct {
ClientID string `json:"clientId"`
Password []byte `json:"password"`
Username string `json:"username"`
}
type IoTTLSContext struct {
ServerName string `json:"serverName"`
}
// IoTCustomAuthorizerResponse represents the expected format of an IoT device gateway authorization response.
type IoTCustomAuthorizerResponse struct {
IsAuthenticated bool `json:"isAuthenticated"`
PrincipalID string `json:"principalId"`
DisconnectAfterInSeconds int32 `json:"disconnectAfterInSeconds"`
RefreshAfterInSeconds int32 `json:"refreshAfterInSeconds"`
PolicyDocuments []string `json:"policyDocuments"`
}
<|start_filename|>vendor/github.com/aws/aws-sdk-go-v2/service/s3/internal/customizations/signer_wrapper.go<|end_filename|>
package customizations
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/service/s3/internal/v4a"
"github.com/aws/smithy-go/middleware"
)
type signerVersionKey struct{}
// GetSignerVersion retrieves the signer version to use for signing
//
// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues
// to clear all stack values.
func GetSignerVersion(ctx context.Context) (v string) {
v, _ = middleware.GetStackValue(ctx, signerVersionKey{}).(string)
return v
}
// SetSignerVersion sets the signer version to be used for signing the request
//
// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues
// to clear all stack values.
func SetSignerVersion(ctx context.Context, version string) context.Context {
return middleware.WithStackValue(ctx, signerVersionKey{}, version)
}
// SignHTTPRequestMiddlewareOptions is the configuration options for the SignHTTPRequestMiddleware middleware.
type SignHTTPRequestMiddlewareOptions struct {
// credential provider
CredentialsProvider aws.CredentialsProvider
// log signing
LogSigning bool
// v4 signer
V4Signer v4.HTTPSigner
//v4a signer
V4aSigner v4a.HTTPSigner
}
// NewSignHTTPRequestMiddleware constructs a SignHTTPRequestMiddleware using the given Signer for signing requests
func NewSignHTTPRequestMiddleware(options SignHTTPRequestMiddlewareOptions) *SignHTTPRequestMiddleware {
return &SignHTTPRequestMiddleware{
credentialsProvider: options.CredentialsProvider,
v4Signer: options.V4Signer,
v4aSigner: options.V4aSigner,
logSigning: options.LogSigning,
}
}
// SignHTTPRequestMiddleware is a `FinalizeMiddleware` implementation to select HTTP Signing method
type SignHTTPRequestMiddleware struct {
// credential provider
credentialsProvider aws.CredentialsProvider
// log signing
logSigning bool
// v4 signer
v4Signer v4.HTTPSigner
//v4a signer
v4aSigner v4a.HTTPSigner
}
// ID is the SignHTTPRequestMiddleware identifier
func (s *SignHTTPRequestMiddleware) ID() string {
return "Signing"
}
// HandleFinalize will take the provided input and sign the request using the SigV4 authentication scheme
func (s *SignHTTPRequestMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (
out middleware.FinalizeOutput, metadata middleware.Metadata, err error,
) {
// fetch signer type from context
signerVersion := GetSignerVersion(ctx)
switch signerVersion {
case v4a.Version:
v4aCredentialProvider, ok := s.credentialsProvider.(v4a.CredentialsProvider)
if !ok {
return out, metadata, fmt.Errorf("invalid credential-provider provided for sigV4a Signer")
}
mw := v4a.NewSignHTTPRequestMiddleware(v4a.SignHTTPRequestMiddlewareOptions{
Credentials: v4aCredentialProvider,
Signer: s.v4aSigner,
LogSigning: s.logSigning,
})
return mw.HandleFinalize(ctx, in, next)
default:
mw := v4.NewSignHTTPRequestMiddleware(v4.SignHTTPRequestMiddlewareOptions{
CredentialsProvider: s.credentialsProvider,
Signer: s.v4Signer,
LogSigning: s.logSigning,
})
return mw.HandleFinalize(ctx, in, next)
}
}
// RegisterSigningMiddleware registers the wrapper signing middleware to the stack. If a signing middleware is already
// present, this provided middleware will be swapped. Otherwise the middleware will be added at the tail of the
// finalize step.
func RegisterSigningMiddleware(stack *middleware.Stack, signingMiddleware *SignHTTPRequestMiddleware) (err error) {
const signedID = "Signing"
_, present := stack.Finalize.Get(signedID)
if present {
_, err = stack.Finalize.Swap(signedID, signingMiddleware)
} else {
err = stack.Finalize.Add(signingMiddleware, middleware.After)
}
return err
}
// PresignHTTPRequestMiddlewareOptions is the options for the PresignHTTPRequestMiddleware middleware.
type PresignHTTPRequestMiddlewareOptions struct {
CredentialsProvider aws.CredentialsProvider
V4Presigner v4.HTTPPresigner
V4aPresigner v4a.HTTPPresigner
LogSigning bool
}
// PresignHTTPRequestMiddleware provides the Finalize middleware for creating a
// presigned URL for an HTTP request.
//
// Will short circuit the middleware stack and not forward onto the next
// Finalize handler.
type PresignHTTPRequestMiddleware struct {
// cred provider and signer for sigv4
credentialsProvider aws.CredentialsProvider
// sigV4 signer
v4Signer v4.HTTPPresigner
// sigV4a signer
v4aSigner v4a.HTTPPresigner
// log signing
logSigning bool
}
// NewPresignHTTPRequestMiddleware constructs a PresignHTTPRequestMiddleware using the given Signer for signing requests
func NewPresignHTTPRequestMiddleware(options PresignHTTPRequestMiddlewareOptions) *PresignHTTPRequestMiddleware {
return &PresignHTTPRequestMiddleware{
credentialsProvider: options.CredentialsProvider,
v4Signer: options.V4Presigner,
v4aSigner: options.V4aPresigner,
logSigning: options.LogSigning,
}
}
// ID provides the middleware ID.
func (*PresignHTTPRequestMiddleware) ID() string { return "PresignHTTPRequest" }
// HandleFinalize will take the provided input and create a presigned url for
// the http request using the SigV4 or SigV4a presign authentication scheme.
//
// Since the signed request is not a valid HTTP request
func (p *PresignHTTPRequestMiddleware) HandleFinalize(
ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler,
) (
out middleware.FinalizeOutput, metadata middleware.Metadata, err error,
) {
// fetch signer type from context
signerVersion := GetSignerVersion(ctx)
switch signerVersion {
case v4a.Version:
v4aCredentialProvider, ok := p.credentialsProvider.(v4a.CredentialsProvider)
if !ok {
return out, metadata, fmt.Errorf("invalid credential-provider provided for sigV4a Signer")
}
mw := v4a.NewPresignHTTPRequestMiddleware(v4a.PresignHTTPRequestMiddlewareOptions{
CredentialsProvider: v4aCredentialProvider,
Presigner: p.v4aSigner,
LogSigning: p.logSigning,
})
return mw.HandleFinalize(ctx, in, next)
default:
mw := v4.NewPresignHTTPRequestMiddleware(v4.PresignHTTPRequestMiddlewareOptions{
CredentialsProvider: p.credentialsProvider,
Presigner: p.v4Signer,
LogSigning: p.logSigning,
})
return mw.HandleFinalize(ctx, in, next)
}
}
// RegisterPreSigningMiddleware registers the wrapper pre-signing middleware to the stack. If a pre-signing middleware is already
// present, this provided middleware will be swapped. Otherwise the middleware will be added at the tail of the
// finalize step.
func RegisterPreSigningMiddleware(stack *middleware.Stack, signingMiddleware *PresignHTTPRequestMiddleware) (err error) {
const signedID = "PresignHTTPRequest"
_, present := stack.Finalize.Get(signedID)
if present {
_, err = stack.Finalize.Swap(signedID, signingMiddleware)
} else {
err = stack.Finalize.Add(signingMiddleware, middleware.After)
}
return err
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/appsync.go<|end_filename|>
package events
import "encoding/json"
// AppSyncResolverTemplate represents the requests from AppSync to Lambda
type AppSyncResolverTemplate struct {
Version string `json:"version"`
Operation AppSyncOperation `json:"operation"`
Payload json.RawMessage `json:"payload"`
}
// AppSyncIAMIdentity contains information about the caller authed via IAM.
type AppSyncIAMIdentity struct {
AccountID string `json:"accountId"`
CognitoIdentityPoolID string `json:"cognitoIdentityPoolId"`
CognitoIdentityID string `json:"cognitoIdentityId"`
SourceIP []string `json:"sourceIp"`
Username string `json:"username"`
UserARN string `json:"userArn"`
}
// AppSyncCognitoIdentity contains information about the caller authed via Cognito.
type AppSyncCognitoIdentity struct {
Sub string `json:"sub"`
Issuer string `json:"issuer"`
Username string `json:"username"`
Claims map[string]interface{} `json:"claims"`
SourceIP []string `json:"sourceIp"`
DefaultAuthStrategy string `json:"defaultAuthStrategy"`
}
// AppSyncOperation specifies the operation type supported by Lambda operations
type AppSyncOperation string
const (
// OperationInvoke lets AWS AppSync know to call your Lambda function for every GraphQL field resolver
OperationInvoke AppSyncOperation = "Invoke"
// OperationBatchInvoke instructs AWS AppSync to batch requests for the current GraphQL field
OperationBatchInvoke AppSyncOperation = "BatchInvoke"
)
// AppSyncLambdaAuthorizerRequest contains an authorization request from AppSync.
type AppSyncLambdaAuthorizerRequest struct {
AuthorizationToken string `json:"authorizationToken"`
RequestContext AppSyncLambdaAuthorizerRequestContext `json:"requestContext"`
}
// AppSyncLambdaAuthorizerRequestContext contains the parameters of the AppSync invocation which triggered
// this authorization request.
type AppSyncLambdaAuthorizerRequestContext struct {
APIID string `json:"apiId"`
AccountID string `json:"accountId"`
RequestID string `json:"requestId"`
QueryString string `json:"queryString"`
OperationName string `json:"operationName"`
Variables map[string]interface{} `json:"variables"`
}
// AppSyncLambdaAuthorizerResponse represents the expected format of an authorization response to AppSync.
type AppSyncLambdaAuthorizerResponse struct {
IsAuthorized bool `json:"isAuthorized"`
ResolverContext map[string]interface{} `json:"resolverContext,omitempty"`
DeniedFields []string `json:"deniedFields,omitempty"`
TTLOverride *int `json:"ttlOverride,omitempty"`
}
<|start_filename|>vendor/github.com/andybalholm/brotli/writer.go<|end_filename|>
package brotli
import (
"errors"
"io"
)
const (
BestSpeed = 0
BestCompression = 11
DefaultCompression = 6
)
// WriterOptions configures Writer.
type WriterOptions struct {
// Quality controls the compression-speed vs compression-density trade-offs.
// The higher the quality, the slower the compression. Range is 0 to 11.
Quality int
// LGWin is the base 2 logarithm of the sliding window size.
// Range is 10 to 24. 0 indicates automatic configuration based on Quality.
LGWin int
}
var (
errEncode = errors.New("brotli: encode error")
errWriterClosed = errors.New("brotli: Writer is closed")
)
// Writes to the returned writer are compressed and written to dst.
// It is the caller's responsibility to call Close on the Writer when done.
// Writes may be buffered and not flushed until Close.
func NewWriter(dst io.Writer) *Writer {
return NewWriterLevel(dst, DefaultCompression)
}
// NewWriterLevel is like NewWriter but specifies the compression level instead
// of assuming DefaultCompression.
// The compression level can be DefaultCompression or any integer value between
// BestSpeed and BestCompression inclusive.
func NewWriterLevel(dst io.Writer, level int) *Writer {
return NewWriterOptions(dst, WriterOptions{
Quality: level,
})
}
// NewWriterOptions is like NewWriter but specifies WriterOptions
func NewWriterOptions(dst io.Writer, options WriterOptions) *Writer {
w := new(Writer)
w.options = options
w.Reset(dst)
return w
}
// Reset discards the Writer's state and makes it equivalent to the result of
// its original state from NewWriter or NewWriterLevel, but writing to dst
// instead. This permits reusing a Writer rather than allocating a new one.
func (w *Writer) Reset(dst io.Writer) {
encoderInitState(w)
w.params.quality = w.options.Quality
if w.options.LGWin > 0 {
w.params.lgwin = uint(w.options.LGWin)
}
w.dst = dst
w.err = nil
}
func (w *Writer) writeChunk(p []byte, op int) (n int, err error) {
if w.dst == nil {
return 0, errWriterClosed
}
if w.err != nil {
return 0, w.err
}
for {
availableIn := uint(len(p))
nextIn := p
success := encoderCompressStream(w, op, &availableIn, &nextIn)
bytesConsumed := len(p) - int(availableIn)
p = p[bytesConsumed:]
n += bytesConsumed
if !success {
return n, errEncode
}
if len(p) == 0 || w.err != nil {
return n, w.err
}
}
}
// Flush outputs encoded data for all input provided to Write. The resulting
// output can be decoded to match all input before Flush, but the stream is
// not yet complete until after Close.
// Flush has a negative impact on compression.
func (w *Writer) Flush() error {
_, err := w.writeChunk(nil, operationFlush)
return err
}
// Close flushes remaining data to the decorated writer.
func (w *Writer) Close() error {
// If stream is already closed, it is reported by `writeChunk`.
_, err := w.writeChunk(nil, operationFinish)
w.dst = nil
return err
}
// Write implements io.Writer. Flush or Close must be called to ensure that the
// encoded bytes are actually flushed to the underlying Writer.
func (w *Writer) Write(p []byte) (n int, err error) {
return w.writeChunk(p, operationProcess)
}
type nopCloser struct {
io.Writer
}
func (nopCloser) Close() error { return nil }
<|start_filename|>vendor/github.com/aws/aws-sdk-go-v2/service/s3/internal/v4a/internal/crypto/ecc.go<|end_filename|>
package crypto
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/hmac"
"encoding/asn1"
"encoding/binary"
"fmt"
"hash"
"math"
"math/big"
)
type ecdsaSignature struct {
R, S *big.Int
}
// ECDSAKey takes the given elliptic curve, and private key (d) byte slice
// and returns the private ECDSA key.
func ECDSAKey(curve elliptic.Curve, d []byte) *ecdsa.PrivateKey {
return ECDSAKeyFromPoint(curve, (&big.Int{}).SetBytes(d))
}
// ECDSAKeyFromPoint takes the given elliptic curve and point and returns the
// private and public keypair
func ECDSAKeyFromPoint(curve elliptic.Curve, d *big.Int) *ecdsa.PrivateKey {
pX, pY := curve.ScalarBaseMult(d.Bytes())
privKey := &ecdsa.PrivateKey{
PublicKey: ecdsa.PublicKey{
Curve: curve,
X: pX,
Y: pY,
},
D: d,
}
return privKey
}
// ECDSAPublicKey takes the provide curve and (x, y) coordinates and returns
// *ecdsa.PublicKey. Returns an error if the given points are not on the curve.
func ECDSAPublicKey(curve elliptic.Curve, x, y []byte) (*ecdsa.PublicKey, error) {
xPoint := (&big.Int{}).SetBytes(x)
yPoint := (&big.Int{}).SetBytes(y)
if !curve.IsOnCurve(xPoint, yPoint) {
return nil, fmt.Errorf("point(%v, %v) is not on the given curve", xPoint.String(), yPoint.String())
}
return &ecdsa.PublicKey{
Curve: curve,
X: xPoint,
Y: yPoint,
}, nil
}
// VerifySignature takes the provided public key, hash, and asn1 encoded signature and returns
// whether the given signature is valid.
func VerifySignature(key *ecdsa.PublicKey, hash []byte, signature []byte) (bool, error) {
var ecdsaSignature ecdsaSignature
_, err := asn1.Unmarshal(signature, &ecdsaSignature)
if err != nil {
return false, err
}
return ecdsa.Verify(key, hash, ecdsaSignature.R, ecdsaSignature.S), nil
}
// HMACKeyDerivation provides an implementation of a NIST-800-108 of a KDF (Key Derivation Function) in Counter Mode.
// For the purposes of this implantation HMAC is used as the PRF (Pseudorandom function), where the value of
// `r` is defined as a 4 byte counter.
func HMACKeyDerivation(hash func() hash.Hash, bitLen int, key []byte, label, context []byte) ([]byte, error) {
// verify that we won't overflow the counter
n := int64(math.Ceil((float64(bitLen) / 8) / float64(hash().Size())))
if n > 0x7FFFFFFF {
return nil, fmt.Errorf("unable to derive key of size %d using 32-bit counter", bitLen)
}
// verify the requested bit length is not larger then the length encoding size
if int64(bitLen) > 0x7FFFFFFF {
return nil, fmt.Errorf("bitLen is greater than 32-bits")
}
fixedInput := bytes.NewBuffer(nil)
fixedInput.Write(label)
fixedInput.WriteByte(0x00)
fixedInput.Write(context)
if err := binary.Write(fixedInput, binary.BigEndian, int32(bitLen)); err != nil {
return nil, fmt.Errorf("failed to write bit length to fixed input string: %v", err)
}
var output []byte
h := hmac.New(hash, key)
for i := int64(1); i <= n; i++ {
h.Reset()
if err := binary.Write(h, binary.BigEndian, int32(i)); err != nil {
return nil, err
}
_, err := h.Write(fixedInput.Bytes())
if err != nil {
return nil, err
}
output = append(output, h.Sum(nil)...)
}
return output[:bitLen/8], nil
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/config.go<|end_filename|>
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
// ConfigEvent contains data from an event sent from AWS Config
type ConfigEvent struct {
// The ID of the AWS account that owns the rule
AccountID string `json:"accountId"`
// The ARN that AWS Config assigned to the rule
ConfigRuleArn string `json:"configRuleArn"` //nolint:stylecheck
ConfigRuleID string `json:"configRuleId"` //nolint:stylecheck
// The name that you assigned to the rule that caused AWS Config to publish the event
ConfigRuleName string `json:"configRuleName"`
// A boolean value that indicates whether the AWS resource to be evaluated has been removed from the rule's scope
EventLeftScope bool `json:"eventLeftScope"`
ExecutionRoleArn string `json:"executionRoleArn"` //nolint:stylecheck
// If the event is published in response to a resource configuration change, this value contains a JSON configuration item
InvokingEvent string `json:"invokingEvent"`
// A token that the function must pass to AWS Config with the PutEvaluations call
ResultToken string `json:"resultToken"`
// Key/value pairs that the function processes as part of its evaluation logic
RuleParameters string `json:"ruleParameters"`
Version string `json:"version"`
}
<|start_filename|>vendor/github.com/aws/aws-lambda-go/events/iot_1_click.go<|end_filename|>
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package events
// IoTOneClickEvent represents a click event published by clicking button type
// device.
type IoTOneClickEvent struct {
DeviceEvent IoTOneClickDeviceEvent `json:"deviceEvent"`
DeviceInfo IoTOneClickDeviceInfo `json:"deviceInfo"`
PlacementInfo IoTOneClickPlacementInfo `json:"placementInfo"`
}
type IoTOneClickDeviceEvent struct {
ButtonClicked IoTOneClickButtonClicked `json:"buttonClicked"`
}
type IoTOneClickButtonClicked struct {
ClickType string `json:"clickType"`
ReportedTime string `json:"reportedTime"`
}
type IoTOneClickDeviceInfo struct {
Attributes map[string]string `json:"attributes"`
Type string `json:"type"`
DeviceID string `json:"deviceId"`
RemainingLife float64 `json:"remainingLife"`
}
type IoTOneClickPlacementInfo struct {
ProjectName string `json:"projectName"`
PlacementName string `json:"placementName"`
Attributes map[string]string `json:"attributes"`
Devices map[string]string `json:"devices"`
}
| ahamlinman/importbounce |
<|start_filename|>token_generic.go<|end_filename|>
package gojsonlex
// TokenGeneric is a generic struct used to represent any possible JSON token
type TokenGeneric struct {
t TokenType
boolean bool
str string
number float64
delim byte
}
func newTokenGenericFromString(s string) TokenGeneric {
return TokenGeneric{
t: LexerTokenTypeString,
str: s,
}
}
func newTokenGenericFromNumber(f float64) TokenGeneric {
return TokenGeneric{
t: LexerTokenTypeNumber,
number: f,
}
}
func newTokenGenericFromBool(b bool) TokenGeneric {
return TokenGeneric{
t: LexerTokenTypeBool,
boolean: b,
}
}
func newTokenGenericFromNull() TokenGeneric {
return TokenGeneric{
t: LexerTokenTypeNull,
}
}
func newTokenGenericFromDelim(d byte) TokenGeneric {
return TokenGeneric{
t: LexerTokenTypeDelim,
delim: d,
}
}
// Type returns type of the token
func (t *TokenGeneric) Type() TokenType {
return t.t
}
// String returns string that points into internal lexer buffer and is guaranteed
// to be valid until the next Token call, otherwise you MUST make a deep copy
func (t *TokenGeneric) String() string {
return t.str
}
// StringCopy return a deep copy of string
func (t *TokenGeneric) StringCopy() string {
return StringDeepCopy(t.str)
}
func (t *TokenGeneric) Bool() bool {
return t.boolean
}
func (t *TokenGeneric) Delim() byte {
return t.delim
}
func (t *TokenGeneric) Number() float64 {
return t.number
}
func (t *TokenGeneric) IsNull() bool {
return t.t == LexerTokenTypeNull
}
<|start_filename|>Makefile<|end_filename|>
EXAMPLES_SRCS=$(wildcard examples/*)
EXAMPLES_BINS=$(addprefix bin/, $(notdir $(basename $(EXAMPLES_SRCS))))
examples: $(EXAMPLES_BINS)
$(EXAMPLES_BINS):
go build -o $@ github.com/gibsn/gojsonlex/examples/$(notdir $@)
test:
go test .
bench:
# go test -bench=. -benchmem -memprofile=out.mem -cpuprofile=out.cpu -memprofilerate=1
go test -bench=. -benchmem
clean:
rm -rf ./bin
.PHONY: test bench examples clean
<|start_filename|>lexer_test.go<|end_filename|>
package gojsonlex
import (
"bytes"
"encoding/json"
"io"
"strings"
"testing"
)
type jsonLexerOutputToken struct {
token interface{}
tokenType TokenType
}
type jsonLexerTestCase struct {
input string
output []jsonLexerOutputToken
skipDelims bool
}
func TestJSONLexer(t *testing.T) {
testcases := []jsonLexerTestCase{
// tests for strings
{
input: `{"hello":"world"}`,
output: []jsonLexerOutputToken{
{
"hello",
LexerTokenTypeString,
},
{
"world",
LexerTokenTypeString,
},
},
},
{
input: `{"liveness_info" : { "tstamp" : "2020-05-06T12:57:14.193447Z" }}`,
output: []jsonLexerOutputToken{
{
"liveness_info",
LexerTokenTypeString,
},
{
"tstamp",
LexerTokenTypeString,
},
{
"2020-05-06T12:57:14.193447Z",
LexerTokenTypeString,
},
},
},
{
input: `{"ua": "\"SomeUA\""}`,
output: []jsonLexerOutputToken{
{
"ua",
LexerTokenTypeString,
},
{
"\"SomeUA\"",
LexerTokenTypeString,
},
},
},
// tests for numbers
{
input: `{"hello":{"0": 10, "1": 11.0}}`,
output: []jsonLexerOutputToken{
{
"hello",
LexerTokenTypeString,
},
{
"0",
LexerTokenTypeString,
},
{
float64(10),
LexerTokenTypeNumber,
},
{
"1",
LexerTokenTypeString,
},
{
float64(11),
LexerTokenTypeNumber,
},
},
},
// {
// input: `{"hello":{"0": -10, "1": -11.0}}`,
// output: []jsonLexerOutputToken{
// {
// "hello",
// LexerTokenTypeString,
// },
// {
// "0",
// LexerTokenTypeString,
// },
// {
// float64(-10),
// LexerTokenTypeNumber,
// },
// {
// "1",
// LexerTokenTypeString,
// },
// {
// float64(-11),
// LexerTokenTypeNumber,
// },
// },
// },
// tests for special symbols
{
input: `{"ua": "\"\"Some\nWeird\tUA\"\""}`,
output: []jsonLexerOutputToken{
{
"ua",
LexerTokenTypeString,
},
{
"\"\"Some\nWeird\tUA\"\"",
LexerTokenTypeString,
},
},
},
// tests for Unicode
{
input: `{"desc": "\u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \u043f\u043e\u0447\u0442\u044b"}`,
output: []jsonLexerOutputToken{
{
"desc",
LexerTokenTypeString,
},
{
"Проверка почты",
LexerTokenTypeString,
},
},
},
// tests for Null
{
input: `{"ua": Null}`,
output: []jsonLexerOutputToken{
{
"ua",
LexerTokenTypeString,
},
{
nil,
LexerTokenTypeNull,
},
},
},
{
input: `{"ua": null}`,
output: []jsonLexerOutputToken{
{
"ua",
LexerTokenTypeString,
},
{
nil,
LexerTokenTypeNull,
},
},
},
// tests for Bool
{
input: `{"isValid": true}`,
output: []jsonLexerOutputToken{
{
"isValid",
LexerTokenTypeString,
},
{
true,
LexerTokenTypeBool,
},
},
},
{
input: `{"isValid": True}`,
output: []jsonLexerOutputToken{
{
"isValid",
LexerTokenTypeString,
},
{
true,
LexerTokenTypeBool,
},
},
},
{
input: `{"isValid": false}`,
output: []jsonLexerOutputToken{
{
"isValid",
LexerTokenTypeString,
},
{
false,
LexerTokenTypeBool,
},
},
},
{
input: `{"isValid": False}`,
output: []jsonLexerOutputToken{
{
"isValid",
LexerTokenTypeString,
},
{
false,
LexerTokenTypeBool,
},
},
},
{
input: `{"isValid": False}`,
output: []jsonLexerOutputToken{
{
"isValid",
LexerTokenTypeString,
},
{
false,
LexerTokenTypeBool,
},
},
},
{
input: `{"delta": 3.14, "temperature": -52, "distance": 1.57e+10, "size": 1.2E-10}`,
output: []jsonLexerOutputToken{
{"delta", LexerTokenTypeString},
{float64(3.14), LexerTokenTypeNumber},
{"temperature", LexerTokenTypeString},
{float64(-52), LexerTokenTypeNumber},
{"distance", LexerTokenTypeString},
{float64(1.57e10), LexerTokenTypeNumber},
{"size", LexerTokenTypeString},
{float64(1.2e-10), LexerTokenTypeNumber},
},
},
{
// should not be supported according to json.org
input: `{"delta1": .314, "delta2": 314.}`,
output: []jsonLexerOutputToken{
{"delta1", LexerTokenTypeString},
{float64(0.314), LexerTokenTypeNumber},
{"delta2", LexerTokenTypeString},
{float64(314.), LexerTokenTypeNumber},
},
},
}
for _, testcase := range testcases {
l, err := NewJSONLexer(strings.NewReader(testcase.input))
if err != nil {
t.Errorf("testcase '%s': could not create lexer: %v", testcase.input, err)
continue
}
l.SetBufSize(4)
tokensFound := 0
for {
token, err := l.Token()
if err != nil {
if err == io.EOF {
break
}
t.Errorf("testcase '%s': %v", testcase.input, err)
break
}
expectedOutput := testcase.output[tokensFound]
switch expectedOutput.tokenType {
case LexerTokenTypeString:
if token != expectedOutput.token.(string) {
t.Errorf("testcase '%s': expected token '%v', got '%s'",
testcase.input, testcase.output[tokensFound].token, token)
break
}
case LexerTokenTypeNumber:
if token != expectedOutput.token.(float64) {
t.Errorf("testcase '%s': expected token '%v', got '%f'",
testcase.input, testcase.output[tokensFound].token, token)
break
}
case LexerTokenTypeBool:
if token != expectedOutput.token.(bool) {
t.Errorf("testcase '%s': expected token '%v', got '%t'",
testcase.input, testcase.output[tokensFound].token, token)
break
}
case LexerTokenTypeNull:
if token != nil {
t.Errorf("testcase '%s': expected token '%v', got '%t'",
testcase.input, testcase.output[tokensFound].token, token)
break
}
}
tokensFound++
}
if tokensFound != len(testcase.output) {
t.Errorf("testcase '%s': expected %d tokens, got %d",
testcase.input, len(testcase.output), tokensFound)
continue
}
}
}
func TestJSONLexerFails(t *testing.T) {
testcases := []jsonLexerTestCase{
{`{"hello":"\u123r"}`, nil, false},
{`{"hello":"\a"}`, nil, false},
{`{"hello`, nil, false},
{`{"hello": Nuii}`, nil, false},
{`{"isValid": tru}`, nil, false},
{`{"isValid": folse}`, nil, false},
{`{"delta": 3.1.4}`, nil, false},
{`{"temperature": 5-2}`, nil, false},
{`{"distance": 1.57+10}`, nil, false},
{`{"size": 1.2e*10}`, nil, false},
{`{"distance": 1.57+e10}`, nil, false},
{`{"size": 1.210-e}`, nil, false},
}
for _, testcase := range testcases {
l, err := NewJSONLexer(strings.NewReader(testcase.input))
if err != nil {
t.Errorf("testcase '%s': could not create lexer: %v", testcase.input, err)
continue
}
l.SetBufSize(64)
errFound := false
for {
_, err := l.Token()
if err != nil {
if err == io.EOF {
break
}
errFound = true
break
}
}
if !errFound {
t.Errorf("testcase '%s': must have failed", testcase.input)
}
}
}
const (
jsonSample = ` {
"type" : "row",
"position" : 471,
"clustering" : [ "1b5bf100-8f99-11ea-8e8d-fa163e4302ba" ],
"liveness_info" : { "tstamp" : "2020-05-06T12:57:14.193447Z" },
"cells" : [
{ "name" : "event_id", "value" : 253 },
{ "name" : "ip", "value" : "172.16.31.10" },
{ "name" : "is_valid", "value" : true },
{ "name" : "session_id", "value" : null },
{ "name" : "delta", "value" : 3.14 },
{ "name" : "temperature", "value" : -52 },
{ "name" : "distance", "value" : 1.57e10 },
{ "name" : "args", "deletion_info" : { "marked_deleted" : "2020-05-06T12:57:14.193446Z", "local_delete_time" : "2020-05-06T12:57:14Z" } },
{ "name" : "args", "path" : [ "f" ], "value" : "fdevmail.openstacklocal" },
{ "name" : "args", "path" : [ "h" ], "value" : "internal-api.devmail.ru" },
{ "name" : "args", "path" : [ "ip" ], "value" : "127.0.0.1" },
{ "name" : "args", "path" : [ "rid" ], "value" : "8c28ca1055" },
{ "name" : "args", "path" : [ "ua" ], "value" : "\"Go-http-client/1.1\"" },
{ "desc": "\u041f\u0440\u043e\u0432\u0435\u0440\u043a\u0430 \\UD83D\\UDCA9 \u043f\u043e\u0447\u0442\u044b"}
]
}`
)
func generateBenchmarkInput(b *bytes.Buffer, numObjects int) {
for i := 0; i < numObjects; i++ {
if i > 0 {
b.WriteRune(',')
}
b.WriteString(jsonSample)
}
}
func BenchmarkEncodingJSON(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
input := bytes.NewBuffer(nil)
input.WriteRune('[')
generateBenchmarkInput(input, 100)
input.WriteRune(']')
dec := json.NewDecoder(input)
b.StartTimer()
for {
_, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
b.Errorf("could not get next token: %v", err)
}
}
}
}
func BenchmarkJSONLexer(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
input := bytes.NewBuffer(nil)
generateBenchmarkInput(input, 100)
l, err := NewJSONLexer(input)
if err != nil {
b.Errorf("could not create JSONLexer: %v", err)
}
b.StartTimer()
for {
_, err := l.Token()
if err == io.EOF {
break
}
if err != nil {
b.Errorf("could not get next token: %v", err)
}
}
}
}
func BenchmarkJSONLexerFast(b *testing.B) {
for i := 0; i < b.N; i++ {
b.StopTimer()
input := bytes.Buffer{}
generateBenchmarkInput(&input, 100)
l, err := NewJSONLexer(&input)
if err != nil {
b.Errorf("could not create JSONLexer: %v", err)
}
l.SetBufSize(1024)
b.StartTimer()
for {
_, err := l.TokenFast()
if err == io.EOF {
break
}
if err != nil {
b.Errorf("could not get next token: %v", err)
}
}
}
}
<|start_filename|>lexer.go<|end_filename|>
package gojsonlex
import (
"encoding/json"
"fmt"
"io"
"log"
"strconv"
"unicode"
)
const (
defaultBufSize = 4096
)
type lexerState byte
const (
stateLexerIdle lexerState = iota
stateLexerSkipping
stateLexerString
stateLexerPendingEscapedSymbol
stateLexerUnicodeRune
stateLexerNumber
stateLexerBool
stateLexerNull
)
// JSONLexer is a JSON lexical analyzer with streaming API support, where stream is a sequence of
// JSON tokens. JSONLexer does its own IO buffering so prefer low-level readers if you want
// to miminize memory footprint.
//
// JSONLexer uses a ring buffer for parsing tokens, every token must fit in its size, otherwise
// buffer will be automatically grown. Initial size of buffer is 4096 bytes, however you can tweak
// it with SetBufSize() in case you know that most tokens are going to be long.
//
// JSONLexer uses unsafe pointers into the underlying buf to minimize allocations, see Token()
// for the provided guarantees.
type JSONLexer struct {
r io.Reader
readingFinished bool // reports whether r has more data to read
state lexerState
buf []byte
currPos int // current positin in buffer
unicodeRuneBytesCounter byte // a counter used to validate a unicode rune
currTokenStart int // positin in the buf of current token start (if any)
currTokenEnd int // positin in the buf of current token start (if any)
currTokenType TokenType
newTokenFound bool // true if during the last feed() a new token was finished being parsed
skipDelims bool
debug bool
}
// NewJSONLexer creates a new JSONLexer with the given reader.
func NewJSONLexer(r io.Reader) (*JSONLexer, error) {
l := &JSONLexer{
r: r,
buf: make([]byte, defaultBufSize),
}
return l, nil
}
// SetBufSize creates a new buffer of the given size. MUST be called before parsing started.
func (l *JSONLexer) SetBufSize(bufSize int) {
l.buf = make([]byte, bufSize)
}
// SetSkipDelims tells JSONLexer to skip delimiters and return only keys and values. This can
// be useful in case you want to simply match the input to some specific grammar and have no
// intention of doing full syntax analysis.
func (l *JSONLexer) SetSkipDelims(mustSkip bool) {
l.skipDelims = true
}
// SetDebug enables debug logging
func (l *JSONLexer) SetDebug(debug bool) {
l.debug = true
}
func (l *JSONLexer) processStateSkipping(c byte) error {
switch {
case c == '"':
l.state = stateLexerString
l.currTokenType = LexerTokenTypeString
l.currTokenStart = l.currPos
case CanAppearInNumber(rune(c)):
l.state = stateLexerNumber
l.currTokenType = LexerTokenTypeNumber
l.currTokenStart = l.currPos
case c == 't' || c == 'T':
fallthrough
case c == 'f' || c == 'F':
l.state = stateLexerBool
l.currTokenType = LexerTokenTypeBool
l.currTokenStart = l.currPos
case c == 'n' || c == 'N':
l.state = stateLexerNull
l.currTokenType = LexerTokenTypeNull
l.currTokenStart = l.currPos
default:
// skipping
}
return nil
}
func (l *JSONLexer) processStateString(c byte) error {
switch c {
case '"':
l.state = stateLexerSkipping
l.currTokenEnd = l.currPos
l.newTokenFound = true
case '\\':
l.state = stateLexerPendingEscapedSymbol
default:
// accumulating string
}
return nil
}
func (l *JSONLexer) processStatePendingEscapedSymbol(c byte) error {
if !IsValidEscapedSymbol(rune(c)) {
return fmt.Errorf("invalid escape sequence '\\%c'", c)
}
if c == 'u' || c == 'U' {
l.state = stateLexerUnicodeRune
l.unicodeRuneBytesCounter = 0
return nil
}
l.state = stateLexerString
return nil
}
func (l *JSONLexer) processStateUnicodeRune(c byte) error {
if !IsHexDigit(rune(c)) {
return fmt.Errorf("invalid hex digit '%c' inside escaped unicode rune", c)
}
l.unicodeRuneBytesCounter++
if l.unicodeRuneBytesCounter == 4 {
l.state = stateLexerString
}
return nil
}
func (l *JSONLexer) processStateNumber(c byte) error {
switch {
case unicode.IsDigit(rune(c)):
fallthrough
case c == '.':
// accumulating number
case IsDelim(rune(c)):
fallthrough
case unicode.IsSpace(rune(c)):
l.state = stateLexerSkipping
l.currTokenEnd = l.currPos
l.newTokenFound = true
}
return nil
}
func (l *JSONLexer) processStateNull(c byte) error {
currPositionInToken := l.currPos - l.currTokenStart
if currPositionInToken == len("null") {
l.state = stateLexerSkipping
l.currTokenEnd = l.currPos
l.newTokenFound = true
return nil
}
expectedLiteral := rune("null"[currPositionInToken])
if unicode.ToLower(rune(c)) != expectedLiteral {
return fmt.Errorf("invalid literal '%c' while parsing 'Null' value", c)
}
return nil
}
func (l *JSONLexer) processStateBool(c byte) error {
firstCharOfToken := unicode.ToLower(rune(l.buf[l.currTokenStart]))
currPositionInToken := l.currPos - l.currTokenStart
var expectedToken string
switch firstCharOfToken {
case 't':
expectedToken = "true"
case 'f':
expectedToken = "false"
}
if currPositionInToken == len(expectedToken) {
l.state = stateLexerSkipping
l.currTokenEnd = l.currPos
l.newTokenFound = true
return nil
}
expectedLiteral := rune(expectedToken[currPositionInToken])
if unicode.ToLower(rune(c)) != expectedLiteral {
return fmt.Errorf("invalid literal '%c' while parsing bool value", c)
}
return nil
}
func (l *JSONLexer) feed(c byte) error {
switch l.state {
case stateLexerSkipping:
return l.processStateSkipping(c)
case stateLexerString:
return l.processStateString(c)
case stateLexerPendingEscapedSymbol:
return l.processStatePendingEscapedSymbol(c)
case stateLexerUnicodeRune:
return l.processStateUnicodeRune(c)
case stateLexerNumber:
return l.processStateNumber(c)
case stateLexerBool:
return l.processStateBool(c)
case stateLexerNull:
return l.processStateNull(c)
}
return nil
}
func (l *JSONLexer) currTokenAsUnsafeString() (string, error) {
// skipping "
var subStr = l.buf[l.currTokenStart+1 : l.currTokenEnd]
subStr, err := UnescapeBytesInplace(subStr)
if err != nil {
return "", err
}
return unsafeStringFromBytes(subStr), nil
}
func (l *JSONLexer) currTokenAsNumber() (float64, error) {
str := unsafeStringFromBytes(l.buf[l.currTokenStart:l.currTokenEnd])
n, err := strconv.ParseFloat(str, 64)
if err != nil {
return 0, fmt.Errorf("could not convert '%s' to float64: %w", StringDeepCopy(str), err)
}
return n, nil
}
func (l *JSONLexer) currTokenAsBool() (bool, error) {
if unicode.ToLower(rune(l.buf[l.currTokenStart])) == 't' {
return true, nil
}
if unicode.ToLower(rune(l.buf[l.currTokenStart])) == 'f' {
return false, nil
}
tokenAsStr := unsafeStringFromBytes(l.buf[l.currTokenStart:l.currTokenEnd])
return false, fmt.Errorf("could not convert '%s' to bool", StringDeepCopy(tokenAsStr))
}
func (l *JSONLexer) currToken() (TokenGeneric, error) {
switch l.currTokenType {
case LexerTokenTypeDelim:
return newTokenGenericFromDelim(l.buf[l.currTokenStart]), nil
case LexerTokenTypeString:
s, err := l.currTokenAsUnsafeString()
return newTokenGenericFromString(s), err
case LexerTokenTypeNumber:
n, err := l.currTokenAsNumber()
return newTokenGenericFromNumber(n), err
case LexerTokenTypeBool:
b, err := l.currTokenAsBool()
return newTokenGenericFromBool(b), err
case LexerTokenTypeNull:
return newTokenGenericFromNull(), nil
}
panic("unexpected token type")
}
func (l *JSONLexer) fetchNewData() error {
// if now some token is in the middle of parsing we gotta copy the part of it
// that has already been parsed, otherwise we won't be able to construct it
if l.state != stateLexerSkipping && l.state != stateLexerIdle {
dstBuf := l.buf
// checking if buf must be extended
currTokenBytesParsed := l.currPos - l.currTokenStart
if currTokenBytesParsed >= l.currTokenStart {
newSize := 2 * len(l.buf)
dstBuf = make([]byte, newSize)
if l.debug {
log.Printf("debug: gojsonlex: growing buffer %d -> %d", len(l.buf), newSize)
}
}
// copying the part that has already been parsed
copy(dstBuf, l.buf[l.currTokenStart:])
l.currTokenStart = 0
l.currPos = currTokenBytesParsed
l.buf = dstBuf
} else {
l.currPos = 0
}
// reading new data into buf
n, err := io.ReadFull(l.r, l.buf[l.currPos:])
if err == io.EOF || err == io.ErrUnexpectedEOF {
l.readingFinished = true
l.buf = l.buf[:l.currPos+n]
} else if err != nil {
return fmt.Errorf("could not fetch new data: %w", err)
}
return nil
}
func (l *JSONLexer) shutdown() error {
if l.state != stateLexerSkipping {
return fmt.Errorf("unexpected EOF")
}
return io.EOF
}
// Token returns the next JSON token, all delimiters are skipped. Token will return io.EOF when
// all input has been exhausted. All strings returned by Token are guaranteed to be valid
// until the next Token call, otherwise you MUST make a deep copy.
func (l *JSONLexer) Token() (json.Token, error) {
t, err := l.TokenFast()
if err != nil {
return nil, err
}
switch t.t {
case LexerTokenTypeNull:
return nil, nil
case LexerTokenTypeDelim:
return t.delim, nil
case LexerTokenTypeNumber:
return t.number, nil
case LexerTokenTypeString:
return t.str, nil
case LexerTokenTypeBool:
return t.boolean, nil
}
panic("unknown token type")
}
// TokenFast is a more efficient version of Token(). All strings returned by Token
// are guaranteed to be valid until the next Token call, otherwise you MUST make a deep copy.
func (l *JSONLexer) TokenFast() (TokenGeneric, error) {
if l.state == stateLexerIdle {
if err := l.fetchNewData(); err != nil {
return TokenGeneric{}, err
}
l.state = stateLexerSkipping
}
for {
if l.currPos >= len(l.buf) {
if l.readingFinished {
return TokenGeneric{}, l.shutdown()
}
if err := l.fetchNewData(); err != nil {
return TokenGeneric{}, err
}
continue // last fetching could probably return 0 new bytes
}
if err := l.feed(l.buf[l.currPos]); err != nil {
return TokenGeneric{}, err
}
l.currPos++
if l.newTokenFound {
l.newTokenFound = false
break
}
}
return l.currToken()
}
<|start_filename|>gojsonlex.go<|end_filename|>
/*
TODO doc
*/
package gojsonlex
<|start_filename|>token.go<|end_filename|>
package gojsonlex
import (
"fmt"
"reflect"
"unicode"
"unicode/utf16"
"unicode/utf8"
"unsafe"
)
type TokenType byte
const (
LexerTokenTypeDelim TokenType = iota
LexerTokenTypeString
LexerTokenTypeNumber
LexerTokenTypeBool
LexerTokenTypeNull
)
const (
utf16SequenceLength = 4 // in digits
utf16MaxWordsForRune = 2
)
func (t TokenType) String() string {
switch t {
case LexerTokenTypeDelim:
return "delim"
case LexerTokenTypeString:
return "string"
case LexerTokenTypeNumber:
return "number"
case LexerTokenTypeBool:
return "bool"
case LexerTokenTypeNull:
return "null"
}
panic("unknown token type")
}
func unsafeStringFromBytes(arr []byte) string {
slice := (*reflect.SliceHeader)(unsafe.Pointer(&arr))
str := (*reflect.StringHeader)(unsafe.Pointer(slice))
str.Data = slice.Data
str.Len = slice.Len
return *(*string)(unsafe.Pointer(str))
}
type bytesUnescaper struct {
writeIter int
readIter int
input []byte
// state modificators
pendingEscapedSymbol bool
pendingUnicodeBytes byte
// since in UTF-16 rune may be encoded by either 1 or 2 words we
// may have to remember the previous word
pendingSecondUTF16SeqPoint bool
firstUTF16SeqPoint rune
}
// UnescapeBytesInplace iterates over the given slice of byte unescaping all
// escaped symbols inplace. Since the unescaped symbols take less space the shrinked
// slice of bytes is returned
func UnescapeBytesInplace(input []byte) ([]byte, error) {
u := bytesUnescaper{
input: input,
}
return u.doUnescaping()
}
func (u *bytesUnescaper) processUnicodeByte(c byte) error {
u.pendingUnicodeBytes--
if u.pendingUnicodeBytes != 0 {
return nil
}
// processing the last byte of unicode sequence
utf16Sequence := u.input[u.readIter+1-utf16SequenceLength : u.readIter+1]
runeAsUint, err := HexBytesToUint(utf16Sequence)
if err != nil {
return fmt.Errorf("invalid unicode sequence \\u%s", utf16Sequence)
}
outRune := rune(runeAsUint)
if utf16.IsSurrogate(outRune) && !u.pendingSecondUTF16SeqPoint {
u.pendingSecondUTF16SeqPoint = true
u.firstUTF16SeqPoint = outRune
return nil
}
if u.pendingSecondUTF16SeqPoint { // then we got a second elem and can decode now
outRune = utf16.DecodeRune(u.firstUTF16SeqPoint, outRune)
if outRune == unicode.ReplacementChar {
return fmt.Errorf("invalid surrogate pair %x%x", u.firstUTF16SeqPoint, outRune)
}
u.pendingSecondUTF16SeqPoint = false
}
n := utf8.EncodeRune(u.input[u.writeIter:], outRune)
u.writeIter += n
return nil
}
func (u *bytesUnescaper) processSpecialByte(c byte) error {
u.pendingEscapedSymbol = false
if c == 'u' || c == 'U' {
u.pendingUnicodeBytes = utf16SequenceLength
return nil
}
if u.pendingSecondUTF16SeqPoint {
return fmt.Errorf("missing second sequence point for %x", u.firstUTF16SeqPoint)
}
var outRune byte
switch c {
case 'n':
outRune = '\n'
case 'r':
outRune = '\r'
case 't':
outRune = '\t'
case 'b':
outRune = '\b'
case 'f':
outRune = '\f'
case '\\':
outRune = '\\'
case '/':
outRune = '/'
case '"':
outRune = '"'
default:
return fmt.Errorf("invalid escape sequence \\%c", c)
}
u.input[u.writeIter] = outRune
u.writeIter++
return nil
}
func (u *bytesUnescaper) processBackSlashByte(c byte) {
u.pendingEscapedSymbol = true
}
func (u *bytesUnescaper) processRegularByte(c byte) {
u.input[u.writeIter] = c
u.writeIter++
}
func (u *bytesUnescaper) terminate() error {
if u.pendingSecondUTF16SeqPoint {
return fmt.Errorf("missing second sequence point for %x", u.firstUTF16SeqPoint)
}
if u.pendingEscapedSymbol || u.pendingUnicodeBytes > 0 {
return fmt.Errorf("incomplete escape sequence %s", string(u.input[u.writeIter:]))
}
return nil
}
func (u *bytesUnescaper) doUnescaping() (_ []byte, err error) {
for u.readIter = 0; u.readIter < len(u.input); u.readIter++ {
currByte := u.input[u.readIter]
switch {
case u.pendingUnicodeBytes > 0:
err = u.processUnicodeByte(currByte)
case u.pendingEscapedSymbol:
err = u.processSpecialByte(currByte)
case currByte == '\\':
u.processBackSlashByte(currByte)
default:
u.processRegularByte(currByte)
}
if err != nil {
return nil, err
}
}
if err = u.terminate(); err != nil {
return nil, err
}
return u.input[:u.writeIter], nil
}
// StringDeepCopy creates a copy of the given string with it's own underlying bytearray.
// Use this function to make a copy of string returned by Token()
func StringDeepCopy(s string) string {
return unsafeStringFromBytes([]byte(s))
}
// IsDelim reports whether the given rune is a JSON delimiter
func IsDelim(c rune) bool {
switch c {
case '{', '}', '[', ']', ':', ',':
return true
}
return false
}
// IsValidEscapedSymbol reports whether the given rune is one of the special symbols
// permitted in JSON
func IsValidEscapedSymbol(c rune) bool {
switch c {
case 'n', 'r', 't', 'b', 'f', '\\', '/', '"', 'u', 'U':
return true
}
return false
}
// IsHexDigit reports whether the given rune is a valid hex digit
func IsHexDigit(c rune) bool {
switch {
case unicode.IsDigit(c):
fallthrough
case 'a' <= c && c <= 'f':
fallthrough
case 'A' <= c && c <= 'F':
return true
}
return false
}
// CanAppearInNUmber reports whether the given rune can appear in a JSON number
func CanAppearInNumber(c rune) bool {
switch {
case unicode.IsDigit(c):
fallthrough
case c == '-', c == '+':
fallthrough
case c == '.':
fallthrough
case c == 'e', c == 'E':
return true
}
return false
}
func HexBytesToUint(in []byte) (result uint64, err error) {
for _, c := range in {
result *= 0x10
var v byte
switch {
case '0' <= c && c <= '9':
v = c - '0'
case 'a' <= c && c <= 'f':
v = c - 'a' + 10
case 'A' <= c && c <= 'F':
v = c - 'A' + 10
default:
return 0, fmt.Errorf("'%s' is not a hex number", string(in))
}
result += uint64(v)
}
return result, nil
}
<|start_filename|>examples/stdinparser/main.go<|end_filename|>
// example_1 parses StdIn as JSON input to tokens and dumps those to StdOut
package main
import (
"fmt"
"io"
"log"
"os"
"github.com/gibsn/gojsonlex"
)
func main() {
l, err := gojsonlex.NewJSONLexer(os.Stdin)
if err != nil {
log.Fatalf("fatal: could not create JSONLexer: %v", err)
}
for {
l, err := l.Token()
if err == io.EOF {
break
}
if err != nil {
log.Fatalf("fatal: could not parse input: %v", err)
}
fmt.Println(l)
}
}
<|start_filename|>token_test.go<|end_filename|>
package gojsonlex
import (
"testing"
)
type stringDeepCopyTestCase struct {
input string
}
func TestStringDeepCopy(t *testing.T) {
testcases := []stringDeepCopyTestCase{
{"hello, world!"}, {""},
}
for _, testcase := range testcases {
currIn := testcase.input
currOut := StringDeepCopy(testcase.input)
if currIn != currOut {
t.Errorf("testcase '%s': got '%s'", currIn, currOut)
}
}
}
type unescapeBytesInplaceTestCase struct {
input []byte
output []byte
}
func TestUnescapeBytesInplace(t *testing.T) {
testcases := []unescapeBytesInplaceTestCase{
{[]byte(""), []byte("")},
{[]byte("a"), []byte("a")},
{[]byte("hello\\nworld"), []byte("hello\nworld")},
{[]byte("hello\\rworld"), []byte("hello\rworld")},
{[]byte("hello\\tworld"), []byte("hello\tworld")},
{[]byte("hello\\bworld"), []byte("hello\bworld")},
{[]byte("hello\\fworld"), []byte("hello\fworld")},
{[]byte("hello\\\\world"), []byte("hello\\world")},
{[]byte("hello\\/world"), []byte("hello/world")},
{[]byte("hello\\\"world"), []byte("hello\"world")},
{[]byte("\\\"hello world\\\""), []byte("\"hello world\"")},
{
[]byte("hello \\u043f\\u0440\\u0438\\u0432\\u0435\\u0442\\u0020\\u043c\\u0438\\u0440 world"),
[]byte("hello привет мир world"),
},
{[]byte("hello \\UD83D\\UDCA9 world"), []byte("hello 💩 world")},
}
for _, testcase := range testcases {
currIn := string(testcase.input) // making a copy
currOut, err := UnescapeBytesInplace(testcase.input)
if err != nil {
t.Errorf("testcase '%s': %v", currIn, err)
continue
}
if string(testcase.output) != string(currOut) {
t.Errorf("testcase '%s': got '%s', expected '%s'",
currIn, string(currOut), string(testcase.output))
}
}
}
func TestUnescapeBytesInplaceFails(t *testing.T) {
testcases := []unescapeBytesInplaceTestCase{
{input: []byte("\\")},
// unknown escape sequnce
{input: []byte("\\a")},
// not enough symbols
{input: []byte("\\u043")},
// wrong utf16 surrogate pair
{input: []byte("hello \\ud83d\\ufca9 world")},
// missing second elem in a utf16 surrogate pair
{input: []byte("hello \\ud83d world")},
}
for _, testcase := range testcases {
currIn := string(testcase.input) // making a copy
_, err := UnescapeBytesInplace(testcase.input)
if err == nil {
t.Errorf("testcase '%s': must have failed", currIn)
}
}
}
type hexBytesToUintTestcase struct {
input []byte
output uint64
}
func TestHexBytesToUint(t *testing.T) {
testcases := []hexBytesToUintTestcase{
{
input: []byte("000f"),
output: 15,
},
{
input: []byte("003F"),
output: 63,
},
{
input: []byte("043f"),
output: 1087,
},
{
input: []byte("543f"),
output: 21567,
},
}
for _, testcase := range testcases {
out, err := HexBytesToUint(testcase.input)
if err != nil {
t.Errorf("testcase '%s': %v", string(testcase.input), err)
continue
}
if testcase.output != out {
t.Errorf("testcase '%s': got '%d', expected '%d'",
testcase.input, out, testcase.output)
}
}
}
func TestHexBytesToUintFails(t *testing.T) {
testcases := []unescapeBytesInplaceTestCase{
{
input: []byte("043z"),
},
}
for _, testcase := range testcases {
_, err := HexBytesToUint(testcase.input)
if err == nil {
t.Errorf("testcase '%s': must have failed", testcase.input)
}
}
}
type canAppearInNumberTestCase struct {
input rune
output bool
}
func TestCanAppearInNumber(t *testing.T) {
testcases := []canAppearInNumberTestCase{
{'0', true},
{'9', true},
{'-', true},
{'.', true},
{'+', true},
{'e', true},
{'E', true},
{'е', false}, // russian 'е'
{'*', false},
}
for _, testcase := range testcases {
currOut := CanAppearInNumber(testcase.input)
if testcase.output != currOut {
t.Errorf("testcase '%c': got '%t', expected '%t'",
testcase.input, currOut, testcase.output)
}
}
}
// TODO tests for IsDelim
| gibsn/gojsonlex |
<|start_filename|>mapmint-services/raster-tools-src/service1.c<|end_filename|>
/******************************************************************************
* $Id$
*
* Project: GDAL Utilities
* Purpose: GDAL Image Translator Program
* Author: <NAME>, <EMAIL>
*
******************************************************************************
* Copyright (c) 1998, 2002, <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_vsi.h"
#include "cpl_conv.h"
#include "cpl_string.h"
#include "gdal_priv.h"
#include "ogr_spatialref.h"
#include "vrtdataset.h"
#include "service.h"
CPL_CVSID("$Id$");
extern "C" {
static void AttachMetadata( GDALDatasetH, char ** );
static int bSubCall = FALSE;
/************************************************************************/
/* Gdal_Translate() */
/************************************************************************/
#ifdef WIN32
__declspec(dllexport)
#endif
int translate(maps*& conf,maps*& inputs,maps*& outputs)
{
/*fprintf(stderr,"STARTING GDAL TRANSLATE\n");
fflush(stderr);*/
GDALDatasetH hDataset, hOutDS;
int i;
int nRasterXSize, nRasterYSize;
const char *pszSource=NULL, *pszDest=NULL, *pszFormat = "GTiff";
GDALDriverH hDriver;
int *panBandList = NULL, nBandCount = 0, bDefBands = TRUE;
double adfGeoTransform[6];
GDALDataType eOutputType = GDT_Unknown;
int nOXSize = 0, nOYSize = 0;
char *pszOXSize=NULL, *pszOYSize=NULL;
char **papszCreateOptions = NULL;
int anSrcWin[4], bStrict = FALSE;
const char *pszProjection;
int bScale = FALSE, bHaveScaleSrc = FALSE;
double dfScaleSrcMin=0.0, dfScaleSrcMax=255.0;
double dfScaleDstMin=0.0, dfScaleDstMax=255.0;
double dfULX, dfULY, dfLRX, dfLRY;
char **papszMetadataOptions = NULL;
char *pszOutputSRS = NULL;
int bQuiet = TRUE, bGotBounds = FALSE;
GDALProgressFunc pfnProgress = GDALDummyProgress;
int nGCPCount = 0;
GDAL_GCP *pasGCPs = NULL;
int iSrcFileArg = -1, iDstFileArg = -1;
int bCopySubDatasets = FALSE;
double adfULLR[4] = { 0,0,0,0 };
int bSetNoData = FALSE;
double dfNoDataReal = 0.0;
int nRGBExpand = 0;
anSrcWin[0] = 0;
anSrcWin[1] = 0;
anSrcWin[2] = 0;
anSrcWin[3] = 0;
dfULX = dfULY = dfLRX = dfLRY = 0.0;
/* ----------------------------------------------------------------- */
/* Register standard GDAL drivers, and process generic GDAL */
/* ----------------------------------------------------------------- */
GDALAllRegister();
/* ----------------------------------------------------------------- */
/* Extract Format, InputDSN, OutputDSN parameters */
/* ----------------------------------------------------------------- */
map* tmpMap=NULL;
char dataPath[1024];
tmpMap=getMapFromMaps(conf,"main","dataPath");
if(tmpMap!=NULL)
sprintf(dataPath,"%s",tmpMap->value);
tmpMap=NULL;
char tempPath[1024];
tmpMap=getMapFromMaps(conf,"main","tmpPath");
if(tmpMap!=NULL){
sprintf(tempPath,"%s",tmpMap->value);
}
tmpMap=NULL;
tmpMap=getMapFromMaps(inputs,"Format","value");
if(tmpMap!=NULL){
pszFormat=tmpMap->value;
}
tmpMap=NULL;
tmpMap=getMapFromMaps(inputs,"InputDSN","value");
if(tmpMap!=NULL){
pszSource=(char*)malloc(sizeof(char)*(strlen(dataPath)+strlen(tmpMap->value)+4));
sprintf((char*)pszSource,"%s/%s",dataPath,tmpMap->value);
}
tmpMap=NULL;
tmpMap=getMapFromMaps(inputs,"OutputDSN","value");
if(tmpMap!=NULL){
pszDest=(char*)malloc(sizeof(char)*(strlen(tempPath)+strlen(tmpMap->value)+6));
char *ext=new char[4];
ext="tif";
if(strncasecmp(pszFormat,"AAIGRID",7)==0)
ext="csv";
else
if(strncasecmp(pszFormat,"PNG",3)==0)
ext="png";
else
if(strncasecmp(pszFormat,"GIF",3)==0)
ext="gif";
else
if(strncasecmp(pszFormat,"JPEG",4)==0)
ext="jpg";
sprintf((char*)pszDest,"%s/%s.%s",tempPath,tmpMap->value,ext);
fprintf(stderr,"DEBUG pszDest : %s\n",pszDest);
}
tmpMap=NULL;
tmpMap=getMapFromMaps(inputs,"ProjWin","value");
if(tmpMap!=NULL){
char *tmp=tmpMap->value;
char *t=strtok(tmp,",");
int cnt=0;
while(t!=NULL){
switch(cnt){
case 0:
dfULX = atof(t);
break;
case 1:
dfULY = atof(t);
break;
case 2:
dfLRX = atof(t);
break;
case 3:
dfLRY = atof(t);
break;
}
fprintf(stderr,"%s\n\n",t);
fprintf(stderr,"%f - %f - %f - %f\n\n",dfULX,dfULY,dfLRX,dfLRY);
t=strtok(NULL,",");
cnt++;
}
}
tmpMap=NULL;
tmpMap=getMapFromMaps(inputs,"SRS","value");
if(tmpMap!=NULL){
OGRSpatialReference oOutputSRS;
if( oOutputSRS.SetFromUserInput( tmpMap->value ) != OGRERR_NONE )
{
fprintf( stderr, "Failed to process SRS definition: %s\n",
tmpMap->value );
/**
* Avoiding GDALDestroyDriverManager() call
*/
return 4;
}
oOutputSRS.exportToWkt( &pszOutputSRS );
}
tmpMap=NULL;
tmpMap=getMapFromMaps(inputs,"Type","value");
if(tmpMap!=NULL){
int iType;
for( iType = 1; iType < GDT_TypeCount; iType++ )
{
if( GDALGetDataTypeName((GDALDataType)iType) != NULL
&& EQUAL(GDALGetDataTypeName((GDALDataType)iType),
tmpMap->value) )
{
eOutputType = (GDALDataType) iType;
}
}
if( eOutputType == GDT_Unknown )
{
fprintf( stderr, "Unknown output pixel type: %s\n", tmpMap->value );
/**
* Avoiding GDALDestroyDriverManager() call
*/
return 4;
}
}
fprintf(stderr,"==%s %s %s %==\n",pszFormat,pszSource,pszDest);
fflush(stderr);
tmpMap=getMapFromMaps(inputs,"OutSize","value");
if(tmpMap!=NULL){
char *temp=strstr(tmpMap->value,",");
pszOXSize=strdup(tmpMap->value);
pszOXSize[strlen(tmpMap->value)-strlen(temp)]=0;
pszOYSize=strdup(temp+1);
fprintf(stderr,"pszOSize %s %s",pszOXSize,pszOYSize);
}
if( pszDest == NULL ){
fprintf(stderr,"exit line 416");
fflush(stderr);
/**
* Avoiding GDALDestroyDriverManager() call
*/
return 4;
}
if ( strcmp(pszSource, pszDest) == 0)
{
fprintf(stderr, "Source and destination datasets must be different.\n");
fflush(stderr);
/**
* Avoiding GDALDestroyDriverManager() call
*/
return 4;
}
/* ----------------------------------------------------------------- */
/* Attempt to open source file. */
/* ----------------------------------------------------------------- */
fprintf(stderr,"dataSource %s\n",pszSource);
hDataset = GDALOpenShared( pszSource, GA_ReadOnly );
if( hDataset == NULL ){
fprintf( stderr,
"GDALOpen failed - %d\n%s\n",
CPLGetLastErrorNo(), CPLGetLastErrorMsg() );
fflush(stderr);
/**
* Avoiding GDALDestroyDriverManager() call
*/
return 4;
}
/* ----------------------------------------------------------------- */
/* Handle subdatasets. */
/* ----------------------------------------------------------------- */
if( !bCopySubDatasets
&& CSLCount(GDALGetMetadata( hDataset, "SUBDATASETS" )) > 0
&& GDALGetRasterCount(hDataset) == 0 )
{
fprintf( stderr,
"Input file contains subdatasets. Please, select one of them for reading.\n" );
fflush(stderr);
GDALClose( hDataset );
/**
* Avoiding GDALDestroyDriverManager() call
*/
return 4;
}
if( CSLCount(GDALGetMetadata( hDataset, "SUBDATASETS" )) > 0
&& bCopySubDatasets )
{
char **papszSubdatasets = GDALGetMetadata(hDataset,"SUBDATASETS");
char *pszSubDest = (char *) CPLMalloc(strlen(pszDest)+32);
int i;
int bOldSubCall = bSubCall;
//argv[iDstFileArg] = pszSubDest;
bSubCall = TRUE;
for( i = 0; papszSubdatasets[i] != NULL; i += 2 )
{
//argv[iSrcFileArg] = strstr(papszSubdatasets[i],"=")+1;
sprintf( pszSubDest, "%s%d", pszDest, i/2 + 1 );
/*if( ProxyMain( argc, argv ) != 0 )
break;*/
}
bSubCall = bOldSubCall;
CPLFree( pszSubDest );
GDALClose( hDataset );
if( !bSubCall )
{
GDALDumpOpenDatasets( stderr );
fflush(stderr);
/**
* Avoiding GDALDestroyDriverManager() call
*/
}
return 1;
}
/* ----------------------------------------------------------------- */
/* Collect some information from the source file. */
/* ----------------------------------------------------------------- */
nRasterXSize = GDALGetRasterXSize( hDataset );
nRasterYSize = GDALGetRasterYSize( hDataset );
if( !bQuiet )
printf( "Input file size is %d, %d\n", nRasterXSize, nRasterYSize );
if( anSrcWin[2] == 0 && anSrcWin[3] == 0 ){
anSrcWin[2] = nRasterXSize;
anSrcWin[3] = nRasterYSize;
}
/* ----------------------------------------------------------------- */
/* Build band list to translate */
/* ----------------------------------------------------------------- */
if( nBandCount == 0 ){
nBandCount = GDALGetRasterCount( hDataset );
if( nBandCount == 0 ){
fprintf( stderr, "Input file has no bands, and so cannot be translated.\n" );
fflush(stderr);
/**
* Avoiding GDALDestroyDriverManager() call
*/
return 4;
}
panBandList = (int *) CPLMalloc(sizeof(int)*nBandCount);
for( i = 0; i < nBandCount; i++ )
panBandList[i] = i+1;
}
else
{
for( i = 0; i < nBandCount; i++ )
{
if( panBandList[i] < 1 || panBandList[i] > GDALGetRasterCount(hDataset) )
{
fprintf( stderr,
"Band %d requested, but only bands 1 to %d available.\n",
panBandList[i], GDALGetRasterCount(hDataset) );
fflush(stderr);
/**
* Avoiding GDALDestroyDriverManager() call
*/
return 4;
}
}
if( nBandCount != GDALGetRasterCount( hDataset ) )
bDefBands = FALSE;
}
/* ----------------------------------------------------------------- */
/* Compute the source window from the projected source window */
/* if the projected coordinates were provided. Note that the */
/* projected coordinates are in ulx, uly, lrx, lry format, */
/* while the anSrcWin is xoff, yoff, xsize, ysize with the */
/* xoff,yoff being the ulx, uly in pixel/line. */
/* ----------------------------------------------------------------- */
if( dfULX != 0.0 || dfULY != 0.0
|| dfLRX != 0.0 || dfLRY != 0.0 )
{
double adfGeoTransform[6];
GDALGetGeoTransform( hDataset, adfGeoTransform );
if( adfGeoTransform[2] != 0.0 || adfGeoTransform[4] != 0.0 ){
fprintf( stderr,
"The -projwin option was used, but the geotransform is\n"
"rotated. This configuration is not supported.\n" );
GDALClose( hDataset );
CPLFree( panBandList );
fflush(stderr);
/**
* Avoiding GDALDestroyDriverManager() call
*/
return 4;
}
anSrcWin[0] = (int)
((dfULX - adfGeoTransform[0]) / adfGeoTransform[1] + 0.001);
anSrcWin[1] = (int)
((dfULY - adfGeoTransform[3]) / adfGeoTransform[5] + 0.001);
anSrcWin[2] = (int) ((dfLRX - dfULX) / adfGeoTransform[1] + 0.5);
anSrcWin[3] = (int) ((dfLRY - dfULY) / adfGeoTransform[5] + 0.5);
if( !bQuiet )
fprintf( stdout,
"Computed -srcwin %d %d %d %d from projected window.\n",
anSrcWin[0],
anSrcWin[1],
anSrcWin[2],
anSrcWin[3] );
if( anSrcWin[0] < 0 || anSrcWin[1] < 0
|| anSrcWin[0] + anSrcWin[2] > GDALGetRasterXSize(hDataset)
|| anSrcWin[1] + anSrcWin[3] > GDALGetRasterYSize(hDataset) )
{
fprintf( stderr,
"Computed -srcwin falls outside raster size of %dx%d.\n",
GDALGetRasterXSize(hDataset),
GDALGetRasterYSize(hDataset) );
return 4;
}
}
/* ----------------------------------------------------------------- */
/* Verify source window. */
/* ----------------------------------------------------------------- */
if( anSrcWin[0] < 0 || anSrcWin[1] < 0
|| anSrcWin[2] <= 0 || anSrcWin[3] <= 0
|| anSrcWin[0] + anSrcWin[2] > GDALGetRasterXSize(hDataset)
|| anSrcWin[1] + anSrcWin[3] > GDALGetRasterYSize(hDataset) )
{
fprintf( stderr,
"-srcwin %d %d %d %d falls outside raster size of %dx%d\n"
"or is otherwise illegal.\n",
anSrcWin[0],
anSrcWin[1],
anSrcWin[2],
anSrcWin[3],
GDALGetRasterXSize(hDataset),
GDALGetRasterYSize(hDataset) );
return 4;
}
/* ----------------------------------------------------------------- */
/* Find the output driver. */
/* ----------------------------------------------------------------- */
hDriver = GDALGetDriverByName( pszFormat );
if( hDriver == NULL )
{
int iDr;
printf( "Output driver `%s' not recognised.\n", pszFormat );
printf( "The following format drivers are configured and support output:\n" );
for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
{
GDALDriverH hDriver = GDALGetDriver(iDr);
if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL
|| GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY,
NULL ) != NULL )
{
fprintf( stderr, " %s: %s\n",
GDALGetDriverShortName( hDriver ),
GDALGetDriverLongName( hDriver ) );
}
}
fprintf( stderr,"\n" );
GDALClose( hDataset );
CPLFree( panBandList );
fflush(stderr);
/**
* Avoiding GDALDestroyDriverManager() call
*/
CSLDestroy( papszCreateOptions );
return 4;
}
/* ----------------------------------------------------------------- */
/* The short form is to CreateCopy(). We use this if the input */
/* matches the whole dataset. Eventually we should rewrite */
/* this entire program to use virtual datasets to construct a */
/* virtual input source to copy from. */
/* ----------------------------------------------------------------- */
if( eOutputType == GDT_Unknown
&& !bScale && CSLCount(papszMetadataOptions) == 0 && bDefBands
&& anSrcWin[0] == 0 && anSrcWin[1] == 0
&& anSrcWin[2] == GDALGetRasterXSize(hDataset)
&& anSrcWin[3] == GDALGetRasterYSize(hDataset)
&& pszOXSize == NULL && pszOYSize == NULL
&& nGCPCount == 0 && !bGotBounds
&& pszOutputSRS == NULL && !bSetNoData
&& nRGBExpand == 0)
{
hOutDS = GDALCreateCopy( hDriver, pszDest, hDataset,
bStrict, papszCreateOptions,
pfnProgress, NULL );
if( hOutDS != NULL )
GDALClose( hOutDS );
GDALClose( hDataset );
CPLFree( panBandList );
if( !bSubCall )
{
GDALDumpOpenDatasets( stderr );
/**
* Avoiding GDALDestroyDriverManager() call
*/
}
CSLDestroy( papszCreateOptions );
//outputs=(maps*)malloc(sizeof(maps*));
//outputs->name="OutputedPolygon";
setMapInMaps(outputs,"Result","value",(char*)pszDest);
//outputs->next=NULL;
return SERVICE_SUCCEEDED;
}
fprintf(stderr,"==%s %s %s %==\n",pszFormat,pszSource,pszDest);
fflush(stderr);
/* ----------------------------------------------------------------- */
/* Establish some parameters. */
/* ----------------------------------------------------------------- */
if( pszOXSize == NULL )
{
nOXSize = anSrcWin[2];
nOYSize = anSrcWin[3];
}
else
{
nOXSize = (int) ((pszOXSize[strlen(pszOXSize)-1]=='%'
? atof(pszOXSize)/100*anSrcWin[2] : atoi(pszOXSize)));
nOYSize = (int) ((pszOYSize[strlen(pszOYSize)-1]=='%'
? atof(pszOYSize)/100*anSrcWin[3] : atoi(pszOYSize)));
}
fprintf(stderr,"==%s %s %s %==\n",pszFormat,pszSource,pszDest);
fflush(stderr);
/* ================================================================= */
/* Create a virtual dataset. */
/* ================================================================= */
VRTDataset *poVDS;
/* ----------------------------------------------------------------- */
/* Make a virtual clone. */
/* ----------------------------------------------------------------- */
poVDS = (VRTDataset *) VRTCreate( nOXSize, nOYSize );
if( nGCPCount == 0 )
{
if( pszOutputSRS != NULL )
{
poVDS->SetProjection( pszOutputSRS );
}
else
{
pszProjection = GDALGetProjectionRef( hDataset );
if( pszProjection != NULL && strlen(pszProjection) > 0 )
poVDS->SetProjection( pszProjection );
}
}
if( bGotBounds )
{
adfGeoTransform[0] = adfULLR[0];
adfGeoTransform[1] = (adfULLR[2] - adfULLR[0]) / nOXSize;
adfGeoTransform[2] = 0.0;
adfGeoTransform[3] = adfULLR[1];
adfGeoTransform[4] = 0.0;
adfGeoTransform[5] = (adfULLR[3] - adfULLR[1]) / nOYSize;
poVDS->SetGeoTransform( adfGeoTransform );
}
else if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None
&& nGCPCount == 0 )
{
adfGeoTransform[0] += anSrcWin[0] * adfGeoTransform[1]
+ anSrcWin[1] * adfGeoTransform[2];
adfGeoTransform[3] += anSrcWin[0] * adfGeoTransform[4]
+ anSrcWin[1] * adfGeoTransform[5];
adfGeoTransform[1] *= anSrcWin[2] / (double) nOXSize;
adfGeoTransform[2] *= anSrcWin[3] / (double) nOYSize;
adfGeoTransform[4] *= anSrcWin[2] / (double) nOXSize;
adfGeoTransform[5] *= anSrcWin[3] / (double) nOYSize;
poVDS->SetGeoTransform( adfGeoTransform );
}
if( nGCPCount != 0 )
{
const char *pszGCPProjection = pszOutputSRS;
if( pszGCPProjection == NULL )
pszGCPProjection = GDALGetGCPProjection( hDataset );
if( pszGCPProjection == NULL )
pszGCPProjection = "";
poVDS->SetGCPs( nGCPCount, pasGCPs, pszGCPProjection );
GDALDeinitGCPs( nGCPCount, pasGCPs );
CPLFree( pasGCPs );
}
else if( GDALGetGCPCount( hDataset ) > 0 )
{
GDAL_GCP *pasGCPs;
int nGCPs = GDALGetGCPCount( hDataset );
pasGCPs = GDALDuplicateGCPs( nGCPs, GDALGetGCPs( hDataset ) );
for( i = 0; i < nGCPs; i++ )
{
pasGCPs[i].dfGCPPixel -= anSrcWin[0];
pasGCPs[i].dfGCPLine -= anSrcWin[1];
pasGCPs[i].dfGCPPixel *= (nOXSize / (double) anSrcWin[2] );
pasGCPs[i].dfGCPLine *= (nOYSize / (double) anSrcWin[3] );
}
poVDS->SetGCPs( nGCPs, pasGCPs,
GDALGetGCPProjection( hDataset ) );
GDALDeinitGCPs( nGCPs, pasGCPs );
CPLFree( pasGCPs );
}
/* ----------------------------------------------------------------- */
/* Transfer generally applicable metadata. */
/* ----------------------------------------------------------------- */
poVDS->SetMetadata( ((GDALDataset*)hDataset)->GetMetadata() );
AttachMetadata( (GDALDatasetH) poVDS, papszMetadataOptions );
fprintf(stderr,"Transfer generally applicable metadata.\n");
fflush(stderr);
/* ----------------------------------------------------------------- */
/* Transfer metadata that remains valid if the spatial */
/* arrangement of the data is unaltered. */
/* ----------------------------------------------------------------- */
if( anSrcWin[0] == 0 && anSrcWin[1] == 0
&& anSrcWin[2] == GDALGetRasterXSize(hDataset)
&& anSrcWin[3] == GDALGetRasterYSize(hDataset)
&& pszOXSize == NULL && pszOYSize == NULL )
{
char **papszMD;
papszMD = ((GDALDataset*)hDataset)->GetMetadata("RPC");
if( papszMD != NULL )
poVDS->SetMetadata( papszMD, "RPC" );
}
if (nRGBExpand != 0)
nBandCount += nRGBExpand - 1;
/* ================================================================= */
/* Process all bands. */
/* ================================================================= */
for( i = 0; i < nBandCount; i++ )
{
VRTSourcedRasterBand *poVRTBand;
GDALRasterBand *poSrcBand;
GDALDataType eBandType;
if (nRGBExpand != 0 && i < nRGBExpand)
{
poSrcBand = ((GDALDataset *)
hDataset)->GetRasterBand(panBandList[0]);
if (poSrcBand->GetColorTable() == NULL)
{
fprintf(stderr, "Error : band %d has no color table\n", panBandList[0]);
GDALClose( hDataset );
CPLFree( panBandList );
fflush(stderr);
/**
* Avoiding GDALDestroyDriverManager() call
*/
CSLDestroy( papszCreateOptions );
exit( 1 );
}
}
else
poSrcBand = ((GDALDataset *)
hDataset)->GetRasterBand(panBandList[i]);
/* ------------------------------------------------------------ */
/* Select output data type to match source. */
/* ------------------------------------------------------------ */
if( eOutputType == GDT_Unknown )
eBandType = poSrcBand->GetRasterDataType();
else
eBandType = eOutputType;
/* ------------------------------------------------------------ */
/* Create this band. */
/* ------------------------------------------------------------ */
poVDS->AddBand( eBandType, NULL );
poVRTBand = (VRTSourcedRasterBand *) poVDS->GetRasterBand( i+1 );
/* ------------------------------------------------------------ */
/* Do we need to collect scaling information? */
/* ------------------------------------------------------------ */
double dfScale=1.0, dfOffset=0.0;
if( bScale && !bHaveScaleSrc )
{
double adfCMinMax[2];
GDALComputeRasterMinMax( poSrcBand, TRUE, adfCMinMax );
dfScaleSrcMin = adfCMinMax[0];
dfScaleSrcMax = adfCMinMax[1];
}
if( bScale )
{
if( dfScaleSrcMax == dfScaleSrcMin )
dfScaleSrcMax += 0.1;
if( dfScaleDstMax == dfScaleDstMin )
dfScaleDstMax += 0.1;
dfScale = (dfScaleDstMax - dfScaleDstMin)
/ (dfScaleSrcMax - dfScaleSrcMin);
dfOffset = -1 * dfScaleSrcMin * dfScale + dfScaleDstMin;
}
/* ------------------------------------------------------------ */
/* Create a simple or complex data source depending on the */
/* translation type required. */
/* ------------------------------------------------------------ */
if( bScale || (nRGBExpand != 0 && i < nRGBExpand) )
{
poVRTBand->AddComplexSource( poSrcBand,
anSrcWin[0], anSrcWin[1],
anSrcWin[2], anSrcWin[3],
0, 0, nOXSize, nOYSize,
dfOffset, dfScale,
VRT_NODATA_UNSET,
(nRGBExpand != 0 && i < nRGBExpand) ? i + 1 : 0 );
}
else
poVRTBand->AddSimpleSource( poSrcBand,
anSrcWin[0], anSrcWin[1],
anSrcWin[2], anSrcWin[3],
0, 0, nOXSize, nOYSize );
/* In case of color table translate, we only set the color interpretation */
/* other info copied by CopyCommonInfoFrom are not relevant in RGB expansion */
if (nRGBExpand != 0 && i < nRGBExpand)
{
poVRTBand->SetColorInterpretation( (GDALColorInterp) (GCI_RedBand + i) );
}
else
{
/* --------------------------------------------------------- */
/* copy over some other information of interest. */
/* --------------------------------------------------------- */
poVRTBand->CopyCommonInfoFrom( poSrcBand );
}
/* ------------------------------------------------------------- */
/* Set a forcable nodata value? */
/* ------------------------------------------------------------- */
if( bSetNoData )
poVRTBand->SetNoDataValue( dfNoDataReal );
}
/* ----------------------------------------------------------------- */
/* Write to the output file using CopyCreate(). */
/* ----------------------------------------------------------------- */
fprintf(stderr,"DEBUG pszDest %s\n",pszDest);
hOutDS = GDALCreateCopy( hDriver, pszDest, (GDALDatasetH) poVDS,
bStrict, papszCreateOptions,
pfnProgress, NULL );
fprintf(stderr,"DEBUG pszDest %s\n",pszDest);
fflush(stderr);
if( hOutDS != NULL )
{
GDALClose( hOutDS );
}
GDALClose( (GDALDatasetH) poVDS );
GDALClose( hDataset );
CPLFree( panBandList );
CPLFree( pszOutputSRS );
if( !bSubCall )
{
GDALDumpOpenDatasets( stderr );
fflush(stderr);
/**
* Avoiding GDALDestroyDriverManager() call
*/
}
CSLDestroy( papszCreateOptions );
setMapInMaps(outputs,"Result","value",(char*)pszDest);
return SERVICE_SUCCEEDED;
}
/************************************************************************/
/* AttachMetadata() */
/************************************************************************/
static void AttachMetadata( GDALDatasetH hDS, char **papszMetadataOptions )
{
int nCount = CSLCount(papszMetadataOptions);
int i;
for( i = 0; i < nCount; i++ )
{
char *pszKey = NULL;
const char *pszValue;
pszValue = CPLParseNameValue( papszMetadataOptions[i], &pszKey );
GDALSetMetadataItem(hDS,pszKey,pszValue,NULL);
CPLFree( pszKey );
}
CSLDestroy( papszMetadataOptions );
}
}
<|start_filename|>mapmint-ui/new-themes/themes/green/window.css<|end_filename|>
.window {
overflow: hidden;
padding: 5px;
border-width: 1px;
border-style: solid;
}
.window .window-header {
background: transparent;
padding: 0px 0px 6px 0px;
}
.window .window-body {
border-width: 1px;
border-style: solid;
border-top-width: 0px;
}
.window .window-body-noheader {
border-top-width: 1px;
}
.window .window-header .panel-icon,
.window .window-header .panel-tool {
top: 50%;
margin-top: -11px;
}
.window .window-header .panel-icon {
left: 1px;
}
.window .window-header .panel-tool {
right: 1px;
}
.window .window-header .panel-with-icon {
padding-left: 18px;
}
.window-proxy {
position: absolute;
overflow: hidden;
}
.window-proxy-mask {
position: absolute;
filter: alpha(opacity=5);
opacity: 0.05;
}
.window-mask {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
filter: alpha(opacity=40);
opacity: 0.40;
font-size: 1px;
*zoom: 1;
overflow: hidden;
}
.window,
.window-shadow {
position: absolute;
-moz-border-radius: 5px 5px 5px 5px;
-webkit-border-radius: 5px 5px 5px 5px;
border-radius: 5px 5px 5px 5px;
}
.window-shadow {
background: #ccc;
-moz-box-shadow: 2px 2px 3px #cccccc;
-webkit-box-shadow: 2px 2px 3px #cccccc;
box-shadow: 2px 2px 3px #cccccc;
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
}
.window,
.window .window-body {
border-color: #D3D3D3;
}
.window {
background:#E8E8E8;
}
.window-proxy {
border: 1px dashed #D3D3D3;
}
.window-proxy-mask,
.window-mask {
background: #ccc;
}
.panel{
overflow:hidden;
font-size:1em;
}
.panel-header{
padding:4px 0 5px 5px;
line-height:24px;
color:#707070;
font-size:0.9em;
font-weight:normal;
background:url('../img/panel_title.png') repeat-x;
position:relative;
border:1px solid #99BBE8;
}
.panel-title{
background:url('../img/blank.gif') no-repeat;
}
.panel-header-noborder{
border-width:0px;
border-bottom:1px solid #aeaeae;
}
.panel-body{
font-size:.85em;
overflow:auto;
border:1px solid #333333;
border-top-width:0px;
color:#5d5d5d;
}
.panel-body-noheader{
border-top-width:1px;
}
.panel-body-noborder{
border-width:0px;
}
.panel-with-icon{
padding-left:18px;
}
.panel-icon{
position:absolute;
left:5px;
top:4px;
width:24px;
height:24px;
}
.panel-tool{
position:absolute;
right:5px;
top:4px;
}
.panel-tool a{
display:inline-block;
width:16px;
height:16px;
opacity:0.6;
filter:alpha(opacity=60);
margin-left:2px;
}
.panel-tool a:hover{
opacity:1;
filter:alpha(opacity=100);
}
.panel-tool-close{
background:url('../img/panel_tools.gif') no-repeat -16px 0px;
}
.panel-tool-min{
background:url('../img/panel_tools.gif') no-repeat 0px 0px;
}
.panel-tool-max{
background:url('../img/panel_tools.gif') no-repeat 0px -16px;
}
.panel-tool-restore{
background:url('../img/panel_tools.gif') no-repeat -16px -16px;
}
.panel-tool-collapse{
background:url('../img/panel_tools.gif') no-repeat -32px 0;
}
.panel-tool-expand{
background:url('../img/panel_tools.gif') no-repeat -32px -16px;
}
.panel-loading{
padding:11px 0px 10px 30px;
background:url('../img/panel_loading.gif') no-repeat 10px 10px;
}
.panel-noscroll{
overflow:hidden;
}
.panel-fit,.panel-fit body{
height:100%;
margin:0;
padding:0;
border:0;
overflow:hidden;
}
a.l-btn:hover{
color:#FFFFFF;
text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
background: -ms-linear-gradient(#C2FF7E, #4FA33F);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
}
<|start_filename|>mapmint-ui/new-themes/themes/default/body.css<|end_filename|>
body{font-family:Arial,Lucida Grande, Trebuchet MS;font-size:1em;}
a { outline: none;}
a.help-link{color:#707070;text-decoration:none;}
.log-out{width:350px;height:auto;}
#logout-message p{margin:0;padding:0 0 0 0;}
p.credits{float:left;margin:12px 0 0 10px;color:#E9E9E9;font-size:.8em;}
p.credits a{text-decoration:none;color:#E9E9E9;}
#map{width:100%;height:92%;}
textarea.bigtarea{width: 540px;height: 230px;}
<|start_filename|>mapmint-ui/templates/Distiller/RasterWindow_bs.html<|end_filename|>
#encoding UTF-8
#import zoo
<div>
<form id="raster-processing-form">
<input type="hidden" id="ofname" value="" />
<input type="hidden" id="ofdst" value="" />
<div class="row myWell">
<div class="col-sm-1">
<label for="ofband" class="control-label">$zoo._("Band:") </label>
</div>
<div class="col-sm-3">
<select id="ofband" class="form-control">
</select>
</div>
<div class="col-sm-1">
<label for"raster_method">$zoo._("Method:") </label>
</div>
<div class="col-sm-3">
<select id="raster_method" class="form-control" onchange="\$('#raster-processing-form').find('.raster_p').hide();if(this.value!=-1)\$('#raster-processing-form').find('#'+this.value+'_p').show();">
<option value="-1">$zoo._("Choose")</option>
#for i in ["hillshade","slope","aspect","contour","TRI","TPI","roughness"]
<option value="$i">$zoo._($i)</option>
#end for
</select>
</div>
</div>
<div id="slope_p" class="raster_p">
<p>$zoo._("This mode will take a DEM raster and output a 32-bit float raster with slope values. You have the option of specifying the type of slope value you want: degrees or percent slope. In cases where the horizontal units differ from the vertical units, you can also supply a scaling factor.")</p>
<div class="row myWell">
<div class="col-sm-1">
<label for="slope_scale">$zoo._("Scale")</label>
</div>
<div class="col-sm-2">
<input type="text" id="slope_scale" value="1" class="hasInfo form-control" data-toggle="tooltip" title="$zoo._("Ratio of vertical units to horizontal. If the horizontal unit of the source DEM is degrees (e.g Lat/Long WGS84 projection), you can use scale=111120 if the vertical units are meters (or scale=370400 if they are in feet)")"/>
</div>
</div>
</div>
<div id="hillshade_p" class="raster_p">
<p>$zoo._("This mode outputs an 8-bit raster with a nice shaded relief effect. It's very useful for visualizing the terrain. You can optionally specify the azimuth and altitude of the light source, a vertical exaggeration factor and a scaling factor to account for differences between vertical and horizontal units.")</p>
<table>
<tr>
<td><label for="hillshade_zFactor">$zoo._("Z-Factor")</label></td>
<td><input class="hasInfo form-control" data-toggle="tooltip" title="$zoo._("Vertical exaggeration used to pre-multiply the elevations")" type="text" id="hillshade_zFactor" value="15"/></td>
</tr>
<tr>
<td colspan="2">
$zoo._("Azimuth / Altitude parameters:")
<input type="checkbox" id="" onchange="if(this.checked){\$(this).parent().parent().parent().find('.raster_azimuth').show();}else \$(this).parent().parent().parent().find('.raster_azimuth').hide()"/>
</td>
</tr>
<tr class="raster_azimuth">
<td>
<label for="hillshade_azimuth">$zoo._("Azimuth")</label>
</td>
<td>
<input class="hasInfo form-control" data-toggle="tooltip" title="$zoo._("Azimuth of the light, in degrees. 0 if it comes from the top of the raster, 90 from the east, ... The default value, 315, should rarely be changed as it is the value generally used to generate shaded maps.")" type="text" id="hillshade_azimuth" value="90"/>
</td>
</tr>
<tr class="raster_azimuth">
<td><label for="hillshade_altitude">$zoo._("Altitude")</label></td>
<td><input class="hasInfo form-control" data-toggle="tooltip" title="$zoo._("Altitude of the light, in degrees. 90 if the light comes from above the DEM, 0 if it is raking light.")" type="text" id="hillshade_altitude" value="45"/></td>
</tr>
<tr>
<td><label for="hillshade_scale">$zoo._("Scale")</label></td>
<td> <input class="hasInfo form-control" data-toggle="tooltip" title="$zoo._("Ratio of vertical units to horizontal. If the horizontal unit of the source DEM is degrees (e.g Lat/Long WGS84 projection), you can use scale=111120 if the vertical units are meters (or scale=370400 if they are in feet)")" type="text" id="hillshade_scale" value="1"/></td>
</tr>
</table>
</div>
<div id="aspect_p" class="raster_p">
<p>$zoo._("This command outputs a 32-bit float raster with values between 0° and 360° representing the azimuth that slopes are facing. The definition of the azimuth is such that : 0° means that the slope is facing the North, 90° it's facing the East, 180° it's facing the South and 270° it's facing the West (provided that the top of your input raster is north oriented). The aspect value -9999 is used as the nodata value to indicate undefined aspect in flat areas with slope=0.")</p>
</div>
<div id="contour_p" class="raster_p">
<p>$zoo._("This command builds vector contour lines from a raster elevation model")</p>
<div>
<label for="contour_interval">$zoo._("Elevation interval between contours")</label>
<input type="text" value="10.0" id="contour_interval" class="form-control"/>
</div>
<div>
<label for="contour_aname">$zoo._("Name for the attribute in which to put the elevation. If not provided no elevation attribute is attached.")</label>
<input type="text" value="elevation" id="contour_aname" class="form-control" />
</div>
</div>
<div id="TRI_p" class="raster_p">
<p>$zoo._("Terrain Ruggedness Index, which is defined as the mean difference between a central pixel and its surrounding cells (see Wilson et al 2007, Marine Geodesy 30:3-35).")</p>
</div>
<div id="TPI_p" class="raster_p">
<p>$zoo._("Topographic Position Index, which is defined as the difference between a central pixel and the mean of its surrounding cells (see Wilson et al 2007, Marine Geodesy 30:3-35).")</p>
</div>
<div id="roughness_p" class="raster_p">
<p>$zoo._("Roughness is the largest inter-cell difference of a central pixel and its surrounding cell, as defined in Wilson et al (2007, Marine Geodesy 30:3-35).")</p>
</div>
<table>
<tr>
<td><label for="raster_oname" class="control-label">$zoo._("Filename")</label></td>
<td><input class="hasInfo form-control" data-toggle="tooltip" title="$zoo._("Destination file")" type="text" id="raster_oname" value=""/></td>
</tr>
</table>
</form>
<button class="btn btn-default">$zoo._("Run")</button>
</div>
<|start_filename|>documentation/_templates/layout.html<|end_filename|>
{% extends "!layout.html" %}
{% block extrahead %}
{{ super() }}
{% endblock %}
{% block header %}
<!-- Begin Header -->
<div id="wrapper">
<div id="myheader">
<div class="hleft">
<h1 class="title"><span class="logo"></span><a href="http://mapmint.com" target="_blank">Map<span>Mint</span></a></h1>
</div>
<div class="hright"></div>
</div>
<div id="mysubheader">
<h1 class="msg">Guide <span>utilisateur</span></h1>
</div>
</div>
<!-- End Header -->
{{ super() }}
{% endblock %}
{% block footer %}
<!-- Begin Footer -->
<div id="footer">
<div class="container">
<div class="lft">
<h1 class="titleb"><span class="logo"></span><a href="http://mapmint.com" target="_blank">Map<span>Mint</span></a></h1>
<hr/>
</div>
<div class="rgt">
<img src="http://test.trial.mapmint.com/cgi-bin/zoo_loader.cgi?service=WPS&version=1.0.0&request=Execute&Identifier=QREncode&DataInputs=size=3;bgcolor=3A3A3A;fgcolor=83C849;Text=http://mapmint.com&RawDataOutput=QR" />
</div>
</div>
</div>
<!-- End Footer -->
<div class="bottom-block">
<div class="btm-cnt">
<p>© Copyright 2011-2013
<a href="http://mapmint.com" class="ftr" target="_blank">
<span class="mmw">Map</span><span class="mmg">Mint</span>
</a>
</p>
</div>
</div>
{% endblock %}
{# remove second relbar, at the bottom of the page #}
{% block relbar2 %}{% endblock %}
<|start_filename|>public_map/assets/js/login-cfg.js<|end_filename|>
// Filename: login.js
requirejs.config({
baseUrl: '../public_map/assets',
paths: {
minimal: 'minimal',
text: 'js/lib/require-text-2.0.12',
hgn: 'js/lib/require-hgn-0.3.0',
ol: 'js/lib/openlayers/ol',
olpopup: 'js/lib/openlayers/ol-popup',
jquery: 'js/lib/jquery/jquery-2.1.3.min',
bootstrap: 'js/lib/bootstrap-3.1.1-dist/js/bootstrap.min',
bootselect: 'js/lib/bootstrap-select.min',
notify: 'js/lib/bootstrap-notify',
enquire: 'js/lib/enquire.min',
hogan: 'js/lib/hogan/hogan-3.0.2',
xml2json: 'js/lib/xml2json/xml2json.min',
queryString: 'js/lib/query-string/query-string',
wpsPayloads: 'js/lib/zoo/payloads',
wpsPayload: 'js/lib/zoo/wps-payload',
utils: 'js/lib/zoo/utils',
zoo: 'js/lib/zoo/zoo',
domReady: 'js/lib/domReady',
app: 'js/login',
},
shim: {
bootstrap: {
deps: ['jquery'],
},
notify: {
deps: ['jquery','bootstrap'],
},
wpsPayloads: {
deps: ['hogan'],
},
wpsPayload: {
deps: ['wpsPayloads'],
exports: 'wpsPayload',
},
hogan: {
exports: 'Hogan',
},
xml2json: {
exports: "X2JS",
},
queryString: {
exports: 'queryString',
},
app: {
deps: ['enquire','notify','bootstrap','minimal']
}
},
waitSeconds: 0
});
requirejs.config({
config: {
app: {
url: 'http://zoo.dev.publicamundi.eu/cgi-bin/zoo_loader.fcgi',
delay: 2000,
}
}
});
requirejs.onResourceLoad = function (context, map, depArray) {
console.log(map.name + ' : ' + map.url);
};
require(['domReady', 'app'], function(domReady, app) {
domReady(function() {
app.initialize();
});
window.cgalProcessing=app.cgalProcessing;
window.app=app;
});
<|start_filename|>mapmint-ui/js/messages-box.js<|end_filename|>
$(function() {
$(".dialog-postgis").dialog({
autoOpen: false,
height: 440,
width: 700,
modal: true,
resizable: false,
buttons: {
'Add': function() {
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$(".dialog-postgis-new").dialog({
autoOpen: false,
height: 280,
width: 300,
modal: true,
resizable: false,
buttons: {
'Add': function() {
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$(".dialog-wms").dialog({
autoOpen: false,
height: 440,
width: 700,
modal: true,
resizable: false,
buttons: {
'Add': function() {
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$(".dialog-wms-new").dialog({
autoOpen: false,
height: 250,
width: 300,
modal: true,
resizable: false,
buttons: {
'Add': function() {
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$(".dialog-wfs").dialog({
autoOpen: false,
height: 440,
width: 700,
modal: true,
resizable: false,
buttons: {
'Add': function() {
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$(".dialog-wfs-new").dialog({
autoOpen: false,
height: 250,
width: 300,
modal: true,
resizable: false,
buttons: {
'Add': function() {
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$(".dialog-success").dialog({
autoOpen: false,
height: 150,
width: 350,
modal: true,
resizable: false,
buttons: {
'OK': function() {
$(this).dialog('close');
}
}
});
$('.success-call')
.button()
.click(function() {
$('.dialog-success').dialog('open');
});
$(".dialog-error").dialog({
autoOpen: false,
height: 150,
width: 350,
modal: true,
resizable: false,
buttons: {
'OK': function() {
$(this).dialog('close');
} }
});
$('.error-call')
.button()
.click(function() {
$('.dialog-error').dialog('open');
});
$(".dialog-loading").dialog({
autoOpen: false,
height: 150,
width: 350,
modal: true,
resizable: false,
buttons: {
'OK': function() {
$(this).dialog('close');
} }
});
$('.loading-call')
.button()
.click(function() {
$('.dialog-loading').dialog('open');
});
});
<|start_filename|>mapmint-ui/js/Distiller.js<|end_filename|>
System.flexi_cnt=0;
function loadFormWithObject(form,fields,object){
var dbParams=fields;
if(!object){
for(var t=0;t<dbParams.length;t++){
if($mj(form+"."+dbParams[t])){
if(t!="stype")
$mj(form+"."+dbParams[t]).value="";
else
try{$mj(form+"."+dbParams[t]).selectedIndex=0;}catch(e){}
}
}
}else{
var tmp=object;
for(var t in tmp){
if($mj(form+"."+t)){
$mj(form+"."+t).value=tmp[t];
}
}
}
}
MapMintDSManager=Class.create({
runConvertion: function(){
var params=[];
if($("#chk1")[0].checked)
params[params.length]={"name":"s_srs","dataType":"string","value":"+init="+$("#s_srs").val()};
if($("#tdso_chk_srs")[0].checked)
params[params.length]={"name":"t_srs","dataType":"string","value":"+init="+$("#tdso_srs").val()};
params[params.length]={"name":"dst_in","dataType":"string","value":$("#dst_in").val()};
params[params.length]={"name":"dso_in","dataType":"string","value":$("#dso_in").val()};
params[params.length]={"name":"dso_f","dataType":"string","value":$("#tdso_format").val()};
params[params.length]={"name":"dst_out","dataType":"string","value":$("#tdso").val()};
params[params.length]={"name":"dso_out","dataType":"string","value":$("#out_name").val()};
//alert($("#sql_chk")[0].checked);
if($("#sql_chk")[0].checked)
params[params.length]={"name":"sql","dataType":"string","value":$("#sql").val()};
if($("#ov1")[0].checked)
params[params.length]={"name":"overwrite","dataType":"string","value":"true"};
else
params[params.length]={"name":"append","dataType":"string","value":"true"};
var request=WPSGetHeader("vector-converter.convert")+WPSGetInputs(params)+WPSGetOutput({"name":"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
data: request,
contentType: "text/xml",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$( "#Ogr2OgrGUI-dialog" ).window("close");
}
}
});
},
remove: function(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.delete&DataInputs=name="+$mj("Distiller.datasource.name").value+";type="+$mj("Distiller.datasource.stype").value,
dataType: "text",
complete: function(xml,status) {
var tmp=$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp!="")
$.notifyBar({ cssClass: "error", html: tmp });
else
$.notifyBar({ cssClass: "success", html: $(xml.responseXML).find("wps\\:LiteralData").text() });
$( "#delete-database-dialog" ).window('close');
MapMintDBManager.refresh($mj("Distiller.datasource.stype").value);
}
});
},
startSetGeometryType: function(){
$.ajax({
url: "./Distiller/SetGeometryType;geoType="+arguments[2]+";dst="+arguments[0]+";dso="+arguments[1],
complete: function(xml,status){
if(!$('#sgt-dialog')[0])
$("body").append('<div id="sgt-dialog" title="Layer Geometry Type"></div>');
$('#sgt-dialog').html("");
$('#sgt-dialog').append(xml.responseText);
$('#sgt-dialog').window({
width: 100,
height: 100,
maximizable:false,
resizable: false
});
}
});
},
setGeometryType: function(){
$.ajax({
url: System.zooUrl+"?request=Execute&service=wps&version=1.0.0&Identifier=mapfile.setGeometryType&DataInputs=dst="+$(dst).val()+";dso="+$(dso).val()+";geoType="+$(geoType).val()+"&RawDataOutput=Result",
complete: function(xml,status){
if(checkWPSResult(xml))
$('#sgt-dialog').window('close');
}
});
}
});
Ogr2OgrGUI=Class.create({
initializeWindow: function(){
$.ajax({
url: "./Distiller/VectorConverter;dst="+arguments[0]+";dso="+arguments[1],
complete: function(xml,status){
if(!$('#Ogr2OgrGUI-dialog')[0])
$("body").append('<div id="Ogr2OgrGUI-dialog" title="'+System.messages["Vector Converter"]+'"></div>');
$('#Ogr2OgrGUI-dialog').html("");
$('#Ogr2OgrGUI-dialog').append(xml.responseText);
$('#Ogr2OgrGUI-dialog').window({
width: 550,
height: 350,
maximizable:false,
resizable: false
});
}
});
}
});
function exportAsZip(){
$.ajax({
url: System.zooUrl+"?request=Execute&service=WPS&version=1.0.0&Identifier=vector-converter.doZip&DataInputs=dst="+arguments[0]+";dso="+arguments[1]+";dstn="+arguments[1]+"_dl.zip&RawDataOutput=Result",
complete: function(xml,status){
if(checkWPSResult(xml,false)){
document.location=xml.responseText;
}
}
});
}
MapMintDBManager=Class.create({
accessDST: function(){
$.ajax({
type: "GET",
url: "./Distiller/PgWindow;dataStore="+$('#browser_selected_dsName').val(),
complete: function(xml,status) {
if(!$('#databaseAccess-dialog')[0])
$('body').append('<div id="databaseAccess-dialog" title="'+System.messages["Database Access"]+'"></div>');
$( "#databaseAccess-dialog" ).html("").append(xml.responseText);
$( "#databaseAccess-dialog" ).window({
height: 500,
width: 720,
minimizable:false,
maximizable:false,
resizable: false
});
}
});
},
validTupleEditing: function(){
var params="{";
var clause="";
$("#pg_editor").find('input').each(function(){
if(this.id){
if(this.id=="clause")
clause=this.id.replace(/pg_tuple_/g,"")+"="+(this.value==""?"NULL":this.value);
else{
params+=(params!="{"?",":"")+'"'+this.id.replace(/pg_tuple_/g,"")+'":"'+(this.value==""?"NULL":(this.type=="checkbox"?(this.checked?'t':'f'):$(this).val()))+'"';
}
}
});
var content=null;
$("#pg_editor").find('textarea').each(function(){
if(this.id!="pg_tuple_content")
params+=(params!="{"?",":"")+'"'+this.id.replace(/pg_tuple_/g,"")+'":"'+$(this).val().replace(/\r\n|\r|\n/g,"\\\\n")+'"'
else
content="<div>"+CKEDITOR.instances.pg_tuple_content.getData()+"</div>";
});
$("#pg_editor").find('select').each(function(){
params+=(params!="{"?",":"")+'"'+this.id.replace(/pg_tuple_/g,"")+'":"'+$(this).val()+'"'
});
params+="}"
var request=WPSGetHeader("datastores.postgis.editTuple");
var dataInputs=[];
dataInputs[dataInputs.length]={"name": "dataStore","value": $('#browser_selected_dsName').val(),"dataType": "string"};
dataInputs[dataInputs.length]={"name": "table","value": $('#pg_table').val(),"dataType": "string"};
if($('#clause').val() && $('#clause').val()!="true")
dataInputs[dataInputs.length]={"name": "clause","value": $('#clause').val(),"dataType": "string"};
dataInputs[dataInputs.length]={"name": "obj","value": params,"dataType": "string"};
if(content!=null)
dataInputs[dataInputs.length]={"name": "content","value": content,"mimeType": "text/xml"};
request+=WPSGetInputs(dataInputs)+WPSGetOutput({"name":"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
data: request,
contentType: "text/xml",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$( "#databaseEditor-dialog" ).window("close");
MapMintDBManager.loadTable();
}
}
});
},
refreshTablesList: function(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.listTables&DataInputs=dataStore="+$('#browser_selected_dsName').val()+";schema="+$('#pg_schema').val()+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var tmp=eval(xml.responseText);
$("#pg_table").html('<option value="-1">'+System.messages["Choose"]+'</option>');
for(i=0;i<tmp.length;i++)
$("#pg_table").append('<option value="'+tmp[i][0]+'">'+tmp[i][1]+'</option>');
}
}
});
},
editTuple: function(){
var cnt=0;
System.tupleID="";
$('#pg_table_display tr').each(function(){
if($(this).hasClass('trSelected')){
System.tupleID=this.id.replace(/row/g,"");
}
cnt+=1;
});
$.ajax({
type: "GET",
url: "./Distiller/PgEditorWindow;dataStore="+$('#browser_selected_dsName').val()+";table="+$('#pg_table').val()+(System.tupleID!=""?";clause="+System.pkey+"="+System.tupleID:""),
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
if(!$('#databaseEditor-dialog')[0])
$('body').append('<div id="databaseEditor-dialog" title="'+System.messages["Database Editor"]+'"></div>');
$( "#databaseEditor-dialog" ).html("").append(xml.responseText);
$( "#databaseEditor-dialog" ).window({
width: 600,
height: 420,
minimizable:false,
maximizable:false,
resizable: false
});
if (CKEDITOR.instances.pg_tuple_content) { CKEDITOR.instances.pg_tuple_content.destroy(true); }
CKEDITOR.replace('pg_tuple_content',{
skin : 'v2',
entities: false,
basicEntities: false,
toolbar:[
{ name: 'document', items : [ 'Source','NewPage','Preview' ] },
{ name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
{ name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','Scayt' ] },
'/',
{ name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
{ name: 'styles', items : [ 'Styles','Format' ] },
'/',
{ name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
{ name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote' ] },
{ name: 'links', items : [ 'Link','Unlink','Anchor' ] },
{ name: 'colors', items : [ 'TextColor','BGColor' ] },
{ name: 'tools', items : [ 'Maximize'] }
]
});
}
}
});
},
deleteTuple: function(){
$('#pg_table_display tr').each(function(){
if($(this).hasClass('trSelected')){
System.tupleID=this.id.replace(/row/g,"");
}
});
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.deleteTuple&DataInputs=dataStore="+$('#browser_selected_dsName').val()+";table="+$('#pg_table').val()+";clause="+System.pkey+"="+System.tupleID+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
MapMintDBManager.loadTable();
}
}
});
},
loadTable: function(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.getTableDescription&DataInputs=dataStore="+$('#browser_selected_dsName').val()+";table="+$('#pg_table').val()+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var colModel=[];
var fields=[];
var tmp=eval(xml.responseText);
for(i=0;i<tmp.length;i++){
if(i==0)
System.pkey=tmp[i][1];
colModel[i]={display: tmp[i][1], name : tmp[i][1], width: (i==0?80:120), sortable : true, align: 'center'};
fields[i]=tmp[i][1];
if(tmp[i][3]=="PRI")
System.pkey=tmp[i][1];
}
if($("#pg_table_display")[0])
$("#flexPG").remove();
$("#databaseAccess-dialog").append('<table id="pg_table_display"></table>');
$("#pg_table_display").flexigrid({
autoload: true,
ogcProtocol: "MM",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.getTableContent&RawDataOutput=Result&DataInputs=dataStore="+$('#browser_selected_dsName').val()+";table="+$('#pg_table').val(),
id: "PG",
singleSelect: true,
buttons : [ {
name : System.messages['Add'],
bclass : 'add',
onpress : MapMintDBManager.editTuple
},{
name : System.messages['Edit'],
bclass : 'edit',
onpress : MapMintDBManager.editTuple
},{
name : System.messages['Delete'],
bclass : 'delete',
onpress : MapMintDBManager.deleteTuple
}],
dataType: 'json',
colModel: colModel,
usepager: true,
sortname: tmp[0][1],
sortorder: "asc",
fields: fields,
dwDataSource: $('#browser_selected_dsName').val(),
dwLayer: $('#browser_selected_dsName').val(),
title: $('#pg_table').val(),
useLimit: true,
limit: 10,
showTableToggleBtn: true,
width: "100%",
height: 290
});
}
}
});
},
initializeAddWindow: function(){
var dsType=arguments[0];
var dsName=arguments[1];
if(!Distiller.windows["add-database-dialog"]){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=template.display&DataInputs=tmpl=Distiller_db_display&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
try{
$( 'body').append(xml.responseText);
if(!Distiller.windows)
Distiller.windows={};
if(!Distiller.windows["add-database-dialog"]){
Distiller.windows["add-database-dialog"]=true;
$( "#add-database-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
$("#dlg-buttons a").button();
}
if(dsName!=null && dsType!=null){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.load&DataInputs=type="+dsType+";name="+dsName+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
try{
var tmp=eval('('+xml.responseText+')');
loadFormWithObject("Distiller.pgisform",
Array("name","dbname","host","port",
"password","user","stype"),
tmp);
}catch(e){alert(e);}
}
});
}else{
loadFormWithObject("Distiller.pgisform",
Array("name","dbname","host","port",
"password","user","stype"));
}
}catch(e){alert(e);}
}
});
}else{
$( "#add-database-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
if(dsName!=null && dsType!=null){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.load&DataInputs=type="+dsType+";name="+dsName+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
try{
var tmp=eval('('+xml.responseText+')');
loadFormWithObject("Distiller.pgisform",
Array("name","dbname","host","port",
"password","user","stype"),
tmp);
}catch(e){alert(e);}
}
});
}else{
loadFormWithObject("Distiller.pgisform",
Array("name","dbname","host","port",
"password","user","stype"));
}
}
},
commit: function(){
if (arguments[0]=='cancel'){
confirm('Delete ' + $('.trSelected',grid).length + ' items?');
}
else if (arguments[0]=='add'){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.save&DataInputs=name="+$mj("Distiller.pgisform.name").value+";dbname="+$mj("Distiller.pgisform.dbname").value+";user="+$mj("Distiller.pgisform.user").value+";password="+$mj("<PASSWORD>").value+";host="+$mj("Distiller.pgisform.host").value+";port="+$mj("Distiller.pgisform.port").value+";type="+$mj("Distiller.pgisform.stype").value,
dataType: "xml",
complete: function(xml,status) {
$('#add-database-dialog').window('close');
MapMintDBManager.refresh($mj("Distiller.pgisform.stype").value);
}
});
}
},
refresh: function(){
var localArg=arguments[0];
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.displayJson&DataInputs=type="+arguments[0]+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
var tmp=null;
try{
tmp=eval("("+xml.responseText+")");
}catch(e){}
var myData=[];
if(tmp!=null)
for(var i=0;i<tmp.sub_elements.length;i++){
myData[i]={id: "browseDirectoriesList"+tmp.sub_elements[i].name, text: tmp.sub_elements[i].name, state: "open"};
}
var child;
var stype=(tmp==null?((localArg=="PostGIS")?"postgisList":(localArg=="MySQL"?"mysqlList":"")):((tmp.name=="PostGIS")?"postgisList":(tmp.name=="MySQL"?"mysqlList":"")));
child=$("#browser").tree('getChildren',$("#browser").tree('find',stype).target);
try{
$("#browser").tree('append',{parent: $("#browser").tree('find',stype).target,data: myData});
}catch(e){}
for(i=0;i<child.length;i++){
$("#browser").tree('remove',child[i].target);
}
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
},
test: function(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.test&DataInputs=name="+$mj("Distiller.pgisform.name").value+";dbname="+$mj("Distiller.pgisform.dbname").value+";user="+$mj("Distiller.pgisform.user").value+";password="+$mj("<PASSWORD>").value+";host="+$mj("Distiller.pgisform.host").value+";port="+$mj("Distiller.pgisform.port").value+";type="+$mj("Distiller.pgisform.stype").value+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
checkWPSResult(xml);
}
});
},
remove: function(){
dsType=$mj("Distiller.pgisrform.stype").value;
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores."+((dsType=='postgis' || dsType=='mysql')?"postgis":((dsType=='WMS' || dsType=='WFS')?"wfs":"directories"))+".delete&DataInputs=name="+$mj("Distiller.pgisrform.name").value+";type="+$mj("Distiller.pgisrform.stype").value,
dataType: "text",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
if(dsType=="PostGIS" || dsType=="MySQL")
MapMintDBManager.refresh($mj("Distiller.pgisrform.stype").value);
else
document.location.reload(true);
}
}
});
},
initializeRemoveWindow: function(){
var dsType=$('#browser_selected_type').val().replace(/List/,"");
var dsName=$('#browser_selected_dsName').val().replace(/browseDirectoriesList/,"");
if(dsType=="PostGIS" || dsType=="MySQL"){
dsType=(dsType=="MySQL"?"mysql":"postgis");
loadFormWithObject("Distiller.pgisrform",
Array("name"));
}
if(Distiller.windows["delete-database-dialog"]){
$( "#delete-database-dialog" ).window('close');
$( "#delete-database-dialog" ).parent().remove();
}
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=template.display&DataInputs=tmpl=Distiller_db_remove&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
$( 'body').append(xml.responseText);
if(!Distiller.windows)
Distiller.windows={};
Distiller.windows["delete-database-dialog"]=true;
$( "#delete-database-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
$("#dlgr-buttons a").button();
loadFormWithObject("Distiller.pgisform",
Array("name"));
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores."+((dsType=="postgis" || dsType=="mysql")?"postgis":((dsType=="wfs" || dsType=="wms")?"wfs":"directories"))+".load&DataInputs=type="+dsType+";name="+dsName+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status){
var tmp=eval('('+xml.responseText+')');
loadFormWithObject("Distiller.pgisrform",
Array("name"),
tmp);
loadFormWithObject("Distiller.pgisrform",
Array("stype"),
dsType);
}
});
}
});
}
});
Distiller=MLayout.extend({
id: 0,
cnt: 0,
dataTypes: [],
args: [],
windows: [],
initializeDirWindow: function(){
var localThis=arguments[0];
var localArg1=arguments[1];
if(!Distiller.windows["dialog-directory-new"]){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=template.display&DataInputs=tmpl=Datastore_dirs_display&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
try{
$( 'body').append(xml.responseText);
if(!Distiller.windows)
Distiller.windows={};
if(!Distiller.windows["dialog-directory-new"]){
Distiller.windows["dialog-directory-new"]=true;
$( ".dialog-directory-new" ).window({
minimizable:false,
height: 400,
width: 500,
maximizable:false,
resizable: false
});
}
localThis.loadDir("/","default");
$( '.dialog-directory-new').window("open");
$('.easyui-linkbutton').button();
document.getElementById("Distiller.form.name").value="";
document.getElementById("Distiller.form.path").value="";
if(localArg1!=null){
tmp1=localArg1.split("/");
document.getElementById("Distiller.form.name").value=tmp1[tmp1.length-2];
document.getElementById("Distiller.form.path").value=localArg1;
}
}catch(e){alert(e);}
}
});
}else{
$( '.dialog-directory-new').dialog("open");
document.getElementById("Distiller.form.name").value="";
document.getElementById("Distiller.form.path").value="";
if(localArg1!=null){
tmp1=localArg1.split("/");
document.getElementById("Distiller.form.name").value=tmp1[tmp1.length-2];
document.getElementById("Distiller.form.path").value=localArg1;
}
}
},
editDataStore: function(){
var dsType=$('#browser_selected_type')[0].value.replace(/List/,"");
var dsName=$('#browser_selected_dsName')[0].value.replace(/browseDirectoriesList/,"");
if(dsType=="postgis" || dsType=="mysql"){
MapMintDBManager.initializeAddWindow((dsType=="mysql"?"MySQL":"PostGIS"),
dsName);
loadFormWithObject("Distiller.pgisform",
Array("name","dbname","host","port",
"password","user","stype"));
//Distiller.loadDbFormValues(null);
}
else{
if(dsType=="wms" || dsType=="wfs"){
OWService.initializeEditWindow(dsType,dsName,System.localThis);
}
else{
var tmpDs=dsName.replace(/__/g,"/");
Distiller.initializeDirWindow(System.localThis,tmpDs);
}
}
},
loadIntoGeoreferencer: function(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=georeferencer.saveGeoreferencedProject&DataInputs=dst="+arguments[0]+";dso="+arguments[1]+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
if(checkWPSResult(xml,false))
document.location="./Georeferencer";
}
});
},
cleanDataStore: function(){
var dsType=$('#browser_selected_type')[0].value.replace(/List/,"");
var dsName=$('#browser_selected_dsName')[0].value.replace(/browseDirectoriesList/,"").replace(/__/g,"/");
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.directories.cleanup&DataInputs=dsType="+dsType+";dsName="+dsName+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
if(checkWPSResult(xml))
document.location.reload(true);
}
});
},
directoriesListRefresh: function(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.directories.displayJson&DataInputs=state=open&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
/*if($mj("directoriesListing"))
$mj("directoriesListing").parentNode.removeChild($mj("directoriesListing"));*/
try{
myData=eval("("+xml.responseText+")");
}catch(e){}
var child=$("#browser").tree('getChildren',$("#browser").tree('find',"mainDirectoriesList").target);
try{
$("#browser").tree('append',{parent: $("#browser").tree('find',"mainDirectoriesList").target,data: myData});
}catch(e){}
for(i=0;i<child.length;i++){
$("#browser").tree('remove',child[i].target);
}
if(myData!=null)
for(var i=0;i<myData.length;i++){
myData[i]["id"]="browseDirectoriesList"+myData[i].id;
}
child=$("#browser").tree('getChildren',$("#browser").tree('find',"mainDirectoriesList").target);
$('#browser').tree("append",{parent: $("#browser").tree('find',"mainDirectoriesList"),data: myData});
for(i=0;i<child.length;i++){
$("#browser").tree('remove',child[i].target);
}
cLayout.refresh();
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
},
DatasourceDirCommit: function(){
if (arguments[0]=='cancel'){
confirm('Delete ' + $('.trSelected',grid).length + ' items?')
}
else if (arguments[0]=='add'){
var tmp=null;
$('input[name="Distiller.form.type"]').each(function(){
if($(this).is("checked"))
tmp=$(this).val();
});
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.directories.saveDir&DataInputs=name="+$mj("Distiller.form.name").value+";path="+$mj("Distiller.form.path").value+";type="+tmp+"",
dataType: "xml",
complete: function(xml,status) {
var tmp=$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp=="")
tmp=$(xml.responseXML).find("ExceptionText").text();
if(tmp!="")
$.notifyBar({ cssClass: "error", html: tmp });
else{
$.notifyBar({ cssClass: "success", html: $(xml.responseXML).find("wps\\:LiteralData").text() });
$('.dialog-directory-new').window('close');
document.location.reload(true);
}
}
});
}
},
loadDirContent: function(){
},
loadDir: function(){
if(!Distiller.references){
Distiller.references=[];
Distiller.references1=[];
}
Distiller.unloadDir(arguments[0]);
/*
* We should not use cache if dataStore was modified ...
*/
for(var i=0;i<Distiller.references.length;i++){
if(arguments[0].replace(/__/g,"/")==Distiller.references[i])
return;
}
$.ajax({
dwDataSource: arguments[0],
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier="+(arguments.length>1?"vector-tools":"datastores")+"."+(arguments.length>1?"mmExtractVectorInfo":"mmVectorInfo2MapJs")+"&DataInputs="+(arguments.length>1?"dataSource":"dataStore")+"="+arguments[0].replace(/__/g,"/")+(arguments.length>1?";type="+arguments[1]:"")+"&RawDataOutput=Result",
mmargs: arguments,
dataType: 'xml',
complete: function(xml,status){
try{
var tmp= $.xml2json(xml.responseXML);
var localTmp=[];
var tt="";
if(!tmp.layer){
$.notifyBar({ cssClass: "error", html: "No file found in the directory" });
}
else{
if(!tmp.layer.length){
tmp.layer=[tmp.layer];
}
for(var i=0;i<tmp.layer.length;i++){
localTmp[i]=tmp.layer[i].name;
tt+=i+" = "+localTmp[i]+"\n";
}
}
}catch(e){
alert(e);
var tmp=$(xml.responseXML).find("ows\\:ExceptionText").text();
$.notifyBar({ cssClass: "error", html: tmp });
}
var localLength=Distiller.references.length;
Distiller.references[Distiller.references.length]=this.dwDataSource;
$.notifyBar({ cssClass: "success", html: System.messages["Wait loading datasources from datastore ..."] });
var localCnt;
if(this.mmargs["0"].indexOf("WMS:")>=0){
var tmp=$.xml2json(xml.responseXML);
if(tmp["layer"])
for(i=0;i<tmp["layer"].length;i++){
/*for(j in tmp["layer"][i])
alert(j+" "+tmp["layer"][i][j]);*/
var str='\
<div class="rDiv flexigrid" id="flex'+(System.flexi_cnt)+'" >\
<div class="trigger">\
<span class="distiller_raster"></span> '+this.dwDataSource.replace(/__/g,"/")+" / "+tmp["layer"][i].label+'\
<div class="delete ui-corner-all" id="delete" title="Delete"></div>\
';
str+='<div id="open-in-manager" class="open-in-manager ui-corner-all" title="'+System.messages["Open in Manager"]+'" onclick="openInManager(\''+this.dwDataSource.replace(/__/g,"/")+'\',\''+tmp["layer"][i].name+'\');"></div>';
str+='\
<div id="preview" class="preview ui-corner-all" onclick="loadPreview(\''+tmp["layer"][i].preview_link+'\');" title="'+System.messages["Preview"]+'"></div>\
<div id=\"uaccess\" class="uaccess ui-corner-all" onclick="MapMintUsersManager.editPrivilege(\''+tmp["layer"][i].name+'\',\''+this.dwDataSource.replace(/__/g,"/")+'\');" title="'+System.messages["Set privileges"]+'"></div>\
</div>\
<div class="toggle_container" id="flexi_toggler_'+(System.flexi_cnt)+'">\
<div class="block">\
<div id="chart'+(System.flexi_cnt)+'" class="plot" style="width:100%;height:300px;"></div>\
</div>\
</div>\
</div>\
';
$('#datasources-container-id').append(str);
Distiller.references[System.flexi_cnt]=this.dwDataSource.replace(/__/g,"/");
$('#flexi_toggler_'+(System.flexi_cnt)).hide();
System.flexi_cnt+=1;
}
else{
$.notifyBar({ cssClass: "error", html: "No file found in the directory" });
}
}
else
if(localTmp)
for(var localI=0;localI<localTmp.length;localI++){
var localTmp1=localTmp[localI];
var localCnt=System.flexi_cnt;
//Distiller.references[System.flexi_cnt]=localTmp[localI];
$.ajax({
mmid: localLength,
dwDataSource: this.dwDataSource,
dwLayer: localTmp[localI],
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=vector-tools.mmExtractVectorInfo&DataInputs=dataSource="+this.dwDataSource.replace(/__/g,"/")+";layer="+localTmp[localI]+"&RawDataOutput=Result",
dataType: 'xml',
complete: function(xml,status) {
colModel=[];
fields=[];
try{
var tmp=$.xml2json(xml.responseXML);
var nbCol=0;
if(tmp.fields){
if(tmp.fields.field.length)
for(j=0;j<tmp.fields.field.length;j++){
colModel[nbCol]={display: tmp.fields.field[j].id, name : tmp.fields.field[j].id, width: (nbCol==0?80:120), sortable : true, align: 'center'};
fields[nbCol]=tmp.fields.field[j].id;
nbCol++;
}
else{
colModel[nbCol]={display: tmp.fields.field.id, name : tmp.fields.field.id, width: (nbCol==0?80:120), sortable : true, align: 'center'};
fields[nbCol]=tmp.fields.field.id;
nbCol++;
}
}
var localTmp1=tmp;
if(tmp.fields){
if(localTmp1.previewLink && localTmp1.previewLink.length==2)
localTmp1.previewLink=localTmp1.previewLink[0];
$('#datasources-container-id').append('<table id="flex'+(System.flexi_cnt)+'" style="display:none"></table>');
Distiller.references[System.flexi_cnt]=this.dwDataSource.replace(/__/g,"/");
Distiller.references1[System.flexi_cnt]=this.dwLayer;
//alert(tmp.fields.field.length+" "+tmp.fields.field.id+" "+(tmp.fields.field.length?tmp.fields.field[0].id:tmp.fields.field.id));
try{
if(!System.ds_flexigrids)
System.ds_flexigrids=Array();
System.ds_flexigrids[System.flexi_cnt]=$("#flex"+(System.flexi_cnt)).flexigrid({
adminAccess: '<tr><td class="ndcol1"></td><td class="ndcol4" onclick="addFeatureId(\''+this.dwDataSource.replace(/__/g,"/")+'\',\''+this.dwLayer+'\');">'+System.messages["Add a FID Column"]+'</td></tr>',
autoload: false,
url: System.zooUrl,
dataType: 'xml',
colModel: colModel,
usepager: true,
sortname: (tmp.fields.field.length?tmp.fields.field[0].id:tmp.fields.field.id),
sortorder: "asc",
id: System.flexi_cnt,
fields: fields,
dwDataSource: this.dwDataSource.replace(/__/g,"/"),
dwLayer: this.dwLayer,
dwDataType: (tmp.geometry=='Polygon'?'polygon':(tmp.geometry=='Point'?'point':'line')),
mmid: this.mmid,
nbElements: tmp.featureCount,
title: this.dwDataSource.replace(/__/g,"/")+" / "+tmp.name.replace(/__/g,"/"),
useLimit: true,
limit: 10,
showTableToggleBtn: true,
tableToggleBtns:
[
{title: System.messages["Delete"],name: 'delete',onclick: function(){
var myId=this.id.split('_')[1];
Distiller.deleteDsConfirm(System.ds_flexigrids[myId][0].p.dwDataSource,System.ds_flexigrids[myId][0].p.dwLayer);
}},
{name: 'open-in-manager', title: ""+System.messages["Open in Manager"]+"", content: '<a href="#" class="change-format" onclick="openInManager(\''+this.dwDataSource+'\',\''+this.dwLayer+'\');"> </a>'
},
{name: 'transform',title: System.messages['Convert'], dso:this.dwDataSource+'|'+this.dwLayer, onclick: function(){var arg=this.id.split("_");Ogr2OgrGUI.initializeWindow(Distiller.references[arg[1]],Distiller.references1[arg[1]]);}},
{name: 'download',title: System.messages['Download'], dso:this.dwDataSource+'|'+this.dwLayer, onclick: function(){var arg=this.id.split("_");exportAsZip(Distiller.references[arg[1]],Distiller.references1[arg[1]]);}},
{name: 'preview',title: System.messages['Preview'],onclick: function(){
loadPreview(localTmp1.previewLink?tmp.previewLink:"");
}},
{name: 'reproject',title: System.messages["Set projection"],content: '<a href="#" class="change-format" onclick="if(\''+tmp.srs+'\'==\'(unknown)\') startSetProjectionWindow(\''+this.dwDataSource+'\',\''+this.dwLayer+'\');">'+(tmp.srs!=""?tmp.srs:"No EPSG")+'</a>'},
{name: 'uaccess',title: System.messages['Set privileges'], dso:this.dwDataSource+'|'+this.dwLayer, onclick: function(){var arg=this.id.split("_");var arg1=$(this).attr("dso").split("|")[1];MapMintUsersManager.editPrivilege(arg1,Distiller.references[arg[1]]);}},
],
bottomToggleBtns:
[
{content: '<span class="pEncoding">'+System.messages["Choose encoding:"]+'<input href="#" type="text" class="change-format" style="width: 80px;margin-top: 5px;" name="swenc_'+System.flexi_cnt+'" id="swenc_'+System.flexi_cnt+'" value="'+tmp.encoding+'" /></span>'}
],
width: "100%",
height: 290
});
$("#flex"+(System.flexi_cnt)).addClass('hideBody');
}catch(e){alert("Flexigrid failed to be created "+e);}
}else{
if(tmp.Band && !tmp.Band.length)
tmp.Band=Array(tmp.Band);
if(tmp.Band){
var str='\
<div class="rDiv flexigrid" id="flex'+(System.flexi_cnt)+'" >\
<div class="trigger">\
<span class="distiller_raster"></span> '+this.dwDataSource.replace(/__/g,"/")+" / "+this.dwLayer+'\
<div class="ptogtitle ui-corner-all" id="flexi_title_'+(System.flexi_cnt)+'" title="Toogle table">\
<span></span>\
</div>\
<div class="delete ui-corner-all" id="delete" title="Delete"></div>\
';
if(tmp.origin)
str+='<div id="open-in-manager" class="open-in-manager ui-corner-all" title="'+System.messages["Open in Manager"]+'" onclick="openInManager(\''+this.dwDataSource.replace(/__/g,"/")+'\',\''+this.dwLayer+'\');"></div>';
else
str+='<div id="open-in-manager" class="open-in-manager ui-corner-all" title="'+System.messages["Open in Georeferencer"]+'" onclick="Distiller.loadIntoGeoreferencer(\''+this.dwDataSource.replace(/__/g,"/")+'\',\''+this.dwLayer+'\');"></div>';
str+='\
<div id="download" class="download ui-corner-all" onclick="exportAsZip(\''+this.dwDataSource.replace(/__/g,"/")+'\',\''+this.dwLayer+'\');" title="'+System.messages["Download"]+'"></div>\
<div id="preview" class="preview ui-corner-all" title="'+System.messages["Preview"]+'" onclick="loadRasterPreview(\''+this.dwDataSource.replace(/__/g,"/")+'\',\''+this.dwLayer+'\')" ></div>\
<div id="transform" class="transform ui-corner-all" title="'+System.messages["Transform"]+'" onclick="Raster.startDemWindow(\''+this.dwDataSource.replace(/__/g,"/")+'\',\''+this.dwLayer+'\');"></div>\
<div id="reproject" class="reproject ui-corner-all" title="'+System.messages["Change projection"]+'" onclick="startSetProjectionWindow(\''+this.dwDataSource.replace(/__/g,"/")+'\',\''+this.dwLayer+'\',true)">\
<a class="change-format" href="#">undefined</a>\
</div>\
<div id=\"uaccess\" class="uaccess ui-corner-all" onclick="MapMintUsersManager.editPrivilege(\''+this.dwLayer+'\',\''+this.dwDataSource.replace(/__/g,"/")+'\');" title="'+System.messages["Set privileges"]+'"></div>\
</div>\
<div class="toggle_container" id="flexi_toggler_'+(System.flexi_cnt)+'">\
<div class="block">\
<div id="chart'+(System.flexi_cnt)+'" class="plot" style="width:100%;height:300px;"></div>\
</div>\
</div>\
</div>\
';
$('#datasources-container-id').append(str);
Distiller.references[System.flexi_cnt]=this.dwDataSource.replace(/__/g,"/");
$.jqplot.config.enablePlugins = true;
mySeries=[];
myLabels=[];
var j=0;
for(var i=0;i<tmp.Band.length;i++){
//alert("["+tmp.Band[i].histogram[0].Text+"]");
mySeries[j] = eval("["+tmp.Band[i].histogram+"]");
myLabels[j] = "Band "+(i+1);
j++;
}
plot2 = $.jqplot('chart'+System.flexi_cnt, mySeries, {
seriesDefaults:{
rendererOptions:{ varyBarColor : true },
lineWidth: 1.5,
markerRenderer: $.jqplot.MarkerRenderer,
markerOptions: {
show: false,
style: 'square',
lineWidth: 2,
size: 4,
color: '#666666',
shadow: true,
shadowAngle: 45,
shadowOffset: 1,
shadowDepth: 3,
shadowAlpha: 0.07
}
},
barRenderer: {barWidth: '1px'},
highlighter: { bringSeriesToFront: true, tooltipLocation: 'e', tooltipOffset: 0, formatString: '<div class="jqplot-highlighter">%s: <strong>%s</strong></div>' },
axesDefaults:{
min: 0
},
cursor: {
show: true,
zoom: true
},
grid: {background: '#FFFFFF', gridLineColor: '#b4b4b4', borderColor: '#b4b4b4', borderWidth:'1px', drawBorder:false},
legend: {show: true, location: 'nw', xoffset: -115, labels: myLabels },
seriesColors: [ "#3DA83B", "#86C55A", "#B3EF75"]
});
$('#flexi_toggler_'+(System.flexi_cnt)).hide();
//$(".toggle_container").hide();
$("#flexi_title_"+System.flexi_cnt)[0].local_id=System.flexi_cnt;
$("#flexi_title_"+System.flexi_cnt).click(function(){
$("#flexi_toggler_"+this.local_id).slideToggle("slow");
});
$("div.ptogtitle, .delete, .open-in-mamanger, .download, .preview, .reproject").tipsy({fade: true, offset:3, opacity: 1, gravity: 'ne'});
}else
return -1;
}
System.flexi_cnt+=1;
}catch(e){
alert("MM Error : "+e);
for(var i in e)
alert(i+" "+e[i]);
}
}
});
}
}
});
},
unloadDir: function(){
arguments[0]=arguments[0].replace(/__/g,"/");
if(Distiller.references)
for(var i=0;i<Distiller.references.length;i++){
try{
//alert(Distiller.references[i]+" "+arguments[0])
if(Distiller.references[i]==arguments[0] && $mj('flex'+i)){
$mj('flex'+i).style.display=($mj('flex'+i).style.display=='none'?'block':'none');//parentNode.removeChild($mj('flex'+i));
//Distiller.references[i]=false;
}
}catch(e){alert("MM Error: "+e);}
}
},
last_dir: null,
loaded_dirs: {},
deleteDsConfirm: function(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=template.display&DataInputs=tmpl=Distiller/removeDs;dst="+arguments[0]+";dso="+arguments[1]+";dsotype="+arguments[1].value+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
if(!$('#removeDs-dialog')[0])
$("body").append('<div id="removeDs-dialog" title="Delete Data Source"></div>');
$('#removeDs-dialog').html("");
$( "#removeDs-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
$('#removeDs-dialog').html(xml.responseText);
$('.easyui-linkbutton').button();
}
}
});
},
deleteDs: function(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.removeDS&DataInputs=dso="+$("#Distiller_deleteDS_name").val()+";dst="+$("#Distiller_deleteDS_dst").val()+";dsotype="+$("#Distiller_deleteDS_stype").val()+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$('#removeDs-dialog').html(xml.responseText);
document.location.reload(true);
}
}
});
},
userManagement: function(){
var dsType=$('#browser_selected_type')[0].value.replace(/List/,"");
var dsName=$('#browser_selected_dsName')[0].value.replace(/browseDirectoriesList/,"").replace(/__/g,"/");
$.ajax({
type: "GET",
url: "UsersManagement/DataStoreAccess;dataStore="+dsName,
dataType: "xml",
complete: function(xml,status) {
if($( "#umdt-dialog" ).length==0)
$("body").append('<div id="umdt-dialog" title="'+System.messages["Admin privileges"]+'"></div>');
$('#umdt-dialog').html("");
$('#umdt-dialog').append(xml.responseText);
$("#umdt-dialog" ).window({
width: 350,
height: 300,
minimizable:false,
maximizable:false,
resizable: true
});
}
});
},
validDataStorePrivileges: function(){
var postRequest=[];
postRequest[postRequest.length]={'name': "dataStore",value: $("#am_dataStore").val(),dataType: "string"};
$('.ds_gselect').each(function(){
postRequest[postRequest.length]={'name': 'group',value: $(this).val(),dataType: "string"};
});
for(i in {"r":"","w":"","x":""})
$('.'+i+'_ds_um_group').each(function(){
postRequest[postRequest.length]={'name': "ds_"+i,value: ($(this).attr("checked")?1:0),dataType: "string"};
});
var data=WPSGetHeader("datastores.saveDataStorePrivileges")+WPSGetInputs(postRequest)+WPSGetOutput({name:"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
data: data,
contentType: "text/xml",
complete: function(xml,status) {
if(checkWPSResult(xml)){
$( "#umEditor-dialog" ).window('close');
}
}
});
},
setUserPrivilegesForLayer: function(){
alert(arguments[0]+" "+arguments[1]);
}
});
Distiller.define({
loadDir: function(){
Distiller.last_dir=arguments[0];
Distiller.last_node=arguments[1];
if(arguments.length>=2 && arguments[1]!="default" && !Distiller.loaded_dirs[Distiller.last_dir]){
Distiller.last_node.origin_text=Distiller.last_node.text;
$("#browser4DirectoriesList__").tree('update',{target: Distiller.last_node.target, id: Distiller.last_node.id, text: Distiller.last_node.origin_text+" (loading...)"});
}
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.directories."+(arguments[0]=="/"?"list":"displayJson")+"&DataInputs=dir="+Distiller.last_dir+(Distiller.last_dir=="/"?"":"/")+(arguments.length>1?";type="+arguments[1]:"")+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
if(!Distiller.loaded_dirs[Distiller.last_dir]){
Distiller.loaded_dirs[Distiller.last_dir]=true;
$('#progress_bar .ui-progress').css('width', '65%');
var reg=/\//g;
var tmpId='#browseDirectoriesList'+Distiller.last_dir.replace(reg,"__");
if(Distiller.last_dir=='/')
$(tmpId).html('<ul id="browser4DirectoriesList'+Distiller.last_dir.replace(reg,'__')+'" class="filetree treeview" style="height: 185px;overflow:auto;"><li class="collapsable lastCollapsable"><div class="hitarea expandable-hitarea" onclick=""></div>'+'<span class="folder">Directory '+Distiller.last_dir+': </span>'+xml.responseText+'</li></ul>');
else{
$("#browser4DirectoriesList__").tree('update',{target: Distiller.last_node.target, id: Distiller.last_node.id, text: Distiller.last_node.origin_text});
//alert(Distiller.last_node.id+" "+eval(xml.responseText));
var tmp=eval(xml.responseText);
/*for(var i=0;i<tmp.length;i++)
alert(tmp[i]["id"]);*/
try{
$("#browser4DirectoriesList__").tree('append',{parent: Distiller.last_node.target, data: tmp});
$("#browser4DirectoriesList__").tree('toggle',Distiller.last_node.target);
$("#browser4DirectoriesList__").tree('toggle',Distiller.last_node.target);
}catch(e){
}
//$(tmpId).append(xml.responseText);
}
$('#progress_bar .ui-progress').css('width', '95%');
if(!Distiller.browser4DirectoriesList)
Distiller.browser4DirectoriesList=$("#browser4DirectoriesList__").tree({
checkbox: true,
onBeforeExpand:function(node){
layouts[0].loadDir(node.id.replace("browseDirectoriesList","").replace(/__/g,"/"),node);
},
onCheck: function(node,ischeck){
try{
var val=node.id;
if($("#browser4DirectoriesList__").tree('isLeaf',node.target)){
val=$("#browser4DirectoriesList__").tree('getParent',node.target).id;
}
if(ischeck)
$mj('Distiller.form.path').value=val.replace("browseDirectoriesList","").replace(/__/g,"/");
//Distiller.loadDir(node.id);
else
$mj('Distiller.form.path').value="/";
}catch(e){}
}
});
/*$("#directoriesList/"+Distiller.last_dir).tree({checkbox: true,
onClick:function(node){
//alert("hehe"+node.id);
}});*/
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
}
});
},
initialize: function(){
$(".addDB-toolbar dt a").click(function() {
$(".addDB-toolbar dd ul").show('slow');
});
$(".addDB-toolbar dd ul").mouseleave(function() {
$(".addDB-toolbar dd ul").hide('slow');
});
Distiller.dataTypes[0]={type: 'MySQL',loaded: true};
Distiller.dataTypes[1]={type: 'PostGIS',loaded: true};
Distiller.dataTypes[2]={type: 'dir',loaded: true};
cLayout.refresh();
//this.loadDir("/","default");
function test(com,grid)
{
if (com=='Delete')
{
confirm('Delete ' + $('.trSelected',grid).length + ' items?')
}
else if (com=='Add')
{
//alert('Add New Item');
}
}
$('b.top').click
(
function ()
{
$(this).parent().toggleClass('fh');
}
);
System.localThis=this;
$('.dir').button({
text: false
}).click(function() {
Distiller.initializeDirWindow(System.localThis);
});
$('.db').button({
text: false
}).click(function() {
MapMintDBManager.initializeAddWindow();
});
$('.wfs').button({
text: false
}).click(function() {
System.wxsType="WFS";
MapMintWFSManager.initializeAddWindow();
});
$('.wms').button({
text: false
}).click(function() {
System.wxsType="WMS";
MapMintWFSManager.initializeAddWindow();
});
endLoading();
},
refresh: function(){
$('.add-layer-vector, .add-layer-raster, .add-layer-wms, .add-layer-wfs, .add-layer-wcs').button({text: false});
$('a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
try{
for(var i=0;i<Distiller.dataTypes.length;i++)
if(Distiller.dataTypes[i].loaded==false)
return -1;
$("#browser").tree({
checkbox: true,
onCheck:function(node, checked){
if($("#browser").tree('isLeaf',node.target)){
//alert(node.id+" "+checked);
reg=/browseDirectoriesList/;
if(checked)
Distiller.loadDir((node.id+'').replace(reg,""));
else
Distiller.unloadDir((node.id+'').replace(reg,""));
}
},
onContextMenu: function(e, node){
if($("#browser").tree('isLeaf',node.target)){
e.preventDefault();
var parentName=$("#browser").tree('getParent',node.target).id;
$('#browser_selected_type').val(parentName);
$('#browser_selected_dsName').val(node.id.replace(/browseDirectoriesList/,""));
System.mmNodeId=node.id;
$('#browser').tree('select', node.target);
/*$('#browser_db_menu').emenu('show', {
left: e.pageX,
top: e.pageY
});
$("#db_menu_item").css({"display":((parentName=="postgisList")?"block":"none")});*/
if(parentName=="postgisList"){
$('#browser_db_menu').emenu('show', {
left: e.pageX,
top: e.pageY
});
}else{
//if(parentName=="mainDirectoriesList")
$('#browser_menu').emenu('show', {
left: e.pageX,
top: e.pageY
});
/*else
$('#browser_ows_menu').emenu('show', {
left: e.pageX,
top: e.pageY
});*/
}
}
}
}
);
$("#browser4DirectoriesList"+Distiller.last_dir).tree();
}catch(e){alert("Tree error"+e);}
},
reloadDir:function(){
Distiller.loaded_dirs[Distiller.Distiller.last_dir]=false;
}
});
function loadRasterPreview(){
$.ajax({
type: "GET",
url: "Distiller/previewLink;dst="+arguments[0]+";dso="+arguments[1]+"",
dataType: "text",
complete: function(xml,status) {
loadPreview(xml.responseText);
}
});
}
function loadPreview(){
var toto=$mj("preview-dialog-image");
//alert(toto==null);
if(toto==null)
$("body").append('<div id="preview-dialog" title="'+System.messages["Preview"]+'"><img id="preview-dialog-image" alt="loading..." src="'+arguments[0]+'" /></div>');
else{
$mj( "preview-dialog-image" ).src="";
$mj( "preview-dialog-image" ).src=arguments[0];
}
$( "#preview-dialog" ).window({
width: 550,
height: 500,
minimizable:false,
maximizable:false,
resizable: true
});
return;
}
function addFeatureId(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=vector-converter.addFeatureId&DataInputs=InputDSTN="+arguments[0]+";InputDSON="+arguments[1]+"",
dataType: "text",
complete: function(xml,status) {
var tmp=$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp!="")
$.notifyBar({ cssClass: "error", html: tmp });
else{
$.notifyBar({ cssClass: "success", html: $(xml.responseXML).find("wps\\:LiteralData").text() });
document.location.reload(true);
}
//$( "#delete-database-dialog" ).window('close');
//MapMintDBManager.refresh($mj("Distiller.datasource.stype").value);
}
});
}
function createTileindex(){
var postRequest=[];
var args="";
postRequest[postRequest.length]={'name': "dir",value: $('#tdir')[0].value.replace(/__/g,"/").replace(/browseDirectoriesList/,""),dataType: "string"};
postRequest[postRequest.length]={'name': "ext",value: $("#t_ext").val(),dataType: "string"};
postRequest[postRequest.length]={'name': "iname",value: $("#tname").val(),dataType: "string"};
$("#tprj").find("option:selected").each(function () {
postRequest[postRequest.length]={'name': "srs",value: this.value,dataType: "string"};
});
$("#tileindex_dest").find("option:selected").each(function () {
postRequest[postRequest.length]={'name': "idir",value: this.value,dataType: "string"};
});
var data=WPSGetHeader("raster-tools.createTindex")+WPSGetInputs(postRequest)+WPSGetOutput({name:"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
data: data,
contentType: "text/xml",
complete: function(xml,status) {
checkWPSResult(xml);
}
});
}
function mozaicImages(){
var postRequest=[];
var args="";
postRequest[postRequest.length]={'name': "dir",value: $('#tdir').val().replace(/__/g,"/").replace(/browseDirectoriesList/,""),dataType: "string"};
postRequest[postRequest.length]={'name': "ext",value: $("#t_ext").val(),dataType: "string"};
postRequest[postRequest.length]={'name': "iname",value: $("#tname").val(),dataType: "string"};
$("#tprj").find("option:selected").each(function () {
postRequest[postRequest.length]={'name': "srs",value: this.value,dataType: "string"};
});
$("#tileindex_dest").find("option:selected").each(function () {
postRequest[postRequest.length]={'name': "OutputDSN",value: System.dataPath+"/dirs/"+this.value+"/"+$("#tname").val()+".tif",dataType: "string"};
});
var data=WPSGetHeader("raster-tools.Gdal_Merge")+WPSGetInputs(postRequest)+WPSGetOutput({name:"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
data: data,
contentType: "text/xml",
complete: function(xml,status) {
checkWPSResult(xml);
}
});
}
function openInManager(dwDataSource,dwLayer){
var data=WPSGetHeader("mapfile.openInManager")+WPSGetInputs([{"name": "dstn","value": dwDataSource.replace(/__/g,"/"),"dataType":"string"},{"name": "dson","value":dwLayer,"dataType":"string"}])+WPSGetOutput({name:"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
data: data,
contentType: "text/xml",
complete: function(xml,status) {
if(checkWPSResult(xml))
document.location="./Manager";
}
});
}
MapMintWFSManager=Class.create({
initializeAddWindow: function(){
var dsType=arguments[0];
var dsName=arguments[1];
if(Distiller.windows["add-wfs-dialog"]){
$("#add-wfs-dialog").window('close');
$("#add-wfs-dialog").parent().remove();
Distiller.windows["add-wfs-dialog"]=false;
}
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=template.display&DataInputs=tmpl=Distiller/wfs/display;type="+System.wxsType+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
try{
$( 'body').append(xml.responseText);
if(!Distiller.windows)
Distiller.windows={};
if(Distiller.windows["add-wfs-dialog"]){
$("#add-wfs-dialog").window("close");
$("#add-wfs-dialog").remove();
}
Distiller.windows["add-wfs-dialog"]=true;
$( "#add-wfs-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
$("#dlg-buttons a").button();
}catch(e){alert(e);}
}
});
},
commit: function(){
if (arguments[0]=='cancel'){
confirm('Delete ' + $('.trSelected',grid).length + ' items?');
}
else if (arguments[0]=='add' || arguments[0]=='test'){
($("#Distiller_wfsform_name").val()?$("#Distiller_wfsform_name").val():$("#OWS_form_name").val())
var tdata=
WPSGetHeader("datastores.wfs."+(arguments[0]=='add'?"save":"test"))+
WPSGetInputs([
{
name: "name",
value: ($("#Distiller_wfsform_name").val() && $("#Distiller_wfsform_name").val()!=""?$("#Distiller_wfsform_name").val():$("#OWS_form_name").val()),
dataType: "string"
},
{
name: "url",
value: ($("#Distiller_wfsform_url").val() && $("#Distiller_wfsform_url").val().replace(/&/g,"&")!=""?$("#Distiller_wfsform_url").val().replace(/&/g,"&"):$("#OWS_form_url").val()),
dataType: "string"
},
{
name: "type",
value: ($("#Distiller_wfsform_wxsType").val() && $("#Distiller_wfsform_wxsType").val()!=""?$("#Distiller_wfsform_wxsType").val():$("#OWS_form_type").val()),
dataType: "string"
}
])+
WPSGetOutput({"name":"Result"})+
WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
data: tdata,
contentType: "text/xml",
mtype: arguments[0],
complete: function(xml,status) {
if(checkWPSResult(xml) && this.mtype!="test"){
MapMintWFSManager.refresh($mj("Distiller_wfsform_wxsType").value);
$('#add-wfs-dialog').window('close');
}
}
});
}
},
refresh: function(){
var localArg=arguments[0];
document.location.reload(true);
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.wfs.displayJson&DataInputs=type="+arguments[0]+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
var tmp=null;
try{
tmp=eval("("+xml.responseText+")");
}catch(e){}
var myData=[];
if(tmp!=null)
for(var i=0;i<tmp.sub_elements.length;i++){
myData[i]={id: "browseDirectoriesList"+tmp.sub_elements[i].name, text: tmp.sub_elements[i].name, state: "open"};
}
var child;
var stype="wfsList";
child=$("#browser").tree('getChildren',$("#browser").tree('find',"wfsList").target);
try{
$("#browser").tree('append',{parent: $("#browser").tree('find',"wfsList").target,data: myData});
}catch(e){}
for(i=0;i<child.length;i++){
$("#browser").tree('remove',child[i].target);
}
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
},
remove: function(){
dsType=$mj("Distiller.pgisrform.stype").value;
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores."+(($mj("Distiller.pgisrform.stype").value=='PostGIS' || $mj("Distiller.pgisrform.stype").value=='MySQL')?"postgis":"directories")+".delete&DataInputs=name="+$mj("Distiller.pgisrform.name").value+";type="+$mj("Distiller.pgisrform.stype").value,
dataType: "text",
complete: function(xml,status) {
var tmp=$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp!="")
$.notifyBar({ cssClass: "error", html: tmp });
else
$.notifyBar({ cssClass: "success", html: $(xml.responseXML).find("wps\\:LiteralData").text() });
$( "#delete-database-dialog" ).window('close');
if(dsType=="PostGIS" || dsType=="MySQL")
MapMintDBManager.refresh($mj("Distiller.pgisrform.stype").value);
else
document.location.reload(true);
}
});
},
initializeRemoveWindow: function(){
var dsType=$('#browser_selected_type')[0].value.replace(/List/,"");
var dsName=$('#browser_selected_dsName')[0].value.replace(/browseDirectoriesList/,"");
if(dsType=="postgis" || dsType=="mysql"){
dsType=(dsType=="mysql"?"MySQL":"PostGIS");
loadFormWithObject("Distiller.pgisrform",
Array("name"));
}
if(!Distiller.windows["delete-database-dialog"]){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=template.display&DataInputs=tmpl=Distiller_db_remove&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
$( 'body').append(xml.responseText);
if(!Distiller.windows)
Distiller.windows={};
if(!Distiller.windows["delete-database-dialog"]){
Distiller.windows["delete-database-dialog"]=true;
$( "#delete-database-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
$("#dlgr-buttons a").button();
loadFormWithObject("Distiller.pgisform",
Array("name"));
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores."+((dsType=="postgis" || dsType=="mysql")?"postgis":"directories")+".load&DataInputs=type="+dsType+";name="+dsName+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status){
var tmp=eval('('+xml.responseText+')');
loadFormWithObject("Distiller.pgisrform",
Array("name"),
tmp);
loadFormWithObject("Distiller.pgisrform",
Array("stype"),
dsType);
}
});
}
}
});
}else{
$( "#delete-database-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
loadFormWithObject("Distiller.pgisform",
Array("name"));
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.load&DataInputs=type="+dsType+";name="+dsName+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status){
var tmp=eval('('+xml.responseText+')');
loadFormWithObject("Distiller.pgisrform",
Array("name"),
tmp);
}
});
}
}
});
Raster={
startDemWindow: function(){
$.ajax({
url: "./Distiller/RasterWindow;dst="+arguments[0]+";dso="+arguments[1],
complete: function(xml,status){
if($('#raster-dialog')[0]){
$('#raster-dialog').window('close');
$('#raster-dialog').remove();
}
$("body").append('<div id="raster-dialog" title="'+System.messages["Terrain Tools"]+' Type"></div>');
$('#raster-dialog').html("");
$('#raster-dialog').append(xml.responseText);
$('#raster-dialog').window({
width: 250,
height: 400,
maximizable:false,
resizable: false
});
$(".hasInfo").tipsy({fade: true, offset:3, opacity: 1, gravity: 'se'});
}
});
}
}
function runGdalDem(){
params=[];
params.push({name: "InputDSN",value: $("#ofname").val(),dataType: "string"});
if($("#raster_method").val()=="contour"){
params.push({name: "OutputDSN",value: $("#ofdst").val()+$("#raster_oname").val()+".shp",dataType: "string"});
params.push({name: "i",value: $("#contour_interval").val(),dataType: "string"});
params.push({name: "a",value: $("#contour_aname").val(),dataType: "string"});
}else{
params.push({name: "OutputDSN",value: $("#ofdst").val()+$("#raster_oname").val()+".tif",dataType: "string"});
params.push({name: "utility",value: $("#raster_method").val(),dataType: "string"});
params.push({name: "s",value: $("#"+$("#raster_method").val()+"_scale").val(),dataType: "string"});
if($("#raster_method").val()=="hillshade")
params.push({name: "z",value: $("#"+$("#raster_method").val()+"_zFactor").val(),dataType: "string"});
}
params.push({name: "b",value: $("#ofband").val(),dataType: "string"});
$("#"+$("#raster_method").val()+"_p").find("inputs").each(function(){
//alert($(this)[0]);
reg=new RegExp($("#raster_method").val()+"_",'g');
params.push({name: $(this)[0].id.replace(reg,""),value: $(this).val(),dataType: "string"});
});
var data=WPSGetHeader("raster-tools."+($("#raster_method").val()=="contour"?"Gdal_Contour":"Gdal_Dem"))+WPSGetInputs(params)+WPSGetOutput({"name":"Result"})+WPSGetFooter();
$("#raster-dialog").find("input[type=submit]").hide();
$.ajax({
type: "POST",
data: data,
contentType: "text/xml",
url: System.zooUrl,
dataType: "xml",
complete: function(xml,status){
if(checkWPSResult(xml,false)){
$.notifyBar({ cssClass: "success", html: xml.responseText+System.messages[" has been successfully created"] });
$("#raster-dialog").find("input[type=submit]").show();
}
}
});
}
OWService=Class.create({
initializeEditWindow: function(){
var dsType=arguments[0];
var dsName=arguments[1].split(":")[1];
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=template.display&DataInputs=tmpl=Distiller/wfs/display;type="+dsType+";name="+dsName+";etype=Edit&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
try{
if(Distiller.windows["add-wfs-dialog"]){
$( '#add-wfs-dialog').window("close");
$( '#add-wfs-dialog').remove();
Distiller.windows["add-wfs-dialog"]=false;
};
$( 'body').append(xml.responseText);
if(!Distiller.windows)
Distiller.windows={};
if(!Distiller.windows["add-wfs-dialog"]){
Distiller.windows["add-wfs-dialog"]=true;
$( "#add-wfs-dialog" ).window({
minimizable:false,
height: 200,
width: 340,
maximizable:false,
resizable: false
});
}
$( '.add-wfs-dialog').window("open");
$('.easyui-linkbutton').button();
}catch(e){}
}
});
}
});
function startMergeWindow(){
mmTIN={};
if($("#tileindex-data-dialog")[0]){
$("#tileindex-data-dialog").window('close');
$("#tileindex-data-dialog").remove();
}
if(!$("#merge-data-dialog")[0])
$("body").append('<div id="merge-data-dialog" title="'+System.messages["Mosaic a set of images"]+'"></div>');
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=upload.getForm&DataInputs=form=Distiller/TileWindow;type=merge&RawDataOutput=Result",
dataType: 'xml',
complete:function(xml,status){
$("#merge-data-dialog").html(xml.responseText);
$("#browse_tile").next().children().tree({
checkbox: true,
onBeforeExpand:function(node){
dirRefresh(node,$("#browse_tile").next().children(),function(myData,node2){
mmTIN[node2.id]["ext"]=detectExt(myData);
});
},
onCheck: function(node,ischeck){
if(ischeck){
if(mmTIN[node.id] && mmTIN[node.id]["ext"]){
$('#t_ext')[0].value=mmTIN[node.id]["ext"];
}
$('#tdir').val(node.id);
}
else
$('#tdir').val("");
}
});
$("#merge-data-dialog").window({
minimizable:false,
maximizable:false,
resizable: false
});
}
});
}
function setProjection(){
var postRequest=[];
postRequest[postRequest.length]={'name': "dstn",value: $("#layer_dst")[0].value,dataType: "string"};
postRequest[postRequest.length]={'name': "dson",value: $("#layer_dso")[0].value,dataType: "string"};
postRequest[postRequest.length]={'name': "srs",value: $("#set_tprj")[0].value,dataType: "string"};
postRequest[postRequest.length]={'name': "isRaster",value: (System.isRaster?System.isRaster:false),dataType: "string"};
var data=WPSGetHeader("vector-converter.setSRS")+WPSGetInputs(postRequest)+WPSGetOutput({name:"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
data: data,
contentType: "text/xml",
complete: function(xml,status) {
checkWPSResult(xml);
Distiller.loaded_dirs[Distiller.last_dir]=false;
}
});
}
function startSetProjectionWindow(){
if(arguments.length>2)
System.isRaster=arguments[2];
else
System.isRaster=false;
if($("#projection-data-dialog").length>0){
$("#projection-data-dialog").window('close');
$("#projection-data-dialog").remove();
}
$("body").append('<div id="projection-data-dialog" title="'+System.messages["Set Projection"]+'"></div>');
$("#projection-data-dialog")[0].title="Set Project for "+arguments[1];
var rpl=System.dataPath+'/dirs/';
rpl=rpl.replace(/\//g,'__');
var dstName=arguments[0].replace(/__/g,"/");/*.replace(rpl,"").replace("__","");*/
var idir=arguments[0].replace(rpl,"").replace("__","");;
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=template.display&DataInputs=tmpl=Distiller/SetProjection;dstName="+dstName+";dsoName="+arguments[1]+"&RawDataOutput=Result",
dataType: 'xml',
complete:function(xml,status){
$("#projection-data-dialog").html(xml.responseText);
$("#projection-data-dialog").window({
minimizable:false,
maximizable:false,
resizable: false
});
}
});
}
function detectExt(myData){
for(var i=0;i<myData.length;i++){
var tmp=myData[i]['text'].split('.');
if(tmp.length > 1 && (tmp[1]=="ecw" || tmp[1]=="tif")){
return tmp[1];
}
}
return System.messages["Not found"];
}
function startTileWindow(){
mmTIN={};
if($("#merge-data-dialog")[0]){
$("#merge-data-dialog").window('close');
$("#merge-data-dialog").remove();
}
if(!$("#tileindex-data-dialog")[0])
$("body").append('<div id="tileindex-data-dialog" title="'+System.messages["Add tileindex"]+'"></div>');
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=upload.getForm&DataInputs=form=Distiller/TileWindow&RawDataOutput=Result",
dataType: 'xml',
complete:function(xml,status){
$("#tileindex-data-dialog").html(xml.responseText);
$("#browse_tile").next().children().tree({
checkbox: true,
onBeforeExpand:function(node){
dirRefresh(node,$("#browse_tile").next().children(),function(myData,node2){
mmTIN[node2.id]["ext"]=detectExt(myData);
});
},
onCheck: function(node,ischeck){
if(ischeck){
if(mmTIN[node.id] && mmTIN[node.id]["ext"]){
$('#t_ext')[0].value=mmTIN[node.id]["ext"];
}
$('#tdir').val(node.id);
}
else
$('#tdir').val("");
}
});
$("#tileindex-data-dialog").window({
minimizable:false,
maximizable:false,
resizable: false
});
}
});
}
var mmTIN={};
function dirRefresh(){
var node1=arguments[0];
var myTree=arguments[1];
var myFunc=arguments[2];
var dir=node1.id.replace('browseDirectoriesList','').replace(/__/g,'/');
var hasValue=false;
for(var i in mmTIN)
if(i==node1.id)
hasValue=true;
if(!hasValue){
mmTIN[node1.id]={text: node1.text};
myTree.tree('update',{target: node1.target,text: mmTIN[node1.id]['text']+" (updating...)"});
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.directories.displayJson&DataInputs=dir="+dir+"&RawDataOutput=Result",
complete: function(xml,status) {
var myData="None";
try{
myData=eval("("+xml.responseText+")");
}catch(e){alert(e);}
if(myFunc)
myFunc(myData,node1);
myTree.tree('append',{parent: node1.target,data: myData});
myTree.tree('update',{target: node1.target,text: mmTIN[node1.id]["text"]});
myTree.tree('toggle',node1.target);
myTree.tree('toggle',node1.target);
}
});
}
}
<|start_filename|>mapmint-ui/templates/Manager/Display_bs.html<|end_filename|>
#import zoo
#def printDenom(name,title)
<div class="form-group">
<label class="col-md-3 control-label">$title</label>
<div class="col-md-9">
<div class="input-group">
<input class="form-control" name="$name" type="text" placeholder="$zoo._("Not defined")" />
<span class="input-group-btn">
<button class="btn btn-default mm-scale" type="button">$zoo._("Use Map Scale")</button>
</span>
</div>
</div>
</div>
#end def
<form class="form-horizontal mtpp" method="get" >
<h4>$zoo._("Layer settings")</h4>
$printDenom("minDisplay",$zoo._("Min Scale"))
$printDenom("maxDisplay",$zoo._("Max Scale"))
<h4>$zoo._("Label settings")</h4>
$printDenom("minLabel",$zoo._("Min Scale"))
$printDenom("maxLabel",$zoo._("Max Scale"))
<button class="btn btn-default mm-layer-save" href="#" >$zoo._("Save")</button>
</form>
<|start_filename|>public_map/tree.css<|end_filename|>
/*
* MapMint Tree CSS
*/
.tree{
font-size:.8em;
margin:0;
color:#565656;
padding:0;
list-style-type:none;
}
.tree li{
white-space:nowrap;
font-size:.95em;
color:#333333;
font-weight:bold;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
}
.tree li ul{
list-style-type:none;
margin:0;
padding:0;
}
.tree li ul li{
font-size:1em;
color:#565656;
font-weight:normal;
text-shadow: none;
}
.tree-node{
height:18px;
padding: 5px 0 3px 0;
white-space:nowrap;
cursor:pointer;
}
.tree-indent{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-hit{
cursor:pointer;
}
.tree-expanded{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
background:url('./img/tree_arrows.png') no-repeat -18px 0px;
}
.tree-expanded-hover{
background:url('./img/tree_arrows.png') no-repeat -50px 0px;
}
.tree-collapsed{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
background:url('./img/tree_arrows.png') no-repeat 0px 0px;
}
.tree-collapsed-hover{
background:url('./img/tree_arrows.png') no-repeat -32px 0px;
}
.tree-folder{
display:inline-block;
background:url('./img/tree_folder.png') no-repeat;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-folder-open{
background:url('./img/tree_folder_open.png') no-repeat;
}
.tree-file{
display:inline-block;
/*background:url('./img/tree_file.png') no-repeat;*/
width:26px;
height:20px;
vertical-align:middle;
}
.tree-loading{
background:url('./img/tree_loading.gif') no-repeat;
}
.tree-title{
display:inline-block;
text-decoration:none;
vertical-align:middle;
padding:1px 2px 1px 2px;
white-space:nowrap;
}
.tree-node-hover{
background:#ffffff;
background: -moz-linear-gradient(top, #FFFFFF, #eaeaea);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#eaeaea));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#EAEAEA'); /* for IE */
}
.tree-checkbox{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-checkbox0{
background:url('./img/tree_checkbox_0.png') no-repeat;
}
.tree-checkbox1{
background:url('./img/tree_checkbox_1.png') no-repeat;
}
.tree-checkbox2{
background:url('./img/tree_checkbox_2.png') no-repeat;
}
.tree-node-proxy{
font-size:12px;
padding:1px 2px 1px 18px;
background:#fafafa;
border:1px solid #ccc;
z-index:9900000;
}
.tree-dnd-yes{
background:url('./img/tree_dnd_yes.png') no-repeat 0 center;
}
.tree-dnd-no{
background:url('./img/tree_dnd_no.png') no-repeat 0 center;
}
.tree-node-top{
border-top:1px dotted red;
}
.tree-node-bottom{
border-bottom:1px dotted red;
}
.tree-node-append .tree-title{
border:1px dotted red;
}
.tree-editor{
border:1px solid #ccc;
font-size:12px;
line-height:16px;
width:80px;
position:absolute;
top:0;
}
.menu, .emenu{
position:absolute;
background:#f0f0f0 url('./img/menu.gif') repeat-y;
margin:0;
padding:2px;
border:1px solid #ccc;
overflow:hidden;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
.menu-item{
position:relative;
margin:0;
padding:0;
height:22px;
line-height:20px;
overflow:hidden;
font-size:.8em;
color:#565656;
cursor:pointer;
border:1px solid transparent;
_border:1px solid #f0f0f0;
}
.menu-text{
position:absolute;
left:28px;
top:0px;
}
.menu-icon{
position:absolute;
width:16px;
height:16px;
top:3px;
left:2px;
}
.menu-rightarrow{
position: absolute;
width:4px;
height:7px;
top:7px;
right:5px;
background:url('./img/menu_rightarrow.png') no-repeat;
}
.menu-sep{
margin:3px 0px 3px 24px;
line-height:2px;
font-size:2px;
background:url('./img/menu_sep.png') repeat-x;
}
.menu-shadow{
position:absolute;
background:#ddd;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
}
.scales{
background:url('./img/scales.png') no-repeat;
}
.min-scale{
background:url('./img/min-scale.png') no-repeat;
}
.max-scale{
background:url('./img/max-scale.png') no-repeat;
}
.icon-moveLayer{
background:url('./img/move.png') no-repeat;
}
.zoomTo{
background:url('./img/zoomtolayer.png') no-repeat;
}
.icon-opacity{
background:url('./img/opacity.png') no-repeat;
}
.icon-db{
background:url('./img/db-icon.png') no-repeat;
}
.icon-blank{
background:url('./img/blank.gif') no-repeat;
}
.icon-add{
background:url('./img/edit_add.png') no-repeat;
}
.icon-edit{
background:url('./img/pencil.png') no-repeat;
}
.icon-remove{
background:url('./img/edit_remove.png') no-repeat;
}
.icon-table{
}
.icon-style{
background:url('./img/palette.png') no-repeat;
}
.icon-properties{
background:url('./img/properties.png') no-repeat;
}
.icon-save{
background:url('./img/filesave.png') no-repeat;
}
.icon-cut{
background:url('./img/cut.png') no-repeat;
}
.icon-ok{
background:url('./img/ok.png') no-repeat;
}
.icon-no{
background:url('./img/no.png') no-repeat;
}
.icon-cancel{
background:url('./img/cancel.png') no-repeat;
}
.icon-reload{
background:url('./img/reload.png') no-repeat;
}
.icon-search{
background:url('./img/search.png') no-repeat;
}
.icon-print{
background:url('./img/print.png') no-repeat;
}
.icon-help{
background:url('./img/help.png') no-repeat;
}
.icon-undo{
background:url('./img/undo.png') no-repeat;
}
.icon-redo{
background:url('./img/redo.png') no-repeat;
}
.icon-back{
background:url('./img/back.png') no-repeat;
}
.icon-sum{
background:url('./img/sum.png') no-repeat;
}
<|start_filename|>public_map/assets/js/toto.js<|end_filename|>
if(baseLayers["mq"].length>=1){
for(i in baseLayers["mq"]){
console.log(i);
console.log(baseLayers["mq"][i]);
var osm=new ol.layer.Tile({
name: "MapQuest_"+baseLayers["mq"][i],
attributions: "",
source: new ol.source.MapQuest({layer: baseLayers["mq"][i]})
});
myBL.push(osm);
}
}
if(baseLayers["mq"].length>=1){
for(i in baseLayers["mq"])
var osm=new ol.layer.Tile({
style: 'Road',
source: new ol.source.MapQuest({layer: 'osm'})
});
myBL.push(osm);
}
if(baseLayers["mq1"]==1){
var osm=new ol.layer.Tile({
style: 'Aerial',
source: new ol.source.MapQuest({layer: 'sat'})
});
myBL.push(osm);
}
<|start_filename|>mapmint-ui/new-themes/themes/default/layout.css<|end_filename|>
/*
* MapMint layout CSS
*/
/*
* Panes titles
*/
h1.pane-title{margin:0;padding:5px 0 3px 5px;font-size:1em;font-weight:bold;text-shadow: #FFFFFF 0px 1px 0px;
background: rgb(255,255,255);
background: url(data:image/svg+xml;base64,<KEY>+Cjwvc3ZnPg==);
background: -moz-linear-gradient(top, rgba(255,255,255,1) 27%, rgba(232,232,232,1) 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(27%,rgba(255,255,255,1)), color-stop(100%,rgba(232,232,232,1)));
background: -webkit-linear-gradient(top, rgba(255,255,255,1) 27%,rgba(232,232,232,1) 100%);
background: -o-linear-gradient(top, rgba(255,255,255,1) 27%,rgba(232,232,232,1) 100%);
background: -ms-linear-gradient(top, rgba(255,255,255,1) 27%,rgba(232,232,232,1) 100%);
background: linear-gradient(to bottom, rgba(255,255,255,1) 27%,rgba(232,232,232,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e8e8e8',GradientType=0 );
color:#707070;
}
h1.pane-title-sub{margin:0;padding:5px 0 3px 5px;font-size:.9em;font-weight:normal;text-shadow: #FFFFFF 0px 1px 0px;
background: -moz-linear-gradient(top, #d9d9d9, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#d9d9d9), to(#b6b6b6));
background: -ms-linear-gradient(#d9d9d9, #b6b6b6);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#d9d9d9', endColorstr='#B6B6B6');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#d9d9d9', endColorstr='#B6B6B6');
}
h1.pane-title-small{margin:0;padding:5px 0 3px 5px;font-size:1em;font-weight:normal;text-shadow: #FFFFFF 0px 1px 0px;
background: -moz-linear-gradient(top, #E9E9E9, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#E9E9E9), to(#b6b6b6));
background: -ms-linear-gradient(#E9E9E9, #b6b6b6);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E9E9E9', endColorstr='#B6B6B6');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E9E9E9', endColorstr='#B6B6B6');
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
margin:0 0 5px 0;
behavior: url(js/ie-css3.htc);
}
h1.pane-title span.project-title{color:red;padding:0 0 0 10px;}
h3.title{margin:0;padding:5px 0 0 10px;font-size:1em;color:#333333;text-shadow: 0 1px 0 rgba(255, 255, 255, 1);}
p.hour, p.ip{margin:0;padding:0;font-size:.8em;color:#777777;padding:3px 0 0 5px;}
.west-container{
height:90%;
overflow-y:auto;
overflow-x:hidden;
background:#FFFFFF;
}
.center-container{
height:89%;
overflow-y:auto;
overflow-x:hidden;
}
.lcontent {
padding: 0px;
position: relative;
overflow-y: auto;
overflow-x: hidden;
}
.ui-layout-pane {
background: #FFFFFF;
border:0;
padding: 0px;
}
.ui-layout-content {
padding: 10px;
position: relative;
overflow: auto;
}
/*
* RESIZER-BARS
*/
.ui-layout-toggler{background:#83c849;}
.ui-layout-toggler:hover{background:#707070;}
.ui-layout-resizer {
background: #CACACA;
border: 1px solid #EEEEEE;
border-width: 0;
}
.ui-layout-resizer{background:#CACACA;}
div.ui-layout-resizer-open span.close {
display:none;
}
div.ui-layout-resizer-open span.close-inv {
display:none;
}
.ui-layout-resizer-hover { /* affects both open and closed states */
background:#CACACA;}
.ui-layout-resizer-open-hover , /* hover-color to 'resize' */
.ui-layout-resizer-dragging { /* resizer beging 'dragging' */
background: #CACACA;
}
.ui-layout-resizer-dragging { /* CLONED resizer being dragged */
border-left: 1px solid #BBB;
border-right: 1px solid #BBB;
}
.ui-layout-resizer-dragging-limit { /* CLONED resizer at min or max size-limit */
background: #E1A4A4; /* red */
}
.ui-layout-resizer-closed-hover { /* hover-color to 'slide open' */
background: #EBD5AA;
}
.ui-layout-resizer-sliding { /* resizer when pane is 'slid open' */
opacity: .10; /* show only a slight shadow */
filter: alpha(opacity=10);
}
.ui-layout-resizer-sliding-hover { /* sliding resizer - hover */
opacity: 1.00; /* on-hover, show the resizer-bar normally */
filter: alpha(opacity=100);
}
.ui-layout-resizer-north-sliding-hover { border-bottom-width: 1px; }
.ui-layout-resizer-south-sliding-hover { border-top-width: 1px; }
.ui-layout-resizer-west-sliding-hover { border-right-width: 1px; }
.ui-layout-resizer-east-sliding-hover { border-left-width: 1px; }
/*
* Panes specific
*/
.ui-layout-north{
background: rgb(255,255,255);
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIyNyUiIHN0b3AtY29sb3I9IiNmZmZmZmYiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjY2FjYWNhIiBzdG9wLW9wYWNpdHk9IjEiLz4KICA8L2xpbmVhckdyYWRpZW50PgogIDxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9InVybCgjZ3JhZC11Y2dnLWdlbmVyYXRlZCkiIC8+Cjwvc3ZnPg==);
background: -moz-linear-gradient(top, rgba(255,255,255,1) 27%, rgba(202,202,202,1) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(27%,rgba(255,255,255,1)), color-stop(100%,rgba(202,202,202,1))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, rgba(255,255,255,1) 27%,rgba(202,202,202,1) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, rgba(255,255,255,1) 27%,rgba(202,202,202,1) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, rgba(255,255,255,1) 27%,rgba(202,202,202,1) 100%); /* IE10+ */
background: linear-gradient(to bottom, rgba(255,255,255,1) 27%,rgba(202,202,202,1) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#cacaca',GradientType=0 ); /* IE6-8 */
overflow:visible;
z-index:100;
min-height:90px;
}
h1.ttitle {
float:left;
color:#707070;
text-decoration: none;
font-size: 3em;
padding:0;
text-transform:none;
max-width:300px;
margin:0 0 0 10px;
text-shadow:#FFFFFF 0 1px 0;
}
h1.ttitle span.logo{
background:url(../img//mapmint-logo.png) no-repeat;
width:60px;
height:60px;
display:inline-block;
margin:0;
padding:0 0 0 5px;
position:relative;
top:10px;
left:0;
}
h1.ttitle span.mint {
color:#83c849;
}
.ui-layout-west{
overflow:hidden;
}
.ui-layout-center{
overflow:hidden;
}
.datasources-container{overflow-y:auto;}
.ui-layout-south{
background:#707070;
}
/*
* Panes close
*/
.close {width:16px;height:17px;
float:right;
margin: 0 5px 0 0;
cursor:pointer;
background: url(../img/close-sidebar.png) no-repeat;
text-align:center;
font-size:.7em;}
.close-inv {width:17px;height:16px;
background: url(../img/close-sidebar-right.png) no-repeat;
font-size:.7em;cursor:pointer;position:absolute;margin: 0 0 0 1px;}
<|start_filename|>mapmint-ui/templates/preview/modules/other_tools/_init.js<|end_filename|>
#import mapfile.service as mms
#if $mms.getMetadata($m.web,'mmOT')
#set f=$mms.getMetadata($m.web,'mmOT').split(',')
#if f.count('MMPanZoom')>0
map.addControl(new OpenLayers.Control.MMPanZoom());
#else
$(Template(file=$conf["main"]["templatesPath"]+"/preview/modules/other_tools/default.js",searchList={"m": $m,"conf":$conf}))
#end if
#if f.count('ScaleBar')>0
map.addControl(new OpenLayers.Control.ScaleBar({div:document.getElementById("scalebar")}));
#end if
#if $f.count('MMOVMap')>0 or $f.count('MMOVMapFixed')>0
$(Template(file=$conf["main"]["templatesPath"]+"/preview/modules/other_tools/overviewmap.js",searchList={"m": $m,"conf":$conf}))
#end if
#else
$(Template(file=$conf["main"]["templatesPath"]+"/preview/modules/other_tools/default.js",searchList={"m": $m,"conf":$conf}))
#end if
<|start_filename|>mapmint-ui/templates/UsersManagement/GroupForm.html<|end_filename|>
#encoding "utf-8"
#import zoo
#if $inputs["type"]["value"]=="delete"
#set titles=['id','name']
#set names=['id','name']
#else
#set titles=['id','name','description','admin access','super admin']
#set names=['id','name','description','adm','sadm']
#end if
<div id="$inputs["type"]["value"]-group" class="collapse groupBaseEditForm #if $inputs["type"]["value"]!="insert"#groupEditForm#end if#">
<form class="form-inline mt myWell" data-toggle="validator" role="form">
<fieldset class="mbp mtp">
<legend>$zoo._("General informations")</legend>
#set cnt=0
#for i in $titles
#set j=$names[$cnt]
<div class="form-group">
#set ii=$i.replace(' ','_')
#if $cnt>0 and ($inputs["type"]["value"]=="update" or $cnt+1==len(titles) or $cnt+2==len(titles))
<label for="up_$ii" class="control-label">$zoo._(i.title()): </label>
#end if
<input name="$j" id="up_$ii" class="form-control" #if $cnt==0#type="hidden"#else##if ($cnt+2==len(titles) or $cnt+1==len(titles)) and $inputs["type"]["value"]!="delete"#type="checkbox"#end if##end if# #if $inputs["type"]["value"]=="insert"#placeholder="$zoo._(i.title())"#end if# />
#set $cnt+=1
</div>
#end for
<input id="um_utype" type="hidden" value="$inputs["type"]["value"]" />
<button type="submit" href="#" class="btn btn-primary groupSubmitForm">
#if $inputs["type"]["value"]=="delete"#$zoo._("Delete")#else##if $inputs["type"]["value"]=="update"#$zoo._("Save")#else#$zoo._("Add")#end if##end if#
</button>
</fieldset>
</form>
</div>
<|start_filename|>mapmint-services/vector-tools-src/service.c<|end_filename|>
/******************************************************************************
* $Id$
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: Simple client for viewing OGR driver data.
* Author: <NAME>, <EMAIL>
*
******************************************************************************
* Copyright (c) 2010-2014, Cartoworks Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#define _USE_MATH_DEFINES
#include <dirent.h>
#include <fcntl.h>
#include "ogr_api.h"
#include "ogrsf_frmts.h"
#include "cpl_multiproc.h"
#include "gdal.h"
#include "gdal_alg.h"
#ifdef ZOO_SERVICE
#ifdef WIN32
#define XP_WIN 1
#define NEED_STRCASESTR 1
#endif
#include "service.h"
#include "mapserver.h"
#endif
#include "service_internal.h"
#include <libxml/parser.h>
#include <libxml/xpath.h>
extern "C" {
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <libxslt/xslt.h>
#include <libxslt/xsltInternals.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include "service_internal_ms.h"
/*int SVFC=4;
char* SVF[4]={
"TAB",
"GPX",
"KML",
"XML"
};*/
/*extern map* getCorrespondance();
extern void setSrsInformations(maps* output,mapObj* m,layerObj* myLayer, char* pszProjection);
void setMsExtent(maps* output,mapObj* m,layerObj* myLayer,
double minX,double minY,double maxX,double maxY);*/
char* mimeType=NULL;
int mmPage = 1;
int mmLimit = 10;
int dataSource = TRUE;
int bReadOnly = FALSE;
int bVerbose = TRUE;
int bSummaryOnly = FALSE;
int nFetchFID = OGRNullFID;
char** papszOptions = NULL;
void ReportOnLayer( mapObj*, maps*, char* , OGRLayer *, const char *, OGRGeometry *, xmlNodePtr,maps* );
void ReportOnLayer4Map( char*,OGRLayer*, const char*,OGRGeometry*, mapObj*, maps* , maps*);
int gdalinfo( maps*,maps*, char*);
/************************************************************************/
/* main() */
/************************************************************************/
#ifdef WIN32
__declspec(dllexport)
#endif
int mmListVectorDir(maps*& conf,maps*& inputs,maps*& outputs)
{
const char *pszWHERE = NULL;
const char *pszDataDir = NULL;
char *pszDataSource = NULL;
char **papszLayers = NULL;
OGRGeometry *poSpatialFilter = NULL;
int nRepeatCount = 1, bAllLayers = FALSE;
char *pszSQLStatement = NULL;
const char *pszDialect = NULL;
/* -------------------------------------------------------------------- */
/* Register format(s). */
/* -------------------------------------------------------------------- */
OGRRegisterAll();
bSummaryOnly = TRUE;
bVerbose = FALSE;
map *tmp=getMapFromMaps(inputs,"dataDir","value");
if(tmp!=NULL)
pszDataDir = strdup(tmp->value);
else{
setMapInMaps(conf,"lenv","message","Data Dir not found");
return SERVICE_FAILED;
}
DIR *dirp = opendir(pszDataDir);
if(dirp==NULL){
char tmp1[1024];
sprintf(tmp1,_ss("The specified path %s doesn't exist !!!"),pszDataDir);
setMapInMaps(conf,"lenv","message",tmp1);
return SERVICE_FAILED;
}
char *res=NULL;
struct dirent *dp;
while ((dp = readdir(dirp)) != NULL){
if(strlen(dp->d_name)>2 && strstr(dp->d_name,".")!=0){
/* -------------------------------------------------------------------- */
/* Open data source. */
/* -------------------------------------------------------------------- */
pszDataSource=(char*) malloc((strlen(dp->d_name)+strlen(pszDataDir)+1)*sizeof(char));
sprintf(pszDataSource,"%s%s",pszDataDir,dp->d_name);
#if GDAL_VERSION_MAJOR >= 2
GDALDataset *poDS =
(GDALDataset*) GDALOpenEx( pszDataSource,
GDAL_OF_READONLY | GDAL_OF_VECTOR,
NULL, NULL, NULL );
GDALDriverManager* poR=GetGDALDriverManager();
GDALDriver *poDriver = NULL;
#else
OGRSFDriver *poDriver = NULL;
OGRDataSource* poDS = OGRSFDriverRegistrar::Open( pszDataSource, !bReadOnly, &poDriver );
if( poDS == NULL && !bReadOnly ){
poDS = OGRSFDriverRegistrar::Open( pszDataSource, FALSE, &poDriver );
}
#endif
if( poDS != NULL ){
if(res!=NULL){
char* tmp4=strdup(dp->d_name);
tmp4[strlen(dp->d_name)-4]=0;
if(strstr(res,tmp4)==0){
char* tmp3=strdup(res);
res=(char*)realloc(res,(strlen(res)+strlen(dp->d_name)+strlen(pszDataSource)+5)*sizeof(char));
sprintf(res,"%s,\"%s\"",tmp3,pszDataSource);
free(tmp3);
}
}
else{
res=(char*)malloc((strlen(dp->d_name)+strlen(pszDataSource)+4)*sizeof(char));
sprintf(res,"[\"%s\"",pszDataSource);
}
#if GDAL_VERSION_MAJOR < 2
OGRDataSource::DestroyDataSource( poDS );
#endif
}
free(pszDataSource);
}
}
char *tmp3=strdup(res);
res=(char*)realloc(res,(strlen(res)+2)*sizeof(char));
sprintf(res,"%s]",tmp3);
free(tmp3);
setMapInMaps(outputs,"Result","value",res);
free(res);
return SERVICE_SUCCEEDED;
}
#ifdef WIN32
__declspec(dllexport)
#endif
int mmExtractVectorInfo(maps*& conf,maps*& inputs,maps*& outputs)
{
char type[8];
char *pszDataSource = NULL;
int isPg=-1;
int isWxs=-1;
int isJson=-1;
int isRaster=-1;
map *tmpP=getMapFromMaps(conf,"main","dataPath");
map *tmp=getMapFromMaps(inputs,"dataSource","value");
if(tmp!=NULL){
fprintf(stderr,"MAP : %s %d \n",__FILE__,__LINE__);
fflush(stderr);
char *tmpDataSource=strdup(tmp->value);
char *pszDataDir;
char *pszDataDirMY;
pszDataDir=(char*)malloc((strlen(tmpDataSource)+strlen(tmpP->value)+14)*sizeof(char));
sprintf(pszDataDir,"%s/PostGIS/%s.xml",tmpP->value,tmpDataSource);
sprintf(type,"PostGIS");
int dirp = open( pszDataDir , O_RDONLY );
if(dirp<0){
fprintf(stderr,"MAP : %s %d \n",__FILE__,__LINE__);
fflush(stderr);
//pszDataDir=NULL;
//free(pszDataDir);
pszDataDir=(char*)malloc((strlen(tmpDataSource)+strlen(tmpP->value)+12)*sizeof(char));
sprintf(pszDataDir,"%s/MySQL/%s.xml",tmpP->value,tmpDataSource);
//pszDataDir[(strlen(tmpDataSource)+strlen(tmpP->value)+12)]=0;
fprintf(stderr,"MAP : %s %d \n",__FILE__,__LINE__);
fflush(stderr);
fprintf(stderr,"MAP : %s %d \n",__FILE__,__LINE__);
fflush(stderr);
fprintf(stderr,"MAP : %s %d %s \n",__FILE__,__LINE__,pszDataDir);
fflush(stderr);
fprintf(stderr,"MAP : %s %d \n",__FILE__,__LINE__);
fflush(stderr);
sprintf(type,"MySQL");
fprintf(stderr,"MAP : %s %d \n",__FILE__,__LINE__);
fflush(stderr);
dirp = open( pszDataDir , O_RDONLY );
fprintf(stderr,"MAP : %s %d \n",__FILE__,__LINE__);
fflush(stderr);
}
//fprintf(stderr,"MAP : %s %s %d %d \n",__FILE__,__LINE__,pszDataDir,dirp);
//fflush(stderr);
char *res=NULL;
struct dirent *dp;
if(dirp>=0){
fprintf(stderr,"MAP : %s %d \n",__FILE__,__LINE__);
fflush(stderr);
close(dirp);
fprintf(stderr,"XML FOUND \n");
xsltStylesheetPtr cur = NULL;
xmlDocPtr doc, res;
char *xslFileName;
fprintf(stderr,"XML FOUND %s \n",tmpP->value);
xslFileName=(char*)malloc((strlen(tmpP->value)+18)*sizeof(char));
sprintf(xslFileName,"%s/%s/conn.xsl",tmpP->value,type);
cur = xsltParseStylesheetFile(BAD_CAST xslFileName);
doc = xmlParseFile(pszDataDir);
res = xsltApplyStylesheet(cur, doc, NULL);
xmlChar *xmlbuff;
int buffersize;
xsltSaveResultToString(&xmlbuff, &buffersize, res, cur);
pszDataSource = strdup((char*)xmlbuff);
fprintf(stderr,"%s\n",pszDataSource);
free(xmlbuff);
isPg=1;
}
else{
if(strncasecmp(tmpDataSource,"WFS",3)==0){
fprintf(stderr,"\n\n** %s **\n\n",tmpDataSource);
char* pszDataDir=(char*)malloc((strlen(tmpP->value)+strlen(strstr(tmp->value,":")+1)+17)*sizeof(char));
sprintf(pszDataDir,"%s/WFS/%s.txt",tmpP->value,strstr(tmp->value,":")+1);
setMapInMaps(inputs,"wxsMap","value",strstr(tmp->value,":")+1);
int dirp = open( pszDataDir , O_RDONLY );
int nn;
fprintf(stderr,"DATADIR %s %i \n",pszDataDir,dirp);
struct stat results;
if (stat(pszDataDir, &results) == 0){
char *xbuff=(char*)malloc(results.st_size+1);
char *xbuff1=(char*)malloc(results.st_size+5);
while ( ( nn=read(dirp, xbuff, results.st_size)) > 0)
{
xbuff[nn-1]='\0';
sprintf(xbuff1,"WFS:%s",xbuff);
xbuff[nn]='\0';
pszDataSource = strdup(xbuff1);
map* tmpMap=getMapFromMaps(inputs,"dataSource","value");
free(tmpMap->value);
tmpMap->value=strdup(pszDataSource);
fprintf(stderr, "DS: (%s)\n", pszDataSource);
isWxs=1;
}
}else{
fprintf(stderr,"Unable to load %s DataStore.",type);
}
//setMapInMaps(conf,"lenv","message","WFS not yet supported");
//return SERVICE_FAILED;
}else{
char *tmpPath=(char*)malloc((strlen(tmpP->value)+7)*sizeof(char));
sprintf(tmpPath,"%s/dirs/",tmpP->value);
DIR *tmpD=opendir(tmpPath);
if(tmpD==NULL){
char tmp[1024];
snprintf(tmp,1024,_ss("Unable to open directory %s."),tmpP->value);
setMapInMaps(conf,"lenv","message",tmp);
return SERVICE_FAILED;
}
if(tmpD!=NULL)
while ((dp = readdir(tmpD)) != NULL){
fprintf(stderr,":> %s,%s\n",dp->d_name,tmpDataSource);
if(strstr(dp->d_name,tmpDataSource)!=NULL){
pszDataSource=(char *)malloc((strlen(tmpP->value)+strlen(dp->d_name)+8)*sizeof(char));
#ifndef WIN32
sprintf(pszDataSource,"%s/dirs/%s/",tmpP->value,dp->d_name);
#else
sprintf(pszDataSource,"%s/dirs/%s",tmpP->value,dp->d_name);
#endif
}
}
else{
setMapInMaps(conf,"lenv","message","Unable to load Data Source");
return SERVICE_FAILED;
}
}
if(pszDataSource==NULL)
pszDataSource = strdup(tmp->value);
}
}
else{
setMapInMaps(conf,"lenv","message","Data Source not found");
return SERVICE_FAILED;
}
fprintf(stderr,"MAP : %s\n",pszDataSource);
char* iniPszDataSource=strdup(pszDataSource);
/* -------------------------------------------------------------------- */
/* Load Mapfile */
/* -------------------------------------------------------------------- */
map* mapfilePath=getMapFromMaps(inputs,"dataSource","value");
char* mapPath;
if(isPg<0 && isWxs<0){
mapPath=(char*)malloc((strlen(mapfilePath->value)+12)*sizeof(char));
sprintf(mapPath,"%s/ds_ows.map",mapfilePath->value);
}
else{
if(isWxs<0){
map* tmpMap1=getMapFromMaps(conf,"main","dataPath");
mapPath=(char*)malloc((strlen(tmpMap1->value)+strlen(type)+strlen(mapfilePath->value)+13)*sizeof(char));
sprintf(mapPath,"%s/%s/%sds_ows.map",tmpMap1->value,type,mapfilePath->value);
}else{
map* tmpMap1=getMapFromMaps(conf,"main","dataPath");
map* tmpMap2=getMapFromMaps(inputs,"wxsMap","value");
mapPath=(char*)malloc((strlen(tmpMap1->value)+strlen(tmpMap2->value)+16)*sizeof(char));
sprintf(mapPath,"%s/WFS/%sds_ows.map",tmpMap1->value,tmpMap2->value);
}
}
setMapInMaps(conf,"main","mapfile",mapPath);
fprintf(stderr,"Load Mapfile %s %d\n",mapPath,__LINE__);
mapObj* myMap=msLoadMap(mapPath,NULL);
if(myMap==NULL){
mapfilePath->value[strlen(mapfilePath->value)-strlen(strrchr(mapfilePath->value,'/'))]=0;
sprintf(mapPath,"%s/ds_ows.map",mapfilePath->value);
fprintf(stderr,"Load Mapfile %s %d\n",mapPath,__LINE__);
myMap=msLoadMap(mapPath,NULL);
if(myMap==NULL){
fprintf(stderr,"Unable to load mapfile %d !!\n\n",__LINE__);
}
}
dumpMaps(inputs);
fprintf(stderr,"Load Mapfile %s %d\n",mapPath,__LINE__);
map* layerName=getMapFromMaps(inputs,"layer","value");
fprintf(stderr,"Load Mapfile %s %d\n",mapPath,__LINE__);
layerObj* myLayer=NULL;
if(layerName!=NULL){
fprintf(stderr,"Load Mapfile %s %d\n",mapPath,__LINE__);
if(myMap!=NULL){
fprintf(stderr,"Load Layer %s %d\n",layerName->value,myMap->numlayers);
layerObj* myLayer=myMap->layers[msGetLayerIndex(myMap,layerName->value)];
fprintf(stderr,"Load Layer %s %d\n",layerName->value,myLayer->type);
//fprintf(stderr,"LAYER TYPE %d\n",myLayer->type);
if(myLayer->type!=3 || myLayer->tileindex!=NULL){
fprintf(stderr,"LAYER CONNECTION %s\n",myLayer->connection);
if(isPg<0 && isWxs<0){
free(mapPath);
mapPath=(char*)malloc((strlen(iniPszDataSource)+13)*sizeof(char));
sprintf(mapPath,"%s/ds_ows.map",iniPszDataSource);
setMapInMaps(conf,"main","mapfile",mapPath);
free(pszDataSource);
if(myLayer->connection!=NULL)
pszDataSource=strdup(myLayer->connection);
else
if(myLayer->tileindex!=NULL)
pszDataSource=strdup(myLayer->tileindex);
}
if(myLayer->connection!=NULL && strstr(myLayer->connection,".json")!=NULL)
isJson=1;
}
else{
fprintf(stderr,"Should treat raster from here !!\n");
gdalinfo(conf,outputs,myLayer->data);
isRaster=1;
}
}
}
fprintf(stderr,"Load Mapfile %s %d\n",mapPath,__LINE__);
if(isRaster<0){
const char *pszWHERE = NULL;
char **papszLayers = NULL;
OGRGeometry *poSpatialFilter = NULL;
int nRepeatCount = 1, bAllLayers = FALSE;
char *pszSQLStatement = NULL;
const char *pszDialect = NULL;
/* -------------------------------------------------------------------- */
/* Register format(s). */
/* -------------------------------------------------------------------- */
OGRRegisterAll();
//msLookupHashTable(&(layer->metadata),defaultkey)
xmlDocPtr resDoc = xmlNewDoc(BAD_CAST "1.0");
xmlNodePtr n;
bSummaryOnly = TRUE;
bVerbose = FALSE;
map *tmp1=getMapFromMaps(inputs,"layer","value");
map *tmp2=getMapFromMaps(inputs,"getFeatures","value");
if(isJson<0 || tmp2!=NULL){
if(tmp1!=NULL){
if(tmp2!=NULL && isJson>0)
papszLayers = CSLAddString( papszLayers, "OGRGeoJSON" );
else
papszLayers = CSLAddString( papszLayers, tmp1->value );
}
else{
char *tmp4=strrchr(tmp->value,'/');
if(tmp4!=NULL && strlen(tmp4) > 1){
char *tmp2=strrchr(tmp->value,'/')+1;
tmp2[strlen(tmp2)-strlen(strstr(tmp2,"."))]=0;
char *tmp3=strdup(tmp2);
papszLayers = CSLAddString( papszLayers, tmp3 );
fprintf(stderr,tmp3);
free(tmp3);
}
}
}
tmp1=getMapFromMaps(inputs,"getFeatures","value");
if(tmp1!=NULL){
dataSource = FALSE;
tmp1=getMapFromMaps(inputs,"page","value");
if(tmp1!=NULL)
mmPage=atoi(tmp1->value);
tmp1=getMapFromMaps(inputs,"limit","value");
if(tmp1!=NULL)
mmLimit=atoi(tmp1->value);
char* mmField=NULL;
char* mmOrder=NULL;
tmp1=getMapFromMaps(inputs,"sortname","value");
if(tmp1!=NULL)
mmField=strdup(tmp1->value);
tmp1=getMapFromMaps(inputs,"sortorder","value");
if(tmp1!=NULL)
mmOrder=strdup(tmp1->value);
if(mmField!=NULL && mmOrder!=NULL){
pszSQLStatement=(char*) malloc((strlen(mmField)+strlen(mmOrder)+128)*sizeof(char)+1);
if(isPg<0)
sprintf(pszSQLStatement,"SELECT * FROM \"%s\" ORDER BY %s %s",papszLayers[0],mmField,mmOrder);
else{
// Make it case sensitive !!
sprintf(pszSQLStatement,"SELECT * FROM %s ORDER BY %s %s",papszLayers[0],mmField,mmOrder);
}
//sprintf(pszSQLStatement,"SELECT * FROM \"%s\" ORDER BY %s %s",papszLayers[0],mmField,mmOrder);
fprintf(stderr,"SQL (%s)\n",pszSQLStatement);
free(mmField);
free(mmOrder);
}
}
if(dataSource){
n = xmlNewNode(NULL, BAD_CAST "datasource");
}
else
n = xmlNewNode(NULL, BAD_CAST "FeatureCollection");
/* -------------------------------------------------------------------- */
/* Open data source. */
/* -------------------------------------------------------------------- */
#if GDAL_VERSION_MAJOR >= 2
GDALDataset *poDS =
(GDALDataset*) GDALOpenEx( pszDataSource,
GDAL_OF_READONLY | GDAL_OF_VECTOR,
NULL, NULL, NULL );
GDALDriverManager* poR=GetGDALDriverManager();
GDALDriver *poDriver = NULL;
#else
OGRDataSource *poDS = NULL;
OGRSFDriver *poDriver = NULL;
OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar();
poDS = OGRSFDriverRegistrar::Open( pszDataSource, !bReadOnly, &poDriver );
if( poDS == NULL && !bReadOnly )
{
poDS = OGRSFDriverRegistrar::Open( pszDataSource, FALSE, &poDriver );
}
#endif
/* -------------------------------------------------------------------- */
/* Report failure */
/* -------------------------------------------------------------------- */
if( poDS == NULL )
{
char tmp2[2048];
sprintf(tmp2,
_ss("FAILURE:\n"
"Unable to open datasource `%s' with the following drivers:\n"),
pszDataSource );
for( int iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
{
char *tmp3=strdup(tmp2);
#if GDAL_VERSION_MAJOR >=2
sprintf( tmp2, "%s -> `%s'\n", tmp3, poR->GetDriver(iDriver)->GetDescription() );
#else
sprintf( tmp2, "%s -> `%s'\n", tmp3, poR->GetDriver(iDriver)->GetName() );
#endif
free(tmp3);
}
setMapInMaps(conf,"lenv","message",tmp2);
return SERVICE_FAILED;
}
xmlNodePtr n1;
if(dataSource){
n1=xmlNewNode(NULL,BAD_CAST "dataType");
poDriver=poDS->GetDriver();
#if GDAL_VERSION_MAJOR >=2
xmlAddChild(n1,xmlNewText(BAD_CAST poDriver->GetDescription()));
#else
xmlAddChild(n1,xmlNewText(BAD_CAST poDriver->GetName()));
#endif
xmlAddChild(n,n1);
//if(strcasecmp(tmp->GetName(),"ESRI Shapefile")==0){
//OGRLayer *_poResultSet = poDS->ExecuteSQL( tmpSQL, poSpatialFilter, pszDialect );
//}
}
/* -------------------------------------------------------------------- */
/* Special case for -sql clause. No source layers required. */
/* -------------------------------------------------------------------- */
map* tmpSql=getMapFromMaps(inputs,"sql","value");
if(tmpSql!=NULL){
if(pszSQLStatement!=NULL)
free(pszSQLStatement);
pszSQLStatement=strdup(tmpSql->value);
}
if( pszSQLStatement != NULL )
{
OGRLayer *poResultSet = NULL;
nRepeatCount = 0; // skip layer reporting.
poResultSet = poDS->ExecuteSQL( pszSQLStatement, poSpatialFilter,
pszDialect );
if( poResultSet != NULL )
{
if( pszWHERE != NULL )
poResultSet->SetAttributeFilter( pszWHERE );
ReportOnLayer( myMap, inputs, pszDataSource, poResultSet, NULL, NULL, n, conf );
poDS->ReleaseResultSet( poResultSet );
}
free(pszSQLStatement);
}
for( int iRepeat = 0; iRepeat < nRepeatCount; iRepeat++ )
{
if ( CSLCount(papszLayers) == 0 )
{
/* -------------------------------------------------------------------- */
/* Process each data source layer. */
/* -------------------------------------------------------------------- */
for( int iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ )
{
OGRLayer *poLayer = poDS->GetLayer(iLayer);
if( poLayer == NULL )
{
char tmp[128];
sprintf( tmp,
_ss("FAILURE: Couldn't fetch advertised layer %d!\n"),
iLayer );
setMapInMaps(conf,"lenv","message",_ss(tmp));
return SERVICE_FAILED;
}
if (!bAllLayers)
{
ReportOnLayer( myMap, inputs, pszDataSource, poLayer, pszWHERE, poSpatialFilter, n, conf );
}
else
{
if( iRepeat != 0 )
poLayer->ResetReading();
ReportOnLayer( myMap, inputs, pszDataSource, poLayer, pszWHERE, poSpatialFilter, n, conf );
}
}
}
else
{
/* -------------------------------------------------------------------- */
/* Process specified data source layers. */
/* -------------------------------------------------------------------- */
char** papszIter = papszLayers;
for( ; *papszIter != NULL; papszIter++ )
{
OGRLayer *poLayer = poDS->GetLayerByName(*papszIter);
if( poLayer == NULL )
{
char tmp[128];
sprintf( tmp,
_ss("FAILURE: Couldn't fetch requested layer %s!\n"),
*papszIter );
setMapInMaps(conf,"lenv","message",tmp);
return SERVICE_FAILED;
}
if( iRepeat != 0 )
poLayer->ResetReading();
ReportOnLayer(myMap, inputs, pszDataSource, poLayer, pszWHERE, poSpatialFilter, n, conf );
}
}
}
/* -------------------------------------------------------------------- */
/* Close down. */
/* -------------------------------------------------------------------- */
CSLDestroy( papszLayers );
CSLDestroy( papszOptions );
#if GDAL_VERSION_MAJOR <2
OGRDataSource::DestroyDataSource( poDS );
#else
//GDALClose(poDS);
#endif
if (poSpatialFilter)
OGRGeometryFactory::destroyGeometry( poSpatialFilter );
//OGRCleanupAll();
xmlChar *xmlb;
int bsize;
xmlDocSetRootElement(resDoc, n);
xmlDocDumpFormatMemory(resDoc, &xmlb, &bsize, 1);
setMapInMaps(outputs,"Result","value",(char*)xmlb);
}
msSaveMap(myMap,mapPath);
msFreeMap(myMap);
return SERVICE_SUCCEEDED;
}
/************************************************************************/
/* mmVectorInfo2Map() */
/************************************************************************/
#ifdef WIN32
__declspec(dllexport)
#endif
int mmVectorInfo2Map(maps*& conf,maps*& inputs,maps*& outputs)
{
const char *pszWHERE = NULL;
char *pszDataSource = NULL;
char **papszLayers = NULL;
OGRGeometry *poSpatialFilter = NULL;
int nRepeatCount = 1, bAllLayers = FALSE;
char *pszSQLStatement = NULL;
const char *pszDialect = NULL;
int isPg=-1;
int isWxs=-1;
char type[8];
/* -------------------------------------------------------------------- */
/* Register format(s). */
/* -------------------------------------------------------------------- */
OGRRegisterAll();
xmlDocPtr resDoc = xmlNewDoc(BAD_CAST "1.0");
xmlNodePtr n;
map* mapfilePath=getMapFromMaps(inputs,"dataSource","value");
char* mapPath=(char*)malloc((strlen(mapfilePath->value)+11)*sizeof(char));
sprintf(mapPath,"%sds_ows.map",mapfilePath->value);
fprintf(stderr,"Save Mapfile %s\n",mapPath);
/*
* Create an empty map, set name, default size and extent
*/
mapObj *myMap=msNewMapObj();
free(myMap->name);
myMap->name=strdup("ZOO-Project_WXS_Server");
msMapSetSize(myMap,2048,2048);
msMapSetExtent(myMap,-1,-1,1,1);
/*
* Set imagepath and imageurl using tmpPath and tmpUrl from main.cfg
*/
map *tmp2=getMapFromMaps(conf,"main","tmpPath");
myMap->web.imagepath=strdup(tmp2->value);
tmp2=getMapFromMaps(conf,"main","tmpUrl");
myMap->web.imageurl=strdup(tmp2->value);
/*
* Set mapserver PROJ_LIB or any other config parameter from main.cfg
* [mapserver] section
*/
maps *tmp3=getMaps(conf,"mapserver");
if(tmp3!=NULL){
map* tmp4=tmp3->content;
while(tmp4!=NULL){
msSetConfigOption(myMap,tmp4->name,tmp4->value);
tmp4=tmp4->next;
}
}
/*
* Define supported output formats
*/
outputFormatObj *o1=msCreateDefaultOutputFormat(NULL,"AGG/PNG","png");
o1->imagemode=MS_IMAGEMODE_RGBA;
o1->transparent=MS_TRUE;
o1->inmapfile=MS_TRUE;
msAppendOutputFormat(myMap,msCloneOutputFormat(o1));
msFreeOutputFormat(o1);
#ifdef USE_KML
outputFormatObj *o2=msCreateDefaultOutputFormat(NULL,"KML","kml");
o2->inmapfile=MS_TRUE;
msAppendOutputFormat(myMap,msCloneOutputFormat(o2));
msFreeOutputFormat(o2);
#endif
outputFormatObj *o3=msCreateDefaultOutputFormat(NULL,"GDAL/GTiff","tiff");
if(!o3)
fprintf(stderr,"Unable to initialize GDAL driver !\n");
else{
o3->imagemode=MS_IMAGEMODE_BYTE;
o3->inmapfile=MS_TRUE;
msAppendOutputFormat(myMap,msCloneOutputFormat(o3));
msFreeOutputFormat(o3);
}
outputFormatObj *o4=msCreateDefaultOutputFormat(NULL,"GDAL/AAIGRID","grd");
if(!o4)
fprintf(stderr,"Unable to initialize GDAL driver !\n");
else{
o4->imagemode=MS_IMAGEMODE_INT16;
o4->inmapfile=MS_TRUE;
msAppendOutputFormat(myMap,msCloneOutputFormat(o4));
msFreeOutputFormat(o4);
}
#ifdef USE_CAIRO
outputFormatObj *o5=msCreateDefaultOutputFormat(NULL,"CAIRO/PNG","cairopng");
if(!o5)
fprintf(stderr,"Unable to initialize CAIRO driver !\n");
else{
o5->imagemode=MS_IMAGEMODE_RGBA;
o5->transparent=MS_TRUE;
o5->inmapfile=MS_TRUE;
msAppendOutputFormat(myMap,msCloneOutputFormat(o5));
msFreeOutputFormat(o5);
}
#endif
/*
* Set default projection to EPSG:4326
*/
msLoadProjectionStringEPSG(&myMap->projection,"EPSG:4326");
myMap->transparent=1;
/**
* Set metadata extracted from main.cfg file maps
*/
maps* cursor=conf;
map* correspondance=getCorrespondance();
while(cursor!=NULL){
map* _cursor=cursor->content;
map* vMap;
while(_cursor!=NULL){
if((vMap=getMap(correspondance,_cursor->name))!=NULL){
if (msInsertHashTable(&(myMap->web.metadata), vMap->value, _cursor->value) == NULL){
#ifdef DEBUGMS
fprintf(stderr,"Unable to add metadata");
#endif
return SERVICE_FAILED;
}
}
_cursor=_cursor->next;
}
cursor=cursor->next;
}
/**
* Set a ows_rootlayer_title,
*/
if (msInsertHashTable(&(myMap->web.metadata), "ows_rootlayer_name", "ZOO_Project_Layer") == NULL){
#ifdef DEBUGMS
fprintf(stderr,"Unable to add metadata");
#endif
return SERVICE_FAILED;
}
if (msInsertHashTable(&(myMap->web.metadata), "ows_rootlayer_title", "ZOO_Project_Layer") == NULL){
#ifdef DEBUGMS
fprintf(stderr,"Unable to add metadata");
#endif
return SERVICE_FAILED;
}
/**
* Enable all the WXS requests using ows_enable_request
* see http://mapserver.org/trunk/development/rfc/ms-rfc-67.html
*/
if (msInsertHashTable(&(myMap->web.metadata), "ows_enable_request", "*") == NULL){
#ifdef DEBUGMS
fprintf(stderr,"Unable to add metadata");
#endif
return SERVICE_FAILED;
}
msInsertHashTable(&(myMap->web.metadata), "ows_srs", "EPSG:4326");
/**
* Set Mapfile SYMBOLSET
*/
map* _tmp1=getMapFromMaps(conf,"main","dataPath");
char *tmpPath=(char*)malloc((13+strlen(_tmp1->value))*sizeof(char));
sprintf(tmpPath,"%s/symbols.sym",_tmp1->value);
msInitSymbolSet(&myMap->symbolset);
myMap->symbolset.filename=strdup(tmpPath);
free(tmpPath);
/**
* Set Mapfile FONTSET
*/
char *tmpPath1=(char*)malloc((16+strlen(_tmp1->value))*sizeof(char));
sprintf(tmpPath1,"%s/fonts/list.txt",_tmp1->value);
msInitFontSet(&myMap->fontset);
myMap->fontset.filename=strdup(tmpPath1);
free(tmpPath1);
bSummaryOnly = TRUE;
bVerbose = FALSE;
map *tmpP=getMapFromMaps(conf,"main","dataPath");
map *tmp=getMapFromMaps(inputs,"dataSource","value");
if(tmp!=NULL) {
if(strncasecmp(tmp->value,"WMS",3)!=0 && strncasecmp(tmp->value,"WFS",3)!=0){
char *tmpDataSource=strdup(tmp->value);
char *pszDataDir;
char *pszDataDirMY;
pszDataDir=(char*)malloc((strlen(tmpDataSource)+strlen(tmpP->value)+14)*sizeof(char));
sprintf(pszDataDir,"%s/PostGIS/%s.xml",tmpP->value,tmpDataSource);
sprintf(type,"PostGIS");
int dirp = open( pszDataDir , O_RDONLY );
if(dirp<0){
//free(pszDataDir);
sprintf(pszDataDir,"%s/MySQL/%s.xml",tmpP->value,tmpDataSource);
sprintf(type,"MySQL");
dirp = open( pszDataDir , O_RDONLY );
}
fprintf(stderr,"\n\n\nDEBUG %s\n",pszDataDir);
char *res=NULL;
struct dirent *dp;
if(dirp>=0){
close(dirp);
fprintf(stderr,"XML FOUND \n");
xsltStylesheetPtr cur = NULL;
xmlDocPtr doc, res;
char *xslFileName;
fprintf(stderr,"XML FOUND %s \n",tmpP->value);
xslFileName=(char*)malloc((strlen(tmpP->value)+18)*sizeof(char));
sprintf(xslFileName,"%s/%s/conn.xsl",tmpP->value,type);
fprintf(stderr,"%s \n",xslFileName);
cur = xsltParseStylesheetFile(BAD_CAST xslFileName);
fprintf(stderr,"%s \n",xslFileName);
doc = xmlParseFile(pszDataDir);
fprintf(stderr,"%s \n",xslFileName);
res = xsltApplyStylesheet(cur, doc, NULL);
fprintf(stderr,"%s \n",xslFileName);
xmlChar *xmlbuff;
int buffersize;
xsltSaveResultToString(&xmlbuff, &buffersize, res, cur);
pszDataSource = strdup((char*)xmlbuff);
fprintf(stderr,"%s\n",pszDataSource);
free(xmlbuff);
isPg=1;
}
else{
char *tmpPath=(char*)malloc((strlen(tmpP->value)+7)*sizeof(char));
sprintf(tmpPath,"%s/dirs/",tmpP->value);
DIR *tmpD=opendir(tmpPath);
if(tmpD==NULL){
char tmp[1024];
snprintf(tmp,1024,_ss("Unable to open directory %s."),tmpP->value);
setMapInMaps(conf,"lenv","message",tmp);
return SERVICE_FAILED;
}
while ((dp = readdir(tmpD)) != NULL){
fprintf(stderr,":> %s,%s (%s)\n",dp->d_name,tmpDataSource,strstr(tmpDataSource,dp->d_name));
if(strstr(tmpDataSource,dp->d_name)!=NULL){
pszDataSource=(char *)malloc((strlen(tmpP->value)+strlen(dp->d_name)+8)*sizeof(char));
#ifndef WIN32
sprintf(pszDataSource,"%s/dirs/%s/",tmpP->value,dp->d_name);
#else
sprintf(pszDataSource,"%s/dirs/%s",tmpP->value,dp->d_name);
#endif
{
FILE* test0=fopen(pszDataSource,"r");
if(test0!=NULL)
pszDataSource=strdup(tmpDataSource);
}
fprintf(stderr,"DATA SOURCE : %s\n",tmpDataSource);
}
}
if(pszDataSource==NULL){
pszDataSource = strdup(tmp->value);
}
}
}else{
if(strncmp(tmp->value,"WFS",3)==0){
sprintf(type,"WFS");
isWxs=1;
}
if(strncmp(tmp->value,"WMS",3)==0){
sprintf(type,"WMS");
isWxs=1;
}
if(isWxs>0){
// WFS
fprintf(stderr,"TYPE %s \n",type);
char* pszDataDir=(char*)malloc((strlen(type)+strlen(tmpP->value)+strlen(strstr(tmp->value,":")+1)+14)*sizeof(char));
sprintf(pszDataDir,"%s/%s/%s.txt",tmpP->value,type,strstr(tmp->value,":")+1);
int dirp = open( pszDataDir , O_RDONLY );
int nn;
fprintf(stderr,"DATADIR %s %i \n",pszDataDir,dirp);
struct stat results;
if (stat(pszDataDir, &results) == 0){
char *xbuff=(char*)malloc(results.st_size+1);
char *xbuff1=(char*)malloc(results.st_size+5);
while ( ( nn=read(dirp, xbuff, results.st_size)) > 0)
{
xbuff[nn-1]='\0';
sprintf(xbuff1,"%s:%s",type,xbuff);
xbuff[nn]='\0';
pszDataSource = strdup(xbuff1);
map* tmpMap=getMapFromMaps(inputs,"dataSource","value");
free(tmpMap->value);
tmpMap->value=strdup(pszDataSource);
fprintf(stderr, "DS: (%s)\n", pszDataSource);
}
}else{
fprintf(stderr,"Unable to load %s DataStore.",type);
}
}
}
}
else{
setMapInMaps(conf,"lenv","message","Data Source not found");
return SERVICE_FAILED;
}
fprintf(stderr,"MAP : %s\n",pszDataSource);
map *tmp1=getMapFromMaps(inputs,"layer","value");
if(tmp1!=NULL)
papszLayers = CSLAddString( papszLayers, tmp1->value );
else{
if(strncmp(tmp->value,"WFS",3)!=0 && strncmp(tmp->value,"WMS",3)!=0){
fprintf(stderr,"%s\n",tmp->value);
char *tmp4=strrchr(tmp->value,'/');
fprintf(stderr,"tmp4 %s\n",tmp4);
if(tmp4!=NULL && strlen(tmp4) > 1){
char *tmp2=strrchr(tmp->value,'/')+1;
if(strstr(tmp2,".")!=NULL){
tmp2[strlen(tmp2)-strlen(strstr(tmp2,"."))]=0;
char *tmp3=strdup(tmp2);
papszLayers = CSLAddString( papszLayers, tmp3 );
fprintf(stderr,"TMP3 %s\n",tmp3);
free(tmp3);
}
}
}
}
fprintf(stderr,"DATASOURCE %s %d : %s\n",__FILE__,__LINE__,pszDataSource);
tmp1=getMapFromMaps(inputs,"getFeatures","value");
if(tmp1!=NULL){
dataSource = FALSE;
tmp1=getMapFromMaps(inputs,"page","value");
if(tmp1!=NULL)
mmPage=atoi(tmp1->value);
tmp1=getMapFromMaps(inputs,"limit","value");
if(tmp1!=NULL)
mmLimit=atoi(tmp1->value);
char* mmField=NULL;
char* mmOrder=NULL;
tmp1=getMapFromMaps(inputs,"sortname","value");
if(tmp1!=NULL)
mmField=strdup(tmp1->value);
tmp1=getMapFromMaps(inputs,"sortorder","value");
if(tmp1!=NULL)
mmOrder=strdup(tmp1->value);
if(mmField!=NULL && mmOrder!=NULL){
pszSQLStatement=(char*) malloc((strlen(mmField)+strlen(mmOrder)+128)*sizeof(char)+1);
//char tmpLayer=strstr(papszLayers[0],".")+1;
if(isPg<0)
sprintf(pszSQLStatement,"SELECT * FROM \"%s\" ORDER BY %s %s",papszLayers[0],mmField,mmOrder);
else{
// Make it case sensitive !!
sprintf(pszSQLStatement,"SELECT * FROM %s ORDER BY %s %s",papszLayers[0],mmField,mmOrder);
}
//sprintf(pszSQLStatement,"SELECT * FROM \"%s\" ORDER BY %s %s",papszLayers[0],mmField,mmOrder);
fprintf(stderr,"SQL (%s)\n",pszSQLStatement);
free(mmField);
free(mmOrder);
}
}else{
papszLayers=NULL;
}
if(dataSource)
n = xmlNewNode(NULL, BAD_CAST "datasource");
else
n = xmlNewNode(NULL, BAD_CAST "FeatureCollection");
/* -------------------------------------------------------------------- */
/* Open data source. */
/* -------------------------------------------------------------------- */
#if GDAL_VERSION_MAJOR >= 2
GDALDataset *poDS =
(GDALDataset*) GDALOpenEx( pszDataSource,
GDAL_OF_VECTOR,
NULL, NULL, NULL );
GDALDriverManager* poR=GetGDALDriverManager();
GDALDriver *poDriver = NULL;
#else
OGRDataSource *poDS = NULL;
OGRSFDriver *poDriver = NULL;
OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar();
poDS = OGRSFDriverRegistrar::Open( pszDataSource, !bReadOnly, &poDriver );
if( poDS == NULL && !bReadOnly )
{
poDS = OGRSFDriverRegistrar::Open( pszDataSource, FALSE, &poDriver );
}
#endif
/* -------------------------------------------------------------------- */
/* Report failure */
/* -------------------------------------------------------------------- */
if( poDS == NULL )
{
fprintf(stderr,"ERROR OCCURS %s\n",pszDataSource);
goto TRYGDAL;
}
if(dataSource){
xmlNodePtr n1=xmlNewNode(NULL,BAD_CAST "dataType");
#if GDAL_VERSION_MAJOR >= 2
GDALDriver*
#else
OGRSFDriver*
#endif
tmp=poDS->GetDriver();
#if GDAL_VERSION_MAJOR >= 2
xmlAddChild(n1,xmlNewText(BAD_CAST tmp->GetDescription()));
fprintf(stderr,"Driver Name: %s\n",BAD_CAST tmp->GetDescription());
#else
xmlAddChild(n1,xmlNewText(BAD_CAST tmp->GetName()));
fprintf(stderr,"Driver Name: %s\n",BAD_CAST tmp->GetName());
#endif
xmlAddChild(n,n1);
}
/* -------------------------------------------------------------------- */
/* Special case for -sql clause. No source layers required. */
/* -------------------------------------------------------------------- */
if( pszSQLStatement != NULL )
{
OGRLayer *poResultSet = NULL;
nRepeatCount = 0; // skip layer reporting.
poResultSet = poDS->ExecuteSQL( pszSQLStatement, poSpatialFilter,
pszDialect );
if( poResultSet != NULL )
{
if( pszWHERE != NULL )
poResultSet->SetAttributeFilter( pszWHERE );
//ReportOnLayer( inputs, pszDataSource, poResultSet, NULL, NULL, n, conf );
poDS->ReleaseResultSet( poResultSet );
}
free(pszSQLStatement);
}
for( int iRepeat = 0; iRepeat < nRepeatCount; iRepeat++ )
{
if ( CSLCount(papszLayers) == 0 )
{
/* -------------------------------------------------------------------- */
/* Process each data source layer. */
/* -------------------------------------------------------------------- */
for( int iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ )
{
OGRLayer *poLayer = poDS->GetLayer(iLayer);
char tmp[128];
sprintf( tmp,
_ss("Fetch layer %d!\n"),
iLayer );
fprintf(stderr,"MSG: %s",tmp);
if( poLayer == NULL )
{
char tmp[128];
sprintf( tmp,
_ss("FAILURE: Couldn't fetch advertised layer %d!\n"),
iLayer );
setMapInMaps(conf,"lenv","message",_ss(tmp));
return SERVICE_FAILED;
}
if (!bAllLayers)
{
if( iRepeat != 0 )
poLayer->ResetReading();
fprintf(stderr,"MSG: %s",tmp);
/*
#if GDAL_VERSION_MAJOR >= 2
if(strcasecmp(poDriver->GetDescription(),"ESRI Shapefile")==0)
#else
if(strcasecmp(poDriver->GetName(),"ESRI Shapefile")==0)
#endif
{
fprintf(stderr,"MSG: %s",tmp);
char tmpSQL[1024];
sprintf(tmpSQL,"CREATE SPATIAL INDEX ON %s",poLayer->GetName());
poDS->ExecuteSQL( tmpSQL, poSpatialFilter,
pszDialect );
}*/
fprintf(stderr,"MSG: %s",tmp);
ReportOnLayer4Map( pszDataSource, poLayer, pszWHERE, poSpatialFilter, myMap, conf , NULL);
fprintf(stderr,"MSG: %s",tmp);
xmlNodePtr n0=xmlNewNode(NULL,BAD_CAST "layer");
xmlNodePtr n1=xmlNewNode(NULL,BAD_CAST "name");
xmlAddChild(n1,xmlNewText(BAD_CAST poLayer->GetLayerDefn()->GetName()));
xmlAddChild(n0,n1);
xmlAddChild(n,n0);
n1=xmlNewNode(NULL,BAD_CAST "geometry");
xmlAddChild(n1,xmlNewText(BAD_CAST
OGRGeometryTypeToName(
poLayer->GetLayerDefn()->GetGeomType()
)
));
xmlAddChild(n0,n1);
}
else
{
if( iRepeat != 0 )
poLayer->ResetReading();
//ReportOnLayer( inputs, pszDataSource, poLayer, pszWHERE, poSpatialFilter, n, conf );
}
}
}
else
{
/* -------------------------------------------------------------------- */
/* Process specified data source layers. */
/* -------------------------------------------------------------------- */
char** papszIter = papszLayers;
for( ; *papszIter != NULL; papszIter++ )
{
OGRLayer *poLayer = poDS->GetLayerByName(*papszIter);
if( poLayer == NULL )
{
char tmp[128];
sprintf( tmp,
_ss("FAILURE: Couldn't fetch requested layer %s!\n"),
*papszIter );
setMapInMaps(conf,"lenv","message",tmp);
return SERVICE_FAILED;
}
if( iRepeat != 0 )
poLayer->ResetReading();
//ReportOnLayer( inputs, pszDataSource, poLayer, pszWHERE, poSpatialFilter, n, conf );
}
}
}
/* -------------------------------------------------------------------- */
/* Close down. */
/* -------------------------------------------------------------------- */
CSLDestroy( papszLayers );
CSLDestroy( papszOptions );
#if GDAL_VERSION_MAJOR < 2
OGRDataSource::DestroyDataSource( poDS );
#endif
if (poSpatialFilter)
OGRGeometryFactory::destroyGeometry( poSpatialFilter );
if(isWxs>0){
int nlayer=myMap->numlayers;
fprintf(stderr,"Layer num %d\n",nlayer);
int i=0;
for(i=0;i<nlayer;i++){
layerObj *l=GET_LAYER(myMap,i);
char* tmp=strdup(strstr(pszDataSource,":")+1);
//msConnectLayer(l,MS_WFS,tmp);
fprintf(stderr,"Layer name %s\n",l->name);
msInsertHashTable(&(l->metadata), "wfs_typename", l->name);
msInsertHashTable(&(l->metadata), "wfs_version", "1.0.0");
free(tmp);
}
GDALAllRegister();
goto CONCLUDE;
}
TRYGDAL:{
if(isPg>0){
goto CONCLUDE;
}
/**
* Raster data
*/
mapfilePath=getMapFromMaps(inputs,"dataSource","value");
fprintf(stderr,"%s \n",mapfilePath->value);
DIR *dirp = opendir(mapfilePath->value);
int res=0;
if(dirp==NULL){
if(isWxs>0){
maps* tmp=createMaps("RasterDS");
tmp->content=createMap("storage",pszDataSource);
if(res!=1){
char **papszMetadata;
char **papszMetadataInit;
GDALDatasetH hDataset;
int i,j=0;
//res=tryGdal(conf,tmp,myMap);
GDALAllRegister();
hDataset = GDALOpen( pszDataSource, GA_ReadOnly );
res=1;
papszMetadata = GDALGetMetadata( hDataset, "SUBDATASETS" );
if( CSLCount(papszMetadata) > 0 ){
for( i = 1; i<CSLCount(papszMetadata) && papszMetadata[i] != NULL; i+=2 ){
if(strstr(papszMetadata[i-1],"_NAME")!=NULL)
fprintf( stderr,"URL %s\n", papszMetadata[i-1] );
if(strstr(papszMetadata[i],"_DESC")!=NULL)
fprintf( stderr,"DESC %s\n", papszMetadata[i] );
if(msGrowMapLayers(myMap)==NULL){
return -1;
}
if(initLayer((myMap->layers[myMap->numlayers]), myMap) == -1){
return -1;
}
char *tName=(char*)malloc(15*sizeof(char));
sprintf(tName,"WMSLayer_%d",j);
layerObj* myLayer=myMap->layers[myMap->numlayers];
myLayer->name = strdup(tName);
myLayer->tileitem=NULL;
myLayer->data = NULL;
myLayer->index = myMap->numlayers;
myLayer->dump = MS_TRUE;
myLayer->status = MS_ON;
myLayer->type = MS_LAYER_RASTER;
myLayer->connection = strdup(strstr(papszMetadata[i-1],"WMS:")+4);
msConnectLayer(myLayer,MS_WMS,myLayer->connection);
char *dname=strdup(strstr(papszMetadata[i],"=")+1);
msInsertHashTable(&(myLayer->metadata), "ows_label", dname);
msInsertHashTable(&(myLayer->metadata), "ows_title", dname);
msInsertHashTable(&(myLayer->metadata), "ows_abstract", dname);
msInsertHashTable(&(myMap->web.metadata), "ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
msInsertHashTable(&(myLayer->metadata), "ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
myMap->layerorder[myMap->numlayers] = myMap->numlayers;
myMap->numlayers++;
j++;
free(tName);
xmlNodePtr n2=xmlNewNode(NULL,BAD_CAST "layer");
xmlNodePtr n1=xmlNewNode(NULL,BAD_CAST "name");
xmlAddChild(n1,xmlNewText(BAD_CAST myLayer->name));
xmlNodePtr n3=xmlNewNode(NULL,BAD_CAST "label");
xmlAddChild(n3,xmlNewText(BAD_CAST dname));
xmlNodePtr n4=xmlNewNode(NULL,BAD_CAST "preview_link");
xmlAddChild(n4,xmlNewText(BAD_CAST myLayer->connection));
xmlAddChild(n2,n1);
n1=xmlNewNode(NULL,BAD_CAST "geometry");
xmlAddChild(n1,xmlNewText(BAD_CAST "raster"));
xmlAddChild(n2,n1);
xmlAddChild(n2,n3);
xmlAddChild(n2,n4);
xmlAddChild(n,n2);
fprintf(stderr,"RASTER FOUND %s\n",tmp->name);
}
}
}
}
else{
if(getMaps(inputs,"force")==NULL){
setMapInMaps(conf,"lenv","message",_("The specified path doesn't exist."));
return 4;//errorException(m, ,"InvalidParameterValue");
}
}
}else{
struct dirent *dp;
while ((dp = readdir(dirp)) != NULL){
if(strcmp(dp->d_name,"..")!=0 && strcmp(dp->d_name,".")!=0){
fprintf(stderr,"%s : %s \n",mapfilePath->value,dp->d_name);
fflush(stderr);
char* fname=(char*)malloc((2+strlen(dp->d_name)+strlen(mapfilePath->value))*sizeof(char));
#ifndef WIN32
sprintf(fname,"%s/%s",mapfilePath->value,dp->d_name);
#else
sprintf(fname,"%s%s",mapfilePath->value,dp->d_name);
#endif
char* rname=strdup(dp->d_name);
maps* tmp=createMaps(dp->d_name);
char* sext=strstr(rname,".");
tmp->name[strlen(rname)-strlen(sext)]=0;
tmp->content=createMap("storage",fname);
// Make sure the file is not vector
int res=0;
int hasValue=0;
{
if(strstr(dp->d_name,".")!=NULL &&
(strcasecmp(strstr(dp->d_name,"."),".SHP")!=0 &&
strcasecmp(strstr(dp->d_name,"."),".DBF")!=0 &&
strcasecmp(strstr(dp->d_name,"."),".SHX")!=0 &&
strcasecmp(strstr(dp->d_name,"."),".QIX")!=0 &&
strcasecmp(strstr(dp->d_name,"."),".PRJ")!=0)){
//res=tryOgr(conf,tmp,myMap);
#if GDAL_VERSION_MAJOR >= 2
poDS =
(GDALDataset*) GDALOpenEx( fname,
GDAL_OF_VECTOR,
NULL, NULL, NULL );
#else
poDS = OGRSFDriverRegistrar::Open( fname, !bReadOnly, &poDriver );
if( poDS == NULL && !bReadOnly ){
poDS = OGRSFDriverRegistrar::Open( fname, FALSE, &poDriver );
}
#endif
if( poDS != NULL){
fprintf(stderr,"Successfully tried to open OGR DataSource %s => %d\n",tmp->content->value,res);
for( int iRepeat = 0; iRepeat < nRepeatCount; iRepeat++ )
{
if ( CSLCount(papszLayers) == 0 )
{
/* -------------------------------------------------------------------- */
/* Process each data source layer. */
/* -------------------------------------------------------------------- */
for( int iLayer = 0; iLayer < poDS->GetLayerCount(); iLayer++ )
{
OGRLayer *poLayer = poDS->GetLayer(iLayer);
if( poLayer == NULL )
{
char tmp[128];
sprintf( tmp,
_ss("FAILURE: Couldn't fetch advertised layer %d!\n"),
iLayer );
setMapInMaps(conf,"lenv","message",_ss(tmp));
return SERVICE_FAILED;
}
if (!bAllLayers)
{
if( iRepeat != 0 )
poLayer->ResetReading();
ReportOnLayer4Map( tmp->content->value, poLayer, pszWHERE, poSpatialFilter, myMap, conf, tmp );
xmlNodePtr n0=xmlNewNode(NULL,BAD_CAST "layer");
xmlNodePtr n1=xmlNewNode(NULL,BAD_CAST "name");
if(strcasecmp(poLayer->GetLayerDefn()->GetName(),"OGRGeoJSON")!=0)
xmlAddChild(n1,xmlNewText(BAD_CAST poLayer->GetLayerDefn()->GetName()));
else
xmlAddChild(n1,xmlNewText(BAD_CAST tmp->name));
xmlAddChild(n0,n1);
xmlAddChild(n,n0);
n1=xmlNewNode(NULL,BAD_CAST "geometry");
xmlAddChild(n1,xmlNewText(BAD_CAST
OGRGeometryTypeToName(
poLayer->GetLayerDefn()->GetGeomType()
)
));
xmlAddChild(n0,n1);
}
else
{
if( iRepeat != 0 )
poLayer->ResetReading();
//ReportOnLayer( inputs, pszDataSource, poLayer, pszWHERE, poSpatialFilter, n, conf );
}
}
}
else
{
/* -------------------------------------------------------------------- */
/* Process specified data source layers. */
/* -------------------------------------------------------------------- */
char** papszIter = papszLayers;
for( ; *papszIter != NULL; papszIter++ )
{
OGRLayer *poLayer = poDS->GetLayerByName(*papszIter);
if( poLayer == NULL )
{
char tmp[128];
sprintf( tmp,
_ss("FAILURE: Couldn't fetch requested layer %s!\n"),
*papszIter );
setMapInMaps(conf,"lenv","message",tmp);
return SERVICE_FAILED;
}
if( iRepeat != 0 )
poLayer->ResetReading();
//ReportOnLayer( inputs, pszDataSource, poLayer, pszWHERE, poSpatialFilter, n, conf );
}
}
}
/* -------------------------------------------------------------------- */
/* Close down. */
/* -------------------------------------------------------------------- */
CSLDestroy( papszLayers );
CSLDestroy( papszOptions );
#if GDAL_VERSION_MAJOR < 2
OGRDataSource::DestroyDataSource( poDS );
#endif
hasValue=1;
}
else{
fprintf(stderr,"Before Gdal %d \n",res);
//dumpMaps(conf);
map *storage=getMap(tmp->content,"storage");
fprintf(stderr,"Before Gdal %d \n",res);
addToMap(tmp->content,"title",dp->d_name);
addToMap(tmp->content,"abstract",dp->d_name);
if(hasValue!=1 && res!=1 && (storage!=NULL && strcasecmp(dp->d_name,"ds_ows.map")!=0 && strstr(dp->d_name,".aux.xml")==NULL)){
res=tryGdal(conf,tmp,myMap);
}
fprintf(stderr,"After Gdal %d \n",res);
}
}
}
if(res==1){
xmlNodePtr n2=xmlNewNode(NULL,BAD_CAST "layer");
xmlNodePtr n1=xmlNewNode(NULL,BAD_CAST "name");
xmlAddChild(n1,xmlNewText(BAD_CAST tmp->name));
xmlAddChild(n2,n1);
n1=xmlNewNode(NULL,BAD_CAST "geometry");
xmlAddChild(n1,xmlNewText(BAD_CAST "raster"));
xmlAddChild(n2,n1);
xmlAddChild(n,n2);
fprintf(stderr,"RASTER FOUND %s\n",tmp->name);
}
freeMaps(&tmp);
free(tmp);
}
}
}
}
CONCLUDE:
xmlChar *xmlb;
int bsize;
xmlDocSetRootElement(resDoc, n);
map* encoding=getMapFromMaps(inputs,"encoding","value");
if(encoding!=NULL){
xmlDocDumpFormatMemoryEnc(resDoc, &xmlb, &bsize, encoding->value, 1);
}
else
xmlDocDumpFormatMemory(resDoc, &xmlb, &bsize, 1);
setMapInMaps(outputs,"Result","value",(char*)xmlb);
xmlFreeDoc(resDoc);
fprintf(stderr,"MAPFILE TO SAVE !\n");
if(isPg>0 || isWxs>0){
char *tmp1=strdup(mapPath);
free(mapPath);
map* tmpMap1=getMapFromMaps(conf,"main","dataPath");
mapPath=(char*)malloc((strlen(tmpMap1->value)+strlen(tmp1)+strlen(type)+4+1)*sizeof(char));
fprintf(stderr,"MAPFILE TO SAVE %s !\n",tmp1);
if(isWxs>0)
sprintf(mapPath,"%s/%s/%s",tmpMap1->value,type,strstr(tmp1,":")+1);
else
sprintf(mapPath,"%s/%s/%s",tmpMap1->value,type,tmp1);
fprintf(stderr,"MAPFILE TO SAVE %s\n",mapPath);
free(tmp1);
}
struct stat mstat;
int s=stat(mapPath,&mstat);
if(s<0){
myMap->mappath=zStrdup(mapPath);
fprintf(stderr,"END! %s %d \n",__FILE__,__LINE__);
msSaveMap(myMap,mapPath);
fprintf(stderr,"END! %s %d \n",__FILE__,__LINE__);
//msFreeMap(myMap);
}
fprintf(stderr,"END! %s %d \n",__FILE__,__LINE__);
//OGRCleanupAll();
fprintf(stderr,"END! %s %d \n",__FILE__,__LINE__);
return SERVICE_SUCCEEDED;
}
/************************************************************************/
/* ReportOnLayer() */
/************************************************************************/
void ReportOnLayer( mapObj* myMap, maps* inputs, char * pszDataSource, OGRLayer * poLayer, const char *pszWHERE,
OGRGeometry *poSpatialFilter, xmlNodePtr n, maps* conf)
{
OGRFeatureDefn *poDefn = poLayer->GetLayerDefn();
/* -------------------------------------------------------------------- */
/* Report various overall information. */
/* -------------------------------------------------------------------- */
char* layerName=NULL;
if(dataSource){
xmlNodePtr n1=xmlNewNode(NULL,BAD_CAST "name");
if(strcasecmp(poDefn->GetName(),"OGRGeoJSON")!=0){
layerName=strdup(poDefn->GetName());
}
else{
map* tmp=getMapFromMaps(inputs,"layer","value");
layerName=strdup(tmp->value);
}
xmlAddChild(n1,xmlNewText(BAD_CAST layerName));
xmlAddChild(n,n1);
n1=xmlNewNode(NULL,BAD_CAST "geometry");
xmlAddChild(n1,xmlNewText(BAD_CAST
OGRGeometryTypeToName( poDefn->GetGeomType() )
));
xmlAddChild(n,n1);
int i=0;
if(myMap!=NULL)
for(i=0;i<myMap->numlayers;i++){
//fprintf(stderr,"layer %s %s => %s\n",poLayer->GetName(),myMap->layers[i]->name,myMap->layers[i]->encoding);
char* ows_encoding=myMap->layers[i]->encoding;//msLookupHashTable(&(myMap->layers[i]->metadata), "ows_encoding");
//fprintf(stderr,"layer %s %s => %s\n",poLayer->GetName(),myMap->layers[i]->name,ows_encoding);
if(strcmp(myMap->layers[i]->name,poLayer->GetName())==0 ||
strcmp(myMap->layers[i]->name,layerName)==0){
n1=xmlNewNode(NULL,BAD_CAST "encoding");
ows_encoding=myMap->layers[i]->encoding;
//ows_encoding=msLookupHashTable(&(myMap->layers[i]->metadata), "ows_encoding");
//fprintf(stderr,"layer %s => %s\n",myMap->layers[i]->name,ows_encoding);
if(ows_encoding!=NULL)
xmlAddChild(n1,xmlNewText(BAD_CAST ows_encoding));
else{
map* encoding=getMapFromMaps(conf,"main","encoding");
xmlAddChild(n1,xmlNewText(BAD_CAST encoding->value));
}
xmlAddChild(n,n1);
}
}
n1=xmlNewNode(NULL,BAD_CAST "featureCount");
char tmp[128];
sprintf(tmp,"%i",poLayer->GetFeatureCount());
xmlAddChild(n1,xmlNewText(BAD_CAST tmp));
xmlAddChild(n,n1);
OGREnvelope oExt;
xmlNodePtr n2;
//fprintf(stderr,"\n*** %s ***\n",pszDataSource);
char *pszWKT;
if( poLayer->GetSpatialRef() == NULL )
pszWKT = CPLStrdup( "(unknown)" );
else
{
OGRSpatialReference* tmpSRS=poLayer->GetSpatialRef();
tmpSRS->AutoIdentifyEPSG();
const char* authNameSRS=tmpSRS->GetAuthorityName(NULL);
const char* authIdSRS=tmpSRS->GetAuthorityCode(NULL);
if(authNameSRS!=NULL && authIdSRS!=NULL){
pszWKT=(char*)malloc((strlen(authNameSRS)+strlen(authIdSRS)+2)*sizeof(char));
sprintf(pszWKT,"%s:%s",authNameSRS,authIdSRS);
OGREnvelope ogExt;
if (OGR_L_GetExtent(poLayer,&ogExt, TRUE) == OGRERR_NONE){
OGRSpatialReference oSourceSRS, oTargetSRS;
OGRCoordinateTransformation *poCT;
double xmin, ymin,xmax, ymax;
oSourceSRS.importFromEPSG(atoi(authIdSRS));
oTargetSRS.importFromEPSG(4326);
poCT = OGRCreateCoordinateTransformation( &oSourceSRS,&oTargetSRS );
xmin = ogExt.MinX ;
ymin = ogExt.MinY;
if( poCT == NULL || !poCT->Transform( 1, &xmin, &ymin ) )
fprintf(stderr, "Transformation failed x/y.\n" );
else{
xmin = ogExt.MinY ;
ymin = ogExt.MinX;
if( poCT == NULL || !poCT->Transform( 1, &ymin, &xmin ) )
fprintf(stderr, "Transformation failed y/x.\n" );
else
fprintf( stderr, "\n\n(%f,%f) -> (%f,%f)\n\n",
ogExt.MinX,
ogExt.MinY,
xmin, ymin );
}
xmax = ogExt.MaxX ;
ymax = ogExt.MaxY;
if( poCT == NULL || !poCT->Transform( 1, &xmax, &ymax ) )
fprintf(stderr, "Transformation failed x/y.\n" );
else{
xmax = ogExt.MaxY ;
ymax = ogExt.MaxX;
if( poCT == NULL || !poCT->Transform( 1, &xmax, &ymax ) )
fprintf(stderr, "Transformation failed y/x.\n" );
else
fprintf( stderr, "\n\n(%f,%f) -> (%f,%f)\n\n",
ogExt.MaxX,
ogExt.MaxY,
xmax, ymax );
}
map* tmpMapPath=getMapFromMaps(conf,"main","mapserverAddress");
char* mapPath=(char*)malloc((strlen(tmpMapPath->value)+strlen(pszDataSource)+11)*sizeof(char));
sprintf(mapPath,"%sds_ows.map",pszDataSource);
fprintf(stderr,"%s?map=%s&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=%f,%f,%f,%f&SRS=EPSG:4326&WIDTH=1024&HEIGHT=1024&LAYERS=%s\n",tmpMapPath->value,mapPath,xmin,ymin,xmax,ymax,layerName);
int maxWidth=512;
int maxHeight=359;
double deltaX=xmax-xmin;
double deltaY=ymax-ymin;
double qWidth=maxWidth/deltaX;
double qHeight=maxHeight/deltaY;
double qValue=qWidth;
double width=qValue*deltaX;
double height=(deltaY*qValue);
if(qWidth>qHeight){
qValue=qHeight;
width=qWidth*deltaX;;
height=qValue*deltaY;
}
#ifdef DEBUGMS
fprintf(stderr,"deltaX : %.15f \ndeltaY : %.15f\n",deltaX,deltaY);
fprintf(stderr,"qWidth : %.15f \nqHeight : %.15f\n",qWidth,qHeight);
fprintf(stderr,"qWidth : %.15f \nqHeight : %.15f\n",width,height);
#endif
char tmpStr[2048];
map* tmpMap=getMapFromMaps(conf,"main","mapfile");
/*if(pszWKT!=NULL && strncasecmp(pszWKT,"EPSG:4326",9)!=0)
else
sprintf(tmpStr,"%s?map=%s&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=%f,%f,%f,%f&SRS=EPSG:4326&WIDTH=%f&HEIGHT=%f&LAYERS=%s\n",tmpMapPath->value,tmpMap->value,xmin,ymin,xmax,ymax,width,height,poDefn->GetName());
*/
sprintf(tmpStr,"%s?map=%s&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=%f,%f,%f,%f&SRS=EPSG:4326&WIDTH=%f&HEIGHT=%f&LAYERS=%s\n",tmpMapPath->value,tmpMap->value,ymin,xmin,ymax,xmax,width,height,layerName);
fprintf(stderr,"SRS : %s\n",tmpStr);
n2=xmlNewNode(NULL,BAD_CAST "previewLink");
xmlAddChild(n2,xmlNewText(BAD_CAST tmpStr));
xmlAddChild(n,n2);
}
}else{
tmpSRS->exportToPrettyWkt( &pszWKT );
OGREnvelope ogExt;
if (OGR_L_GetExtent(poLayer,&ogExt, TRUE) == OGRERR_NONE){
OGRSpatialReference oSourceSRS, oTargetSRS;
OGRCoordinateTransformation *poCT;
double xmin, ymin,xmax, ymax;
OSRImportFromWkt( &oSourceSRS, &pszWKT );
oTargetSRS.importFromEPSG(4326);
poCT = OGRCreateCoordinateTransformation( &oSourceSRS,&oTargetSRS );
xmin = ogExt.MinX ;
ymin = ogExt.MinY;
if( poCT == NULL || !poCT->Transform( 1, &xmin, &ymin ) )
fprintf(stderr, "Transformation failed.\n" );
else
fprintf( stderr, "\n\n(%f,%f) -> (%f,%f)\n\n",
ogExt.MinX,
ogExt.MinY,
xmin, ymin );
xmax = ogExt.MaxX ;
ymax = ogExt.MaxY;
if( poCT == NULL || !poCT->Transform( 1, &xmax, &ymax ) )
fprintf(stderr, "Transformation failed.\n" );
else
fprintf( stderr, "\n\n(%f,%f) -> (%f,%f)\n\n",
ogExt.MaxX,
ogExt.MaxY,
xmax, ymax );
char* mapPath=(char*)malloc((strlen(pszDataSource)+11)*sizeof(char));
sprintf(mapPath,"%sds_ows.map",pszDataSource);
int maxWidth=512;
int maxHeight=359;
double deltaX=xmax-xmin;
double deltaY=ymax-ymin;
double qWidth=maxWidth/deltaX;
double qHeight=maxHeight/deltaY;
double qValue=qWidth;
double width=qValue*deltaX;
double height=(deltaY*qValue);
if(qWidth<qHeight){
qValue=qHeight;
width=qValue*deltaX;;
height=qValue*deltaY;
}
#ifdef DEBUGMS
fprintf(stderr,"deltaX : %.15f \ndeltaY : %.15f\n",deltaX,deltaY);
fprintf(stderr,"qWidth : %.15f \nqHeight : %.15f\n",qWidth,qHeight);
fprintf(stderr,"qWidth : %.15f \nqHeight : %.15f\n",width,height);
#endif
char tmpStr[2048];
map* tmpMapPath=getMapFromMaps(conf,"main","mapserverAddress");
map* tmpMap=getMapFromMaps(conf,"main","mapfile");
/*if(pszWKT!=NULL && strncasecmp(pszWKT,"EPSG:4326",9)==0)*/
sprintf(tmpStr,"%s?map=%s&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=%f,%f,%f,%f&SRS=EPSG:4326&WIDTH=%f&HEIGHT=%f&LAYERS=%s\n",tmpMapPath->value,tmpMap->value,xmin,ymin,xmax,ymax,width,height,layerName);
/*else
sprintf(tmpStr,"%s?map=%s&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=%f,%f,%f,%f&SRS=EPSG:4326&WIDTH=%f&HEIGHT=%f&LAYERS=%s\n",tmpMapPath->value,tmpMap->value,ymin,xmin,ymax,xmax,width,height,poDefn->GetName());*/
n2=xmlNewNode(NULL,BAD_CAST "previewLink");
xmlAddChild(n2,xmlNewText(BAD_CAST tmpStr));
xmlAddChild(n,n2);
}
}
}
fprintf(stderr,"pszWKT %s\n",pszWKT);
n1=xmlNewNode(NULL,BAD_CAST "srs");
xmlAddChild(n1,xmlNewText(BAD_CAST pszWKT));
xmlAddChild(n,n1);
fprintf(stderr,"pszWKT %s\n",pszWKT);
if (poLayer->GetExtent(&oExt, TRUE) == OGRERR_NONE)
{
char tmp[128];
if(pszWKT!=NULL && strncasecmp(pszWKT,"EPSG:4326",9)!=0)
sprintf(tmp,"%f, %f,%f, %f",
oExt.MinY, oExt.MinX, oExt.MaxY, oExt.MaxX);
else
sprintf(tmp,"%f, %f,%f, %f",
oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
n1=xmlNewNode(NULL,BAD_CAST "extent");
xmlAddChild(n1,xmlNewText(BAD_CAST tmp));
xmlAddChild(n,n1);
char *tmpStr;
map* tmpMapPath=getMapFromMaps(conf,"main","mapserverAddress");
char* mapPath=(char*)malloc((strlen(tmpMapPath->value)+strlen(pszDataSource)+11)*sizeof(char));
sprintf(mapPath,"%sds_ows.map",pszDataSource);
int maxWidth=512;
int maxHeight=359;
double deltaX=oExt.MaxX-oExt.MinX;
double deltaY=oExt.MaxY-oExt.MinY;
double qWidth=maxWidth/deltaX;
double qHeight=maxHeight/deltaY;
double qValue=qWidth;
double width=qValue*deltaX;
double height=(deltaY*qValue);
if(qWidth<qHeight){
qValue=qHeight;
width=qValue*deltaX;;
height=qValue*deltaY;
}
map* tmpMap=getMapFromMaps(conf,"main","mapfile");
tmpStr=(char*)malloc((strlen(tmpMapPath->value)+strlen(tmpMap->value)+strlen(layerName)+2048)*sizeof(char));
/*if(pszWKT!=NULL && strncasecmp(pszWKT,"EPSG:4326",9)==0)
sprintf(tmpStr,"%s?map=%s&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=%f,%f,%f,%f&SRS=EPSG:4326&WIDTH=%f&HEIGHT=%f&LAYERS=%s\n",tmpMapPath->value,tmpMap->value,oExt.MinY,oExt.MinX,oExt.MaxY,oExt.MaxX,width,height,poDefn->GetName());
else*/
sprintf(tmpStr,"%s?map=%s&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=%f,%f,%f,%f&SRS=EPSG:4326&WIDTH=%f&HEIGHT=%f&LAYERS=%s",tmpMapPath->value,tmpMap->value,oExt.MinX,oExt.MinY,oExt.MaxX,oExt.MaxY,width,height,layerName);
fprintf(stderr,"previewLink *%s* %d\n",tmpStr,(pszWKT!=NULL && strncasecmp(pszWKT,"EPSG:4326",9)!=0));
n2=xmlNewNode(NULL,BAD_CAST "previewLink");
xmlAddChild(n2,xmlNewText(BAD_CAST tmpStr));
xmlAddChild(n,n2);
free(tmpStr);
}
n1=xmlNewNode(NULL,BAD_CAST "fields");
for( int iAttr = 0; iAttr < poDefn->GetFieldCount(); iAttr++ )
{
OGRFieldDefn *poField = poDefn->GetFieldDefn( iAttr );
xmlNodePtr n2=xmlNewNode(NULL,BAD_CAST "field");
xmlNodePtr n3=xmlNewNode(NULL,BAD_CAST "id");
xmlAddChild(n3,xmlNewText(BAD_CAST poField->GetNameRef()));
xmlAddChild(n2,n3);
n3=xmlNewNode(NULL,BAD_CAST "type");
char tmp[128];
sprintf( tmp, "%s (%d.%d)",
poField->GetFieldTypeName( poField->GetType() ),
poField->GetWidth(),
poField->GetPrecision() );
xmlAddChild(n3,xmlNewText(BAD_CAST tmp));
xmlAddChild(n2,n3);
xmlAddChild(n1,n2);
}
xmlAddChild(n,n1);
}
else{
const char* pszDisplayFields =
CSLFetchNameValue(papszOptions, "DISPLAY_FIELDS");
OGRFeature *poFeature = NULL;
int nbFeature=0;
/*int i=0;
char* ows_encoding=myMap->layers[i]->encoding;//msLookupHashTable(&(myMap->layers[i]->metadata), "ows_encoding");*/
map* encoding=getMapFromMaps(inputs,"encoding","value");
/*if(encoding!=NULL){
for(i=0;i<myMap->numlayers;i++){
fprintf(stderr,"layer %s => %s\n",myMap->layers[i]->name,ows_encoding);
if(strcmp(myMap->layers[i]->name,poLayer->GetName())==0){
myMap->layers[i]->encoding=strdup(encoding->value);
//msInsertHashTable(&(myMap->layers[i]->metadata),"ows_encoding",encoding->value);
ows_encoding=myMap->layers[i]->encoding;//msLookupHashTable(&(myMap->layers[i]->metadata), "ows_encoding");*/
if(myMap!=NULL){
int i=0;
char* ows_encoding=myMap->layers[i]->encoding;//msLookupHashTable(&(myMap->layers[i]->metadata), "ows_encoding");
if(encoding!=NULL){
for(i=0;i<myMap->numlayers;i++){
fprintf(stderr,"layer %s => %s\n",myMap->layers[i]->name,ows_encoding);
if(strcmp(myMap->layers[i]->name,poLayer->GetName())==0){
myMap->layers[i]->encoding=strdup(encoding->value);
//msInsertHashTable(&(myMap->layers[i]->metadata),"ows_encoding",encoding->value);
ows_encoding=myMap->layers[i]->encoding;//msLookupHashTable(&(myMap->layers[i]->metadata), "ows_encoding");
fprintf(stderr,"layer %s => %s\n",myMap->layers[i]->name,ows_encoding);
}
}
}
}
while((poFeature = poLayer->GetNextFeature()) != NULL ){
if( nbFeature >= ( ( mmPage * mmLimit ) - mmLimit ) &&
nbFeature < ( mmPage * mmLimit ) ){
xmlNodePtr n1=xmlNewNode(NULL,BAD_CAST "featureMember");
for( int iField = 0; iField < OGR_F_GetFieldCount(poFeature); iField++ )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn(iField);
xmlNodePtr n2=xmlNewNode(NULL,BAD_CAST poFDefn->GetNameRef());
if( OGR_F_IsFieldSet( poFeature, iField ) ){
const char* cf=OGR_F_GetFieldAsString( poFeature, iField );
if(encoding==NULL)
encoding=getMapFromMaps(conf,"main","encoding");
if(encoding!=NULL && strncasecmp(encoding->value,"undefined",9)!=0){
char* tmp=msGetEncodedString(cf,encoding->value);
xmlAddChild(n2,xmlNewText(BAD_CAST tmp));
}
else
xmlAddChild(n2,xmlNewText(BAD_CAST cf));
}
else
xmlAddChild(n2,xmlNewText(BAD_CAST "(null)" ));
xmlAddChild(n1,n2);
}
xmlAddChild(n,n1);
}
else{
if( nbFeature < ( ( mmPage * mmLimit ) - mmLimit ) )
;
else
break;
}
nbFeature++;
}
}
}
/************************************************************************/
/* ReportOnLayer4Map() */
/************************************************************************/
void ReportOnLayer4Map( char* pszDataSource,
OGRLayer * poLayer, const char *pszWHERE,
OGRGeometry *poSpatialFilter, mapObj* m, maps* conf,
maps* lay)
{
OGRFeatureDefn *poDefn = poLayer->GetLayerDefn();
/* -------------------------------------------------------------------- */
/* Report various overall information. */
/* -------------------------------------------------------------------- */
if(dataSource){
/**
* Add a new layer set name, data
*/
if(msGrowMapLayers(m)==NULL){
fprintf(stderr,"Unable to add layer");
return;
}
if(initLayer((m->layers[m->numlayers]), m) == -1){
fprintf(stderr,"Unable to init layer");
return;
}
layerObj* myLayer=m->layers[m->numlayers];
//dumpMaps(output);
if(strcasecmp(poDefn->GetName(),"OGRGeoJSON")!=0)
myLayer->name = strdup(poDefn->GetName());
else
myLayer->name = strdup(lay->name);
fprintf(stderr,"LAYER NAME: %s\n",myLayer->name);
if(strncasecmp(myLayer->name,"tile_",4)==0){
myLayer->tileindex = (char*)malloc((strlen(pszDataSource)+strlen(myLayer->name)+5+1)*sizeof(char));
sprintf(myLayer->tileindex,"%s/%s.shp",pszDataSource,myLayer->name);
myLayer->tileitem=strdup("Location");
myLayer->type = MS_LAYER_RASTER;
msLayerAddProcessing(myLayer,"RESAMPLE=AVERAGE");
}else{
if(strncasecmp(myLayer->name,"vtile_",4)==0){
myLayer->tileindex = (char*)malloc((strlen(pszDataSource)+strlen(myLayer->name)+5+1)*sizeof(char));
sprintf(myLayer->tileindex,"%s/%s.shp",pszDataSource,myLayer->name);
myLayer->tileitem=strdup("Location");
OGRLayer * poiLayer;
myLayer->type = MS_LAYER_POLYGON;
//msLayerAddProcessing(myLayer,"RESAMPLE=AVERAGE");
}else{
myLayer->tileitem=NULL;
myLayer->data = strdup(poDefn->GetName());
myLayer->index = m->numlayers;
myLayer->dump = MS_TRUE;
myLayer->status = MS_ON;
if(strncasecmp(pszDataSource,"WFS",3)==0){
char *tmp=strdup(strstr(pszDataSource,":")+1);
myLayer->connection = strdup(tmp);
msConnectLayer(myLayer,MS_WFS,tmp);
fprintf(stderr,"WFS %s\n",tmp);
free(tmp);
}
else{
myLayer->connection = strdup(pszDataSource);
msConnectLayer(myLayer,MS_OGR,pszDataSource);
}
if(strncasecmp(pszDataSource,"PG:",3)==0 ||
strncasecmp(pszDataSource,"MYSQL:",6)==0 ||
strncasecmp(pszDataSource,"OCI:",4)==0 )
msLayerAddProcessing(myLayer,"CLOSE_CONNECTION=DEFER");
/**
* Detect the Geometry Type or use Polygon
*/
if(OGR_L_GetGeomType(poLayer) != wkbUnknown){
switch(OGR_L_GetGeomType(poLayer)){
case wkbPoint:
case wkbMultiPoint:
case wkbPoint25D:
case wkbMultiPoint25D:
#ifdef DEBUGMS
fprintf(stderr,"%s %s POINT DataSource Layer \n",pszDataSource,myLayer->data);
#endif
myLayer->type = MS_LAYER_POINT;
break;
case wkbLineString :
case wkbMultiLineString :
case wkbLineString25D:
case wkbMultiLineString25D:
#ifdef DEBUGMS
fprintf(stderr,"%s %s LINE DataSource Layer \n",pszDataSource,myLayer->data);
#endif
myLayer->type = MS_LAYER_LINE;
break;
case wkbPolygon:
case wkbMultiPolygon:
case wkbPolygon25D:
case wkbMultiPolygon25D:
#ifdef DEBUGMS
fprintf(stderr,"%s %s POLYGON DataSource Layer \n",pszDataSource,myLayer->data);
#endif
myLayer->type = MS_LAYER_POLYGON;
break;
default:
myLayer->type = MS_LAYER_POLYGON;
break;
}
}else
myLayer->type = MS_LAYER_POLYGON;
}
}
/**
* Detect spatial reference or use WGS84
**/
OGRSpatialReferenceH srs=OGR_L_GetSpatialRef(poLayer);
if(srs!=NULL){
char *wkt=NULL;
OSRExportToWkt(srs,&wkt);
setSrsInformations(NULL,m,myLayer,wkt);
//msLoadProjectionString(&(myLayer->projection),wkt);
OGREnvelope ogExt;
if (OGR_L_GetExtent(poLayer,&ogExt, TRUE) == OGRERR_NONE){
OGRSpatialReference oSourceSRS, oTargetSRS;
OGRCoordinateTransformation *poCT;
double xmin, ymin,xmax, ymax;
OSRImportFromProj4( &oSourceSRS, wkt );
oTargetSRS.importFromEPSG(4326);
poCT = OGRCreateCoordinateTransformation( &oSourceSRS,&oTargetSRS );
xmin = ogExt.MinX ;
ymin = ogExt.MinY;
if( poCT == NULL || !poCT->Transform( 1, &xmin, &ymin ) )
fprintf(stderr, "Transformation failed.\n" );
else{
xmin = ogExt.MinY;
ymin = ogExt.MinX;
if( poCT == NULL || !poCT->Transform( 1, &xmin, &ymin ) )
fprintf(stderr, "Transformation failed.\n" );
else
fprintf( stderr, "\n\n(%f,%f) -> (%f,%f)\n\n",
ogExt.MinX,
ogExt.MinY,
xmin, ymin );
}
xmax = ogExt.MaxX ;
ymax = ogExt.MaxY;
if( poCT == NULL || !poCT->Transform( 1, &xmax, &ymax ) )
fprintf(stderr, "Transformation failed.\n" );
else{
xmax = ogExt.MaxY;
ymax = ogExt.MaxX;
if( poCT == NULL || !poCT->Transform( 1, &xmax, &ymax ) )
fprintf(stderr, "Transformation failed.\n" );
else
fprintf( stderr, "\n\n(%f,%f) -> (%f,%f)\n\n",
ogExt.MaxX,
ogExt.MaxY,
xmax, ymax );
}
map* tmpMapPath=getMapFromMaps(conf,"main","mapserverAddress");
char* mapPath=(char*)malloc((strlen(tmpMapPath->value)+strlen(pszDataSource)+11)*sizeof(char));
sprintf(mapPath,"%sds_ows.map",pszDataSource);
//fprintf(stderr,"%s?map=%s&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=%f,%f,%f,%f&SRS=EPSG:4326&WIDTH=1024&HEIGHT=1024&LAYERS=%s\n",tmpMapPath->value,mapPath,xmin,ymin,xmax,ymax,myLayer->data);
}
}
else{
msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
msLoadProjectionStringEPSG(&myLayer->projection,"EPSG:4326");
msInsertHashTable(&(m->web.metadata), "ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
msInsertHashTable(&(myLayer->metadata), "ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
}
msInsertHashTable(&(m->web.metadata), "ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
msInsertHashTable(&(myLayer->metadata), "ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
OGREnvelope ogExt;
if (OGR_L_GetExtent(poLayer,&ogExt, TRUE) == OGRERR_NONE){
if(strncasecmp(pszDataSource,"WFS",3)==0){
fprintf(stderr,"WFS FOUND !!\n");
msLayerSetExtent(myLayer,ogExt.MinY,ogExt.MinX,ogExt.MaxY,ogExt.MaxX);
}
else
msLayerSetExtent(myLayer,ogExt.MinX, ogExt.MinY, ogExt.MaxX, ogExt.MaxY);
//eErr = poDstFeature->GetGeometryRef()->transform( poCT );
}
if(strncasecmp(myLayer->name,"tile_",4)!=0){
/**
* Detect the FID column or use the first attribute field as FID
*/
//char *fid=NULL;
/**
* Should be better to set gml_include_items list and gml_[attr]_type
*/
msInsertHashTable(&(myLayer->metadata), "gml_include_items", "all");
msInsertHashTable(&(myLayer->metadata), "gml_types", "auto");
const char *fid=OGR_L_GetFIDColumn(poLayer);
fprintf(stderr,"FID COLUMN %s ! \n",fid);
int hasFid=-1;
if(strlen(fid)==0){
OGRFeatureDefnH def=OGR_L_GetLayerDefn(poLayer);
int fIndex=0;
for(fIndex=0;fIndex<OGR_FD_GetFieldCount(def);fIndex++){
OGRFieldDefnH fdef=OGR_FD_GetFieldDefn(def,fIndex);
if(hasFid<0)
fid=OGR_Fld_GetNameRef(fdef);
fprintf(stderr,"FID COLUMN %s ! \n",fid);
if(strcasestr(fid,"id")!=NULL){
hasFid=1;
break;
}
/*char tmpTypes[128];
sprintf(tmpTypes"gml_%s_types",);
msInsertHashTable(&(myLayer->metadata), tmpType, "auto");*/
//break;
}
}
msInsertHashTable(&(myLayer->metadata), "gml_featureid", fid);
msInsertHashTable(&(myLayer->metadata), "ows_featureid", fid);
msInsertHashTable(&(myLayer->metadata), "ows_name", myLayer->name);
msInsertHashTable(&(myLayer->metadata), "ows_title", myLayer->name);
classObj* myClass;
if((myClass=msGrowLayerClasses(myLayer)) == NULL)
return;
///myLayerclass;
//classObj* myClass=myLayer->class;
if(initClass(myClass) == -1)
return;
//myClass->type = myLayer->type;
if(msGrowClassStyles(myClass) == NULL)
return ;
if(initStyle(myClass->styles[myClass->numstyles]) == -1)
return;
/**
* Set style
*/
myClass->styles[myClass->numstyles]->color.red=125;
myClass->styles[myClass->numstyles]->color.green=125;
myClass->styles[myClass->numstyles]->color.blue=255;
myClass->styles[myClass->numstyles]->outlinecolor.red=80;
myClass->styles[myClass->numstyles]->outlinecolor.green=80;
myClass->styles[myClass->numstyles]->outlinecolor.blue=80;
/**
* Set specific style depending on type
*/
if(myLayer->type == MS_LAYER_POLYGON)
myClass->styles[myClass->numstyles]->width=3;
if(myLayer->type == MS_LAYER_LINE){
myClass->styles[myClass->numstyles]->width=3;
myClass->styles[myClass->numstyles]->outlinewidth=1.5;
}
if(myLayer->type == MS_LAYER_POINT){
myClass->styles[myClass->numstyles]->symbol=1;
myClass->styles[myClass->numstyles]->size=15;
}
myClass->numstyles++;
myLayer->numclasses++;
}
m->layerorder[m->numlayers] = m->numlayers;
m->numlayers++;
xmlNodePtr n1=xmlNewNode(NULL,BAD_CAST "name");
xmlAddChild(n1,xmlNewText(BAD_CAST poDefn->GetName()));
//xmlAddChild(n,n1);
n1=xmlNewNode(NULL,BAD_CAST "geometry");
xmlAddChild(n1,xmlNewText(BAD_CAST
OGRGeometryTypeToName( poDefn->GetGeomType() )
));
//xmlAddChild(n,n1);
n1=xmlNewNode(NULL,BAD_CAST "featureCount");
char tmp[128];
sprintf(tmp,"%i",poLayer->GetFeatureCount());
xmlAddChild(n1,xmlNewText(BAD_CAST tmp));
//xmlAddChild(n,n1);
OGREnvelope oExt;
if (poLayer->GetExtent(&oExt, TRUE) == OGRERR_NONE)
{
char tmp[128];
sprintf(tmp,"%f, %f,%f, %f",
oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
n1=xmlNewNode(NULL,BAD_CAST "extent");
xmlAddChild(n1,xmlNewText(BAD_CAST tmp));
//xmlAddChild(n,n1);
}
char *pszWKT;
if( poLayer->GetSpatialRef() == NULL )
pszWKT = CPLStrdup( "(unknown)" );
else
{
OGRSpatialReference* tmpSRS=poLayer->GetSpatialRef();
tmpSRS->AutoIdentifyEPSG();
const char* authNameSRS=tmpSRS->GetAuthorityName(NULL);
const char* authIdSRS=tmpSRS->GetAuthorityCode(NULL);
if(authNameSRS!=NULL && authIdSRS!=NULL){
pszWKT=(char*)malloc((strlen(authNameSRS)+strlen(authIdSRS)+2)*sizeof(char));
sprintf(pszWKT,"%s:%s",authNameSRS,authIdSRS);
}else
tmpSRS->exportToPrettyWkt( &pszWKT );
}
n1=xmlNewNode(NULL,BAD_CAST "srs");
xmlAddChild(n1,xmlNewText(BAD_CAST pszWKT));
//xmlAddChild(n,n1);
n1=xmlNewNode(NULL,BAD_CAST "fields");
for( int iAttr = 0; iAttr < poDefn->GetFieldCount(); iAttr++ )
{
OGRFieldDefn *poField = poDefn->GetFieldDefn( iAttr );
xmlNodePtr n2=xmlNewNode(NULL,BAD_CAST "field");
xmlNodePtr n3=xmlNewNode(NULL,BAD_CAST "id");
xmlAddChild(n3,xmlNewText(BAD_CAST poField->GetNameRef()));
xmlAddChild(n2,n3);
n3=xmlNewNode(NULL,BAD_CAST "type");
char tmp[128];
sprintf( tmp, "%s (%d.%d)",
poField->GetFieldTypeName( poField->GetType() ),
poField->GetWidth(),
poField->GetPrecision() );
xmlAddChild(n3,xmlNewText(BAD_CAST tmp));
xmlAddChild(n2,n3);
xmlAddChild(n1,n2);
}
//xmlAddChild(n,n1);
}
else{
const char* pszDisplayFields =
CSLFetchNameValue(papszOptions, "DISPLAY_FIELDS");
OGRFeature *poFeature = NULL;
int nbFeature=0;
while((poFeature = poLayer->GetNextFeature()) != NULL ){
if( nbFeature >= ( ( mmPage * mmLimit ) - mmLimit ) &&
nbFeature < ( mmPage * mmLimit ) ){
xmlNodePtr n1=xmlNewNode(NULL,BAD_CAST "featureMember");
for( int iField = 0; iField < OGR_F_GetFieldCount(poFeature); iField++ )
{
OGRFieldDefn *poFDefn = poDefn->GetFieldDefn(iField);
xmlNodePtr n2=xmlNewNode(NULL,BAD_CAST poFDefn->GetNameRef());
if( OGR_F_IsFieldSet( poFeature, iField ) )
xmlAddChild(n2,xmlNewText(BAD_CAST OGR_F_GetFieldAsString( poFeature, iField )));
else
xmlAddChild(n2,xmlNewText(BAD_CAST "(null)" ));
xmlAddChild(n1,n2);
}
//xmlAddChild(n,n1);
}
else{
if( nbFeature < ( ( mmPage * mmLimit ) - mmLimit ) )
;
else
break;
}
nbFeature++;
}
}
fprintf(stderr,"exit %s DataSource Layer \n",pszDataSource);
}
/************************************************************************/
/* gdalinfo() */
/************************************************************************/
int gdalinfo( maps* conf,maps* outputs, char *pszFilename )
{
GDALDatasetH hDataset;
GDALRasterBandH hBand;
int i, iBand;
double adfGeoTransform[6];
GDALDriverH hDriver;
char **papszMetadata;
int bComputeMinMax = TRUE, bSample = FALSE;
int bShowGCPs = TRUE, bShowMetadata = TRUE, bShowRAT=TRUE;
int bStats = FALSE, bApproxStats = TRUE, iMDD;
int bShowColorTable = TRUE, bComputeChecksum = FALSE;
int bReportHistograms = TRUE;
int nSubdataset = -1;
char **papszExtraMDDomains = NULL, **papszFileList;
const char *pszProjection = NULL;
OGRCoordinateTransformationH hTransform = NULL;
int bShowFileList = TRUE;
int hasMin = FALSE, hasMax = FALSE;
xmlDocPtr resDoc = xmlNewDoc(BAD_CAST "1.0");
xmlNodePtr n = xmlNewNode(NULL, BAD_CAST "datasource");
/* Check that we are running against at least GDAL 1.5 */
/* Note to developers : if we use newer API, please change the requirement */
if (atoi(GDALVersionInfo("VERSION_NUM")) < 1500)
{
char message[1024];
sprintf(message,"GDAL >= 1.5.0 is required but you are using "
"GDAL %s\n", GDAL_RELEASE_NAME);
return 4;
}
GDALAllRegister();
/* -------------------------------------------------------------------- */
/* Parse arguments. */
/* -------------------------------------------------------------------- *
for( i = 1; i < argc; i++ )
{
if( EQUAL(argv[i], "--utility_version") )
{
printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
return 0;
}
else if( EQUAL(argv[i], "-mm") )
bComputeMinMax = TRUE;
else if( EQUAL(argv[i], "-hist") )
bReportHistograms = TRUE;
else if( EQUAL(argv[i], "-stats") )
{
bStats = TRUE;
bApproxStats = FALSE;
}
else if( EQUAL(argv[i], "-approx_stats") )
{
bStats = TRUE;
bApproxStats = TRUE;
}
else if( EQUAL(argv[i], "-sample") )
bSample = TRUE;
else if( EQUAL(argv[i], "-checksum") )
bComputeChecksum = TRUE;
else if( EQUAL(argv[i], "-nogcp") )
bShowGCPs = FALSE;
else if( EQUAL(argv[i], "-nomd") )
bShowMetadata = FALSE;
else if( EQUAL(argv[i], "-norat") )
bShowRAT = FALSE;
else if( EQUAL(argv[i], "-noct") )
bShowColorTable = FALSE;
else if( EQUAL(argv[i], "-mdd") && i < argc-1 )
papszExtraMDDomains = CSLAddString( papszExtraMDDomains,
argv[++i] );
else if( EQUAL(argv[i], "-nofl") )
bShowFileList = FALSE;
else if( EQUAL(argv[i], "-sd") && i < argc-1 )
nSubdataset = atoi(argv[++i]);
else if( pszFilename == NULL )
pszFilename = argv[i];
}
*/
/* -------------------------------------------------------------------- */
/* Open dataset. */
/* -------------------------------------------------------------------- */
hDataset = GDALOpen( pszFilename, GA_ReadOnly );
if( hDataset == NULL )
{
fprintf( stderr,
"gdalinfo failed - unable to open '%s'.\n",
pszFilename );
//CSLDestroy( argv );
CSLDestroy( papszExtraMDDomains );
//GDALDumpOpenDatasets( stderr );
GDALDestroyDriverManager();
CPLDumpSharedList( NULL );
setMapInMaps(conf,"lenv","message","Unable to open the file");
return SERVICE_FAILED;
}
/* -------------------------------------------------------------------- */
/* Read specified subdataset if requested. */
/* -------------------------------------------------------------------- */
if ( nSubdataset > 0 )
{
char **papszSubdatasets = GDALGetMetadata( hDataset, "SUBDATASETS" );
int nSubdatasets = CSLCount( papszSubdatasets );
if ( nSubdatasets > 0 && nSubdataset <= nSubdatasets )
{
char szKeyName[1024];
char *pszSubdatasetName;
snprintf( szKeyName, sizeof(szKeyName),
"SUBDATASET_%d_NAME", nSubdataset );
szKeyName[sizeof(szKeyName) - 1] = '\0';
pszSubdatasetName =
CPLStrdup( CSLFetchNameValue( papszSubdatasets, szKeyName ) );
GDALClose( hDataset );
hDataset = GDALOpen( pszSubdatasetName, GA_ReadOnly );
CPLFree( pszSubdatasetName );
}
else
{
fprintf( stderr,
"gdalinfo warning: subdataset %d of %d requested. "
"Reading the main dataset.\n",
nSubdataset, nSubdatasets );
}
}
/* -------------------------------------------------------------------- */
/* Report general info. */
/* -------------------------------------------------------------------- */
hDriver = GDALGetDatasetDriver( hDataset );
xmlNodePtr n1=xmlNewNode(NULL,BAD_CAST "dataType");
xmlAddChild(n1,xmlNewText(BAD_CAST GDALGetDriverLongName( hDriver )));
xmlAddChild(n,n1);
n1=xmlNewNode(NULL,BAD_CAST "size");
char size[1024];
sprintf(size,"%d,%d",
GDALGetRasterXSize( hDataset ),GDALGetRasterYSize( hDataset ));
xmlAddChild(n1,xmlNewText(BAD_CAST size));
xmlAddChild(n,n1);
/* -------------------------------------------------------------------- */
/* Report projection. */
/* -------------------------------------------------------------------- */
n1=xmlNewNode(NULL,BAD_CAST "srs");
if( GDALGetProjectionRef( hDataset ) != NULL )
{
OGRSpatialReferenceH hSRS;
char *pszProjection;
pszProjection = (char *) GDALGetProjectionRef( hDataset );
hSRS = OSRNewSpatialReference(NULL);
if( OSRImportFromWkt( hSRS, &pszProjection ) == CE_None )
{
char *pszPrettyWkt = NULL;
OSRExportToPrettyWkt( hSRS, &pszPrettyWkt, FALSE );
fprintf( stderr, "Coordinate System is:\n%s\n", pszPrettyWkt );
CPLFree( pszPrettyWkt );
}
else
fprintf( stderr, "Coordinate System is `%s'\n",
GDALGetProjectionRef( hDataset ) );
OSRDestroySpatialReference( hSRS );
}
/* -------------------------------------------------------------------- */
/* Report Geotransform. */
/* -------------------------------------------------------------------- */
if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
{
if( adfGeoTransform[2] == 0.0 && adfGeoTransform[4] == 0.0 )
{
n1=xmlNewNode(NULL,BAD_CAST "origin");
char orig[1024];
sprintf( orig,"%.15f,%.15f",
adfGeoTransform[0], adfGeoTransform[3] );
xmlAddChild(n1,xmlNewText(BAD_CAST orig));
xmlAddChild(n,n1);
n1=xmlNewNode(NULL,BAD_CAST "prixelSize");
sprintf( orig,"%.15f,%.15f",
adfGeoTransform[1], adfGeoTransform[5] );
xmlAddChild(n1,xmlNewText(BAD_CAST orig));
xmlAddChild(n,n1);
}
else{
char orig[2048];
n1=xmlNewNode(NULL,BAD_CAST "geoTransform");
sprintf( orig,"%.16g,%.16g,%.16g;"
"%.16g,%.16g,%.16g\n",
adfGeoTransform[0],
adfGeoTransform[1],
adfGeoTransform[2],
adfGeoTransform[3],
adfGeoTransform[4],
adfGeoTransform[5] );
xmlAddChild(n1,xmlNewText(BAD_CAST orig));
xmlAddChild(n,n1);
}
}
/* -------------------------------------------------------------------- */
/* Report GCPs. */
/* -------------------------------------------------------------------- */
if( bShowGCPs && GDALGetGCPCount( hDataset ) > 0 )
{
if (GDALGetGCPProjection(hDataset) != NULL)
{
OGRSpatialReferenceH hSRS;
char *pszProjection;
pszProjection = (char *) GDALGetGCPProjection( hDataset );
hSRS = OSRNewSpatialReference(NULL);
if( OSRImportFromWkt( hSRS, &pszProjection ) == CE_None )
{
char *pszPrettyWkt = NULL;
OSRExportToPrettyWkt( hSRS, &pszPrettyWkt, FALSE );
fprintf( stderr, "GCP Projection = \n%s\n", pszPrettyWkt );
CPLFree( pszPrettyWkt );
}
else
fprintf( stderr,"GCP Projection = %s\n",
GDALGetGCPProjection( hDataset ) );
OSRDestroySpatialReference( hSRS );
}
for( i = 0; i < GDALGetGCPCount(hDataset); i++ )
{
const GDAL_GCP *psGCP;
psGCP = GDALGetGCPs( hDataset ) + i;
fprintf( stderr, "GCP[%3d]: Id=%s, Info=%s\n"
" (%.15g,%.15g) -> (%.15g,%.15g,%.15g)\n",
i, psGCP->pszId, psGCP->pszInfo,
psGCP->dfGCPPixel, psGCP->dfGCPLine,
psGCP->dfGCPX, psGCP->dfGCPY, psGCP->dfGCPZ );
}
}
/* -------------------------------------------------------------------- */
/* Report metadata. */
/* -------------------------------------------------------------------- *
papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, NULL ) : NULL;
if( bShowMetadata && CSLCount(papszMetadata) > 0 )
{
printf( "Metadata:\n" );
for( i = 0; papszMetadata[i] != NULL; i++ )
{
printf( " %s\n", papszMetadata[i] );
}
}
for( iMDD = 0; bShowMetadata && iMDD < CSLCount(papszExtraMDDomains); iMDD++ )
{
papszMetadata = GDALGetMetadata( hDataset, papszExtraMDDomains[iMDD] );
if( CSLCount(papszMetadata) > 0 )
{
printf( "Metadata (%s):\n", papszExtraMDDomains[iMDD]);
for( i = 0; papszMetadata[i] != NULL; i++ )
{
printf( " %s\n", papszMetadata[i] );
}
}
}*/
/* -------------------------------------------------------------------- */
/* Report "IMAGE_STRUCTURE" metadata. */
/* -------------------------------------------------------------------- *
papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, "IMAGE_STRUCTURE" ) : NULL;
if( bShowMetadata && CSLCount(papszMetadata) > 0 )
{
printf( "Image Structure Metadata:\n" );
for( i = 0; papszMetadata[i] != NULL; i++ )
{
printf( " %s\n", papszMetadata[i] );
}
}*/
/* -------------------------------------------------------------------- */
/* Report subdatasets. */
/* -------------------------------------------------------------------- *
papszMetadata = GDALGetMetadata( hDataset, "SUBDATASETS" );
if( CSLCount(papszMetadata) > 0 )
{
printf( "Subdatasets:\n" );
for( i = 0; papszMetadata[i] != NULL; i++ )
{
printf( " %s\n", papszMetadata[i] );
}
}*/
/* -------------------------------------------------------------------- */
/* Report geolocation. */
/* -------------------------------------------------------------------- */
papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, "GEOLOCATION" ) : NULL;
if( bShowMetadata && CSLCount(papszMetadata) > 0 )
{
fprintf( stderr,"Geolocation:\n" );
for( i = 0; papszMetadata[i] != NULL; i++ )
{
fprintf( stderr," %s\n", papszMetadata[i] );
}
}
/* -------------------------------------------------------------------- */
/* Report RPCs */
/* -------------------------------------------------------------------- */
papszMetadata = (bShowMetadata) ? GDALGetMetadata( hDataset, "RPC" ) : NULL;
if( bShowMetadata && CSLCount(papszMetadata) > 0 )
{
fprintf( stderr,"RPC Metadata:\n" );
for( i = 0; papszMetadata[i] != NULL; i++ )
{
fprintf( stderr," %s\n", papszMetadata[i] );
}
}
/* -------------------------------------------------------------------- */
/* Setup projected to lat/long transform if appropriate. */
/* -------------------------------------------------------------------- */
if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
pszProjection = GDALGetProjectionRef(hDataset);
if( pszProjection != NULL && strlen(pszProjection) > 0 )
{
OGRSpatialReferenceH hProj, hLatLong = NULL;
hProj = OSRNewSpatialReference( pszProjection );
if( hProj != NULL )
hLatLong = OSRCloneGeogCS( hProj );
if( hLatLong != NULL )
{
CPLPushErrorHandler( CPLQuietErrorHandler );
hTransform = OCTNewCoordinateTransformation( hProj, hLatLong );
CPLPopErrorHandler();
OSRDestroySpatialReference( hLatLong );
}
if( hProj != NULL )
OSRDestroySpatialReference( hProj );
}
/* -------------------------------------------------------------------- */
/* Report corners. */
/* -------------------------------------------------------------------- */
/*printf( "Corner Coordinates:\n" );
GDALInfoReportCorner( hDataset, hTransform, "Upper Left",
0.0, 0.0 );
GDALInfoReportCorner( hDataset, hTransform, "Lower Left",
0.0, GDALGetRasterYSize(hDataset));
GDALInfoReportCorner( hDataset, hTransform, "Upper Right",
GDALGetRasterXSize(hDataset), 0.0 );
GDALInfoReportCorner( hDataset, hTransform, "Lower Right",
GDALGetRasterXSize(hDataset),
GDALGetRasterYSize(hDataset) );
GDALInfoReportCorner( hDataset, hTransform, "Center",
GDALGetRasterXSize(hDataset)/2.0,
GDALGetRasterYSize(hDataset)/2.0 );*/
if( hTransform != NULL )
{
OCTDestroyCoordinateTransformation( hTransform );
hTransform = NULL;
}
xmlNodePtr n2;
/* ==================================================================== */
/* Loop over bands. */
/* ==================================================================== */
for( iBand = 0; iBand < GDALGetRasterCount( hDataset ); iBand++ )
{
n1=xmlNewNode(NULL,BAD_CAST "Band");
double dfMin, dfMax, adfCMinMax[2], dfNoData;
int bGotMin, bGotMax, bGotNodata, bSuccess;
int nBlockXSize, nBlockYSize, nMaskFlags;
double dfMean, dfStdDev;
GDALColorTableH hTable;
CPLErr eErr;
hBand = GDALGetRasterBand( hDataset, iBand+1 );
if( bSample )
{
float afSample[10000];
int nCount;
nCount = GDALGetRandomRasterSample( hBand, 10000, afSample );
fprintf( stderr,"Got %d samples.\n", nCount );
}
GDALGetBlockSize( hBand, &nBlockXSize, &nBlockYSize );
fprintf( stderr, "Band %d Block=%dx%d Type=%s, ColorInterp=%s\n", iBand+1,
nBlockXSize, nBlockYSize,
GDALGetDataTypeName(
GDALGetRasterDataType(hBand)),
GDALGetColorInterpretationName(
GDALGetRasterColorInterpretation(hBand)) );
if( GDALGetDescription( hBand ) != NULL
&& strlen(GDALGetDescription( hBand )) > 0 )
fprintf( stderr," Description = %s\n", GDALGetDescription(hBand) );
dfMin = GDALGetRasterMinimum( hBand, &bGotMin );
dfMax = GDALGetRasterMaximum( hBand, &bGotMax );
if( bGotMin || bGotMax || bComputeMinMax )
{
if( bGotMin ){
char orig[128];
n2=xmlNewNode(NULL,BAD_CAST "min");
sprintf( orig,"%.3f", dfMin );
xmlAddChild(n2,xmlNewText(BAD_CAST orig));
xmlAddChild(n1,n2);
hasMin=TRUE;
}
if( bGotMax ){
char orig[128];
n2=xmlNewNode(NULL,BAD_CAST "max");
sprintf( orig,"%.3f", dfMax );
xmlAddChild(n2,xmlNewText(BAD_CAST orig));
xmlAddChild(n1,n2);
hasMax=TRUE;
}
if( bComputeMinMax )
{
CPLErrorReset();
GDALComputeRasterMinMax( hBand, FALSE, adfCMinMax );
if (CPLGetLastErrorType() == CE_None)
{
char orig[128];
n2=xmlNewNode(NULL,BAD_CAST "cmin");
sprintf( orig,"%.3f", adfCMinMax[0] );
xmlAddChild(n2,xmlNewText(BAD_CAST orig));
xmlAddChild(n1,n2);
n2=xmlNewNode(NULL,BAD_CAST "cmax");
sprintf( orig,"%.3f", adfCMinMax[1] );
xmlAddChild(n2,xmlNewText(BAD_CAST orig));
xmlAddChild(n1,n2);
}
}
}
eErr = GDALGetRasterStatistics( hBand, bApproxStats, bStats,
&dfMin, &dfMax, &dfMean, &dfStdDev );
fprintf(stderr,"loop over %d Band : %.3f %.3f %.3f %.3f\n",GDALGetRasterCount( hDataset ),dfMin, dfMax, dfMean, dfStdDev);
if( eErr == CE_None )
{
fprintf( stderr, " Minimum=%.3f, Maximum=%.3f, Mean=%.3f, StdDev=%.3f\n",
dfMin, dfMax, dfMean, dfStdDev );
}
if( bReportHistograms )
{
int nBucketCount, *panHistogram = NULL;
eErr = GDALGetDefaultHistogram( hBand, &dfMin, &dfMax,
&nBucketCount, &panHistogram,
TRUE, NULL, NULL );
fprintf(stderr,"Error : %d\n",eErr);
if( eErr == CE_None )
{
int iBucket;
char orig[128];
n2=xmlNewNode(NULL,BAD_CAST "number");
sprintf( orig,"%d", nBucketCount );
xmlAddChild(n2,xmlNewText(BAD_CAST orig));
xmlAddChild(n1,n2);
if(hasMin==FALSE){
n2=xmlNewNode(NULL,BAD_CAST "min");
sprintf( orig,"%.3f", dfMin );
xmlAddChild(n2,xmlNewText(BAD_CAST orig));
xmlAddChild(n1,n2);
}
if(hasMax==FALSE){
n2=xmlNewNode(NULL,BAD_CAST "max");
sprintf( orig,"%.3f", dfMax );
xmlAddChild(n2,xmlNewText(BAD_CAST orig));
xmlAddChild(n1,n2);
}
n2=xmlNewNode(NULL,BAD_CAST "histogram");
for( iBucket = 0; iBucket < nBucketCount; iBucket++ ){
if(iBucket==0)
sprintf( orig, "%d", panHistogram[iBucket] );
else
sprintf( orig, ",%d", panHistogram[iBucket] );
xmlAddChild(n2,xmlNewText(BAD_CAST orig));
}
xmlAddChild(n1,n2);
CPLFree( panHistogram );
}
}
if ( bComputeChecksum)
{
fprintf( stderr, " Checksum=%d\n",
GDALChecksumImage(hBand, 0, 0,
GDALGetRasterXSize(hDataset),
GDALGetRasterYSize(hDataset)));
}
dfNoData = GDALGetRasterNoDataValue( hBand, &bGotNodata );
if( bGotNodata )
{
if (CPLIsNan(dfNoData))
fprintf( stderr," NoData Value=nan\n" );
else
fprintf( stderr," NoData Value=%.18g\n", dfNoData );
}
if( GDALGetOverviewCount(hBand) > 0 )
{
int iOverview;
fprintf( stderr, " Overviews: " );
for( iOverview = 0;
iOverview < GDALGetOverviewCount(hBand);
iOverview++ )
{
GDALRasterBandH hOverview;
const char *pszResampling = NULL;
if( iOverview != 0 )
fprintf( stderr, ", " );
hOverview = GDALGetOverview( hBand, iOverview );
if (hOverview != NULL)
{
fprintf( stderr, "%dx%d",
GDALGetRasterBandXSize( hOverview ),
GDALGetRasterBandYSize( hOverview ) );
pszResampling =
GDALGetMetadataItem( hOverview, "RESAMPLING", "" );
if( pszResampling != NULL
&& EQUALN(pszResampling,"AVERAGE_BIT2",12) )
fprintf( stderr,"*" );
}
else
fprintf( stderr, "(null)" );
}
fprintf( stderr, "\n" );
if ( bComputeChecksum)
{
fprintf( stderr, " Overviews checksum: " );
for( iOverview = 0;
iOverview < GDALGetOverviewCount(hBand);
iOverview++ )
{
GDALRasterBandH hOverview;
if( iOverview != 0 )
fprintf( stderr, ", " );
hOverview = GDALGetOverview( hBand, iOverview );
if (hOverview)
fprintf( stderr, "%d",
GDALChecksumImage(hOverview, 0, 0,
GDALGetRasterBandXSize(hOverview),
GDALGetRasterBandYSize(hOverview)));
else
fprintf( stderr, "(null)" );
}
fprintf( stderr, "\n" );
}
}
if( GDALHasArbitraryOverviews( hBand ) )
{
fprintf( stderr, " Overviews: arbitrary\n" );
}
nMaskFlags = GDALGetMaskFlags( hBand );
if( (nMaskFlags & (GMF_NODATA|GMF_ALL_VALID)) == 0 )
{
GDALRasterBandH hMaskBand = GDALGetMaskBand(hBand) ;
fprintf( stderr, " Mask Flags: " );
if( nMaskFlags & GMF_PER_DATASET )
fprintf( stderr, "PER_DATASET " );
if( nMaskFlags & GMF_ALPHA )
fprintf( stderr, "ALPHA " );
if( nMaskFlags & GMF_NODATA )
fprintf( stderr, "NODATA " );
if( nMaskFlags & GMF_ALL_VALID )
fprintf( stderr, "ALL_VALID " );
fprintf( stderr, "\n" );
if( hMaskBand != NULL &&
GDALGetOverviewCount(hMaskBand) > 0 )
{
int iOverview;
fprintf( stderr, " Overviews of mask band: " );
for( iOverview = 0;
iOverview < GDALGetOverviewCount(hMaskBand);
iOverview++ )
{
GDALRasterBandH hOverview;
if( iOverview != 0 )
fprintf( stderr, ", " );
hOverview = GDALGetOverview( hMaskBand, iOverview );
fprintf( stderr, "%dx%d",
GDALGetRasterBandXSize( hOverview ),
GDALGetRasterBandYSize( hOverview ) );
}
fprintf( stderr, "\n" );
}
}
if( strlen(GDALGetRasterUnitType(hBand)) > 0 )
{
fprintf( stderr, " Unit Type: %s\n", GDALGetRasterUnitType(hBand) );
}
if( GDALGetRasterCategoryNames(hBand) != NULL )
{
char **papszCategories = GDALGetRasterCategoryNames(hBand);
int i;
fprintf( stderr, " Categories:\n" );
for( i = 0; papszCategories[i] != NULL; i++ )
fprintf( stderr, " %3d: %s\n", i, papszCategories[i] );
}
if( GDALGetRasterScale( hBand, &bSuccess ) != 1.0
|| GDALGetRasterOffset( hBand, &bSuccess ) != 0.0 )
fprintf( stderr, " Offset: %.15g, Scale:%.15g\n",
GDALGetRasterOffset( hBand, &bSuccess ),
GDALGetRasterScale( hBand, &bSuccess ) );
papszMetadata = (bShowMetadata) ? GDALGetMetadata( hBand, NULL ) : NULL;
if( bShowMetadata && CSLCount(papszMetadata) > 0 )
{
fprintf( stderr, " Metadata:\n" );
for( i = 0; papszMetadata[i] != NULL; i++ )
{
fprintf( stderr, " %s\n", papszMetadata[i] );
}
}
papszMetadata = (bShowMetadata) ? GDALGetMetadata( hBand, "IMAGE_STRUCTURE" ) : NULL;
if( bShowMetadata && CSLCount(papszMetadata) > 0 )
{
fprintf( stderr, " Image Structure Metadata:\n" );
for( i = 0; papszMetadata[i] != NULL; i++ )
{
fprintf( stderr, " %s\n", papszMetadata[i] );
}
}
if( GDALGetRasterColorInterpretation(hBand) == GCI_PaletteIndex
&& (hTable = GDALGetRasterColorTable( hBand )) != NULL )
{
int i;
if (bShowColorTable)
{
n2=xmlNewNode(NULL,BAD_CAST "colorTable");
for( i = 0; i < GDALGetColorEntryCount( hTable ); i++ )
{
GDALColorEntry sEntry;
GDALGetColorEntryAsRGB( hTable, i, &sEntry );
char tmp[1024];
sprintf( tmp, "%d,%d,%d,%d;",
i,
sEntry.c1,
sEntry.c2,
sEntry.c3,
sEntry.c4 );
xmlAddChild(n2,xmlNewText(BAD_CAST tmp));
}
xmlAddChild(n1,n2);
}
}
if( bShowRAT && GDALGetDefaultRAT( hBand ) != NULL )
{
GDALRasterAttributeTableH hRAT = GDALGetDefaultRAT( hBand );
//GDALRATDumpReadable( hRAT, NULL );
}
xmlAddChild(n,n1);
}
GDALClose( hDataset );
CSLDestroy( papszExtraMDDomains );
//GDALDumpOpenDatasets( stderr );
GDALDestroyDriverManager();
CPLDumpSharedList( NULL );
CPLCleanupTLS();
xmlChar *xmlb;
int bsize;
xmlDocSetRootElement(resDoc, n);
xmlDocDumpFormatMemory(resDoc, &xmlb, &bsize, 1);
setMapInMaps(outputs,"Result","value",(char*)xmlb);
return SERVICE_SUCCEEDED;
}
}
<|start_filename|>mapmint-ui/templates/preview/modules/addLayer/OverlayLayers_bs.html<|end_filename|>
#encoding UTF-8
#import zoo
#import mapscript
#from Cheetah.Template import Template
<div id="overlay_layerswitcher" class="flipped">
#from mapfile.service import getMapList
#set linputs={"name": {"value": "Overlays"}}
#set loutputs={"Result": {"value": ""}}
#set a=getMapList($conf,$linputs,$loutputs)
#set a=eval($loutputs["Result"]["value"])
<ul id="overlays_list">
#for i in range(0,len($a[0]["children"]))
$Template(file=$conf['main']['templatesPath']+"layer_tree_bs.tmpl",searchList={"m":$m,"elem": $a[0]["children"],"i": $i,"conf": $conf,"prefix":"_overlays"})
#end for
</ul>
</div>
<|start_filename|>public_map/default_init.js<|end_filename|>
System.initialIndexCnt=0
$(document).ready(function(){
searchTable("indicators");
searchTable1("documents");
var items = $('\#stage li'),
itemsByTags = {};
// Looping though all the li items:
items.each(function(i){
var elem = $(this),
tags = elem.data('tags').split(',');
// Adding a data-id attribute. Required by the Quicksand plugin:
elem.attr('data-id',i);
$.each(tags,function(key,value){
// Removing extra whitespace:
value = $.trim(value);
if(!(value in itemsByTags)){
// Create an empty array to hold this item:
itemsByTags[value] = [];
}
// Each item is added to one array per tag:
itemsByTags[value].push(elem);
});
});
// Creating the "Everything" option in the menu:
createList(System.messages['All themes'],items);
// Looping though the arrays in itemsByTags:
$.each(itemsByTags,function(k,v){
createList(k,v);
});
$('#filter a').click(function(e){
var link = $(this);
link.addClass('active').siblings().removeClass('active');
// Using the Quicksand plugin to animate the li items.
// It uses data('list') defined by our createList function:
$('#stage').quicksand( $('#stage').find('li'),
{
useScaling: true,
adjustHeight: 'dynamic',
attribute: function(v) {
return $(v).find('img').attr('src');
}
});
$('#stage').quicksand(link.data('list').find('li'),function(){
startMozaic($('.mosaic-block'));
});
e.preventDefault();
});
link=$('#filter a:first');
link.addClass('active').siblings().removeClass('active');
link.trigger("click");
function createList(text,items){
// This is a helper function that takes the
// text of a menu button and array of li items
// Creating an empty unordered list:
var ul = $('<ul>',{'class':'hidden'});
$.each(items,function(){
// Creating a copy of each li item
// and adding it to the list:
$(this).clone().appendTo(ul);
});
ul.appendTo('#container');
// Creating a menu item. The unordered list is added
// as a data parameter (available via .data('list'):
if(text!="")
var a = $('<a>',{
html: text,
href:'#',
data: {list:ul}
}).appendTo('#filter');
}
//refreshIndexDisplay();
if(System.hasIndexes)
setCurrentIndex();
});
function setCurrentIndex(){
params=[{name: "id", value: $("#index_id").val(), dataType: "string"}];
data=WPSGetHeader("np.setCurrentIndex")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false,false)){
if(System.nodeId)
$("#vote_0_"+System.nodeId).attr("id","vote_0_"+$("#index_id").val());
System.starcIds=[];
System.nodeId=$("#index_id").val();
$("#vote_0_"+System.nodeId).each(function(){
System.starcIds.push({"id":$("#index_id").val(),"elem":$(this)});
getIndexQuote($(this),System.starcIds);
});
var tmp=$.parseJSON(xml.responseText);
System.full_index=tmp;
var typs=[
["description", "idx_desc"],
["name", "idx_title"]
];
if(!tmp["file"] || tmp["file"]==""){
if(!tmp["url"] || tmp["url"]==""){
$('#indicateur_file_link').attr("href",tmp['url']);
$('#indicateur_file_link').hide();
}
else{
$('#indicateur_file_link').attr("href",tmp['url']);
$('#indicateur_file_link').show();
}
}
else{
$('#indicateur_file_link').attr("href",System.public_map_url+"/indicateurs/"+tmp['file']);
$('#indicateur_file_link').show();
}
for(i=0;i<typs.length;i++){
if(tmp[typs[i][0]])
$("#"+typs[i][1]).html(tmp[typs[i][0]]);
else
$("#"+typs[i][1]).html("");
}
tmp0=$("#idx_ov").attr("src");
$("#idx_ov").attr("src",tmp0.replace(new RegExp("idx"+System.initialIndex,"g"),"idx"+$("#index_id").val()).replace(new RegExp("PIndex"+System.initialIndex,"g"),"PIndex"+$("#index_id").val()));
System.initialIndex=$("#index_id").val();
refreshIndexDisplay();
System.nodeId=$("#index_id").val();
}
}
});
}
function refreshIndexDisplay(){
params=[{name: "id", value: $("#index_id").val(), dataType: "string"}];
data=WPSGetHeader("np.getIndexDisplayJs")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
try{
colModel=$.parseJSON(xml.responseText);
fields=new Array();
for(i=0;i<colModel["values"].length;i++)
fields.push(colModel["values"][i].name);
$("#tblDisplay").html('<div id="flexi_index"></div>');
$("#flexi_index").flexigrid({
autoload: true,
ogcProtocol: "MM",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.getIndexValues&RawDataOutput=Result&DataInputs=id="+$('#index_id').val(),
id: "PG",
singleSelect: true,
colModel: colModel["values"],
usepager: true,
sortname: colModel["ord"],
sortorder: "asc",
fields: fields,
dwDataSource: "Toto",
dwLayer: "Tata",
title: colModel["title"],
useLimit: true,
autozoom: false,
limit: 10,
showTableToggleBtn: true,
width: "100%",
height: 290,
onSuccess: function(){
System.doOnGraphLoad=function(){
refreshGraph($("#index_id").val());
System.initialIndexCnt+=1;
};
refreshGraphFields();
}
});
}catch(e){
//alert(e);
}
}
}
});
}
function displayIndexPage(){
var tabContainers = $('div.all > div');
tabContainers.hide();
tabContainers.filter($(".indx")[0].hash).fadeIn();
$('.main-navigation a').removeClass('current');
$(".indx").addClass('current');
}
<|start_filename|>mapmint-ui/new-themes/themes/green/forms.css<|end_filename|>
ul.style-tabs-nav1 li a.selected,
ul.style-tabs-nav1 li a:hover, a.classify:hover {
color:#FFFFFF;
position:relative;
top:1px;
left:0px;
text-shadow:#333333 0 1px 0;
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
background: -ms-linear-gradient(#C2FF7E, #4FA33F);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
}
ul.style-tabs-nav li a.selected,
ul.style-tabs-nav li a:hover, a.classify:hover {
color:#FFFFFF;
position:relative;
top:1px;
left:0px;
text-shadow:#333333 0 1px 0;
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
background: -ms-linear-gradient(#C2FF7E, #4FA33F);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
}
.customfile-hover .customfile-button, .customfile-focus .customfile-button { color:#111; background: #65D115; border-color:#FFFFFF;padding: .3em .6em;}
.wbutton{
text-decoration:none;
padding:10px;
color:#ffffff;
background: #9ACB6B;
display:inline-block;
max-width:80px;
text-align:center;
margin:10px 10px 0 0;
}
.button:hover, .wbutton:hover{
background:#FC0D1B;
}
.wbuttonc{
text-decoration:none;
padding:10px;
color:#ffffff;
background: #E0E0E0;
display:inline-block;
max-width:80px;
text-align:center;
margin:10px 10px 0 0;
}
.wbuttonc:hover{
background:#707070;
color:#FFFFFF;
}
<|start_filename|>mapmint-ui/new-themes/themes/default/window.css<|end_filename|>
/*
* MapMint Window CSS
*/
/*
* Window general
*/
.window {
position:absolute;
overflow:hidden;
background:#E8E8E8;
padding:5px;
border:1px solid #949494;
-moz-border-radius:5px;
-webkit-border-radius: 5px;
min-width:350px;
}
.window-shadow{
position:absolute;
background:#ddd;
-moz-border-radius:5px;
-webkit-border-radius: 5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
}
.window .window-header{
background:transparent;
padding:2px 0px 4px 0px;
}
.window .window-body{
background:#fff;
border:1px solid #B6B6B6;
border-top-width:0px;
padding:10px;
}
.window .window-header .panel-icon{
left:1px;
top:1px;
}
.window .window-header .panel-with-icon{
padding-left:18px;
}
.window .window-header .panel-tool{
top:0px;
right:1px;
}
.window-proxy{
position:absolute;
overflow:hidden;
border:1px dashed #15428b;
}
.window-proxy-mask{
position:absolute;
background:#fafafa;
filter:alpha(opacity=10);
opacity:0.10;
}
.window-mask{
position:absolute;
left:0;
top:0;
width:100%;
height:100%;
filter:alpha(opacity=40);
opacity:0.40;
background:#ccc;
display1:none;
font-size:1px;
*zoom:1;
overflow:hidden;
}
.panel{
overflow:hidden;
font-size:12px;
}
.panel-header{
padding:5px;
line-height:15px;
font-size:1em;
color:#333333;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
font-weight:bold;
font-size:12px;
background:url('../img/panel_title.png') repeat-x;
position:relative;
border:1px solid #B6B6B6;
}
.panel-header-noborder{
border-width:0px;
border-bottom:1px solid #909090;
}
.panel-body{
overflow:auto;
border:1px solid #99BBE8;
border-top-width:0px;
}
.panel-body-noheader{
border-top-width:1px;
}
.panel-body-noborder{
border-width:0px;
}
.panel-with-icon{
padding-left:18px;
}
.panel-icon{
position:absolute;
left:5px;
top:4px;
width:16px;
height:16px;
}
.panel-tool{
position:absolute;
right:5px;
top:4px;
}
.panel-tool a{
display:block;
float:left;
width:16px;
height:16px;
margin-left:2px;
cursor:pointer;
opacity:0.6;
filter:alpha(opacity=60);
}
.panel-tool a.panel-tool-over{
opacity:1;
filter:alpha(opacity=100);
}
a.l-btn{
float:right;
color:#333333;
background: -moz-linear-gradient(top, #e2e2e2, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E2E2E2', endColorstr='#B6B6B6');
font-size:12px;
text-decoration:none;
display:inline-block;
zoom:1;
height:24px;
padding-right:18px;
cursor:pointer;
outline:none;
margin:15px 0 5px 5px;
-moz-border-radius:4px;
border-radius:4px;
-webkit-border-radius:4px;
text-shadow: #FFFFFF 0px 1px 0px;
}
a.l-btn-plain{
background:transparent;
padding-right:5px;
border:1px solid transparent;
_border:0px solid #efefef;
_padding:1px 6px 1px 1px;
}
a.l-btn-disabled{
color:#ccc;
opacity:0.5;
filter:alpha(opacity=50);
cursor:default;
}
a.l-btn span.l-btn-left{
display:inline-block;
padding:4px 0px 4px 18px;
line-height:16px;
height:16px;
-moz-border-radius:4px;
border-radius:4px;
-webkit-border-radius:4px;
}
a.l-btn-plain span.l-btn-left{
background:transparent;
padding-left:5px;
}
a.l-btn span span.l-btn-text{
display:inline-block;
height:16px;
line-height:16px;
padding:0px;
}
a.l-btn span span span.l-btn-empty{
display:inline-block;
padding:0px;
width:16px;
}
a:hover.l-btn{
background-position: bottom right;
outline:none;
}
a:hover.l-btn span.l-btn-left{
background-position: bottom left;
}
a:hover.l-btn-plain{
border:1px solid #7eabcd;
background:url('../img/button_plain_hover.png') repeat-x left bottom;
_padding:0px 5px 0px 0px;
-moz-border-radius:3px;
-webkit-border-radius: 3px;
}
a:hover.l-btn-disabled{
background-position:top right;
}
a:hover.l-btn-disabled span.l-btn-left{
background-position:top left;
}
/*
* Window specific
*/
#add-database-dialog{width:350px;height:auto;}
#add-database-dialog table{margin:5px 0 0 0;width:100%;}
#add-directory-dialog{width:350px;height:auto;}
#dlg-buttons{margin:10px 0 0 0;}
#add-directory-dialog table{margin:5px 0 0 0;width:100%;}
#add-directory-dialog ul {margin:5px 0 0 0;padding:0;}
#add-directory-dialog ul li {margin:0;padding:0;display:inline;}
#add-layer-dialog{width:350px;height:auto;max-height:250px;}
#add-layer-dialog p{margin:0;padding:10px 0 0 0;}
#open-map-dialog{width:350px;height:auto;}
#open-map-dialog p{margin:0;padding:10px 0 0 0;}
#save-as-map-dialog{width:350px;height:auto;}
#save-as-map-dialog table {margin:5px 0 0 0;width:100%;}
#zoom-to-point-dialog{width:350px;height:auto;}
#zoom-to-point-dialog table {margin:5px 0 0 0;width:100%;margin:0 auto;}
#zoom-to-point-dialog table tr td{padding:5px;}
input-zoom{width:70%;}
#change-srs-dialog{width:350px;height:auto;}
#change-srs-dialog table{margin:5px 0 0 0;width:100%;}
#change-format-dialog{width:350px;height:auto;}
#change-format-dialog table{margin:5px 0 0 0;width:100%;}
#preview-dialog{width:350px;height:auto;}
#view-table-dialog{width:550px;height:auto;}
#view-table-dialog.window-body{padding:0;}
/*
* TileIndex window
*/
#tileindex-data-dialog{width:350px;height:320px;}
.ti-top, .sti-top, .ti-mid, .ti-bot{margin:0 0 5px 0;}
/*
* Layer properties
*/
#view-lprop-dialog{height:325px;height:325px;}
/*
* old toolbars
*/
#editing-toolbar.window-body, #spatial-toolbar.window-body, #raster-toolbar.window-body, #terrain-toolbar.window-body {padding:0px;border:0;background: -moz-linear-gradient(top, #B6B6B6, #c7c7c7);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E2E2E2', endColorstr='#B6B6B6');}
/*
* OSM importer window
*/
#importOSM-dialog{background: url(../img/osm-window-bck.png) no-repeat top left;}
.osm-type, .osm-datastore, .osm-filename{margin:0 0 5px 0;}
.osm-attribution{font-size:.85em;padding:4px;background:#FFFFFF;color:#707070;-moz-border-radius:4px;-webkit-border-radius: 4px;border-radius:4px;position:absolute;bottom:5px;left:15px;}
.osm-attribution a, .osm-attribution a:visited{text-decoration:none;color:#979797;}
.osm-attribution a:hover, {color:#82a868;text-decoration:underline;}
/*
* Style window
*/
#style-dialog{width:350px;height:auto;}
#Styler_Labels table{width:100%;margin 0 auto;}
#Styler_Labels table tr td{padding: 5px ;}
#Styler_Labels table tr td.title{width:110px;}
table.classif {width:100%;margin 0 auto;}
table.classif tr td{padding: 5px ;}
table.classif tr td.title{width:110px;}
#flexiClasses table{width:100%;margin 0;}
#flexiClasses table tr td{margin:0;padding:0;}
#flexiClasses table tr td.title{width:auto;}
input.opacity{width:50px;border:0;background:#FFFFFF;border:0;display:inline;font-weight:bold;text-indent:10px;}
.point-symbol-container{width:100%;background:#FFFFFF;height:30%;margin:0 0 5px 0;border:0;-moz-border-radius:4px;-webkit-border-radius: 4px;border-radius:4px;border:1px solid #9f9f9f;}
.point-symbol-container img{margin:3px;margin-right:0;background:#E6E6E6;moz-border-radius:4px;-webkit-border-radius: 4px;border-radius:4px;}
.point-symbol-container .active img{margin:3px;margin-right:0;background:#43cb1f;}
.point-symbol-container img:hover{margin-right:0;background:#FFFFFF;}
.adds{margin:5px 0 5px;}
.ssy {margin: 3px 0 5px 0;}
div.color_picker {
height: 20px;
width: 20px;
padding: 0 !important;
border: 1px solid #9f9f9f;
background: url(../img/arrow.gif) no-repeat top right;
cursor: pointer;
line-height: 20px;
display:inline-block;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius: 2px;
}
div#color_selector {
width: 150px;
position: absolute;
padding:2px;
border:1px solid #ccc;
overflow:hidden;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
background-color: #EFEFEF;
padding: 5px;
z-index:10000000000;
-moz-box-shadow: 0 1px 0 rgba(123, 123, 123, 0.2);
-webkit-box-shadow: 0 1px 0 rgba(123, 123, 123, 0.2);
}
div#color_custom {width: 100%; float:left }
div#color_custom label {font-size: .8em; color: #2F2F2F; margin: 5px 2px; width: 25%}
div#color_custom input {margin: 5px 2px; padding: 0; font-size: .8em; border: 1px solid #9F9F9F; width: 65%; }
div.color_swatch {
height: 12px;
width: 12px;
border: 1px solid #9F9F9F;
margin: 2px;
float: left;
cursor: pointer;
line-height: 12px;
}
#symbolOrig, #symbolAdd{
width: 450px;
height: 120px;
overflow-y: auto;
}
#symbolOrig{
height: 40px;
}
#symbolAdd img:hover{
border: 1px solid #ffffff;
}
#symbolAdd img:hover{
border: 1px solid #00aa00;
}
<|start_filename|>mapmint-ui/js/Themes.js<|end_filename|>
Themes=MLayout.extend();
Themes.define({
id: 0,
layoutOptions: {
contentSelector: ".lcontent",
center__paneSelector: ".inner-center",
west__paneSelector: ".inner-west",
west__size: .28,
west__draggable: false,
west__resizable: false,
west__spacing_closed:10,
west__spacing_open:8,
east__paneSelector: ".inner-east",
east__size: .28,
east__closable: false,
east__draggable: false,
east__resizable: false,
spacing_open: 4,
spacing_closed: 4,
//resizeWhileDragging: true,
onopen: function() {updateSize();},
onclose: function() {updateSize();},
onresize: function() {updateSize();}
},
initialize: function(){
this.refresh();
endLoading();
this.id++;
},
refresh: function(){
defaultInit();
}
});
$(document).ready(function () {
$(".add-theme").click(function(){
$("#eName").val("");
$('#add-themes-dialog').window({
width: 300,
height: 150,
left:150,
top:150,
maximizable:false,
minimizable:false,
resizable: false
})
});
$(".delete-theme").click(function(){
if(System.nodeVal){
$("#edName").val(System.nodeVal);
$('#delete-themes-dialog').window({
width: 300,
height: 150,
left:150,
top:150,
maximizable:false,
minimizable:false,
resizable: false
});
}
});
startColorPicker();
refreshList();
});
function startColorPicker(){
$("#customWidget > div").html('<div id="colorSelector2"><div style="background-color:#'+(arguments.length>0?arguments[0]:'9ACB6B')+'"></div></div><div id="colorpickerHolder2"></div>');
var tColor="ff0000";
if(arguments.length>0){
$('#colorSelector2 div').css('backgroundColor', '#' + arguments[0]);
tColor=arguments[0];
}
$('#colorpickerHolder2').ColorPicker({
flat: true,
color: "#"+tColor,
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector2 div').css('backgroundColor', '#' + hex);
$("#themes_color").val(hex);
}
});
$('#colorpickerHolder2>div').css('position', 'absolute');
var widt = false;
$('#colorSelector2').bind('click', function() {
$('#colorpickerHolder2').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
}
/**
* Common part
*/
function updateElement(){
var params={id: System.nodeId};
$("#themes_edition_ui").find("input").each(function(){
if($(this)[0].id)
params[$(this)[0].id.replace(/themes_/,"")]=$(this).val();
});
$("#themes_edition_ui").find("select").each(function(){
if($(this)[0].multiple){
localId=$(this)[0].id.replace(/themes_/,"");
params[localId]=[];
$(this).find("option:selected").each(function(){
params[localId].push($(this).val());
});
}
else{
params[$(this)[0].id.replace(/themes_/,"")]=$(this).val();
}
});
params=[
{name: "table", value: "themes",dataType: "string"},
{name: "themes_groups_in", value: "t_id",dataType: "string"},
{name: "themes_groups_out", value: "g_id",dataType: "string"},
{name: "indicateurs_themes_in", value: "t_id",dataType: "string"},
{name: "indicateurs_themes_out", value: "i_id",dataType: "string"},
{name: "tuple", value: $.stringify(params), mimeType: "application/json"}
];
data=WPSGetHeader("np.updateElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
System.noSelectAgain=true;
refreshList();
}
}
});
}
function refreshDetails(){
$("#themes_pid option:disabled").removeAttr("disabled");
$("#themes_pid option:selected").removeAttr("selected");
$("#themes_pid option[value="+System.nodeId+"]").attr("disabled","disabled");
$("#themes_themes_groups option:selected").removeAttr("selected");
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.details&DataInputs=table=themes;id="+System.nodeId+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var data=$.parseJSON(xml.responseText);
for(var i in data){
if(!$.isArray(data[i])){
if(i=="name")
$("#themes_"+i+"_title").html(data[i]);
$("#themes_"+i).val("");
if(data[i]!=null)
$("#themes_"+i).val(data[i]);
else
$("#themes_"+i).val(-1);
}else{
//$("#themes_"+i+" option:selected").removeAttr("selected");
if(data[i].length){
for(var j=0;j<data[i].length;j++){
$("#themes_"+i+' option[value="'+data[i][j]+'"]').prop("selected", "selected");
}
}
else
$('#themes_'+i+' option[value="-1"]').prop("selected", "selected");
$('select[multiple]').blur().focus();
}
}
startColorPicker(data["color"]);
}
}
});
}
function getCurrentElements(obj){
var res=Array();
for(var i=0;i<obj.length;i++){
res.push({"id":obj[i]["id"],"text":obj[i]["text"]});
if(obj[i].children && obj[i].children.length>0){
var tmp=getCurrentElements(obj[i].children);
for(k=0;k<tmp.length;k++)
res.push({"id":tmp[k]["id"],"text":tmp[k]["text"]});
}
}
return res;
}
function refreshList(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.list&DataInputs=table=themes&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var data=$.parseJSON(xml.responseText);
$('#ltree').tree({
data: data,
onSelect: function(node){
System.nodeId=node.id;
System.nodeVal=node.text;
refreshDetails();
}
});
var tmp=getCurrentElements(data);
vals={};
orig=Array();
ord=Array();
for(i=0;i<tmp.length;i++){
vals[""+tmp[i]["id"]]=tmp[i]["text"];
orig[i]=tmp[i]["id"];
ord[i]=tmp[i]["id"];
}
ord.sort(function(a,b){return a-b});
$("#themes_pid option[value!='-1']").remove();
for(i=0;i<ord.length;i++){
if(i==0)
$("#themes_pid").append('<option value="'+ord[i]+'">'+vals[ord[i]]+'</option>');
else
if(ord[i]!=ord[i-1])
$("#themes_pid").append('<option value="'+ord[i]+'">'+vals[ord[i]]+'</option>');
}
if(!System.noSelectAgain){
var tmp=$("#ltree").tree('getSelected');
var tmpr=$("#ltree").tree('getRoot');
if(!tmp && tmpr){
$("#ltree").tree('select',tmpr.target);
}
}else{
var node = $('#ltree').tree('find', System.nodeId);
$("#ltree").tree('select',node.target);
}
System.noSelectAgain=false;
}
}
});
}
function deleteElement(){
params=[
{name: "table", value: "themes",dataType: "string"},
{name: "atable", value: "indicateurs_themes",dataType: "sting"},
{name: "akey", value: "t_id",dataType: "string"},
{name: "atable", value: "themes_groups",dataType: "sting"},
{name: "akey", value: "t_id",dataType: "string"},
{name: "id", value: System.nodeId,dataType: "string"}
];
data=WPSGetHeader("np.deleteElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshList();
$('#delete-themes-dialog').window('close');
}
}
});
}
function insertElement(){
params=[
{name: "table", value: "themes",dataType: "string"},
{name: "name", value: $("#eName").val(),dataType: "string"}
];
data=WPSGetHeader("np.insertElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshList();
$('#add-themes-dialog').window('close');
}
}
});
}
<|start_filename|>mapmint-ui/templates/preview/modules/auth/init.js<|end_filename|>
#import zoo
System.isIn=$conf["senv"]["loggedin"];
function loadLoginForm(){
System.clen=arguments.length;
$.ajax({
type: "GET",
url: "modules/auth/login#if $m is None#;pcancel=true#end if#",
complete: function(xml,status) {
#if $m is not None
if(\$("#authContainer")>0){
\$("#authContainer").window('close');
\$("#authContainer").remove();
}
\$("body").append('<div id="authContainer" title="$zoo._("Login")"></div>');
\$("#authContainer").html(xml.responseText);
\$( "#authContainer" ).window({
modal: true,
collapsible:false,
minimizable:false,
maximizable:false,
draggable:false,
resizable: false
});
#if $m.web.metadata.get('layout_t')=="mobile"
\$('#authPage').trigger('pagecreate');
\$('#authPage').listview("refresh");
#end if
#else
\$("#recover").html(xml.responseText);
if(System.clen==0){
\$('#formContainer').toggleClass('flipped');
if(!\$.support.css3d){
\$('#login').toggle();
\$('#recover').toggle();
}
}
#end if
}
});
}
#if $m is None
function pcancel(){
\$('#formContainer').toggleClass('flipped');
if(!\$.support.css3d){
\$('#login').toggle();
\$('#recover').toggle();
}
}
#end if
function cancelUserPreferences(){
#if $m is not None
\$( "#authContainer" ).window('close');
\$( "#authContainer" ).remove();
#end if
}
function recoverUserWindow(){
$.ajax({
type: "GET",
url: "modules/auth/recover#if $m is None#;pcancel=true#end if#",
complete: function(xml,status) {
#if $m is not None
if(\$("#authContainer").length>0){
\$("#authContainer").window('close');
\$("#authContainer").remove();
}
\$("body").append('<div id="authContainer" title="$zoo._("Recover password").replace("'","\\'")"></div>');
\$("#authContainer").html(xml.responseText);
\$( "#authContainer" ).window({
modal: true,
collapsible:false,
minimizable:false,
maximizable:false,
draggable:false,
resizable: false,
width: 320
});
#else
\$("#recover").html(xml.responseText);
\$('#formContainer').toggleClass('flipped');
if(!\$.support.css3d){
\$('#login').toggle();
\$('#recover').toggle();
}
#end if
}
});
}
function recoverPassword(){
var params=[
{name: "login",value: \$("#relogin").val(),dataType: "string"}
];
var data=WPSGetHeader("authenticate.getLostPassword")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false,true)){
try{
cancelUserPreferences();
if(System.onOnAuthenticate)
System.onOnAuthenticate();
}catch(e){alert(e);}
}
}
});
}
function registerUserWindow(){
$.ajax({
type: "GET",
url: "modules/auth/register#if $m is None#;pcancel=true#end if#",
complete: function(xml,status) {
#if $m is not None
if(\$("#authContainer").length>0){
\$("#authContainer").window('close');
\$("#authContainer").remove();
}
\$("body").append('<div id="authContainer" title="$zoo._("Register").replace("'","\\'")"></div>');
\$("#authContainer").html(xml.responseText);
\$( "#authContainer" ).window({
modal: true,
collapsible:false,
minimizable:false,
maximizable:false,
draggable:false,
resizable: false,
width: 380,
height: 250
});
#else
\$("#recover").html(xml.responseText);
\$('#formContainer').toggleClass('flipped');
if(!\$.support.css3d){
\$('#login').toggle();
\$('#recover').toggle();
}
#end if
}
});
}
function registerUser(){
var params=[
{name: "fields",value: "firstname",dataType: "string"},
{name: "values",value: \$("#firstname").val(),dataType: "string"},
{name: "fields",value: "lastname",dataType: "string"},
{name: "values",value: \$("#lastname").val(),dataType: "string"},
{name: "fields",value: "login",dataType: "string"},
{name: "values",value: \$("#rlogin").val(),dataType: "string"},
{name: "fields",value: "passwd",dataType: "string"},
{name: "values",value: \$("#rpassword").val(),dataType: "string"},
{name: "fields",value: "s_group_id",dataType: "string"},
{name: "values",value: "1",dataType: "string"},
{name: "fields",value: "mail",dataType: "string"},
{name: "values",value: \$("#email").val(),dataType: "string"}
];
var data=WPSGetHeader("authenticate.registerUser")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
//alert(data);
\$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
try{
if(checkWPSResult(xml,false,true)){
\$("#login_f").val(\$("#rlogin").val());
\$("#password_f").val(\$("#rpassword").val());
try{pcancel();}catch(e){};
authenticateUser();
}
}
catch(e){alert(e.message);}
}
});
}
function saveUserPreferences(){
var params=[
{name: "fields",value: "mail",dataType: "string"},
{name: "values",value: \$("#umail").val(),dataType: "string"}
];
if(\$("#upass").val()!=""){
if(\$("#upass").val()!=\$("#upass1").val()){
alert("$zoo._("Please set your password again")");
\$("#upass").val("");
\$("#upass1").val("");
return false;
}
params[params.length]={name: "fields",value: "passwd",dataType: "string"};
params[params.length]={name: "values",value: \$("#upass").val(),dataType: "string"};
}
var data=WPSGetHeader("authenticate.saveUserPreferences")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false,true)){
#if $m is not None
cancelUserPreferences();
loadLoginForm();
#end if
}
}
});
}
function authenticateUser(){
var params=[
{name: "login",value: \$("#login_f").val(),dataType: "string"},
{name: "password",value: \$("#password_f").val(),dataType: "string"}
];
var data=WPSGetHeader("authenticate.clogIn")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false,true)){
try{
cancelUserPreferences();
System.isIn=true;
if(System.onOnAuthenticate)
System.onOnAuthenticate();
}catch(e){alert(e);}
}
}
});
}
function logoutUser(){
var params=[
{name: "login",value: \$("#login").val(),dataType: "string"}
];
var data=WPSGetHeader("authenticate.clogOut")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
cancelUserPreferences();
System.isIn=false;
if(System.onOnAuthenticate)
System.onOnAuthenticate();
}
}
});
}
<|start_filename|>mapmint-ui/js/Publisher.js<|end_filename|>
function searchTable(){
System.tableName=arguments[0];
$( "#"+arguments[0]+"_search" ).autocomplete({
source: function(request,response){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&identifier=mapfile.searchByName&DataInputs=tbl="+System.tableName+";val="+request.term+"&RawDataOutput=Result",
success: function(xml,status){
var data=xml;
response(data);
}});
},
minLength: 0,
select: function( event, ui ) {
setCurrentMap(ui.item.id);
}
});
}
$(document).ready(function () {
searchTable("project");
defaultInit();
$("#datasources_list").flexigrid({noSelection: true,rp: 4, usepager: false, resizable: false,height: ($(window).height()-480)});
startUploadForm("Publisher");
createEditor("mmDescription");
$("#uploader_filelist").css({"height": ($(window).height()/14)+"px"});
$(".plupload_droptext").css({"height": ($(window).height()/14)+"px","line-height": (($(window).height()/14)-40)+"px"});
updateBaseLayersList();
$(".map_extent").click(function(e){
$('#form_move_map_'+this.id).css({'display':'block'})
});
myLayout = $('body').layout({
north__minSize:80,
north__closable:false,
north__resizable:false,
north__spacing_open:0,
north__spacing_closed:0,
north__showOverflowOnHover: true,
west__minSize: .28,
west__resizable: false,
west__spacing_closed: 20,
east__minSize: .28,
east__resizable: false,
east__closable:false,
south__closable:false,
south__resizable:false,
south__minSize:40,
});
$('div.ui-layout-resizer-west div.ui-layout-toggler').before('<span class="close-inv" onclick="myLayout.open(\'west\')" title="Open"></span>');
var localCnt=0;
$(".map-page").each(function(){localCnt++;});
if(localCnt>1){
$("#maps-pager").paginate({
count: localCnt,
start: 1,
display: 5,
border: true,
border_color: '#fff',
text_color: '#fff',
background_color: '#808080',
border_hover_color: '#ccc',
text_hover_color: '#000',
background_hover_color : '#fff',
images: false,
mouse: 'press',
onChange: function(page){
$('._current').removeClass('_current').hide();
$('#p'+page).addClass('_current').show();
}
});
}
$(function(){
$('#file').customFileInput();
});
$(function() {
$('#font-colorpicker').colorPicker();
});
$( "#nav li a" ).button();
$( "a.save-config" ).button();
$( ".nb-container p a" ).button();
$('.toolbar a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
$('.toolbar2 a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
function megaHoverOver(){
$(this).find(".sub").stop().fadeTo('fast', 1).show();
(function($) {
jQuery.fn.calcSubWidth = function() {
rowWidth = 0;
$(this).find("ul").each(function() {
rowWidth += $(this).width();
});
};
})(jQuery);
if ( $(this).find(".row").length > 0 ) {
var biggestRow = 0;
$(this).find(".row").each(function() {
$(this).calcSubWidth();
if(rowWidth > biggestRow) {
biggestRow = rowWidth;
}
});
$(this).find(".sub").css({'width' :biggestRow});
$(this).find(".row:last").css({'margin':'0'});
} else {
$(this).calcSubWidth();
$(this).find(".sub").css({'width' : rowWidth});
}
}
function megaHoverOut(){
$(this).find(".sub").stop().fadeTo('fast', 0, function() {
$(this).hide();
});
}
var config = {
sensitivity: 1,
interval: 50,
over: megaHoverOver,
timeout: 50,
out: megaHoverOut
};
$("ul li .sub").css({'opacity':'0'});
$("ul li").hoverIntent(config);
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
$("#logout").click(function () {
$( "#logout-message" ).window({
modal: true,
collapsible:false,
minimizable:false,
maximizable:false,
draggable:false,
resizable: false
});
});
endLoading();
});
$(function () {
var tabContainers = $('div.tabs-project > div');
tabContainers.hide().filter(':first').show();
$('div.toolbar2 a').click(function () {
if($(this).is("._nothidable"))
;
else{
tabContainers.hide();
tabContainers.filter(this.hash).show();
}
}).filter(':first').click();
});
MapMintNavPriv={
edit: function(){
$.ajax({
url: "./UsersManagement/NavWindow",//"$conf["main"]["serverAddress"]?service=WPS&version=1.0.0&request=Execute&Identifier=template.display&DataInputs=tmpl=Publisher/confirmRemove&RawDataOutput=Result",
complete: function(xml,status){
if(!$('#navPriv').length>0)
$("body").append('<div id="navPriv" title="'+System.messages["Navigation Toolbar"]+' '+System.messages["Privileges"]+'"></div>');
$('#navPriv').html("");
$('#navPriv').append(xml.responseText);
$('#navPriv').window({
width: 500,
height: 320,
maximizable:false,
resizable: false
});
$("#mmAccessNav").flexigrid({noSelection: true,rp: 4, usepager: false, resizable: false,height: 220});
}
})
},
confirm: function(){
System.navAccess=[];
System.navStr="";
for(var i=0;i<arguments[0].length;i++){
System.navAccess[i]=[];
if(System.navStr!="")
System.navStr+="|";
$(".mm_access_"+arguments[0][i]).each(function(){
if(System.navStr!="" && System.navStr[System.navStr.length-1]!="|")
System.navStr+=",";
if($(this).attr("checked")){
System.navStr+="1";
System.navAccess[i]+=[1]
}
else{
System.navAccess[i]+=[0]
System.navStr+="0";
}
});
}
postRequest=[];
postRequest[postRequest.length]={name:'priv',value: System.navStr,dataType: "string"};
var data=WPSGetHeader("mapfile.saveNavPrivileges")+WPSGetInputs(postRequest)+WPSGetOutput({name:"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
data: data,
contentType: "text/xml",
complete: function(xml,status) {
if(checkWPSResult(xml))
$('#navPriv').window('close');
}
});
}
}
<|start_filename|>mapmint-ui/new-themes/themes/blue/body.css<|end_filename|>
p.credits a:hover{text-decoration:underline;color:#0ed9e6;}
<|start_filename|>mapmint-ui/templates/preview/modules/other_tools/display.html<|end_filename|>
#if $m.web.metadata.get('mmOT')
#set f=$m.web.metadata.get('mmOT').split(',')
#if f.count('MMPanZoom')==0
#include($conf["main"]["templatesPath"]+"/preview/modules/other_tools/default.html")
#end if
#if f.count('ScaleBar')>0
<div class="scalebar-container">
<div id="scalebar"></div>
</div>
#end if
#else
#include($conf["main"]["templatesPath"]+"/preview/modules/other_tools/default.html")
#end if
<|start_filename|>public_map/assets/js/demo007-app.js<|end_filename|>
// Filename: app.js
/*
This work was supported by a grant from the European Union's 7th Framework Programme (2007-2013)
provided for the project PublicaMundi (GA no. 609608).
*/
//require(['bootstrap', 'notify']);
define([
'module', /*'jquery',*/ 'zoo', /*'xml2json',*/
'wpsPayload'
], function(module, /*$,*/ Zoo, /*X2JS,*/ wpsPayload) {
var myZooObject = new Zoo({
url: module.config().url,
delay: module.config().delay,
});
var initialize = function() {
self = this;
var request_params = {
request: 'GetCapabilities',
language: 'en-US'
};
console.log(wpsPayload.getPayload(request_params));
var request_params = {
Identifier: ["Buffer","Centroid"],
language: 'en-US'
};
console.log(wpsPayload.getPayload_DescribeProcess(request_params));
var request_params = {
request: 'Execute',
Identifier: "Buffer",
DataInputs: [{"identifier":"InputPolygon","href":"http://www.zoo-project.org:8082/geoserver/ows?SERVICE=WFS&REQUEST=GetFeature&VERSION=1.0.0&typename=topp:states&SRS=EPSG:4326&FeatureID=states.16","mimeType":"text/xml"}],
DataOutputs: [{"identifier":"Result","mimeType":"application/json"}],
language: 'en-US'
};
console.log(wpsPayload.getPayload(request_params));
/*var myZooObject = new Zoo({
url: "http://localhost/cgi-bin/zoo_loader.fcgi",
delay: 2500
});*/
myZooObject.getCapabilities({
type: 'POST',
success: function(data){
for(i in data["Capabilities"]["ProcessOfferings"]["Process"])
console.log(data["Capabilities"]["ProcessOfferings"]["Process"][i]["Identifier"]["__text"]);
}
});
myZooObject.describeProcess({
type: 'POST',
identifier: "all",
success: function(data){
console.log(data);
}
});
myZooObject.execute({
identifier: "Buffer",
dataInputs: [{"identifier":"InputPolygon","href":"http://www.zoo-project.org:8082/geoserver/ows?SERVICE=WFS&REQUEST=GetFeature&VERSION=1.0.0&typename=topp:states&SRS=EPSG:4326&FeatureID=states.16","mimeType":"text/xml"}],
dataOutputs: [{"identifier":"Result","mimeType":"application/json","type":"raw"}],
type: 'POST',
success: function(data) {
console.log(data);
}/*,
error: function(data){
console.log(data);
}*/
});
}
// Return public methods
return {
initialize: initialize
};
});
<|start_filename|>mapmint-ui/templates/preview/modules/other_tools/overviewmap.js<|end_filename|>
var overview = new OpenLayers.Control.OverviewMap({ div: \$('#overviewmap')[0]},{
mapOptions: {
numZoomLevels: 1,
units: "m",
minExtent: map.maxExtent.clone()
}
});
map.addControl(overview);
#if $m.web.metadata.get('mmOT').count("MMOVMapFixed")
if(System.initZoomLevel-3>=0){
overview.maxRatio=map.getResolutionForZoom(System.initZoomLevel-4)/map.getResolutionForZoom(19);
overview.minRatio=map.getResolutionForZoom(System.initZoomLevel-1)/map.getResolutionForZoom(0);
}
#end if
<|start_filename|>mapmint-ui/new-themes/themes/default/paginate.css<|end_filename|>
.jPaginate{
height:40px;
position:fixed;
bottom:50px;
color:#a5a5a5;
font-size:small;
width:100%;
background:url(../img/wbg.png) repeat-x;
}
.jPaginate a{
line-height:15px;
height:18px;
cursor:pointer;
padding:2px 5px;
margin:2px;
float:left;
}
.jPag-control-back{
position:absolute;
left:0px;
padding:7px 0 0 5px;
}
.jPag-control-front{
position:absolute;
top:0px;
padding:7px 0 0 5px;
}
.jPaginate span{
cursor:pointer;
}
ul.jPag-pages{
float:left;
list-style-type:none;
margin:0 auto;
padding:7px 0 0 5px;
}
ul.jPag-pages li{
display:inline;
float:left;
padding:0px;
margin:0px;
}
ul.jPag-pages li a{
float:left;
padding:2px 5px;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
span.jPag-current{
cursor:default;
font-weight:normal;
line-height:15px;
height:18px;
padding:2px 5px;
margin:2px;
float:left;
padding:2px 5px;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
ul.jPag-pages li span.jPag-previous,
ul.jPag-pages li span.jPag-next,
span.jPag-sprevious,
span.jPag-snext,
ul.jPag-pages li span.jPag-previous-img,
ul.jPag-pages li span.jPag-next-img,
span.jPag-sprevious-img,
span.jPag-snext-img{
height:22px;
margin:2px;
float:left;
line-height:18px;
}
ul.jPag-pages li span.jPag-previous,
ul.jPag-pages li span.jPag-previous-img{
margin:2px 0px 2px 2px;
font-size:12px;
font-weight:bold;
width:10px;
}
ul.jPag-pages li span.jPag-next,
ul.jPag-pages li span.jPag-next-img{
margin:2px 2px 2px 0px;
font-size:12px;
font-weight:bold;
width:10px;
}
span.jPag-sprevious,
span.jPag-sprevious-img{
margin:2px 0px 2px 2px;
font-size:18px;
width:15px;
text-align:right;
}
span.jPag-snext,
span.jPag-snext-img{
margin:2px 2px 2px 0px;
font-size:18px;
width:15px;
text-align:right;
}
.jPag-first{
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
.jPag-last{
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
<|start_filename|>mapmint-services/vector-converter-src/Makefile<|end_filename|>
PREFIX=/usr/local
XSLT_LDFLAGS=-lxslt -lxml2
ZOO_FILE=/home/src/zoo/zoo-project/zoo-kernel/service_internal_ms.o
ZOO_DIR=/home/src/zoo/zoo-project/zoo-kernel
ZRPATH=/home/src/zoo/zoo-project/zoo-kernel/../
include ${ZOO_DIR}/ZOOMakefile.opts
CPPFLAGS := -DZOO_SERVICE -DUSE_CAIRO -DUSE_KML -DUSE_MS -I${ZOO_DIR}
BIN_LIST = cgi-env/service.zo
default : $(BIN_LIST)
cgi-env/service.zo: service.c
g++ -I${INST_INCLUDE} ${GDAL_CFLAGS} ${MS_CFLAGS} ${CPPFLAGS} $(CFLAGS) $(CPPFLAGS) -shared -fpic $< ${ZOO_LDFLAGS} ${GDAL_LIBS} ${MACOS_LD_NET_FLAGS} ${MS_LDFLAGS} ${MACOS_CFLAGS} ${MACOS_LD_FLAGS} -L${INST_LIB} -lzoo_service -o $@
install:
install -d ${PREFIX}/vector-converter/
cd ${PREFIX}/vector-converter/ && ln -s ../main.cfg
cd ${PREFIX}/vector-converter/ && ln -s ../ZOO-api.js
cd ${PREFIX}/vector-converter/ && ln -s ../ZOO-proj4js.js
install $(BIN_LIST) ${PREFIX}/vector-converter/
install cgi-env/*.zcfg ${PREFIX}/vector-converter/
install cgi-env/*.py ${PREFIX}/vector-converter/
install cgi-env/*.js ${PREFIX}/vector-converter/
clean :
rm -f cgi-env/*zo
<|start_filename|>mapmint-ui/templates/Publisher/confirmRemove_bs.html<|end_filename|>
#encoding UTF-8
#import zoo
<div class="warning">
<h1>$zoo._("Do you really want to remove") $conf["senv"]["last_map"] ?</h1>
<p>$zoo._("Once removed, you cannot access the project anymore. You cannot recover a removed project. Deleting a project may destroy important data and make other projects unstable.")</p>
</div>
<|start_filename|>mapmint-ui/templates/Manager/TemplateEditor_bs.html<|end_filename|>
#import zoo
#def printSelect(name,title,options)
<div class="form-group">
<label class="col-md-4 control-label">$title</label>
<div class="col-md-8">
<select name="$name" class="form-control #if $options is None# mmField#end if#" >
#if $options is not None
#for i in $options
<option value="$i[0]">$i[1]</option>
#end for
#else
<option value="-1">$zoo._("Choose")</option>
#end if
</select>
</div>
</div>
#end def
<form class="form-horizontal mtpp" method="get" >
$printSelect("case",$zoo._("Choose case"),[["over",$zoo._("On feature over")],["click",$zoo._("On Click")]])
$printSelect("field",$zoo._("Field"),None)
<div class="col-md-12">
<textarea name="editor" class="mm-editor"></textarea>
</div>
<button class="btn btn-default mm-layer-save" href="#" >$zoo._("Save")</button>
</form>
<|start_filename|>mapmint-ui/templates/Distiller/wfs/display_bs.html<|end_filename|>
#import zoo
#set tmpl=$conf['main']['templatesPath']+"/Distiller/form_line.html"
#include $tmpl
#set ftmpl=$self._CHEETAH__cheetahIncludes[$tmpl]
<div id="add-wfs-dialog">
<h2>$zoo._("Add OGC Server")</h2>
<div>
<form class="form-horizontal mtpp" >
$ftmpl.printLine({"id":"name","name":$zoo._("Name")})
$ftmpl.printLine({"id":"url","name":$zoo._("URL")})
$ftmpl.printLine({"id":"type","name":$zoo._("Type"),"type":"select","options":["WMS","WFS"]})
$ftmpl.printButton({"id":"test","name":$zoo._("Test")})
$ftmpl.printButton({"id":"add","name":$zoo._("Add")})
</form>
</div>
</div>
<|start_filename|>mapmint-ui/new-themes/themes/default/toolbars.css<|end_filename|>
/*
* MapMint toolbars CSS
*/
#nav {
position:relative;
top:28px;
left:50px;
margin: 0;
padding:0;
background: transparent;
border:0;
font-size:.85em;
text-transform:uppercase;
float:left;
}
#nav li {
margin: 0 5px;
padding: 0 0 8px;
float: left;
position: relative;
list-style: none;
}
.toolbar, .toolbar2{background:#E8E8E8;width:100%;margin:0;padding:0;height:35px;}
.toolbar-noborder{background:transparent;width:100%;margin:4px 0;padding:0;}
a.fg-button {background:#ffffff;float:left;width:26px;height:26px;margin:0 0 0 5px;padding:0; text-decoration:none !important; cursor:pointer; position: relative; text-align: center;border:1px solid #FFFFFF;}
a.fg-button:hover {border:1px solid #a5a5a5;}
a.fg-button-s {background:#E9E9E9;float:left;width:20px;height:20px;margin:0 0 0 5px;padding:0; text-decoration:none !important; cursor:pointer; position: relative; text-align: center;}
a.fg-button:hover {background:#FFFFFF;}
a.butt{font-size:.95em;text-decoration:none;border:1px solid #D3D3D3;padding:4px;color:#777777;position:relative;top:5px;left:0px;text-shadow:#E9E9E9 0 1px 0;}
a.save-as-map{font-size:.85em;text-decoration:none;border:1px solid #adadad;padding:4px;color:#777777;position:relative;top:3px;left:20px;text-shadow:#E9E9E9 0 1px 0;}
span.save-as-map{font-size:.85em;text-decoration:none;border:1px solid #adadad;padding:4px;color:#777777;position:relative;top:3px;left:10px;}
a.view-site{font-size:.8em;text-decoration:none;border:1px solid #888888;padding:4px;color:#777777;position:relative;top:1px;left:20px;text-shadow:#E9E9E9 0 1px 0;}
a.view-all-project, a.view-all-docs{float:right;font-size:.8em;text-decoration:none;border:1px solid #888888;padding:4px;color:#777777;position:relative;top:0;right:10px;text-shadow:#E9E9E9 0 1px 0;}
a.preview, a.export{font-size:.8em;text-decoration:none;border:1px solid #888888;padding:4px;color:#777777;position:relative;top:0;left:5px;text-shadow:#E9E9E9 0 1px 0;}
ul.nav-toolbar {position:absolute;top:100px;left:5px;margin:0;padding:2px;list-style:none;z-index:1000000000;width:32px;height:57px;background:url(../img/bcknav.png);border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius: 5px;
behavior: url(js/ie-css3.htc);
}
ul.nav-toolbar li a{margin: 3px 0 3px 5px;}
.dropdown-toolbars {width:150px;max-width:150px;margin:0;padding:0;font-size:.8em;font-weight:normal;position:absolute;left:250px;}
.dropdown-toolbars dd, .dropdown-toolbars dt, .dropdown-toolbars ul {margin:0px; padding:0px;font-weight:normal;}
.dropdown-toolbars dd {position:absolute;}
.dropdown-toolbars a, .dropdown a:visited {color:#777777; text-decoration:none;outline:none;width:140px;max-width:140px;padding:0;}
.dropdown-toolbars a:hover {color:#333333;width:140px;max-width:140px;}
.dropdown-toolbars dt a:hover {color:#000000;border:1px solid #7d7d7d;}
.dropdown-toolbars dt a {background:#E0E0E0 url(../img/arrow.png) no-repeat scroll right center; display:block; padding-right:10px;border:1px solid #8F8F8F; width:140px;}
.dropdown-toolbars dt a:hover {background:#E4E4E4 url(../img/arrow.png) no-repeat scroll right center; }
.dropdown-toolbars dt a span {cursor:pointer; display:block;padding:4px;}
.dropdown-toolbars dd ul {font-size:.95em;z-index:10000000000;color:#333333; display:none;left:0px; padding:5px 0px; position:absolute; top:2px; width:130px; min-width:130px; list-style:none; background:#f0f0f0; -moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
margin:0;
border:1px solid #ccc;
overflow:hidden;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
behavior: url(js/ie-css3.htc);
}
.dropdown-toolbars span.value { display:none;}
.dropdown-toolbars dd ul li a { padding:5px; display:block;width:120px;max-width:120px;cursor:pointer;}
.dropdown-toolbars dd ul li a:hover { background-color:#C5C5C5;width:120px;max-width:120px;cursor:pointer;}
.dropdown-toolbars dd ul li a label{cursor:pointer;}
#editing-toolbar.window-body, #spatial-toolbar.window-body, #raster-toolbar.window-body, #terrain-toolbar.window-body {
padding:0px;border:0;background: -moz-linear-gradient(top, #B6B6B6, #c7c7c7);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E2E2E2', endColorstr='#B6B6B6');}
.base_layer{
position: relative;
z-index: 1010;
width: 24px;
height: 24px;
float: left;
}
#base_layers{
z-index: 1010;
position: absolute;
right: 250px;
top:20px;
}
#base_layer_Map{
background: url(../img/mapquest-str.png) no-repeat;
margin:0 0 0 5px;
border:1px solid #CDCDCD;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
behavior: url(js/ie-css3.htc);
cursor:pointer;}
#base_layer_Aerial{
background: url(../img/mapquest-sat.png) no-repeat;
margin:0 0 0 5px;
border:1px solid #CDCDCD;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
behavior: url(js/ie-css3.htc);
cursor:pointer;
}
#base_layer_OSM{
background: url(../img/osm.png) no-repeat;
margin:0 0 0 5px;
border:1px solid #CDCDCD;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
behavior: url(js/ie-css3.htc);
cursor:pointer;}
<|start_filename|>mapmint-ui/new-themes/themes/green/toolbars.css<|end_filename|>
a.butt:hover{color:#FFFFFF;position:relative;top:5px;left:0px;text-shadow:#333333 0 1px 0;
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
background: -ms-linear-gradient(#C2FF7E, #4FA33F);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
}
a.save-as-map:hover{color:#FFFFFF;position:relative;top:1px;left:20px;text-shadow:#333333 0 1px 0;background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
background: -ms-linear-gradient(#C2FF7E, #4FA33F);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
}
a.view-site:hover{color:#FFFFFF;position:relative;top:1px;left:20px;text-shadow:#333333 0 1px 0;background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
background: -ms-linear-gradient(#C2FF7E, #4FA33F);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');}
a.view-all-project:hover, a.view-all-docs:hover{color:#FFFFFF;position:relative;top:0;right:10px;text-shadow:#333333 0 1px 0;background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
background: -ms-linear-gradient(#C2FF7E, #4FA33F);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
}
a.preview:hover, a.export:hover{color:#FFFFFF;position:relative;top:0;left:5px;text-shadow:#333333 0 1px 0;background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
background: -ms-linear-gradient(#C2FF7E, #4FA33F);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
}
<|start_filename|>mapmint-ui/templates/Georeferencer/CropeImage_bs.html<|end_filename|>
#encoding "utf-8"
#import zoo
<li id="layerswitcher">
<a class="mmaction" role="tab" href="#distDataSources" data-toggle="tab"><i class="fa fa-folder fa-fw"></i> $zoo._("Georeference")<span class="fa arrow"></span></a>
<ul class="nav nav-second-level collapse" id="geoForm">
<li class="col-xs-12">
<label for="diro">$zoo._("Datastore")</label>
</li>
<li class="col-xs-12">
#import datastores.service as ds
#import mapfile.service as ms
#set outputs={"Result":{"value":""}}
#set tt=ds.list($conf,$inputs,$outputs)
#set elements=eval($outputs["Result"]["value"])
<select id="diro">
#for ij in $elements
#if $ij!="WFS" and $ij!="PostGIS"
<option disabled="true" style="font-weight: bold;color: #111">$ij</option>
#for jk in $elements[$ij]
<option>$jk.name</option>
#end for
#end if
#end for
</select>
</li>
<li class="col-xs-12">
<label for="filename">Filename </label>
</li>
<li class="col-xs-12">
<input id="filename" value="" />
</li>
<li class="col-xs-12">
<input type="submit" value="Save" onclick=try{cropImage()}catch(e){alert(e)};return false;" />
</li>
</ul>
</li>
<|start_filename|>mapmint-ui/js/DistillerOld.js<|end_filename|>
function loadFormWithObject(form,fields,object){
var dbParams=fields;
if(!object){
for(var t=0;t<dbParams[t];t++){
if($mj(form+"."+dbParams[t])){
if(t!="stype")
$mj(form+"."+dbParams[t]).value="";
else
try{$mj(form+"."+dbParams[t]).selectedIndex=-1;}catch(e){}
}
}
}else{
var tmp=object;
for(var t in tmp){
if($mj(form+"."+t)){
$mj(form+"."+t).value=tmp[t];
}
}
}
}
MapMintDBManager=Class.create({
initializeAddWindow: function(){
var dsType=arguments[0];
var dsName=arguments[1];
if(!Distiller.windows["add-database-dialog"]){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=template&service=WPS&version=1.0.0&request=Execute&Identifier=display&DataInputs=tmpl=Distiller_db_display&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
try{
$( 'body').append(xml.responseText);
if(!Distiller.windows)
Distiller.windows={};
if(!Distiller.windows["add-database-dialog"]){
Distiller.windows["add-database-dialog"]=true;
$( "#add-database-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
$("#dlg-buttons a").button();
}
if(dsName!=null && dsType!=null){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=load&DataInputs=type="+dsType+";name="+dsName+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
try{
var tmp=eval('('+xml.responseText+')');
loadFormWithObject("Distiller.pgisform",
Array("name","dbname","host","port",
"password","user","stype"),
tmp);
}catch(e){alert(e);}
}
});
}else{
loadFormWithObject("Distiller.pgisform",
Array("name","dbname","host","port",
"password","user","stype"));
}
}catch(e){alert(e);}
}
});
}else{
$( "#add-database-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
if(dsName!=null && dsType!=null){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=load&DataInputs=type="+dsType+";name="+dsName+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
try{
var tmp=eval('('+xml.responseText+')');
loadFormWithObject("Distiller.pgisform",
Array("name","dbname","host","port",
"password","user","stype"),
tmp);
}catch(e){alert(e);}
}
});
}else{
loadFormWithObject("Distiller.pgisform",
Array("name","dbname","host","port",
"password","user","stype"));
}
}
},
commit: function(){
if (arguments[0]=='cancel'){
confirm('Delete ' + $('.trSelected',grid).length + ' items?');
}
else if (arguments[0]=='add'){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=save&DataInputs=name="+$mj("Distiller.pgisform.name").value+";dbname="+$mj("Distiller.pgisform.dbname").value+";user="+$mj("Distiller.pgisform.user").value+";password="+$mj("<PASSWORD>").value+";host="+$mj("Distiller.pgisform.host").value+";port="+$mj("Distiller.pgisform.port").value+";type="+$mj("Distiller.pgisform.stype").value,
dataType: "xml",
complete: function(xml,status) {
$('#add-database-dialog').window('close');
MapMintDBManager.refresh($mj("Distiller.pgisform.stype").value);
}
});
}
},
refresh: function(){
var localArg=arguments[0];
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=displayJson&DataInputs=type="+arguments[0]+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
var tmp=null;
try{
tmp=eval("("+xml.responseText+")");
}catch(e){}
var myData=[];
if(tmp!=null)
for(var i=0;i<tmp.sub_elements.length;i++){
myData[i]={id: "browseDirectoriesList"+tmp.sub_elements[i].name, text: tmp.sub_elements[i].name, state: "open"};
}
var child;
var stype=(tmp==null?((localArg=="PostGIS")?"postgisList":(localArg=="MySQL"?"mysqlList":"")):((tmp.name=="PostGIS")?"postgisList":(tmp.name=="MySQL"?"mysqlList":"")));
child=$("#browser").tree('getChildren',$("#browser").tree('find',stype).target);
try{
$("#browser").tree('append',{parent: $("#browser").tree('find',stype).target,data: myData});
}catch(e){}
for(i=0;i<child.length;i++){
$("#browser").tree('remove',child[i].target);
}
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
},
test: function(){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=test&DataInputs=name="+$mj("Distiller.pgisform.name").value+";dbname="+$mj("Distiller.pgisform.dbname").value+";user="+$mj("Distiller.pgisform.user").value+";password="+$mj("<PASSWORD>").value+";host="+$mj("Distiller.pgisform.host").value+";port="+$mj("Distiller.pgisform.port").value+";type="+$mj("Distiller.pgisform.stype").value,
dataType: "text",
complete: function(xml,status) {
var tmp=$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp!="")
$.notifyBar({ cls: "error", html: tmp });
else
$.notifyBar({ cls: "success", html: $(xml.responseXML).find("wps\\:LiteralData").text() });
}
});
},
remove: function(){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=delete&DataInputs=name="+$mj("Distiller.pgisrform.name").value+";type="+$mj("Distiller.pgisrform.stype").value,
dataType: "text",
complete: function(xml,status) {
var tmp=$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp!="")
$.notifyBar({ cls: "error", html: tmp });
else
$.notifyBar({ cls: "success", html: $(xml.responseXML).find("wps\\:LiteralData").text() });
$( "#delete-database-dialog" ).window('close');
MapMintDBManager.refresh($mj("Distiller.pgisrform.stype").value);
}
});
},
initializeRemoveWindow: function(){
var dsType=$('#browser_selected_type')[0].value.replace(/List/,"");
var dsName=$('#browser_selected_dsName')[0].value.replace(/browseDirectoriesList/,"");
if(dsType=="postgis" || dsType=="mysql"){
dsType=(dsType=="mysql"?"MySQL":"PostGIS");
Distiller.loadDbFormValues(null);
}
if(!Distiller.windows["delete-database-dialog"]){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=template&service=WPS&version=1.0.0&request=Execute&Identifier=display&DataInputs=tmpl=Distiller_db_remove&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
$( 'body').append(xml.responseText);
if(!Distiller.windows)
Distiller.windows={};
if(!Distiller.windows["delete-database-dialog"]){
Distiller.windows["delete-database-dialog"]=true;
$( "#delete-database-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
$("#dlgr-buttons a").button();
loadFormWithObject("Distiller.pgisform",
Array("name"));
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=load&DataInputs=type="+dsType+";name="+dsName+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status){
var tmp=eval('('+xml.responseText+')');
loadFormWithObject("Distiller.pgisrform",
Array("name"),
tmp);
}
});
}
}
});
}else{
$( "#delete-database-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
loadFormWithObject("Distiller.pgisform",
Array("name"));
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=load&DataInputs=type="+dsType+";name="+dsName+"&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status){
var tmp=eval('('+xml.responseText+')');
loadFormWithObject("Distiller.pgisrform",
Array("name"),
tmp);
}
});
}
}
});
Distiller=MLayout.extend({
id: 0,
cnt: 0,
dataTypes: [],
args: [],
windows: [],
initializeDirWindow: function(){
var localThis=arguments[0];
if(!Distiller.windows["dialog-directory-new"]){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=template&service=WPS&version=1.0.0&request=Execute&Identifier=display&DataInputs=tmpl=Datastore_dirs_display&RawDataOutput=Result",
dataType: "text",
complete: function(xml,status) {
try{
$( 'body').append(xml.responseText);
if(!Distiller.windows)
Distiller.windows={};
if(!Distiller.windows["dialog-directory-new"]){
Distiller.windows["dialog-directory-new"]=true;
$(".dialog-directory-new").dialog({
autoOpen: false,
height: 400,
width: 500,
resizable: false
});
}
localThis.loadDir("/","default");
$( '.dialog-directory-new').dialog("open");
}catch(e){alert(e);}
}
});
}else{
$( '.dialog-directory-new').dialog("open");
}
},
editDataStore: function(){
var dsType=$('#browser_selected_type')[0].value.replace(/List/,"");
var dsName=$('#browser_selected_dsName')[0].value.replace(/browseDirectoriesList/,"");
if(dsType=="postgis" || dsType=="mysql"){
MapMintDBManager.initializeAddWindow((dsType=="mysql"?"MySQL":"PostGIS"),
dsName);
loadFormWithObject("Distiller.pgisform",
Array("name","dbname","host","port",
"password","user","stype"));
//Distiller.loadDbFormValues(null);
}
else
Distiller.initializeDirWindow();
},
directoriesListRefresh: function(){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/directories&service=WPS&version=1.0.0&request=Execute&Identifier=list&DataInputs=&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
if($mj("directoriesListing"))
$mj("directoriesListing").parentNode.removeChild($mj("directoriesListing"));
$('#mainDirectoriesList').append(xml.responseText);
cLayout.refresh();
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
},
DatasourceDirCommit: function(){
if (arguments[0]=='cancel'){
confirm('Delete ' + $('.trSelected',grid).length + ' items?')
}
else if (arguments[0]=='add'){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/directories&service=WPS&version=1.0.0&request=Execute&Identifier=saveDir&DataInputs=name="+$mj("Distiller.form.name").value+";path="+$mj("Distiller.form.path").value+";type="+$("input[name=Distiller.form.type]:checked")[0].value+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
Distiller.directoriesListRefresh();
}
});
}
},
loadDir: function(){
if(!Distiller.references)
Distiller.references=[];
Distiller.unloadDir(arguments[0]);
for(var i=0;i<Distiller.references.length;i++)
if(arguments[0]==Distiller.references[i])
return;
$.ajax({
dwDataSource: arguments[0],
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=vector-tools&service=WPS&version=1.0.0&request=Execute&Identifier=mmExtractVectorInfo&DataInputs=dataSource="+arguments[0].replace(/__/g,"/")+(arguments.length>1?";type="+arguments[1]:"")+"&RawDataOutput=Result",
dataType: 'xml',
complete: function(xml,status){
try{
var tmp=$.xmlToJSON(xml.responseXML);
var localTmp=[];
var tt="";
for(var i=0;i<tmp.name.length;i++){
localTmp[i]=tmp.name[i].Text;
tt+=i+" = "+localTmp[i]+"\n";
}
}catch(e){alert("MM Error : "+e);}
var localCnt;
if(localTmp)
for(var localI=0;localI<localTmp.length;localI++){
var localTmp1=localTmp[localI];
var localCnt=Distiller.cnt;
//Distiller.references[Distiller.cnt]=localTmp[localI];
$.ajax({
dwDataSource: this.dwDataSource,
dwLayer: localTmp[localI],
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=vector-tools&service=WPS&version=1.0.0&request=Execute&Identifier=mmExtractVectorInfo&DataInputs=dataSource="+this.dwDataSource.replace(/__/g,"/")+";layer="+localTmp[localI]+"&RawDataOutput=Result",
dataType: 'xml',
complete: function(xml,status) {
colModel=[];
fields=[];
try{
var tmp=$.xmlToJSON(xml.responseXML);
var nbCol=0;
for(i=0;i<tmp.fields.length;i++){
for(j=0;j<tmp.fields[i].field.length;j++){
colModel[nbCol]={display: tmp.fields[i].field[j].id[0].Text, name : tmp.fields[i].field[j].id[0].Text, width: (nbCol==0?80:120), sortable : true, align: 'center'};
fields[nbCol]=tmp.fields[i].field[j].id[0].Text;
nbCol++;
}
}
$('#datasources-container-id').append('<table id="flex'+(Distiller.cnt)+'" style="display:none"></table>');
Distiller.references[Distiller.cnt]=this.dwDataSource.replace(/__/g,"/");
$("#flex"+(Distiller.cnt)).flexigrid({
autoload: false,
url: '/cgi-bin/zoo_loader.cgi',
dataType: 'xml',
colModel: colModel,
usepager: (tmp.featureCount[0].Text>10?true:false),
sortname: tmp.fields[0].field[0].id[0].Text,
sortorder: "asc",
fields: fields,
dwDataSource: this.dwDataSource.replace(/__/g,"/"),
dwLayer: this.dwLayer,
dwDataType: (tmp.geometry[0].Text=='Polygon'?'polygon':(tmp.geometry[0].Text=='Point'?'point':'line')),
nbElements: tmp.featureCount[0].Text,
title: this.dwDataSource.replace(/__/g,"/")+" / "+tmp.name[0].Text.replace(/__/g,"/"),
useLimit: true,
limit: 10,
showTableToggleBtn: true,
tableToggleBtns:
[
{title: "Delete",name: 'delete'},
{name: 'open-in-manager', title: "Open in Manager"},
{name: 'download',title: 'Download'},
{name: 'preview',title: 'Preview'},
{name: 'reproject',title: 'Change projection',content: '<a href="#" class="change-srs">EPSG:4326</a>'},
{name: 'convert', title: 'Change format', content: '<a href="#" class="change-format">SHP</a>',onclick: function () {
alert('ok');
$( "#change-format-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
})}}
],
width: "100%",
height: 290
});
Distiller.cnt+=1;
System.flexi_cnt=Distiller.cnt;
$('.flexigrid').addClass('hideBody');
}catch(e){alert("MM Error : "+e);}
}
});
}
}
});
},
unloadDir: function(){
arguments[0]=arguments[0].replace(/__/g,"/");
if(Distiller.references)
for(var i=0;i<Distiller.references.length;i++){
try{
//alert(Distiller.references[i]+" "+arguments[0])
if(Distiller.references[i]==arguments[0] && $mj('flex'+i)){
$mj('flex'+i).style.display=($mj('flex'+i).style.display=='none'?'block':'none');//parentNode.removeChild($mj('flex'+i));
//Distiller.references[i]="";
}
}catch(e){alert("MM Error: "+e);}
}
},
last_dir: null
});
Distiller.define({
loadDir: function(){
Distiller.last_dir=arguments[0];
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/directories&service=WPS&version=1.0.0&request=Execute&Identifier=list&DataInputs=dir="+Distiller.last_dir+(arguments.length>1?";type="+arguments[1]:"")+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
var reg=/\//g;
var tmpId='#browseDirectoriesList'+Distiller.last_dir.replace(reg,"_");
$(tmpId).append('<h1>HeyHo</h1>');
if(Distiller.last_dir=='/')
$(tmpId).html('<ul id="browser4DirectoriesList'+Distiller.last_dir.replace(reg,'_')+'" class="filetree treeview" style="height: 185px;overflow:auto;"><li class="collapsable lastCollapsable"><div class="hitarea expandable-hitarea" onclick=""></div>'+'<span class="folder">Directory '+Distiller.last_dir+': </span>'+xml.responseText+'</li></ul>');
else
$(tmpId).append(xml.responseText);
$('#progress_bar .ui-progress').css('width', '95%');
if(!Distiller.browser4DirectoriesList)
Distiller.browser4DirectoriesList=$("#browser4DirectoriesList_").tree({
checkbox: true,
onClick:function(node){
//$("#"+node.id).append("<h1>HeyHo</h1>");
$("#browser4DirectoriesList_").tree('append',{parent: $('#browser4DirectoriesList_').tree('getSelected').target,
data:[
{
"id": 13,
"text":"Raspberry"
},{
"id": 14,
"text":"Cantaloupe"
}
]});
layouts[0].loadDir(node.id.replace("browseDirectoriesList","").replace(/_/g,"/"));
},
onCheck: function(node,check){
if(check)
Distiller.loadDir(node.id);
else
Distiller.unloadDir(node.id);
}
});
/*$("#directoriesList/"+Distiller.last_dir).tree({checkbox: true,
onClick:function(node){
//alert("hehe"+node.id);
}});*/
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
},
initialize: function(){
$(".addDB-toolbar dt a").click(function() {
$(".addDB-toolbar dd ul").show('slow');
});
$(".addDB-toolbar dd ul").mouseleave(function() {
$(".addDB-toolbar dd ul").hide('slow');
});
Distiller.dataTypes[0]={type: 'MySQL',loaded: false};
Distiller.dataTypes[1]={type: 'PostGIS',loaded: false};
Distiller.dataTypes[2]={type: 'dir',loaded: false};
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=list&DataInputs=type=MySQL&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
Distiller.dataTypes[0]['loaded']=true;
$('#progress_bar .ui-progress').css('width', '65%');
$('#mysqlList').append(xml.responseText);
cLayout.refresh();
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=list&DataInputs=type=PostGIS&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
Distiller.dataTypes[1]['loaded']=true;
$('#progress_bar .ui-progress').css('width', '65%');
$('#postgisList').append(xml.responseText);
cLayout.refresh();
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/directories&service=WPS&version=1.0.0&request=Execute&Identifier=list&DataInputs=state=open&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
Distiller.dataTypes[2]['loaded']=true;
$('#progress_bar .ui-progress').css('width', '65%');
$('#mainDirectoriesList').append(xml.responseText);
cLayout.refresh();
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
//this.loadDir("/","default");
function test(com,grid)
{
if (com=='Delete')
{
confirm('Delete ' + $('.trSelected',grid).length + ' items?')
}
else if (com=='Add')
{
alert('Add New Item');
}
}
$('b.top').click
(
function ()
{
$(this).parent().toggleClass('fh');
}
);
var localThis=this;
$('.dir').button({
text: false
}).click(function() {
Distiller.initializeDirWindow(localThis);
});
$('.db').button({
text: false
}).click(function() {
MapMintDBManager.initializeAddWindow();
});
},
refresh: function(){
$('.add-layer-vector, .add-layer-raster, .add-layer-wms, .add-layer-wfs, .add-layer-wcs').button({text: false});
$('a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
try{
for(var i=0;i<Distiller.dataTypes.length;i++)
if(Distiller.dataTypes[i].loaded==false)
return -1;
$("#browser").tree({
checkbox: true,
onCheck:function(node, checked){
//alert(node.id+" "+checked);
reg=/browseDirectoriesList/;
if(checked)
Distiller.loadDir((node.id+'').replace(reg,""));
else
Distiller.unloadDir((node.id+'').replace(reg,""));
},
onContextMenu: function(e, node){
if($("#browser").tree('isLeaf',node.target)){
e.preventDefault();
var parentName=$("#browser").tree('getParent',node.target).id;
$('#browser_selected_type')[0].value=parentName;
$('#browser_selected_dsName')[0].value=node.id;
$('#browser').tree('select', node.target);
$('#browser_menu').menu('show', {
left: e.pageX,
top: e.pageY
});
}
}
}
);
$("#browser4DirectoriesList"+Distiller.last_dir).tree();
}catch(e){alert("Tree error"+e);}
}
});
<|start_filename|>mapmint-ui/templates/preview/modules/addLayer/_init.js<|end_filename|>
\$("#overlays_list").find("li").each(function(){
var tmp=\$(this).attr('iconCls');
\$(this).attr('iconCls',tmp.replace(/layer_/g,"overlays_layer_"));
});
try{
\$("#overlays_list").tree({
checkbox: true
});
\$(".tree_overlays_layer_class").next().hide();
WMSList=\$("#wms_list").tree({
checkbox: true
});
}catch(e){}
\$("#overlays_list").css({"height": ((\$(window).height()/2)-(125))+"px"});
\$("#tabs li").click(function() {
\$("#tabs li").removeClass('active');
\$(this).addClass("active");
\$(".tab_content").hide();
var selected_tab = \$(this).find("a").attr("href");
\$(selected_tab).fadeIn();
return false;
});
\$(".ls-button").click(function(){
var myelement = \$(this).attr("href")
if(myelement!="#layerswitcher")
\$(myelement).toggle();
\$(".ipannel:visible").not(myelement).hide();
});
<|start_filename|>mapmint-ui/new-themes/themes/pink/icons.css<|end_filename|>
/*
* MapMint Icons CSS
*/
.maincfg1 {border:1px solid #8f8f8f;background-image:url(../img/monitor-pink.png) !important;}
.maincfg2 {border:1px solid #8f8f8f;background-image:url(../img/security-pink.png) !important;}
.maincfg3 {border:1px solid #8f8f8f;background-image:url(../img/user-pink.png) !important;}
.projects {border:1px solid #8f8f8f;background-image:url(../img/process-pink.png) !important;}
.documents {border:1px solid #8f8f8f;background-image:url(../img/docs-pink.png) !important;}
.add-database {border:1px solid #8f8f8f;background-image:url(../img/add-database-default-pink.png) !important;}
.add-directory {border:1px solid #8f8f8f;background-image:url(../img/add-directory-default-pink.png) !important;}
.add-vector {border:1px solid #8f8f8f;background-image:url(../img/add-vector-pink.png) !important;}
.add-raster {border:1px solid #8f8f8f;background-image:url(../img/add-raster-pink.png) !important;}
.add-wms {border:1px solid #8f8f8f;background-image:url(../img/add-wms-pink.png) !important;}
.add-wfs {border:1px solid #8f8f8f;background-image:url(../img/add-wfs-pink.png) !important;}
.add-wcs {border:1px solid #8f8f8f;background-image:url(../img/add-wcs-pink.png) !important;}
.add-layer {border:1px solid #8f8f8f;background-image:url(../img/add-layer-pink.png) !important;}
.open-map {border:1px solid #8f8f8f;background-image:url(../img/open-map-pink.png) !important;}
.pan {border:1px solid #8f8f8f;background-image:url(../img/pan-pink.png) !important;}
.zoom-box {border:1px solid #8f8f8f;background-image:url(../img/zoom-in-pink.png) !important;}
.zoom-in {border:1px solid #8f8f8f;background-image:url(../img/zoomin-pink.png) !important;}
.zoom-in:hover {border:1px solid #8f8f8f;background: #73C354 url(../img/zoomin-hover-pink.png) !important;
}
.zoom-to-max-extent {border:1px solid #8f8f8f;background-image:url(../img/zoomtomaxextent-pink.png) !important;}
.zoom-to-max-extent:hover {border:1px solid #8f8f8f;background-image:url(../img/zoomtomaxextent-hover-pink.png) !important;}
.zoom-out {border:1px solid #8f8f8f;background-image:url(../img/zoomout-pink.png) !important;}
.zoom-out:hover {border:1px solid #8f8f8f;background: #73C354 url(../img/zoomout-hover-pink.png) !important;}
.zoom-to-point {border:1px solid #8f8f8f;background-image:url(../img/zoom-to-point-pink.png) !important;}
.identify {border:1px solid #8f8f8f;background-image:url(../img/identify-pink.png) !important;}
.mesure-distance {border:1px solid #8f8f8f;background-image:url(../img/ruler-pink.png) !important;}
.mesure-area {border:1px solid #8f8f8f;background-image:url(../img/ruler-crop-pink.png) !important;}
.select {border:1px solid #8f8f8f;background-image:url(../img/select-pink.png) !important;}
.edit-point {border:1px solid #8f8f8f;background-image:url(../img/edit-point-pink.png) !important;}
.edit-line {border:1px solid #8f8f8f;background-image:url(../img/edit-line-pink.png) !important;}
.edit-polygon {border:1px solid #8f8f8f;background-image:url(../img/edit-polygon-pink.png) !important;}
.delete-feature {border:1px solid #8f8f8f;background-image:url(../img/delete-feature-pink.png) !important;}
.buffer {border:1px solid #8f8f8f;background-image:url(../img/buffer-pink.png) !important;}
.centroid {border:1px solid #8f8f8f;background-image:url(../img/centroid-pink.png) !important;}
.boundary {border:1px solid #8f8f8f;background-image:url(../img/boundary-pink.png) !important;}
.convexhull {border:1px solid #8f8f8f;background-image:url(../img/convexhull-pink.png) !important;}
.simplify {border:1px solid #8f8f8f;background-image:url(../img/simplify-pink.png) !important;}
.union {border:1px solid #8f8f8f;background-image:url(../img/union-pink.png) !important;}
.intersection {border:1px solid #8f8f8f;background-image:url(../img/intersection-pink.png) !important;}
.symdifference {border:1px solid #8f8f8f;background-image:url(../img/symdifference-pink.png) !important;}
.difference {border:1px solid #8f8f8f;background-image:url(../img/difference-pink.png) !important;}
.raster-histogram {border:1px solid #8f8f8f;background-image:url(../img/raster-histogram-pink.png) !important;}
.clip-raster {border:1px solid #8f8f8f;background-image:url(../img/clip-layer-pink.png) !important;}
.merge-rasters {border:1px solid #8f8f8f;background-image:url(../img/merge-layer-pink.png) !important;}
.polygons-from-raster {border:1px solid #8f8f8f;background-image:url(../img/polygons-from-raster-pink.png) !important;}
.raster-from-csv {border:1px solid #8f8f8f;background-image:url(../img/raster-from-csv-pink.png) !important;}
.terrain-profile {border:1px solid #8f8f8f;background-image:url(../img/terrain-profile-pink.png) !important;}
.contours-from-dem {border:1px solid #8f8f8f;background-image:url(../img/contours-from-dem-pink.png) !important;}
.shaded-relief {border:1px solid #8f8f8f;background-image:url(../img/shaded-relief-pink.png) !important;}
.color-relief {border:1px solid #8f8f8f;background-image:url(../img/color-relief-pink.png) !important;}
.slope-map {border:1px solid #8f8f8f;background-image:url(../img/slope-map-pink.png) !important;}
.main-configuration {border:1px solid #8f8f8f;background-image:url(../img/process-pink.png) !important;}
.layout-settings {border:1px solid #8f8f8f;background-image:url(../img/layout-settings-pink.png) !important;}
.map-settings {border:1px solid #8f8f8f;background-image:url(../img/map-settings-pink.png) !important;}
.layers-settings {border:1px solid #8f8f8f;background-image:url(../img/layers-settings-pink.png) !important;}
.controls-settings {border:1px solid #8f8f8f;background-image:url(../img/controls-settings-pink.png) !important;}
<|start_filename|>public_map/assets/js/examples-app.js<|end_filename|>
// Filename: app.js
/*
This work was supported by a grant from the European Union's 7th Framework Programme (2007-2013)
provided for the project PublicaMundi (GA no. 609608).
*/
require(['bootstrap', 'notify']);
define([
'module', 'jquery', 'zoo',
], function(module, $, Zoo) {
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
});
var mymodal = $('#myModal');
var mynotify = $('.top-right');
function notify(text, type) {
mynotify.notify({
message: { text: text },
type: type,
}).show();
}
function showModal(title, body) {
mymodal.find('.modal-body').text('');
mymodal.find('.modal-body').append(body);
mymodal.find('.modal-title').text(title);
var options = {};
mymodal.modal(options);
}
//
var initialize = function() {
self = this;
// DescribeProcess button
$('.btn.describeprocess').on('click', function(e) {
e.preventDefault();
zoo.describeProcess({
identifier: 'longProcess',
type: 'GET',
success: function(data) {
notify('DescribeProcess success', 'success');
console.log(data);
},
error: function(data) {
notify('DescribeProcess failed', 'danger');
}
});
});
// Misc tests
$('.btn.testalert').on('click', function(e) {
e.preventDefault();
var type = this.dataset.type;
notify('This is a message.', type);
});
}
// Return public methods
return {
initialize: initialize,
};
});
<|start_filename|>mapmint-ui/new-themes/themes/blue/misc.css<|end_filename|>
.tabs-right ul li:hover, .maps-container ul li:hover {cursor:pointer;
background: -moz-linear-gradient(top, #7fe5f9 , #3d93df);
background: -webkit-gradient(linear, left top, left bottom, from(#7fe5f9), to(#3d93df));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#7fe5f9', endColorstr='#3d93df');
}
<|start_filename|>mapmint-services/symbol-tools-src/service.c<|end_filename|>
// FreeTypeParser.cpp : définit le point d'entrée pour l'application console.
//
#ifdef WIN32
#endif
#include <ft2build.h>
#include <freetype/freetype.h>
#include FT_FREETYPE_H
#include "service.h"
FT_Library library;
FT_Face face;
extern "C" {
#ifdef WIN32
__declspec(dllexport)
#endif
int getSymbols(maps*& conf,maps*& inputs,maps*& outputs)
{
FT_Error error = FT_Init_FreeType( &library );
map* tmpMap4Path=getMapFromMaps(conf,"main","dataPath");
map* tmpMap=getMapFromMaps(inputs,"ttf","value");
char ttfFile[1024];
sprintf(ttfFile,"%s/fonts/%s",tmpMap4Path->value,tmpMap->value);
fprintf(stderr,"File to open : %s\n",ttfFile);
error = FT_New_Face( library, ttfFile, 0, &face );
if ( error == FT_Err_Unknown_File_Format ){
setMapInMaps(conf,"lenv","message","Error unknow format");
return SERVICE_FAILED;
}
else if ( error ) {
setMapInMaps(conf,"lenv","message","Unable to load the specified file");
return SERVICE_FAILED;
}
//int *charcodes=(int *)malloc(face->num_glyphs*sizeof(int));
//printf("%d|",face->num_glyphs);
int n;
FT_CharMap found = 0;
FT_CharMap charmap;
int disp=0;
char *charCodes=NULL;
for ( n = 0; n < face->num_charmaps; n++ ) {
charmap = face->charmaps[n];
//printf("\nplatform_id : %d ; encoding_id %d\n",charmap->platform_id,charmap->encoding_id);
found = charmap;
error = FT_Set_Charmap( face, found );
FT_UInt agindex;
FT_ULong charcode;
charcode=FT_Get_First_Char(face,&agindex);
int count=1;
if(agindex==0){
setMapInMaps(conf,"lenv","message","Unable to find anything in your font file");
return SERVICE_FAILED;
}
else{
char tmp[100];
if(charCodes==NULL){
sprintf(tmp,"%d",charcode);
charCodes=(char*)malloc((strlen(tmp)+2)*sizeof(char));
sprintf(charCodes,"[%s",tmp);
}else{
sprintf(tmp,",%d",charcode);
char *tmp2=strdup(charCodes);
charCodes=(char*)realloc(charCodes,(strlen(tmp2)+strlen(tmp)+1)*sizeof(char));
memcpy(charCodes+strlen(tmp2),tmp,strlen(tmp)+1);
free(tmp2);
}
while ( agindex != 0 )
{
charcode = FT_Get_Next_Char( face, charcode, &agindex );
if(agindex != 0 ){
char tmp1[100];
sprintf(tmp1,",%d",charcode);
char *tmp2=strdup(charCodes);
charCodes=(char*)realloc(charCodes,(strlen(tmp2)+strlen(tmp1)+1)*sizeof(char));
memcpy(charCodes+strlen(tmp2),tmp1,strlen(tmp1)+1);
free(tmp2);
}
}
}
}
char *tmp2=strdup(charCodes);
charCodes=(char*)realloc(charCodes,(strlen(tmp2)+2)*sizeof(char));
memcpy(charCodes+strlen(tmp2),"]",2);
free(tmp2);
//printf("\n**%s**\n",charCodes);
setMapInMaps(outputs,"Result","value",charCodes);
return SERVICE_SUCCEEDED;
}
}
<|start_filename|>mapmint-ui/templates/preview/modules/routing/_init.js<|end_filename|>
#encoding UTF-8
if(!System.hover){
System.hover = new OpenLayers.Layer.Vector("DisplaySelectedFeatures", {
styleMap: new OpenLayers.Style({
fillColor:"white",
fillOpacity:0,
strokeOpacity:0,
fillColor:"white",
strokeColor:"pink",
pointRadius: 10,
strokeWidth:3
}),renderers: System.renderer
});
map.addLayer(System.hover);
}
points_layer = new OpenLayers.Layer.Vector("points");
points_layer.styleMap=new OpenLayers.StyleMap({pointRadius: 14,graphicYOffset: -24,graphicXOffset: -6,'externalGraphic': '$conf['main']['publicationUrl']/img/endMarker.png'});
points_layer.styleMap.addUniqueValueRules("default", "type", lookup);
#if $m.web.metadata.get('layout_t')!="mobile"
points_layer.events.on({
featureadded: function(e) {
var tmpFeature=e.feature.clone();
tmpFeature.attributes["idPoint"]=this.features[this.features.length-1].attributes["idPoint"];
System.hover.styleMap["select"]=System.hover.styleMap["default"];
System.hover.addFeatures([tmpFeature]);
},
featureremoved: function(e){
for(i=0;i<System.hover.features.length;i++){
if(System.hover.features[i].data["idPoint"]==e.feature.attributes["idPoint"])
System.hover.removeFeatures([System.hover.features[i]]);
}
}
});
#end if
route_layer1 = new OpenLayers.Layer.Vector("route1",{
styleMap: new OpenLayers.StyleMap(new OpenLayers.Style({
strokeColor: "red",
strokeWidth: 16
}))
});
points_layer1 = new OpenLayers.Layer.Vector("points1");
points_layer1.styleMap=new OpenLayers.StyleMap({pointRadius: 24,'externalGraphic': '$conf['main']['publicationUrl']/img/ccMarker.png'});
map.addLayers([points_layer,route_layer1,points_layer1]);
draw_points = new DrawPoints(points_layer);
OpenLayers.Control.DragFeature.prototype.overFeature = function(feature) {
var activated = false;
if(!this.handlers.drag.dragging) {
this.feature = feature;
//alert(" id point : "+this.feature.data["idPoint"]);
this.handlers.drag.activate();
activated = true;
this.over = true;
if (this.feature.data["idPoint"]) {
OpenLayers.Element.addClass(this.map.viewPortDiv, this.displayClass + "Over");
}
this.onEnter(feature);
} else {
if(this.feature.data["idPoint"] == feature.data["idPoint"]) {
this.over = true;
} else {
this.over = false;
}
}
return activated;
}
drag_points = new OpenLayers.Control.DragFeature(System.hover, {
autoActivate: false,
onStart: function(feature,pixel){
/*for(i in map.controls){
if(map.controls[i].active){
System.revActivated=map.controls[i];
map.controls[i].deactivate();
}
}*/
if(!feature.data["idPoint"]){
drag_points.handlers.drag.deactivate();
return false;
}
},
onDrag: function(feature,pixel){
if(feature.data["idPoint"]){
for(i=0;i<points_layer.features.length;i++){
//alert(points_layer.features[i].attributes["idPoint"]+"=="+feature.data["idPoint"]);
if(points_layer.features[i].attributes["idPoint"]==feature.data["idPoint"]){
//points_layer.removeFeatures([points_layer.features[i]]);
//points_layer.addFeature(feature.clone());
var newPoint = new OpenLayers.LonLat(feature.geometry.x,feature.geometry.y);
points_layer.features[i].move(newPoint);
//points_layer.refresh();
//alert(feature.geometry.x+","+feature.geometry.y);
//
//
//alert(newPoint);
//points_layer.refresh();
}
}
}
else
return false;
},
onComplete: function(feature,pixel){
for(i in map.controls){
if(map.controls[i].active){
mapControls[i].deactivate();
}
}
System.revActivated.activate();
}
});
drag_points.onComplete = function() {
#if $m.web.metadata.get('layout_t')!="mobile"
mmGeocode(draw_points,arguments[0]);
pgrouting( points_layer );
#end if
};
drag_points.handlers['drag'].stopDown = false;
drag_points.handlers['drag'].stopUp = false;
drag_points.handlers['drag'].stopClick = false;
drag_points.handlers['feature'].stopDown = false;
drag_points.handlers['feature'].stopUp = false;
drag_points.handlers['feature'].stopClick = false;
mapControls["draw_points"]=draw_points;
mapControls["drag_points"]=drag_points;
map.addControls([draw_points, drag_points]);
#if $m.web.metadata.get('layout_t')=="mobile"
toggleControl({name: "pan"});
#else
displayRoadmap(-1);
startSearch1("adresseLieu");
startSearch1("adresseDepart");
startSearch1("adresseArrivee");
startSearch1("adresseDepart_rayon");
startSearch1("adresseDepart_temps");
startSearch1("adresseDepart_theme");
startSearch1("adresseArrivee_theme");
\$("#profileInfo").tipsy({gravity: "nw"});
#end if
<|start_filename|>mapmint-ui/js/Styler.js<|end_filename|>
var tabContainers;
Styler=MLayout.extend();
Styler.define({
initialize: function(){
$("input:checkbox, input:radio, input:file").uniform();
$('.toolbar a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
},
refresh: function(){
$('.save-style').button({text: false});
$(function () {
tabContainers = $('div.tabs-styler > div');
$('.toolbar a').click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
}).filter(':first').click();
});
tabContainers.hide().filter(':first').show();
$('.point, .line, .polygon').button({text: false});
$(".dropdown dt a").click(function() {
$(".dropdown dd ul").show('slow');
});
$('.dropdown dd').mouseleave(function() {
$(".dropdown dd ul").hide();
});
$(".dropdown dd ul li a").click(function() {
var text = $(this).html();
$(".dropdown dt a span").html(text);
$(".dropdown dd ul").hide();
});
$(".dropdown-fill dt a").click(function() {
$(".dropdown-fill dd ul").show('slow');
});
$('.dropdown-fill dd ul').mouseleave(function() {
$(".dropdown-fill dd ul").hide();
});
$(".dropdown-fill dd ul li a").click(function() {
var text = $(this).html();
$(".dropdown-fill dt a span").html(text);
$(".dropdown-fill dd ul").hide();
});
$(".dropdown-stroke dt a").click(function() {
$(".dropdown-stroke dd ul").show('slow');
});
$('.dropdown-stroke dd ul').mouseleave(function() {
$(".dropdown-stroke dd ul").hide();
});
$(".dropdown-stroke dd ul li a").click(function() {
var text = $(this).html();
$(".dropdown-stroke dt a span").html(text);
$(".dropdown-stroke dd ul").hide();
});
$('#colorpickerHolder').ColorPicker({flat: true});
$('#colorpickerHolder1').ColorPicker({
flat: true,
color: '#00ff00',
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector1 div').css('backgroundColor', '#' + hex);
}
});
$('#colorpickerHolder1>div').css('position', 'absolute');
var widt = false;
$('#colorSelector1').bind('click', function() {
$('#colorpickerHolder1').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
$('#colorpickerHolder2').ColorPicker({
flat: true,
color: '#00ff00',
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector2 div').css('backgroundColor', '#' + hex);
}
});
$('#colorpickerHolder2>div').css('position', 'absolute');
var widt = false;
$('#colorSelector2').bind('click', function() {
$('#colorpickerHolder2').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
$('#colorpickerHolder3').ColorPicker({
flat: true,
color: '#00ff00',
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector3 div').css('backgroundColor', '#' + hex);
}
});
$('#colorpickerHolder3>div').css('position', 'absolute');
var widt = false;
$('#colorSelector3').bind('click', function() {
$('#colorpickerHolder3').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
$('#colorpickerField1, #colorpickerField2, #colorpickerField3').ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
$(el).val(hex);
$(el).ColorPickerHide();
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
})
.bind('keyup', function(){
$(this).ColorPickerSetColor(this.value);
});
$('#colorSelector').ColorPicker({
color: '#0000ff',
onShow: function (colpkr) {
$(colpkr).fadeIn(500);
return false;
},
onHide: function (colpkr) {
$(colpkr).fadeOut(500);
return false;
},
onChange: function (hsb, hex, rgb) {
$('#colorSelector div').css('backgroundColor', '#' + hex);
}
});
$(function() {
$( "#slider-opacity" ).slider({
value:100,
min: 0,
max: 100,
step: 1,
slide: function( event, ui ) {
$( "#amount" ).val(ui.value + "%" );
}
});
$( "#amount" ).val( $( "#slider-opacity" ).slider( "value" ) + "%" );
});
}
});
<|start_filename|>public_map/_index.css<|end_filename|>
body{margin:0;padding:0;font-family:Lucida grande;}
a{outline:none;}
input {border:1px solid #d3d3d3; outline: none;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff'); /* for IE */
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
border-radius: 4px;
}
input.rounded{width:100%;height:20px;margin:1px;border:1px solid #d3d3d3; outline: none;
background:#EBEBEB;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
input:focus, select:focus{
-webkit-box-shadow: 0px 0px 5px #9e9e9e;
-moz-box-shadow: 0px 0px 5px #9e9e9e;
}
div#map{width:100%;height:100%;margin:0;padding:0;}
div#header {position:absolute; top:10px; left:10px;width:380px;min-width:380px; height:82px;background:url('img/bckw.png'); z-index:100000000000; overflow: hidden;display:block;
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
text-shadow: #FFFFFF 0px 1px 0px;
}
div#header img.logo{float:left;position:relative;top:5px;left:5px;}
div#header h1{font-size:1.4em;margin:0;padding:5px;color:#808080;position:relative;top:0px;left:15px;}
div#ls-container{position:absolute;top:10px; right:10px;width:auto;z-index:100000000;}
div#ls-container table.slid{position:absolute;top:110px;left:100px;margin:0;padding:0;width:160px;}
div#ls-container table td.sli{width:100px;}
a.ls-toogler{float:left;background:#FFFFFF url('img/layers-icon.png');background-position:3px 2px;width:24px;height:24px;padding:display:block;z-index:10000000000;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
margin:0 7px 0 0;
}
a.ls-toogler:hover{background:#EDEDED url('img/layers-icon.png');background-position:3px 2px;width:24px;height:24px;}
div#layerswitcher {background:url('img/bckw.png'); z-index:100000000000; overflow: hidden;display:block;
-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);float:right;width:300px;height:300px;}
div#layerswitcher h2, div#zoomswitcher h2{font-size:.9em;margin:0;padding:5px;color:#808080;position:relative;top:0px;left:10px;font-weight:bold; text-shadow: #FFFFFF 0px 1px 0px;letter-spacing:2px;}
.baseLbl, .dataLbl{display:none;}
.labelSpan{padding:0 0 0 10px;font-size:.9em;}
.baseLayersDiv, .dataLayersDiv {font-size:.9em;margin:0;padding:5px;color:#808080;position:relative;top:0px;left:20px;font-weight:normal;}
/* zoommenu
----------------------------------*/
div#zoomswitcher {position:absolute;top:170px; right:10px;background:url('img/bckw.png'); z-index:100000000000; overflow: hidden;display:block;
-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);float:right;width:230px;height:auto;}
select#speedC { }
.ui-selectmenu { min-width:230px;display: block; position:relative;top:0;left:0px; height:20px; text-decoration: none; overflow:hidden;font-size:.7em;}
.ui-selectmenu-icon { position:absolute; right:6px; margin-top:-8px; top: 50%; }
.ui-selectmenu-menu { padding:0; margin:0; list-style:none; position:absolute; top: 0; visibility: hidden; overflow: auto;width:100%; }
.ui-selectmenu-open { visibility: visible; }
.ui-selectmenu-menu-popup { margin-top: -1px; }
.ui-selectmenu-menu-dropdown { z-index:1000000000000000; font-size:.7em;min-width:230px;}
.ui-selectmenu-menu li { padding:0; margin:0; display: block; border-top: 1px dotted transparent; border-bottom: 1px dotted transparent; border-right-width: 0 !important; border-left-width: 0 !important; font-weight: normal !important;}
.ui-selectmenu-menu li a,.ui-selectmenu-status {line-height: 1.1em; display:block; padding:.3em; outline:none; text-decoration:none; }
.ui-selectmenu-menu li.ui-selectmenu-hasIcon a,
.ui-selectmenu-hasIcon .ui-selectmenu-status { padding-left: 20px; position: relative; margin-left: 5px; }
.ui-selectmenu-menu li .ui-icon, .ui-selectmenu-status .ui-icon { position: absolute; top: 1em; margin-top: -8px; left: 0; }
.ui-selectmenu-status { line-height: 1.4em;}
.ui-selectmenu-open li.ui-selectmenu-item-focus a { }
.ui-selectmenu-open li.ui-selectmenu-item-selected { }
.ui-selectmenu-menu li span,.ui-selectmenu-status span { display:block; margin-bottom: .2em; }
.ui-selectmenu-menu li .ui-selectmenu-item-header { font-weight: bold; }
.ui-selectmenu-menu li .ui-selectmenu-item-content { }
.ui-selectmenu-menu li .ui-selectmenu-item-footer { opacity: .8; }
/*for optgroups*/
.ui-selectmenu-menu .ui-selectmenu-group { font-size: 1em; }
.ui-selectmenu-menu .ui-selectmenu-group .ui-selectmenu-group-label { line-height: 1.4em; display:block; padding:.6em .5em 0; font-weight: bold; }
.ui-selectmenu-menu .ui-selectmenu-group ul { margin: 0; padding: 0; }
.streetname{position:absolute;top:10px;left:500px;width:auto;background:red; z-index:100000000000; overflow: hidden;display:block;-moz-border-radius:5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
color:#FFFFFF;text-shadow: #707070 0 1px 0;
padding:10px;
font-size:.9em;
}
div#zoomTo_control {position:absolute; top:30%; left:10px; width:36px; height:172px;background:url('img/bckw.png'); z-index:100000000000; overflow: hidden; text-indent:-9999%; font-size:0; display:block; line-height:0;-moz-border-radius:5px;-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);}
div#zoomTo_control:hover {background:#FFFFFF;-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);}
div#zoomTo_control a.zoomTo_in {position:absolute; top:5px; left:5px; width:20px; height:20px;background: #E9E9E9 url('img/zoomin.png');z-index:1000000;padding:2px;-moz-border-radius:5px;border-radius:5px;-webkit-border-radius:5px;background-position: 1px 3px;border:1px solid #CCCCCC;}
div#zoomTo_control a.zoomTo_out {position:absolute; bottom:5px; left:5px; width:20px; height:20px;background: #E9E9E9 url('img/zoomout.png');z-index:1000000;padding:2px;-moz-border-radius:5px;border-radius:5px;-webkit-border-radius:5px;background-position: 1px 3px;border:1px solid #CCCCCC;}
div#zoomTo_control a.zoomTo_in:hover {background: #cccccc url('img/zoomin-hover.png');background-position: 1px 3px;}
div#zoomTo_control a.zoomTo_out:hover {background: #cccccc url('img/zoomout-hover.png');background-position: 1px 3px;}
input.opac{width:50px;padding:3px 0 0 0;border:0;background:transparent;border:0;text-indent:10px;color:#808080;}
div#zoomTo_control span.slider {position:absolute; top:34px; left:14px; height:104px; width:4px; }
div#zoomTo_control .ui-slider { position: relative; text-align: left;}
div#zoomTo_control .ui-slider .ui-slider-handle { position: absolute; z-index: 20; width:1.2em!important; height:1.2em!important; cursor: default;}
div#zoomTo_control .ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
div#zoomTo_control .ui-slider-vertical { width: .8em; height: 50px; }
div#zoomTo_control .ui-slider-vertical .ui-slider-handle { left: -7px; margin-left: 0; margin-bottom: -.6em; height:4px!important; width:16px!important;background:#E9E9E9;-moz-border-radius:2px;border-radius:2px;-webkit-border-radius:2px;border:1px solid #CCCCCC;}
div#zoomTo_control .ui-slider-vertical .ui-slider-range { left: 0; width: 100%; }
div#zoomTo_control .ui-slider-vertical .ui-slider-range-min { bottom: 0;background:#bababa; }
div#zoomTo_control .ui-slider-vertical .ui-slider-range-max { top: 0; }
div#zoomTo_control .ui-slider-vertical .ui-state-focus {cursor:pointer;}
div#zoomTo_control .ui-slider-vertical .ui-state-active {cursor:pointer;}
div#opacity_control{position:absolute; height:10px; width:130px; }
div#opacity_control span#o-slider {position:absolute;height:4px; width:100px; }
div#opacity_control .ui-slider { position: relative; text-align: left;}
div#opacity_control .ui-slider .ui-slider-handle { position: absolute; z-index: 20; width:4px!important; height:12px!important; cursor: default;}
div#opacity_control .ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
div#opacity_control .ui-slider-horizontal { width: .8em; height: 50px; }
div#opacity_control .ui-slider-handle { left: -7px; margin-left: 0; margin-bottom: -.6em; height:4px!important; width:16px!important;background:#E9E9E9;-moz-border-radius:2px;border-radius:2px;-webkit-border-radius:2px;border:1px solid #CCCCCC;}
div#opacity_control .ui-slider-horizontal .ui-slider-range { left: 0; width: 100%; }
div#opacity_control .ui-slider-horizontal .ui-slider-range-min { bottom: 0;background:#bababa; }
div#opacity_control .ui-slider-horizontal .ui-slider-range-max { top: 0; }
div#opacity_control .ui-slider-horizontal .ui-state-focus {cursor:pointer;}
div#opacity_control .ui-slider-horizontal .ui-state-active {cursor:pointer;}
ul.links{position:relative;display:block;margin:30px 0 0 30px;padding:0;font-size:.8em;}
ul.links li{list-style:none;margin:0 0 15px 0;}
ul.links li a {text-decoration:none;color:#C80020;text-shadow:#E0E0E0 0 1px 0;}
.btm{width:100%;height:40px;background: transparent url('img/bcknav.png');position:fixed;bottom:0;left:0;z-index:1000000000000;}
.btm a{margin:0 0 0 30px;padding:3px 0 0 3px;font-size:.6em;color:#FFFFFF;text-decoration:none;}
.btm a span{margin:0 0 0 30px;padding:0 0 0 3px;font-size:2em;color:#FFFFFF;font-family:arial;font-weight:bold;display:block;letter-spacing:1px;text-shadow:#333333 0 1px 0;}
.toolbar-noborder{background:transparent;width:100%;margin:0;padding:0;}
.toolbar-noborder a{margin:5px 0 5px 5px;}
.lft{float:left;width:120px;background:url('img/mm-logo.png') no-repeat;padding:3px;}
.copy{float:left;margin:0 28% 0 30%;padding:0;max-width:22%;min-width:22%;display:inline-block;}
.copy p{text-align:center;margin:0;padding:12px 0 10px 0;font-size:.7em;color:#FFFFFF;}
.copy p a.clink{color:#FFFFFF;text-decoration:none;font-size:1em;padding:0;margin:0;}
.copy p a.clink:hover{color:#FFFFFF;text-decoration:underline;font-size:1em;padding:0;margin:0;}
#coords{float:left;padding:0 5px 0 0;color:#FFFFFF;font-size:.8em;text-shadow:#333333 0 1px 0;display:inline;position:absolute;right:0;bottom:12px;}
.ls-button {
margin:0px;
margin-bottom:0;
padding:.2em;
text-decoration:none !important;
cursor:pointer;
text-align: center;
zoom: 1;
}
.fg-button {
margin:5px;
margin-bottom:0;
padding:.2em;
text-decoration:none !important;
cursor:pointer;
text-align: center;
zoom: 1;
}
.fg-button .ui-icon {
position: absolute;
width:24px;
height:24px;
}
.fg-button-tools .ui-icon {
position: absolute;
width:36px;
height:36px;
}
a.fg-button {
float:left;
}
/*important*/
button.fg-button {width:auto; overflow:visible; }
.fg-button-icon-solo {display:block; width:24px;height:24px; text-indent: -9999px; }
.fg-button-icon-solo-tools {display:block; width:36px;height:36px; text-indent: -9999px; }
.fg-buttonset {float:left;}
.fg-buttonset .fg-button {float: left;}
.fg-buttonset-single .fg-button,
.fg-buttonset-multi .fg-button {margin-right: -1px;}
/*ToolBar left*/
.fg-toolbar {
z-index:1000000000000;
position:relative;
top:0;
left:10px;
width:100%;
height:45px;
padding:0;
margin:0;
}
.fg-toolbar . set {
margin-right:1.5em;
padding-left: 1px;
}
.fg-toolbar .fg-button { font-size: 1em;}
.zoom-in {width:24px;height:24px;background-image:url(img/zoom-in.png) !important;}
.zoom-out {background-image:url(img/zoom-out.png) !important;}
.pan {background-image:url(img/pan.png) !important;}
.zoomtomaxextent{background-image:url(img/zoom-to-maxextent.png) !important;}
.info{background-image:url(img/information.png) !important;}
.dist{background-image:url(img/mesure-distance.png) !important;}
.area{background-image:url(img/mesure-area.png) !important;}
.print{background-image:url(img/print.png) !important;}
.edit-point {background-image:url(img/edit-point.png) !important;}
.edit-line {background-image:url(img/edit-line.png) !important;}
.edit-polygon {background-image:url(img/edit-polygon.png) !important;}
.delete-feature {background-image:url(img/delete-feature.png) !important;}
.select {background-image:url(img/select.png) !important;}
.buffer {background-image:url(img/buffer.png) !important;}
.centroid {background-image:url(img/centroid.png) !important;}
.boundary {background-image:url(img/boundary.png) !important;}
.convexhull {background-image:url(img/convexhull.png) !important;}
.simplify {background-image:url(img/simplify.png) !important;}
.union {background-image:url(img/union.png) !important;}
.intersection {background-image:url(img/intersection.png) !important;}
.symdifference {background-image:url(img/symdifference.png) !important;}
.difference {background-image:url(img/difference.png) !important;}
.raster-histogram {border:1px solid #8f8f8f;background-image:url(img/raster-histogram.png) !important;}
.clip-raster {border:1px solid #8f8f8f;background-image:url(img/clip-layer.png) !important;}
.merge-rasters {border:1px solid #8f8f8f;background-image:url(img/merge-layer.png) !important;}
.polygons-from-raster {border:1px solid #8f8f8f;background-image:url(img/polygons-from-raster.png) !important;}
.raster-from-csv {border:1px solid #8f8f8f;background-image:url(img/raster-from-csv.png) !important;}
.terrain-profile {border:1px solid #8f8f8f;background-image:url(img/terrain-profile.png) !important;}
.contours-from-dem {border:1px solid #8f8f8f;background-image:url(img/contours-from-dem.png) !important;}
.shaded-relief {border:1px solid #8f8f8f;background-image:url(img/shaded-relief.png) !important;}
.color-relief {border:1px solid #8f8f8f;background-image:url(img/color-relief.png) !important;}
.slope-map {border:1px solid #8f8f8f;background-image:url(img/slope-map.png) !important;}
.tipsy {margin:5px 5px;padding: 5px; font-size: .8em; position: absolute; z-index: 1000000000000;}
.tipsy-inner { padding: 5px 8px 4px 8px;background:#E0E0E0;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e0e0e0'); /* for IE */
background:-webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#e0e0e0)); /* for webkit browsers */
background:-moz-linear-gradient(top, #ffffff, #e0e0e0); /* for firefox 3.6+ */
text-shadow: 0 1px 0 rgba(255, 255, 255, .8);color: #777777; max-width: 250px; text-align: center;border:1px solid #bfbfbf; }
.tipsy-inner { border-radius: 3px; -moz-border-radius:3px; -webkit-border-radius:3px; }
/* avoid pink tiles */
.olImageLoadError {
border: none !important;
background: #FFFFFF !important;
background-color: #FFFFFF !important;
}
div.ui-dialog {
background:#E0E0E0;
border:0;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e0e0e0'); /* for IE */
background:-webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#e0e0e0)); /* for webkit browsers */
background:-moz-linear-gradient(top, #ffffff, #e0e0e0); /* for firefox 3.6+ */padding:0;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
}
.ui-dialog .ui-dialog-titlebar {
background:transparent;
position: relative;
font-size:.8em;
color:#808080;
text-shadow:#FFFFFF 0 1px 0;
border:0;
margin:0;
}
.ui-dialog .ui-dialog-content{
padding:0;
margin:0;
font-size:.7em;
color:#808080;
}
.olControlLoadingPanel {
display:none;
}
#loading{
width:auto;
height:auto;
background:url('img/bckw.png');
text-align: center;
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
display:none;
z-index:100000000;
}
.ui-progress-bar {
/* Usual setup stuff */
margin:15px;
height: 15px;
width:150px;
/* Pad right so we don't cover the borders when fully progressed */
padding-right: 2px;
/* For browser that don't support gradients, we'll set a blanket background colour */
background-color: #abb2bc;
/* Rounds the ends, we specify an excessive amount to make sure they are completely rounded */
/* Adjust to your liking, and don't forget to adjust to the same amount in .ui-progress */
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
/* Webkit background gradient */
background: -webkit-gradient(linear, left bottom, left top, color-stop(0, #b6bcc6), color-stop(1, #9da5b0));
/* Mozilla background gradient */
background: -moz-linear-gradient(#9da5b0 0%, #b6bcc6 100%);
/* Give it the inset look by adding some shadows and highlights */
-webkit-box-shadow: inset 0px 1px 2px 0px rgba(, 0, 0, 0.5), 0px 1px 0px 0px #565656;
-moz-box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #565656;
box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #565656;
}
/* Progress part of the progress bar */
.ui-progress {
/* Usual setup stuff */
position: relative;
display: block;
overflow: hidden;
/* Height should be 2px less than .ui-progress-bar so as to not cover borders and give it a look of being inset */
height: 13px;
/* Rounds the ends, we specify an excessive amount to make sure they are completely rounded */
/* Adjust to your liking, and don't forget to adjust to the same amount in .ui-progress-bar */
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
/* Set the background size so the stripes work correctly */
-webkit-background-size: 24px 24px; /* Webkit */
/* For browser that don't support gradients, we'll set a blanket background colour */
background-color: #74d04c;
/* Webkit background stripes and gradient */
background: -webkit-gradient(linear, 0 0, 24 24,
color-stop(0.00, rgba(255,255,255,0.17)),
color-stop(0.25, rgba(255,255,255,0.17)),
color-stop(0.26, rgba(255,255,255,0)),
color-stop(0.50, rgba(255,255,255,0)),
color-stop(0.51, rgba(255,255,255,0.17)),
color-stop(0.75, rgba(255,255,255,0.17)),
color-stop(0.76, rgba(255,255,255,0)),
color-stop(1.00, rgba(255,255,255,0))
), -webkit-gradient(linear, left bottom, left top, color-stop(0, #8ad148), color-stop(1, #4bbf30));
/* Mozilla (Firefox etc) background stripes */
/* Note: Mozilla's support for gradients is more true to the original design, allowing gradients at 30 degrees, as apposed to 45 degress in webkit. */
background: -moz-repeating-linear-gradient(top left -30deg,
rgba(255,255,255,0.17),
rgba(255,255,255,0.17) 5px,
rgba(255,255,255,0) 5px,
rgba(255,255,255,0) 10px
), -moz-linear-gradient(#8ad148 0%, #4bbf30 100%);
/* Webkit embossing */
-webkit-box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
/* Mozilla embossing */
-moz-box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
/* IE9 and Opera embossing */
box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
/* Give it a higher contrast outline */
border: 1px solid #4c8932;
/* Webkit magic */
-webkit-animation: animate-stripes 2s linear infinite;
/* TODO: Wait for Mozilla to support animation, then implement */
}
/* Progress indicator text */
.ui-progress span.ui-label {
font-size: 0.7em;
position: absolute;
right: 0;
line-height: 13px;
padding-right: 3px;
color: rgba(0,0,0,0.6);
text-shadow: rgba(255,255,255, 0.45) 0 1px 0px;
white-space: nowrap;
}
.olLayerGoogleV3 {display:none;}
div.popup ui-widget-header{color:#FF0000;}
div.popup table{font-size:.8em;margin:0;padding:0;color:#707070;}
#output-lenght, #output-area{margin-left:10px;}
#print-window table{width:230px;}
#print-window table td.lab{max-width:110px;width:110px;font-size:.8em;color:#333333;}
#print-window table td.inp{padding-left:10px;}
#print-options{width:170px;display:inline;}
#dlg-buttons{margin:0 10px 0 0;}
.window {
position:absolute;
overflow:hidden;
background: -moz-linear-gradient(top, #f4f4f4, #d0d0d0);
background: -webkit-gradient(linear, left top, left bottom, from(#f4f4f4), to(#d0d0d0));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='f4f4f4', endColorstr='#d0d0d0');
padding:5px;
border:1px solid #D0D0D0;
-moz-border-radius:5px;
-webkit-border-radius: 5px;
z-index:10000000000000;
}
.window-shadow{
position:absolute;
background:#ddd;
-moz-border-radius:5px;
-webkit-border-radius: 5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
}
.window .window-header{
background:transparent;
padding:2px 0px 4px 0px;
}
.window .window-body{
background:#fff;
border:1px solid #B6B6B6;
border-top-width:0px;
padding:10px;
}
.window .window-header .panel-icon{
left:1px;
top:1px;
}
.window .window-header .panel-with-icon{
padding-left:18px;
}
.window .window-header .panel-tool{
top:0px;
right:1px;
}
.window-proxy{
position:absolute;
overflow:hidden;
border:1px dashed #15428b;
}
.window-proxy-mask{
position:absolute;
background:#fafafa;
filter:alpha(opacity=10);
opacity:0.10;
}
.window-mask{
position:absolute;
left:0;
top:0;
width:100%;
height:100%;
filter:alpha(opacity=40);
opacity:0.40;
background:#ccc;
display1:none;
font-size:1px;
*zoom:1;
overflow:hidden;
}
.panel{
overflow:hidden;
font-size:12px;
z-index:10000000000000;
}
.panel-header{
padding:5px;
line-height:15px;
font-size:1.1em;
color:#808080;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
font-weight:bold;
font-size:1.1em;
background:url('img/panel_title.png') repeat-x;
position:relative;
border:1px solid #B6B6B6;
}
.panel-header-noborder{
border-width:0px;
border-bottom:1px solid #909090;
}
.panel-body{
overflow:auto;
border:1px solid #99BBE8;
border-top-width:0px;
}
.panel-body-noheader{
border-top-width:1px;
}
.panel-body-noborder{
border-width:0px;
}
.panel-with-icon{
padding-left:18px;
}
.panel-icon{
position:absolute;
left:5px;
top:4px;
width:16px;
height:16px;
}
.panel-tool{
position:absolute;
right:5px;
top:4px;
}
.panel-tool div{
display:block;
float:right;
width:16px;
height:16px;
margin-left:2px;
cursor:pointer;
opacity:0.6;
filter:alpha(opacity=60);
}
.panel-tool div.panel-tool-over{
opacity:1;
filter:alpha(opacity=100);
}
.panel-tool-close{
background:url('img/panel_tools.gif') no-repeat -16px 0px;
}
.panel-tool-min{
background:url('img/panel_tools.gif') no-repeat 0px 0px;
}
.panel-tool-max{
background:url('img/panel_tools.gif') no-repeat 0px -16px;
}
.panel-tool-restore{
background:url('img/panel_tools.gif') no-repeat -16px -16px;
}
.panel-tool-collapse{
background:url('img/panel_tool_collapse.gif') no-repeat;
}
.panel-tool-expand{
background:url('img/panel_tool_expand.gif') no-repeat;
}
.panel-loading{
padding:11px 0px 10px 30px;
background:url('img/panel_loading.gif') no-repeat 10px 10px;
}
a.l-btn{
float:right;
color:#333333;
background: -moz-linear-gradient(top, #e2e2e2, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E2E2E2', endColorstr='#B6B6B6');
font-size:12px;
text-decoration:none;
display:inline-block;
zoom:1;
height:24px;
padding-right:18px;
cursor:pointer;
outline:none;
margin:15px 0 5px 5px;
-moz-border-radius:4px;
border-radius:4px;
-webkit-border-radius:4px;
text-shadow: #FFFFFF 0px 1px 0px;
}
a.l-btn:hover{
color:#FFFFFF;
text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F'); /* for IE */
}
a.l-btn-plain{
background:transparent;
padding-right:5px;
border:1px solid transparent;
_border:0px solid #efefef;
_padding:1px 6px 1px 1px;
}
a.l-btn-disabled{
color:#ccc;
opacity:0.5;
filter:alpha(opacity=50);
cursor:default;
}
a.l-btn span.l-btn-left{
display:inline-block;
padding:4px 0px 4px 18px;
line-height:16px;
height:16px;
-moz-border-radius:4px;
border-radius:4px;
-webkit-border-radius:4px;
}
a.l-btn-plain span.l-btn-left{
background:transparent;
padding-left:5px;
}
a.l-btn span span.l-btn-text{
display:inline-block;
height:16px;
line-height:16px;
padding:0px;
}
a.l-btn span span span.l-btn-empty{
display:inline-block;
padding:0px;
width:16px;
}
a:hover.l-btn{
background-position: bottom right;
outline:none;
}
a:hover.l-btn span.l-btn-left{
background-position: bottom left;
}
a:hover.l-btn-plain{
border:1px solid #7eabcd;
background:url('img/button_plain_hover.png') repeat-x left bottom;
_padding:0px 5px 0px 0px;
-moz-border-radius:3px;
-webkit-border-radius: 3px;
}
a:hover.l-btn-disabled{
background-position:top right;
}
a:hover.l-btn-disabled span.l-btn-left{
background-position:top left;
}
.tree{
font-size:.8em;
margin:0;
color:#565656;
padding:0;
list-style-type:none;
}
.tree li{
white-space:nowrap;
font-size:.95em;
color:#333333;
font-weight:bold;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
}
.tree li ul{
list-style-type:none;
margin:0;
padding:0;
}
.tree li ul li{
font-size:1em;
color:#565656;
font-weight:normal;
text-shadow: none;
}
.tree-node{
height:18px;
padding: 5px 0 3px 0;
white-space:nowrap;
cursor:pointer;
}
.tree-indent{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-hit{
cursor:pointer;
}
.tree-expanded{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
background:url('./img/tree_arrows.png') no-repeat -18px 0px;
}
.tree-expanded-hover{
background:url('./img/tree_arrows.png') no-repeat -50px 0px;
}
.tree-collapsed{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
background:url('./img/tree_arrows.png') no-repeat 0px 0px;
}
.tree-collapsed-hover{
background:url('./img/tree_arrows.png') no-repeat -32px 0px;
}
.tree-folder{
display:inline-block;
background:url('./img/tree_folder.png') no-repeat;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-folder-open{
background:url('./img/tree_folder_open.png') no-repeat;
}
.tree-file{
display:inline-block;
background:url('./img/tree_file.png') no-repeat;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-loading{
background:url('./img/tree_loading.gif') no-repeat;
}
.tree-title{
display:inline-block;
text-decoration:none;
vertical-align:middle;
padding:1px 2px 1px 2px;
white-space:nowrap;
}
.tree-node-hover{
background:#ffffff;
background: -moz-linear-gradient(top, #FFFFFF, #eaeaea);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#eaeaea));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#EAEAEA'); /* for IE */
}
.tree-node-selected{
background:#4FA33F;
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#4FA33F'); /* for IE */
}
.tree-checkbox{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-checkbox0{
background:url('./img/tree_checkbox_0.png') no-repeat;
}
.tree-checkbox1{
background:url('./img/tree_checkbox_1.png') no-repeat;
}
.tree-checkbox2{
background:url('./img/tree_checkbox_2.png') no-repeat;
}
.tree-node-proxy{
font-size:12px;
padding:1px 2px 1px 18px;
background:#fafafa;
border:1px solid #ccc;
z-index:9900000;
}
.tree-dnd-yes{
background:url('./img/tree_dnd_yes.png') no-repeat 0 center;
}
.tree-dnd-no{
background:url('./img/tree_dnd_no.png') no-repeat 0 center;
}
.tree-node-top{
border-top:1px dotted red;
}
.tree-node-bottom{
border-bottom:1px dotted red;
}
.tree-node-append .tree-title{
border:1px dotted red;
}
.tree-editor{
border:1px solid #ccc;
font-size:12px;
line-height:16px;
width:80px;
position:absolute;
top:0;
}
.menu{
position:absolute;
background:#f0f0f0 url('./img/menu.gif') repeat-y;
margin:0;
padding:2px;
border:1px solid #ccc;
overflow:hidden;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
.menu-item{
position:relative;
margin:0;
padding:0;
height:22px;
line-height:20px;
overflow:hidden;
font-size:.8em;
color:#565656;
cursor:pointer;
border:1px solid transparent;
_border:1px solid #f0f0f0;
}
.menu-text{
position:absolute;
left:28px;
top:0px;
}
.menu-icon{
position:absolute;
width:16px;
height:16px;
top:3px;
left:2px;
}
.menu-rightarrow{
position: absolute;
width:4px;
height:7px;
top:7px;
right:5px;
background:url('./img/menu_rightarrow.png') no-repeat;
}
.menu-sep{
margin:3px 0px 3px 24px;
line-height:2px;
font-size:2px;
background:url('./img/menu_sep.png') repeat-x;
}
.menu-active{
border:1px solid #ADEF73;
background:#fafafa;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
.menu-shadow{
position:absolute;
background:#ddd;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
}
#layers_list{
height: 266px;
overflow-y: auto;
}
._layer1{
background:url('http://www.mapmint.com:8082/cgi-bin/eserv?map=/Library/WebServer/Documents/data/maps/map4legend_Demo_Project_1_BATIMENT.map&LAYERS=BATIMENT&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=-1.5,-1.5,7.5,7.5&SRS=EPSG:4326&WIDTH=20&HEIGHT=20&r=1315253453.18') no-repeat;
width: 26px;
}
._layer2_class1{
background:url('http://www.mapmint.com:8082/cgi-bin/eserv?map=/Library/WebServer/Documents/data/maps/map4legend_Demo_Project_1_BATIMENT.map&LAYERS=BATIMENT&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=-1.5,-1.5,7.5,7.5&SRS=EPSG:4326&WIDTH=20&HEIGHT=20&r=1315253453.18') no-repeat;
width: 26px;
}
<|start_filename|>mapmint-ui/new-themes/themes/green/icons.css<|end_filename|>
/*
* MapMint Icons CSS
*/
.maincfg1 {border:1px solid #8f8f8f;background-image:url(../img/monitor.png) !important;}
.maincfg2 {border:1px solid #8f8f8f;background-image:url(../img/security.png) !important;}
.maincfg3 {border:1px solid #8f8f8f;background-image:url(../img/user.png) !important;}
.add-database {border:1px solid #cfcece;background-image:url(../img/add-database-default.png) !important;}
.add-directory {border:1px solid #8f8f8f;background-image:url(../img/add-directory-default.png) !important;}
.add-vector {border:1px solid #8f8f8f;background-image:url(../img/add-vector.png) !important;}
.add-raster {border:1px solid #8f8f8f;background-image:url(../img/add-raster.png) !important;}
.add-wms {border:1px solid #8f8f8f;background-image:url(../img/add-wms.png) !important;}
.add-wfs {border:1px solid #8f8f8f;background-image:url(../img/add-wfs.png) !important;}
.add-wcs {border:1px solid #8f8f8f;background-image:url(../img/add-wcs.png) !important;}
.add-territory {border:1px solid #8f8f8f;background-image:url(../img/add-territory.png) !important;}
.view-territory {border:1px solid #8f8f8f;background-image:url(../img/view-territory.png) !important;}
.delete-territory {border:1px solid #8f8f8f;background-image:url(../img/delete-territory.png) !important;}
.add-index {border:1px solid #8f8f8f;background-image:url(../img/add-index.png) !important;}
.delete-index {border:1px solid #8f8f8f;background-image:url(../img/delete-index.png) !important;}
.data{border:1px solid #8f8f8f;background-image:url(../img/data.png) !important;background-position:1px 2px !important;}
.metadata{border:1px solid #8f8f8f;background-image:url(../img/metadata.png) !important;background-position:1px 2px !important;}
.symbology{border:1px solid #8f8f8f;background-image:url(../img/symbology.png) !important;background-repeat:no-repeat !important;background-position:1px 1px !important;}
.table{border:1px solid #8f8f8f;background-image:url(../img/table.png) !important;background-repeat:no-repeat !important;background-position:1px 1px !important;}
.chart{border:1px solid #8f8f8f;background-image:url(../img/chart.png) !important;background-repeat:no-repeat !important;background-position:1px 1px !important;}
.aggregation{border:1px solid #8f8f8f;background-image:url(../img/aggregation.png) !important;background-position:1px 2px !important;}
.repport{border:1px solid #8f8f8f;background-image:url(../img/repport.png) !important;background-position:1px 2px !important;}
.desactivated{opacity: 0.2;filter:alpha(opacity=20);}
.add-theme {border:1px solid #8f8f8f;background-image:url(../img/add-theme.png) !important;}
.delete-theme {border:1px solid #8f8f8f;background-image:url(../img/delete-theme.png) !important;}
.add-document {border:1px solid #8f8f8f;background-image:url(../img/add-document.png) !important;}
.delete-document {border:1px solid #8f8f8f;background-image:url(../img/delete-document.png) !important;}
.add-layer {border:1px solid #8f8f8f;background-image:url(../img/add-layer.png) !important;}
.open-map {border:1px solid #8f8f8f;background-image:url(../img/open-map.png) !important;}
.bl-button{margin:0 5px 0 0;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;}
.zoom-to-max-extent {border:1px solid #8f8f8f;background-image:url(../img/zoomtomaxextent.png) !important;background-position:1px 2px !important;}
.pan {border:1px solid #8f8f8f;background-image:url(../img/pan.png) !important;}
.zoom-box {border:1px solid #8f8f8f;background-image:url(../img/zoom-in.png) !important;}
.osm-box {border:1px solid #8f8f8f;background-image:url(../img/import-osm.png) !important;}
.crop-box {border:1px solid #8f8f8f;background-image:url(../img/crop-raster.png) !important;}
.zoom-in {border:1px solid #8f8f8f;background-image:url(../img/zoomin.png) !important;}
.zoom-in:hover {border:1px solid #8f8f8f;background-image: #73C354 url(../img/zoomin-hover.png) !important; }
.zoom-out {border:1px solid #8f8f8f;background-image:url(../img/zoomout.png) !important;}
.zoom-out:hover {border:1px solid #8f8f8f;background-image: #73C354 url(../img/zoomout-hover.png) !important;}
.zoom-to-point {border:1px solid #8f8f8f;background-image:url(../img/zoom-to-point.png) !important;}
.identify {border:1px solid #8f8f8f;background-image:url(../img/identify.png) !important;}
.mesure-distance {border:1px solid #8f8f8f;background-image:url(../img/ruler.png) !important;}
.mesure-area {border:1px solid #8f8f8f;background-image:url(../img/ruler-crop.png) !important;}
.select {border:1px solid #8f8f8f;background-image:url(../img/select.png) !important;}
.edit-point {border:1px solid #8f8f8f;background-image:url(../img/edit-point.png) !important;}
.edit-line {border:1px solid #8f8f8f;background-image:url(../img/edit-line.png) !important;}
.edit-polygon {border:1px solid #8f8f8f;background-image:url(../img/edit-polygon.png) !important;}
.delete-feature {border:1px solid #8f8f8f;background-image:url(../img/delete-feature.png) !important;}
.buffer {border:1px solid #8f8f8f;background-image:url(../img/buffer.png) !important;}
.spatial-buffer {border:1px solid #8f8f8f;background-image:url(../img/buffer-mask.png) !important;}
.centroid {border:1px solid #8f8f8f;background-image:url(../img/centroid.png) !important;}
.boundary {border:1px solid #8f8f8f;background-image:url(../img/boundary.png) !important;}
.convexhull {border:1px solid #8f8f8f;background-image:url(../img/convexhull.png) !important;}
.simplify {border:1px solid #8f8f8f;background-image:url(../img/simplify.png) !important;}
.union {border:1px solid #8f8f8f;background-image:url(../img/union.png) !important;}
.intersection {border:1px solid #8f8f8f;background-image:url(../img/intersection.png) !important;}
.symdifference {border:1px solid #8f8f8f;background-image:url(../img/symdifference.png) !important;}
.difference {border:1px solid #8f8f8f;background-image:url(../img/difference.png) !important;}
.spatial-query {border:1px solid #8f8f8f;background-image:url(../img/spatial-query.png) !important;}
.raster-histogram {border:1px solid #8f8f8f;background-image:url(../img/raster-histogram.png) !important;}
.clip-raster {border:1px solid #8f8f8f;background-image:url(../img/clip-layer.png) !important;}
.merge-rasters {border:1px solid #8f8f8f;background-image:url(../img/merge-layer.png) !important;}
.polygons-from-raster {border:1px solid #8f8f8f;background-image:url(../img/polygons-from-raster.png) !important;}
.raster-from-csv {border:1px solid #8f8f8f;background-image:url(../img/raster-from-csv.png) !important;}
.terrain-profile {border:1px solid #8f8f8f;background-image:url(../img/terrain-profile.png) !important;}
.contours-from-dem {border:1px solid #8f8f8f;background-image:url(../img/contours-from-dem.png) !important;}
.shaded-relief {border:1px solid #8f8f8f;background-image:url(../img/shaded-relief.png) !important;}
.color-relief {border:1px solid #8f8f8f;background-image:url(../img/color-relief.png) !important;}
.slope-map {border:1px solid #8f8f8f;background-image:url(../img/slope-map.png) !important;}
.main-configuration {border:1px solid #8f8f8f;background-image:url(../img/process.png) !important;}
.layout-settings {border:1px solid #8f8f8f;background-image:url(../img/layout-settings.png) !important;}
.map-settings {border:1px solid #8f8f8f;background-image:url(../img/map-settings.png) !important;}
.layers-settings {border:1px solid #8f8f8f;background-image:url(../img/layers-settings.png) !important;}
.controls-settings {border:1px solid #8f8f8f;background-image:url(../img/controls-settings.png) !important;}
<|start_filename|>mapmint-ui/js/np-public.js<|end_filename|>
$(document).ready(function(){
$('.thumbnail').hover(
function(){
$(this).parent().find('.caption').slideDown(250); //.fadeIn(250)
},
function(){
$(this).parent().find('.caption').slideUp(250); //.fadeOut(205)
}
);
$("#stage").on({
mouseenter: function () {
$(this).find('.caption').slideDown(250); //.fadeIn(250)
},
mouseleave:function () {
$(this).find('.caption').slideUp(250); //.fadeIn(250)
}
},'li');
$("#tagcloud a").tagcloud({
size: {
start: 12,
end: 35,
unit: 'px'
},
color: {
start: "#88B33A",
end: "#548B2C"
}
});
go_to_page(0);
$('#indicateurs_search').click(function(event) { event.preventDefault();$(this).val('');$("#indicateurs_search").autocomplete('search',''); return false;});
$('#documents_search').click(function(event) { event.preventDefault();$(this).val('');$("#documents_search").autocomplete('search',''); return false;});
$(function() {
var allPanels = $('.accordion > dd').hide();
$('.accordion > dt > a.expd').click(function() {
$this = $(this);
$target = $this.parent().next();
if(!$target.hasClass('active')){
allPanels.removeClass('active').slideUp();
$target.addClass('active').slideDown();
}
return false;
});
});
if(System.hasIIndexes){
System.starcIds=[];
$(".starc").each(function(){
System.starcIds.push({"id":$(this).attr("id").replace(/vote_/g,"").replace(/0_/g,""),"elem":$(this)})
});
getIndexQuote(null,System.starcIds);
}
//$('.bar2').mosaic({animation:'slide'});
//startMozaic($('.mosaic-block'));
});
function startMozaic(){
$('.minfo').click(function(e) {
System.hoverMap=$(this).attr("id");
e.preventDefault();
if($("#moreinfo-dialog")[0])
$("#moreinfo-dialog").remove();
$.ajax({
type: "GET",
url: "./MapDetails;id="+System.hoverMap,
complete: function(xml,status) {
var map_details = '<div id="moreinfo-dialog" title="'+System.messages["Map details"]+'"></div>';
bootbox.dialog({
message: map_details,
title: System.messages["Map details"],
buttons: {
view: {
label: System.messages["View map"],
className: "map-btn",
callback: function() {
document.location="./"+System.hoverMap;
}
},
cancel: {
label: System.messages["Cancel"],
className: "map-btn",
callback: function() {
}
}
}
});
$('#moreinfo-dialog').html(xml.responseText);
$('#moreinfo-dialog').show();
//function startMozaic(){
// arguments[0].hover(function() {
// System.hoverMap=$(this).parent().attr("id");
// $(this).append("<div class='mosaic-subbackdrop'><a class='plus' href='#'> + d'info</a></div>");
// $(this).parent().find(".mosaic-overlay").css({"bottom":"0px"});
// $('.plus').click(function(e) {
// e.preventDefault();
// if($("#moreinfo-dialog")[0])
// $("#moreinfo-dialog").remove();
// $.ajax({
// type: "GET",
// url: "./MapDetails;id="+System.hoverMap,
// complete: function(xml,status) {
//
// $('<div id="moreinfo-dialog" title="Description détaillée">').appendTo('body');
// $('#moreinfo-dialog').append(xml.responseText);
// $('#moreinfo-dialog').show();
//
// $( "#moreinfo-dialog" ).window({
// width:600,
// height:400,
// modal: true,
// draggable:false,
// collapsible: false,
// maximizable:false,
// minimizable:false,
// resizable:false,
// onBeforeClose: function(){
// $("body").removeClass('stop-scrolling');
// }
// });
// $("body").addClass('stop-scrolling');
}
});
});
// },function() {
// $(this).parent().find(".mosaic-overlay").css({"bottom":"-130px"});
// $('.mosaic-subbackdrop').remove();
// });
}
$("#slideshow > div:gt(0)").hide();
setInterval(function() {
$('#slideshow > div:first')
.fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo('#slideshow');
}, 2000);
$(function(){
var tabContainers=$('div.all > div');
tabContainers.hide().filter(':first').show();
$(".them").click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
return false;
}).filter(':first').click();
$(".home").click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
return false;
});
$(".indx").click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
return false;
});
});
$(function () {
var tabContainers = $('div.all > div');
tabContainers.hide().filter(':first').show();
$('.main-navigation li a').click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
$('.main-navigation a').removeClass('active');
$(this).addClass('active');
return false;
}).filter(':first').click();
});
function previous(){
new_page = parseInt($('#current_page').val()) - 1;
if($('.active_page').prev('.page_link').length==true){
go_to_page(new_page);
}
}
function next(){
new_page = parseInt($('#current_page').val()) + 1;
if($('.active_page').next('.page_link').length==true){
go_to_page(new_page);
}
}
function go_to_page(page_num){
var show_per_page = 3;
var number_of_items = $('#document_counter').val();
var number_of_pages = Math.ceil(number_of_items/show_per_page);
$('#current_page').val(page_num);
$('#show_per_page').val(show_per_page);
start_from = page_num * show_per_page;
end_on = start_from + show_per_page;
var d=new Date();
$.ajax({
type: "GET",
localID: this.length,
localElement: arguments[0],
localId: arguments[1],
url: "./modules/indexes/documents;"+(System.doc_id?"id="+System.doc_id:"offset="+start_from)+"×tamp="+d.getTime(),
complete: function(xml,status){
$("#documents_container").html(xml.responseText);
var navigation_html = "";
var current_link = 0;
if(number_of_pages > 1){
navigation_html += '<a class="previous_link" href="javascript:previous();">Prev</a>';
while(number_of_pages > current_link){
navigation_html += '<a class="page_link" href="javascript:go_to_page(' + current_link +')" longdesc="' + current_link +'">'+ (current_link + 1) +'</a>';
current_link++;
}
navigation_html += '<a class="next_link" href="javascript:next();">Next</a>';
}
$('#page_navigation').html(navigation_html);
$('#page_navigation .page_link:first').addClass('active_page');
$('.accordion').children().css('display', 'none');
$('.accordion').children('dt').not("dt dd ul li").slice(0, show_per_page).css('display', 'block');
if(System.doc_id>=0){
var tin=0;
$('.accordion').find("dd").each(function(){
if(tin==$("#document_pos").val()){
$(this).addClass('active').slideDown();
page_num=$("#document_cpage").val();
}
tin++;
});
System.doc_id=null;
}
$('.page_link[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page');
$('#current_page').val(page_num);
var allPanels = $('.accordion > dd');
$('.accordion > dt > a.expd').click(function() {
$this = $(this);
$target = $this.parent().next();
if(!$target.hasClass('active')){
allPanels.removeClass('active').slideUp();
$target.addClass('active').slideDown();
}
return false;
});
}
});
}
function setIndexQuote(){
var d=new Date();
$.ajax({
type: "GET",
localID: this.length,
localElement: arguments[0],
localId: arguments[1],
url: zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.setIndexQuote&DataInputs=id="+arguments[1]+";quote="+arguments[2]+"&RawDataOutput=Result×tamp="+d.getTime(),
complete: function(xml,status){
getIndexQuote(this.localElement,this.localId);
}
});
}
System.quotes={};
function getIndexQuote(){
var d=new Date();
var la=arguments[0];
//System.quotes[arguments[1]]={"elem":arguments[0],};
$.ajax({
type: "GET",
localElem: arguments[0],
url: zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.getIndexQuote&DataInputs=id="+arguments[1]+"&RawDataOutput=Result×tamp="+d.getTime(),
complete: function(xml,status){
$("#"+this.localElem.attr('id')).raty({
number: 10,
click: function(score, event) {
event.preventDefault();
setIndexQuote($(this),$(this).attr("id").replace(/vote_/g,""),score);
},
score: xml.responseText
});
}
});
}
<|start_filename|>mapmint-services/raster-tools-src/cgi-env/service.js<|end_filename|>
function createTindex(conf,inputs,outputs){
var myOutputs= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
var myProcess = new ZOO.Process(conf["main"]["serverAddress"],'raster-tools.tindex');
inputs["iname"]["value"]="tile_"+inputs["iname"]["value"];
inputs["dir"]["value"]=inputs["dir"]["value"].replace(conf["main"]["dataPath"]+"/ftp/","")
var myExecuteResult=myProcess.Execute(inputs,myOutputs);
alert(myExecuteResult);
inputs["InputDSTN"]={"value": conf["main"]["dataPath"]+"/dirs/"+inputs["idir"]["value"]}
inputs["InputDSON"]={"value": inputs["iname"]["value"]}
inputs["a_srs"]=inputs["srs"];
inputs["a_srs"]["value"]="+init="+inputs["a_srs"]["value"];
inputs["OutputDSN"]={"value": "TEMP_"+inputs["iname"]["value"]}
var myProcess1 = new ZOO.Process(conf["main"]["serverAddress"],'vector-converter.Converter');
var myOutputs1= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
var myExecuteResult1=myProcess1.Execute(inputs,myOutputs1);
alert(myExecuteResult1);
var myProcess2 = new ZOO.Process(conf["main"]["serverAddress"],'raster-tools.copyTileIndex');
var myOutputs2= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
var myExecuteResult2=myProcess2.Execute(inputs,myOutputs2);
alert(myExecuteResult2);
return {result: 3, outputs: {"Result": {"value": ZOO._("TileIndex file created")}}};
}
<|start_filename|>mapmint-ui/new-themes/themes/green/grid.css<|end_filename|>
.flexigrid div.mDiv div.preview:hover {
background: #FFFFFF url(../img/preview-hover.png);
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.download:hover {
background: #FFFFFF url(../img/download-hover.png);
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.open-in-manager:hover {
background:#FFFFFF url(../img/open-in-manager-hover.png);
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.delete:hover {
background: #FFFFFF url(../img/delete-datasource-hover.png);
border-color: #9a9a9a;
}
.flexigrid div.bDiv tr.trSelected:hover td,.flexigrid div.bDiv tr.trSelected:hover td.sorted,.flexigrid div.bDiv tr.trOver.trSelected td.sorted,.flexigrid div.bDiv tr.trOver.trSelected td,.flexigrid tr.trSelected td.sorted,.flexigrid tr.trSelected td{
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
background: -ms-linear-gradient(#C2FF7E, #4FA33F);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
border-right: 1px solid #a3ec92;
border-left: 1px solid #a3ec92;
border-bottom: 1px solid #a3ec92;
}
.flexigrid .pSearch:hover {
background: url(../img/magnifier-hover.png) no-repeat center;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
behavior: url(js/ie-css3.htc);
}
.flexigrid .pFirst:hover {
background: #FFFFFF url(../img/first-hover.png) no-repeat center;
}
.flexigrid .pPrev:hover {
background: #FFFFFF url(../img/prev-hover.png) no-repeat center;
}
.flexigrid .pNext:hover {
background: #FFFFFF url(../img/next-hover.png) no-repeat center;
}
.flexigrid .pLast:hover {
background: #FFFFFF url(../img/last-hover.png) no-repeat center;
}
.change-srs{text-decoration:none;color:#808080;text-shadow:none;font-weight:normal;padding: 0 3px 0 3px;}
.change-srs:hover{color:#3edf64;}
.change-format{text-decoration:none;color:#808080;text-shadow:none;font-weight:normal;padding: 0 3px 0 3px;}
.change-format:hover{color:#3edf64;}
<|start_filename|>mapmint-ui/new-themes/themes/blue/icons.css<|end_filename|>
/*
* MapMint Icons CSS
*/
.maincfg1 {border:1px solid #8f8f8f;background-image:url(../img/monitor-blue.png) !important;}
.maincfg2 {border:1px solid #8f8f8f;background-image:url(../img/security-blue.png) !important;}
.maincfg3 {border:1px solid #8f8f8f;background-image:url(../img/user-blue.png) !important;}
.projects {border:1px solid #8f8f8f;background-image:url(../img/process-blue.png) !important;}
.documents {border:1px solid #8f8f8f;background-image:url(../img/docs-blue.png) !important;}
.add-database {border:1px solid #8f8f8f;background-image:url(../img/add-database-default-blue.png) !important;}
.add-directory {border:1px solid #8f8f8f;background-image:url(../img/add-directory-default-blue.png) !important;}
.add-vector {border:1px solid #8f8f8f;background-image:url(../img/add-vector-blue.png) !important;}
.add-raster {border:1px solid #8f8f8f;background-image:url(../img/add-raster-blue.png) !important;}
.add-wms {border:1px solid #8f8f8f;background-image:url(../img/add-wms-blue.png) !important;}
.add-wfs {border:1px solid #8f8f8f;background-image:url(../img/add-wfs-blue.png) !important;}
.add-wcs {border:1px solid #8f8f8f;background-image:url(../img/add-wcs-blue.png) !important;}
.add-layer {border:1px solid #8f8f8f;background-image:url(../img/add-layer-blue.png) !important;}
.open-map {border:1px solid #8f8f8f;background-image:url(../img/open-map-blue.png) !important;}
.pan {border:1px solid #8f8f8f;background-image:url(../img/pan-blue.png) !important;}
.zoom-box {border:1px solid #8f8f8f;background-image:url(../img/zoom-in-blue.png) !important;}
.zoom-in {border:1px solid #8f8f8f;background-image:url(../img/zoomin-blue.png) !important;}
.zoom-in:hover {border:1px solid #8f8f8f;background: #73C354 url(../img/zoomin-hover-blue.png) !important;
}
.zoom-to-max-extent {border:1px solid #8f8f8f;background-image:url(../img/zoomtomaxextent-blue.png) !important;}
.zoom-to-max-extent:hover {border:1px solid #8f8f8f;background-image:url(../img/zoomtomaxextent-hover-blue.png) !important;}
.zoom-out {border:1px solid #8f8f8f;background-image:url(../img/zoomout-blue.png) !important;}
.zoom-out:hover {border:1px solid #8f8f8f;background: #73C354 url(../img/zoomout-hover-blue.png) !important;}
.zoom-to-point {border:1px solid #8f8f8f;background-image:url(../img/zoom-to-point-blue.png) !important;}
.identify {border:1px solid #8f8f8f;background-image:url(../img/identify-blue.png) !important;}
.mesure-distance {border:1px solid #8f8f8f;background-image:url(../img/ruler-blue.png) !important;}
.mesure-area {border:1px solid #8f8f8f;background-image:url(../img/ruler-crop-blue.png) !important;}
.select {border:1px solid #8f8f8f;background-image:url(../img/select-blue.png) !important;}
.edit-point {border:1px solid #8f8f8f;background-image:url(../img/edit-point-blue.png) !important;}
.edit-line {border:1px solid #8f8f8f;background-image:url(../img/edit-line-blue.png) !important;}
.edit-polygon {border:1px solid #8f8f8f;background-image:url(../img/edit-polygon-blue.png) !important;}
.delete-feature {border:1px solid #8f8f8f;background-image:url(../img/delete-feature-blue.png) !important;}
.buffer {border:1px solid #8f8f8f;background-image:url(../img/buffer-blue.png) !important;}
.centroid {border:1px solid #8f8f8f;background-image:url(../img/centroid-blue.png) !important;}
.boundary {border:1px solid #8f8f8f;background-image:url(../img/boundary-blue.png) !important;}
.convexhull {border:1px solid #8f8f8f;background-image:url(../img/convexhull-blue.png) !important;}
.simplify {border:1px solid #8f8f8f;background-image:url(../img/simplify-blue.png) !important;}
.union {border:1px solid #8f8f8f;background-image:url(../img/union-blue.png) !important;}
.intersection {border:1px solid #8f8f8f;background-image:url(../img/intersection-blue.png) !important;}
.symdifference {border:1px solid #8f8f8f;background-image:url(../img/symdifference-blue.png) !important;}
.difference {border:1px solid #8f8f8f;background-image:url(../img/difference-blue.png) !important;}
.raster-histogram {border:1px solid #8f8f8f;background-image:url(../img/raster-histogram-blue.png) !important;}
.clip-raster {border:1px solid #8f8f8f;background-image:url(../img/clip-layer-blue.png) !important;}
.merge-rasters {border:1px solid #8f8f8f;background-image:url(../img/merge-layer-blue.png) !important;}
.polygons-from-raster {border:1px solid #8f8f8f;background-image:url(../img/polygons-from-raster-blue.png) !important;}
.raster-from-csv {border:1px solid #8f8f8f;background-image:url(../img/raster-from-csv-blue.png) !important;}
.terrain-profile {border:1px solid #8f8f8f;background-image:url(../img/terrain-profile-blue.png) !important;}
.contours-from-dem {border:1px solid #8f8f8f;background-image:url(../img/contours-from-dem-blue.png) !important;}
.shaded-relief {border:1px solid #8f8f8f;background-image:url(../img/shaded-relief-blue.png) !important;}
.color-relief {border:1px solid #8f8f8f;background-image:url(../img/color-relief-blue.png) !important;}
.slope-map {border:1px solid #8f8f8f;background-image:url(../img/slope-map-blue.png) !important;}
.main-configuration {border:1px solid #8f8f8f;background-image:url(../img/process-blue.png) !important;}
.layout-settings {border:1px solid #8f8f8f;background-image:url(../img/layout-settings-blue.png) !important;}
.map-settings {border:1px solid #8f8f8f;background-image:url(../img/map-settings-blue.png) !important;}
.layers-settings {border:1px solid #8f8f8f;background-image:url(../img/layers-settings-blue.png) !important;}
.controls-settings {border:1px solid #8f8f8f;background-image:url(../img/controls-settings-blue.png) !important;}
<|start_filename|>public_map/assets/js/lib/mapmint/mmdatatables.js<|end_filename|>
/**
* Author : <NAME>
*
* Copyright (c) 2014 GeoLabs SARL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
define([
'xml2json', 'queryString', 'wpsPayload', 'utils'
], function(X2JS, qs, wpsPayload, utils) {
/**
* The ZooProcess Class
* @constructs ZooProcess
* @param {Object} params Parameters
* @example
* var myZooObject = new ZooProcess({
* url: "http://localhost/cgi-bin/zoo_loader.cgi",
* delay: 2500
* });
*/
var MMDataTable = function(params) {
/**
* Object configuring the xml2json use.
*
* @access private
* @memberof ZooProcess#
* @var _x2js {x2js}
*/
var _x2js = new X2JS({
arrayAccessFormPaths: [
'ProcessDescriptions.ProcessDescription.DataInputs.Input',
'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
'Capabilities.ServiceIdentification.Keywords'
],
});
/**
* @access public
* @memberof ZooProcess#
* @var debug {Boolean} true if verbose messages should be displayed on the console
* @default false
*/
this.debug = false;
/**
* @access public
* @memberof ZooProcess#
* @var debug {Boolean} true if verbose messages should be displayed on the console
* @default false
*/
this.debug = false;
this.display = function(key){
var key=getLayerById(layer);
var CRowSelected=[];
console.log(key);
console.log("++++++++++++"+oLayers)
//$("#table-wrapper").removeAttr("style");
if($("#table-wrapper").hasClass("collapse") && !$("#table-wrapper").hasClass("in")){
console.log("collapse || in");
$("#table-wrapper").collapse("show");
//$('#mmm_table-content-wrapper_'+key).tab("show");
//$("#table-wrapper").removeClass("collapse");
}
$('#mmm_table-content-display_'+key).tab("show");
if(!$('#mmm_table-content-wrapper_'+key).length){
//$("#table-wrapper").toggleClass("in");
//if(tableDisplay!=0)
//$(mm_table-content_'+key+').parent().remove();
//tableDisplay++;
for(var i in {"container":0,"header":0})
$("#mmm_table-wrapper-"+i).find(".active").each(function(){
$(this).removeClass("active");
});
$("#mmm_table-wrapper-container").append($('<div id="mmm_table-content-wrapper_'+key+'" class="tab-pane active"></div>').append('<table id="mmm_table-content_'+key+'" class="display" width="100%"></table>'));
$("#mmm_table-wrapper-header").append('<li role="presentation" class="active"><a id="mmm_table-content-display_'+key+'" title="'+oLayers[key]["alias"]+'" data-toggle="tab" data-target="#mmm_table-content-wrapper_'+key+'" href="#mmm_table-content-wrapper_'+key+'"><i class="fa fa-table"></i><b class="ncaret"> </b><span class="hidden-xs hidden-sm">'+oLayers[key]["alias"]+'</span> </a> </li>');
if(selectLayer.getSource().getFeatures().length==0)
$(".require-select").hide();
var columns=[];
var properties="";
var clause="";
var order="";
var j=0;
for(var i in oLayers[key]["queryParams"]["fields"]){
columns.push({
data: oLayers[key]["queryParams"]["fields"][i],
name: oLayers[key]["queryParams"]["fields"][i],
title: oLayers[key]["queryParams"]["aliases"][i],
width: oLayers[key]["queryParams"]["sizes"][i]
});
properties+=oLayers[key]["queryParams"]["fields"][i]+",";
clause+="CAST("+oLayers[key]["queryParams"]["fields"][i]+" AS character(255)) like '%dd%'"+
" OR "+
"CAST("+oLayers[key]["queryParams"]["fields"][i]+" AS character(255)) like 'dd%'"+
" OR "+
"CAST("+oLayers[key]["queryParams"]["fields"][i]+" AS character(255)) like 'dd'"+
(j+1<oLayers[key]["queryParams"]["fields"].length?" OR ":"");
if(i==0)
order=oLayers[key]["queryParams"]["fields"][i];
j++;
}
properties+="msGeometry";
var _x2js = new X2JS();
var featureCount=0;
var cnt=0;
var CFeatures=[];
console.log("HEIGHT: "+$("#map").height()/2);
$('#mmm_table-content_'+key).DataTable( {
data: [],
"scrollY": ($("#map").height()/5)+"px",
"scrollCollapse": true,
"scrollX": true,
"lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
console.log(aoData);
var myAoData=[];
CFeatures=[];
var llimit=[];
for(j in {"iDisplayStart":0,"iDisplayLength":0,"iSortCol_0":0,"sSortDir_0":0,"sSearch":0})
for(i in aoData)
if(aoData[i].name==j){
if(llimit.length==4 && aoData[i].value!="")
llimit.push(aoData[i].value);
if(llimit.length<4)
llimit.push(aoData[i].value);
}
console.log(llimit);
var lclause="";
if(llimit.length>4){
lclause=" WHERE "+clause.replace(/dd/g,llimit[4]);
}
var opts=zoo.getRequest({
identifier: "vector-tools.access",
dataInputs: [
{"identifier":"InputData","href":sSource,"mimeType":"text/xml"},
{"identifier":"offset","value":llimit[0],"dataType":"int"},
{"identifier":"limit","value":llimit[1],"dataType":"int"},
{"identifier":"sql","value":"SELECT "+properties.replace(/,msGeometry/g,"")+" from "+key+lclause+" order by "+(properties.split(",")[llimit[2]])+" "+llimit[3],"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","mimeType":"application/json"},
{"identifier":"Count","dataType":"string"}
],
type: 'POST',
storeExecuteResponse: false
});
console.log(opts);
opts["success"]=function() {
console.log(arguments);
var obj=_x2js.xml_str2json( arguments[2].responseText );
console.log(obj);
notify('vector-tools.access service run successfully','success');
var outputs=obj["ExecuteResponse"]["ProcessOutputs"]["Output"];
var features,count;
console.log(obj["ExecuteResponse"]["ProcessOutputs"]["Output"]);
for(var i in outputs){
if(outputs[i]["Identifier"].toString()=="Count")
featureCount=eval(outputs[i]["Data"]["LiteralData"].toString());
if(outputs[i]["Identifier"].toString()=="Result")
features=JSON.parse(outputs[i]["Data"]["ComplexData"].toString());
}
var format=new ol.format.GeoJSON({});
console.log("format");
console.log(format);
CFeatures=format.readFeatures(outputs[i]["Data"]["ComplexData"].toString(),{
dataProjection: ol.proj.get('EPSG:4326'),
featureProjection: ol.proj.get('EPSG:3857')
});
console.log(CFeatures);
features=features.features;
var data=[];
for(var i in features){
features[i].properties['id']=key+"_"+features[i].id;
features[i].properties['DT_RowId']=key+"_"+features[i].id;
data.push(features[i].properties);
//CFeatures.push(features[i]);
}
var opts={
"sEcho": cnt++,
"iDraw": cnt++,
"iTotalRecords": featureCount,
"iTotalDisplayRecords": featureCount,
"aaData": (featureCount>0?data:[])
};
console.log(opts);
//fnClear();
fnCallback(opts);
if(featureCount==0){
$('#mmm_table-content_'+key).DataTable().clear();
console.log("clear table");
}
console.log(CRowSelected);
/*$(".selected").each(function(){
$('#mmm_table-content').DataTable().row($(this)).deselect();
});*/
for(d in data){
console.log(data[d].DT_RowId);
console.log($.inArray(data[d].DT_RowId, CRowSelected) !== -1 );
if ( $.inArray(data[d].DT_RowId+"", CRowSelected) !== -1 ) {
console.log(data[d].DT_RowId);
$('#mmm_table-content_'+key).DataTable().row($("#"+data[d].DT_RowId)).select();
}else{
$('#mmm_table-content_'+key).DataTable().row($("#"+data[d].DT_RowId)).deselect();
}
}
var existing=$('#mmm_table-content_'+key+'_info').children('span.select-info');
if(existing.length)
existing.remove();
$('#mmm_table-content_'+key+'_info').append($('<span class="select-info"/>').append(
$('<span class="select-item"/>').append('dd rows selected'.replace(/dd/g,CRowSelected.length))
));
console.log('finish');
};
opts["error"]=function(){
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
};
oSettings.jqXHR = $.ajax( opts );
},
"sAjaxSource": msUrl+"?map="+oLayers[key]["map"]+"&version=1.0.0&service=WFS&request=GetFeature&typename="+key+"&propertyname="+properties,
"bProcessing": true,
"bServerSide": true,
fixedHeader: true,
//searching: true,
responsive: true,
deferRender: true,
rowId: 'id',
select: {
info: false,
},
"rowCallback": function( row, data ) {
console.log(CRowSelected);
console.log(data.DT_RowId);
$(row).removeClass('selected');
console.log($(row));
console.log($.inArray(data.DT_RowId, CRowSelected) !== -1 );
if ( $.inArray(data.DT_RowId, CRowSelected) !== -1 ) {
console.log(data.DT_RowId);
console.log($('#mmm_table-content_'+key).DataTable());
$('#mmm_table-content_'+key).DataTable().row($(row)).select();
//$(row).addClass('selected');
}else{
$('#mmm_table-content_'+key).DataTable().row($(row)).deselect();
//$(row).removeClass('selected');
}
},
//dom: 'Bfrtip0001',
//dom: 'Bfrtip',
columns: columns
} );
$('#mmm_table-content_'+key+' tbody').on('hover', 'tr', function () {
console.log('hover');
/*for(var i=0;i<CFeatures.length;i++){
if(CFeatures[i].getId()==id){
console.log(CFeatures.length);
CFeatures[i].set("origin","query_selected_"+key);
selectLayer.getSource().addFeature(CFeatures[i]);
}
}*/
});
$('#mmm_table-content_'+key+' tbody').on('click', 'tr', function () {
var id = this.id+"";
console.log("CURRENT ID: "+id+" "+key);
console.log("CURRENT ID: "+$(this).parent().parent().get('id'));
var index = $.inArray(id, CRowSelected);
if ( index === -1 ) {
if(selectLayer.getSource().getFeatures().length==0)
$(".require-select").show();
CRowSelected.push( id );
$('#mmm_table-content_'+key).DataTable().row("#"+id).select();
console.log(CFeatures.length);
for(var i=0;i<CFeatures.length;i++){
console.log(CFeatures[i].getId());
if(key+"_"+CFeatures[i].getId()==id){
console.log(CFeatures.length);
CFeatures[i].set("origin","query_selected_"+key);
selectLayer.getSource().addFeature(CFeatures[i]);
}
}
console.log(CFeatures);
} else {
CRowSelected.splice( index, 1 );
$('#mmm_table-content_'+key).DataTable().row("#"+id).deselect();
for(var i=0;i<CFeatures.length;i++){
if(key+"_"+CFeatures[i].getId()==id){
console.log(CFeatures.length);
//CFeatures[i].set("origin","query_selected_"+key);
selectLayer.getSource().removeFeature(selectLayer.getSource().getFeatureById(CFeatures[i].getId()));
}
}
if(selectLayer.getSource().getFeatures().length==0)
$(".require-select").hide();
}
var existing=$('#mmm_table-content_'+key+'_info').children('span.select-info');
if(existing.length)
existing.remove();
console.log('#mmm_table-content_'+key+'_info');
console.log($('#mmm_table-content_'+key+'_info'));
console.log(selectLayer.getSource().getFeatures().length);
console.log(CRowSelected.length);
console.log('#mmm_table-content_'+key+'_info');
$('#mmm_table-content_'+key+'_info').append($('<span class="select-info"/>').append(
$('<span class="select-item"/>').append((selectLayer.getSource().getFeatures().length!=CRowSelected.length?'dd rows selected (ee total selected)'.replace(/dd/g,CRowSelected.length).replace(/ee/g,selectLayer.getSource().getFeatures().length):'dd rows selected'.replace(/dd/g,CRowSelected.length)))
));
} );
$('#mmm_table-content-wrapper_'+key).bind('cssClassChanged', function(){
if($("#mmm_table-wrapper-header-title").text()!=oLayers[key]["alias"]){
$("#mmm_table-wrapper-header-title").text(oLayers[key]["alias"]);
console.log( "First handler for .cssClassChanged() called." + "(" +key +")");
console.log( arguments );
}
//do stuff here
});
}
}
}
}
return MMDataTable;
});
<|start_filename|>public_map/mapmint-leftcol.css<|end_filename|>
/*
* PANES & CONTENT-DIVs
*/
.ui-layout-pane { /* all 'panes' */
background: transparent;
border: 0;
/* DO NOT add scrolling (or padding) to 'panes' that have a content-div,
otherwise you may get double-scrollbars - on the pane AND on the content-div
*/
padding: 0;
overflow: auto;
}
/* (scrolling) content-div inside pane allows for fixed header(s) and/or footer(s) */
.ui-layout-content {
padding: 0;
position: relative; /* contain floated or positioned elements */
overflow: auto; /* add scrolling to content-div */
}
/*
* RESIZER-BARS
*/
.ui-layout-resizer { /* all 'resizer-bars' */
background: #DDD;
border: 0;
border-width: 0;
}
.ui-layout-resizer-drag { /* REAL resizer while resize in progress */
}
.ui-layout-resizer-hover { /* affects both open and closed states */
}
/* NOTE: It looks best when 'hover' and 'dragging' are set to the same color,
otherwise color shifts while dragging when bar can't keep up with mouse */
.ui-layout-resizer-open-hover , /* hover-color to 'resize' */
.ui-layout-resizer-dragging { /* resizer beging 'dragging' */
background: #C4E1A4;
}
.ui-layout-resizer-dragging { /* CLONED resizer being dragged */
border-left: 0;
border-right: 0;
}
/* NOTE: Add a 'dragging-limit' color to provide visual feedback when resizer hits min/max size limits */
.ui-layout-resizer-dragging-limit { /* CLONED resizer at min or max size-limit */
background: #E1A4A4; /* red */
}
.ui-layout-resizer-closed-hover { /* hover-color to 'slide open' */
background: #EBD5AA;
}
.ui-layout-resizer-sliding { /* resizer when pane is 'slid open' */
opacity: .10; /* show only a slight shadow */
filter: alpha(opacity=10);
}
.ui-layout-resizer-sliding-hover { /* sliding resizer - hover */
opacity: 1.00; /* on-hover, show the resizer-bar normally */
filter: alpha(opacity=100);
}
/* sliding resizer - add 'outside-border' to resizer on-hover
* this sample illustrates how to target specific panes and states */
.ui-layout-resizer-north-sliding-hover { border-bottom-width: 1px; }
.ui-layout-resizer-south-sliding-hover { border-top-width: 1px; }
.ui-layout-resizer-west-sliding-hover { border-right-width: 1px; }
.ui-layout-resizer-east-sliding-hover { border-left-width: 1px; }
/*
* TOGGLER-BUTTONS
*/
.ui-layout-toggler {
border: 0; /* match pane-border */
background-color: #BBB;
}
.ui-layout-resizer-hover .ui-layout-toggler {
opacity: .60;
filter: alpha(opacity=60);
}
.ui-layout-toggler-hover , /* need when NOT resizable */
.ui-layout-resizer-hover .ui-layout-toggler-hover { /* need specificity when IS resizable */
background-color: #92cb4b;
opacity: 1.00;
filter: alpha(opacity=100);
}
.ui-layout-toggler-north ,
.ui-layout-toggler-south {
border-width: 0 1px; /* left/right borders */
}
.ui-layout-toggler-west ,
.ui-layout-toggler-east {
border-width: 1px 0; /* top/bottom borders */
display:none;
}
/* hide the toggler-button when the pane is 'slid open' */
.ui-layout-resizer-sliding ui-layout-toggler {
display: none;
}
ui-layout-resizer-west-closed{width:17px;}
/*
* style the text we put INSIDE the togglers
*/
.ui-layout-toggler .content {
color: #666;
font-size: 12px;
font-weight: bold;
width: 100%;
padding-bottom: 0.35ex; /* to 'vertically center' text inside text-span */
}
.ui-layout-north{
padding:0;
background: #83c849;
width:100%;
overflow:hidden;
height:90px;
}
.ui-layout-north img{float:left;margin:15px 0 0 20px;display:inline-block;}
.ui-layout-north h1{font-size:1.4em;margin:0;padding:5px;color:#FFFFFF;position:relative;top:5px;left:20px;line-height:1.3em;}
.ui-layout-west {
padding:0;
background:#FFFFFF;
width:250px;
overflow:hidden;
}
.ui-layout-west h2{font-size:.9em;margin:0;padding:10px 0 6px 10px;color:#808080;position:relative;font-weight:bold;letter-spacing:1px;text-transform:uppercase;}
.close {width:16px;height:17px;
float:right;
margin: 0 5px 0 0;
cursor:pointer;
background: url(img/close-sidebar.png) no-repeat;
text-align:center;
font-size:.7em;
}
.close:hover{
width:16px;height:17px;cursor:pointer;margin: 0 5px 0 0;background: url(img/close-sidebar.png) no-repeat;
}
.open {width:16px;height:17px;
position:absolute;
float:left;
top:10px;
left:10px;
cursor:pointer;
background: url(img/close-sidebar-right.png) no-repeat;
text-align:center;
font-size:.7em;
z-index: 10000 !important;
}
.open:hover {width:16px;height:17px;cursor:pointer;background: url(../img/close-sidebar-right.png) no-repeat;}
.ui-layout-south{
padding: 0;
width:100%;
overflow:hidden;
max-height:40px;
height:40px;
background: transparent url('img/bcknav.png');
}
.ui-layout-south img {
border:0;
position:relative;
top:10px;
left:0;
}
div#map{width:100%;height:100%;margin:0;padding:0;}
div#ls-container{position:absolute;top:10px; right:10px;width:auto;z-index:100000000;}
div#ls-container table{position:absolute;top:110px;left:100px;margin:0;padding:0;width:160px;}
div#ls-container table td.sli{width:100px;}
a.ls-toogler{float:right;background:#FFFFFF url('img/layers-icon.png');background-position:3px 2px;width:24px;height:24px;position:absolute;bottom:5px;right:5px;margin:0;z-index:10000000000000;
}
a.ls-toogler:hover{background:#EDEDED url('img/layers-icon.png');background-position:3px 2px;width:24px;height:24px;}
div#layerswitcher {background:url('img/bckw.png'); z-index:100000000000; overflow: hidden;display:block;
-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);float:right;width:300px;height:300px;}
div#layerswitcher h2, div#zoomswitcher h2{font-size:.9em;margin:0;padding:5px;color:#808080;position:relative;top:0px;left:10px;font-weight:bold; text-shadow: #FFFFFF 0px 1px 0px;letter-spacing:2px;}
.baseLbl, .dataLbl{display:none;}
.labelSpan{padding:0 0 0 10px;font-size:.9em;}
.baseLayersDiv, .dataLayersDiv {font-size:.9em;margin:0;padding:5px;color:#808080;position:relative;top:0px;left:20px;font-weight:normal;}
/* zoommenu
----------------------------------*/
div#zoomswitcher {position:absolute;top:170px; right:10px;background:url('img/bckw.png'); z-index:100000000000; overflow: hidden;display:block;
-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);float:right;width:230px;height:auto;}
select#speedC { }
.ui-selectmenu { min-width:230px;display: block; position:relative;top:0;left:0px; height:20px; text-decoration: none; overflow:hidden;font-size:.7em;}
.ui-selectmenu-icon { position:absolute; right:6px; margin-top:-8px; top: 50%; }
.ui-selectmenu-menu { padding:0; margin:0; list-style:none; position:absolute; top: 0; visibility: hidden; overflow: auto;width:100%; }
.ui-selectmenu-open { visibility: visible; }
.ui-selectmenu-menu-popup { margin-top: -1px; }
.ui-selectmenu-menu-dropdown { z-index:1000000000000000; font-size:.7em;min-width:230px;}
.ui-selectmenu-menu li { padding:0; margin:0; display: block; border-top: 1px dotted transparent; border-bottom: 1px dotted transparent; border-right-width: 0 !important; border-left-width: 0 !important; font-weight: normal !important;}
.ui-selectmenu-menu li a,.ui-selectmenu-status {line-height: 1.1em; display:block; padding:.3em; outline:none; text-decoration:none; }
.ui-selectmenu-menu li.ui-selectmenu-hasIcon a,
.ui-selectmenu-hasIcon .ui-selectmenu-status { padding-left: 20px; position: relative; margin-left: 5px; }
.ui-selectmenu-menu li .ui-icon, .ui-selectmenu-status .ui-icon { position: absolute; top: 1em; margin-top: -8px; left: 0; }
.ui-selectmenu-status { line-height: 1.4em;}
.ui-selectmenu-open li.ui-selectmenu-item-focus a { }
.ui-selectmenu-open li.ui-selectmenu-item-selected { }
.ui-selectmenu-menu li span,.ui-selectmenu-status span { display:block; margin-bottom: .2em; }
.ui-selectmenu-menu li .ui-selectmenu-item-header { font-weight: bold; }
.ui-selectmenu-menu li .ui-selectmenu-item-content { }
.ui-selectmenu-menu li .ui-selectmenu-item-footer { opacity: .8; }
/*for optgroups*/
.ui-selectmenu-menu .ui-selectmenu-group { font-size: 1em; }
.ui-selectmenu-menu .ui-selectmenu-group .ui-selectmenu-group-label { line-height: 1.4em; display:block; padding:.6em .5em 0; font-weight: bold; }
.ui-selectmenu-menu .ui-selectmenu-group ul { margin: 0; padding: 0; }
.streetname{position:absolute;top:10px;left:500px;width:auto;background:red; z-index:100000000000; overflow: hidden;display:block;-moz-border-radius:5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
color:#FFFFFF;text-shadow: #707070 0 1px 0;
padding:10px;
font-size:.9em;
}
div#zoomTo_control {position:absolute; top:30%; left:10px; width:36px; height:172px;background:url('img/bckw.png'); z-index:100000000000; overflow: hidden; text-indent:-9999%; font-size:0; display:block; line-height:0;-moz-border-radius:5px}
div#zoomTo_control:hover {background:#FFFFFF;}
div#zoomTo_control a.zoomTo_in {position:absolute; top:5px; left:5px; width:20px; height:20px;background: #E9E9E9 url('img/zoomin.png');z-index:1000000;padding:2px;-moz-border-radius:5px;border-radius:5px;-webkit-border-radius:5px;background-position: 1px 3px;border:1px solid #CCCCCC;}
div#zoomTo_control a.zoomTo_out {position:absolute; bottom:5px; left:5px; width:20px; height:20px;background: #E9E9E9 url('img/zoomout.png');z-index:1000000;padding:2px;-moz-border-radius:5px;border-radius:5px;-webkit-border-radius:5px;background-position: 1px 3px;border:1px solid #CCCCCC;}
div#zoomTo_control a.zoomTo_in:hover {background: #cccccc url('img/zoomin-hover.png');background-position: 1px 3px;}
div#zoomTo_control a.zoomTo_out:hover {background: #cccccc url('img/zoomout-hover.png');background-position: 1px 3px;}
input.opac{width:50px;padding:3px 0 0 0;border:0;background:transparent;border:0;text-indent:10px;color:#808080;}
div#zoomTo_control span.slider {position:absolute; top:34px; left:14px; height:104px; width:4px; }
div#zoomTo_control .ui-slider { position: relative; text-align: left;}
div#zoomTo_control .ui-slider .ui-slider-handle { position: absolute; z-index: 20; width:1.2em!important; height:1.2em!important; cursor: default;}
div#zoomTo_control .ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
div#zoomTo_control .ui-slider-vertical { width: .8em; height: 50px; }
div#zoomTo_control .ui-slider-vertical .ui-slider-handle { left: -7px; margin-left: 0; margin-bottom: -.6em; height:4px!important; width:16px!important;background:#E9E9E9;-moz-border-radius:2px;border-radius:2px;-webkit-border-radius:2px;border:1px solid #CCCCCC;}
div#zoomTo_control .ui-slider-vertical .ui-slider-range { left: 0; width: 100%; }
div#zoomTo_control .ui-slider-vertical .ui-slider-range-min { bottom: 0;background:#bababa; }
div#zoomTo_control .ui-slider-vertical .ui-slider-range-max { top: 0; }
div#zoomTo_control .ui-slider-vertical .ui-state-focus {cursor:pointer;}
div#zoomTo_control .ui-slider-vertical .ui-state-active {cursor:pointer;}
div#opacity_control{position:absolute; height:10px; width:130px; }
div#opacity_control span#o-slider {position:absolute;height:4px; width:100px; }
div#opacity_control .ui-slider { position: relative; text-align: left;}
div#opacity_control .ui-slider .ui-slider-handle { position: absolute; z-index: 20; width:4px!important; height:12px!important; cursor: default;}
div#opacity_control .ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
div#opacity_control .ui-slider-horizontal { width: .8em; height: 50px; }
div#opacity_control .ui-slider-handle { left: -7px; margin-left: 0; margin-bottom: -.6em; height:4px!important; width:16px!important;background:#E9E9E9;-moz-border-radius:2px;border-radius:2px;-webkit-border-radius:2px;border:1px solid #CCCCCC;}
div#opacity_control .ui-slider-horizontal .ui-slider-range { left: 0; width: 100%; }
div#opacity_control .ui-slider-horizontal .ui-slider-range-min { bottom: 0;background:#bababa; }
div#opacity_control .ui-slider-horizontal .ui-slider-range-max { top: 0; }
div#opacity_control .ui-slider-horizontal .ui-state-focus {cursor:pointer;}
div#opacity_control .ui-slider-horizontal .ui-state-active {cursor:pointer;}
ul.links{position:relative;display:block;margin:30px 0 0 30px;padding:0;font-size:.8em;}
ul.links li{list-style:none;margin:0 0 15px 0;}
ul.links li a {text-decoration:none;color:#C80020;text-shadow:#E0E0E0 0 1px 0;}
div#overviewmap {z-index:1000; overflow: hidden;position:relative;top:10px;left:10px;float:left;margin:0;padding:0;}
.toolbar-noborder{background:transparent;width:100%;margin:0;padding:0;}
.toolbar-noborder a{margin:5px 0 5px 5px;}
#coords{float:left;padding:0 5px 0 0;color:#FFFFFF;font-size:.8em;text-shadow:#333333 0 1px 0;display:inline;position:absolute;right:50px;top:16px;}
.ls-button {
position:relative;
padding:.2em;
text-decoration:none !important;
cursor:pointer;
text-align: center;
zoom: 1;
}
.fg-button {
margin:5px;
margin-bottom:0;
padding:.2em;
text-decoration:none !important;
cursor:pointer;
text-align: center;
zoom: 1;
}
.fg-button .ui-icon {
position: absolute;
width:24px;
height:24px;
}
.fg-button-tools .ui-icon {
position: absolute;
width:36px;
height:36px;
}
a.fg-button {
float:left;
}
/*important*/
button.fg-button {width:auto; overflow:visible; }
.fg-button-icon-solo {display:block; width:24px;height:24px; text-indent: -9999px; }
.fg-button-icon-solo-tools {display:block; width:36px;height:36px; text-indent: -9999px; }
.fg-buttonset {float:left;}
.fg-buttonset .fg-button {float: left;}
.fg-buttonset-single .fg-button,
.fg-buttonset-multi .fg-button {margin-right: -1px;}
.nav{position:absolute;top:0;left:15px !important;width:auto;display:block;}
.fg-toolbar {
z-index:1000000000000;
position:relative;
top:0;
left:0;
width:auto;
max-width:550px;
padding:0;
margin:0;
display:block;
}
.soc-toolbar{
z-index:1000000000000;
position:absolute;
float:right;
top:36px;
right:10px;
width:150px;
border:1px solid red;
max-width:200px;
height:35px;
padding:0;
margin:0;
display:block;
}
#base_layers {
z-index:1000000000000;
position:relative;
top:0;
left:6px;
width:98%;
padding:0;
margin:0;
float:left;
}
.fg-toolbar . set {
margin-right:1.5em;
padding-left: 1px;
}
.fg-toolbar .fg-button { font-size: 1em;}
.zoom-in {width:24px;height:24px;background-image:url(img/zoom-in.png) !important;}
.zoom-out {background-image:url(img/zoom-out.png) !important;}
.pan {background-image:url(img/pan.png) !important;}
.zoomtomaxextent{background-image:url(img/zoom-to-maxextent.png) !important;}
.info{background-image:url(img/information.png) !important;}
.dist{background-image:url(img/mesure-distance.png) !important;}
.area{background-image:url(img/mesure-area.png) !important;}
.print{background-image:url(img/print.png) !important;}
.edit-point {background-image:url(img/edit-point.png) !important;}
.edit-line {background-image:url(img/edit-line.png) !important;}
.edit-polygon {background-image:url(img/edit-polygon.png) !important;}
.delete-feature {background-image:url(img/delete-feature.png) !important;}
.select {background-image:url(img/select.png) !important;}
.buffer {background-image:url(img/buffer.png) !important;}
.centroid {background-image:url(img/centroid.png) !important;}
.boundary {background-image:url(img/boundary.png) !important;}
.convexhull {background-image:url(img/convexhull.png) !important;}
.simplify {background-image:url(img/simplify.png) !important;}
.union {background-image:url(img/union.png) !important;}
.intersection {background-image:url(img/intersection.png) !important;}
.symdifference {background-image:url(img/symdifference.png) !important;}
.difference {background-image:url(img/difference.png) !important;}
.raster-histogram {border:1px solid #8f8f8f;background-image:url(img/raster-histogram.png) !important;}
.clip-raster {border:1px solid #8f8f8f;background-image:url(img/clip-layer.png) !important;}
.merge-rasters {border:1px solid #8f8f8f;background-image:url(img/merge-layer.png) !important;}
.polygons-from-raster {border:1px solid #8f8f8f;background-image:url(img/polygons-from-raster.png) !important;}
.raster-from-csv {border:1px solid #8f8f8f;background-image:url(img/raster-from-csv.png) !important;}
.terrain-profile {border:1px solid #8f8f8f;background-image:url(img/terrain-profile.png) !important;}
.contours-from-dem {border:1px solid #8f8f8f;background-image:url(img/contours-from-dem.png) !important;}
.shaded-relief {border:1px solid #8f8f8f;background-image:url(img/shaded-relief.png) !important;}
.color-relief {border:1px solid #8f8f8f;background-image:url(img/color-relief.png) !important;}
.slope-map {border:1px solid #8f8f8f;background-image:url(img/slope-map.png) !important;}
.tipsy {margin:5px 5px;padding: 5px; font-size: .8em; position: absolute; z-index: 1000000000000;}
.tipsy-inner { padding: 5px 8px 4px 8px;background:#E0E0E0;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e0e0e0'); /* for IE */
background:-webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#e0e0e0)); /* for webkit browsers */
background:-moz-linear-gradient(top, #ffffff, #e0e0e0); /* for firefox 3.6+ */
text-shadow: 0 1px 0 rgba(255, 255, 255, .8);color: #777777; max-width: 250px; text-align: center;border:1px solid #bfbfbf; }
.tipsy-inner { border-radius: 3px; -moz-border-radius:3px; -webkit-border-radius:3px; }
/* avoid pink tiles */
.olImageLoadError {
border: none !important;
background: #FFFFFF !important;
background-color: #FFFFFF !important;
}
div.ui-dialog {
background:#E0E0E0;
border:0;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e0e0e0'); /* for IE */
background:-webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#e0e0e0)); /* for webkit browsers */
background:-moz-linear-gradient(top, #ffffff, #e0e0e0); /* for firefox 3.6+ */padding:0;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
}
.ui-dialog .ui-dialog-titlebar {
background:transparent;
position: relative;
font-size:.8em;
color:#808080;
text-shadow:#FFFFFF 0 1px 0;
border:0;
margin:0;
}
.ui-dialog .ui-dialog-content{
padding:0;
margin:0;
font-size:.7em;
color:#808080;
}
.olControlLoadingPanel {
display:none;
}
#loading{
position: absolute;
top: 10px;
right: 10px;
width:auto;
height:auto;
background:url('img/bckw.png');
text-align: left;
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
display:none;
z-index:100000000;
font-size: 11px;
color:#707070;
}
#loading ul{
list-style: none;
margin: 0;
padding: 1em;
}
<|start_filename|>mapmint-ui/new-themes/themes/default/forms.css<|end_filename|>
/*
* MapMint default forms CSS
*/
#dlg-buttons{font-size:.9em;}
input {border:1px solid #9f9f9f;outline: none;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
behavior: url(js/ie-css3.htc);
}
input.rounded{width:100%;height:20px;margin:1px;border:1px solid #9f9f9f; outline: none;
background:#EBEBEB;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
behavior: url(js/ie-css3.htc);
}
input:focus, select:focus{
-webkit-box-shadow: 0px 0px 5px #9e9e9e;
-moz-box-shadow: 0px 0px 5px #9e9e9e;
}
input.name{width:65%;height:20px;margin:1px;border-radius:5px;-webkit-border-radius:5px;-moz-border-radius:5px;border:1px solid #9f9f9f;margin-left:10px;
}
fieldset{border-radius:5px;-webkit-border-radius:5px;-moz-border-radius:5px;border:1px solid #9f9f9f;}
textarea.maincfg, textarea.classif{width:100%;height:130px;margin:1px;outline: none;border:1px solid #9f9f9f;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
behavior: url(js/ie-css3.htc);
}
select{
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
border:1px solid #9f9f9f;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
padding:2px;
font-size:1em;
behavior: url(js/ie-css3.htc);
}
select option{
font-size:1em;
}
select#scalesList {
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
border:1px solid #CDCDCD;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
padding:2px;
font-size:.85em;
behavior: url(js/ie-css3.htc);
position:relative;
top:0;right:40px;
}
select#scalesList option{
font-size:.85em;
}
select.select-window{margin:0;width:100%;}
select.select-window-short{margin:0;width:85%;}
input.input-window-short{margin:0;width:30px;}
ul.style-tabs-nav1 {
list-style: none;
margin: 0;
padding: 0;
margin-top: 1em;
}
ul.style-tabs-nav1 li {
display: inline;
}
ul.style-tabs-nav1 li a, a.classify, a.mmbutton{
text-decoration:none;border:1px solid #9a9a9a;padding:4px;color:#777777;position:relative;top:1px;left:0px;text-shadow:#E9E9E9 0 1px 0;
background: -moz-linear-gradient(top, #E0E0E0 , #E9E9E9);
background: -webkit-gradient(linear, left top, left bottom, from(#E0E0E0), to(#E9E9E9));
background: -ms-linear-gradient(#E0E0E0, #E9E9E9);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E0E0E0', endColorstr='#E9E9E9');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E0E0E0', endColorstr='#E9E9E9');
}
ul.style-tabs-nav1 li a:focus {
outline: 0;
}
ul.style-tabs-nav {
list-style: none;
margin: 0;
padding: 0;
}
ul.style-tabs-nav li {
display: inline;
}
ul.style-tabs-nav li a, a.classify, a.mmbutton{
text-decoration:none;border:1px solid #9a9a9a;padding:4px;color:#777777;position:relative;top:1px;left:0px;text-shadow:#E9E9E9 0 1px 0;
background: -moz-linear-gradient(top, #E0E0E0 , #E9E9E9);
background: -webkit-gradient(linear, left top, left bottom, from(#E0E0E0), to(#E9E9E9));
background: -ms-linear-gradient(#E0E0E0, #E9E9E9);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E0E0E0', endColorstr='#E9E9E9');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E0E0E0', endColorstr='#E9E9E9');
}
ul.style-tabs-nav li a:focus {
outline: 0;
}
div.style-tabs > div {
position:relative;
top:10px;
padding: 5px;
border:0;
}
.hidden {
display: none;
}
label.up{ display: block; margin: 0 10px 3px 0; }
label.up-small{ display: block; margin: 10px 10px .5em 0; font-size:.95em;font-style:italic; }
/*custom upload elements*/
.customfile-input {
position: absolute; height: 100px;cursor: pointer;background: transparent; border: 0; opacity: 0; -moz-opacity: 0;
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0); z-index: 999; }
.customfile {
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
border:1px solid #9f9f9f;
cursor: pointer;
overflow: hidden;
padding: 0;
-moz-border-radius:4px;
-webkit-border-radius:4px;
behavior: url(js/ie-css3.htc);
border-radius:4px;
position: relative;
color:#333333;
}
.customfile-disabled { opacity: .5; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0); cursor: default; }
.customfile-feedback { display: block; margin: 1px 1px 1px 5px;color: #A9A9A9; font-style: italic; padding: .3em; }
.customfile-feedback-populated { color: #33333; font-style: normal; font-weight: normal;}
.customfile-button {border: 1px solid #FFFFFF;background: #E9E9E9; color: #333333; float: right; width: 70px; padding: .3em .6em; text-align: center; text-decoration: none;-moz-border-radius:5px; -webkit-border-radius:5px; border-radius:5px;color:#333333; }
.customfile-focus .customfile-button { outline: 1px dotted #ccc; }
.combo{
display:inline-block;
white-space:nowrap;
font-size:12px;
margin:0;
padding:0;
border:1px solid #A4BED4;
background:#fff;
}
.combo-text{
font-size:12px;
border:0px;
line-height:20px;
height:20px;
padding:0px;
*height:18px;
*line-height:18px;
_height:18px;
_line-height:18px;
}
.combo-arrow{
background:#E0ECF9 url('../img/combo_arrow.gif') no-repeat 3px 4px;
width:18px;
height:20px;
overflow:hidden;
display:inline-block;
vertical-align:top;
cursor:pointer;
opacity:0.6;
filter:alpha(opacity=60);
}
.combo-arrow-hover{
opacity:1.0;
filter:alpha(opacity=100);
}
.combo-panel{
background:#fff;
overflow:auto;
}
.combobox-item{
padding:2px;
font-size:12px;
padding:3px;
padding-right:0px;
}
.combobox-item-hover{
background:#fafafa;
}
.combobox-item-selected{
background:#FBEC88;
}
ul.choice{
margin:10px 0 20px 0;
min-width:50%;
display:block;
font-size:0.85em;
color:#707070;
padding:0 0 0 10px;
}
ul.choice li{
display:inline;
}
.desc {
display:none;
}
label.ch{font-size:0.85em;color:#707070;}
input[type="checkbox"].chch , a.al {margin:0 0 0 10px;}
<|start_filename|>mapmint-ui/templates/preview/modules/geolocation/_init.js<|end_filename|>
geolocation=new OpenLayers.Layer.Vector('geolocation',{renderers: System.renderer});
map.addLayers([geolocation]);
mapControls.geolocate.events.register("locationupdated",mapControls.geolocate,function(e) {
geolocation.removeAllFeatures();
var circle = new OpenLayers.Feature.Vector(
OpenLayers.Geometry.Polygon.createRegularPolygon(
new OpenLayers.Geometry.Point(e.point.x, e.point.y),
e.position.coords.accuracy/2,
40,
0
),
{},
style
);
geolocation.addFeatures([
new OpenLayers.Feature.Vector(
e.point,
{},
{
graphicName: 'cross',
strokeColor: '#f00',
strokeWidth: 2,
fillOpacity: 0,
pointRadius: 10
}
),
circle
]);
if (firstGeolocation) {
map.zoomToExtent(geolocation.getDataExtent());
pulsate(circle);
firstGeolocation = false;
this.bind = true;
}
});
mapControls.geolocate.events.register("locationfailed",this,function() {
\$("<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>Sorry, location detection failed. Please try again.</h1></div>").css({ "display": "block", "opacity": 0.96, "top": \$(window).scrollTop() + 100 })
.appendTo( \$.mobile.pageContainer )
.delay( 1500 )
.fadeOut( 400, function(){
\$(this).remove();
});
//OpenLayers.Console.log('Location detection failed');
});
<|start_filename|>mapmint-ui/templates/preview/modules/timeline/display.html<|end_filename|>
#import zoo
#import mapscript
#try
#set suffix=$suffix
#except
#set suffix=""
#end try
<div id="timeliners$suffix">
#try
#set m0=$m.getLayer(0)
#set isIndex=False
#except
#set m=mapscript.mapObj($conf["main"]["dataPath"]+"/indexes_maps/project_Index"+$conf["senv"]["last_index"]+".map")
#set isIndex=True
#end try
#set hasIndex=False
#for i in range(0,$m.numlayers)
#if $m.getLayer($i).metadata.get('mmClass')=="tl"
#set l=$m.getLayer($i)
#set steps=$l.metadata.get("mmSteps").split(',')
#set cnt=0
<div id="timeline$(l.name.replace(".","_"))" class="timeline" #if $m.web.metadata.get("mmActivatedLayers") and $m.web.metadata.get("mmActivatedLayers").count($l.name)>0#style="display:block"#else#style="display:none"#end if#>
<ul id="dates$l.name.replace(".","_")" class="dates">
#for j in steps
<li class="std#if $cnt==0# selected#end if#"><a href="#$(i)step$cnt">$j</a></li>
#set $cnt=$cnt+1
#end for
</ul>
<ul id="issues$l.name.replace('.','_')" class="issues">
#set $cnt=0
#set $jsStr=""
#for j in steps
<li id="step$(i)$cnt" class="std#if $cnt==0# selected#end if#">
<div class="innerTree">
<ul id="step$(i)00$cnt">
#if isIndex==True
#set m0=mapscript.mapObj($conf["main"]["dataPath"]+"/indexes_maps/timeline_PIndex"+$conf["senv"]["last_index"]+"_indexes_view_idx"+$conf["senv"]["last_index"]+"_step"+str($cnt)+".map")
#else
#set m0=mapscript.mapObj($conf["main"]["dataPath"]+"/maps/timeline_"+$conf["senv"]["last_map"]+"_"+$l.name+"_step"+str($cnt)+".map")
#end if
#set layer=m0.getLayer($i)
#set res=$layer.metadata.set("cstep",str($cnt))
$Template(file=$conf['main']['templatesPath']+"layer_display.tmpl",searchList={"m": $m0,"layer": $layer,"conf": $conf})
</ul>
#set $jsStr=$jsStr+'$("#step'+str($i)+'00'+str($cnt)+'").tree({checkbox: true,isAlreadyLoaded: false,dnd: false});'
#set $jsStr=$jsStr+'$("#step'+str($i)+'00'+str($cnt)+' .tree-checkbox0").hide();'
</div>
</li>
#set $cnt=$cnt+1
#end for
</ul>
<a href="#" id="next">+</a>
<a href="#" id="prev">-</a>
</div>
<script>
\$().timelinr({
runAfter:function(){
try{
#if isIndex
#if not(hasIndex)
#set m00=mapscript.mapObj($conf["main"]["dataPath"]+"/public_maps/project_indicateurs.map")
#set cid=i+$m00.numlayers
#set hasIndex=True
#end if
layersList[$(cid)].url=msUrl+"?map=$conf["main"]["dataPath"]/indexes_maps/timeline_PIndex$(conf["senv"]["last_index"])_indexes_view_idx$(conf["senv"]["last_index"])_step"+arguments[0]+".map";
layersList[$(cid)].redraw(true);
#else
layersList[$(i)].url=msUrl+"?map=$conf["main"]["dataPath"]/maps/timeline_$(conf["senv"]["last_map"])_$(layer.name)_step"+arguments[0]+".map";
layersList[$(i)].redraw(true);
#end if
}catch(e){}
},
arrowKeys: 'true',
containerDiv: "#timeline$(l.name.replace(".","_"))",
datesDiv: "#dates$(l.name.replace(".","_"))",
issuesDiv: "#issues$(l.name.replace(".","_"))"
});
$jsStr
</script>
#end if
#end for
</div>
<|start_filename|>mapmint-ui/templates/preview/modules/measure/line/control.js<|end_filename|>
,line: new OpenLayers.Control.Measure(OpenLayers.Handler.Path,{
persist: true,
geodesic: true,
displaySystem: "$m.web.metadata.get("tuom")",
handlerOptions: {layerOptions: {styleMap: styleMap}},
eventListeners: {
"measure": handleMeasurements
}
})
<|start_filename|>mapmint-ui/templates/preview/modules/routing/display_bs.html<|end_filename|>
#encoding UTF-8
#import zoo
#import mapfile.service as mms
#if $mms.getMetadata($m.web,'mmOT')
#set f0=$mms.getMetadata($m.web,'mmOT').split(',')
#if $f0.count('Routing')>0
#def printInputGroup($obj)
<div class="input-group">
<input class="form-control" id="$obj["id"]" placeholder="$obj["placeholder"]" type="text" />
<span class="input-group-btn" title="$obj["title"]" rel="tooltip">
<button class="btn btn-default" id="$obj["action"]["name"]"
type="button" onclick="app.addInteraction(\$(this));"><i class="fa $obj["action"]["type"]"></i></button>
</span>
</div>
#end def
<div role="tabpanel" class="tab-pane" id="routing-ui">
<div class="well sources-container">
<div class="padder">
<h5 class="sbt"><i class="fa fa-road"></i> $zoo._("Routing")</h5>
<div>
$zoo._("Starting point:")
</div>
$printInputGroup({"id":"start","title":$zoo._("Starting point"),"action":{"name":"setStart","type":"fa-flag"},"placeholder":$zoo._("Type an address")})
<div>
$zoo._("Destination:")
</div>
$printInputGroup({"id":"end","title":$zoo._("End point"),"action":{"name":"setEnd","type":"fa-flag-checkered"},"placeholder":$zoo._("Type an address")})
<div>
<div class="row myWell">
<div class="btn-group">
<button class="btn btn-default pull-right">
$zoo._("Compute route")
</button>
<button class="btn btn-default pull-right">
$zoo._("Add a step")
</button>
</div>
</div>
<a class="ui-state-default ui-corner-all" href="#" title="$zoo._("Compute route")" onclick="pgrouting(points_layer);">$zoo._("Compute route")</a>
</div>
<script type="text/template">
<div>
$zoo._("Step [n]:")
</div>
$printInputGroup({"id":"step_[nn]","title":$zoo._("Step [n]"),"action":{"name":"setStep","type":"fa-flag-o"},"placeholder":$zoo._("Type an address")})
</script>
</div>
</div>
</div>
#end if
#end if
<|start_filename|>mapmint-ui/templates/Publisher/confirmRemove.html<|end_filename|>
#encoding UTF-8
#import zoo
<div class="warning">
<h1>$zoo._("Do you really want to remove") $conf["senv"]["last_map"] ?</h1>
<p>$zoo._("Once removed, you cannot access the project anymore. You cannot recover a removed project. Deleting a project may destroy important data and make other projects unstable.")</p>
<a href="#" onclick="removePublishedMap()" class="mmbutton ui-state-default ui-corner-all">$zoo._("Yes")</a>
<a href="#" onclick="\$('#confirmRemoveProject').window('close');" class="mmbutton ui-state-default ui-state-default ui-corner-all">$zoo._("No")</a>
</div>
<|start_filename|>mapmint-ui/templates/Indexes/DocPart_bs.html<|end_filename|>
#encoding UTF-8
#import zoo
#import mm_access
#import authenticate.service as auth
#set con=auth.getCon($conf)
#set cur=con.conn.cursor()
#set prefix=auth.getPrefix($conf)
#*import np.service as np
#set outputs1={"Result":{"value":""}}
#set res=np.parseDocAttr($conf,{"template":$inputs["template"]},$outputs1)*#
#set res=$cur.execute("select id,label,name from "+$prefix+"ftypes order by id")
#set res=$cur.fetchall()
#set defaultTypes=["map","table","diag"]
#set tmpl=$conf['main']['templatesPath']+"/Distiller/form_line.html"
#include $tmpl
#set ftmpl=$self._CHEETAH__cheetahIncludes[$tmpl]
<div class="form-horizontal" id="repport">
<div class="row col-sm-12">
<label class="col-sm-3 control-label">
$zoo._("Document model")
</label>
<div class="form-group col-sm-6">
<form id="afileUpload" action="$conf["main"]["serverAddress"]?request=Execute&service=WPS&version=1.0.0&Identifier=upload.saveOnServer&dataInputs=file=upload" method="post" enctype="multipart/form-data" target="auploader">
<input type="file" name="file" id="file" class="form-control file" />
<a id="documents_afile_link" href="" target="_blank"></a>
<input type="hidden" id="documents_afilename" class="form-control" />
</form>
<iframe name="auploader" id="auploader" style="display:none"></iframe>
</div>
$ftmpl.printButton({"id":"import-doc","name":$zoo._("Import"),"classes":"btn-small col-sm-3" })
</div>
<div id="documents_repport_editor" >
</div>
<script type="txt/template" id="document_settings_container_template">
<table id="repport_display2">
<thead>
<th width="25">$zoo._("D.")</th>
<th width="105">$zoo._("Name")</th>
<th width="160">$zoo._("Type")</th>
<th width="205">$zoo._("Value")</th>
</thead>
<tbody>
[content]
</tbody>
</table>
$ftmpl.printButton({"id":"save-doc","name":$zoo._("Save"),"classes":"btn-small" })
$ftmpl.printButton({"id":"preview-doc","name":$zoo._("Preview"),"classes":"btn-small" })
</script>
<script type="txt/template" id="document_settings_line_template">
<tr>
<td><input type="checkbox" checked="checked" id="rtable_display_[x]" /></td>
<td><input type="hidden" value="[name]" id="rtable_name_[x]"/> [name]</td>
<td>
<select class="form-control" id="rtable_type_[x]">
#for j in res
<option value="$j[0]">$j[1]</option>
#end for
</select>
</td>
<td><textarea class="form-control" id="rtable_value_[x]"></textarea></td>
</tr>
</script>
</div>
<|start_filename|>mapmint-ui/templates/Publisher/Map.html<|end_filename|>
#encoding UTF-8
#import zoo,mapscript
#import mapfile.service as mms
<form class="form-horizontal mtpp" method="get" >
<h1> <i class="fa fa-map-o"></i> $zoo._("Display")</h1>
<div class="row">
<label class="col-sm-3 control-label">$zoo._("Navigation Toolbar")</label>
<div class="col-sm-9 range">
#from Cheetah.Template import Template
$(Template(file=$conf["main"]["templatesPath"]+"/Distiller/Projection.tmpl",searchList={"conf": $conf,"prefix":"","selected": $mms.getMetadata($m.web,'tprj')}))
</div>
</div>
<!--
<div class="row">
<label class="col-sm-3 control-label">$zoo._("Renderer Method")</label>
<div class="col-sm-9 range">
<select name="render" class="form-control">
<option value="SVG" #if $mms.getMetadata($m.web,'mmRenderer') is None or $mms.getMetadata($m.web,'mmRenderer')=='SVG'#selected#end if#>SVG</option>
<option value="Canvas" #if $mms.getMetadata($m.web,'mmRenderer') is not None and $mms.getMetadata($m.web,'mmRenderer')=='Canvas'#selected#end if#>Canvas</option>
</select>
</div>
</div>
<div class="row">
<label class="col-sm-3 control-label">$zoo._("Other Tools")</label>
<div class="col-sm-9 range">
<select name="render" class="form-control">
<option value="SVG" #if $mms.getMetadata($m.web,'mmRenderer') is None or $mms.getMetadata($m.web,'mmRenderer')=='SVG'#selected#end if#>SVG</option>
<option value="Canvas" #if $mms.getMetadata($m.web,'mmRenderer') is not None and $mms.getMetadata($m.web,'mmRenderer')=='Canvas'#selected#end if#>Canvas</option>
</select>
</div>
</div>
-->
<div class="row">
<div class="col-sm-12">
<table class="gen">
<thead>
<tr>
<th valign="middle" style="width:120px;">$zoo._("Extent")</th>
<th>X min</th>
<th>Y min</th>
<th>X max</th>
<th>Y max</th>
<th style="width: 30px;"></th>
</tr>
</thead>
<tbody>
#set labels=[$zoo._("Default"),$zoo._("Maximum"),$zoo._("Minimum")]
#set j=0
#for i in ['default','max','min']
<tr>
<td valign="middle" style="width:120px;">
$labels[$j]
#if $i=="max"
<input id="mmRestricted" class="rounded" type="checkbox" value="true" #if $mms.getMetadata($m.web,"mmRestricted")=="true"#checked="true"#end if# data-toggle="tooltip" title="$zoo._("Restricted")" />
#end if
</td>
#for k in ['minx','miny','maxx','maxy']
<td><input id="${i}_${k}" class="rounded" type="text" value="#if $mms.getMetadata($m.web,$i+'_'+$k)#$mms.getMetadata($m.web,$i+'_'+$k)#end if#" /></td>
#end for
<td style="width: 150px;">
<div id="form_move_$(i)" >
<select class="form-control" id="form_move_layer_$(i)" onchange="if(this.options[this.selectedIndex].value=='-1'){\$('#${i}_minx')[0].value='';\$('#${i}_miny')[0].value='';\$('#${i}_maxx')[0].value='';\$('#${i}_maxy')[0].value='';}else{var tmp=this.value.split(' ');\$('#${i}_minx')[0].value=tmp[0];\$('#${i}_miny')[0].value=tmp[1];\$('#${i}_maxx')[0].value=tmp[2];\$('#${i}_maxy')[0].value=tmp[3];}">
<option value="-1">$zoo._("Select")</option>
#for k in range(0,$m.numlayers)
#set l=$m.getLayer($k)
#if $l.name.count("grid_")==0
#try
#set iproj=mapscript.projectionObj($l.getProjection())
#except
#set iproj=mapscript.projectionObj("epsg:4326")
#end try
#set oproj=mapscript.projectionObj($m.getProjection())
#set toto=$l.getExtent()
#set va=$toto.project(iproj,oproj)
<option value="$toto.minx $toto.miny $toto.maxx $toto.maxy">$m.getLayer($k).name</option>
#end if
#end for
</select>
</div>
</td>
</tr>
#set j=$j+1
#end for
</tbody>
</table>
</div>
</div>
<h1> <i class="fa fa-th-large"></i> $zoo._("Layout")</h1>
<div class="row">
<label class="col-sm-3 control-label">$zoo._("Text settings")</label>
<div class="col-sm-3 range">
<select name="layoutFont" class="form-control">
<option value="-1" #if $mms.getMetadata($m.web,"ffamily")==""#selected="selected"#end if#>$zoo._("Font-family")</option>
#set fonts=["Arial","Courier","Georgia","Helvetica","Lucida","Tahoma","Trebuchet"]
#for i in fonts
<option style="font-family:${i};font-size:1.1em;" value="${i}" #if $mms.getMetadata($m.web,"ffamily")==$i#selected="selected"#end if#>${i}</option>
#end for
</select>
</div>
<div class="col-sm-3 range">
<select name="layoutFontSize" class="form-control">
<option value="-1" #if $mms.getMetadata($m.web,"fsize")==""#selected="selected"#end if#>$zoo._("Font-size")</option>
#for i in range(9,15)
<option style="font-size:${i}px;" value="$i" #if $mms.getMetadata($m.web,"fsize")==str($i)#selected="selected"#end if#>${i}px</option>
#end for
</select>
</div>
<div class="col-sm-3 range">
<div class="input-group cpicker">
<input type="text" class="form-control" id="mmFontColor" name="layoutFontColor" value="#if $mms.getMetadata($m.web,"font-colorpicker")==""#selected="selected"#\#333333#else#$mms.getMetadata($m.web,"font-colorpicker")#end if#" />
<span class="input-group-addon"><i></i></span>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-3 control-label">$zoo._("Layer Switcher Position")</label>
<div class="col-sm-3 range">
<select name="layerswitcherPosition" class="form-control">
#set fonts=[
[zoo._("Left"),"Left"],
[zoo._("Right"),"Right"]
]
#for i in fonts
<option value="${i[1]}" #if $mms.getMetadata($m.web,"mmLSPosition")==$i#selected="selected"#end if#>${i[0]}</option>
#end for
</select>
</div>
<label class="col-sm-3 control-label">$zoo._("Layer Switcher")</label>
<div class="col-sm-3 range">
<select name="layerswitcherOpen" class="form-control">
#set fonts=[zoo._("Open"),zoo._("Close")]
#for i in fonts
<option value="${i}" #if $mms.getMetadata($m.web,"mmLSPosition")==$i#selected="selected"#end if#>${i}</option>
#end for
</select>
</div>
</div>
</form>
<|start_filename|>mapmint-ui/templates/Manager/timeline.js<|end_filename|>
#import zoo
MMStyler={
startWindow: function(){
if(arguments.length>0)
System.styleIsStep=arguments[0];
else
System.styleIsStep=false;
if(System.startWindowStep)
System.startWindowStep();
\$.ajax({
type: "GET",
url: "$conf["main"]["serverAddress"]?service=WPS&version=1.0.0&request=Execute&Identifier=mapfile.createLegend&DataInputs=name="+(\$("#mapName").val()?\$("#mapName").val():"Index"+System.nodeId)+";layer="+System.mmNodeId+(System.styleIsStep?";mmStep="+(\$("#mmsteps")[0].selectedIndex-2):"")+(\$("#mmPrefix").val()?";prefix="+\$("#mmPrefix").val():"")+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
if(\$("#mapName").val()){
updateSelectWithFields(["gsField","ccField","usField","labelField","labelAngleField"]);
\$( "#style-dialog" ).html(xml.responseText);
\$( "#style-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false,
height:460,
width:500
});
\$(".hasInfo").tipsy({fade: true, offset:3, opacity: 1, gravity: 'se'});
}else
\$("#indexStyle").html(xml.responseText);
try{
\$(".flexiClasses").flexigrid({title: 'Classes', noSelection: true,height: (\$("#dropdown").val()=='gradSymb'?140:180), rp: 4, usepager: false, resizable: false});
}catch(e){}
if(\$("#opacity").val())
\$( "#slider-opacity" ).slider({
value:\$("#opacity").val().replace("%",""),
min: 0,
max: 100,
step: 1,
slide: function( event, ui ) {
\$("#opacity").val(ui.value + "%" );
}
});
if(\$('#dropdown').val()=="uniqSymb")
\$("#opacityOnly").hide();
try{
\$("#ccLegend")[0].src="$conf["main"]["serverAddress"]?request=Execute&service=WPS&version=1.0.0&Identifier=classifier.getClassifierImage&DataInputs=from="+\$("#cc-min-colorpicker")[0].value.replace("#","")+";to="+\$("#cc-max-colorpicker")[0].value.replace("#","")+";nbClass=24&RawDataOutput=Result"
}catch(e){}
try{
\$(function () {
var tabContainers = \$('div.style-tabs > div');
tabContainers.hide().filter(':first').show();
\$('div.style-tabs ul.style-tabs-nav a').click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
\$('div.style-tabs ul.style-tabs-nav a').removeClass('selected');
\$(this).addClass('selected');
return false;
}).filter(':first').click();
});
}catch(e){}
try{
\$('#divuniqSymb, #divgradSymb, #divcontCol, #divuniqVal').hide();
\$('#dropdown').change(function() {
if(\$("#dropdown").val()!="timeline"){
\$(".tl").hide();
\$('.box').hide();
\$('#div' + \$(this).val()).show();
}else{
\$(".tl").show();
}
});
\$('#dropdown1').change(function() {
\$('.box').hide();
\$('#div' + \$(this).val()).show();
});
}catch(e){}
\$('.box').hide();
if(\$('#dropdown')[0]){
if(\$('#dropdown').val()!="timeline")
\$('#div' +\$('#dropdown').val()).show();
else{
\$('#div' +\$('#dropdown1').val()).show();
for(i=0;i<map.layers.length;i++)
if(map.layers[i].local_id==System.mmNodeId){
map.layers[i].url="$conf["main"]["mapserverAddress"]?map=$conf["main"]["dataPath"]/maps/timeline_"+\$("#mapName")[0].value+"_"+System.mmNodeId+"_step"+(\$("#mmsteps")[0].selectedIndex-2)+".map";
map.layers[i].redraw(true);
}
}
}
else
\$('#divuniqSymb').show();
\$(function() {
try{
\$('#fill-colorpicker').colorPicker();
\$('#stroke-colorpicker').colorPicker();
\$('#nodata-colorpicker').colorPicker();
\$('#cc-min-colorpicker').colorPicker();
\$('#cc-max-colorpicker').colorPicker();
\$('#font-colorpicker').colorPicker();
\$('#us-min-colorpicker').colorPicker();
\$('#us-max-colorpicker').colorPicker();
\$('#gs-min-colorpicker').colorPicker();
\$('#gs-max-colorpicker').colorPicker();
\$('#buffer-font-colorpicker').colorPicker();
System.isRaster=false;
}catch(e){
alert(e);
System.isRaster=true;
}
for(var i=0;i<toRunAfter.length;i++){
toRunAfter[i]();
}
});
}
});
},
Timeline: {
startStepEditor: function (){
\$.ajax({
type: "GET",
url: "Manager/Styler/AddStep",
complete: function(xml,status) {
if(\$( "#view-addstep-dialog" )[0]){
\$( "#view-addstep-dialog" ).window('close');
\$( "#view-addstep-dialog" ).parent().remove();
}
\$( "body" ).append('<div id="view-addstep-dialog" title="$zoo._("Add step in timeline")"></div>');
\$( "#view-addstep-dialog" ).html("");
\$( "#view-addstep-dialog" ).append(xml.responseText);
\$( "#view-addstep-dialog" ).window({
collapsible:false,
minimizable:false,
maximizable:false,
draggable:true,
resizable: false
});
}
});
},
saveStep: function (){
\$.ajax({
type: "GET",
url: System.zooUrl+"?version=1.0.0&service=WPS&request=Execute&service=WPS&Identifier=mapfile."+(arguments.length==0?"saveStep":"removeStep")+"&dataInputs=layer="+System.mmNodeId+";name="+\$("#mmStepName").val()+(\$("#mmPrefix").val()?";prefix="+\$("#mmPrefix").val():"")+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml)){
\$( "#view-addstep-dialog" ).window('close');
\$( "#view-addstep-dialog" ).parent().remove();
MMStyler.Timeline.refreshStepList();
}
}
});
},
deleteStep: function (){
\$.ajax({
type: "GET",
url: System.zooUrl+"?version=1.0.0&service=WPS&request=Execute&service=WPS&Identifier=mapfile.deleteStep&dataInputs=layer="+System.mmNodeId+";name="+\$("#mmsteps").val()+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml)){
\$( "#view-addstep-dialog" ).window('close');
\$( "#view-addstep-dialog" ).parent().remove();
MMStyler.Timeline.refreshStepList();
}
}
});
},
refreshStepList: function(){
\$.ajax({
type: "GET",
url: System.zooUrl+"?version=1.0.0&service=WPS&request=Execute&service=WPS&Identifier=mapfile.listStep&dataInputs=layer="+System.mmNodeId+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
json=new OpenLayers.Format.JSON();
var tmp=json.read(xml.responseText);
\$('#mmsteps option').each(function() {
if ( \$(this).val() != '-1' && \$(this).val() != 'add') {
\$(this).remove();
}
});
for(i=0;i<tmp.length;i++){
if(i==0)
System.stepId=tmp[i];
var o = new Option(tmp[i],tmp[i]);
\$(o).html(tmp[i]);
\$("#mmsteps").append(o);
}
if(System.runAfterStep)
System.runAfterStep();
if(!System.break)
\$("#mmDeleteStep").hide();
}
}
});
}
}
}
<|start_filename|>mapmint-ui/new-themes/themes/green/tree.css<|end_filename|>
.tree-node-selected{
background:#99CC66;
}
.menu-active{
border:1px solid #ADEF73;
background:#fafafa;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
behvior: url(js/ie-css3.htc);
}
<|start_filename|>public_map/assets/js/spatialtools-py-app.js<|end_filename|>
// Filename: app.js
/*
This work was supported by a grant from the European Union's 7th Framework Programme (2007-2013)
provided for the project PublicaMundi (GA no. 609608).
*/
//require(['bootstrap', 'notify']);
define([
'module', 'jquery', 'zoo', 'xml2json',
], function(module, $, Zoo, X2JS) {
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
});
var mymodal = $('#myModal');
/**
*
* Complex payload callback functions
*/
//
window.complexPayload_InputPolygon_JSON = function() {
return '{"type":"Polygon","coordinates":[[[-102.036758,36.988972],[-106.860657,36.989491],[-109.047821,36.996643],[-109.055199,38.24493],[-109.052864,39.518196],[-109.050591,40.210545],[-109.047638,40.998474],[-107.918037,41.00341],[-104.051201,41.003227],[-102.620789,41.000225],[-102.047279,40.998077],[-102.04557,40.697323],[-102.036758,36.988972]]]}';
}
window.complexPayload_GML = function() {
return '<wfs:GetFeature xmlns:wfs="http://www.opengis.net/wfs" service="WFS" version="1.1.0" maxFeatures="10" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><wfs:Query typeName="states" srsName="EPSG:4326"><ogc:Filter xmlns:ogc="http://www.opengis.net/ogc"><ogc:BBOX><ogc:PropertyName>the_geom</ogc:PropertyName><gml:Envelope xmlns:gml="http://www.opengis.net/gml" srsName="EPSG:4326"><gml:lowerCorner>-98.417969 29.498046625</gml:lowerCorner><gml:upperCorner>-97.53906275 30.376952875</gml:upperCorner></gml:Envelope></ogc:BBOX></ogc:Filter></wfs:Query></wfs:GetFeature>';
}
function notify(text, type) {
/*mynotify.notify({
message: { text: text },
type: type,
}).show();*/
}
function showModal(title, body) {
mymodal.find('.modal-body').text('');
mymodal.find('.modal-body').append(body);
mymodal.find('.modal-title').text(title);
var options = {};
mymodal.modal(options);
}
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
var map, SubwayStops, layer;
var pop;
function onPopupClose(){
if(pop)
map.removePopup(pop);
}
function createPopup(){
var tmp=arguments[0].geometry.getCentroid();
if(pop)
map.removePopup(pop);
var attrs='<div style="color: #000;"><table>';
for(var i in arguments[0].data)
if(i!="gml_id")
attrs+="<tr><td width='100' style='font-weight: bold;'>"+i+"</td><td>"+arguments[0].data[i]+"</td></tr>";
attrs+="</table></div>";
pop=new OpenLayers.Popup.FramedCloud("Information",
arguments[0].geometry.getBounds().getCenterLonLat(),
new OpenLayers.Size(100,100),
"<h2>"+arguments[0].data.name+"</h2>"+attrs,
null, true,onPopupClose);
map.addPopup(pop);
}
function unSelect(){
if(pop)
map.removePopup(pop);
//alert(arguments[0]);
}
function parseMapServerId(){
try{
var sf=arguments[0].split(".");
return sf[0]+"."+sf[1].replace(/ /g,'');
}catch(e){}
}
function toggleControl(element) {
for(key in mapControls) {
var control = mapControls[key];
//alert ($(element).is('.ui-state-active'));
if(element.name == key && $(element).is('.ui-state-active')) {
control.activate();
} else {
control.deactivate();
}
}
}
function restartDisplay(){
var tmp=[select,hover_,hover,multi];
for(i=0;i<tmp.length;i++)
if(tmp[i].features.length>=1)
tmp[i].removeFeatures(tmp[i].features);
slist=$(".single-process:not(.ui-state-disabled)");
for(var i=0;i<slist.length;i++)
slist[i].style.display='none';
mlist=$(".multi-process:not(.ui-state-disabled)");
for(var i=0;i<mlist.length;i++)
mlist[i].style.display='none';
}
function singleProcessing(aProcess) {
if (select.features.length == 0)
return alert("No feature selected!");
if(multi.features.length>=1)
multi.removeFeatures(multi.features);
var started=true;
var dep=hover;
if(arguments.length>1){
dep=arguments[1];
started=false;
}
var xlink = control.protocol.url +"&SERVICE=WFS&REQUEST=GetFeature&VERSION=1.0.0";
xlink += '&typename='+control.protocol.featurePrefix;
xlink += ':'+control.protocol.featureType;
xlink += '&SRS='+control.protocol.srsName;
xlink += '&FeatureID='+parseMapServerId(select.features[0].fid);
var inputs=[{"identifier":"InputPolygon","href":xlink,"mimeType":"text/xml"}];
var isChain2=false;
if(aProcess=="SimpleChain2"){
aProcess="BufferRequest";
isChain2=true;
}
for(var i in activatedServices)
if(aProcess==i){
inputs[0].identifier="InputData";
break;
}
if (aProcess == 'Buffer' || aProcess == 'BufferPy') {
inputs.push({"identifier":"BufferDistance","value":"0.001","dataType":"integer"})
}
/*var my_request=zoo.getRequest({identifier: aProcess,
dataInputs: inputs,
dataOutputs: [{"identifier":"Result","mimeType":"application/json","type":"raw"}],
type: 'POST',
storeExecuteResponse: false});
var my_request1=zoo.getRequest({identifier: aProcess,
dataInputs: [{"identifier":"InputPolygon","complexPayload": my_request.data,"href":my_request.url,"headers":[{"key":"Content-Type","value":"text/xml"}],"method": "POST","mimeType":"text/xml"}],
dataOutputs: [{"identifier":"Result","mimeType":"application/json","type":"raw"}],
type: 'POST',
storeExecuteResponse: false});
alert(my_request1.data);
console.log(my_request);*/
console.log(inputs);
zoo.execute({
identifier: aProcess,
dataInputs: inputs,
dataOutputs: [{"identifier":"Result","mimeType":"application/json","type":"raw"}],
type: 'POST',
storeExecuteResponse: false,
success: function(data) {
notify('Execute succeded', 'success');
console.log(data);
var GeoJSON = new OpenLayers.Format.GeoJSON();
var features = GeoJSON.read(JSON.stringify(data));
console.log(features);
dep.removeFeatures(dep.features);
if(aProcess!="SimpleChain1" && aProcess!="SimpleChain2"
&& aProcess!="BufferRequest")
if(dep!=hover_)
hover_.removeFeatures(hover_.features);
for(var j in features){
features[j].geometry=features[j].geometry.transform(wgs84,mercator);
}
dep.addFeatures(features);
},
error: function(data) {
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
}
});
if(isChain2 && started)
singleProcessing("BufferMask",hover_);
}
function multiProcessing(aProcess) {
if (select.features.length == 0 || hover.features.length == 0)
return alert("No feature created!");
var xlink = control.protocol.url +"&SERVICE=WFS&REQUEST=GetFeature&VERSION=1.0.0";
xlink += '&typename='+control.protocol.featurePrefix;
xlink += ':'+control.protocol.featureType;
xlink += '&SRS='+control.protocol.srsName;
xlink += '&FeatureID='+select.features[0].fid;
var GeoJSON = new OpenLayers.Format.GeoJSON();
lfeatures=[];
for(var i in hover.features){
lfeatures.push(hover.features[i].clone());
lfeatures[i].geometry=lfeatures[i].geometry.transform(mercator,wgs84);
}
var inputs=[{"identifier":"InputEntity1","href":xlink,"mimeType":"text/xml"},
{"identifier":"InputEntity2","value":GeoJSON.write(lfeatures),"mimeType":"application/json"}];
zoo.execute({
identifier: aProcess,
dataInputs: inputs,
dataOutputs: [{"identifier":"Result","mimeType":"application/json","type":"raw"}],
type: 'POST',
storeExecuteResponse: false,
success: function(data) {
notify('Execute succeded', 'success');
console.log(data);
var GeoJSON = new OpenLayers.Format.GeoJSON();
var features = GeoJSON.read(JSON.stringify(data));
if(multi.features)
multi.removeFeatures(multi.features);
for(var j in features){
features[j].geometry=features[j].geometry.transform(wgs84,mercator);
}
multi.addFeatures(features);
},
error: function(data) {
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
}
});
}
function activateService(){
try{
$("#buttonBar").append('<a href="#" class="fg-button ui-state-default ui-text-only ui-corner-all single-process process" title="'+(arguments[0]!="SimpleChain2"?arguments[0]:"BufferRequestAndMask")+'" name="'+(arguments[0]!="SimpleChain2"?arguments[0]:"BufferRequestAndMask")+'" onclick="app.singleProcessing(\''+(arguments[0]!="SimpleChain2"?arguments[0]:"SimpleChain2")+'\');"> '+(arguments[0]!="SimpleChain2" && arguments[0]!="BufferMask" && arguments[0]!="BufferRequest"?arguments[0]:(arguments[0]!="BufferMask" && arguments[0]!="BufferRequest"?"Buffer Request and Mask":arguments[0]!="BufferRequest"?"Buffer Mask":"Buffer Request"))+' </a>');
elist=$('.process');
for(var i=0;i<elist.length;i++){
elist[i].style.display='none';
}
}catch(e){
alert(e);
}
}
//
var initialize = function() {
self = this;
// DescribeProcess button
$('.btn.describeprocess').on('click', function(e) {
e.preventDefault();
self.describeProcess(this.dataset);
});
// GetCapabilities button
$('.btn.getcapabilities').on('click', function(e) {
e.preventDefault();
self.getCapabilities(this.dataset);
});
// Execute synchrone button
$('.btn.executesynchrone').on('click', function(e) {
e.preventDefault();
self.executeSynchrone(this.dataset);
});
// Launch executeasynchrone button
$('.btn.executeasynchrone').on('click', function(e) {
e.preventDefault();
self.executeAsynchrone(this.dataset);
});
// Launch longProcess button
$('.btn.longprocess').on('click', function(e) {
e.preventDefault();
self.longProcessDemo(this.dataset);
});
// Misc tests
$('.btn.testalert').on('click', function(e) {
e.preventDefault();
var type = this.dataset.type;
notify('This is a message.', type);
});
zoo.getCapabilities({
type: 'POST',
success: function(data){
var processes=data["Capabilities"]["ProcessOfferings"]["Process"];
for(var i in activatedServices){
for(var j=0;j<processes.length;j++)
if(i==processes[j].Identifier){
activateService(i);
activatedServices[i]=true;
if(activatedServices["BufferRequest"] && activatedServices["BufferMask"] && !hasSimpleChain){
activateService("SimpleChain2");
activatedServices["BufferRequestAndMask"]=true;
hasSimpleChain=true;
}
if(i=="BufferMask")
if(activatedServices["BufferRequest"]){
activateService("SimpleChain2");
activatedServices["BufferRequestAndMask"]=true;
}
break;
}
}
}
});
wgs84=new OpenLayers.Projection("EPSG:4326"); // transform from WGS 1984
mercator=new OpenLayers.Projection("EPSG:900913"); // to Spherical Mer
var mybounds = new OpenLayers.Bounds(-109.060636, 36.992427,
-102.042531, 41.004493);
mybounds=mybounds.transform(wgs84,mercator);
map = new OpenLayers.Map('map', {
projection: new OpenLayers.Projection("EPSG:900913"),
units: "m",
maxExtent: mybounds,
controls: [
new OpenLayers.Control.Navigation()
]
});
arrayOSM = ["http://otile1.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png",
"http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png",
"http://otile3.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png",
"http://otile4.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png"];
layerLS=new OpenLayers.Layer.OSM("MapQuest-OSM Tiles", arrayOSM);
layer = new OpenLayers.Layer.WMS("ways",
main_url,
{layers: typename, transparent:'true', format: 'image/png'},
{isBaseLayer: false, sphericalMercator: true, visibility: true, opacity: 0.6}
);
layer.setVisibility(true);
var myStyleMap=new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
strokeColor: "#5555ee",
pointRadius: 4,
strokeWidth: 4
})
});
var myStyleMap1=new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
strokeColor: "#000000",
pointRadius: 4,
strokeWidth: 1
}, {
rules: [
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LIKE,
property: "name",
value: "Cafe:%"
}),
symbolizer: {
fillColor: "#ffaaaa",
pointRadius: 4,
strokeWidth: 1
}
}),
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LIKE,
property: "name",
value: "Restaurant:*"
}),
symbolizer: {
fillColor: "#aaffaa",
pointRadius: 4,
strokeWidth: 1
}
}),
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LIKE,
property: "name",
value: "Cafe:*"
}),
symbolizer: {
fillColor: "#444444",
fillOpacity: 1,
strokeOpacity: 0.4,
pointRadius: 4,
strokeWidth: 1
}
}),
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LIKE,
property: "name",
value: "Hotel:*"
}),
symbolizer: {
fillColor: "#aaaaff",
fillOpacity: 1,
strokeOpacity: 0.4,
pointRadius: 4,
strokeWidth: 1
}
}),
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LIKE,
property: "name",
value: "Recycling"
}),
symbolizer: {
fillColor: "#66ff66",
pointRadius: 4,
strokeWidth: 1
}
}),
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LIKE,
property: "fid",
value: "29547"
}),
symbolizer: {
fillColor: "#ffffff",
pointRadius: 6,
strokeWidth: 1
}
}),
new OpenLayers.Rule({
elseFilter: true,
symbolizer: {
fillColor: "#aaaaff",
opacity: 0.7,
pointRadius: 4,
fillOpacity: 0.4,
strokeWidth: 1
}
})
]
})
});
select1 = new OpenLayers.Layer.Vector("Selection", {styleMap:
myStyleMap
});
select = new OpenLayers.Layer.Vector("Selection", {styleMap:
myStyleMap
});
hover_ = new OpenLayers.Layer.Vector("Hover_", {styleMap:
new OpenLayers.Style({
fillColor:"grey",
fillOpacity:0.4,
strokeColor:"grey",
strokeOpacity:0.6,
strokeWidth:4
})
});
hover = new OpenLayers.Layer.Vector("Hover", {styleMap:myStyleMap1
/*new OpenLayers.Style({
fillColor:"pink",
fillOpacity:0.6,
strokeColor:"red",
strokeOpacity:1,
strokeWidth:2,
pointRadius: 3.5
})*/
});
multi = new OpenLayers.Layer.Vector("Multi", {styleMap:
new OpenLayers.Style({
fillColor:"yellow",
fillOpacity:0.6,
strokeColor:"red",
strokeOpacity:1,
strokeWidth:4
})
});
map.addLayers([ layerLS, layer, select, hover_, hover, multi]);
var protocol = OpenLayers.Protocol.WFS.fromWMSLayer(layer, {
featurePrefix: 'ms',
geometryName: 'msGeometry',
featureType: typename,
srsName: "EPSG:900913",
version: "1.0.0"
});
control = new OpenLayers.Control.GetFeature({
protocol: protocol,
box: false,
hover: false,
multipleKey: "shiftKey",
toggleKey: "ctrlKey"
});
control.events.register("featureselected", this, function(e) {
e.feature.geometry=e.feature.geometry.transform(wgs84,mercator);
select.addFeatures([e.feature]);
elist=$(".single-process:not(.ui-state-disabled)");
for(var i=0;i<elist.length;i++)
elist[i].style.display='block';
if(hover.features.length>=1){
slist=$(".multi-process:not(.ui-state-disabled)");
for(var i=0;i<slist.length;i++)
slist[i].style.display='block';
}
});
control.events.register("featureunselected", this, function(e) {
select.removeFeatures([e.feature]);
});
control.events.register("hoverfeature", this, function(e) {
hover.addFeatures([e.feature]);
});
control.events.register("outfeature", this, function(e) {
hover.removeFeatures([e.feature]);
});
map.addControl(control);
control.activate();
control1=new OpenLayers.Control.SelectFeature(hover,{hover: true, clickFeature:createPopup, onUnselect:unSelect});
map.addControl(control1);
control1.activate();
var tmp=new OpenLayers.LonLat(-122.684273,45.512334);
tmp=tmp.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
);
map.setCenter(tmp,16);
//alert(map.getExtent().transform(mercator,wgs84));
mapControls=map.controls;
}
//
var getCapabilities = function (params) {
//var target = $(params.target);
zoo.getCapabilities({
type: params.method,
success: function(data) {
// Define some usefull functions for templating.
data.setUpIndex = function() {
return ++window['INDEX']||(window['INDEX']=0);
};
data.getIndex = function() {
return window['INDEX'];
};
data.resetIndex = function() {
window['INDEX']=null;
return;
};
console.log(data);
// Render.
var accordion = tpl_getCapabilities(data);
//target.append(accordion);
showModal("test", accordion)
// Details button
$('.showdetails').on('click', function(e) {
e.preventDefault();
console.log(this.dataset);
var $this = $(this);
var $collapse = $this.closest('.panel-body').find('.collapse');
zoo.describeProcess({
identifier: this.dataset.identifier,
success: function(data) {
var details = tpl_describeProcess(data);
$collapse.hide();
$collapse.text('');
$collapse.append(details);
$collapse.show();
},
error: function(data) {
$collapse.hide();
$collapse.text('');
$collapse.append("ERROR");
$collapse.show();
}
});
});
},
error: function(data) {
notify('GetCapabilities failed', 'danger');
//target.append('ERROR');
}
});
};
//
var describeProcess = function(params) {
//var target = $(params.target);
zoo.describeProcess({
identifier: params.identifier,
type: params.method,
success: function(data) {
var details = tpl_describeProcess(data);
//target.text('');
//target.append(details);
var title = 'DescribeProcess '+params.identifier;
showModal(title, details);
},
error: function(data) {
notify('DescribeProcess failed', 'danger');
}
});
};
//
var executeSynchrone = function(params) {
var target = $(params.target);
notify('Calling Execute synchrone ...', 'info');
zoo.execute({
identifier: params.identifier,
dataInputs: params.inputs ? JSON.parse(params.inputs) : null,
dataOutputs: params.outputs ? JSON.parse(params.outputs) : null,
type: params.method,
storeExecuteResponse: false,
success: function(data) {
notify('Execute succeded', 'success');
var details = tpl_executeResponse(data);
target.text('');
target.append(details);
var output = data.ExecuteResponse.ProcessOutputs.Output;
console.log('======== OUTPUT ========');
console.log(output);
if (output.hasOwnProperty('Data')) {
console.log("FOUND DATA");
if (output.Data.hasOwnProperty('ComplexData')) {
console.log("FOUND COMPLEX DATA");
if (output.Data.ComplexData.hasOwnProperty('__cdata')) {
console.log('FOUND CDATA');
showModal('Execute '+params.identifier, output.Data.ComplexData.__cdata);
}
else {
console.log('SHOWING COMPLEX DATA');
console.log(output.Data.ComplexData);
var _x2js = new X2JS({
arrayAccessFormPaths: [
'ProcessDescriptions.ProcessDescription.DataInputs.Input',
'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
'Capabilities.ServiceIdentification.Keywords'
],
});
showModal('Execute '+params.identifier, _x2js.json2xml_str(output.Data.ComplexData));
}
}
} else if (output.hasOwnProperty('Reference')) {
console.log("FOUND REFERENCE");
showModal('Execute '+params.identifier, output.Reference._href);
}
},
error: function(data) {
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
}
});
};
//
var executeAsynchrone = function(params) {
var target = $(params.target);
notify('Calling Execute asynchrone ...', 'info');
zoo.execute({
identifier: params.identifier,
dataInputs: params.inputs ? JSON.parse(params.inputs) : null,
dataOutputs: params.outputs ? JSON.parse(params.outputs) : null,
type: params.method,
storeExecuteResponse: true,
status: true,
success: function(data) {
console.log("**** SUCCESS ****");
notify('Execute succeded', 'success');
var details = tpl_executeResponse_async(data);
target.text('');
target.append(details);
},
error: function(data) {
notify('Execute failed', 'danger');
}
});
}
//
var longProcessDemo = function(params) {
var progress = $(params.target);
progress.removeClass("progress-bar-success").addClass("progress-bar-info");
zoo.execute({
identifier: params.identifier,
type: params.method,
dataInputs: params.inputs ? JSON.parse(params.inputs) : null,
dataOutputs: params.outputs ? JSON.parse(params.outputs) : null,
storeExecuteResponse: true,
status: true,
success: function(data, launched) {
console.log("**** SUCCESS ****");
console.log(launched);
notify("Execute asynchrone launched: "+launched.sid, 'info');
// Polling status
zoo.watch(launched.sid, {
onPercentCompleted: function(data) {
console.log("**** PercentCompleted ****");
console.log(data);
progress.css('width', (data.percentCompleted)+'%');
progress.text(data.text+' : '+(data.percentCompleted)+'%');
},
onProcessSucceeded: function(data) {
//console.log("**** ProcessSucceeded ****");
//console.log(data);
progress.css('width', (100)+'%');
progress.text(data.text+' : '+(100)+'%');
progress.removeClass("progress-bar-info").addClass("progress-bar-success");
// TODO: multiple output
if (data.result.ExecuteResponse.ProcessOutputs) {
var output = data.result.ExecuteResponse.ProcessOutputs.Output;
var id = output.Identifier.__text;
var text = output.Data.LiteralData.__text;
console.log(id+': '+text);
notify("Execute asynchrone "+id+': '+text, 'success');
}
},
onError: function(data) {
console.log("**** onError ****");
console.log(data);
notify("Execute asynchrone failed", 'danger');
},
});
},
error: function(data) {
console.log("**** ERROR ****");
console.log(data);
notify("Execute asynchrone failed", 'danger');
},
});
};
// Return public methods
return {
initialize: initialize,
singleProcessing: singleProcessing,
multiProcessing: multiProcessing,
restartDisplay: restartDisplay,
describeProcess: describeProcess,
getCapabilities: getCapabilities,
executeSynchrone: executeSynchrone,
executeAsynchrone: executeAsynchrone,
longProcessDemo: longProcessDemo
};
});
<|start_filename|>mapmint-ui/new-themes/themes/green/misc.css<|end_filename|>
.tabs-right ul li:hover, .maps-container ul li:hover {cursor:pointer;
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
background: -ms-linear-gradient(#C2FF7E, #4FA33F);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F');
}
<|start_filename|>mapmint-ui/js/flip.js<|end_filename|>
function bindNews(){
$('.news').click(function(e){
if($(this)[0].id)
$.ajax({
type: "GET",
url: "./modules/news/display;back=true;id="+$(this)[0].id.replace(/news_/g,""),
dataType: "xml",
complete: function(xml,status) {
$('#news_display').html(xml.responseText);
$('#news_block').toggleClass('flipped');
if(!$.support.css3d){
$('#main_content_bg').toggle();
}
e.preventDefault();
}
});
else{
$('#news_block').toggleClass('flipped');
if(!$.support.css3d){
$('#main_content_bg').toggle();
}
e.preventDefault();
}
});
}
function loadIPage(){
$.ajax({
type: "GET",
url: "./ipage;back=true;idp="+arguments[0],
dataType: "xml",
complete: function(xml,status) {
$('#main_content_bg').html(xml.responseText);
/*$('#m_content').toggleClass('flipped');
if(!$.support.css3d){*/
$('#main_content').toggle();
$('#main_content_bg').toggle();
/*}*/
/*$(".home").click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).fadeIn();
return false;
});*/
}
});
}
$(function(){
$.support.css3d = supportsCSS3D();
var formContainer = $('#formContainer');
/*$('.flipLink').click(function(e){
formContainer.toggleClass('flipped');
if(!$.support.css3d){
$('#login').toggle();
}
e.preventDefault();
});*/
bindNews();
formContainer.find('form').submit(function(e){
e.preventDefault();
});
function supportsCSS3D() {
var props = [
'perspectiveProperty', 'WebkitPerspective', 'MozPerspective'
], testDom = document.createElement('a');
for(var i=0; i<props.length; i++){
if(props[i] in testDom.style){
return true;
}
}
return false;
}
});
<|start_filename|>mapmint-ui/css/all-ie-only.css<|end_filename|>
#maincfg1 {background:url(../img/monitor.png) no-repeat;width:24px;height:24px;}
#maincfg2 {background:url(../img/security.png) no-repeat;width:24px;height:24px;}
#maincfg3 {background:url(../img/user.png) no-repeat;width:24px;height:24px;}
<|start_filename|>public_map/assets/js/importers.js<|end_filename|>
// Filename: login.js
define([
'module', 'jquery', 'zoo','notify', 'metisMenu', 'summernote', 'xml2json','typeahead', 'adminBasic', 'ol','datasources','mmDataTables','rowReorder','colorpicker','slider',"sortable","colReorder","managerTools"
], function(module, $,Zoo,notify, metisMenu, summernote, X2JS,typeahead,adminBasic,ol,datasources,MMDataTable,rowReorder,colorpicker,slider,sortable,colReorder,managerTools) {
(function(){
var methods = ['addClass', 'removeClass'];
$.each(methods, function (index, method) {
var originalMethod = $.fn[method];
$.fn[method] = function () {
var oldClass = this.className;
var result = originalMethod.apply(this, arguments);
var newClass = this.className;
this.trigger(method, [oldClass, newClass]);
return result;
};
});
})();
var _x2js = new X2JS({
arrayAccessFormPaths: [
'ProcessDescriptions.ProcessDescription.DataInputs.Input',
'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
'Capabilities.ServiceIdentification.Keywords'
],
});
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
language: module.config().language
});
var llevels=["first","second","third","forth"];
var llevelInit=false;
var reg0=new RegExp("documents_","");
var reloadElement=true;
var tableName="mm_tables.importers";
var fileName="";
var isAttributes=true;
var attributes=[];
var attributes_index=[];
var values=[];
function loadElements(table,init){
zoo.execute({
identifier: "np.list",
type: "POST",
dataInputs: [
{"identifier": "table","value": table,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
if(!reloadElement)
return;
if(init){
if($("#listElements").find("#document_"+localId).length){
console.log($("#listElements").find("#document_"+localId).hasClass("selected"));
if(!$("#listElements").find("#document_"+localId).hasClass("selected"))
$("#listElements").find("#document_"+localId).click();
else{
for(var i=0;i<2;i++)
$("#listElements").find("#document_"+localId).click();
}
}else{
loadAnElement(localId);
}
}
else
for(var i=0;i<data.length;i++){
if(data[i]["selected"]){
if($("#listElements").find("#document_"+data[i]["id"]).length){
$("#listElements").find("#document_"+data[i]["id"]).click();
}else{
loadAnElement(data[i]["id"]);
}
break;
}
}
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function fileUrlSelection(data){
$("input#file").val("");
if(data["url"]==null){
$("input[name=doct]").first().prop("checked",true);
$("input[name=doct]").first().click();
$("#documents_file_link").attr("href",module.config().publicationUrl+"/documents/"+data["file"]);
$("#documents_file_link").html(data["file"]);
}
else{
$("input[name=doct]").last().prop("checked",true);
$("input[name=doct]").last().click();
$("#documents_file_link").attr("href","");
$("#documents_file_link").html("");
}
}
function fillGeoreferencing(data){
console.log("**********-------------*************");
var cnt=0;
$("select[name='georef_field']").each(function(){
if(cnt>0)
$(this).parent().parent().remove();
cnt++;
});
for(var key in data.pages){
console.log(data.pages[key]["georef"]);
if(data.pages[key]["georef"] && data.pages[key]["georef"].length>0){
console.log("**********-------------*************");
for(var i=0;i<data.pages[key]["georef"].length;i++){
var currentGeoref=data.pages[key]["georef"][i];
$("#document_georef_id").val(currentGeoref.id);
console.log($("#document_georef_id").val());
console.log("**********-------------*************");
console.log(" REQUIRE TO LOAD THE FIELDS !");
$("#documents_georef_method").val(currentGeoref.fields.length==0?-1:currentGeoref.fields.length>2?"georef":"coord").change();
for(var i=0;i<currentGeoref.fields.length;i++){
if(i>0){
$("a.georef_add").click();
console.log("**********------ CLICK -------*************");
}
console.log("select[name='georef_field']:eq("+i+")");
console.log($("select[name='georef_field']:eq("+i+")"));
console.log(currentGeoref.fields[i]["column_name"]);
$("select[name='georef_field']:eq("+i+")").val(currentGeoref.fields[i]["column_name"]);
if(i>0){
console.log("input[name='georef_sep']:eq("+(i-1)+")");
console.log($("input[name='georef_sep']:eq("+(i-1)+")"));
$("input[name='georef_sep']:eq("+(i-1)+")").val(currentGeoref.fields[i]["separator"]);
}
console.log(currentGeoref.fields[i]);
}
console.log("**********-------------*************");
}
console.log("**********-------------*************");
}
}
}
var hasBeenDone=false;
function fillForm(data){
$(".project-title").html(data["name"]+' <i class="fa fa-'+(data["published"]=="false"?"exclamation":"check")+'"> </i>');
var myRootLocation=$(".theForm");
var reg=new RegExp("documents_","");
$("#indicators_form_link").find("#documents_template_name").val(data["template_name"]);
$("#indicators_form_link").find("#documents_ifilename").val(data["otemplate"]);
$("#indicators_form_link").find("#documents_template_link").attr("href",data["template"]).text(data["template_name"]);
//var cData=data;
(function(cData){
getLastFile(function(data){
console.log(hasBeenDone);
fetchInfoAndDisplay(data,function(){
if(!hasBeenDone){
$("#pages_fields_table_display").prev().remove();
$("#pages_fields_table_display").remove();
var cPage=cData["pages"][$("#documents_ifile_page").val()];
console.log("+++++>");
console.log(cPage);
console.log("<+++++");
if(cPage["ofield"]){
console.log("+++++>");
console.log(cPage);
console.log("<+++++");
$("#pages_id").val(cPage["id"]);
if(cPage["isreference"])
$("#documents_page_isreference").prop("checked",true);
else
$("#documents_page_isreference").prop("checked",false);
$("#documents_page_type").val(cPage["type"]).change();
$("#documents_page_tablename").val(cPage["tablename"]);
var cid=0;
try{
cid=eval((cPage["ofield"].replace(/Field/g,"")+"-1"));
}catch(e){
try{
var columns=$("#DS_table_indicatorTable_indicator").dataTable().fnSettings().aoColumns;
for(var kk=0;kk<columns.length;kk++)
if(columns[kk].data==cPage["ofield"]){
cid=kk;
break;
}
}catch(e){
console.log("!! MM ERROR "+e);
}
}
var closure={
"field": cid,
"type": cPage["otype"]
};
console.log("Now fix the order to "+closure["field"]+" "+closure["type"]+"!");
try{
managerTools.datasources[data].order([closure["field"],closure["type"]]).draw();
}catch(e){
console.log("****** ERROR ");
console.log(e);
console.log("****** ERROR ");
}
var tbody="";
//console.log(managerTools.generateFromTemplate($("#page_fields_table_template").html(),["tbody"],[tbody]));
$("#page_table_init").html(managerTools.generateFromTemplate($("#page_fields_table_template").html(),["tbody"],[tbody]));
$("#pages_fields_table_display").DataTable({
rowReorder: true,
"scrollX": true,
"scrollY": (($("#indicators_form_eye").height())-($(".navbar").height()*6))+"px",
"scrollCollapse": true,
autoWidth: false,
"paging": false,
//"info": false,
//"responsive": true,
//deferRender: true,
bFilter: false
});
hasBeenDone=true;
$(".processImportData").off('click');
$(".processImportData").click(function(){
console.log('processImportData !');
var dstName=$("#documents_ifilename").val();
dstName=dstName+(dstName.indexOf(".mdb")>0?"_dir":'');
var lparams=[
{"identifier": "id","value": localId,"dataType":"string"},
{"identifier": "dstName","value": dstName,"dataType":"string"}
];
zoo.execute({
identifier: "np.massiveImport",
type: "POST",
mode: "async",
storeExecuteResponse: true,
status: true,
dataInputs: lparams,
dataOutputs: [
{"identifier":"Result","mimeType":"text/plain"},
],
success: function(data){
console.log(data);
var progress=$("#indicators_form_table").find(".progress-bar").first();
progress.parent().show();
progress.removeClass("progress-bar-success");
progress.attr("aria-valuenow",0);
progress.css('width', (0)+'%');
zoo.watch(cid, {
onPercentCompleted: function(data) {
progress.css('width', (eval(data.percentCompleted))+'%');
progress.attr("aria-valuenow",eval(data.percentCompleted));
progress.text(data.text+' : '+(data.percentCompleted)+'%');
},
onProcessSucceeded: function(data) {
progress.attr("aria-valuenow",100);
progress.css('width', (100)+'%');
progress.text(data.text+' : '+(100)+'%');
progress.addClass("progress-bar-success");
if (data.result.ExecuteResponse.ProcessOutputs) {
progress.text(data.result.ExecuteResponse.ProcessOutputs.Output.Data.LiteralData.__text );
$(".notifications").notify({
message: { text: data.result.ExecuteResponse.ProcessOutputs.Output.Data.LiteralData.__text },
type: 'success',
}).show();
}
},
onError: function(data) {
progress.attr("aria-valuenow",100);
progress.css('width', (100)+'%');
progress.text(data.text+' : '+(100)+'%');
try{
$(".notifications").notify({
message: { text: data["result"]["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}catch(e){
console.log(e);
var progress=$("#indicators_form_table").find(".progress-bar").first();
progress.attr("aria-valuenow",100);
progress.css('width', (100)+'%');
progress.text(data.text+' : '+(100)+'%');
try{
$(".notifications").notify({
message: { text: data["result"]["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}catch(e){
console.log(e);
}
}
},
});
},
error: function(data){
console.log(data);
}
});
});
$(".savePageSettings").off('click');
$(".savePageSettings").click(function(){
console.log('savePageSettings !');
var mapping={
"name": "field_name",
"type": "field_type",
"rlabel": "field_label",
"label": "field_label_index",
"value": "value",
"clause": "clause",
};
var objs=[];
$("#pages_fields_table_display").find("tbody").find('tr').each(function(){
var obj={};
for(var i in mapping){
obj[i]=$(this).find("input[name="+mapping[i]+"],select[name="+mapping[i]+"],textarea[name="+mapping[i]+"]").val();
}
objs.push(obj);
});
var params=[
{"identifier": "table","value": "mm_tables.pages","dataType":"string"},
{"identifier": "columns","value": JSON.stringify([], null, ' '),"mimeType":"application/json"},
{"identifier": "links","value": JSON.stringify({"fields":{"table":"mm_tables.page_fields","ocol":"pid","tid":"pid"}}, null, ' '),"mimeType":"application/json"},
{"identifier": "fields","value": JSON.stringify(objs, null, ' '),"mimeType":"application/json"},
{"identifier": "id","value": $("#pages_id").val(),"dataType":"string"}
];
insert(params,($("#pages_id").val()!=-1),function(data){
console.log(data);
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
//loadAnElement($("#tables_id").val(),false);
});
console.log(params);
});
$("select[name='georef_method']").off('change');
$("select[name='georef_method']").change(function(){
console.log($(this).val());
if($(this).val()=="coord")
$(this).parent().parent().next().show();
else
$(this).parent().parent().next().hide();
if($(this).val()=="-1")
$(this).parent().parent().next().next().hide();
else
$(this).parent().parent().next().next().show();
});
$("select[name='georef_method']").change();
$("a.georef_add").off('click');
$("a.georef_add").click(function(e){
e.stopPropagation();
$(this).parent().parent().parent().parent().find("div.form-group").last().after($(this).parent().parent().parent().clone());
//$(this).parent().parent().parent().after($(this).parent().parent().parent().clone())
//$(this).parent().parent().parent().next().find(".btn-group").remove();
$(this).parent().parent().parent().parent().find("div.form-group").last().find(".btn-group").remove();
if($("select[name='georef_method']").val()=="georef"){
//$(this).parent().parent().parent().next().find("label").append($("#template_georef_separator").html());
$(this).parent().parent().parent().parent().find("div.form-group").last().find("label").append($("#template_georef_separator").html());
}
if($("select[name='georef_field']").length==1)
$("a.georef_delete").addClass("disabled");
if($("select[name='georef_field']").length>1)
$("a.georef_delete").removeClass("disabled");
console.log($(this));
});
$("a.georef_delete").off('click');
$("a.georef_delete").click(function(e){
e.stopPropagation();
$(this).parent().parent().parent().parent().find("div.form-group").last().remove();
console.log($("select[name='georef_field']").length);
if($("select[name='georef_field']").length==1)
$(this).addClass("disabled");
console.log($(this));
});
if($("select[name='georef_field']").length==1)
$("a.georef_delete").addClass("disabled");
try{
$("#DS_table_indicatorTable_indicator").dataTable().fnSettings().aoDrawCallback.push( {
"fn": function () {
console.log("****** TABLE REFRESH !");
if(cData["pages"][$("#documents_ifile_page").val()]["fields"].length>0){
console.log("****** TABLE REFRESH WITH VALUES !");
var tbody="";
$("#documents_georef_field").html("");
for(var i=0;i<cData["pages"][$("#documents_ifile_page").val()]["fields"].length;i++){
var celem=cData["pages"][$("#documents_ifile_page").val()]["fields"][i];
tbody+=managerTools.generateFromTemplate($("#page_fields_line_template").html(),
["id","name","label","label_index","value","clause"],
[i+1,celem["name"],celem["rlabel"],celem["label"],celem["value"],celem["clause"]]);
$("#documents_georef_field").append('<option>'+celem["name"]+'</option>');
try{
var tmp=celem["label"].split('||');
for(var j=0;j<tmp.length;j++){
var tmp1=tmp[j].split(',');
var coords=[];
for(var k=0;k<tmp1.length;k++){
coords.push(parseInt(tmp1[k].replace(/\(|\)/g,"")));
}
console.log(coords);
console.log($("#DS_table_indicatorTable_indicator").DataTable());
var element=null;
if(coords[1]>=0){
console.log($("#DS_table_indicatorTable_indicator").DataTable().cells(coords[1],coords[0]));
console.log($("#DS_table_indicatorTable_indicator").DataTable().cell(coords[1],coords[0]));
element=$($("#DS_table_indicatorTable_indicator").DataTable().cells(coords[1],coords[0]).nodes());
}else
element=$($("#DS_table_indicatorTable_indicator").DataTable().column(coords[0]).header());
console.log($(element));
element.addClass("alert alert-success");
element.append(' <span class="badge progress-bar-info">'+(i+1)+'</span>');
}
tmp=celem["value"].split('||');
for(var j=0;j<tmp.length;j++){
var tmp1=tmp[j].split(',');
var coords=[];
for(var k=0;k<tmp1.length;k++){
coords.push(parseInt(tmp1[k].replace(/\(|\)/g,"")));
}
var element=$($("#DS_table_indicatorTable_indicator").DataTable().cell(coords[1],coords[0]).node());
console.log(element);
element.addClass("alert alert-danger");
element.append(' <span class="badge progress-bar-info">'+(i+1)+'</span>');
}
}catch(e){
console.log("******************"+e+"_____");
};
}
$("#pages_fields_table_display").find("tbody").html(tbody);
var cnt=0;
$("#pages_fields_table_display").find('tbody').find('tr').each(function(){
$(this).find('select[name=field_type]').first().val(cData["pages"][$("#documents_ifile_page").val()]["fields"][cnt]["type"]);
cnt+=1;
});
}
fillGeoreferencing(cData);
},
"sName": "user"
} );
}catch(e){
alert(e);
}
/*$("#DS_table_indicatorTable_indicator").DataTable().fnDrawCallback=function(){
console.log("****** TABLE REFRESH !");
};*/
if(cData["pages"][$("#documents_ifile_page").val()]["length"]!=null)
$("#DS_table_indicatorTable_indicator").DataTable().page.len(cData["pages"][$("#documents_ifile_page").val()]["length"]).draw();
}else{
$("#pages_id").val(-1);
}
console.log($('#DS_table_indicatorTable_indicator tbody'));
$('#DS_table_indicatorTable_indicator tbody').on( 'click', 'td', function () {
console.log('Clicked');
console.log($("#DS_table_indicatorTable_indicator").DataTable().cell( this ));
if($(this).hasClass("alert")){
if(!$(this).find('span').first().hasClass("progress-bar-info")){
$(this).removeClass("alert "+(isAttributes?"alert-success":"alert-danger"));
$(this).find('span').first().remove();
if(isAttributes){
attributes_index.pop(attributes.indexOf($(this).text()));
attributes.pop(attributes.indexOf($(this).text()));
}else
values.pop(values.indexOf('('+$("#DS_table_indicatorTable_indicator").DataTable().cell( this ).index().column+','+$("#DS_table_indicatorTable_indicator").DataTable().cell( this ).index().row+')'));
}
}
else{
if(!$(this).find('span').first().hasClass("progress-bar-info")){
$(this).addClass("alert "+(isAttributes?"alert-success":"alert-danger"));
if(isAttributes){
attributes.push($(this).text());
attributes_index.push('('+$("#DS_table_indicatorTable_indicator").DataTable().cell( this ).index().column+','+$("#DS_table_indicatorTable_indicator").DataTable().cell( this ).index().row+')');
if($("#pages_fields_table_display").find("tbody").find('tr').find('td').first().attr('colspan')==6)
$(this).append(' <span class="badge">'+(1)+'</span>');
else
$(this).append(' <span class="badge">'+($("#pages_fields_table_display").find("tbody").find('tr').length+1)+'</span>');
}
else{
values.push('('+$("#DS_table_indicatorTable_indicator").DataTable().cell( this ).index().column+','+$("#DS_table_indicatorTable_indicator").DataTable().cell( this ).index().row+')');
console.log($("#DS_table_indicatorTable_indicator").DataTable().cell( this ).index());
$(this).append(' <span class="badge">'+($("#pages_fields_table_display").find("tbody").find('tr').length)+'</span>');
}
}
}
console.log($("#DS_table_indicatorTable_indicator").DataTable().cell( this ).index());
} );
$(".addRow").first().click(function(){
alert("add row to table");
console.log($("#page_fields_line_template").html());
$("#pages_fields_table_display").find("tbody").append(managerTools.generateFromTemplate($("#page_fields_line_template").html(),["id","name","label","true","ignore","value"],[$("#pages_fields_table_display").find("tbody").find('tr').length,"true",0,""]));
});
$("[data-mmaction=useColumnNV]").off('click');
$("[data-mmaction=useColumnNV]").click(function(){
var columns=$("#DS_table_indicatorTable_indicator").dataTable().fnSettings().aoColumns;
$("#pages_fields_table_display").find("tbody").html("");
for(var kk=0;kk<columns.length;kk++){
console.log(columns[kk].data);
console.log($("#pages_fields_table_display").find("tbody").find('tr').length);
$("#pages_fields_table_display").find("tbody").append(managerTools.generateFromTemplate($("#page_fields_line_template").html(),["id","name","label","ignore","value","clause","label_index"],[$("#pages_fields_table_display").find("tbody").find('tr').length+1,columns[kk].data,columns[kk].data,0,"","true","("+kk+",-1)"]));
$("#pages_fields_table_display").find("tbody").find('tr').last().find("textarea").last().val("("+kk+",0)");
var element=$($("#DS_table_indicatorTable_indicator").DataTable().column(kk).header());
element.addClass("alert alert-success");
element.append(' <span class="badge progress-bar-info">'+(kk+1)+'</span>');
var element=$($("#DS_table_indicatorTable_indicator").DataTable().cells(0,kk).nodes());
element.addClass("alert alert-danger");
element.append(' <span class="badge progress-bar-info">'+(kk+1)+'</span>');
}
});
$("[data-mmaction=setAttribute]").off('click');
$("[data-mmaction=setAttribute]").click(function(){
isAttributes=false;
$("#pages_fields_table_display").find("tbody").find("td").first().each(function(){
if($(this).attr("colspan")==6)
$(this).parent().remove();
});
$("#pages_fields_table_display").find("tbody").append(managerTools.generateFromTemplate($("#page_fields_line_template").html(),["id","name","label","ignore","value","clause","label_index"],[$("#pages_fields_table_display").find("tbody").find('tr').length+1,attributes.join("_"),attributes.join("_"),0,"","true",attributes_index.join(' || ')]));
});
$("[data-mmaction=setValue]").off('click');
$("[data-mmaction=setValue]").click(function(){
isAttributes=true;
var tmp=$("#pages_fields_table_display").find("tbody").find('tr').last().find("textarea").last().val(values.join(' || '));
for(var i=0;i<attributes.length;i++){
var tmp=attributes_index[i].split('||');
var aCoords=[];
for(var j=0;j<tmp.length;j++){
var tmp1=tmp[j].split(',');
aCoords.push([]);
for(var k=0;k<tmp1.length;k++){
aCoords[aCoords.length-1][k]=tmp1[k].replace(/\(|\)/g, "");
}
console.log($($("#DS_table_indicatorTable_indicator").DataTable().cell( aCoords[aCoords.length-1][1],aCoords[aCoords.length-1][0] ).node()).find(".badge").addClass("progress-bar-info"));
}
console.log(aCoords);
}
for(var i=0;i<values.length;i++){
var tmp=values[i].split('||');
var aCoords=[];
for(var j=0;j<tmp.length;j++){
var tmp1=tmp[j].split(',');
aCoords.push([]);
for(var k=0;k<tmp1.length;k++){
aCoords[aCoords.length-1][k]=tmp1[k].replace(/\(|\)/g, "");
}
console.log($($("#DS_table_indicatorTable_indicator").DataTable().cell( aCoords[aCoords.length-1][1],aCoords[aCoords.length-1][0] ).node()).find(".badge").addClass("progress-bar-info"));
}
console.log(aCoords);
}
attributes_index=[];
attributes=[];
values=[];
//$("#pages_fields_table_display").find("tbody").append(managerTools.generateFromTemplate($("#page_fields_line_template").html(),["id","name","label","ignore","value"],[$("#pages_fields_table_display").find("tbody").find('tr').length,attributes.join("_"),attributes.join("_"),"true",0,""]));
});
}
});
});
})(data);
myRootLocation.find("textarea").each(function(){
if(!$(this).attr("id"))
return;
if($(this).attr("id").replace(reg,"")=="description"){
$(this).summernote("code",data[$(this).attr("id").replace(reg,"")]);
}
else
$(this).val(data[$(this).attr("id").replace(reg,"")]).change();
});
$(".tab-content").find("select").find("option").each(function(){
$(this).prop('selected', false);
});
myRootLocation.find("input[type=text],input[type=hidden],select").each(function(){
if(!$(this).attr("id"))
return;
if($(this).attr("type")=="text"){
if($(this).attr("id").replace(/color/g,"")!=$(this).attr("id")){
if(data[$(this).attr("id").replace(reg,"")])
$(this).val("#"+data[$(this).attr("id").replace(reg,"")]).change();
else
$(this).val("#000").change();
}
else
$(this).val(data[$(this).attr("id").replace(reg,"")]);
}else{
console.log($(this));
$(this).find('option').each(function(){$(this).prop('selected', false);});
if($.isArray(data[$(this).attr("id").replace(reg,"")])){
var obj=data[$(this).attr("id").replace(reg,"")];
var oid=$(this).attr("id").replace(reg,"");
if(obj.length==0)
$(this).find('option[value="-1"]').prop("selected",true);
for(var i=0;i<obj.length;i++){
//(this).find('option').each(function(){if($(this).val()==obj[j])$(this).prop('selected', true);});
$(this).find('option[value="'+obj[i]+'"]').prop("selected",true);
}
}else{
$(this).val((data[$(this).attr("id").replace(reg,"")]!=null?data[$(this).attr("id").replace(reg,"")]:-1));
}
}
});
}
function fillGraphForm(data){
var myRootLocation=$("#indicators_form_pie-chart");
var prefix="documents_graphs_";
myRootLocation.find("input[type=text],input[type=hidden],select,textarea").each(function(){
if(!$(this).attr("id"))
return;
var myReg=new RegExp(prefix,"g");
var cid=$(this).attr("id").replace(myReg,"");
console.log(cid);
if($(this).attr("type")=="text" || !$(this).attr("type") || $(this).attr("type")=="hidden"){
if(cid.replace(/color/g,"")!=cid){
if(data[cid])
$(this).val("#"+data[cid]).change();
else
$(this).val("#000").change();
}
else
$(this).val(data[cid])
}else{
$(this).find('option').prop('selected', false);
if($.isArray(data[cid])){
var obj=data[cid];
var oid=cid;
if(obj.length==0)
$(this).find('option[value="-1"]').prop("selected",true);
for(var i=0;i<obj.length;i++){
$(this).find('option[value="'+obj[i]+'"]').prop("selected",true);
}
}else{
$(this).val((data[cid]!=null?data[cid]:-1));
}
}
});
}
function fillDefaultRepport(data){
var myRootLocation=$("#indicators_form_file-text-o");
var lines="";
var freg=new RegExp("\\[content\\]","g");
var regs=[
new RegExp("\\[x\\]","g"),
new RegExp("\\[name\\]","g")
];
var tmpl=$("#document_settings_line_template")[0].innerHTML;
for(var i=0;i<data.length;i++){
lines+=tmpl.replace(regs[0],i).replace(regs[1],data[i]);
}
var content=$("#document_settings_container_template")[0].innerHTML.replace(freg,lines);
$("#documents_repport_editor").html(content);
var defaultTypes={
"map": 1,
"table": 3,
"diag": 4
};
var noOptionTypes=[
"1","2","5","6","7"
];
$("#documents_repport_editor").find("table").find("select").each(function(){
if(defaultTypes[$(this).parent().prev().find('input').val()]){
$(this).val(defaultTypes[$(this).parent().prev().find('input').val()]);
$(this).prop("disabled",true);
$(this).parent().prev().prev().find('input').prop("disabled",true);
$(this).parent().next().find('textarea').hide();
}else{
$(this).change(function(){
if($.inArray($(this).val(),noOptionTypes)>=0)
$(this).parent().next().find("textarea").hide();
else
$(this).parent().next().find("textarea").show();
});
}
});
$("#documents_repport_editor").find("table").DataTable({
"bPaginate": false,
"bFilter": false,
"bInfo": false,
"bAutoWidth": false,
"scrollY": ($(window).height()/2)+"px",
});
$("[data-mmaction=save-doc]").click(function(){
saveRepport();
});
}
function fillRepport(data){
for(var i=0;i<data.length;i++){
for(var a in data[i]){
if($("#rtable_"+a+"_"+i).attr("type")!="checkbox")
$("#rtable_"+a+"_"+i).val(data[i][a]);
else
$("#rtable_"+a+"_"+i).prop("checked",data[i][a]);
}
}
}
function saveRepport(){
var params=[
{identifier: "id", value: localId, dataType: "sring"}
];
if(arguments.length>0)
params.push({name: "tid", value: $("#p_tname").val(), dataType: "sring"});
$("#repport_display2").find("input[type=checkbox]").each(function(){
var tmp=($(this).attr("id")+"").split('_');
var params0={identifier: "tuple", value:'{"id":'+tmp[tmp.length-1]+',"display":"'+$(this).is(":checked")+'","var":"'+$("#rtable_name_"+tmp[tmp.length-1]).val()+'","type":'+$("#rtable_type_"+tmp[tmp.length-1]).val()+',"value":"'+ $("#rtable_value_"+tmp[tmp.length-1]).val()+'"}',mimeType: "application/json"};
var obj={
"id":tmp[tmp.length-1],
"display":$(this).is(":checked")+"",
"var":$("#rtable_name_"+tmp[tmp.length-1]).val(),
"type":$("#rtable_type_"+tmp[tmp.length-1]).val(),
"value":$("#rtable_value_"+tmp[tmp.length-1]).val()
};
params.push({identifier: "tuple", value:JSON.stringify(obj, null, ' '),mimeType: "application/json"});
});
if($("#repport_steps").is(":visible") && $("#repport_step").val()>0){
params.push({identifier: "step", value: ($("#repport_step")[0].selectedIndex-1), dataType: "sring"});
}
if($('#agregation').is(":visible") && $("#agregate_step")[0].selectedIndex-1>=0) {
params.push({identifier: "step", value: ($("#agregate_step")[0].selectedIndex-1), dataType: "sring"});
}
callService("np.saveRepportSettings",params,function(data){
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
});
}
function loadAnElement(id){
localId=id;
//console.log("loadATheme -> "+id);
$(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.details",
type: "POST",
dataInputs: [
{"identifier": "table","value": tableName,"dataType":"string"},
{"identifier": "id","value": id,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
//fillGeoreferencing(data);
fileUrlSelection(data);
$("#indicatorForm").find(".nav").find("li").first().trigger("click");
if(data.it_id){
console.log(data["_style"]);
//managerTools.loadStyleDisplay(data["_style"]);
//bindClassifier(data["_style"]);
fetchIndexTableAndDisplay(data["_style"],function(d){
var lcnt0=0;
$("#layer_property_table_table_display_wrapper").find("table tbody").find("tr").each(function(){
var lcnt=0;
var fields=["pos","display","search","var","label","value","width"]
if(data["_table"]["fields"])
$(this).find("td").each(function(){
if($(this).find("input").length){
if($(this).find("input").attr("type")!="checkbox")
$(this).find("input").val(data["_table"]["fields"][lcnt0][fields[lcnt]]);
else
$(this).find("input").prop("checked",data["_table"]["fields"][lcnt0][fields[lcnt]]);
}
if(lcnt==3){
var tmp=$(this).children().first().html();
$(this).html(data["_table"]["fields"][lcnt0][fields[lcnt]]+tmp);
}
lcnt+=1;
});
lcnt0+=1;
});
if(data["_repport"]["docFields"]){
$("#documents_afile_link").attr("href",data["_repport"]["doc"]);
$("#documents_afile_link").attr("href",data["_repport"]["docUrl"]).text(data["_repport"]["docUrl"]);
fillDefaultRepport(data["_repport"]["docFields"]);
if(data["_repport"]["fields"])
fillRepport(data["_repport"]["fields"]);
}else{
}
if(data["_table"]["id"]){
$("#documents_table_title").val(data["_table"]["title"]);
$("#documents_table_id").val(data["_table"]["id"]);
}else{
$("#documents_table_title").val("");
$("#documents_table_id").val(-1);
}
fillGraphForm(data["_graph"]);
});
$("#documents_indicators_table").val(data["indicators_territories"]).change();
console.log(data["query"]);
console.log(data["query"]);
console.log(data["query"]!=null);
console.log((data["query"]?"query":"file"));
//$("input[name=indicator_data_type]").val((data["query"]?"query":"file")).change();
$("input[name=indicator_data_type]").each(function(){
console.log((data["query"]?"query":"file"));
console.log($(this).val()==(data["query"]?"query":"file"));
if($(this).val()==(data["query"]?"query":"file"))
$(this).trigger("click");
});
var fields=["query"];
for(var i=0;i<fields.length;i++){
$("#documents_data_"+fields[i]).val(data[fields[i]]);
}
console.log($("#DS_indicatorTable_indicator"));
if(data["file_link"] && !data["query"]){
$("#documents_ifile_link").attr("href",data["file_url"]).text(data["file_name"]);
fetchInfoAndDisplay(data["file_link"]);
}else{
if(data["query"])
runSql(true);
else{
$("#DS_indicatorTable_indicator").remove();
$("#documents_ifile_link").attr('href','#').text('');
}
}
/*var lcnt=0;
$("#indicatorForm").find('.nav').first().find('[role=presentation]').each(function(){
if(lcnt>1){
$(this).removeClass("disabled");
$(this).prop("disabled",false);
}
lcnt+=1;
});*/
}else{
console.log($("#DS_indicatorTable_indicator"));
$("#DS_indicatorTable_indicator").remove();
$("#documents_ifile_link").attr('href','#').text('');
/*var lcnt=0;
console.log($("#indicatorForm").find('.nav').first());
console.log($("#indicatorForm").find('.nav').first().find('[role=presentation]'));
$("#indicatorForm").find('.nav').first().find('[role=presentation]').each(function(){
if(lcnt>1){
$(this).prop("disabled",true);
$(this).addClass("disabled");
}
lcnt+=1;
});*/
}
$(".fa-spin").addClass("hide");
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function createJsonFromForm(form){
var params={};
form.find('textarea').each(function(){
if(!$(this).attr("id"))
return;
var cid=$(this).attr('id').replace(reg0,"");
if(cid=="description")
params[cid]=$(this).summernote("code");
else
params[cid]=$(this).val();
});
form.find('input[type="text"]').each(function(){
if(!$(this).attr("id") || $(this).attr("id")=="indicators_keywords")
return;
if($(this).attr("id").replace(/color/g,"")!=$(this).attr("id"))
params[$(this).attr('id').replace(reg0,"")]=$(this).val().replace(/#/,"");
else
params[$(this).attr('id').replace(reg0,"")]=$(this).val();
});
form.find('select').each(function(){
if(!$(this).attr("id"))
return;
if($(this).find("option:selected").length>1){
params[$(this).attr('id').replace(reg0,"")]=[];
var oid=$(this).attr('id').replace(reg0,"");
$(this).find("option:selected").each(function(){
params[oid].push($(this).val());
});
}else
params[$(this).attr('id').replace(reg0,"")]=$(this).val();
});
return params;
}
function bindSave(){
$(".theForm").find("button").click(function(){
$('#documents_filename').val($('#file').val());$('#fileUpload').submit();
});
}
var lid="listElements";
function saveAnElement(){
var id=localId;
$(".fa-spin").removeClass("hide");
var obj=createJsonFromForm($(".theForm"));
obj["id"]=id;
localId=id;
obj["filename"]=$('input#file').val();
localInit=true;
zoo.execute({
identifier: "np.updateElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": tableName,"dataType":"string"},
{"identifier": "keywords", value: $("#indicators_keywords").val(),dataType: "string"},
{"identifier": "indicators_groups_in", value: "i_id",dataType: "string"},
{"identifier": "indicators_groups_out", value: "g_id",dataType: "string"},
{"identifier": "indicators_themes_in", value: "i_id",dataType: "string"},
{"identifier": "indicators_themes_out", value: "t_id",dataType: "string"},
{"identifier": "tuple","value": JSON.stringify(obj, null, ' '),"mimeType":"application/json"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
$(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
reloadElement=true;
$("#"+lid).dataTable().fnDraw();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function addAnElement(){
$(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.insertElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": tableName,"dataType":"string"},
{"identifier": "name","value": $("#adder").find('input[name="dname"]').val(),"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
$(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
localInit=false;
reloadElement=true;
$("#"+lid).dataTable().fnDraw();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function deleteAnElement(id){
$(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.deleteElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": tableName,"dataType":"string"},
{"identifier": "atable","value": "documents_themes","dataType":"string"},
{"identifier": "akey","value": "d_id","dataType":"string"},
{"identifier": "atable","value": "documents_groups","dataType":"string"},
{"identifier": "akey","value": "d_id","dataType":"string"},
{"identifier": "id","value": id,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
$(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
localInit=false;
reloadElement=true;
$("#"+lid).dataTable().fnDraw();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
var localInit=false;
var localItem=-1;
function startDataTable(rfields,fields){
var cnt=0;
var CRowSelected=[];
var CFeaturesSelected=[];
var CFeatures=[];
var lid="listElements";
$('#listElements').DataTable( {
language: {
url: module.config().translationUrl
},
data: [],
"dom": 'Zlfrtip',
"colResize": true,
autoWidth: false,
"scrollY": ($(window).height()/2)+"px",
"scrollCollapse": true,
"scrollX": true,
//"sScrollX": "100%",
//"sScrollXInner": "100%",
"bAutoWidth": false,
"bProcessing": true,
"bServerSide": true,
fixedHeader: true,
//searching: true,
responsive: true,
deferRender: true,
crollCollapse: true,
ordering: "id",
rowId: 'fid',
"sAjaxSource": "users",
select: {
info: false,
},
"lengthMenu": [[5, 10, 25, 50, 1000], [5, 10, 25, 50, "All"]],
columns: fields,
"rowCallback": function( row, data ) {
$(row).removeClass('selected');
if ( $.inArray(data.DT_RowId, CRowSelected) !== -1 ) {
$('#'+lid).DataTable().row($(row)).select();
}else{
$('#'+lid).DataTable().row($(row)).deselect();
}
},
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
var llimit=[];
for(j in {"iDisplayStart":0,"iDisplayLength":0,"iSortCol_0":0,"sSortDir_0":0,"sSearch":0})
for(i in aoData)
if(aoData[i].name==j){
if(llimit.length==4 && aoData[i].value!="")
llimit.push(aoData[i].value);
if(llimit.length<4)
llimit.push(aoData[i].value);
}
var closestproperties=rfields;
var page=llimit[0]+1;
if(page!=1){
page=(llimit[0]/llimit[1])+1;
}
var opts=zoo.getRequest({
identifier: "datastores.postgis.getTableContent",
dataInputs: [
{"identifier":"dataStore","value":module.config().db,"dataType":"string"},
{"identifier":"table","value":"mm_tables.importers","dataType":"string"},
{"identifier":"offset","value":llimit[0],"dataType":"int"},
{"identifier":"limit","value":llimit[1],"dataType":"int"},
{"identifier":"page","value":page,"dataType":"int"},
{"identifier":"sortorder","value":llimit[3],"dataType":"string"},
{"identifier":"search","value":llimit[llimit.length-1],"dataType":"string"},
{"identifier":"sortname","value":(closestproperties.split(",")[llimit[2]]),"dataType":"string"},
{"identifier":"fields","value":closestproperties.replace(/,msGeometry/g,""),"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","mimeType":"application/json","type":"raw"}
],
type: 'POST',
storeExecuteResponse: false
});
opts["success"]=function(rdata) {
features=rdata;
featureCount=rdata["total"];
var data=[];
CFeatures=[];
for(var i in features.rows){
var lparams={
"fid": "document_"+features.rows[i].id
}
var tmp=rfields.split(',');
for(var kk=0;kk<tmp.length;kk++)
lparams[tmp[kk]]=features.rows[i].cell[kk];
data.push(lparams);
CFeatures.push(data[data.length-1]);
}
var opts={
"sEcho": cnt++,
"iDraw": cnt++,
"iTotalRecords": featureCount,
"iTotalDisplayRecords": featureCount,
"aaData": (featureCount>0?data:[])
};
fnCallback(opts);
for(d in data){
if ( $.inArray(data[d].fid+"", CRowSelected) !== -1 ) {
$('#'+lid).DataTable().row($("#"+data[d].fid)).select();
}else{
$('#'+lid).DataTable().row($("#"+data[d].fid)).deselect();
}
}
if(featureCount==0){
$('#'+lid+'Table').DataTable().clear();
}
var existing=$('#'+lid+'_info').children('span.select-info');
if(existing.length)
existing.remove();
$('#'+lid+'_info').append($('<span class="select-info"/>').append(
$('<span class="select-item"/>').append('dd rows selected'.replace(/dd/g,CRowSelected.length))
));
loadElements(tableName,localInit);
};
opts["error"]=function(){
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
};
oSettings.jqXHR = $.ajax( opts );
}
});
var ltype="document";
//var myRootElement=$('#'+lid).parent().find(".btn-group").first().parent();
$('#'+lid+' tbody').on('click', 'tr', function () {
if(!this.id)
return;
hasBeenDone=false;
var id = this.id+"";
var reg0=new RegExp(ltype+'s_',"g");
var index = $.inArray(id, CRowSelected);
if ( index == -1 ) {
if(CRowSelected.length>0){
$('#'+lid).DataTable().row($("#"+CRowSelected[0])).deselect();
CRowSelected.pop(CRowSelected[0]);
CFeaturesSelected.pop(CFeaturesSelected[0]);
}
/*if(CFeaturesSelected.length==0)
myRootElement.find(".require-select").removeClass("disabled");*/
CRowSelected.push( id );
$('#'+lid).DataTable().row("#"+id).select();
for(var i=0;i<CFeatures.length;i++){
if(CFeatures[i]["fid"]==id)
CFeaturesSelected.push( CFeatures[i] );
}
reg=new RegExp(ltype+"_","g");
localId=id.replace(reg,"");
reloadElement=false;
loadAnElement(localId);
} else {
$("."+lid+"BaseEditForm").removeClass("in");
CRowSelected.pop(index);
CFeaturesSelected.pop(index);
$('#'+lid).DataTable().row("#"+id).deselect();
}
var existing=$('#'+lid+'_info').children('span.select-info');
if(existing.length)
existing.remove();
$('#'+lid+'_info').append($('<span class="select-info"/>').append(
$('<span class="select-item"/>').append((CFeaturesSelected.length!=CRowSelected.length?'dd rows selected (ee total selected)'.replace(/dd/g,CRowSelected.length).replace(/ee/g,CFeaturesSelected.length):'dd rows selected'.replace(/dd/g,CRowSelected.length)))
));
});
}
function runSql(execute,dbname,sql){
zoo.execute({
identifier: (execute?"np.createTempFile":"np.testQuery"),
type: "POST",
dataInputs: [
{"identifier":(execute?"map":"dbname"),"value":(dbname?dbname:$("#documents_indicators_database").val()),"dataType":"string"},
{"identifier":(execute?"sql":"query"),"value":(sql?sql:$("#documents_data_query").val()),"dataType":"integer"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
if(execute)
fetchInfoAndDisplay(data);
else
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
var fetchInfoAndDisplay=function(data,ffunc){
fileName=data;
var ldata=data;
console.log("********************** "+ldata.indexOf("mdb"));
if(ldata.indexOf(".mdb")>0)
ldata+="_dir/";
/*if(ldata.indexOf(".csv")>0){
var tmp=ldata.split('/');
ldata="";
for(var i=0;i<ldata.length-1;i++)
ldata+=tmp[i]+"/";
console.log("********************** "+ldata);
}*/
zoo.execute({
//identifier: "vector-tools.mmVectorInfo2Map",
identifier: "datastores.mmVectorInfo2MapJs",
type: "POST",
dataInputs: [
//{"identifier":"dataSource","value":ldata,"dataType":"string"},
{"identifier":"dataStore","value":ldata,"dataType":"string"},
{"identifier":"force","value":"1","dataType":"integer"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
if(data.datasource){
var val="";
$("select[name=ifile_page]").html('');
if($.isArray(data.datasource.layer)){
for(var i=0;i<data.datasource.layer.length;i++){
if(i==0)
val=data.datasource.layer[i].name;
$("select[name=ifile_page]").append("<option>"+data.datasource.layer[i].name+"</option>");
}
}else{
val=data.datasource.layer.name;
$("select[name=ifile_page]").append("<option>"+val+"</option>");
}
$("select[name=ifile_page]").off('change');
$("select[name=ifile_page]").change(function(){
$("#pages_id").val(-1);
var lval=$(this).val();
hasBeenDone=false;
getVectorInfo(ldata,$(this).val(),function(data){
var reg=new RegExp("\\[datasource\\]","g");
var reg1=new RegExp("\\[font\\]","g");
font="fa fa-table";
//console.log("FONT !! "+font);
//console.log($("#DS_indicatorTable_indicator"));
if($("#DS_indicatorTable_indicator").length)
$("#DS_indicatorTable_indicator").remove();
$("[data-mmaction=join]").first().parent().append($($("#dataSource_template")[0].innerHTML.replace(reg1,font).replace(reg,$("select[name=ifile_page]").val())).attr("id","DS_indicatorTable_indicator"));
managerTools.displayVector(data,ldata,"indicatorTable","indicator",lval,
function(){
$("#DS_indicatorTable_indicator").find(".panel").addClass("panel-warning").removeClass("panel-default");
$("[data-mmaction=join]").addClass("disabled");
},
function(){
$("#DS_indicatorTable_indicator").find(".panel").removeClass("panel-warning").addClass("panel-default");
$("[data-mmaction=join]").removeClass("disabled");
try{
ffunc();
}catch(e){
}
});
});
});
$("select[name=ifile_page]").find('option').first().prop("selected",true).change();
/*getVectorInfo(ldata,val,function(data){
var reg=new RegExp("\\[datasource\\]","g");
var reg1=new RegExp("\\[font\\]","g");
font="fa fa-table";
console.log("FONT !! "+font);
console.log($("#DS_indicatorTable_indicator"));
if($("#DS_indicatorTable_indicator").length)
$("#DS_indicatorTable_indicator").remove();
$("[data-mmaction=join]").first().parent().append($($("#dataSource_template")[0].innerHTML.replace(reg1,font).replace(reg,$("select[name=ifile_page]").val())).attr("id","DS_indicatorTable_indicator"));
managerTools.displayVector(data,ldata,"indicatorTable","indicator",val,
function(){
$("#DS_indicatorTable_indicator").find(".panel").addClass("panel-warning").removeClass("panel-default");
$("[data-mmaction=join]").addClass("disabled");
},
function(){
$("#DS_indicatorTable_indicator").find(".panel").removeClass("panel-warning").addClass("panel-default");
$("[data-mmaction=join]").removeClass("disabled");
try{
ffunc();
}catch(e){
}
});
});*/
}
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function getLastFile(func){
zoo.execute({
identifier: "np.getLastFile",
type: "POST",
dataInputs: [ ],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function getIndicatorInfo(func){
zoo.execute({
identifier: "np.refreshIndex",
type: "POST",
dataInputs: [
{"identifier":"id","value":localId,"dataType":"integer"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function getVectorInfo(dataSource,layer,func){
zoo.execute({
identifier: "vector-tools.mmExtractVectorInfo",
type: "POST",
dataInputs: [
{"identifier":"dataSource","value":dataSource,"dataType":"string"},
{"identifier":"layer","value":layer,"dataType":"integer"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
//console.log(data);
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function fetchFields(datasource,func){
zoo.execute({
identifier: "np.getMapRequest0",
type: "POST",
dataInputs: [
{"identifier":"t_id","value":datasource,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
//var obj=_x2js.xml_str2json( data );
console.log(data.schema.complexType.complexContent.extension.sequence.element);
if($.isArray(data.schema.complexType.complexContent.extension.sequence.element)){
$("#documents_indicators_field").html("");
for(var i=0;i<data.schema.complexType.complexContent.extension.sequence.element.length;i++){
var cname=data.schema.complexType.complexContent.extension.sequence.element[i]._name;
if(cname!="msGeometry")
$("#documents_indicators_field").append('<option>'+cname+'</option>');
}
}
if(func)
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
var llcnt=0;
function insertElem(params,func){
zoo.execute({
identifier: "np."+(test?"updateElem":"insertElem"),
type: "POST",
dataInputs: params,
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function callService(service,params,func,outputs){
var dataOutputs=[
{"identifier":"Result","type":"raw"},
];
if(outputs)
dataOutputs=outputs;
zoo.execute({
identifier: service,
type: "POST",
dataInputs: params,
dataOutputs: dataOutputs,
success: function(data){
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function fetchIndicatorInfo(lfunc){
getIndicatorInfo(function(data){
$(".class-switcher").off('change');
$(".class-switcher").change(function(){
console.log(".class-switcher CHANGE ! "+llcnt);
llcnt+=1;
var myRootLocation=$(this).parent().parent().parent();
var index=0;
var hasElement=true;
var closure=$(this);
myRootLocation.find('.no-us').show();
myRootLocation.find('.class-switcher').each(function(){
if(closure[0]==$(this)[0]){
hasElement=false;
}
else
if(hasElement)
index+=1;
});
$(this).find('option').each(function(){
if(!$(this).is(':selected'))
myRootLocation.find('.no-'+$(this).attr('value')).show();
});
$(this).find('option:selected').each(function(){
myRootLocation.find('.no-'+$(this).attr('value')).hide();
});
if(index>0)
myRootLocation.find(".require-tl").show();
if(data.type!=3)
myRootLocation.find(".require-raster").hide();
myRootLocation.find(".require-add-step").hide();
});
managerTools.displayVector(data,module.config().db,"indicatorTable","dataTable","indexes.view_idx"+localId,
function(){
$("#DS_indicatorTable_dataTable").find(".panel").addClass("panel-warning").removeClass("panel-default");
},
function(){
$("#DS_indicatorTable_dataTable").find(".panel").removeClass("panel-warning").addClass("panel-default");
});
//$(".class-switcher").trigger("change");
if(lfunc)
lfunc(data);
});
}
function fetchIndexTableAndDisplay(ldata,func){
managerTools.getTableDesc(module.config().msUrl,module.config().dataPath+"/PostGIS/"+module.config().db+"ds_ows.map","indexes.view_idx"+localId,ldata,function(obj,rdata,idata){
managerTools.loadTableDefinition(obj,idata,function(elem){
console.log('toto');
var prefix="";
if(arguments.length>1)
prefix="agregate_";
///var params=produceParams(prefix);
var params=[
{identifier: "table", value: "d_table",dataType: "string"},
{identifier: "name", value: $("#documents_table_title").val(),dataType: "string"},
{identifier: "i_id", value: localId,dataType: "string"}
];
if($("#agregation").is(":visible")){
test=false;
params.push({
identifier: "tid",
value: $("#p_tname").val(),
dataType: "string"
});
}
test=$("#documents_"+prefix+"table_id")[0] && $("#documents_"+prefix+"table_id").val()!='-1' && $("#documents_"+prefix+"table_id").val()!='';
if(test){
params.push({
identifier: "id",
value: localId,
dataType: "string"
});
}
if($("#documents_table_steps").is(":visible") && $("#table_step").val()>0)
params.push({"identifier":"step","value":($("#documents_table_step")[0].selectedIndex-1),dataType: "string"});
$("#mm_layer_property_table_display").find("tbody").find("tr").each(function(){
var params0={
"pos":"",
"display":"",
"search":"",
"var":"",
"label":"",
"value":"",
"width":""
};
var cnt=0;
$(this).find("td").find("input").each(function(){
if($(this).attr('type')=="checkbox"){
var lcnt1=0;
for(var k in params0){
if(lcnt1==cnt)
params0[k]=$(this).prop('checked')+"";
lcnt1+=1;
}
}else{
var lcnt1=0;
for(var k in params0){
if(lcnt1==cnt)
params0[k]=$(this).val();
lcnt1+=1;
}
}
cnt+=1;
});
params.push({
identifier:"tuple",
value:JSON.stringify(params0),
mimeType: "application/json"
});
});
params.push({
"identifier": "map",
"value": $("#save-map").val(),
"dataType": "string"
});
params.push({
"identifier": "layer",
"value": ldata.name,
"dataType": "string"
});
callService("np.saveIndexTable",params,function(data){
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
});
});
console.log("getTableDesc end");
console.log($(".mmFields"));
$(".mmFields,.mmField").html("");
console.log(rdata);
for(var i=0;i<rdata.fields.length;i++){
if(rdata.fields[i]!="msGeometry")
$(".mmFields,.mmField").append('<option>'+rdata.fields[i]+'</option>');
console.log($(".mmFields"));
}
/*$("#indicators_form_table").find("button").first().click(function(){
});*/
if(func)
func(rdata);
managerTools.loadStyleDisplay(ldata,[
{"identifier": "map","value": "Index"+localId,"dataType":"string"},
{"identifier": "prefix","value": "indexes","dataType":"string"},
{"identifier": "name","value": "Index"+localId,"dataType":"string"},
{"identifier": "orig","value": module.config().db,"dataType":"string"},
{"identifier": "id","value": localId,"dataType":"int"},
{"identifier": "formula","value": $('#mm_layer_property_style_display').find("textarea[name=formula]").val(),"dataType":"int"},
]);
bindClassifier(ldata);
});
var reg=new RegExp("\\[datasource\\]","g");
var reg1=new RegExp("\\[font\\]","g");
font="fa fa-table";
if($("#DS_indicatorTable_dataTable").length)
$("#DS_indicatorTable_dataTable").remove();
$("#indicators_form_table").append($($("#dataSource_template")[0].innerHTML.replace(reg1,font).replace(reg,"indexes.view_idx"+localId)).attr("id","DS_indicatorTable_dataTable"));
fetchIndicatorInfo();
}
function bindClassifier(ldata){
$("#mm_layer_property_style_display").find("button.mmClassifier").off("click");
$("#mm_layer_property_style_display").find("button.mmClassifier").click(function(e){
var params=[
{"identifier": "prefix","value": "indexes","dataType":"string"},
{"identifier": "name","value": "Index"+localId,"dataType":"string"},
{"identifier": "orig","value": module.config().db,"dataType":"string"},
{"identifier": "id","value": localId,"dataType":"int"},
{"identifier": "formula","value": $('#mm_layer_property_style_display').find("textarea[name=formula]").val(),"dataType":"int"},
];
try{
managerTools.classifyMap(this,"Index"+localId,ldata,params,function(data){
console.log(data);
});
}catch(e){
console.log(e);
}
return false;
});
}
function refreshLayerStyle(){
var params=[
{"identifier":"prefix","value":"indexes","dataType":"string"},
{"identifier":"name","value":"Index"+localId,"dataType":"string"},
{"identifier":"orig","value":module.config().db,"dataType":"string"},
{"identifier":"id","value":localId,"dataType":"string"}
];
console.log(params);
managerTools.callCreateLegend(null,"indexes.view_idx"+localId,null,params,function(data){
console.log(data);
try{
fetchIndexTableAndDisplay(data);
//fetchIndicatorInfo(data);
}catch(e){
console.log(e);
}
console.log(data);
});
}
function insertElem(params,test,func){
zoo.execute({
identifier: "np."+(test?"updateElem":"insertElem"),
type: "POST",
dataInputs: params,
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function insert(params,test,func){
zoo.execute({
identifier: "np.insert",
type: "POST",
dataInputs: params,
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
var initialize=function(){
adminBasic.initialize(zoo);
managerTools.initialize(zoo);
window.setTimeout(function () {
$("textarea#documents_description").summernote();
},10);
$('[data-toggle="tooltip"]').tooltip({container: 'body'});
startDataTable("id,name",[
{
"data": "id",
"name": "id",
"sWidth": "10%"
},
{
"data": "name",
"name": "name",
"sWidth": "80%"
},
]);
bindSave();
$("#documents_page_type").change(function(){
if($(this).val()==1)
$(".processImportData").show();
else
$(".processImportData").hide();
});
$("#adder").find("button").click(function(){
addAnElement();
$("#adder").removeClass("in");
});
$("#deleter").find("button").click(function(){
deleteAnElement(localId);
$("#deleter").removeClass("in");
});
$(".tab-pane").css({"max-height":($(window).height()-($(".navbar").height()*3.5))+"px","overflow-y":"auto","overflow-x":"hidden"});
$("#page-wrapper").find("[role=presentation]").first().children().first().click();
$("[data-mmaction=georef_save]").off('click');
$("[data-mmaction=georef_save]").click(function(){
var columns=["pid"];
if($("#tprj").is(":visible"))
columns.push("srs");
var params=[
{"identifier": "table","value": "mm_tables.page_geom","dataType":"string"},
{"identifier": "columns","value": JSON.stringify(columns, null, ' '),"mimeType":"application/json"},
{"identifier": "links","value": JSON.stringify({"fields":{"table":"mm_tables.page_geom_fields","ocol":"pid","tid":"pid"}}, null, ' '),"mimeType":"application/json"},
{"identifier": "pid","value": $("#pages_id").val(),"dataType":"string"},
{"identifier": "iid","value": $("#pages_id").val(),"dataType":"string"}
];
if($("#tprj").is(":visible"))
params.push({"identifier": "srs","value": $("#tprj").val(),"dataType":"string"});
var fcnt=0;
var lfields=[];
$("select[name='georef_field']").each(function(){
if(fcnt>0){
lfields.push({"column_name": $(this).val(), "separator": $("input[name='georef_sep']:eq("+(fcnt-1)+")").val()});
console.log(lfields);
console.log(lfields.length-1);
console.log(lfields[lfields.lengh-1]);
//lfields[lfields.lengh-1]["separator"]=$("input[name='georef_sep']:eq("+(fcnt-1)+")").val();
//separators.push($("input[name='georef_sep']:eq("+(fcnt-1)+")").val());
}else{
lfields.push({"column_name": $(this).val()});
}
fcnt+=1;
});
params.push({"identifier": "fields","value": JSON.stringify(lfields, null, ' '),"mimeType":"application/json"});
//params.push({"identifier": "separators","value": JSON.stringify(separators, null, ' '),"mimeType":"application/json"});
console.log(params);
insert(params,($("#tables_view_id").val()!=-1),function(data){
console.log(data);
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
loadAnElement($("#documents_id").val(),false);
});
});
$("[data-mmaction=join]").off('click');
$("[data-mmaction=join]").click(function(){
console.log($(this));
var params=[
{"identifier": "table","value": "mm_tables.pages","dataType":"string"},
{"identifier": "columns","value": JSON.stringify(["name","tablename","type","ofield","otype","length","iid","isreference"], null, ' '),"mimeType":"application/json"},
{"identifier": "name","value": $(this).prev().prev().prev().prev().find('select').val(),"dataType":"string"},
{"identifier": "isreference","value": $(this).prev().prev().prev().find('input[type=checkbox]').is(":checked"),"dataType":"string"},
{"identifier": "type","value": $(this).prev().prev().find('select').val(),"dataType":"string"},
{"identifier": "tablename","value": $(this).prev().find('input').val(),"dataType":"string"},
{"identifier": "length","value": $("select[name=DS_table_indicatorTable_indicator_length]").val(),"dataType":"string"},
{"identifier": "ofield","value": managerTools.sort["field"],"dataType":"string"},
{"identifier": "otype","value": managerTools.sort["type"],"dataType":"string"},
{"identifier": "iid","value": $("#documents_id").val(),"dataType":"string"},
];
if($("#pages_id").val()!=-1){
params.push({"identifier": "id","value": $("#pages_id").val(),"dataType":"string"});
}
insert(params,($("#tables_view_id").val()!=-1),function(data){
console.log(data);
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
loadAnElement($("#documents_id").val(),false);
});
console.log(managerTools.sort);
var myLocation=$(this);
for(var i=0;i<2;i++){
myLocation=myLocation.prev();
console.log(myLocation.find('select').val());
}
console.log($(this).prev());
console.log($(this).prev().prev());
});
$("[data-mmaction=import]").click(function(){
$("#iuploader").off("load");
$("#iuploader").on("load",function(){
console.log(arguments);
getLastFile(function(data){
fetchInfoAndDisplay(data);
console.log(data);
alert('Run Save File in DB: '+data);
zoo.execute({
identifier: "np.saveUploadedFile",
type: "POST",
dataInputs: [
{"identifier": "table","value": "mm_tables.importers","dataType":"string"},
{"identifier": "id","value": $("#documents_id").val(),"dataType":"string"},
{"identifier": "field","value": "template","dataType":"string"},
{"identifier": "file","value": data,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
});
});
$("#ifileUpload").submit();
});
$("#indicators_form_info").find("button").last().click(function(e){
var tmp=["groups","themes"];
var multiples=[[],[]];
for(var i=0;i<tmp.length;i++){
$("#documents_"+tmp[i]).find("option:selected").each(function(){
multiples[i].push($(this).val());
});
}
var params=[
{"identifier": "table","value": "mm_tables.importers","dataType":"string"},
{"identifier": "columns","value": JSON.stringify(["name","description","tid"], null, ' '),"mimeType":"application/json"},
{"identifier": "links","value": JSON.stringify({"importer_groups":{"table":"mm_tables.importer_groups","ocol":"iid","tid":"gid"},"importer_themes":{"table":"mm_tables.importer_themes","ocol":"iid","tid":"tid"}}, null, ' '),"mimeType":"application/json"},
{"identifier": "name","value": $("#documents_name").val(),"dataType":"string"},
{"identifier": "description","value": $("#documents_description").val(),"dataType":"string"},
{"identifier": "tid","value": ($("#documents_tid").val()!="None"?$("#documents_tid").val():"NULL"),"dataType":"string"},
{"identifier": "importer_groups","value": JSON.stringify(multiples[0], null, ' '),"mimeType":"application/json"},
{"identifier": "importer_themes","value": JSON.stringify(multiples[1], null, ' '),"mimeType":"application/json"},
];
if($("#documents_id").val()!=-1)
params.push({"identifier": "id","value": $("#documents_id").val(),"dataType":"string"});
insert(params,($("#documents_id").val()!=-1),function(data){
console.log(data);
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
uploadedFile=null;
loadAnElement($("#documents_id").val(),false);
});
});
console.log($("#page-wrapper").find("[role=presentation]").first());
console.log("Start Importer Module");
$('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
$.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
} );
};
function editLine(){
alert('Activate line editing !');
}
// Return public methods
return {
initialize: initialize,
saveAnElement: saveAnElement,
editLine: editLine
};
});
<|start_filename|>public_map/MMMap/MMPanZoom.css<|end_filename|>
div.olControlMMPanZoom {
top: 15px;
left:15px;
display: block;
position: absolute;
}
div.olControlMMPanZoomPanWrapper {
display: block;
width:83px;
height:80px;
background-image:url("images/sgpan_compass.png");
background-repeat:no-repeat;
}
div.olControlMMPanZoomPanJoystick
{
cursor:pointer;
}
div.olControlMMPanZoomJoystickWrapper
{
width:29px;
height:29px;
position:absolute;
top:27px;
left:27px;
}
div.olControlMMPanZoomPanButton
{
cursor:pointer;
}
div.olControlMMPanZoomZoomWrapper
{
position:relative;
height:140px;
width:83px;
background-image:url("images/sgzoom_BckElev.png");
background-repeat:no-repeat;
background-position: 30px 0;
}
.olControlMMPanZoom .ui-slider
{
background-color:transparent;
background-image:url("images/sgzoom_Elev.png");
background-repeat:no-repeat;
background-position:top left;
width:29px;
height:130px;
border:none;
position:absolute;
left:29px;
top:0;
cursor:pointer;
}
.olControlMMPanZoom .ui-slider-handle
{
background-image: url("images/sgzoom_BarElev.png");
background-color:Transparent;
background-repeat:no-repeat;
cursor:pointer;
width:16px;
height:7px;
border:none;
padding-left:11px;
}
div.olControlMMPanZoomZoomLevels
{
text-align:left;
color:#FFFFFF;
}
div.olControlMMPanZoomZoomLevels .zoomLevel
{
cursor:pointer;
display:block;
padding:2px;
width:auto;
left:60px;
position:absolute;
font-size:0.7em;
color:grey;
background:#FFFFFF;
border:0;
border-radius:3px;
}
div.olControlMMPanZoomZoomLevels .zoomLevel:hover
{
background:red;
color:#FFFFFF;
}
<|start_filename|>mapmint-ui/templates/preview/modules/addLayer/display.html<|end_filename|>
#import zoo
#if $m.web.metadata.get('mmOT')
#set f0=$m.web.metadata.get('mmOT').split(',')
#if $f0.count('AddLayer')>0 or $f0.count('AddWMSLayer')>0
<div id="olayerswitcher" class="al-container ipannel" style="height: 337px;">
<h3 class="lgn">$zoo._("Add layers")</h3>
<ul id="tabs">
#if $f0.count('AddLayer')>0
<li class="active"><a href="#tab1">$zoo._("Add layer")</a></li>
#end if
#if $f0.count('AddWMSLayer')>0
<li><a class="icon_accept" href="#tab2">$zoo._("Add WMS")</a></li>
#end if
</ul>
#else
#if $f0.count('AddLayer')>0
$zoo._("Add layer")
#else
#if $f0.count('AddWMSLayer')>0
$zoo._("Add WMS")
#end if
#end if
#end if
#if $f0.count('AddLayer')>0
<div id="tab1" class="tab_content" style="display: block;">
#from Cheetah.Template import Template
#import mapscript
#set m0=mapscript.mapObj($conf["main"]["dataPath"]+"/maps/project_idxOverlays.map")
$(Template(file=$conf["main"]["templatesPath"]+"/preview/modules/addLayer/OverlayLayers.tmpl",searchList={"m":$m0,"conf":$conf}))
<a class="vsource" onclick="mmAddOverlayLayers();" href="#">$zoo._("Add")</a>
</div>
#end if
#if $f0.count('AddWMSLayer')>0
<div id="tab2" class="tab_content">
$(Template(file=$conf["main"]["templatesPath"]+"/preview/modules/addLayer/WMSLayers.tmpl",searchList={"m":$m,"conf":$conf}))
<a class="vsource" onclick="mmAddWMSLayers();" href="#">$zoo._("Add")</a>
</div>
</div>
#end if
#end if
<|start_filename|>mapmint-services/routing/service.js<|end_filename|>
function computeRouteProfile(conf,inputs,outputs){
var myOutputs= {"Result": { "type": 'RawDataOutput', "mimeType": "application/json" }};
var myProcess = new ZOO.Process(conf["main"]["serverAddress"],'routing.doUnion');
var myExecuteResult=myProcess.Execute(inputs,myOutputs);
alert("*********** Parse error",myExecuteResult);
var myOutputs1= {"Profile": { type: 'ResponseDocument', "mimeType": "application/json", "asReference": "true" }};
var myProcess1 = new ZOO.Process(conf["main"]["serverAddress"],'routing.GdalExtractProfile');
inputs["RasterFile"]={"value":"topofr.tif","dataType":"string"}
var geom=false;
var json=new ZOO.Format.GeoJSON();
try{
var tmp=json.read(myExecuteResult);
geom=tmp[0].geometry;
}catch(e){
alert("*********** Parse error",e);
}
if(geom)
inputs["Geometry"]={"value": json.write(geom),"dataType":"string"}
else
inputs["Geometry"]={"value": myExecuteResult,"dataType":"string"}
var myExecuteResult1=myProcess1.Execute(inputs,myOutputs1);
return {result: ZOO.SERVICE_SUCCEEDED, outputs: {"Result": {"value": myExecuteResult1, "mimeType": "text/xml"}} };
}
<|start_filename|>public_map/assets/js/lib/mapmint/datatable.js<|end_filename|>
/**
* Author : <NAME>
*
* Copyright (c) 2015 GeoLabs SARL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
define([
'xml2json', 'queryString', 'wpsPayload', 'utils'
], function(X2JS, qs, wpsPayload, utils) {
/**
* The MMDataTable Class
* @constructs MMDataTable
* @param {Object} params Parameters
* @example
* var myZooObject = new ZooProcess({
* url: "http://localhost/cgi-bin/zoo_loader.cgi",
* delay: 2500
* });
*/
var MMDataTable = function(params) {
/**
* Object configuring the xml2json use.
*
* @access private
* @memberof ZooProcess#
* @var _x2js {x2js}
*/
var _x2js = new X2JS({
arrayAccessFormPaths: [
'ProcessDescriptions.ProcessDescription.DataInputs.Input',
'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
'Capabilities.ServiceIdentification.Keywords'
],
});
/**
* @access public
* @memberof ZooProcess#
* @var debug {Boolean} true if verbose messages should be displayed on the console
* @default false
*/
this.debug = false;
}
return MMDataTable;
});
<|start_filename|>public_map/assets/css/mm-font.css<|end_filename|>
@font-face {
font-family: 'mapmint-layers';
src:url('../fonts/mapmint-layers.eot?x5r743');
src:url('../fonts/mapmint-layers.eot?x5r743#iefix') format('embedded-opentype'),
url('../fonts/mapmint-layers.ttf?x5r743') format('truetype'),
url('../fonts/mapmint-layers.woff?x5r743') format('woff'),
url('../fonts/mapmint-layers.svg?x5r743#mapmint-layers') format('svg');
font-weight: normal;
font-style: normal;
}
.mm0-layers {
font-family: 'mapmint-layers';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.mm-layers-measure-area:before {
content: "\e900";
}
.mm-layers-measure-distance:before {
content: "\e901";
}
.mm-layers-add:before {
content: "\e800";
}
.mm-layers-overlays-only:before {
content: "\e816";
}
.mm-layers-baseonly:before {
content: "\e817";
}
.mm-layers-layers:before {
content: "\e80f";
}
<|start_filename|>mapmint-ui/new-themes/themes/pink/tree.css<|end_filename|>
.tree-node-selected{
background: #f630f8; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f869ec', endColorstr='#f630f8'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#f869ec), to(#f630f8)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
}
.menu-active{
border:1px solid #f982f5;
background:#fafafa;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
<|start_filename|>mapmint-ui/templates/Distiller/VectorConverter_bs.html<|end_filename|>
#import zoo
#import mm_access
<form id="vectorProcessing" class="form-inline">
<fieldset>
<legend>$zoo._("Source")</legend>
<input disabled="true" type="hidden" id="dst_in" value=""/>
<input type="hidden" id="dso_in1" value=""/>
<input disabled="true" type="text" class="form-control" id="dso_in" value=""/>
#import sqlite_module as sql
#set v="SELECT code as id,name, fav from spatial_ref_sys where fav order by name"
#set t=sql.request($conf,v)
<label for="chk1">$zoo._("SRS:")</label>
<input type="checkbox" id="chk1" onclick="if(this.checked) this.nextSibling.nextSibling.style.display='inline';else this.nextSibling.nextSibling.style.display='none';"/>
<select id="s_srs" class="form-control" style="display:none">
#for i in $t
<option value="$i[0].lower()">$i[1]</option>
#end for
</select>
</fieldset>
<fieldset>
<legend>$zoo._("Target")</legend>
#import datastores.service as ds
#import mapfile.service as ms
#set outputs={"Result":{"value":""}}
#set tt=ds.list($conf,$inputs,$outputs)
#set elements=eval($outputs["Result"]["value"])
<div>
<label for="tdso">$zoo._("Datastore:")</label>
<select id="tdso" class="form-control" onchange="var hasVal=false;for(var i=this.selectedIndex;i>=0;i--) if(this.options[i].value=='PostGIS') {hasVal=true;var opt=\$('#tdso_format')[0].options;for(var j=0;j<opt.length;j++) {if(opt[j].value!='PostgreSQL') opt[j].disabled=true;};\$('#tdso_format').val('PostgreSQL');\$('#tdso_format').attr('disabled', true);}; if(!hasVal) {var opt=\$('#tdso_format')[0].options;for(var j=0;j<opt.length;j++){if(opt[j].value=='PostgreSQL') opt[j].disabled=true; else opt[j].disabled=false;};\$('#tdso_format').removeAttr('disabled');\$('#tdso_format').val('ESRI Shapefile');}">
#for ij in $elements
#if $ij!="WFS"
<option disabled="true" style="font-weight: bold;color: #111">$ij</option>
#for jk in $elements[$ij]
#if $mm_access.checkDataStorePriv($conf,$jk.name,"rwx")
<option>$jk.name</option>
#end if
#end for
#end if
#end for
</select>
</div>
<div>
<label for="out_name">$zoo._("Datasource Name:")</label>
<input type="text" id="out_name" class="form-control" value="new_layer"/>
</div>
<div>
<label for="tdso_chk_srs">SRS:</label>
<input type="checkbox" id="tdso_chk_srs" onclick="\$(this).next().css({'display':(this.checked?'inline':'none')});"/>
<select class="form-control" id="tdso_srs" style="display: none;">
#for i in $t
<option value="$i[0].lower()">$i[1]</option>
#end for
</select>
<label for="tdso_format">$zoo._("Format:")</label>
<select id="tdso_format" class="form-control">
#import osgeo.ogr as ogr
#for iDriver in range(ogr.GetDriverCount()):
<option>$ogr.GetDriver(iDriver).GetName()</option>
#end for
</select>
</div>
<div>
$zoo._("Override:") <input type="radio" name="overr" checked="true" id="ov1" />
$zoo._("Append:") <input type="radio" name="overr" id="ov2" />
</div>
<div>
<label for="chkType">$zoo._("Geometry Type:")</label>
<input type="checkbox" id="chkType" onclick="if(this.checked) this.nextSibling.nextSibling.style.display='inline';else this.nextSibling.nextSibling.style.display='none';"/>
<select id="force_geometry_type" class="form-control" style="display:none">
#for i in ["GeometryCollection","Geometry","Multipolygon","Polygon","Multipoint","Point","MultiLinestring","Linestring"]
<option value="$(i.upper())">$zoo._($i)</option>
#end for
</select>
</div>
<div>
<fieldset>
<legend>$zoo._("Simplify") <input id="simplify_chk" type="checkbox" onclick="\$(this).parent().next().css({'display':(this.checked?'inline':'none')});"/></legend>
<input type="text" class="form-control" id="simplify" value="" style="display:none" />
</fieldset>
<fieldset>
<legend>$zoo._("SQL") <input id="sql_chk" type="checkbox" onclick="\$(this).parent().next().css({'display':(this.checked?'inline':'none')});"/></legend>
<textarea id="sql" class="form-control" style="width:470px;display:none;">SELECT * FROM layer</textarea>
</fieldset>
</div>
</fieldset>
<button class="btn btn-default">$zoo._("Run convertion")</button>
</form>
<|start_filename|>mapmint-ui/js/Manager.js<|end_filename|>
function updateSize(){
var li=0;
for(var l in layouts){
if(layouts[l].updateSize){
try{
layouts[l].updateSize();
}catch(e){alert(e);}
}
li++;
}
}
function reload(){
var node = $('#tt2').tree('getSelected');
if (node){
$('#tt2').tree('reload', node.target);
} else {
$('#tt2').tree('reload');
}
}
function getChildren(){
var node = $('#tt2').tree('getSelected');
if (node){
var children = $('#tt2').tree('getChildren', node.target);
} else {
var children = $('#tt2').tree('getChildren');
}
var s = '';
for(var i=0; i<children.length; i++){
s += children[i].text + ',';
}
alert(s);
}
function getChecked(){
var nodes = $('#tt2').tree('getChecked');
var s = '';
for(var i=0; i<nodes.length; i++){
if (s != '') s += ',';
s += nodes[i].text;
}
alert(s);
}
function getSelected(){
var node = $('#tt2').tree('getSelected');
alert(node.text);
}
function collapse(){
var node = $('#tt2').tree('getSelected');
$('#tt2').tree('collapse',node.target);
}
function expand(){
var node = $('#tt2').tree('getSelected');
$('#tt2').tree('expand',node.target);
}
function collapseAll(){
var node = $('#tt2').tree('getSelected');
if (node){
$('#tt2').tree('collapseAll', node.target);
} else {
$('#tt2').tree('collapseAll');
}
}
function expandAll(){
var node = $('#tt2').tree('getSelected');
if (node){
$('#tt2').tree('expandAll', node.target);
} else {
$('#tt2').tree('expandAll');
}
}
function append(){
var node = $('#tt2').tree('getSelected');
$('#tt2').tree('append',{
parent: (node?node.target:null),
data:[{
text:'new1',
checked:true
}]
});
}
function remove(){
var node = $('#tt2').tree('getSelected');
$('#tt2').tree('remove', node.target);
}
function update(){
var node = $('#tt2').tree('getSelected');
if (node){
node.text = '<span style="font-weight:bold">new text</span>';
node.iconCls = 'icon-save';
$('#tt2').tree('update', node);
}
}
function isLeaf(){
var node = $('#tt2').tree('getSelected');
var b = $('#tt2').tree('isLeaf', node.target);
alert(b);
}
MapMintDsRefresh=function(){
$.getJSON(
System.zooUrl+"?request=Execute&service=WPS&version=1.0.0&Identifier=mapfile.redrawDsList&DataInputs=name="+arguments[0]+"&RawDataOutput=Result",
{id: arguments[0], ajax: 'true'},
function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].value + '">' + j[i].name + '</option>';
}
$("select#select-datasource").html(options);
}
)
}
function addLayer(){
var dsoNames="";
var j=0;
$("#select-datasource").each(function(){
for(i=0;i<this.options.length;i++){
if(this.options[i].selected){
if(j>=1)
dsoNames+=";";
dsoNames+="dsoName="+this.options[i].value;
j+=1;
}
}
});
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=mapfile.loadMapForDs&DataInputs=map="+$('#mapName')[0].value+";dstName="+$("#select-datastore")[0].value+";"+dsoNames+";dsgName="+$("#select-group")[0].value+"",
dataType: "xml",
complete: function(xml,status) {
var tmp=$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp!="")
$.notifyBar({ cssClass: "error", html: tmp });
else{
$( "#add-layer-dialog" ).window('close');
startMapList();
}
}
});
}
function refreshMapLayers(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=mapfile.getLayersList&DataInputs=name="+$("#mapName")[0].value+"&RawDataOutput=Result",
dataType: "json",
complete: function(xml,status) {
var tmp=$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp!="")
$.notifyBar({ cssClass: "error", html: tmp });
else
$( "#add-layer-dialog" ).window('close');
}
});
}
function refreshTablesList(){
var localTarget=arguments[1];
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.listTablesAndViews&DataInputs=dataStore="+$('#complex_ds').val()+";schema="+$('#'+arguments[0]).val()+"&RawDataOutput=Result",
tid: arguments[0],
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var tmp=eval(xml.responseText);
$("#"+localTarget).html('<option value="-1">'+System.messages["Choose"]+'</option>');
for(i=0;i<tmp.length;i++)
$("#"+localTarget).append('<option value="'+tmp[i][0]+'">'+tmp[i][1]+'</option>');
}
}
});
}
function refreshFieldsList(){
var localTarget=[];
for(i=1;i<arguments.length;i++)
localTarget.push(arguments[i]);
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.getTableDescription&DataInputs=dataStore="+$('#complex_ds').val()+";table="+$('#'+arguments[0]).val()+"&RawDataOutput=Result",
tid: arguments[0],
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var tmp=eval(xml.responseText);
for(t=0;t<localTarget.length;t++){
$("#"+localTarget[t]).html('<option value="-1">'+System.messages["Choose"]+'</option>');
for(i=0;i<tmp.length;i++)
$("#"+localTarget[t]).append('<option value="'+tmp[i][1]+'">'+tmp[i][1]+'</option>');
}
}
}
});
}
function runComplexParam(){
$.ajax({
type: "GET",
url: "./Manager/ComplexSearch;layer="+System.mmNodeId+"&RawDataOutput=Result",
tid: arguments[0],
complete: function(xml,status) {
if(!$('#complex-params')[0])
$("body").append('<div id="complex-params" title="'+System.messages['Complex Search Engine Parameters']+'"></div>');
$('#complex-params').html("");
$('#complex-params').append(xml.responseText);
$("#FieldsSorted2").flexigrid({id:"cs"});
$("#FieldsSorted2 tbody").sortable();
$('#complex-params').window({
width: 1125,
height: 620,
maximizable:false,
resizable: false,
onClose: function(){
}
});
$(".hasInfo").tipsy({fade: true, offset:3, opacity: 1, gravity: 'se'});
}
});
}
function saveComplexParam(){
var dataInputs=[{name: "map",value: $("#mapName")[0].value,dataType: "string"},{name: "layer",value: System.mmNodeId,dataType: "string"}];
var sorted=0;
var args={};
var fields=[
["colonne_class","sfield"],
["alias_class","afield"],
["ids_class","ifield"],
["sessions_class","s1field"],
["values_class","vfield"],
["deps_class","vfield"],
["orders_class","ofield",true],
["multiples_class","mfield",true]
];
$("#FieldsSorted2").find("tr").each(function(){
for(i=0;i<fields.length;i++){
if(!args[fields[i][0]])
args[fields[i][0]]=[];
$(this).find("input."+fields[i][0]).each(function(){
if(fields[i].length>2)
args[fields[i][0]].push($(this).is(":checked"));
else
args[fields[i][0]].push($(this).val());
});
}
});
for(i=0;i<fields.length;i++){
dataInputs.push({name: fields[i][0],value: JSON.stringify(args[fields[i][0]]),mimeType: "application/json"});
}
if($("#tbl_abo").is(":checked")){
dataInputs.push({name: "subscription",value: JSON.stringify({"tbl":$("#tbl_abo_table").val(),"id": $("#tbl_abo_champ_id").val(),"sessid": $("#tbl_abo_session_id").val()}),mimeType: "application/json"});
}
var tmp={"tbl_legend": $("#legend_table").val(),"ofield":$("#orig_column").val(),"tfield":$("#target_column").val(),"color":$("#target_color").val(),"min":$("#target_min").val(),"max":$("#target_max").val()};
dataInputs.push({name: "legend",value: JSON.stringify(tmp),mimeType: "application/json"});
var data=WPSGetHeader("mapfile.saveComplexSearch")+WPSGetInputs(dataInputs)+WPSGetOutput({name: "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: 'text/xml',
url: System.zooUrl,
data: data,
complete: function(xml,status) {
checkWPSResult(xml);
}
});
}
<|start_filename|>mapmint-ui/templates/preview/modules/edit/list.html<|end_filename|>
#import zoo
<ul data-role="listview" data-inset="true" id="newsListContainer">
#import routing.service as r
#import json
#set d=r.listPOIUser($conf,{"type":{"value":"1"}},$outputs)
#set d=json.loads($outputs["Result"]["value"])
#for i in $d
<li id="$i[0]">
<div data-role="controlgroup" data-type="horizontal" data-mini="true">
#set j=json.loads($i[3])
<a href="#" data-role="button" data-icon="plus" onclick="zoomOnPoi($j.coordinates)">$zoo._("Display On Map")</a>
<h1>$i[1]</h1>
<p class="new_content">$i[2]</p>
#if $conf["senv"]["loggedin"]=="true" and r.getGroupForUser($conf)=="CG56"
<a href="#" data-role="button" data-icon="delete" onclick="deleteTrace('$i[0]')">$zoo._("Delete")</a>
#end if
</div>
</li>
#end for
</ul>
<|start_filename|>public_map/mapmint-fullscreen.js<|end_filename|>
var map;
var mybounds, markers, layer, osm, gsat, mapControls, loadingPanel;
var wgs84,mercator;
var gfiControl;
var System={};
System.loading_progress=0;
System.toLoad=0;
System.loaded=0;
System.flexi_cnt=0
System.ProcessLayers=[]
function progress1() {
$('#progress_bar .ui-progress').animateProgress(Math.round(((System.loaded-System.toLoad)*100)/System.loaded));
$('#progress_bar .ui-progress').animateProgress(Math.round(((System.loaded-System.toLoad)*100)/System.loaded));
}
function registerLoadEvents(layer) {
layer.events.register("loadstart", layer, function() {
System.loaded++;
System.toLoad++;
$("#loading").show();
//progress1();
});
layer.events.register("tileloaded", layer, function() {
var txt="<ul>";
var tmp=0;
for(var i=0;i<this.map.layers.length;i++){
if(this.map.layers[i].visibility){
if(this.map.layers[i].numLoadingTiles>0)
txt+="<li>"+this.map.layers[i].name + " (" + this.map.layers[i].numLoadingTiles + " left)</li>";
tmp+=this.map.layers[i].numLoadingTiles;
}
}
txt+="</ul>";
$('#progress_txt').html(txt);
if(tmp==0)
$("#loading").fadeOut();
});
layer.events.register("loadend", layer, function() {
doOnLayerLoad();
});
layer.events.register("loadcancel", layer, function() {
doOnLayerLoad();
});
}
function doOnLayerLoad(){
System.toLoad--;
//progress1();
if(System.toLoad<=0){
System.loaded=0;
System.toLoad=0;
$("#loading").fadeOut();
/*$('#progress_bar .ui-progress').animateProgress(100, function() {
$("#loading").hide();
});*/
}
}
var wgs84;
var mercator;
function init(){
/*$("#layerswitcher").css({height: ($(window).height()/2)+"px"});
$("#layers_list").css({height: (($(window).height()/2)-(46))+"px"});*/
tinit();
$("#layers_list").tree({checkbox: true,
onCheck: function(node, checked){
layersList[node.id.replace(/layer_/,"")].setVisibility(checked);
},
onContextMenu: function(e, node){
if(node.iconCls){
try{
e.preventDefault();
$("#layers_list").tree('select', node.target);
System.mmNodeId=node.id;
$('#ltm').menu('show', {
left: e.pageX,
top: e.pageY
});
}catch(e){alert(e);}
}
}
});
$("._layer_class").each(function(){
$(this).next().hide();
});
$("._group").each(function(){
$(this).next().hide();
});
$(".base_layer").tipsy();
wgs84=new OpenLayers.Projection("EPSG:4326");
mercator=new OpenLayers.Projection("EPSG:900913");
mybounds = new OpenLayers.Bounds(-179,-80,179,80);
mybounds=mybounds.transform(wgs84,mercator);
map = new OpenLayers.Map('map', {
controls: [new OpenLayers.Control.Navigation({'zoomWheelEnabled': false})],
projection: "EPSG:900913",
units: "m",
numZoomLevel: 19,
maxExtent: mybounds
});
/*loadingPanel = new OpenLayers.Control.LoadingPanel({ 'div': OpenLayers.Util.getElement('loading'), roundedCorner:false });
map.addControl(loadingPanel);*/
var styleMap = new OpenLayers.StyleMap({
"default": new OpenLayers.Style(null, {
rules: [new OpenLayers.Rule({
symbolizer: {
"Point": {
pointRadius: 4,
graphicName: "circle",
fillColor: "white",
fillOpacity: 1,
strokeWidth: 2,
strokeOpacity: 1,
strokeColor: "#808080"
},
"Line": {
strokeWidth: 2,
strokeOpacity: 1,
strokeColor: "#808080",
strokeDashstyle: "dash"
},
"Polygon": {
strokeWidth: 2,
strokeOpacity: 1,
strokeColor: "#808080",
strokeDashstyle: "dash",
fillColor: "white",
fillOpacity: 0.3
}
}
})]
})
});
startOverlay();
map.events.register("zoomend", null, updateSlider);
gfiControl = new OpenLayers.Control();
OpenLayers.Util.extend(gfiControl, {
draw: function () {
// this Handler.Box will intercept the shift-mousedown
// before Control.MouseDefault gets to see it
this.box = new OpenLayers.Handler.Box( gfiControl,
{"done": this.notice});
this.box.activate();
},
notice: function (bounds) {
$('#output-gfi').html("");
var ll = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.left, bounds.bottom)).transform(mercator,wgs84);
var ur = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.right, bounds.top)).transform(mercator,wgs84);
for(var i=0;i<queryLayersList.length;i++){
if(queryLayersList[i].visibility){
var localI=i;
$.ajax({
localI: i,
type: "GET",
url: zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=mapfile.getInitialInfo&DataInputs=map="+lastMap+";layer="+queryLayersList[i].real_name+"&RawDataOutput=Result",
dataType: 'xml',
complete:function(xml,status){
var tmp=$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp!=""){
alert(tmp);
return;
}
colModel=[];
fields=[];
var localI=this.localI;
if(queryLayersList[this.localI].displayed_fields=="all"){
var nbCol=0;
$(xml.responseXML).find("field").each(function(){
$(this).find("id").each(function(){
colModel[nbCol]={display: $(this).text(), name : $(this).text(), width: (nbCol==0?80:120), sortable : true, align: 'center'};
fields[nbCol]=$(this).text();
nbCol++;
});
});
}else{
var tmp=queryLayersList[this.localI].displayed_fields.split(',');
var tmp1=queryLayersList[this.localI].displayed_fields_width.split(',');
var tmp2=queryLayersList[this.localI].displayed_fields_aliases.split(',');
var nbCol=0;
$(xml.responseXML).find("field").each(function(){
$(this).find("id").each(function(){
for(var j=0;j<tmp.length;j++)
if(tmp[j]==$(this).text()){
colModel[nbCol]={display: (tmp2[j]&&tmp2[j]!="all"?tmp2[j]:$(this).text()), name : $(this).text(), width: (tmp1[j]?tmp1[j]:120), sortable : false, align: 'center'};
fields[nbCol]=$(this).text();
nbCol++;
}
});
});
}
$('#output-gfi').append('<table id="flex'+localI+'" style="display:none"></table>');
try{
var tmpName="#flex"+localI;
$("#flex"+localI).flexigrid({
autoload: true,
url: msUrl,
ogcProtocol: "WFS",
ogcUrl: msUrl,
autozoom: false,
dataType: 'xml',
colModel: colModel,
usepager: false,
ltoolbar: true,
id: localI,
fields: fields,
sortname: fields[0],
sortorder: "asc",
dwDataSource: pmapfile,
dwLayer: queryLayersList[localI].real_name,
title: queryLayersList[localI].name,
useLimit: false,
noSelection: false,
showTableToggleBtn: true,
width: "100%",
height: 290,
onHide: function(hidden) {
finalLayers[(this.id*3)].setVisibility(!hidden);
finalLayers[(this.id*3)+1].setVisibility(!hidden);
finalLayers[(this.id*3)+2].setVisibility(!hidden);
},
params: [{name: "bbox", value: ll.lon.toFixed(4)+","+ll.lat.toFixed(4)+","+ur.lon.toFixed(4)+","+ur.lat.toFixed(4) }],
tableToggleBtns: [{name: 'zoomToSetExtent',title: 'Zoom to set extent', onclick: function(){
map.zoomToExtent(finalLayers[(this.id.replace(/zoomToSetExtent_/,"")*3)].getDataExtent());
}}]
});
}catch(e){alert(e);}
var pixels= queryLayersList[this.localI].map.getPixelFromLonLat(new OpenLayers.LonLat(ll.lon, ll.lat));
$('.dialog-gfi').window({
width: 625,
height: 500,
maximizable:false,
resizable: false,
onClose: function(){
for(var i=0;i<finalLayers.length;i++){
finalLayers[i].removeFeatures(finalLayers[i].features);
}
}
});
}
});
}
System.flexi_cnt++;
}
}
});
mapControls = {
zoomin: new OpenLayers.Control.ZoomBox({title:"Zoom in box", out: false}),
getFeature: gfiControl,
line: new OpenLayers.Control.Measure(OpenLayers.Handler.Path,{
persist: true,
geodesic: true,
handlerOptions: {layerOptions: {styleMap: styleMap}},
eventListeners: {
"measure": handleMeasurements
}
}),
polygon: new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon,{
persist: true,
geodesic: true,
handlerOptions: {layerOptions: {styleMap: styleMap}},
eventListeners: {
"measure": handleMeasurements
}
})
};
map.events.register("mousemove", map, function(e) {
var pixel = new OpenLayers.Pixel(e.xy.x,e.xy.y);
var lonlat = map.getLonLatFromPixel(pixel);
var lonlatGCS = lonlat.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
OpenLayers.Util.getElement("coords").innerHTML = '' + Math.round(lonlatGCS.lon*1000000)/1000000 + ', ' + Math.round(lonlatGCS.lat*1000000)/1000000;
});
var tmp=new OpenLayers.LonLat(0,45);
tmp=tmp.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
);
map.setCenter(tmp,2);
/*zoom controls*/
$('a.zoomTo_in').click(function(ev){
ev.stopPropagation();
ev.preventDefault();
var zoom = map.getZoom();
map.zoomTo(zoom + 1);
slider.slider('value', slider.slider('value') + 1);
return false;
});
$('a.zoomTo_out').click(function(ev){
ev.stopPropagation();
ev.preventDefault();
var zoom = map.getZoom();
map.zoomTo(zoom - 1);
slider.slider('value', slider.slider('value')-1);
return false;
});
/*zoomTo slider*/
var numzoomlevels = map.getNumZoomLevels();
var slider = $('span.slider').slider({
orientation: "vertical",
range: "min",
animate: true,
min: 2,
max: numzoomlevels,
value: map.getZoom(),
step: 1,
slide: function(event, ui) {
map.zoomTo(ui.value);
},
change: function(event, ui) {
map.zoomTo(ui.value);
}
}).hover(function()
{
$('.ui-slider-vertical .ui-slider-handle').tipsy({live: true,title: function() { return map.getZoom(); }, gravity: 'w'})
});
}
// init() ends
function handleMeasurements(event) {
var geometry = event.geometry;
var units = event.units;
var order = event.order;
var measure = event.measure;
var lonlat = geometry.getBounds().getCenterLonLat();
var pixels= this.map.getPixelFromLonLat(new OpenLayers.LonLat(lonlat.lon, lonlat.lat));
var out = "";
if(order == 1) {
var element = document.getElementById('output-lenght');
out += "" + measure.toFixed(3) + " " + units;
$(".dialog-lenght").dialog({
autoOpen: false,
height: 50,
width: 200,
position: [pixels.x,pixels.y],
resizable: false,
close: function(event, ui) {
}
});
$(".dialog-lenght").dialog("open");
} else {
var element = document.getElementById('output-area');
out += "" + measure.toFixed(3) + " " + units + "<sup>2</sup>";
$(".dialog-area").dialog({
autoOpen: false,
height: 52,
width: 210,
position: [pixels.x,pixels.y],
resizable: false,
close: function(event, ui) {
}
});
$(".dialog-area").dialog("open");
}
element.innerHTML = out;
}
function zoomto(x,y,z) {
var point = new OpenLayers.LonLat(x,y);
point.transform(wgs84,mercator);
map.setCenter(point, z);
}
function updateSlider() {
$( "span.slider" ).slider( "option", "value", map.getZoom() );
}
function toggleControl(element) {
for(key in mapControls) {
var control = mapControls[key];
if(element.name == key && $(element).is('.ui-state-active')) {
map.addControl(control);
control.activate();
} else {
control.deactivate();
if(control.box)
control.box.deactivate();
}
}
}
$(function(){
$(".fg-button:not(.ui-state-disabled)")
.hover(
function(){
$(this).addClass("ui-state-hover");
},
function(){
$(this).removeClass("ui-state-hover");
}
)
.mousedown(function(){
$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
if( $(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
else { $(this).addClass("ui-state-active"); }
})
.mouseup(function(){
if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button, .fg-buttonset-multi .fg-button') ){
$(this).removeClass("ui-state-active");
}
});
});
$(function(){
$(".ls-button:not(.ui-state-disabled)")
.hover(
function(){
$(this).addClass("ui-state-hover");
},
function(){
$(this).removeClass("ui-state-hover");
}
)
.mousedown(function(){
$(this).parents('.ls-buttonset-single:first').find(".ls-button.ui-state-active").removeClass("ui-state-active");
if( $(this).is('.ui-state-active.ls-button-toggleable, .ls-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
else { $(this).addClass("ui-state-active"); }
})
.mouseup(function(){
if(! $(this).is('.ls-button-toggleable, .ls-buttonset-single .ls-button, .ls-buttonset-multi .ls-button') ){
$(this).removeClass("ui-state-active");
}
});
});
$(function(){
$('select#speedC').selectmenu({style:'dropdown'});
$('select#print-options').selectmenu({style:'dropdown'});
});
$(document).ready(function() {
$("#layerswitcher").toggle();
$(".ls-toogler").click(function () {
$("#layerswitcher").toggle();
});
$('.fg-toolbar a').tipsy({fade: true, offset:5, opacity: 1, gravity: 'nw'});
$('.toolbar-noborder a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
$(".print").click(function () {
$('#print-window').window( {
collapsible:false,
minimizable:false,
maximizable:false,
draggable:true,
resizable: false
});
$('#print-window').window('open');
});
$(".edit-toolbar").click(function () {
$( "#editing-toolbar" ).window({
collapsible:false,
minimizable:false,
maximizable:false,
draggable:true,
resizable: false
});
$('#editing-toolbar').window('open');
});
$(".spatial-toolbar").click(function () {
$( "#spatial-toolbar" ).window({
collapsible:false,
minimizable:false,
maximizable:false,
draggable:true,
resizable: false
});
$('#spatial-toolbar').window('open');
});
$(".raster-toolbar").click(function () {
$( "#raster-toolbar" ).window({
collapsible:false,
minimizable:false,
maximizable:false,
draggable:true,
resizable: false
});
$('#raster-toolbar').window('open');
});
$(".terrain-toolbar").click(function () {
$( "#terrain-toolbar" ).window({
collapsible:false,
minimizable:false,
maximizable:false,
draggable:true,
resizable: false
});
$('#terrain-toolbar').window('open');
});
$(function() {
$("select#speedC").change(function() {
var x1 = $(this).find("option:selected").attr("value").split(',')[0];
var y1 = $(this).find("option:selected").attr("value").split(',')[1];
var z1 = $(this).find("option:selected").attr("value").split(',')[2];
zoomto(x1,y1,z1)
});
});
$(".zoomTo").click(function () {
try{
var i=System.mmNodeId.replace(/layer_/,"");
var bounds = new OpenLayers.Bounds(
layersList[i].mmLc[0], layersList[i].mmLc[1],
layersList[i].mmUc[0], layersList[i].mmUc[1]
);
var proj=new OpenLayers.Projection("EPSG:4326");
map.zoomToExtent(bounds.transform(proj, map.getProjectionObject()));
}catch(e){}
});
});
// end ready
function singleGeom() {
var aProcess=arguments[1];
var tmpId=finalLayers[(arguments[0]*3)]?(arguments[0]*3):0;
//alert(tmpId+" "+arguments[0]);
if (finalLayers[tmpId+2].features.length == 0)
return alert("No feature selected!");
var started=true;
//alert(finalLayers[tmpId+3].name);
var dep=finalLayers[tmpId+3];
var url = '/cgi-bin/zoo_loader.cgi?request=Execute&service=WPS&version=1.0.0&';
if (aProcess == 'BufferPy') {
var dist = document.getElementById('bufferDist')?document.getElementById('bufferDist').value:'1';
if (isNaN(dist))
return alert("Distance is not a Number!");
url+='Identifier=BufferPy&DataInputs=BufferDistance=0.01@datatype=interger;InputPolygon=Reference@xlink:href=';
} else
if(aProcess == "SimpleBBOX" || aProcess == "SimpleChain" ||
aProcess == "Mask" || aProcess == "BufferMask" ||
aProcess == "BufferRequest" ||
aProcess == "SimpleChain1" || aProcess == "SimpleChain2")
url += 'Identifier='+(aProcess == "SimpleChain2"?"BufferRequest":aProcess)+'&DataInputs=InputData=Reference@xlink:href=';
else
url += 'Identifier='+aProcess+'&DataInputs=InputPolygon=Reference@xlink:href=';
var xlink = msUrl +"?map="+pmapfile+"&SERVICE=WFS&REQUEST=GetFeature&VERSION=1.0.0";
xlink += '&typename='+arguments[2];
//xlink += '&SRS='+control.protocol.srsName;
/*bounds = new OpenLayers.Bounds();
var f=new OpenLayers.Format.WKT();
var bbounds=f.read(select.features[0].geometry);
var bounds=select.features[0].geometry.getVertices();
var fbounds = new OpenLayers.Bounds();
for(var t in bounds){
fbounds.extend(bounds[t]);
}*/
xlink += '&FeatureID=';
for(var i=0;i<finalLayers[tmpId+2].features.length;i++)
xlink += (i>0?",":"") + finalLayers[tmpId+2].features[i].fid;
url += encodeURIComponent(xlink);
url += '&RawDataOutput=Result@mimeType=application/json';
var request = new OpenLayers.Request.XMLHttpRequest();
request.open('GET',url,true);
request.onreadystatechange = function() {
if(request.readyState == OpenLayers.Request.XMLHttpRequest.DONE) {
var GeoJSON = new OpenLayers.Format.GeoJSON();
var features = GeoJSON.read(request.responseText);
finalLayers[tmpId+3].removeFeatures(finalLayers[tmpId+3].features);
if(aProcess!="SimpleChain1" && aProcess!="SimpleChain2"
&& aProcess!="BufferRequest")
if(dep!=finalLayers[tmpId+3])
finalLayers[tmpId+3].removeFeatures(hover_.features);
try{
for(var j in features)
if(features[j].geometry){
features[j].geometry=features[j].geometry.transform(wgs84,mercator);
}
}catch(e){alert(e);}
finalLayers[tmpId+3].addFeatures(features);
/*slist=$(".multi-process:not(.ui-state-disabled)");
for(var i=0;i<slist.length;i++)
slist[i].style.display='block';*/
}
}
request.send();
/*if(aProcess == "SimpleChain2" && started)
singleProcessing("BufferMask",hover_);*/
}
<|start_filename|>mapmint-ui/templates/preview/modules/getFeatureCircle/control.js<|end_filename|>
,getFeatureCircle: gfiControlCircle
<|start_filename|>mapmint-ui/new-themes/themes/purple/misc.css<|end_filename|>
.tabs-right ul li:hover, .maps-container ul li:hover {cursor:pointer;
background: #8340f3; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#c743f8', endColorstr='#8340f3'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#c743f8), to(#8340f3)); /* for webkit browsers */
background: -moz-linear-gradient(top, #c743f8, #8340f3 ); /* for firefox 3.6+ */
}
<|start_filename|>mapmint-ui/templates/preview/modules/indexes/functions.js<|end_filename|>
#encoding UTF-8
#import zoo
function idx_activate(){
if(arguments[0]=="table" || arguments[0]=="removeAll" ){
for(i in idxCtrl){
if(i!=arguments[0]){
idxCtrl[i].deactivate();
if(idxCtrl[i].box)
idxCtrl[i].box.deactivate();
}
}
if(arguments[0]=="table")
getTerritoriesTable();
else
removeAllSelectedFeatures();
return;
}
for(i in idxCtrl){
if(i!=arguments[0]){
idxCtrl[i].deactivate();
if(idxCtrl[i].box)
idxCtrl[i].box.deactivate();
}
else{
if(arguments[0]!="table"){
map.addControl(idxCtrl[arguments[0]]);
idxCtrl[arguments[0]].activate();
if(idxCtrl[i].box)
idxCtrl[i].box.activate();
}
}
}
}
function removeAllSelectedFeatures(){
if(System.si=="in")
toggleRepportSubmit(false);
\$('#basket_'+System.si).html('');
for(i=System.cfeatures.length-1;i>=0;i--){
if(System.cfeatures[i]["mmtype"]==System.si)
System.cfeatures.pop(i);
}
if(System.overlays[System.si]){
map.removeLayer(System.overlays[System.si]);
System.overlays[System.si]=false;
}
if(System.allOverlays){
try{
params=[];
params.push({"name": "InputEntity1","xlink:href": System.allOverlays+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result&bbox="+bounds0.getBounds()+"&times="+(Date()+"").split(' ')[4],"mimeType": "text/xml"});
params.push({"name": "InputEntity2","xlink:href": ((System.si=="in")?System.inMap:System.outMap)+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result&times="+(Date()+"").split(' ')[4],"mimeType": "text/xml"});
req=WPSGetHeader("vector-tools.Remove")+WPSGetInputs(params)+WPSGetOutput({"name": "Result","form":"ResponseDocument","mimeType": "image/png","asReference":"true"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: req,
complete: function(xml,status) {
System.allOverlays=WPSParseReference(xml);
}
});
}catch(e){}
}
if(System.si=="in"){
System.inMap=false;
System.inMap0=false;
}else{
System.outMap=false;
System.outMap0=false;
}
}
function displayIndexInfo(i,ll,ur){
idxRequestFeatures({
map: pmapfiles[queryLayersList[i].real_name][0],
typename: queryLayersList[i].real_name,
bbox: ll.lon.toFixed(4)+","+ll.lat.toFixed(4)+","+ur.lon.toFixed(4)+","+ur.lat.toFixed(4)
});
}
function getIndexInfo(i,ll,ur){
var ll=ll;
var ur=ur;
\$.ajax({
localI: i,
ll: ll,
ur: ur,
type: "GET",
url: zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=mapfile.getInitialInfo&DataInputs=map="+lastMap+";layer="+queryLayersList[i].real_name+"&RawDataOutput=Result",
dataType: 'xml',
complete:function(xml,status){
var tmp=\$(xml.responseXML).find("ows\\:ExceptionText").text();
if(!tmp)
tmp=\$(xml.responseXML).find("ExceptionText").text();
if(tmp!=""){
return;
}
var localI=this.localI;
idxRequestFeatures({
map: pmapfiles[queryLayersList[localI].real_name][0],
typename: queryLayersList[localI].real_name,
bbox: ll.lon.toFixed(4)+","+ll.lat.toFixed(4)+","+ur.lon.toFixed(4)+","+ur.lat.toFixed(4),
i: this.localI
});
}
});
}
function idxRequestFeatures(){
var cid0=0;
for(i=0;i<layersList.length;i++){
if(layersList[i].name==queryLayersList[arguments[0].i].name){
cid0=i;
break;
}
}
var cid=map.getLayerIndex(finalLayers[(cid0*4)+1]);
//map.removeLayer(finalLayers[(cid0*4)+1]);
\$.ajax({
type: "GET",
layer: queryLayersList[arguments[0].i].real_name,
i: arguments[0].i,
url: "./modules/indexes/project_js;layer="+queryLayersList[arguments[0].i].real_name+";ext="+arguments[0]["bbox"],
complete:function(xml,status){
tmp=eval(xml.responseText);
var sld="<StyledLayerDescriptor version=\"1.0.0\"><NamedLayer><Name>"+this.layer+"</Name><UserStyle><Title>hatch with background</Title><FeatureTypeStyle><Rule><Name>default</Name><Filter><BBOX><PropertyName>msGeometry</PropertyName><Box><coordinates>"+tmp[0]+","+tmp[1]+" "+tmp[2]+","+tmp[3]+"</coordinates></Box></BBOX></Filter><PolygonSymbolizer><Fill><CssParameter name=\"fill\">#880000</CssParameter></Fill></PolygonSymbolizer></Rule></FeatureTypeStyle></UserStyle></NamedLayer></StyledLayerDescriptor>";
var tmp=new OpenLayers.Layer.WMS(
"Select",
queryLayersList[this.i].url,
{
format: "image/png",
layers: queryLayersList[this.i].params["LAYERS"],
styles: "default",
sld_body: sld
},
{useCanvas: System.useCanvas,isBaseLayer: false}
);
tmp.setVisibility(true);
map.addLayer(tmp);
map.setLayerIndex(tmp,cid);
idxReadFeatures(xml);
}
});
//finalLayers[(arguments[0].i*4)+1].redraw(true);
/*
\$.ajax({
type: "GET",
url: msUrl+"?map="+arguments[0]["map"]+"&version=1.0.0&service=WFS&request=GetFeature&typename="+arguments[0]["typename"]+"&bbox="+arguments[0]["bbox"],
dataType: 'xml',
complete:function(xml,status){
idxReadFeatures(xml);
}
});
*/
}
function toggleRepportSubmit(){
if(arguments[0])
\$("#repport_submit").show();
else
\$("#repport_submit").hide();
}
System.loadTemplate={};
function idxReadFeatures(xml){
fRead=new OpenLayers.Format.GeoJSON({
'internalProjection': map.getProjectionObject(),
'externalProjection': new OpenLayers.Projection("EPSG:4326")
});
var localFeatures=fRead.read(xml.responseText);
if(!System.loadTemplate[\$('#it1 option:selected').text()])
System.loadTemplate[\$('#it1 option:selected').text()]=false;
System[System.si+"_length"]=localFeatures.length;
for(var j=0;j<localFeatures.length;j++){
if(!System.iltemplates[\$('#it1 option:selected').text()] && !System.loadTemplate[\$('#it1 option:selected').text()]){
System.loadTemplate[\$('#it1 option:selected').text()]=true;
fetchTemplate(localFeatures);
}
else{
try{
printTemplate(localFeatures[j]);
}catch(e){}
}
}
}
function getTerritoriesTable(){
for(var i=0;i<queryLayersList.length;i++){
if(queryLayersList[i].real_name==\$('#it1 option:selected').text()){
var localI=i;
getTerritoryTable(i);
System.flexi_cnt++;
break;
}
}
}
function getTerritoryTable(i){
\$.ajax({
localI: i,
type: "GET",
url: zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=mapfile.getInitialInfo&DataInputs=map="+lastMap+";layer="+queryLayersList[i].real_name+"&RawDataOutput=Result",
dataType: 'xml',
complete:function(xml,status){
var tmp=\$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp!=""){
return;
}
colModel=[];
searchitems=[];
fields=[];
featurecnt=0;
var localI=this.localI;
\$(xml.responseXML).find("featureCount").each(function(){
featurecnt=\$(this).text();
});
if(queryLayersList[this.localI].displayed_fields=="all"){
var nbCol=0;
\$(xml.responseXML).find("field").each(function(){
\$(this).find("id").each(function(){
colModel[nbCol]={display: \$(this).text(), name : \$(this).text(), width: (nbCol==0?80:120), sortable : true, align: 'center'};
searchitems[nbCol]={display: \$(this).text(), name : \$(this).text()};
fields[nbCol]=\$(this).text();
nbCol++;
});
});
}else{
var tmp=queryLayersList[this.localI].displayed_fields.split(',');
var tmp1=queryLayersList[this.localI].displayed_fields_width.split(',');
var tmp2=queryLayersList[this.localI].displayed_fields_aliases.split(',');
var nbCol=0;
\$(xml.responseXML).find("field").each(function(){
\$(this).find("id").each(function(){
for(var j=0;j<tmp.length;j++)
if(tmp[j]==\$(this).text()){
colModel[nbCol]={display: (tmp2[j]&&tmp2[j]!="all"?tmp2[j]:\$(this).text()), name : \$(this).text(), width: (tmp1[j]?tmp1[j]:120), sortable : false, align: 'center'};
searchitems[nbCol]={display: (tmp2[j]&&tmp2[j]!="all"?tmp2[j]:\$(this).text()), name : \$(this).text()};
fields[nbCol]=\$(this).text();
nbCol++;
}
});
});
}
\$('#output-gfi').html('<table id="flex'+localI+'" style="display:none"></table>');
try{
var tmpName="#flex"+localI;
\$("#flex"+localI).flexigrid({
autoload: true,
url: msUrl,
ogcProtocol: "WFS",
ogcUrl: msUrl,
autozoom: false,
dataType: 'xml',
colModel: colModel,
searchitems: searchitems,
usepager: true,
ltoolbar: false,
cfailed: true,
id: this.localI,
fields: fields,
sortname: fields[0],
sortorder: "asc",
dwDataSource: pmapfiles[queryLayersList[localI].real_name][0],
dwLayer: queryLayersList[localI].real_name,
title: queryLayersList[localI].name,
useLimit: false,
nbElements: featurecnt,
noSelection: false,
showTableToggleBtn: true,
width: "100%",
height: 290,
onHide: function(hidden) {
finalLayers[(this.id*4)].setVisibility(!hidden);
finalLayers[(this.id*4)+1].setVisibility(!hidden);
finalLayers[(this.id*4)+2].setVisibility(!hidden);
finalLayers[(this.id*4)+3].setVisibility(!hidden);
},
params: [{name: "maxfeatures", value: 15 }],
tableToggleBtns: [
{name: 'zoomToSetExtent',title: '$zoo._("Zoom to set extent").replace("'","\\'")', onclick: function(){
map.zoomToExtent(finalLayers[(this.id.replace(/zoomToSetExtent_/,"")*4)].getDataExtent());
}},
{name: 'addSelectedItems',title: '$zoo._("Add selected items").replace("'","\\'")', onclick: function(){
geojson=new OpenLayers.Format.GeoJSON({
'internalProjection': map.getProjectionObject(),
'externalProjection': new OpenLayers.Projection("EPSG:4326")
});
var tmpIdp=this.id.replace(/addSelectedItems_/,"");
var tmpId0=tmpIdp*4;
var tmpId=tmpId0+2;
filter="<Filter><OR>"
//var lfeatures=geojson.write(finalLayers[tmpId].features);
//alert(lfeatures);
try{
for(i=0;i<finalLayers[tmpId].features.length;i++){
var feature=finalLayers[tmpId].features[i];
/*if(!System.iltemplates[\$('#it1 option:selected').text()]){
try{
fetchTemplate(feature);
}catch(e){
alert("fecthTemplate: "+e);
}
}
else
printTemplate(feature);*/
filter+="<PropertyIsLike wildcard='*' singleChar='.' escape='!'><PropertyName>"+System.full_index["indicateurs_territoires_key"]+"</PropertyName><Literal>"+(feature.data && feature.data[System.full_index["indicateurs_territoires_key"]]?feature.data[System.full_index["indicateurs_territoires_key"]]:feature.attributes[System.full_index["indicateurs_territoires_key"]])+"</Literal></PropertyIsLike>"
}
filter+="</OR></Filter>";
//alert(msUrl+"?service=WFS&request=GetFeature&verion=1.0.0&map="+pmapfiles[queryLayersList[tmpIdp].real_name][0]+"&typename="+queryLayersList[tmpIdp].real_name+"&filter="+(filter.replace(/</g,"<").replace(/>/g,">")));
//req0=WPSGetHeader("nullGeo")+WPSGetInputs([{"name": "InputEntity1", "xlink:href": msUrl+"?map="+pmapfiles[queryLayersList[tmpIdp].real_name][0]+"&typename="+queryLayersList[tmpIdp].real_name+"&__tt="+Date()+"&filter="+(filter.replace(/</g,"<").replace(/>/g,">")),"mimeType": "text/xml"}])+WPSGetOutput({"name": "Result","form":"RawDataOutput","mimeType": "application/json","asReference":"true"})+WPSGetFooter();
rbody='<wps:Body><wfs:GetFeature service="WFS" version="1.0.0" outputFormat="GML2" xmlns:wfs="http://www.opengis.net/wfs" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd"><wfs:Query typeName="'+queryLayersList[tmpIdp].real_name+'">'+filter+'</wfs:Query></wfs:GetFeature></wps:Body>';
var params=[];
if(System.inMap || System.outMap){
if(!System.allOverlays){
if((System.si=="in") && System.outMap)
params.push({"name": "InputEntity2","xlink:href": System.outMap+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
else
if(System.inMap)
params.push({"name": "InputEntity2","xlink:href": System.inMap+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
}else
params.push({"name": "InputEntity2","xlink:href": System.allOverlays+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result&__tt="+Date(),"mimeType": "text/xml"});
}
params.push({"name": "InputEntity1", "xlink:href": msUrl+"?map="+pmapfiles[queryLayersList[tmpIdp].real_name][0],"method":"POST","headers":[{"key":"Content-Type","value":"text/xml"}],"body": rbody,"mimeType": "text/xml"});
req=WPSGetHeader("vector-tools.getFeaturesCopy")+WPSGetInputs(params)+WPSGetOutput({"name": "Result","form":"ResponseDocument","mimeType": "image/png","asReference":"true"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: req,
complete: function(xml,status) {
//urlContext = xml.responseText;
var params=[];
if(System.si=="in"){
if(System.inMap){
System.inMap0=System.inMap;
params.push({"name": "InputEntity1", "xlink:href": System.inMap0+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
}
System.inMap=WPSParseReference(xml);
//alert((params.length+1)+" "+System.inMap);
//alert(xml);
params.push({"name": "InputEntity"+(params.length+1), "xlink:href": System.inMap+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
}else{
if(System.outMap){
System.outMap0=System.outMap;
params.push({"name": "InputEntity2", "xlink:href": System.outMap0+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
}
System.outMap=WPSParseReference(xml);
params.push({"name": "InputEntity1", "xlink:href": System.outMap+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
}
req0=WPSGetHeader("vector-tools.nullGeo")+WPSGetInputs([{"name": "InputEntity1", "xlink:href": ((System.si=="in")?System.inMap:System.outMap)+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=ms:Result"+"&__tt="+Date(),"mimeType": "text/xml"}])+WPSGetOutput({"name": "Result","form":"RawDataOutput","mimeType": "application/json","asReference":"true"})+WPSGetFooter();
indexes_reaction(req0,params);
}
});
}catch(e){
//alert(e);
}
//alert("ok");
finalLayers[tmpId0].getDataExtent();
}
}
]
});
}catch(e){alert(e);}
\$('.dialog-gfi').window({
width: 625,
height: 500,
resizable: false,
maximizable:false,
resizable: false,
onClose: function(){
for(var i=0;i<finalLayers.length;i++){
finalLayers[i].removeFeatures(finalLayers[i].features);
}
processResultLayer.removeFeatures(processResultLayer.features);
}
});
}
});
}
System.iltemplates={};
function fetchTemplate(){
//alert("$conf["main"]["templatesAddress"]"+\$('#it1 option:selected').text()+"_$(conf["senv"]["last_map"])_tmpl.html");
//alert(arguments[0]);
//System
\$.ajax({
type: "GET",
url: "$conf["main"]["templatesAddress"]"+\$('#it1 option:selected').text()+"_$(conf["senv"]["last_map"])_tmpl.html",
mm_features: arguments[0],
complete: function(xml,status) {
var res=xml.responseText.replace(/item name/g,"");
System.iltemplates[\$('#it1 option:selected').text()]=res;
System.loadTemplate[\$('#it1 option:selected').text()]=false;
var features=this.mm_features;
//alert("FEATURES: "+features);
try{
printTemplate(features);
}catch(e){
//alert("Error in printTemplate: "+e);
for(var j=0;j<features.length;j++){
{
//alert("feature "+j);
printTemplate(features[j]);
}
}
}
}
});
}
System.iltemplates0={};
function printTemplate(feature){
//alert(arguments[0]);
if(!feature){
//alert("arguments[0] is null !");
return;
}
var j=0;
//alert('ok -2');
if(!System.iltemplates0[\$('#it1 option:selected').text()])
System.iltemplates0[\$('#it1 option:selected').text()]=System.iltemplates[\$('#it1 option:selected').text()];
//alert('ok -1');
var res1=System.iltemplates[\$('#it1 option:selected').text()];
//alert('ok 0');
for(j in feature.data){
if(j!="msGeometry"){
preres1=res1;
res1=res1.replace("[="+j+"]",feature.data[j]);
if(preres1!=res1){
System.sifield=j;
}
}
}
//alert('ok 1');
/*for(j in feature.attributes){
if(j!="msGeometry"){
preres1=res1;
res1=res1.replace("[="+j+"]",feature.attributes[j]);
if(preres1!=res1){
System.sifield=j;
}
}
}*/
if(!System.cfeatures)
System.cfeatures=[];
for(i=0;i<System.cfeatures.length;i++){
if(System.cfeatures[i]["val"]==feature.attributes[System.sifield]){
return;
}
}
var tmpFeature=feature.clone();
tmpFeature.attributes["idx_type"]=System.si;
tmpFeature.attributes["idx_id"]=TerritoriesSelected.features.length;
if(!System.si0)
System.si0=0;
res1='<div id="'+System.si+'_'+System.si0+'"><input name="toto_'+System.si0+'" id="toto_'+System.si0+'" value="'+feature.data[System.full_index["indicateurs_territoires_key"]]+'" type="hidden" /><a href="#" class="sdelete" onclick="idxRemoveFeature(\$(this).parent().attr(\'id\').replace(/'+System.si+'_/g,\'\'));\$(this).parent().remove();"></a>'+res1+'</div>';
//TerritoriesSelected.addFeatures([tmpFeature]);
var tmp=System.sifield;
System.cfeatures.push({"val": feature.attributes[System.full_index["indicateurs_territoires_key"]],"mmtype": System.si});
\$("#basket_"+System.si).append(res1);
System.si0+=1;
}
function idxRemoveFeature(id){
filter="<Filter>"
filter+="<PropertyIsLike wildcard='*' singleChar='.' escape='!'><PropertyName>"+System.full_index["indicateurs_territoires_key"]+"</PropertyName><Literal>"+\$("#toto_"+id).val()+"</Literal></PropertyIsLike>"
filter+="</Filter>"
var tmpIdp=0;
for(var i=0;i<queryLayersList.length;i++){
if(queryLayersList[i].real_name==\$('#it1 option:selected').text()){
tmpIdp=i;
break;
}
}
rbody='<wps:Body><wfs:GetFeature service="WFS" version="1.0.0" outputFormat="GML2" xmlns:wfs="http://www.opengis.net/wfs" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd"><wfs:Query typeName="'+queryLayersList[tmpIdp].real_name+'">'+filter+'</wfs:Query></wfs:GetFeature></wps:Body>';
if(System.allOverlays){
try{
params=[];
params.push({"name": "InputEntity1","xlink:href": System.allOverlays+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result&times="+(Date()+"").split(' ')[4],"mimeType": "text/xml"});
params.push({"name": "InputEntity2", "xlink:href": msUrl+"?map="+pmapfiles[queryLayersList[tmpIdp].real_name][0],"method":"POST","headers":[{"key":"Content-Type","value":"text/xml"}],"body": rbody,"mimeType": "text/xml"});
req=WPSGetHeader("vector-tools.Remove")+WPSGetInputs(params)+WPSGetOutput({"name": "Result","form":"ResponseDocument","mimeType": "image/png","asReference":"true"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: req,
complete: function(xml,status) {
System.allOverlays=WPSParseReference(xml);
}
});
}catch(e){}
}
params=[];
params.push({"name": "InputEntity1","xlink:href": ((System.si=="in")?System.inMap:System.outMap)+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result&times="+(Date()+"").split(' ')[4],"mimeType": "text/xml"});
params.push({"name": "InputEntity2", "xlink:href": msUrl+"?map="+pmapfiles[queryLayersList[tmpIdp].real_name][0],"method":"POST","headers":[{"key":"Content-Type","value":"text/xml"}],"body": rbody,"mimeType": "text/xml"});
req=WPSGetHeader("vector-tools.Remove")+WPSGetInputs(params)+WPSGetOutput({"name": "Result","form":"ResponseDocument","mimeType": "image/png","asReference":"true"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: req,
complete: function(xml,status) {
if(System.si=="in")
System.inMap=WPSParseReference(xml);
else
System.outMap=WPSParseReference(xml);
var sld="<StyledLayerDescriptor version=\"1.0.0\"><NamedLayer><Name>Result</Name><UserStyle><Title>hatch with background</Title><FeatureTypeStyle><Rule><Name>default</Name><PolygonSymbolizer><Fill><CssParameter name=\"fill\">"+((System.si=="in")?"#FF0000":"#0000FF")+"</CssParameter></Fill><Stroke><CssParameter name=\"stroke\">#ffffff</CssParameter></Stroke></PolygonSymbolizer></Rule></FeatureTypeStyle></UserStyle></NamedLayer></StyledLayerDescriptor>";
if(System.overlays[System.si]){
map.removeLayer(System.overlays[System.si]);
}
System.overlays[System.si]=new OpenLayers.Layer.WMS(
"Select"+System.si,
((System.si=="in")?System.inMap:System.outMap),
{
format: "image/png",
layers: "Result",
styles: "default",
sld_body: sld
},
{useCanvas: System.useCanvas,isBaseLayer: false}
);
System.overlays[System.si].setVisibility(true);
System.overlays[System.si].setOpacity(0.3);
map.addLayer(System.overlays[System.si]);
map.setLayerIndex(System.overlays[System.si],map.layers.length-1);
}
});
//System.cfeatures=[];
//return;
for(i=0;i<TerritoriesSelected.features.length;i++){
alert(TerritoriesSelected.features[i].attributes["idx_id"]);
if(TerritoriesSelected.features[i].attributes["idx_id"]==id){
alert(TerritoriesSelected.features[i].attributes["idx_id"]);
try{
TerritoriesSelected.removeFeatures([TerritoriesSelected.features[i]]);
}catch(e){alert(e);}
}
}
}
function idxPrintDocument(){
params=[
{"name": "idx","value":System.index,dataType:"string"},
{"name": "field","value":System.full_index["indicateurs_territoires_key"],dataType:"string"}
];
for(i=0;i<System.cfeatures.length;i++){
params.push({"name": System.cfeatures[i]["mmtype"]+"_val","value":System.cfeatures[i]["val"],dataType:"string"});
}
\$("#idxs_list").find("div").each(function(){
params.push({"name": "idx","value":\$(this).attr('id').replace(/idx_/g,""),dataType:"string"});
});
params.push({"name": "tid","value":\$('#it1').val(),dataType:"string"});
data=WPSGetHeader("np.viewRepport")+WPSGetInputs(params)+WPSGetOutput({name:"Result",form: "ResponseDocument","status": "true","storeExecuteResponse": "true", "asReference": "true"})+WPSGetFooter();
\$("#doc_progress_bar_c").show();
\$('#repport_submit').hide();
\$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
WPSPull(xml,
function(){
\$('#doc_progress_bar .ui-progress').animateProgress(arguments[0]);
\$('#doc_progress_bar_c .loading').html(arguments[1]);
},
function(){
var ref0=WPSParseReference(arguments[0]);
if(ref0){
\$("#doc_progress_bar_c").hide();
\$('#repport_submit').show();
var reg0=new RegExp(System.tmpUrl,"g");
\$.ajax({
type: "GET",
url: zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=print.preview&DataInputs=res=42;file="+ref0.replace(reg0,System.tmpPath)+"&ResponseDocument=Result@asReference=true",
complete: function(xml,status){
if(\$('#print-preview-dialog')[0]){
\$("#print-preview-dialog").window('close');
\$("#print-preview-dialog").remove();
}
\$("body").append('<div id="print-preview-dialog" title="$zoo._("Preview printed Document").replace("'","\\'")"><div id="print-content"><a href="'+ref0+'" target="_blank" class="vidx">Télécharger le rapport</a><a href="'+ref0+'" target="_blank"><img id="preview-link" src="'+WPSParseReference(xml)+'?r='+Date()+'"/></a></div></div></div>')
var prpos=\$(window).width() - 750;
\$("#print-preview-dialog").window({
closed: false,
top: 100,
left: prpos,
width: 420,
height: 381,
resizable:false,
minimizable: false,
maximizable:false,
collapsible:false
});
}
});
}
},
function(){
\$("#doc_progress_bar_c").hide();
\$('#repport_submit').show();
});
}
});
}
var OverlaysLayers=[];
function mmAddOverlayLayers(){
var params=[
{"name": "map","value":"idxOverlays",dataType:"string"}
];
var nodes=\$("#overlays_list").tree('getChecked');
var legend=[];
for(i in nodes)
if(nodes[i]["id"]){
params.push({"name": "id","value": nodes[i]["id"].replace(/layer_/g,""),dataType:"string"});
var j = parseInt(nodes[i]["id"].replace(/layer_/g,""));
legend.push({
"id": "layer_"+(layersList.length),
"text": nodes[i]["text"],
"children": \$("#overlays_list").tree('getChildren',nodes[i]["target"])
});
\$("#overlays_list").tree('uncheck',nodes[i].target);
}
\$("#layers_list").tree('append',{
parent: \$("#layers_list").tree('getRoot').target,
data:[
{
"id": "layer_"+(layersList.length),
checked: true,
text: '<a href="#" class="sdelete" onclick="removeOverlays(\$(this));"></a>'+System.messages["Overlay Layers"]+" "+(OverlaysLayers.length+1),
children: legend
}
]
});
var cnt=0;
\$("div").find("[node-id='layer_"+layersList.length+"']").each(function(){
if(cnt==0){
cnt+=1;
return;
}
var child=\$(this).children();
for(i=0;i<child.length;i++){
if(\$(child[i]).attr("class")!=\$(child[i]).attr("class").replace(/tree-checkbox/g,"")){
\$(child[i]).hide();
}
}
});
\$(".tree_overlays_layer_class").next().hide();
var data=WPSGetHeader("mapfile.getLayers")+WPSGetInputs(params)+WPSGetOutput({name:"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
var tmp=\$.parseJSON(xml.responseText);
var layers="";
for(i=0;i<tmp.length;i++){
if(layers!="")
layers+=",";
layers+=tmp[i];
}
OverlaysLayers[OverlaysLayers.length]=new OpenLayers.Layer.WMS(
"Overlay Layers "+OverlaysLayers.length,
System.mapUrl+"?map="+System.dataPath+"/maps/project_idxOverlays.map",
{layers: layers,format: "image/png"},
{useCanvas: System.useCanvas,isBaseLayer: false}
);
OverlaysLayers[OverlaysLayers.length-1].setVisibility(true);
map.addLayer(OverlaysLayers[OverlaysLayers.length-1]);
layersList[layersList.length]=OverlaysLayers[OverlaysLayers.length-1];
if(System.fullList.length>0)
System.fullList.push({name: layersList[layersList.length-1].name, id: (layersList.length-1),text: "Overlay Layers "+(OverlaysLayers.length-1)});
}
});
}
function removeOverlays(){
//\$("#layer_list").tree('pop',arguments[0].parent().parent());
layersList[parseInt(arguments[0].parent().parent().attr('node-id').replace(/layer_/g,""))].setVisibility(false);
for(i=0;i<System.fullList.length;i++)
if(System.fullList[i].id==parseInt(arguments[0].parent().parent().attr('node-id').replace(/layer_/g,"")))
System.fullList.pop(i);
arguments[0].parent().parent().parent().remove();
}
var WMSLayers=[];
function mmAddWMSLayers(){
var nodes=\$("#wms_list").tree('getChecked');
var tmp={"text":""}
var layers="";
var legend=[];
for(i in nodes)
if(nodes[i]["id"]){
if(layers!="")
layers+=",";
layers+=nodes[i]["id"];
tmp=\$("#wms_list").tree('getParent',nodes[i].target);
legend.push({
"id": "layer_"+i+"_"+(layersList.length),
"text": nodes[i]["text"],
"children": \$("#wms_list").tree('getChildren',nodes[i]["target"])
});
\$("#wms_list").tree('uncheck',nodes[i].target);
}
\$("#layers_list").tree('append',{
parent: \$("#layers_list").tree('getRoot').target,
data:[
{
"id": "layer_"+(layersList.length),
checked: true,
text: '<a href="#" class="sdelete" onclick="removeOverlays(\$(this));"></a>'+System.messages["WMS Layers"]+" "+(WMSLayers.length+1),
children: legend
}
]
});
WMSLayers[WMSLayers.length]=new OpenLayers.Layer.WMS(
"WMS Layers "+(WMSLayers.length+1),
System.mapUrl+"?map="+System.dataPath+"/WMS/"+tmp.text+"ds_ows.map",
{layers: layers,format: "image/png"},
{useCanvas: System.useCanvas,isBaseLayer: false}
);
WMSLayers[WMSLayers.length-1].setVisibility(true);
map.addLayer(WMSLayers[WMSLayers.length-1]);
layersList[layersList.length]=WMSLayers[WMSLayers.length-1];
if(System.fullList.length>0)
System.fullList.push({name: layersList[layersList.length-1].name, id: (layersList.length-1),text: "WMS Layers "+(WMSLayers.length)});
}
function indexes_reaction(req0,params){
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: req0,
complete: function(xml,status) {
idxReadFeatures(xml);
req=WPSGetHeader("vector-tools.Append")+WPSGetInputs(params)+WPSGetOutput({"name": "Result","form":"ResponseDocument","mimeType": "image/png","asReference":"true"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: req,
complete: function(xml,status) {
if(System.si=="in"){
System.inMap=WPSParseReference(xml);
toggleRepportSubmit(System[System.si+"_length"]>0);
}
else
if(System.outMap)
System.outMap=WPSParseReference(xml);
var sld="<StyledLayerDescriptor version=\"1.0.0\"><NamedLayer><Name>Result</Name><UserStyle><Title>hatch with background</Title><FeatureTypeStyle><Rule><Name>default</Name><PolygonSymbolizer><Fill><CssParameter name=\"fill\">"+((System.si=="in")?"#FF0000":"#0000FF")+"</CssParameter></Fill><Stroke><CssParameter name=\"stroke\">#ffffff</CssParameter></Stroke></PolygonSymbolizer></Rule></FeatureTypeStyle></UserStyle></NamedLayer></StyledLayerDescriptor>";
if(System.overlays[System.si]){
map.removeLayer(System.overlays[System.si]);
}
System.overlays[System.si]=new OpenLayers.Layer.WMS(
"Select"+System.si,
((System.si=="in")?System.inMap:System.outMap),
{
format: "image/png",
layers: "Result",
styles: "default",
sld_body: sld
},
{useCanvas: System.useCanvas,isBaseLayer: false}
);
System.overlays[System.si].setVisibility(true);
System.overlays[System.si].setOpacity(0.3);
map.addLayer(System.overlays[System.si]);
map.setLayerIndex(System.overlays[System.si],map.layers.length-1);
var params=[{"name": "InputEntity1", "xlink:href": ((System.si=="in")?System.inMap:System.outMap)+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result","mimeType": "text/xml"}];
params.push();
if(System.allOverlays){
var tmp=params[0]["xlink:href"];
params=[{"name": "InputEntity1", "xlink:href": System.allOverlays+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result","mimeType": "text/xml"}];
params.push({"name": "InputEntity2", "xlink:href": tmp,"mimeType": "text/xml"});
}
req=WPSGetHeader("vector-tools.Append")+WPSGetInputs(params)+WPSGetOutput({"name": "Result","form":"ResponseDocument","mimeType": "image/png","asReference":"true"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: req,
complete: function(xml,status) {
System.allOverlays=WPSParseReference(xml);
}
});
//alert(System.mapUrl+"\?map=");
//alert(System.inMap);
}
});
}
});
}
<|start_filename|>mapmint-services/symbol-tools-src/Makefile<|end_filename|>
MACOS_CPP=-arch x86_64
PREFIX=/usr/local
ZOO_FILE=/home/src/zoo/zoo-project/zoo-kernel/service_internal.o
ZOO_DIR=/home/src/zoo/zoo-project/zoo-kernel
FT_LDFLAGS=-lfreetype
FT_CFLAGS=-I/usr/include/freetype2 -I/usr/include/libpng16
ZRPATH=/home/src/zoo/zoo-project/zoo-kernel/../
include ${ZOO_DIR}/ZOOMakefile.opts
CPPFLAGS := -DZOO_SERVICE -DUSE_KML -I${ZOO_DIR}
BIN_LIST = cgi-env/service.zo
default : $(BIN_LIST)
cgi-env/service.zo: service.c
g++ ${ZOO_CFLAGS} ${FT_CFLAGS} ${CPPFLAGS} -shared -fpic $< ${MACOS_LD_NET_FLAGS} ${FT_LDFLAGS} -lc -L${INST_LIB} -lzoo_service ${GDAL_LIBS} ${MACOS_LD_FLAGS} ${MACOS_LD_NET_FLAGS} ${ZOO_LDFLAGS} -lcrypto -o $@
install:
install -d ${PREFIX}/symbol-tools/
install $(BIN_LIST) ${PREFIX}/symbol-tools/
install cgi-env/*.zcfg ${PREFIX}/symbol-tools/
install cgi-env/*.py ${PREFIX}/symbol-tools/
install cgi-env/*.js ${PREFIX}/symbol-tools/
cd ${PREFIX}/symbol-tools/ && ln -s ../main.cfg
cd ${PREFIX}/symbol-tools/ && ln -s ../ZOO-api.js
cd ${PREFIX}/symbol-tools/ && ln -s ../ZOO-proj4js.js
clean :
rm -f cgi-env/*zo
<|start_filename|>public_map/assets/js/init.js<|end_filename|>
// Filename: app.js
/*
This work was supported by a grant from the European Union's 7th Framework Programme (2007-2013)
provided for the project PublicaMundi (GA no. 609608).
*/
define([
'module', 'jquery', 'zoo', 'xml2json', 'ol', 'mmDataTables'
], function(module, $, Zoo, X2JS,ol,MMDataTable) {
(function(){
var methods = ['addClass', 'removeClass'];
$.each(methods, function (index, method) {
var originalMethod = $.fn[method];
$.fn[method] = function () {
var oldClass = this.className;
var result = originalMethod.apply(this, arguments);
var newClass = this.className;
this.trigger(method, [oldClass, newClass]);
return result;
};
});
})();
var zoo = new Zoo({
url: zooUrl,
delay: module.config().delay,
});
var map,pmap;
var gmap;
var mmview;
var accuracyFeature,positionFeature;
var mapInteractions={};
var drawSource;
var geolocation;
var selectLayer,printLayer;
var mymodal = $('#myModal');
var mynotify = $('.top-right');
var wgs84Sphere = new ol.Sphere(6378137);
function notify(text, type) {
mynotify.notify({
message: { text: text },
type: type,
}).show();
}
function setTreeHeight(){
console.log("************ Tree view height !!!!!!");
console.log($(window).height()- $('.navbar-header').height() - (2*$('.nav-tabs').height()) - $('#mmcdts').height() - 30);
var theight= $(window).height() - ((3*$('.navbar-header').height()) + $('#mmcdts').height() + 30);
$('.baselayers,.tree-container,.info-container,.sources-container').height(theight);
}
function setMapHeight(){
var mpheight= $(window).height() - $('.navbar-header').height();
$('#map').height(mpheight);
}
$(window).resize(function() {
setMapHeight();
setTreeHeight();
map.updateSize();
});
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
var myBaseLayersUrls=[];
var myBaseLayerNames=[];
function updateBSImages(){
mmZoom=map.getView().getZoom();
mmCenter=ol.proj.transform(map.getView().getCenter(),"EPSG:3857","EPSG:4326");
var layers=map.getLayers();
for(var l=0;l<myBaseLayers.length;l++){
try{
loadBaseLayerIcon(myBaseLayerNames[l],layers.item(l));
}catch(e){
try{
loadBaseLayerIcon(myBaseLayerNames[l],layers.item(l).getLayers().item(1));
}catch(e){
console.log("Unable to display baselayer background image see http://mapmint.com/faq/BaseLayerDisplay");
}
}
}
}
function loadBaseLayerIcon(key,layer){
var obj=layer.getSource().getTileGrid().getTileCoordForCoordAndZ(ol.proj.transform(mmCenter,"EPSG:4326","EPSG:3857"),mmZoom);
var tmp=layer.getSource().getTileUrlFunction()(obj,1.325,ol.proj.get("EPSG:3857"));
var res=tmp.split('\n')[0];
if(myBaseLayerNames.indexOf(key)<0)
myBaseLayerNames.push(key);
$("#base_layer_"+key+"_img").attr("src",res);
return res;
}
var initBaseLayers = function(){
if(baseLayers["osm"]==1){
var osm = new ol.layer.Tile({
source: new ol.source.OSM(),
visible: baseLayers["default"]==myBaseLayers.length?true:false,
name: 'osm'
});
myBaseLayers.push(osm);
url=loadBaseLayerIcon("OSM",osm);
console.log("OK 0");
console.log(url);
}
if(baseLayers["mq"].length>=1){
for(i in baseLayers["mq"]){
var osm;
console.log(baseLayers["mq"][i]);
if(baseLayers["mq"][i]!='hyb'){
osm=new ol.layer.Tile({
visible: baseLayers["default"]==myBaseLayers.length?true:false,
source: new ol.source.MapQuest({layer: baseLayers["mq"][i]})
});
url=loadBaseLayerIcon(baseLayers["mq"][i],osm);
console.log("OK 0");
console.log(url);
}
else{
osm=new ol.layer.Group({
visible: baseLayers["default"]==myBaseLayers.length?true:false,
layers: [
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
}),
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'hyb'})
})
]
});
console.log("OK 1");
url=loadBaseLayerIcon(baseLayers["mq"][i],osm.getLayers().item(1));
console.log("OK 0");
console.log(url);
}
myBaseLayers.push(osm);
}
}
if(baseLayers["proprietary"]["type"]!="Google"){
if(baseLayers["proprietary"]["layers"] && baseLayers["proprietary"]["layers"].length>=1){
var resolutions = [];
var matrixIds = [];
var proj3857 = ol.proj.get('EPSG:3857');
var maxResolution = ol.extent.getWidth(proj3857.getExtent()) / 256;
for (var i = 0; i < 18; i++) {
matrixIds[i] = i.toString();
resolutions[i] = maxResolution / Math.pow(2, i);
}
var tileGrid = new ol.tilegrid.WMTS({
origin: [-20037508, 20037508],
resolutions: resolutions,
matrixIds: matrixIds
});
var layer;
for(i in baseLayers["proprietary"]["layers"]){
if(baseLayers["proprietary"]["type"]!="IGN"){
var attributions = {
"ESRI": new ol.Attribution({
html: 'Tiles © <a href="http://services.arcgisonline.com/ArcGIS/' +
'rest/services/'+
baseLayers["proprietary"]["layers"][i]+
'/MapServer">ArcGIS</a>'
}),
"MapBox": new ol.Attribution({
html: '<a href="http://mapbox.com/about/maps">Terms & Feedback</a>'
})
};
var urls= {
"ESRI": 'http://server.arcgisonline.com/ArcGIS/rest/services/' +
baseLayers["proprietary"]["layers"][i]+
'/MapServer/tile/{z}/{y}/{x}',
"MapBox": "https://api.mapbox.com/v4/" +
baseLayers["proprietary"]["layers"][i] +
"/{z}/{x}/{y}.png?access_token="+
baseLayers["proprietary"]["key"]
};
layer=(baseLayers["proprietary"]["type"]!="Bing"?
new ol.layer.Tile({
visible: baseLayers["default"]==myBaseLayers.length?true:false,
source: new ol.source.XYZ({
attributions: [attributions[baseLayers["proprietary"]["type"]]],
url: urls[baseLayers["proprietary"]["type"]]
})
}):
new ol.layer.Tile({
visible: false,
preload: Infinity,
source: new ol.source.BingMaps({
key: baseLayers["proprietary"]["key"],
imagerySet: baseLayers["proprietary"]["layers"][i],
// use maxZoom 19 to see stretched tiles instead of the BingMaps
// "no photos at this zoom level" tiles
maxZoom: 19
})
})
);
}
else{
var ign_source = new ol.source.WMTS({
url: 'http://wxs.ign.fr/' + baseLayers["proprietary"]["key"] + '/wmts',
layer: baseLayers["proprietary"]["layers"][i],
matrixSet: 'PM',
format: 'image/jpeg',
projection: 'EPSG:3857',
tileGrid: tileGrid,
style: 'normal',
attributions: [new ol.Attribution({
html: '<a href="http://www.geoportail.fr/" target="_blank">' +
'<img src="http://api.ign.fr/geoportail/api/js/latest/' +
'theme/geoportal/img/logo_gp.gif"></a>'
})]
});
layer = new ol.layer.Tile({
visible: baseLayers["default"]==myBaseLayers.length?true:false,
source: ign_source
});
}
url=loadBaseLayerIcon(baseLayers["proprietary"]["layers"][i].replace(/\./g,"_"),layer);
console.log("OK 0");
console.log(url);
myBaseLayers.push(layer);
//url=loadBaseLayerIcon(baseLayers["mq"][i],osm.getLayers().item(1));
}
}
}
if(baseLayers["proprietary"]["type"]=="Google"){
var gMapDiv = document.getElementById('gmap');
gMapDiv.style.height=olMapDiv.style.height;
gMapDiv.style.width=olMapDiv.style.width;
gmap = new google.maps.Map(document.getElementById('gmap'), {
disableDefaultUI: true,
keyboardShortcuts: false,
draggable: false,
disableDoubleClickZoom: true,
scrollwheel: false,
streetViewControl: false
});
mmview = new ol.View({
// make sure the view doesn't go beyond the 22 zoom levels of Google Maps
maxZoom: 21
});
mmview.on('change:center', function() {
var center = ol.proj.transform(mmview.getCenter(), 'EPSG:3857', 'EPSG:4326');
gmap.setCenter(new google.maps.LatLng(center[1], center[0]));
});
mmview.on('change:resolution', function() {
gmap.setZoom(mmview.getZoom());
});
}
};
var finalizeBaseLayers=function(){
if(baseLayers["proprietary"]["type"]=="Google"){
map.setView(mmview);
mmview.setCenter([0, 0]);
mmview.setZoom(1);
olMapDiv.parentNode.removeChild(olMapDiv);
//gmap.setMapTypeId(google.maps.MapTypeId.TERRAIN);
gmap.controls[google.maps.ControlPosition.TOP_LEFT].push(olMapDiv);
}
}
var myBaseLayers=[];
var myToolsLayers=[];
var olMapDiv;
var initialize = function() {
console.log('START !');
$('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
$.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
} );
enquire.register("screen and (max-width:980px)", {
setup : function() {
setMapHeight();
setTreeHeight();
},
match : function() {
$('#mmtabs').prepend('<li id="mapwrap" class="active" role="map" data-toggle="tooltip" data-placement="bottom" title="Map"><a href="#mapcontainer" aria-controls="settings" role="tab" data-toggle="tab"><i class="i i-map"></i></a></li>');
$('.tab-content').prepend('<div role="tabpanel" class="tab-pane" id="mapcontainer"></div>');
$('.nav-tabs li:eq(2) a').tab('show');
$('.nav-tabs li:eq(0) a').tab('show');
$('#main-wrapper').children().each(function(){
$(this).detach().appendTo('#mapcontainer');
});
$('#map').css("position","relative");
var mnheight= $(window).height() - $('.navbar-header').height() - $('.nav-tabs').height() - $('#mmcdts').height() - 4;
$('#map').height(mnheight);
setTreeHeight();
},
unmatch : function() {
$('#mapcontainer').children().each(function(){
$(this).detach().appendTo('#main-wrapper');
});
$('#mapwrap, #mapcontainer').remove();
//$('#map').height(mpheight);
$('#map').css("width","100%");
$('#map').css({'position':'relative','top' : '0'});
setMapHeight();
map.updateSize();
$('.nav-tabs li:eq(0) a').tab('show');
setTreeHeight();
}
});
$(".cm").contextmenu({
target: "#context-menu"
});
authenticateSetup();
//$("[rel='dropdown']").dropdown("toggle");
$('.selectpicker').selectpicker();
$('.dropdown-menu button').on({
"click":function(e){
e.stopPropagation();
console.log(e);
return false;
}
});
$('.dropdown-menu .dropdown-toggle').on({
"click":function(e){
e.stopPropagation();
console.log(e);
try{
console.log($(this).parent().data('open'));
//$(this).parent().dropdown("toggle");
//$("[rel='dropdown']").dropdown("toggle");
$(this).parent().find(".dropdown-menu").each(function(){
if($(this).hasClass('inner')){
$(this).addClass('show');
$(this).find("a").each(function(){
$(this).on('click',function(e){
//e.stopPropagation();
$(this).parent().parent().parent().parent().removeClass('open');
});
});
}
else
$(this).removeClass('open');
});
$(this).parent().toggleClass('open');
if($(this).parent().data('open')) {
$(this).parent().data('open', false);
} else
$(this).parent().data('open', true);
console.log($(this).parent().data('open'));
}catch(e){
console.log(e);
}
}
});
$('.cm').bind("contextmenu",function(e){
//alert('Context Menu event has fired!');
$(".tree li").find(".active").toggleClass("active");
$(this).toggleClass("active");
console.log($(this).attr("id"));
var cid=eval($(this).attr("id").replace(/layer_/,""));
clayer=getLayerById(cid);
console.log(oLayers[clayer]["query"]);
for(i in {"export":0,"query":0}){
if(!oLayers[clayer][i])
$("#mmm_"+i).parent().addClass("hidden");
else
$("#mmm_"+i).parent().removeClass("hidden");
}
$("#mmm_opacity").val(oLayers[clayer]["opacity"]*100);
$("#mmm_range").val(Math.round(oLayers[clayer]["opacity"]*100).toFixed(0)+"%");
$('body, #context-menu > ul > li > a').on('click', function (e) {$(".tree li").find(".active").removeClass('active');});
return false;
});
$( ".tp, .op" ).click(function() {
$( "#sidebar-wrapper").toggle();
$( ".op").toggle();
$('#map').css("position","relative");
$("#main-wrapper").toggleClass("fw");
$(".ol-zoomslider").toggleClass("ol-zsm");
$(".ol-zoom-extent").toggleClass("ol-zmm");
$(".ol-zoom").toggleClass("ol-zzm");
map.updateSize();
});
var transformer = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
original_extent=ol.extent.applyTransform(original_extent, transformer);
var controls = [
new ol.control.Attribution(),
new ol.control.Rotate({autoHide: true}),
new ol.control.Zoom(),
];
/*new ol.control.MousePosition({
undefinedHTML: 'outside',
projection: 'EPSG:4326',
coordinateFormat: function(coordinate) {
return ol.coordinate.format(coordinate, '{x}, {y}', 4);
}
}),
new ol.control.OverviewMap(),
new ol.control.ScaleLine(),
new ol.control.ZoomSlider(),
new ol.control.ZoomToExtent({"label":"E","extent":original_extent})/*,
new ol.control.FullScreen()
];*/
var optionals={
"zoomtomaxextent": new ol.control.ZoomToExtent({"label":"E","extent":original_extent}),
"MousePosition": new ol.control.MousePosition({
undefinedHTML: 'outside',
projection: 'EPSG:4326',
coordinateFormat: function(coordinate) {
return ol.coordinate.format(coordinate, '{x}, {y}', 4);
}
}),
"ScaleBar": new ol.control.ScaleLine(),
"MMOVMap": new ol.control.OverviewMap(),
/*"MMOVMapFixed":{
"active":-1,
"index":-1
},*/
"MMPanZoom": new ol.control.ZoomSlider()
};
for(j in optionals){
for(i in mmToolNames){
if(mmToolNames[i]==j){
console.log("PUSH CONTROL: "+j)
controls.push(optionals[j]);
break;
}
}
}
/*for(j in optionals){
for(i in mmToolNames){
if(mmToolNames[i]==j){
controls.push(optionals[j]["control"]);
break;
}
}
}*/
var myWMSLayers;
olMapDiv = document.getElementById('map');
initBaseLayers();
map = new ol.Map({
target: olMapDiv,
controls: controls,
layers: myBaseLayers,
interactions: ol.interaction.defaults({
altShiftDragRotate: true,
dragPan: false,
rotate: true
}).extend([new ol.interaction.DragPan({kinetic: null})]),//ol.interaction.defaults({shiftDragZoom: false}) ,
view: new ol.View({
extent: original_extent,
center: [0, 0],
zoom: 2
})
});
map.getView().fit(original_extent,map.getSize());
geolocation = new ol.Geolocation({
projection: map.getView().getProjection()
});
accuracyFeature = new ol.Feature();
geolocation.on('change:accuracyGeometry', function() {
accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
map.getView().fit(accuracyFeature.getGeometry().getExtent(),map.getSize());
});
var noTracking=true;
positionFeature = new ol.Feature();
positionFeature.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#3399CC'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
}));
geolocation.on('change:position', function() {
var accuracy = geolocation.getAccuracy();
var heading = geolocation.getHeading() || 0;
var speed = geolocation.getSpeed() || 0;
var m = Date.now();
var coordinates = geolocation.getPosition();
positionFeature.setGeometry(coordinates ?
new ol.geom.Point(coordinates) : null);
if(noTracking){
geolocation.setTracking(false);
}
});
layers=[];
var styles=[];
var vectors=[];
var cnt=0;
for(layerName in oLayers){
console.log(layerName);
console.log(oLayers[layerName]);
if(oLayers[layerName].display=="raster"){
var layer=new ol.layer.Tile({
visible: oLayers[layerName]["activated"],
source: new ol.source.TileWMS({
url: msUrl+"?map="+pmapfile,
params: {'LAYERS': layerName, 'TILED': true},
serverType: 'mapserver'
})
});
layers.push(layer);
map.addLayer(layer);
}else{
console.log(oLayers[layerName].display);
console.log(pubUrl);
console.log(lastMap);
var d=new Date();
map.addLayer(layerVector = new ol.layer.Vector());
console.log("/styles/"+layerName+"_"+(oLayers[layerName].filter?System.iniFilterValue+"_":"")+lastMap+"_sld.xml?timestamp="+d.getTime());
$.ajax({
type: "GET",
localID: layerName,
url: pubUrl+"/styles/"+layerName+"_"+(oLayers[layerName].filter?System.iniFilterValue+"_":"")+lastMap+"_sld.xml",
complete: function(xml,status){
var style;
console.log(this.localID);
console.log(oLayers[this.localID]);
console.log(this.localID);
if(xml.responseText!=""){
var _x2js = new X2JS();
var obj=_x2js.xml_str2json( xml.responseText );
console.log(obj);
if(oLayers[this.localID].dataType=="point"){
try{
var tmp1=obj["StyledLayerDescriptor"]["NamedLayer"]["UserStyle"]["FeatureTypeStyle"]["Rule"];
console.log(tmp1);
if(tmp1.length){
var pointsStyles=[];
var pointsConditions=[];
for(var j=0;j<tmp1.length;j++){
console.log(tmp1[j]);
pointsConditions.push(tmp1[j]["Filter"]);
var tmp0=tmp1[j]["PointSymbolizer"];
var options={};
options["radius"]=tmp0["Graphic"]["Size"].toString();
if(tmp0["Graphic"]["Mark"]["Fill"])
options["fill"]=new ol.style.Fill({
color: tmp0["Graphic"]["Mark"]["Fill"]["CssParameter"].toString(),
opacity: 0.6
});
if(tmp0["Graphic"]["Mark"]["Stroke"])
options["stroke"]=new ol.style.Fill({
color: tmp0["Graphic"]["Mark"]["Stroke"]["CssParameter"].toString(),
width: 1,
opacity: 0.6
});
pointsStyles.push(new ol.style.Style({
image: new ol.style.Circle(options)
}));
}
style=(function(feature, resolution){
for(var k=0;k<pointsConditions.length;k++){
if(pointsConditions[k]["PropertyIsEqualTo"]){
var filter=pointsConditions[k]["PropertyIsEqualTo"];
if(
feature.get(filter["PropertyName"].toString())==
filter["Literal"].toString()
){
return [pointsStyles[k]];
}
}
}
return [pointsStyles[0]];
});
console.log(pointsConditions);
console.log(pointsStyles);
}else{
console.log(obj["StyledLayerDescriptor"]["NamedLayer"]["UserStyle"]["FeatureTypeStyle"]["Rule"]["PointSymbolizer"]);
var tmp0=obj["StyledLayerDescriptor"]["NamedLayer"]["UserStyle"]["FeatureTypeStyle"]["Rule"]["PointSymbolizer"];
console.log(tmp0["Graphic"]["Mark"]["WellKnownName"]);
if(tmp0["Graphic"]["Mark"]["WellKnownName"]=="square"){
console.log(tmp0["Graphic"]["Mark"]["WellKnownName"]);
style=new ol.style.Style({
image: new ol.style.Circle({
radius: eval(tmp0["Graphic"]["Size"].toString()+"*10"),
fill: new ol.style.Fill({
color: tmp0["Graphic"]["Mark"]["Fill"]["CssParameter"].toString(),
opacity: 0.6
}),
stroke: new ol.style.Stroke({
color: tmp0["Graphic"]["Mark"]["Stroke"]["CssParameter"].toString(),
opacity: 0.4
})
})});
}
}
styles.push(style);
}catch(e){
console.log(e);
}
}
}
var sourceVector;
loadFeatures = function(response) {
formatWFS = new ol.format.WFS(),
sourceVector.addFeatures(formatWFS.readFeatures(response,{
dataProjection: ol.proj.get('EPSG:4326'),
featureProjection: ol.proj.get('EPSG:3857')
}));
};
sourceVector = new ol.source.Vector({
});
if(styles[cnt]!=null)
layerVector = new ol.layer.Vector({
visible: true,
style: style,
source: sourceVector
});
else
layerVector = new ol.layer.Vector({
visible: true,
source: sourceVector
});
cnt++;
console.log(this.localID);
$.ajax(msUrl+"?map="+pmapfile,{
type: 'GET',
data: {
service: 'WFS',
version: '1.1.0',
request: 'GetFeature',
typename: this.localID,
srsName: 'EPSG:4326'/*,
bbox: extent.join(',') + ',EPSG:3857'*/
},
}).done(loadFeatures);
layerVector.set("name",this.localID);
//map.addLayer(layerVector);
var col=map.getLayers();
var j=0;
for(i in oLayers){
if(i==this.localID)
break;
j++;
}
col.removeAt(j+myBaseLayers.length);
col.insertAt(j+myBaseLayers.length,layerVector);
if(j+myBaseLayers.length!=col.getLength()){
console.log(j+myBaseLayers.length);
console.log(col.getLength());
}
}
});
}
}
$("#mm_bs_display").on("addClass",function(){
updateBSImages();
});
finalizeBaseLayers();
var featuresOverlay = new ol.layer.Vector({
map: map,
source: new ol.source.Vector({
features: [accuracyFeature, positionFeature]
})
});
myToolsLayers.push(featuresOverlay);
$('input[type="checkbox"]').each(function(){
console.log($(this).parent());
$(this).change(function(){
//console.log($(this));
if($(this).parent()[0]["id"].replace(/layer_/g,"")){
console.log($(this).parent()[0]["id"].replace(/layer_/g,""));
//console.log(map.getLayers());
console.log($(this).is(":checked"));
var tmp=eval($(this).parent()[0]["id"].replace(/layer_/g,"")+"+myBaseLayers.length");
console.log(tmp);
map.getLayers().item(eval($(this).parent()[0]["id"].replace(/layer_/g,"")+'+myBaseLayers.length')).setVisible($(this).is(":checked"));
}
else{
$(this).parent().find(".cm").each(function(){
console.log(myBaseLayers.length);
console.log($(this)[0]["id"]);
var tmp=eval($(this)[0]["id"].replace(/layer_/g,"")+'+myBaseLayers.length');
console.log(tmp);
console.log($(this).find("input").is(":checked"));
map.getLayers().item(tmp).setVisible(($(this).find("input").is(":checked")));
console.log($(this)[0]["id"]);
});
}
});
});
$(".base_layer").on('click',function(e){
$(this).parent().parent().find(".active").removeClass("active");
var tmpId=eval($(this).parent().attr("id").replace(/bl_/g,""));
for(var i=0;i<myBaseLayers.length;i++)
if(i!=tmpId)
map.getLayers().item(i).setVisible(false);
var tmp=$(this).attr("id").replace(/base_layer_/g,"").replace(/_/g,".");
console.log(tmp);
var tmp0=tmp.split('.');
console.log(tmp0);
if(tmp0.length>1 && tmp0[0]=="google")
gmap.setMapTypeId(eval(tmp));
else{
map.getLayers().item(tmpId).setVisible(true);
}
$(this).parent().addClass("active");
});
/*var bid=0;
$(".base_layer").each(function(){
var lbid=bid;
$(this).click(function(){
console.log($(this));
$(this).parent().parent().find(".active").removeClass("active");
var tmpId=eval($(this).parent().attr("id").replace(/bl_/g,""));
for(var i=0;i<myBaseLayers.length;i++)
if(i!=tmpId)
map.getLayers().item(i).setVisible(false);
var tmp=$(this).children()[0]["id"].replace(/base_layer_/g,"").replace(/_/g,".");
var tmp0=tmp.split('.');
if(tmp0.length>1 && tmp0[0]=="google")
gmap.setMapTypeId(eval($(this).children()[0]["id"].replace(/base_layer_/g,"").replace(/_/g,".")));
else{
map.getLayers().item(tmpId).setVisible(true);
}
$(this).addClass("active");
});
bid++;
});*/
var popup = new ol.Overlay.Popup();
map.addOverlay(popup);
map.on('click', function (evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,function (feature, layer) {
if(layer)
feature.set("layerName",layer.get("name"));
return feature;
});
if (feature && feature.get("layerName")) {
var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();
popup.setPosition(coord);
if(oLayers[feature.get("layerName")]["dataType"]=="point"){
System.onPrintlTemplate=function(feature,html){
//var coords = ol.coordinate.toStringXY(ol.proj.transform(coord, 'EPSG:3857', 'EPSG:4326'),2);
popup.show(evt.coordinate, '<div>' + html
+'</div>');
}
tryRun(feature);
}else{
var wmsSource = new ol.source.TileWMS({
url: msUrl+"?map="+oLayers[feature.get("layerName")]["search"],
params: {'LAYERS': feature.get("layerName")},
serverType: 'mapserver',
crossOrigin: ''
});
var url = wmsSource.getGetFeatureInfoUrl(
evt.coordinate, map.getView().getResolution(), 'EPSG:3857',
{'INFO_FORMAT': 'text/html'});
$.ajax({
type: "GET",
url: url
}).done(function(res){
//console.log(res);
//var coords = ol.coordinate.toStringXY(ol.proj.transform(coord, 'EPSG:3857', 'EPSG:4326'),2);
popup.show(evt.coordinate, '<div>' + res
+'</div>');
});
console.log(url);
}
} else {
popup.hide();
}
});
mapInteractions["default"]=new ol.interaction.Select({
style: function(feature, resolution) {
//console.log(feature.getStyle());
return [new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
fill: new ol.style.Fill({
color: '#FF0000'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 5
}),
text: new ol.style.Text({
//text: feature.get('name'),
font: '15px Verdana,sans-serif',
fill: '#FFFFFFF',
stroke:'#333333',
offsetY: 25
})
}),
condition: function(e) {
return e.originalEvent.type=='mousemove';
}
})];
}
});
map.addInteraction(mapInteractions["default"]);
mapInteractions["zoomin"] = new ol.interaction.DragZoom({condition: ol.events.condition.always});
drawSource = new ol.source.Vector();
var vector = new ol.layer.Vector({
source: drawSource,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
map.addLayer(vector);
selectLayer = new ol.layer.Vector({
visible: true,
source: new ol.source.Vector({})
});
map.addLayer(selectLayer);
myToolsLayers.push(selectLayer);
myMMDataTableObject = new MMDataTable({"selectLayer": selectLayer, "zook": zoo});
loadContextualMenu();
load_menu();
$('[data-toggle="remove"]').on('click',function(e){
console.log("data-toggle");
console.log("* DEBUG DJAY !!!!!!!");
console.log("* DEBUG DJAY !!!!!!!");
//console.log($("#mmm_table-wrapper-container").find(".active").get("id"));
$("#mmm_table-wrapper-container").find(".active").remove();
$("#mmm_table-wrapper-header").find(".active").remove();
if($("#mmm_table-wrapper-header").find("li a").length>1)
$($("#mmm_table-wrapper-header").find("li a")[1]).tab('show');
else
$("#table-wrapper").collapse("hide");
e.preventDefault();
});
$("[data-toggle=zoomToElement]").on('click',function(){
console.log(map.getSize());
var size=map.getSize();
//size[1]/=2;
map.getView().fit(selectLayer.getSource().getExtent(),map.getSize());
});
}
var myMMDataTableObject;
var tableDisplay=0;
var contextualMenu={
"zoomTo": {
"run": function(layer){
var key=getLayerById(layer);
var transformer = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
var extent=ol.extent.applyTransform(oLayers[key]["extent"], transformer);
map.getView().fit(extent,map.getSize());
}
},
"query": {
"run": function(layer){
var key=getLayerById(layer);
console.log(oLayers[key]);
if(oLayers[key]["dataType"]=="raster"){
zoo.execute({
"identifier": "mapfile.getInitialInfo",
"type": "POST",
dataInputs: [
{"identifier":"map","value":lastMap,"dataType":"string"},
{"identifier":"layer","value":key,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log("SUCCESS");
console.log(data);
var layer=key;
var Bands=[];
if(data["datasource"]["Band"].length){
for(i in data["datasource"]["Band"])
Bands.push({
name: "Band "+i,
data: data["datasource"]["Band"]["histogram"].split(",")
});
}
else
Bands.push({
name: "Band 1",
data: data["datasource"]["Band"]["histogram"].split(",")
});
for(i in Bands)
for(j in Bands[i]["data"])
Bands[i]["data"][j]=parseFloat(Bands[i]["data"][j]);
for(var i in {"container":0,"header":0})
$("#mmm_table-wrapper-"+i).find(".active").each(function(){
$(this).removeClass("active");
});
$("#mmm_table-wrapper-container").append('<div class="output-profile tab-pane active" id="output-histogram-'+key+'" style="height: '+($(window).height()/3)+'px;"></div>');
if(!$('#mmm_table-content-display_'+layer).length){
$("#mmm_table-wrapper-header").append('<li role="presentation" class="active"><a id="mmm_table-content-display_'+key+'" title="'+oLayers[key]["alias"]+'" data-toggle="tab" data-target="#output-histogram-'+key+'" href="#output-histogram-'+layer+'"><i class="fa fa-area-chart"></i><b class="ncaret"> </b><span class="hidden-xs hidden-sm">'+oLayers[key]["alias"]+'</span> </a> </li>');
}else
$('#output-histogram-'+key).remove();
if(!$("#table-wrapper").hasClass("in"))
$("#table-wrapper").collapse("show");
$('#mmm_table-content-display_'+key).tab("show");
var chart = new Highcharts.Chart({
chart: {
zoomType: 'x',
renderTo: 'output-histogram-'+key
},
title: {
text: "Raster Histogram"
},
xAxis: {
labels: {
formatter: function(){
var tmp=this.value+"";
return tmp;
}
},
title: { text: 'Points' },
maxZoom: 0
},
yAxis: {
//max: mmax*2,
title: { text: null },
startOnTick: false,
showFirstLabel: false
},
legend: {
enabled: false
},
plotOptions: {
area: {
cursor: 'pointer',
fillColor: {
linearGradient: [0, 0, 0, 300],
stops: [
[0, '#74B042'],
[1, 'rgba(255,255,255,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 3
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
tooltip: {
formatter: function() {
return '<h1>'+this.x+': '+Highcharts.numberFormat(this.y, 0)+"</h1>";
}
},
series: Bands
});
},
error: function(data){
console.log("ERROR");
console.log(data);
}
});
}
else
myMMDataTableObject.display(key,{
url: msUrl,
data: {
"map":oLayers[key]["map"],
version: "1.0.0",
service: "WFS",
request: 'GetFeature',
typename: key
}
});
}
},
"export": {
"run": function(layer){
var key=getLayerById(layer);
zoo.execute({
identifier: "vector-converter.exportTo",
type: "GET",
dataInputs: [
{"identifier":"map","value":lastMap,"dataType":"string"},
{"identifier":"layer","value":layer,"dataType":"string"},
{"identifier":"format","value":$("#sGSelectedFormat").val(),"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log("SUCCESS");
console.log(data);
window.open(data,"_blank");
},
error: function(data){
console.log("ERROR");
console.log(data);
}
});
/*$.ajax({
type: "GET",
dataType: "html",
url: zooUrl+"?request=Execute&service=WPS&version=1.0.0&Identifier=vector-converter.exportTo"+"&DataInputs=map="+lastMap+";layer="+layer+";format="+$("#sGSelectedFormat").val()+"&RawDataOutput=Result",
success: function(xml){
window.open();
$("#export_dl_link").attr("href",xml);
$("#export_dl_link").show();
$('#routingDownloadContainer').attr('href',xml);
}
});*/
}
}
};
function loadContextualMenu(){
$("#mmm_opacity").on("change",function(){
var cLayer=$(".tree li").find(".active");
var cid=eval("myBaseLayers.length+"+cLayer.attr("id").replace(/layer_/,""));
var clayer=getLayerById(eval(cLayer.attr("id").replace(/layer_/,"")));
oLayers[clayer]["opacity"]=$(this).val()/100;
map.getLayers().item(cid).setOpacity($(this).val()/100);
});
$.ajax(msUrl+'?map='+pmapfile+"&service=WMS&request=GetCapabilities").then(function(response) {
var parser = new ol.format.WMSCapabilities();
var result = parser.read(response);
console.log(result);
myWMSLayers=result;
console.log(myWMSLayers);
var j=0;
for(var i in pmapfiles){
var ext=myWMSLayers["Capability"]["Layer"]["Layer"][j]["BoundingBox"][0]["extent"];
oLayers[i]["extent"]=[
ext[1],
ext[0],
ext[3],
ext[2]
];
j++;
}
});
$(".mm-menu").each(function(){
console.log($(this));
$(this).on('click',function(){
var cLayer=$(".tree li").find(".active");
contextualMenu[$(this).attr("id").replace(/mmm_/,"")]["run"](cLayer.attr("id").replace(/layer_/,""));
});
});
}
var oldItem;
function load_menu(){
$("#header").find(".mm-action").each(function(){
$(this).on('click',function(){
oldItem=$(this).parent().parent().find(".active").attr('id');
for(var i in menuItems){
menuItems[i]["deactivate"]();
if(!$(this).hasClass("do-not-select")){
$("#"+i).parent().removeClass("active");
}
}
//oldItem=$(this).attr('id');
if(!$(this).hasClass("do-not-select")){
$(this).parent().addClass("active");
}
menuItems[$(this).attr('id')]["activate"]();
});
});
}
/**
* Currently drawn feature.
* @type {ol.Feature}
*/
var sketch;
/**
* The help tooltip element.
* @type {Element}
*/
var helpTooltipElement;
/**
* Overlay to show the help messages.
* @type {ol.Overlay}
*/
var helpTooltip;
/**
* The measure tooltip element.
* @type {Element}
*/
var measureTooltipElement;
/**
* Overlay to show the measurement.
* @type {ol.Overlay}
*/
var measureTooltip;
/**
* Message to show when the user is drawing a polygon.
* @type {string}
*/
var continuePolygonMsg = 'Click to continue drawing the polygon';
/**
* Message to show when the user is drawing a line.
* @type {string}
*/
var continueLineMsg = 'Click to continue drawing the line';
function mmActivateDrawTool(args){
var isActive=true;
var toolName=args.name;
if(!mapInteractions[args.name]){
mapInteractions[args.name] = new ol.interaction.Draw({
source: (args.source?args.source:drawSource),
type: (args.type?args.type:'Circle'),
style: (args.style?args.style:new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 0.5)',
lineDash: [10, 10],
width: 2
}),
image: new ol.style.Circle({
radius: 5,
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 0.7)'
}),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
})
})
}))
});
isActive=false;
}
desactivateInteractions();
map.addInteraction(mapInteractions[args.name]);
if(!isActive){
mapInteractions[args.name].on('drawstart',(args.startHandler?args.startHandler:function(evt) {
if(drawSource.getFeatures().length>0){
drawSource.removeFeature(drawSource.getFeatures()[0]);
}
// set sketch
sketch = evt.feature;
}));
mapInteractions[args.name].on('drawend', args.endHandler);
}
}
var urlContext;
function saveContext(func){
console.log("SAVE CONTEXT START");
var ext=ol.proj.transformExtent(map.getView().calculateExtent(map.getSize()),'EPSG:3857','EPSG:4326');
console.log(ext);
var params=[{"identifier":"extent", value: ext, dataType: "string"}];
var layers=map.getLayers();
console.log(map.getLayers());
for(var i=0;i<layers.getLength();i++){
console.log(i+" "+myBaseLayers.length+" "+oLayers.length);
console.log(layers.item(i).getVisible());
if(i>myBaseLayers.length &&
getLayerById(i-myBaseLayers.length) &&
layers.item(i).getVisible()){
console.log(layers.item(i).getVisible());
params.push({identifier: "layers",value:getLayerById(i-myBaseLayers.length),dataType: "string"});
}
}
console.log(params);
(function(func){
zoo.execute({
identifier: "context.saveContext",
dataInputs: params,
dataOutputs: [
{"identifier":"Result","type":"raw"}
],
type: 'POST',
storeExecuteResponse: false,
success: function(data){
console.log("SUCCESS");
console.log(data);
func(data);
},
error: function(data){
console.log("ERROR");
console.log(data);
}
})})(func);
}
var popupWindow;
function loadSharingWindow(){
var hauteur=(arguments.length>2?arguments[2]:480);
var largeur=(arguments.length>3?arguments[3]:480);
var top=(screen.height-hauteur)/2;
var left=(screen.width-largeur)/2;
var options = "menubar=no,scrollbars=yes,statusbar=no,resizable=yes";
if(popupWindow)
popupWindow.close();
popupWindow=window.open(arguments[1],"_blank");
popupWindow.focus();
}
var menuItems={
"control": {
activate: function(){
desactivateInteractions();
activateDefaultInteractions();
},
deactivate: function(){
}
},
"zoomin": {
activate: function(){
desactivateInteractions();
activateDefaultInteractions();
map.addInteraction(mapInteractions["zoomin"]);
},
deactivate: function(){
map.removeInteraction(mapInteractions["zoomin"]);
}
},
"geolocate": {
activate: function(){
noTracking=true;
geolocation.setTracking(true);
//geolocation.setTracking(false);
},
deactivate: function(){
geolocation.setTracking(false);
positionFeature.setGeometry(null);
accuracyFeature.setGeometry(null);
}
},
"track": {
activate: function(){
noTracking=false;
geolocation.setTracking(true);
},
deactivate: function(){
geolocation.setTracking(false);
}
},
"line": {
activate: function(){
launchMeasureTools("line");
},
deactivate: function(){
if(drawSource.getFeatures().length>0){
drawSource.removeFeature(drawSource.getFeatures()[0]);
$(".mtooltip-static").parent().remove();
}
}
},
"polygon": {
activate: function(){
launchMeasureTools("area");
},
deactivate: function(){
if(drawSource.getFeatures().length>0){
drawSource.removeFeature(drawSource.getFeatures()[0]);
$(".mtooltip-static").parent().remove();
}
}
},
"getFeature": {
activate: function(){
var isActive=true;
if(!mapInteractions["getFeature"]){
mapInteractions["getFeature"] = new ol.interaction.DragBox({
condition: ol.events.condition.always,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: [0, 0, 255, 1]
})
})
});
isActive=false;
}
desactivateInteractions();
map.addInteraction(mapInteractions['getFeature']);
if(!isActive)
mapInteractions["getFeature"].on('boxend', function(e) {
var extent = mapInteractions["getFeature"].getGeometry().getExtent();
var transformer = ol.proj.getTransform('EPSG:3857','EPSG:4326');
var ext=ol.extent.applyTransform(extent, transformer);
for(var i in oLayers){
if(oLayers[i]["queryParams"] && oLayers[i]["queryParams"]["fields"]){
var key=i;
myMMDataTableObject.display(key,{
url: msUrl,
data: {
"map":oLayers[key]["map"],
version: "1.0.0",
service: "WFS",
request: 'GetFeature',
typename: key,
bbox: ext
}
},true);
}
}
console.log(extent);
});
},
deactivate: function(){
map.removeInteraction(mapInteractions["getFeature"]);
if(drawSource.getFeatures().length>0){
drawSource.removeFeature(drawSource.getFeatures()[0]);
$(".mtooltip-static").parent().remove();
}
}
},
"getFeatureCircle": {
activate: function(){
mmActivateDrawTool({
name: "getFeatureCircle",
type: "Circle",
endHandler: function(evt) {
var format1=new ol.format.GML3({featureNS: "gml", curve:false});
var poly=ol.geom.Polygon.fromCircle(evt.feature.getGeometry());
var sVal1=format1.writeGeometryNode(poly,{
dataProjection: ol.proj.get('EPSG:4326'),
featureProjection: ol.proj.get('EPSG:3857')
});
var layer;
for(layer in oLayers){
if(oLayers[layer]["queryParams"] && oLayers[layer]["queryParams"]["fields"]){
myMMDataTableObject.display(layer,{
url: msUrl,
data: {
"map":oLayers[layer]["map"],
version: "1.0.0",
service: "WFS",
request: 'GetFeature',
typename: layer
},
feature: sVal1
},true);
}
}
}
});
},
deactivate: function(){
map.removeInteraction(mapInteractions["getFeature"]);
if(drawSource.getFeatures().length>0){
drawSource.removeFeature(drawSource.getFeatures()[0]);
$(".mtooltip-static").parent().remove();
}
}
},
"tshare": {
activate: function(){
saveContext(function(data){
console.log("QRCODE RESULT");
$("#qrcodeUrl").val(data);
var urlTwitter = "http://www.twitter.com/share?url="+data+"&text=We would like to share the following Map : ";
loadSharingWindow("Twitter",urlTwitter,480,520);
});
},
deactivate: function(){
}
},
"permalink": {
activate: function(){
console.log("permalink start");
console.log(oldItem);
if(!$("#qrcodeTab").length){
$("#mmtabs").append($("#permalink_header_template")[0].innerHTML);
//Load the template page to display the result
$.ajax({
url: 'modules/sharing/default',
method: 'GET',
success: function(){
console.log(arguments);
$("#mmtabs").next().prepend($('<div role="tabpanel" class="tab-pane" id="qrcodeTab"></div>'));
$("#qrcodeTab").append(arguments[0]);
$("#qrcodeAction").tab('show');
$("#qrcodeTab").bind("removeClass",function(){
console.log(arguments);
$("#qrcodeAction").parent().remove();
$(this).remove();
});
}
});
}
else
$("#qrcodeAction").tab('show');
saveContext(function(data){
console.log("QRCODE RESULT");
$("#qrcodeUrl").val(data);
zoo.execute({
identifier: "QREncode",
dataInputs: [
{"identifier":"Text","value": data,"dataType": "string"}
],
dataOutputs: [
{"identifier":"QR","mimeType": "image/png","asReference":"true"}
],
type: 'POST',
storeExecuteResponse: false,
success: function(data){
console.log("SUCCESS");
console.log(data);
console.log(data["ExecuteResponse"]["ProcessOutputs"]["Output"]["Reference"]["_href"]);
console.log($("#qrcodeImg"));
var d=new Date();
$("#qrcodeClock").html(d.getHours()+": "+d.getMinutes()+": "+d.getSeconds());
$("#qrcodeImg").attr("src",data["ExecuteResponse"]["ProcessOutputs"]["Output"]["Reference"]["_href"]);
},
error: function(data){
console.log("ERROR");
console.log(data);
}
});
});
},
deactivate: function(){
}
},
"fshare": {
activate: function(){
console.log("fshare start");
console.log(oldItem);
saveContext(function(data){
console.log("QRCODE RESULT");
$("#qrcodeUrl").val(data);
var originUrl=data;
zoo.execute({
identifier: "QREncode",
dataInputs: [
{"identifier":"Text","value": data,"dataType": "string"}
],
dataOutputs: [
{"identifier":"QR","mimeType": "image/png","asReference":"true"}
],
type: 'POST',
storeExecuteResponse: false,
success: function(data){
console.log("SUCCESS");
console.log(data);
console.log(data["ExecuteResponse"]["ProcessOutputs"]["Output"]["Reference"]["_href"]);
console.log($("#qrcodeImg"));
var d=new Date();
$("#qrcodeClock").html(d.getHours()+": "+d.getMinutes()+": "+d.getSeconds());
var ref=data["ExecuteResponse"]["ProcessOutputs"]["Output"]["Reference"]["_href"];
$("#qrcodeImg").attr("src",ref);
var urlFB = "http://www.facebook.com/sharer.php?s=100&p[title]=MapMint Sharing&p[url]="+originUrl+"&p[images][0]="+encodeURIComponent(ref);
loadSharingWindow("Facebook",urlFB,480,480);
},
error: function(data){
console.log("ERROR");
console.log(data);
}
});
});
},
deactivate: function(){
}
},
"profile_line": {
activate: function(){
mmActivateDrawTool({
name: "profile_line",
type: "LineString",
endHandler: function(evt) {
var format1=new ol.format.GeoJSON();
//var poly=ol.geom.Polygon.fromCircle(evt.feature.getGeometry());
var lgeom=evt.feature.getGeometry().clone();
console.log(lgeom.getCoordinates());
var coords=lgeom.getCoordinates();
for(i in coords)
coords[i]=coords[i].reverse();
var sVal1=format1.writeGeometry(evt.feature.getGeometry(),{
dataProjection: ol.proj.get('EPSG:4326'),
featureProjection: ol.proj.get('EPSG:3857')
});
console.log(lgeom.getCoordinates());
console.log(sVal1);
var layer;
for(layer in oLayers){
console.log(oLayers[layer]["query"]+" "+oLayers[layer]["type"]=="raster");
console.log(oLayers[layer]["query"] && oLayers[layer]["type"]=="raster");
if(oLayers[layer]["query"] && oLayers[layer]["type"]=="raster"){
window["raster_query_"+layer]=function(){
return sVal1;
}
window["raster_query_level1_"+layer]=function(){
var tmp=zoo.getRequest({
identifier: "template.display",
dataInputs: [
{"identifier":"tmpl","value":"public/project_js","dataType":"string"},
{"identifier":"layer","value":layer,"dataType":"string"},
{
"identifier":"geometry",
"mimeType":"application/json",
"value": sVal1
}
],
dataOutputs: [
{"identifier":"Result","type":"raw"}
],
type: 'POST',
storeExecuteResponse: false
});
return tmp.data;
}
window["raster_query_level2_"+layer]=function(){
var tmp=zoo.getRequest({
identifier: "raster-tools.GdalExtractProfile",
dataInputs: [
{"identifier":"RasterFile","value":oLayers[layer]["rQuery"],"dataType":"string"},
{
"identifier":"Geometry",
"mimeType":"application/json",
headers: [
{ key: "Content-Type", value: "text/xml"},
{ key: "Cookie", value: _MMID}
],
href: zoo.url,
method: "POST",
"complexPayload_callback":"raster_query_level1_"+layer
}
],
dataOutputs: [
{"identifier":"Profile","type":"raw"}
],
type: 'POST',
storeExecuteResponse: false
});
return tmp.data;
}
zoo.execute({
identifier: "template.display",
dataInputs: [
{"identifier":"tmpl","value":"public/project_inv_js","dataType":"string"},
{"identifier":"layer","value":layer,"dataType":"string"},
{
"identifier":"geometry",
"mimeType":"application/json",
"href": zoo.url,
"method": "POST",
"headers": [
{ key: "Content-Type", value: "text/xml"},
{ key: "Cookie", value: _MMID}
],
"complexPayload_callback":"raster_query_level2_"+layer}
],
dataOutputs: [
{"identifier":"Result","type":"raw"}
],
type: 'POST',
storeExecuteResponse: false,
success: function(data){
console.log("SUCCESS");
console.log(data);
var values=[];
var sspoints=[];
for(i in data.coordinates){
values.push(data.coordinates[i][2]);
sspoints.push([data.coordinates[i][0],data.coordinates[i][1]]);
}
for(var i in {"container":0,"header":0})
$("#mmm_table-wrapper-"+i).find(".active").each(function(){
$(this).removeClass("active");
});
if(!$('#mmm_table-content-display_'+layer).length){
$("#mmm_table-wrapper-header").append('<li role="presentation" class="active"><a id="mmm_table-content-display_'+layer+'" title="'+oLayers[layer]["alias"]+'" data-toggle="tab" data-target="#output-profile-'+layer+'" href="#output-profile-'+layer+'"><i class="fa fa-area-chart"></i><b class="ncaret"> </b><span class="hidden-xs hidden-sm">'+oLayers[layer]["alias"]+'</span> </a> </li>');
}else
$('#output-profile-'+layer).remove();
$("#mmm_table-wrapper-container").append('<div class="output-profile tab-pane active" id="output-profile-'+layer+'" style="height: '+($(window).height()/3)+'px;"></div>');
$('#mmm_table-content-display_'+layer).tab("show");
if(!$("#table-wrapper").hasClass("in"))
$("#table-wrapper").collapse("show");
var chart = new Highcharts.Chart({
chart: {
zoomType: 'x',
renderTo: 'output-profile-'+layer
},
title: {
text: "Elevation profile"
},
xAxis: {
labels: {
formatter: function(){
var tmp=this.value+"";
return tmp;
}
},
title: { text: 'Points' },
maxZoom: 0
},
yAxis: {
//max: mmax*2,
title: { text: null },
startOnTick: false,
showFirstLabel: false
},
legend: {
enabled: false
},
plotOptions: {
area: {
cursor: 'pointer',
point: {
events: {
click: function() {
selectLayer.getSource().clear();
var lgeom=new ol.geom.Point([sspoints[this.x][0],sspoints[this.x][1]]);
lgeom=lgeom.transform('EPSG:4326','EPSG:3857');
selectLayer.getSource().addFeature(new ol.Feature({
geometry: lgeom
}));
}
}
},
fillColor: {
linearGradient: [0, 0, 0, 300],
stops: [
[0, '#74B042'],
[1, 'rgba(255,255,255,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 3
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
tooltip: {
formatter: function() {
selectLayer.getSource().clear();
var lgeom=new ol.geom.Point([sspoints[this.x][0],sspoints[this.x][1]]);
lgeom=lgeom.transform('EPSG:4326','EPSG:3857');
selectLayer.getSource().addFeature(new ol.Feature({
geometry: lgeom
}));
return '<h1>Altitude: '+Highcharts.numberFormat(this.y, 0)+"</h1>";
}
},
series: [{
name: 'Elevation',
type: 'area',
data: values
}]
});
},
error: function(data){
console.log("ERROR");
console.log(data);
}
});
}
}
}
});
},
deactivate: function(){
map.removeInteraction(mapInteractions["getFeature"]);
if(drawSource.getFeatures().length>0){
drawSource.removeFeature(drawSource.getFeatures()[0]);
$(".mtooltip-static").parent().remove();
}
}
},
"favorite": {
activate: function(){
zoo.execute({
identifier: "np.setFavoriteMap",
dataInputs: [],
dataOutputs: [{"identifier":"Result","type":"raw"}],
type: 'POST',
storeExecuteResponse: false,
success: function(data) {
$("#favorite").find("i").each(function(){
if($(this).hasClass("fa-star"))
$(this).addClass("fa-star-o").removeClass("fa-star");
else
$(this).addClass("fa-star").removeClass("fa-star-o");
});
console.log("SUCCESS");
console.log(data);
},
error: function(data) {
console.log("SUCCESS");
console.log(data);
}
});
},
deactivate: function(){
}
},
"print": {
activate: function(){
if(!$("#mmprintTab").length){
$("#mmtabs").append($("#printtab_header_template")[0].innerHTML);
$("#mmtabs").next().prepend($('<div role="tabpanel" class="tab-pane" id="mmprintTab"></div>'));
$("#mmprintTab").append($("#printtab_template")[0].innerHTML);
}
$("#mmprintAction").tab('show');
$("#mmprintTab").bind("removeClass",function(){
console.log(arguments);
$("#mmprintAction").parent().remove();
$(this).remove();
});
$("#iFormat").change(function(){
updatePrintDisplay();
});
tmpExt1=getPrintComputeExtent();
printLayer=new ol.layer.Vector({
source: new ol.source.Vector()
});
var my2BS=[];
for(i in myBaseLayers)
if(map.getLayers().item(i).getVisible())
my2BS.push(map.getLayers().item(i));
my2BS.push(printLayer);
pmap=new ol.Map({
target: $("#print-map")[0],
controls: [],
layers: my2BS,
interactions: ol.interaction.defaults({
altShiftDragRotate: true,
dragPan: false,
rotate: true
}).extend([new ol.interaction.DragPan({kinetic: null})]),//ol.interaction.defaults({shiftDragZoom: false}) ,
view: new ol.View({
extent: tmpExt1,
center: [0, 0],
zoom: 2
})
});
printLayer.getSource().clear();
printLayer.getSource().addFeature(new ol.Feature({geometry: ol.geom.Polygon.fromExtent(tmpExt1)}));
pmap.getView().fit(map.getView().calculateExtent(map.getSize()),pmap.getSize());
//$('#iFormat').selectpicker();
if(!printHasLoaded){
map.getView().on('change:center', function() {
updatePrintDisplay();
});
map.getView().on('change:resolution', function() {
updatePrintDisplay();
});
printHasLoaded=true;
}
},
deactivate: function(){
$("#pmap").children().remove();
}
},
};
var printHasLoaded=false;
function updatePrintDisplay(){
if(!$("#mmprintTab").length)
return;
var tmpExt1=getPrintComputeExtent();
printLayer.getSource().clear();
printLayer.getSource().addFeature(new ol.Feature({geometry: ol.geom.Polygon.fromExtent(tmpExt1)}));
pmap.getView().fit(map.getView().calculateExtent(map.getSize()),pmap.getSize());
}
var coeff=1;
var mmPrintSizes={
"A4l": [(1024*coeff),(768*coeff)],
"A4": [(768*coeff),(1024*coeff)]
}
function getPrintComputeExtent(){
var ext=map.getView().calculateExtent(map.getSize());
bufferSize=1;//600*(map.getResolution());
var tmpExt=ext;
width=mmPrintSizes[$('#iFormat').val()][0];
cwidth=tmpExt[2]-tmpExt[0];
wdelta=cwidth/width
height=mmPrintSizes[$('#iFormat').val()][1];
cheight=tmpExt[3]-tmpExt[1];
hdelta=cheight/height;
delta=parseFloat(width)/parseFloat(height);
Wd=(mmPrintSizes[$('#iFormat').val()][0]*map.getView().getResolution())/2;
Hd=(mmPrintSizes[$('#iFormat').val()][1]*map.getView().getResolution())/2;
x0=(tmpExt[0]+((tmpExt[2]-tmpExt[0])/2));
y0=(tmpExt[3]+((tmpExt[1]-tmpExt[3])/2))
return [x0-Wd,y0-Hd,x0+Wd,y0+Hd];
}
function desactivateInteractions(){
for(var i in mapInteractions){
console.log(i);
map.removeInteraction(mapInteractions[i]);
}
}
function activateDefaultInteractions(){
for(var i in mapInteractions){
if(i=="default")
map.addInteraction(mapInteractions[i]);
}
}
function launchMeasureTools(typeSelect){
var type = (typeSelect == 'area' ? 'Polygon' : 'LineString');
var isActive=true;
if(!mapInteractions["line"]){
mapInteractions["line"] = new ol.interaction.Draw({
source: drawSource,
type: 'LineString',
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 0.5)',
lineDash: [10, 10],
width: 2
}),
image: new ol.style.Circle({
radius: 5,
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 0.7)'
}),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
})
})
})
});
mapInteractions["area"] = new ol.interaction.Draw({
source: drawSource,
type: 'Polygon',
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 0.5)',
lineDash: [10, 10],
width: 2
}),
image: new ol.style.Circle({
radius: 5,
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 0, 0.7)'
}),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
})
})
})
});
isActive=false;
}
desactivateInteractions();
map.addInteraction(mapInteractions[typeSelect]);
createMeasureTooltip();
createHelpTooltip();
var listener;
if(!isActive) {
for(var i in {"line":0,"area":0}){
mapInteractions[i].on('drawstart',
function(evt) {
if(drawSource.getFeatures().length>0){
drawSource.removeFeature(drawSource.getFeatures()[0]);
$(".mtooltip-static").parent().remove();
}
// set sketch
sketch = evt.feature;
/** @type {ol.Coordinate|undefined} */
var tooltipCoord = evt.coordinate;
listener = sketch.getGeometry().on('change', function(evt) {
var geom = evt.target;
var output;
if (geom instanceof ol.geom.Polygon) {
output = formatArea(/** @type {ol.geom.Polygon} */ (geom));
tooltipCoord = geom.getInteriorPoint().getCoordinates();
} else if (geom instanceof ol.geom.LineString) {
output = formatLength( /** @type {ol.geom.LineString} */ (geom));
tooltipCoord = geom.getLastCoordinate();
}
measureTooltipElement.innerHTML = output;
measureTooltip.setPosition(tooltipCoord);
});
}, this);
mapInteractions[i].on('drawend',
function(evt) {
measureTooltipElement.className = 'mtooltip mtooltip-static';
measureTooltip.setOffset([0, -7]);
// unset sketch
sketch = null;
// unset tooltip so that a new one can be created
measureTooltipElement = null;
createMeasureTooltip();
ol.Observable.unByKey(listener);
}, this);
}
}
}
/**
* Creates a new help tooltip
*/
function createHelpTooltip() {
if (helpTooltipElement) {
helpTooltipElement.parentNode.removeChild(helpTooltipElement);
}
helpTooltipElement = document.createElement('div');
helpTooltipElement.className = 'mtooltip ';
helpTooltip = new ol.Overlay({
element: helpTooltipElement,
offset: [15, 0],
positioning: 'center-left'
});
map.addOverlay(helpTooltip);
}
/**
* Creates a new measure tooltip
*/
function createMeasureTooltip() {
if (measureTooltipElement) {
measureTooltipElement.parentNode.removeChild(measureTooltipElement);
}
measureTooltipElement = document.createElement('div');
measureTooltipElement.className = 'mtooltip mtooltip-measure';
measureTooltip = new ol.Overlay({
element: measureTooltipElement,
offset: [0, -15],
positioning: 'bottom-center'
});
map.addOverlay(measureTooltip);
}
/**
* format length output
* @param {ol.geom.LineString} line
* @return {string}
*/
var formatLength = function(line) {
var length;
{
var coordinates = line.getCoordinates();
length = 0;
var sourceProj = map.getView().getProjection();
for (var i = 0, ii = coordinates.length - 1; i < ii; ++i) {
var c1 = ol.proj.transform(coordinates[i], sourceProj, 'EPSG:4326');
var c2 = ol.proj.transform(coordinates[i + 1], sourceProj, 'EPSG:4326');
length += wgs84Sphere.haversineDistance(c1, c2);
}
}
var output;
if (length > 100) {
output = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
output = (Math.round(length * 100) / 100) +
' ' + 'm';
}
console.log(output);
return output;
};
/**
* format length output
* @param {ol.geom.Polygon} polygon
* @return {string}
*/
var formatArea = function(polygon) {
var area;
{
var sourceProj = map.getView().getProjection();
var geom = /** @type {ol.geom.Polygon} */(polygon.clone().transform(
sourceProj, 'EPSG:4326'));
var coordinates = geom.getLinearRing(0).getCoordinates();
area = Math.abs(wgs84Sphere.geodesicArea(coordinates));
}
var output;
if (area > 10000) {
output = (Math.round(area / 1000000 * 100) / 100) +
' ' + 'km<sup>2</sup>';
} else {
output = (Math.round(area * 100) / 100) +
' ' + 'm<sup>2</sup>';
}
console.log(output);
return output;
};
// recenters the view by putting the given coordinates at 3/4 from the top or
// the screen
function getCenterWithHeading(position, rotation, resolution) {
var size = map.getSize();
var height = size[1];
return [
position[0] - Math.sin(rotation) * height * resolution * 1 / 4,
position[1] + Math.cos(rotation) * height * resolution * 1 / 4
];
}
var System={};
System.lTemplates={};
System.lTemplates0={};
System.loadTemplates={};
function fetchlTemplate(features){
$.ajax({
type: "GET",
url: templatesUrl+features.get("layerName")+"_"+mapProject+"_tmpl.html",
complete: function(xml,status) {
var res=xml.responseText.replace(/item name/g,"");
var layer=features.get("layerName");
System.lTemplates[layer]=res;
System.loadTemplates[layer]=false;
try{
printlTemplate(features);
}catch(e){
for(var j=0;j<features.length;j++){
{
printlTemplate(features[j]);
}
}
}
}
});
}
function printlTemplate(feature){
if(!feature){
return;
}
var j=0;
var layer=feature.get("layerName");
if(!System.lTemplates0[layer])
System.lTemplates0[layer]=System.lTemplates[layer];
var res1=System.lTemplates[layer];
var tmp="";
var data=feature.getProperties();
for(j in data){
if(j!="msGeometry"){
var reg=new RegExp("\\[=""+j+""\\]","g");
res1=res1.replace(reg,feature.get(j));
var reg=new RegExp("\\[="+j+"\\]","g");
res1=res1.replace(reg,feature.get(j));
}
}
System.onPrintlTemplate(feature,res1);
}
function tryRun(feature){
if(!System.lTemplates0[layerName])
fetchlTemplate(feature);
else
printlTemplate(feature);
}
var filename="http://127.0.0.1/zoo-requirejs/data/stations.gml";
function cgalProcessing(aProcess) {
notify('Running '+aProcess+' service','info');
zoo.execute({
identifier: "cgal."+aProcess,
dataInputs: [{"identifier":"InputPoints","href":filename,"mimeType":"text/xml"}],
dataOutputs: [{"identifier":"Result","mimeType":"application/json","type":"raw"}],
type: 'POST',
storeExecuteResponse: false,
success: function(data) {
notify(aProcess+' service run successfully','success');
var GeoJSON = new OpenLayers.Format.GeoJSON();
var features = GeoJSON.read((data));
layer.removeFeatures(layer.features);
layer.addFeatures(features);
},
error: function(data) {
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
}
});
}
function applyMargins() {
var leftToggler = $(".mini-submenu-left");
if (leftToggler.is(":visible")) {
$("#map .ol-zoom")
.css("margin-left", 0)
.removeClass("zoom-top-opened-sidebar")
.addClass("zoom-top-collapsed");
} else {
$("#map .ol-zoom")
.css("margin-left", $(".sidebar-left").width())
.removeClass("zoom-top-opened-sidebar")
.removeClass("zoom-top-collapsed");
}
}
function isConstrained() {
return $(".sidebar").width() == $(window).width();
}
function applyInitialUIState() {
if (isConstrained()) {
$(".sidebar-left .sidebar-body").fadeOut('slide');
$('.mini-submenu-left').fadeIn();
}
}
function getLayerById(cid){
var clayer=null;
var j=0;
for(i in oLayers){
if(j==cid){
clayer=i;
return clayer;
}
j++;
}
return clayer;
}
var printDocument = function() {
console.log("run print");
$("#print-loader").show();
var realExt=getPrintComputeExtent();
var tmpExt0=[realExt[0],realExt[1],realExt[2],realExt[3]];
var tmpExt=[realExt[0],realExt[3],realExt[2],realExt[1]];
var d=new Date();
$("#print-loader-info").html($("#printtab_loading_bg_template")[0].innerHTML);
zoo.execute({
identifier: "raster-tools.translate",
dataInputs: [
{"identifier":"InputDSN","value":"base_layers/default.xml","dataType":"string"},
{"identifier":"OutputDSN","value":"tmp_"+_MMID.replace(/MMID=/g,""),"dataType":"string"},
{"identifier":"Format","value":"GTiff","dataType":"string"},
{"identifier":"OutSize","value":mmPrintSizes[$('#iFormat').val()],"dataType":"string"},
{"identifier":"ProjWin","value":tmpExt,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
type: 'POST',
success: function(data){
console.log("SUCCESS");
console.log(data);
$("#print-loader-info").html($("#printtab_loading_print_template")[0].innerHTML);
var activatedLayers=[];
for(var i=myBaseLayers.length;i<map.getLayers().getLength()-myToolsLayers.length;i++){
if(map.getLayers().item(i).getVisible())
activatedLayers.push(i-myBaseLayers.length);
}
zoo.execute({
identifier: "print.printMap",
dataInputs: [
{"identifier":"layers","value":activatedLayers,"dataType":"string"},
{"identifier":"ext","value":tmpExt0,"dataType":"string"},
{"identifier":"iFormat","value":$('#iFormat').val(),"dataType":"string"},
{"identifier":"tDoc","value":"MM-PrintedMap.pdf","dataType":"string"},
{"identifier":"map","value":lastMap,"dataType":"string"},
{"identifier":"bgMap","value":data,"dataType":"string"},
{"identifier":"zoom","value":map.getView().getZoom(),"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","asReference":"true"},
],
type: 'POST',
success: function(data){
console.log("SUCCESS");
console.log(data);
console.log(data["ExecuteResponse"]["ProcessOutputs"]["Output"]["Reference"]["_href"]);
$("#print-loader-info").html($("#printtab_loading_print_success_template")[0].innerHTML);
$("#printtab_res_link").attr("href",data["ExecuteResponse"]["ProcessOutputs"]["Output"]["Reference"]["_href"]);
printPreview(data["ExecuteResponse"]["ProcessOutputs"]["Output"]["Reference"]["_href"].toString());
},
error: function(data){
console.log("ERROR");
console.log(data);
$("#print-loader-info").html($("#printtab_loading_print_error_template")[0].innerHTML);
$("#print-error-details").html(data["ExceptionReport"]["Exception"]["ExceptionText"].toString());
}
});
},
error: function(data){
console.log("ERRROR");
console.log(data);
}
});
}
function authenticateSetup(){
$("#authenticate_setup").click(function(){
$("#mmtabs").append($("#auth_header_template")[0].innerHTML);
//Load the template page to display the result
$.ajax({
url: 'modules/auth/login',
method: 'GET',
success: function(){
console.log(arguments);
$("#mmtabs").next().prepend($('<div role="tabpanel" class="tab-pane" id="authTab"></div>'));
$("#authTab").append(arguments[0]);
$("#authAction").tab('show');
$("#authTab").bind("removeClass",function(){
console.log(arguments);
$("#authAction").parent().remove();
$(this).remove();
});
}
})
});
}
function printPreview(){
var reg=new RegExp(tmpUrl,"g");
zoo.execute({
identifier: "print.preview",
dataInputs: [
{"identifier":"res","value":"32","dataType":"integer"},
{"identifier":"file","value":arguments[0].replace(reg,tmpPath),"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","asReference":"true"},
],
type: 'POST',
success: function(data){
console.log("SUCCESS");
console.log(data);
var tmp=data["ExecuteResponse"]["ProcessOutputs"]["Output"]["Reference"]["_href"].toString();
$("#print-preview-img").attr("src",tmp);
},
error: function(data){
console.log("ERROR");
console.log(data);
}
});
}
// Return public methods
return {
initialize: initialize,
printDocument: printDocument,
cgalProcessing: cgalProcessing
};
});
<|start_filename|>mapmint-ui/templates/preview/modules/geolocation/control.js<|end_filename|>
,geolocate: new OpenLayers.Control.Geolocate({
bind: false,
geolocationOptions: {
enableHighAccuracy: false,
maximumAge: 0,
timeout: 9000
}
})
<|start_filename|>mapmint-ui/new-themes/themes/blue/grid.css<|end_filename|>
.flexigrid div.mDiv div.preview:hover {
background: #FFFFFF url(../img/preview-hover-blue.png);
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.download:hover {
background: #FFFFFF url(../img/download-hover-blue.png);
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.open-in-manager:hover {
background:#FFFFFF url(../img/open-in-manager-hover-blue.png);
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.delete:hover {
background: #FFFFFF url(../img/delete-datasource-hover-blue.png);
border-color: #9a9a9a;
}
.flexigrid div.bDiv tr.trSelected:hover td,.flexigrid div.bDiv tr.trSelected:hover td.sorted,.flexigrid div.bDiv tr.trOver.trSelected td.sorted,.flexigrid div.bDiv tr.trOver.trSelected td,.flexigrid tr.trSelected td.sorted,.flexigrid tr.trSelected td
{
background: -moz-linear-gradient(top, #7fe5f9 , #3d93df);
background: -webkit-gradient(linear, left top, left bottom, from(#7fe5f9), to(#3d93df));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#7fe5f9', endColorstr='#3d93df');
border-right: 1px solid #7ef7ff;
border-left: 1px solid #7ef7ff;
border-bottom: 1px solid #7ef7ff;
}
.flexigrid .pSearch:hover {
background: url(../img/magnifier-hover-blue.png) no-repeat center;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
.flexigrid .pFirst:hover {
background: #FFFFFF url(../img/first-hover-blue.png) no-repeat center;
}
.flexigrid .pPrev:hover {
background: #FFFFFF url(../img/prev-hover-blue.png) no-repeat center;
}
.flexigrid .pNext:hover {
background: #FFFFFF url(../img/next-hover-blue.png) no-repeat center;
}
.flexigrid .pLast:hover {
background: #FFFFFF url(../img/last-hover-blue.png) no-repeat center;
}
.change-srs{text-decoration:none;color:#808080;text-shadow:none;font-weight:normal;padding: 0 3px 0 3px;}
.change-srs:hover{color:#3d93df;}
.change-format{text-decoration:none;color:#808080;text-shadow:none;font-weight:normal;padding: 0 3px 0 3px;}
.change-format:hover{color:#3d93df;}
<|start_filename|>public_map/assets/js/cgal-app.js<|end_filename|>
// Filename: app.js
/*
This work was supported by a grant from the European Union's 7th Framework Programme (2007-2013)
provided for the project PublicaMundi (GA no. 609608).
*/
require(['bootstrap', 'notify']);
define([
'module', 'jquery', 'zoo', 'xml2json',
], function(module, $, Zoo, X2JS) {
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
});
var mymodal = $('#myModal');
var mynotify = $('.top-right');
function notify(text, type) {
mynotify.notify({
message: { text: text },
type: type,
}).show();
}
var initialize = function() {
$('.sidebar-left .slide-submenu').on('click',function() {
var thisEl = $(this);
thisEl.closest('.sidebar-body').fadeOut('slide',function(){
$('.mini-submenu-left').fadeIn();
applyMargins();
});
});
$('.mini-submenu-left').on('click',function() {
var thisEl = $(this);
$('.sidebar-left .sidebar-body').toggle('slide');
thisEl.hide();
applyMargins();
});
$(window).on("resize", applyMargins);
applyInitialUIState();
applyMargins();
map = new OpenLayers.Map('map', {
controls: [
new OpenLayers.Control.PanZoom(),
//new OpenLayers.Control.Permalink(),
//new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.Navigation()
],
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
maxResolution: 156543.0399,
numZoomLevels: 19,
units: "m",
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326")
});
//gmap = new OpenLayers.Layer.Google("Google Map");
baseOSM = new OpenLayers.Layer.OSM();
arrayOSM = ["http://otile1.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png",
"http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png",
"http://otile3.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png",
"http://otile4.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png"];
layerLS=new OpenLayers.Layer.OSM("MapQuest-OSM Tiles", arrayOSM);
//map.addLayer(layerLS);
map.addLayers([layerLS,baseOSM]);
layer = new OpenLayers.Layer.Vector("Voronoi",{
styleMap: new OpenLayers.StyleMap({
fillColor: "#ffffff",
fillOpacity: 0.1,
strokeColor: "#0a625c",
strokeWidth: 1.5
})
});
map.addLayer(layer);
SubwayStops = new OpenLayers.Layer.GML("Subway stops",
"./data/stations.gml",
{
format: OpenLayers.Format.GML,
styleMap: new OpenLayers.StyleMap({
pointRadius: 4,
fillColor: "#00a099",
fillOpacity: 1,
strokeColor: "#0a625c",
strokeWidth: 2
}),
visibility: true
});
map.addLayer(SubwayStops);
map.zoomToExtent(new OpenLayers.Bounds(240047.557702813,6234682.54296228,281304.353234602,6267347.78149257),true);
}
// $( ".osmbl" ).click(function() {
// map.setBaseLayer(baseOSM);
// });
// $( ".mqbl" ).click(function() {
// map.setBaseLayer(layerLS);
// });
var filename="http://127.0.0.1/zoo-requirejs/data/stations.gml";
function cgalProcessing(aProcess) {
notify('Running '+aProcess+' service','info');
zoo.execute({
identifier: "cgal."+aProcess,
dataInputs: [{"identifier":"InputPoints","href":filename,"mimeType":"text/xml"}],
dataOutputs: [{"identifier":"Result","mimeType":"application/json","type":"raw"}],
type: 'POST',
storeExecuteResponse: false,
success: function(data) {
notify(aProcess+' service run successfully','success');
var GeoJSON = new OpenLayers.Format.GeoJSON();
var features = GeoJSON.read((data));
layer.removeFeatures(layer.features);
layer.addFeatures(features);
},
error: function(data) {
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
}
});
}
function applyMargins() {
var leftToggler = $(".mini-submenu-left");
if (leftToggler.is(":visible")) {
$("#map .ol-zoom")
.css("margin-left", 0)
.removeClass("zoom-top-opened-sidebar")
.addClass("zoom-top-collapsed");
} else {
$("#map .ol-zoom")
.css("margin-left", $(".sidebar-left").width())
.removeClass("zoom-top-opened-sidebar")
.removeClass("zoom-top-collapsed");
}
}
function isConstrained() {
return $(".sidebar").width() == $(window).width();
}
function applyInitialUIState() {
if (isConstrained()) {
$(".sidebar-left .sidebar-body").fadeOut('slide');
$('.mini-submenu-left').fadeIn();
}
}
// Return public methods
return {
initialize: initialize,
cgalProcessing: cgalProcessing
};
});
<|start_filename|>public_map/jquery.fixedcenter.js<|end_filename|>
/***
@title:
Fixed Center
@version:
1.3
@author:
<NAME>
@date:
2010-12-06 - performance issues update
2010-06-27 - updated plugin to use fixed positioning instead of absolute
2010-06-17 - released version 1 of the plugin
@url
www.david-tang.net
@copyright:
2010 <NAME>
@requires:
jquery
@does:
This plugin centers an element on the page using fixed positioning and keeps the element centered
if you scroll horizontally or vertically.
@howto:
jQuery('#my-element').fixedCenter(); would center the element with ID 'my-element' using absolute positioning
*/
(function(){
jQuery.fn.fixedCenter = function(){
return this.each(function(){
var element = jQuery(this), win = jQuery(window);
centerElement();
jQuery(window).bind('resize',function(){
centerElement();
});
function centerElement(){
var elementWidth, elementHeight, windowWidth, windowHeight, X2, Y2;
elementWidth = element.outerWidth();
elementHeight = element.outerHeight();
windowWidth = win.width();
windowHeight = win.height();
X2 = (windowWidth/2 - elementWidth/2) + "px";
Y2 = (windowHeight/2 - elementHeight/2) + "px";
jQuery(element).css({
'left':X2,
'top':Y2,
'position':'fixed'
});
} //centerElement function
});
}
})();
<|start_filename|>mapmint-ui/js/Dashboard.js<|end_filename|>
Dashboard=MLayout.extend();
Dashboard.define({
id: 0,
layoutOptions: {
contentSelector: ".lcontent",
center__paneSelector: ".inner-center",
west__paneSelector: ".inner-west",
west__size: .28,
west__closable: false,
west__draggable: false,
west__resizable: false,
east__paneSelector: ".inner-east",
east__size: .28,
east__closable: false,
east__draggable: false,
east__resizable: false,
spacing_open: 4,
spacing_closed: 4,
//resizeWhileDragging: true,
onopen: function() {updateSize();},
onclose: function() {updateSize();},
onresize: function() {updateSize();}
},
initialize: function(){
$('.maincfg1,.maincfg2,.maincfg3').button({text: false});
var tmpConfMap={
main: {},
identification: {},
provider: {}
};
this.refresh();
this.id++;
},
refresh: function(){
$('.maincfg1,.maincfg2,.maincfg3, .start-stop').button({text: false});
$('.toolbar a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
$( "a.save-config" ).button();
$( "#nav li a" ).button();
$( ".nb-container p a" ).button();
var tabContainers = $('div.tabs-left > div');
tabContainers.hide().filter(':first').show();
$('div.toolbar a').click(function () {
if(this.id!="saveConf"){
tabContainers.hide();
tabContainers.filter(this.hash).show();
}else{
saveConf(cTab);
}
}).filter(':first').click();
defaultInit();
}
});
System.has_dstats=false;
function diskUsage(){
$.ajax({
url: "./Dashboard/DiskUsage",
complete: function(xml,status){
$('#slocal_stats_body').append(xml.responseText);
System.has_dstats=true;
}
});
}
SrsManager=Class.create({
initializeWindow: function(){
$.ajax({
url: "./Projections",
complete: function(xml,status){
if(!$('#SrsManager-dialog')[0])
$("body").append('<div id="SrsManager-dialog" title="'+System.messages["SRS Manager"]+'"></div>');
$('#SrsManager-dialog').html("");
$('#SrsManager-dialog').append(xml.responseText);
$(".combo").click(function(){
System.currentField="";
$(this).parent().find("select").each(function(){
System.currentField=$(this).attr('id');
});
});
$(".combo-panel").click(function(){
$("#"+System.currentField).next().find(".combo-text").each(
function(){
System.currentSelection=$(this).val();
}
);
System.sid=0;
$("#"+System.currentField).find("option").each(
function(){
if($(this).val()==System.currentSelection){
SrsManager.isFav();
$("#tags"+(System.currentField=="tags"?"1":"")).next().find(".combo-text").each(function(){
$(this).val(
$("#tags"+(System.currentField=="tags"?"1":""))[0].options[System.sid].value
);
});
}
System.sid+=1;
}
);
});
System.srsHasChanged=false;
$('#SrsManager-dialog').window({
width: 325,
height: 220,
maximizable:false,
resizable: false,
onClose: function(){
if(System.srsHasChanged)
document.location.reload(false);
}
});
}
});
},
isFav: function(){
var val="";
$("#"+System.currentField).next().find("input.combo-value").each(function(){val=$(this).val();})
$.ajax({
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.isFavSrs&DataInputs=srs_field="+(System.currentField=="tags"?"name":"id")+";srs_id="+val+";fav="+$("#prjfav").is(":checked")+"&RawDataOutput=Result",
complete: function(xml,status){
if(checkWPSResult(xml,false))
$("#prjfav").prop( "checked", eval(xml.responseText));
}
});
},
updateFav: function(){
var val="";
$("#"+System.currentField).next().find("input.combo-value").each(function(){val=$(this).val();})
$.ajax({
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.saveFavSrs&DataInputs=srs_field="+(System.currentField=="tags"?"name":"id")+";srs_id="+val+";fav="+$("#prjfav").is(":checked")+"&RawDataOutput=Result",
complete: function(xml,status){
if(checkWPSResult(xml))
System.srsHasChanged=true;
}
});
}
});
var tabs={};
var cTab;
function loadTab(){
cTab=arguments[0];
tabs[cTab]="";
$.ajax({
cache: false,
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=configuration.GetConf&DataInputs=section="+arguments[0]+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
eval("var tmp="+xml.responseText+";");
tabs[cTab]=tmp;
$('#progress_bar .ui-progress').css('width', '85%');
for(var t in tmp)
if($("#"+t)[0]){
$("#"+t).val(tmp[t]);
if(t=="abstract"){
if (CKEDITOR.instances[t]) { CKEDITOR.instances[t].destroy(true); }
CKEDITOR.replace(t,{
skin : 'v2',
entities: false,
basicEntities: false,
toolbar:[
{ name: 'document', items : [ 'Source','NewPage','Preview' ] },
{ name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
{ name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','Scayt' ] },
'/',
{ name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
{ name: 'styles', items : [ 'Styles','Format' ] },
'/',
{ name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
{ name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote' ] },
{ name: 'links', items : [ 'Link','Unlink','Anchor' ] },
{ name: 'colors', items : [ 'TextColor','BGColor' ] },
{ name: 'tools', items : [ 'Maximize'] }
]
});
}
}
$('#progress_bar .ui-progress').css('width', '95%');
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
endLoading();
}
});
}
function saveConf(){
var args={};
var tmp=[];
tmp[tmp.length]={name: "section",value: arguments[0],dataType: "string"};
for(var i in tabs[arguments[0]]){
if($("#"+i)[0]){
if(i!="abstract")
tmp[tmp.length]={name: i,value: $("#"+i).val(),dataType: "string"};
else
tmp[tmp.length]={name: i,value: CKEDITOR.instances[i].getData(),dataType: "string"};
}
}
try{
var data=WPSGetHeader("configuration.SaveConf")+WPSGetInputs(tmp)+WPSGetOutput({name: "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
try{
loadTab(cTab);
}catch(e){alert(e);}
}
});
}catch(e){alert(e);}
return false;
}
<|start_filename|>mapmint-ui/js/generic.js<|end_filename|>
function searchTable(){
System.tableName=arguments[0];
$( "#"+arguments[0]+"_search" ).autocomplete({
source: function(request,response){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&identifier=np.searchByName&DataInputs=tbl="+System.tableName+";val="+request.term+"&RawDataOutput=Result",
success: function(xml,status){
var data=xml;
response(data);
}});
},
minLength: 0,
select: function( event, ui ) {
System.nodeId=ui.item.id;
var node = $('#ltree').tree('find', System.nodeId);
$("#ltree").tree('select',node.target);
}
});
}
function destroyEditor(name){
try{
if (CKEDITOR.instances[name]) { CKEDITOR.instances[name].destroy(true); CKEDITOR.instances[name]=null;}
}catch(e){}
}
function createEditor(name){
try{
/*
cf. http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Toolbar for more
informations on ckEditor toolbars
*/
if (CKEDITOR.instances[name]) { CKEDITOR.instances[name].destroy(true); }
CKEDITOR.replace(name,{
skin : 'v2',
toolbar:[
{ name: 'document', items : [ 'Source','NewPage','Preview' ] },
{ name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
{ name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','Scayt' ] },
'/',
{ name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
{ name: 'styles', items : [ 'Styles','Format' ] },
'/',
{ name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
{ name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote' ] },
{ name: 'links', items : [ 'Link','Unlink','Anchor' ] },
{ name: 'colors', items : [ 'TextColor','BGColor' ] },
{ name: 'tools', items : [ 'Maximize'] }
]
});
}catch(e){
alert("Error creating editor: "+e);
}
}
<|start_filename|>mapmint-ui/templates/UsersManagement/GroupMultipleList.html<|end_filename|>
#set res=$cur.execute("SELECT id,name as val from "+$prefix+"groups order by name")
#set vals=$cur.fetchall()
#for i in range(0,len(vals))
<option value="$vals[i][0]">$vals[i][1]</option>
#end for
<|start_filename|>mapmint-ui/js/Printer.js<|end_filename|>
$(document).ready(function () {
myLayout = $('body').layout({
north__minSize:60,
north__closable:false,
north__resizable:false,
north__spacing_open:0,
north__spacing_closed:0,
north__showOverflowOnHover: true,
west__minSize: .28,
west__resizable: false,
west__spacing_closed: 20,
east__minSize: .28,
east__resizable: false,
east__closable:false,
south__closable:false,
south__resizable:false,
south__minSize:40,
});
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
$('div.ui-layout-resizer-west div.ui-layout-toggler').before('<span class="close-inv" onclick="myLayout.open(\'west\')" title="Open"></span>');
$("#demo5").paginate({
count : 10,
start : 1,
display : 5,
border : true,
border_color : '#fff',
text_color : '#fff',
background_color : '#808080',
border_hover_color : '#ccc',
text_hover_color : '#000',
background_hover_color : '#fff',
images : false,
mouse : 'press',
onChange : function(page){
$('._current','#paginationdemo').removeClass('_current').hide();
$('#p'+page).addClass('_current').show();
}
});
$('.styleswitch').bind('click',
function(e){
$.stylesheetSwitch(this.getAttribute('rel'));
return false;
}
);
$(function(){
$('#file').customFileInput();
});
$(function() {
$('#font-colorpicker').colorPicker();
});
$.jGrowl.defaults.pool = 3;
$( "#nav li a" ).button();
$( "a.save-config" ).button();
$( ".nb-container p a" ).button();
$('.toolbar a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
$('.toolbar2 a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
function megaHoverOver(){
$(this).find(".sub").stop().fadeTo('fast', 1).show();
(function($) {
jQuery.fn.calcSubWidth = function() {
rowWidth = 0;
$(this).find("ul").each(function() {
rowWidth += $(this).width();
});
};
})(jQuery);
if ( $(this).find(".row").length > 0 ) {
var biggestRow = 0;
$(this).find(".row").each(function() {
$(this).calcSubWidth();
if(rowWidth > biggestRow) {
biggestRow = rowWidth;
}
});
$(this).find(".sub").css({'width' :biggestRow});
$(this).find(".row:last").css({'margin':'0'});
} else {
$(this).calcSubWidth();
$(this).find(".sub").css({'width' : rowWidth});
}
}
function megaHoverOut(){
$(this).find(".sub").stop().fadeTo('fast', 0, function() {
$(this).hide();
});
}
var config = {
sensitivity: 1,
interval: 50,
over: megaHoverOver,
timeout: 50,
out: megaHoverOut
};
$("ul li .sub").css({'opacity':'0'});
$("ul li").hoverIntent(config);
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
$("#logout").click(function () {
$( "#logout-message" ).window({
modal: true,
collapsible:false,
minimizable:false,
maximizable:false,
draggable:false,
resizable: false
});
});
});
<|start_filename|>mapmint-ui/js/upload.js<|end_filename|>
function startUploadWindow(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=upload.getForm&DataInputs=form=Upload&RawDataOutput=Result",
dataType: 'xml',
complete:function(xml,status){
if(!$("#upload-data-dialog")[0])
$("body").append('<div id="upload-data-dialog" title="'+System.messages["Upload Files"]+'"></div>');
$("#upload-data-dialog").html(xml.responseText);
$("#upload-data-dialog").window({
minimizable:false,
maximizable:false,
resizable: false
});
}
});
}
function startUploadForm(){
// Setup html5 version
var args={
// General settings
runtimes : 'html5',
url : System.zooUrl+'?service=WPS&version=1.0.0&request=Execute&Identifier=upload.saveOnServer&dataInputs=file=upload;dest='+$("#upload_dest")[0].value,
max_file_size : '10mb',
chunk_size : '10mb',
unique_names : true
};
if(arguments[0]=="Publisher")
args["multiple_queues"]=false;
$("#uploader").pluploadQueue(args);
$("#upload_form").css({visibility: "visible"});
}
function startCheck(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=upload.checkFile&DataInputs=dest="+$("#upload_dest")[0].value+"&RawDataOutput=Result",
dataType: 'xml',
complete:function(xml,status){
$("#uploader").html("");
var list="";
try{tmp=eval("["+xml.responseText+"]");}catch(e){alert(e);}
for(var i=0;i<tmp[0]["accepted"].length;i++)
list+="<li>"+tmp[0]["accepted"][i]+"</li>";
$("#uploader").append("<h2>Accepted files in "+$("#upload_dest")[0].value+":</h2><ul>"+list+"</ul>");
list="";
for(var i=0;i<tmp[0]["refused"].length;i++)
list+="<li>"+tmp[0]["refused"][i]+"</li>";
if(tmp[0]["refused"].length>1)
$("#uploader").append("<h2>Files not accepted:</h2> <ul>"+list+"</ul>");
}
});
}
<|start_filename|>mapmint-ui/css/login.css<|end_filename|>
html{height: 100%;}
body{
height:100%;
padding:0;
margin:0;
font-family:Arial,Lucida Grande,Trebuchet MS,verdana;
background: rgb(254,255,255);
background: url(data:image/svg+xml;base64,<KEY>);
background: -moz-linear-gradient(top, rgba(254,255,255,1) 36%, rgba(131,200,73,1) 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(36%,rgba(254,255,255,1)), color-stop(100%,rgba(131,200,73,1)));
background: -webkit-linear-gradient(top, rgba(254,255,255,1) 36%,rgba(131,200,73,1) 100%);
background: -o-linear-gradient(top, rgba(254,255,255,1) 36%,rgba(131,200,73,1) 100%);
background: -ms-linear-gradient(top, rgba(254,255,255,1) 36%,rgba(131,200,73,1) 100%);
background: linear-gradient(to bottom, rgba(254,255,255,1) 36%,rgba(131,200,73,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#feffff', endColorstr='#83c849',GradientType=0 );
}
#container{
border:1px solid #FFFFFF;
position:absolute;
height:280px;
width:500px;
margin:-130px 0px 0px -250px;
top: 40%;
left: 50%;
text-align: center;
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPHJhZGlhbEdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY3g9IjUwJSIgY3k9IjUwJSIgcj0iNzUlIj4KICAgIDxzdG9wIG9mZnNldD0iMzklIiBzdG9wLWNvbG9yPSIjZTFmY2Q4IiBzdG9wLW9wYWNpdHk9IjAuNjUiLz4KICAgIDxzdG9wIG9mZnNldD0iNDIlIiBzdG9wLWNvbG9yPSIjZTFmY2Q4IiBzdG9wLW9wYWNpdHk9IjAuNTciLz4KICAgIDxzdG9wIG9mZnNldD0iNjMlIiBzdG9wLWNvbG9yPSIjZTFmY2Q4IiBzdG9wLW9wYWNpdHk9IjAiLz4KICAgIDxzdG9wIG9mZnNldD0iNzclIiBzdG9wLWNvbG9yPSIjZTFmY2Q4IiBzdG9wLW9wYWNpdHk9IjAiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogIDxyZWN0IHg9Ii01MCIgeT0iLTUwIiB3aWR0aD0iMTAxIiBoZWlnaHQ9IjEwMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
background: -moz-radial-gradient(center, ellipse cover, rgba(225,252,216,0.65) 39%, rgba(225,252,216,0.57) 42%, rgba(225,252,216,0) 63%, rgba(225,252,216,0) 77%);
background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(39%,rgba(225,252,216,0.65)), color-stop(42%,rgba(225,252,216,0.57)), color-stop(63%,rgba(225,252,216,0)), color-stop(77%,rgba(225,252,216,0)));
background: -webkit-radial-gradient(center, ellipse cover, rgba(225,252,216,0.65) 39%,rgba(225,252,216,0.57) 42%,rgba(225,252,216,0) 63%,rgba(225,252,216,0) 77%);
background: -o-radial-gradient(center, ellipse cover, rgba(225,252,216,0.65) 39%,rgba(225,252,216,0.57) 42%,rgba(225,252,216,0) 63%,rgba(225,252,216,0) 77%);
background: -ms-radial-gradient(center, ellipse cover, rgba(225,252,216,0.65) 39%,rgba(225,252,216,0.57) 42%,rgba(225,252,216,0) 63%,rgba(225,252,216,0) 77%);
background: radial-gradient(ellipse at center, rgba(225,252,216,0.65) 39%,rgba(225,252,216,0.57) 42%,rgba(225,252,216,0) 63%,rgba(225,252,216,0) 77%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#a6e1fcd8', endColorstr='#00e1fcd8',GradientType=1 );
}
h1.title {
color:#707070;
text-decoration: none;
font-size: 4em !important;
margin:0;
padding:0;
text-transform:none;
min-width:300px;
text-shadow:#FFFFFF 0 1px 0;
display:inline !important;}
h1.title span.logo{
background:url(../img//mapmint-logo.png) no-repeat;
width:60px;
height:60px;
display:inline-block;
margin:0;
padding:0 0 0 5px;
position:relative;
top:6px;
left:0;
}
h1.title span.mint {
color:#83c849;
}
p.announce a{
text-decoration:none;
position:relative;
top:110px;
left:0;
margin:0 auto;
color:#818181;
text-shadow: 0 1px 1px rgba(255, 255, 255, 1);
letter-spacing:3px;
font-size:2em;
text-align:center;
text-transform:uppercase;}
a{outline:0;}
#connexion-form {
position:relative;
margin:30px 0 0 0;
width: 500px;
height:170px;
background:transparent;
}
#connexion-form table {
margin:0 auto;
}
label {font-size:.85em; color:#b0b0b0;text-shadow: 0 1px 0 rgba(255, 255, 255, 1);}
input {
position:relative;
width:240px;
min-width:240px;
margin:0 0 5px 0;
font-size:.8em;
color:#707070;
border:1px solid #c1c1c1 !important;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
z-index:1000000;
}
input:focus
{
border:1px solid #a3a3a3;
box-shadow: 0px 0px 5px #9e9e9e;
-webkit-box-shadow: 0px 0px 5px #9e9e9e;
-moz-box-shadow: 0px 0px 5px #9e9e9e;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
behavior: url(ie-css3.htc);
z-index:1000000;
}
.butt{
width:160px !important;
max-width: 160px !important;
min-width:160px !important;
font-family: Arial, Helvetica, sans-serif;
font-size:.85em;
color:#707070;
margin:30px 0 0 0;
padding: 6px 25px;
background: -moz-linear-gradient(
top,
#ffffff 0%,
#ffffff 50%,
#dddddd);
background: -webkit-gradient(
linear, left top, left bottom,
from(#ffffff),
color-stop(0.50, #ffffff),
to(#dddddd));
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
border: 2px solid #f9fff7;
-moz-box-shadow:
0px 1px 2px rgba(000,000,000,0.2),
inset 0px 0px 2px rgba(255,255,255,1);
-webkit-box-shadow:
0px 1px 2px rgba(000,000,000,0.2),
inset 0px 0px 2px rgba(255,255,255,1);
box-shadow:
0px 1px 2px rgba(000,000,000,0.2),
inset 0px 0px 2px rgba(255,255,255,1);
text-shadow:
0px 1px 0px rgba(255,255,255,1);
}
.butt:hover{
background:#83c849;
border: 2px solid #d8ffcb;
-moz-box-shadow:
0px 1px 2px rgba(255,255,255,1),
inset 0px 0px 2px rgba(255,255,255,1);
-webkit-box-shadow:
0px 1px 2px rgba(255,255,255,1),
inset 0px 0px 2px rgba(255,255,255,1);
box-shadow:
0px 1px 2px rgba(255,255,255,1),
inset 0px 0px 2px rgba(255,255,255,1);
color:#FFFFFF;
cursor:pointer;
text-shadow:none !important;
}
ul.links{list-style:none;position: relative; top:50px; text-align: center; }
ul.links li{display:inline;padding:0 ;}
ul.links li a{font-size:.8em;color:#777777;text-decoration:none;text-shadow:#FFFFFF 0 1px 0;padding:5px 10px 5px 10px;}
ul.links li a:hover{color:#333333;}
.mapm{
display:block;
position:fixed;
bottom:0;
width:100%;
height:30%;
}
ul.credits{
list-style:none;
display:block;
position:fixed;
bottom:0;
text-align:center;
width:100%;
margin:0;
padding:0 0 30px 0;
margin:0;
background:transparent;
}
ul.credits{color:#FFFFFF;}
ul.credits li{display:inline;padding:0;margin:0;font-size:.9em;text-decoration:none;}
ul.credits li a{font-size:1em;color:#FFFFFF;text-decoration:none;padding:0 10px 0 0;}
ul.credits li a:hover{text-decoration:none;color:#707070;}
.ui-dialog-titlebar-close{
display: none;
}
.dialog-loading{
background:#E0E0E0;
}
.load{
margin:0;padding:0;
}
<|start_filename|>public_map/mapmint-default.css<|end_filename|>
body{-ms-zoom: 1.0; margin:0;padding:0;font-family:Lucida grande, Verdana, Arial;}
a{outline:none;}
input {border:1px solid #d3d3d3; outline: none;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff'); /* for IE */
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
input.rounded{width:100%;height:20px;margin:1px;border:1px solid #d3d3d3; outline: none;
background:#EBEBEB;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
input:focus, select:focus{
-webkit-box-shadow: 0px 0px 5px #9e9e9e;
-moz-box-shadow: 0px 0px 5px #9e9e9e;
}
#base_layers{
z-index: 1010;
}
#base_layer_Map{
background: url(./img/mapquest-str.png) no-repeat;
}
#base_layer_Aerial{
background: url(./img/mapquest-sat.png) no-repeat;
}
#base_layer_OSM{
background: url(./img/osm.png) no-repeat;
}
#base_layer_google_maps_MapTypeId_TERRAIN{
background: url(./img/gmaps-ter.png) no-repeat;
}
#base_layer_null{
background: url(./img/gmaps-str.png) no-repeat;
}
#base_layer_google_maps_MapTypeId_SATELLITE{
background: url(./img/gmaps-sat.png) no-repeat;
}
#base_layer_google_maps_MapTypeId_HYBRID{
background: url(./img/gmaps-hyb.png) no-repeat;
}
#base_layer_BingRoad{
background: url(./img/bing-str.png) no-repeat;
}
#base_layer_BingAerial{
background: url(./img/bing-sat.png) no-repeat;
}
#base_layer_BingAerialWithLabels{
background: url(./img/gmaps-hyb.png) no-repeat;
}
#base_layer_IGNGEOGRAPHICALGRIDSYSTEMS_MAPS{
background: url(./img/ign-carte.png) no-repeat;
}
#base_layer_IGNORTHOIMAGERY_ORTHOPHOTOS{
background: url(./img/ign-ortho.png) no-repeat;
}
#base_layer_IGNGEOGRAPHICALGRIDSYSTEMS_ETATMAJOR40{
background: url(./img/ign-major.png) no-repeat;
}
#base_layer_IGNGEOGRAPHICALGRIDSYSTEMS_CASSINI{
background: url(./img/ign-cassini.png) no-repeat;
}
#base_layer_IGNELEVATION_SLOPES{
background: url(./img/ign-elev.png) no-repeat;
}
.fg-button{
float: left;
}
#coords{position:absolute;bottom:12px;right:10px;float:right;}
a.ls-toogler{background:#FFFFFF url('img/layers-icon.png') no-repeat 3px 3px;width:24px;height:24px;z-index:1000;
margin:0 10px 0 0;
border:0;
}
a.ls-toogler:hover{background:#FFFFFF url('img/layers-icon.png') no-repeat 3px 3px;width:24px;height:24px;border:0;}
#ls-toolbar{float:left;}
.ipannel, div#layerswitcher,div#olayerswitcher {background:url('img/bckw.png'); z-index:1000; overflow: hidden;display:block;
float:right;width:350px;height: 50%}
div#layerswitcher h2, div#olayerswitcher h2, div#zoomswitcher h2, div#overviewmap h2{font-size:.9em;margin:0;padding:5px;color:#808080;position:relative;top:0px;left:10px;font-weight:bold; text-shadow: #FFFFFF 0px 1px 0px;letter-spacing:2px;text-transform:uppercase;}
.baseLbl, .dataLbl{display:none;}
.labelSpan{padding:0 0 0 10px;font-size:.9em;}
.baseLayersDiv, .dataLayersDiv {font-size:.9em;margin:0;padding:5px;color:#808080;position:relative;top:0px;left:20px;font-weight:normal;}
#tabs, #tabs-hp {
color: #707070;
font-size: 0.85em;
list-style: none outside none;
margin: 0 0 0 10px;
padding: 5px 0 4px;
}
#tabs li, #tabs-hp li {
display: inline;
}
#tabs li a, #tabs-hp li a {
background-color: #FFFFFF;
border-bottom: medium none;
border-radius: 5px;
color: #707070;
outline: medium none;
padding: 4px 6px;
text-decoration: none;
}
#tabs li a:hover, #tabs-hp li a:hover {
background-color: #DDDDDD;
padding: 4px 6px;
}
#tabs li.active a, #tabs-hp li.active a {
background: none repeat scroll 0 0 #AEA500;
color: #FFFFFF;
text-shadow: 0 1px 0 #333333;
}
#tabs li.active a:hover, #tabs-hp li.active a:hover {
background: none repeat scroll 0 0 #AEA500;
color: #FFFFFF;
text-shadow: 0 1px 0 #333333;
}
.tab_content, .tab_content-hp {
color: #707070;
display: none;
font-size: 0.9em;
padding: 10px;
}
a.al-toogler {
background: url("img/add-layer.png") no-repeat scroll 4px 3px #FFFFFF;
border: 0;
top: 35px;
height: 25px;
margin: 0;
left: 0px;
width: 25px;
z-index: 1000;
}
/* zoommenu
----------------------------------*/
div#zoomswitcher {position:absolute;top:170px; right:10px;background:url('img/bckw.png'); z-index:1000; overflow: hidden;display:block;
-moz-border-radius:5px;-webkit-border-radius:5px;
border-radius:5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
float:right;width:230px;height:auto;}
select#speedC { }
.ui-selectmenu { min-width:230px;display: block; position:relative;top:0;left:0px; height:20px; text-decoration: none; overflow:hidden;font-size:.7em;}
.ui-selectmenu-icon { position:absolute; right:6px; margin-top:-8px; top: 50%; }
.ui-selectmenu-menu { padding:0; margin:0; list-style:none; position:absolute; top: 0; visibility: hidden; overflow: auto;width:100%; }
.ui-selectmenu-open { visibility: visible; }
.ui-selectmenu-menu-popup { margin-top: -1px; }
.ui-selectmenu-menu-dropdown { z-index:1000; font-size:.7em;min-width:230px;}
.ui-selectmenu-menu li { padding:0; margin:0; display: block; border-top: 1px dotted transparent; border-bottom: 1px dotted transparent; border-right-width: 0 !important; border-left-width: 0 !important; font-weight: normal !important;}
.ui-selectmenu-menu li a,.ui-selectmenu-status {line-height: 1.1em; display:block; padding:.3em; outline:none; text-decoration:none; }
.ui-selectmenu-menu li.ui-selectmenu-hasIcon a,
.ui-selectmenu-hasIcon .ui-selectmenu-status { padding-left: 20px; position: relative; margin-left: 5px; }
.ui-selectmenu-menu li .ui-icon, .ui-selectmenu-status .ui-icon { position: absolute; top: 1em; margin-top: -8px; left: 0; }
.ui-selectmenu-status { line-height: 1.4em;}
.ui-selectmenu-open li.ui-selectmenu-item-focus a { }
.ui-selectmenu-open li.ui-selectmenu-item-selected { }
.ui-selectmenu-menu li span,.ui-selectmenu-status span { display:block; margin-bottom: .2em; }
.ui-selectmenu-menu li .ui-selectmenu-item-header { font-weight: bold; }
.ui-selectmenu-menu li .ui-selectmenu-item-content { }
.ui-selectmenu-menu li .ui-selectmenu-item-footer { opacity: .8; }
/*for optgroups*/
.ui-selectmenu-menu .ui-selectmenu-group { font-size: 1em; }
.ui-selectmenu-menu .ui-selectmenu-group .ui-selectmenu-group-label { line-height: 1.4em; display:block; padding:.6em .5em 0; font-weight: bold; }
.ui-selectmenu-menu .ui-selectmenu-group ul { margin: 0; padding: 0; }
.streetname{position:absolute;top:10px;left:500px;width:auto;background:red; z-index:1000; overflow: hidden;display:block;-moz-border-radius:5px;
webkit-border-radius:5px;
border-radius: 5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
color:#FFFFFF;text-shadow: #707070 0 1px 0;
padding:10px;
font-size:.9em;
}
div#zoomTo_control {position:absolute; top:32%; left:10px; width:36px; height:172px;background:url('img/bckw.png'); z-index:1000; overflow: hidden; text-indent:-9999%; font-size:0; display:block; line-height:0;-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius: 5px;
}
div#zoomTo_control:hover {background:#FFFFFF;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
}
div#zoomTo_control a.zoomTo_in {position:absolute; top:5px; left:5px; width:20px; height:20px;background: #E9E9E9 url('img/zoomin.png');z-index:1000;padding:2px;-moz-border-radius:5px;
border-radius:5px;-webkit-border-radius:5px;background-position: 1px 3px;border:1px solid #CCCCCC;
}
div#zoomTo_control a.zoomTo_out {position:absolute; bottom:5px; left:5px; width:20px; height:20px;background: #E9E9E9 url('img/zoomout.png');z-index:1000;padding:2px;-moz-border-radius:5px;
border-radius:5px;-webkit-border-radius:5px;background-position: 1px 3px;border:1px solid #CCCCCC;
}
div#zoomTo_control a.zoomTo_in:hover {background: #cccccc url('img/zoomin-hover.png');background-position: 1px 3px;}
div#zoomTo_control a.zoomTo_out:hover {background: #cccccc url('img/zoomout-hover.png');background-position: 1px 3px;}
input.opac{width:50px;padding:3px 0 0 0;border:0;background:transparent;border:0;text-indent:10px;color:#808080;}
div#zoomTo_control span.slider {position:absolute; top:34px; left:14px; height:104px; width:4px; }
div#zoomTo_control .ui-slider { position: relative; text-align: left;}
div#zoomTo_control .ui-slider .ui-slider-handle { position: absolute; z-index: 20; width:1.2em!important; height:1.2em!important; cursor: default;}
div#zoomTo_control .ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
div#zoomTo_control .ui-slider-vertical { width: .8em; height: 50px; }
div#zoomTo_control .ui-slider-vertical .ui-slider-handle { left: -7px; margin-left: 0; margin-bottom: -.6em; height:4px!important; width:16px!important;background:#E9E9E9;-moz-border-radius:2px;border-radius:2px;-webkit-border-radius:2px;border:1px solid #CCCCCC;}
div#zoomTo_control .ui-slider-vertical .ui-slider-range { left: 0; width: 100%; }
div#zoomTo_control .ui-slider-vertical .ui-slider-range-min { bottom: 0;background:#bababa; }
div#zoomTo_control .ui-slider-vertical .ui-slider-range-max { top: 0; }
div#zoomTo_control .ui-slider-vertical .ui-state-focus {cursor:pointer;}
div#zoomTo_control .ui-slider-vertical .ui-state-active {cursor:pointer;}
div#opacity_control{position:absolute; height:10px; width:130px; }
div#opacity_control span#o-slider {position:absolute;height:4px; width:100px; }
div#opacity_control .ui-slider { position: relative; text-align: left;}
div#opacity_control .ui-slider .ui-slider-handle { position: absolute; z-index: 20; width:4px!important; height:12px!important; cursor: default;}
div#opacity_control .ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
div#opacity_control .ui-slider-horizontal { width: .8em; height: 50px; }
div#opacity_control .ui-slider-handle { left: -7px; margin-left: 0; margin-bottom: -.6em; height:4px!important; width:16px!important;background:#E9E9E9;-moz-border-radius:2px;border-radius:2px;-webkit-border-radius:2px;border:1px solid #CCCCCC;}
div#opacity_control .ui-slider-horizontal .ui-slider-range { left: 0; width: 100%; }
div#opacity_control .ui-slider-horizontal .ui-slider-range-min { bottom: 0;background:#bababa; }
div#opacity_control .ui-slider-horizontal .ui-slider-range-max { top: 0; }
div#opacity_control .ui-slider-horizontal .ui-state-focus {cursor:pointer;}
div#opacity_control .ui-slider-horizontal .ui-state-active {cursor:pointer;}
ul.links{position:relative;display:block;margin:30px 0 0 30px;padding:0;font-size:.8em;}
ul.links li{list-style:none;margin:0 0 15px 0;}
ul.links li a {text-decoration:none;color:#C80020;text-shadow:#E0E0E0 0 1px 0;}
.btm{width:100%;height:50px;background: transparent url('img/bcknav.png');position:absolute;bottom:0;left:0;z-index:1000;}
.btm a{margin:5px 0 0 0;padding: 0;font-size:1em;color:#FFFFFF;text-decoration:none;}
.btm a span{margin:5px 0 0 0;padding:0 0 0 0;font-size:1em;color:#FFFFFF;font-family:arial;font-weight:bold;display:block;letter-spacing:1px;text-shadow:#333333 0 1px 0;}
.toolbar-noborder{background:transparent;width:100%;margin:0;padding:0;}
.toolbar-noborder a{margin:5px 0 5px 5px;}
.toolbar-noborder input,.toolbar-noborder span,.toolbar-noborder select{margin:5px 0 5px 5px;float:left;}
.toolbar-noborder input{width: 50px;}
.lft{background: url('img/mm-logo.png') no-repeat;padding:0 3px 0 0;display:block;margin:5px 10px 0 10px;float:left;width:30px;height:35px;}
.lft a{margin:0 0 0 10px;padding:3px 0 0 3px;font-size:.6em;color:#FFFFFF;text-decoration:none;}
.lft a span{margin:0 0 0 10px;padding:0 0 0 3px;font-size:2em;color:#FFFFFF;font-family:arial;font-weight:bold;display:block;letter-spacing:1px;text-shadow:#333333 0 1px 0;}
.copy{float:left;margin:0;padding:0;max-width:35%;min-width:35%;display:inline-block;}
.copy p{text-align:left;margin:0;padding:5px 0 0 0;font-size:.8em;color:#FFFFFF;margin:0;}
.copy p a{color:#FFFFFF;text-decoration:none;display:block;font-weight:bold;font-size:1.6em;display:block;padding:0;margin:0;}
.copy p a:hover{color:#FFFFFF;text-decoration:none;}
a.ov-toogler{float:right;background:#FFFFFF url('img/overview.png') no-repeat;background-position:2px 2px;width:24px;height:24px;position:absolute;top:8px;right:10px;padding:2px !important;margin:0;z-index:10000;
}
a.ov-toogler:hover{background:#EDEDED url('img/overview.png') no-repeat;background-position:2px 2px;padding:4px;width:24px;height:24px;}
div#overviewmap{z-index:100000000;background:#FFFFFF;}
.olControlOverviewMapElement {
background-color: #FFFFFF !important;
padding:0;
margin:0
}
a.hp-toogler{float:right;background:#FFFFFF url('img/help.png') no-repeat;background-position:3px 3px;width:24px;height:24px;padding:4px !important;position:absolute;top:8px;right:50px;margin:0;z-i$
}
a.hp-toogler:hover{background:#EDEDED url('img/help.png') no-repeat;background-position:3px 3px;padding:4px;width:24px;height:24px;}
.ls-button {
margin:0px;
margin-bottom:0;
padding:.2em;
text-decoration:none !important;
cursor:pointer;
text-align: center;
zoom: 1;
}
.fg-button {
margin:5px;
margin-bottom:0;
padding:.2em;
text-decoration:none !important;
cursor:pointer;
text-align: center;
zoom: 1;
}
.fg-button .ui-icon {
position: absolute;
width:24px;
height:24px;
}
.fg-button-tools .ui-icon {
position: absolute;
width:36px;
height:36px;
}
a.fg-button {
float:left;
}
/*important*/
button.fg-button {width:auto; overflow:visible; }
.fg-button-icon-solo {display:block; width:24px;height:24px; text-indent: -9999px; }
.fg-button-icon-solo-tools {display:block; width:36px;height:36px; text-indent: -9999px; }
.fg-buttonset {float:left;}
.fg-buttonset .fg-button {float: left;}
.fg-buttonset-single .fg-button,
.fg-buttonset-multi .fg-button {margin-right: -1px;}
/*ToolBar left*/
.fg-toolbar{margin-left: 85px;}
.fg-toolbar . set {
margin-right:1.5em;
padding-left: 1px;
}
.fg-toolbar .fg-button, .fg-button { font-size: 1em;width:24px;height:24px;}
.home{width:24px;height:24px;background-image:url(img/home.png) !important;}
.zoom-in {width:24px;height:24px;background-image:url(img/zoom-in.png) !important;}
.zoom-out {background-image:url(img/zoom-out.png) !important;}
.pan {background-image:url(img/pan.png) !important;}
.zoomtomaxextent{background-image:url(img/zoom-to-maxextent.png) !important;}
.info{background-image:url(img/information.png) !important;}
.infocircle{background-image:url(img/information-c.png) !important;}
.infopoint{background-image:url(img/information-p.png) !important;}
.panel-body .table{background-image:url(img/information-t.png) !important;}
.idx-button .table{background-image:url(img/information-t.png) !important;}
.removeAll{background-image:url(img/removeall.png) !important;}
.permalink{background-image:url(img/permalink.png) !important;}
.auth{background-image:url(img/user.png) !important;}
.tshare{background-image:url(img/twitter.png) !important;}
.fshare{background-image:url(img/facebook.png) !important;}
.dist{background-image:url(img/mesure-distance.png) !important;}
.area{background-image:url(img/mesure-area.png) !important;}
.print{background-image:url(img/print.png) !important;}
.geoloc {background-image:url(img/geolocate.png) !important;}
.track {background-image:url(img/position.png) !important;}
.edit-point {background-image:url(img/edit-point.png) !important;}
.edit-line {background-image:url(img/edit-line.png) !important;}
.edit-polygon {background-image:url(img/edit-polygon.png) !important;}
.delete-feature {background-image:url(img/delete-feature.png) !important;}
.select {background-image:url(img/select.png) !important;}
.buffer {background-image:url(img/buffer.png) !important;}
.centroid {background-image:url(img/centroid.png) !important;}
.boundary {background-image:url(img/boundary.png) !important;}
.convexhull {background-image:url(img/convexhull.png) !important;}
.simplify {background-image:url(img/simplify.png) !important;}
.union {background-image:url(img/union.png) !important;}
.intersection {background-image:url(img/intersection.png) !important;}
.symdifference {background-image:url(img/symdifference.png) !important;}
.difference {background-image:url(img/difference.png) !important;}
.raster-histogram {border:1px solid #8f8f8f;background-image:url(img/raster-histogram.png) !important;}
.clip-raster {border:1px solid #8f8f8f;background-image:url(img/clip-layer.png) !important;}
.merge-rasters {border:1px solid #8f8f8f;background-image:url(img/merge-layer.png) !important;}
.polygons-from-raster {border:1px solid #8f8f8f;background-image:url(img/polygons-from-raster.png) !important;}
.raster-from-csv {border:1px solid #8f8f8f;background-image:url(img/raster-from-csv.png) !important;}
.star {background-image:url(img/star-unselected.png) !important;}
.star-enabled {background-image:url(img/star-selected.png) !important;}
.terrain-profile {background-image:url(img/terrain-profile.png) !important;}
.contours-from-dem {border:1px solid #8f8f8f;background-image:url(img/contours-from-dem.png) !important;}
.shaded-relief {border:1px solid #8f8f8f;background-image:url(img/shaded-relief.png) !important;}
.color-relief {border:1px solid #8f8f8f;background-image:url(img/color-relief.png) !important;}
.slope-map {border:1px solid #8f8f8f;background-image:url(img/slope-map.png) !important;}
.tipsy {margin:3px 5px;padding: 5px; font-size: .8em; position:absolute; z-index: 1000;color:#707070;}
.tipsy-inner {
z-index:10000;
padding: 5px 8px 4px 8px;
background:-webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#e0e0e0)); /* for webkit browsers */
background:-moz-linear-gradient(top, #ffffff, #e0e0e0); /* for firefox 3.6+ */
text-shadow: 0 1px 0 rgba(255, 255, 255, .8);color: #777777; text-align: center;
border:1px solid #bfbfbf;
border-radius: 3px; -moz-border-radius:3px; -webkit-border-radius:3px;
}
/* avoid pink tiles */
.olImageLoadError {
border: none !important;
background: #FFFFFF !important;
background-color: #FFFFFF !important;
}
div.ui-dialog {
background:#E0E0E0;
border:0;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e0e0e0'); /* for IE */
background:-webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#e0e0e0)); /* for webkit browsers */
background:-moz-linear-gradient(top, #ffffff, #e0e0e0); /* for firefox 3.6+ */padding:0;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
zoom: 1;
}
.ui-dialog .ui-dialog-titlebar {
background:transparent;
position: relative;
font-size:.8em;
color:#808080;
text-shadow:#FFFFFF 0 1px 0;
border:0;
margin:0;
}
.ui-dialog .ui-dialog-content{
padding:0;
margin:0;
font-size:.7em;
color:#808080;
}
.olControlLoadingPanel {
display:none;
}
.ui-progress-bar {
/* Usual setup stuff */
margin:15px;
height: 15px;
width:150px;
/* Pad right so we don't cover the borders when fully progressed */
padding-right: 2px;
/* For browser that don't support gradients, we'll set a blanket background colour */
background-color: #abb2bc;
/* Rounds the ends, we specify an excessive amount to make sure they are completely rounded */
/* Adjust to your liking, and don't forget to adjust to the same amount in .ui-progress */
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
/* Webkit background gradient */
background: -webkit-gradient(linear, left bottom, left top, color-stop(0, #b6bcc6), color-stop(1, #9da5b0));
/* Mozilla background gradient */
background: -moz-linear-gradient(#9da5b0 0%, #b6bcc6 100%);
/* Give it the inset look by adding some shadows and highlights */
-webkit-box-shadow: inset 0px 1px 2px 0px rgba(, 0, 0, 0.5), 0px 1px 0px 0px #565656;
-moz-box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #565656;
box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #565656;
}
/* Progress part of the progress bar */
.ui-progress {
/* Usual setup stuff */
position: relative;
display: block;
overflow: hidden;
/* Height should be 2px less than .ui-progress-bar so as to not cover borders and give it a look of being inset */
height: 13px;
/* Rounds the ends, we specify an excessive amount to make sure they are completely rounded */
/* Adjust to your liking, and don't forget to adjust to the same amount in .ui-progress-bar */
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
/* Set the background size so the stripes work correctly */
-webkit-background-size: 24px 24px; /* Webkit */
/* For browser that don't support gradients, we'll set a blanket background colour */
background-color: #74d04c;
/* Webkit background stripes and gradient */
background: -webkit-gradient(linear, 0 0, 24 24,
color-stop(0.00, rgba(255,255,255,0.17)),
color-stop(0.25, rgba(255,255,255,0.17)),
color-stop(0.26, rgba(255,255,255,0)),
color-stop(0.50, rgba(255,255,255,0)),
color-stop(0.51, rgba(255,255,255,0.17)),
color-stop(0.75, rgba(255,255,255,0.17)),
color-stop(0.76, rgba(255,255,255,0)),
color-stop(1.00, rgba(255,255,255,0))
), -webkit-gradient(linear, left bottom, left top, color-stop(0, #8ad148), color-stop(1, #4bbf30));
/* Mozilla (Firefox etc) background stripes */
/* Note: Mozilla's support for gradients is more true to the original design, allowing gradients at 30 degrees, as apposed to 45 degress in webkit. */
background: -moz-repeating-linear-gradient(top left -30deg,
rgba(255,255,255,0.17),
rgba(255,255,255,0.17) 5px,
rgba(255,255,255,0) 5px,
rgba(255,255,255,0) 10px
), -moz-linear-gradient(#8ad148 0%, #4bbf30 100%);
/* Webkit embossing */
-webkit-box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
/* Mozilla embossing */
-moz-box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
/* IE9 and Opera embossing */
box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
/* Give it a higher contrast outline */
border: 1px solid #4c8932;
/* Webkit magic */
-webkit-animation: animate-stripes 2s linear infinite;
/* TODO: Wait for Mozilla to support animation, then implement */
}
/* Progress indicator text */
.ui-progress span.ui-label {
font-size: 0.7em;
position: absolute;
right: 0;
line-height: 13px;
padding-right: 3px;
color: rgba(0,0,0,0.6);
text-shadow: rgba(255,255,255, 0.45) 0 1px 0px;
white-space: nowrap;
}
.olLayerGoogleV3 {display:none;}
/* Popup formatting */
.olPopupCloseBox {
background: url("img/close.gif") no-repeat;
cursor: pointer;
padding:0;
}
.olFramedCloudPopupContent {padding:0;overflow: auto;}
.olFramedCloudPopupContent h1 {font-size:1em;color:#555555;margin:0;padding:0;}
.olFramedCloudPopupContent h2 {font-size:.9em;color:#777777;margin:0;padding:0;}
.olFramedCloudPopupContent h3 {font-size:.8em;color:#707070;margin:0;padding:0;}
.olFramedCloudPopupContent p {font-size:.8em;color:#707070;margin:0;padding:0;}
.olFramedCloudPopupContent a, .olFramedCloudPopupContent a:visited, {color:#707070;text-decoration:none;outline:none;}
.olFramedCloudPopupContent a:hover {text-decoration:underline;color:#60c63c;}
.olFramedCloudPopupContent img {max-width:400px;max-height:300px;border:0;}
div.popup ui-widget-header{color:#FF0000;}
div.popup table{font-size:.8em;margin:0;padding:0;color:#707070;}
#output-lenght, #output-area{margin-left:10px;}
#print-window table{width:230px;}
#print-window table td.lab{max-width:110px;width:110px;font-size:.8em;color:#333333;}
#print-window table td.inp{padding-left:10px;}
#print-options{width:170px;display:inline;}
#dlg-buttons{margin:0 10px 0 0;}
.window {
position:absolute;
overflow:hidden;
background: -moz-linear-gradient(top, #f4f4f4, #d0d0d0);
background: -webkit-gradient(linear, left top, left bottom, from(#f4f4f4), to(#d0d0d0));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='f4f4f4', endColorstr='#d0d0d0');
padding:5px;
border:1px solid #D0D0D0;
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius: 5px;
z-index:1000;
}
.window-shadow{
position:absolute;
background:#ddd;
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius: 5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
box-shadow:2px 2px 3px rgba(0, 0, 0, 0.2);
}
.window .window-header{
background:transparent;
padding:2px 0px 4px 0px;
}
.window .window-body{
background:#fff;
border:1px solid #B6B6B6;
border-top-width:0px;
padding:0;
}
.window .window-header .panel-icon{
left:1px;
top:1px;
}
.window .window-header .panel-with-icon{
padding-left:18px;
}
.window .window-header .panel-tool{
top:0px;
right:1px;
}
.window-proxy{
position:absolute;
overflow:hidden;
border:1px dashed #15428b;
}
.window-proxy-mask{
position:absolute;
background:#fafafa;
filter:alpha(opacity=10);
opacity:0.10;
}
.window-mask{
position:absolute;
left:0;
top:0;
width:100%;
height:100%;
filter:alpha(opacity=40);
opacity:0.40;
background:#ccc;
display1:none;
font-size:1px;
*zoom:1;
overflow:hidden;
}
.panel{
overflow:hidden;
font-size:12px;
z-index:1000;
}
.panel-header{
padding:5px;
line-height:15px;
font-size:1.1em;
color:#808080;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
font-weight:bold;
font-size:1em;
background:url('img/panel_title.png') repeat-x;
position:relative;
border:1px solid #B6B6B6;
}
.panel-header-noborder{
border-width:0px;
border-bottom:1px solid #909090;
}
.panel-body{
overflow:auto;
border:1px solid #99BBE8;
border-top-width:0px;
}
.panel-body-noheader{
border-top-width:1px;
}
.panel-body-noborder{
border-width:0px;
}
.panel-with-icon{
padding-left:18px;
}
.panel-icon{
position:absolute;
left:5px;
top:4px;
width:16px;
height:16px;
}
.panel-title{
color: #808080 !important;
font-size: 1.1em;
font-weight: bold;
line-height: 15px;
text-shadow: 0 2px 0 #FFFFFF !important;
cursor: pointer;
}
.panel-tool{
position:absolute;
right:5px;
top:4px;
}
.panel-tool div,.panel-tool a{
display:block;
float:right;
width:16px;
height:16px;
margin-left:2px;
cursor:pointer;
opacity:0.6;
filter:alpha(opacity=60);
}
.panel-tool a{
float: left;
}
.panel-tool div.panel-tool-over{
opacity:1;
filter:alpha(opacity=100);
}
.panel-tool-close{
background:url('img/panel_tools.gif') no-repeat -16px 0px;
}
.panel-tool-min{
background:url('img/panel_tools.gif') no-repeat 0px 0px;
}
.panel-tool-max{
background:url('img/panel_tools.gif') no-repeat 0px -16px;
}
.panel-tool-restore{
background:url('img/panel_tools.gif') no-repeat -16px -16px;
}
.panel-tool-collapse{
background:url('img/panel_tool_collapse.gif') no-repeat;
}
.panel-tool-expand{
background:url('img/panel_tool_expand.gif') no-repeat;
}
.panel-loading{
padding:11px 0px 10px 30px;
background:url('img/panel_loading.gif') no-repeat 10px 10px;
}
a.l-btn{
float:right;
color:#333333;
background: -moz-linear-gradient(top, #e2e2e2, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E2E2E2', endColorstr='#B6B6B6');
font-size:12px;
text-decoration:none;
display:inline-block;
zoom:1;
height:24px;
padding-right:18px;
cursor:pointer;
outline:none;
margin:15px 0 5px 5px;
-moz-border-radius:4px;
border-radius:4px;
-webkit-border-radius:4px;
text-shadow: #FFFFFF 0px 1px 0px;
}
a.l-btn:hover{
color:#FFFFFF;
text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F'); /* for IE */
}
a.l-btn-plain{
background:transparent;
padding-right:5px;
border:1px solid transparent;
_border:0px solid #efefef;
_padding:1px 6px 1px 1px;
}
a.l-btn-disabled{
color:#ccc;
opacity:0.5;
filter:alpha(opacity=50);
cursor:default;
}
a.l-btn span.l-btn-left{
display:inline-block;
padding:4px 0px 4px 18px;
line-height:16px;
height:16px;
-moz-border-radius:4px;
border-radius:4px;
-webkit-border-radius:4px;
}
a.l-btn-plain span.l-btn-left{
background:transparent;
padding-left:5px;
}
a.l-btn span span.l-btn-text{
display:inline-block;
height:16px;
line-height:16px;
padding:0px;
}
a.l-btn span span span.l-btn-empty{
display:inline-block;
padding:0px;
width:16px;
}
a:hover.l-btn{
background-position: bottom right;
outline:none;
}
a:hover.l-btn span.l-btn-left{
background-position: bottom left;
}
a:hover.l-btn-plain{
border:1px solid #7eabcd;
background:url('img/button_plain_hover.png') repeat-x left bottom;
_padding:0px 5px 0px 0px;
-moz-border-radius:3px;
-webkit-border-radius: 3px;
}
a:hover.l-btn-disabled{
background-position:top right;
}
a:hover.l-btn-disabled span.l-btn-left{
background-position:top left;
}
.tree{
font-size:.8em;
margin:10px 0 0 10px;
color:#565656;
padding:0;
list-style-type:none;
}
.tree li{
white-space:nowrap;
font-size:.95em;
color:#333333;
font-weight:bold;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
}
.tree li ul{
list-style-type:none;
margin:0;
padding:0;
}
.tree li ul li{
font-size:1em;
color:#565656;
font-weight:normal;
text-shadow: none;
}
.tree-node{
height:18px;
padding: 5px 0 3px 0;
white-space:nowrap;
cursor:pointer;
}
.tree-indent{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-hit{
cursor:pointer;
}
.tree-expanded{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
background:url('./img/tree_arrows.png') no-repeat -18px 0px;
}
.tree-expanded-hover{
background:url('./img/tree_arrows.png') no-repeat -50px 0px;
}
.tree-collapsed{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
background:url('./img/tree_arrows.png') no-repeat 0px 0px;
}
.tree-collapsed-hover{
background:url('./img/tree_arrows.png') no-repeat -32px 0px;
}
.tree-folder{
display:inline-block;
background:url('./img/tree_folder.png') no-repeat;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-folder-open{
background:url('./img/tree_folder_open.png') no-repeat;
}
.tree-file{
display:inline-block;
background:url('./img/tree_file.png') no-repeat;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-loading{
background:url('./img/tree_loading.gif') no-repeat;
}
.tree-title{
display:inline-block;
text-decoration:none;
vertical-align:middle;
padding:1px 2px 1px 2px;
white-space:nowrap;
}
.tree-node-hover{
background:#ffffff;
background: -moz-linear-gradient(top, #FFFFFF, #eaeaea);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#eaeaea));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#EAEAEA'); /* for IE */
}
.tree-node-selected{
background:#ffffff;
background: -moz-linear-gradient(top, #FFFFFF, #eaeaea);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#eaeaea));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#EAEAEA'); /* for IE */
}
.tree-checkbox{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-checkbox0{
background:url('./img/tree_checkbox_0.png') no-repeat;
}
.tree-checkbox1{
background:url('./img/tree_checkbox_1.png') no-repeat;
}
.tree-checkbox2{
background:url('./img/tree_checkbox_2.png') no-repeat;
}
.tree-node-proxy{
font-size:12px;
padding:1px 2px 1px 18px;
background:#fafafa;
border:1px solid #ccc;
z-index:1000;
}
.tree-dnd-yes{
background:url('./img/tree_dnd_yes.png') no-repeat 0 center;
}
.tree-dnd-no{
background:url('./img/tree_dnd_no.png') no-repeat 0 center;
}
.tree-node-top{
border-top:1px dotted red;
}
.tree-node-bottom{
border-bottom:1px dotted red;
}
.tree-node-append .tree-title{
border:1px dotted red;
}
.tree-editor{
border:1px solid #ccc;
font-size:12px;
line-height:16px;
width:80px;
position:absolute;
top:0;
}
.menu, .emenu{
position:absolute;
background:#f0f0f0 url('./img/menu.gif') repeat-y;
margin:0;
padding:2px;
border:1px solid #ccc;
overflow:hidden;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
.menu-item{
position:relative;
margin:0;
padding:0;
height:22px;
line-height:20px;
overflow:hidden;
font-size:.8em;
color:#565656;
cursor:pointer;
border:1px solid transparent;
_border:1px solid #f0f0f0;
}
.menu-text{
position:absolute;
left:28px;
top:0px;
}
.menu-icon{
position:absolute;
width:16px;
height:16px;
top:3px;
left:2px;
}
.menu-rightarrow{
position: absolute;
width:4px;
height:7px;
top:7px;
right:5px;
background:url('./img/menu_rightarrow.png') no-repeat;
}
.menu-sep{
margin:3px 0px 3px 24px;
line-height:2px;
font-size:2px;
background:url('./img/menu_sep.png') repeat-x;
}
.menu-active{
border:1px solid #ADEF73;
background:#fafafa;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
.menu-shadow{
position:absolute;
background:#ddd;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
}
#layers_list{
height: 266px;
overflow-y: auto;
position:relative;
top:4px;
left:7px;
width:98%;}
.pDiv2{display:block;}
.flexigrid div.mDiv div.zoomToSetExtent {
position: absolute;
top: 4px;
right: 24px;
padding: 0px;
height: 16px;
width: 16px;
overflow: hidden;
background:url(./img/magnifier.png);
border: 1px solid #ccc;
cursor: pointer;
}
.flexigrid div.mDiv div.zoomToSetExtent:hover {
background: #FFFFFF url(./img/magnifier-hover.png);
border-color: #9a9a9a;
}
#pm{
z-index:1000;
}
.pGroup .toolbar-noborder .fg-button{
margin: 0 0 5px 5px;
padding: 0;
}
#search-container{
position:absolute;
left: 50%;
margin-left: -130px;
top: 10px;
width:260px;max-width:260px;
height:58px;background:transparent; z-index:1000; overflow: hidden;display:block;
}
#search-container p{
font-size:14px;
padding:0;
font-weight:normal;
margin: 5px 0 0 5px;
color:#FFFFFF;
text-transform:uppercase;
text-align:center;
text-shadow:#707070 0 1px 0;
}
#search-container select{
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff'); /* for IE */
border:1px solid #9f9f9f;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
padding:1px;
font-size:0.8em;
margin:5px 0 0 5px;
width:120px;
max-width:120px;
}
.sfield{display:inline;margin:5px 0 0 0;width:120px;max-width:120px;height:17px;vertical-align:top;font-size:0.75em;}
.ui-autocomplete{max-height:200px;overflow-y:auto;z-index:1000;}
.ui-widget {
font-family: Lucida Grande, Verdana,Arial,sans-serif;
font-size: 0.75em;
}
.nodisplay{
text-decoration:line-through;
color:#707070;
opacity:0.7;
}
.nodisplay span{
text-decoration:line-through;
color:#707070;
}
.well-table{
margin-bottom:0;
padding: 10px 18px;
background: #fff;
border-top: none;
}
<|start_filename|>mapmint-ui/new-themes/themes/default/settings.css<|end_filename|>
/*
* MapMint Settings CSS
*/
.admin{
position:absolute;
top:30px;
right:20px;
display:block;
margin:0;
background:transparent;
z-index:1000 !important;
}
.sets{position:absolute;top:15px;right:0;
-moz-box-shadow:
0px 1px 3px rgba(000,000,000,0.3),
inset 0px 0px 2px rgba(255,255,255,1);
-webkit-box-shadow:
0px 1px 3px rgba(000,000,000,0.3),
inset 0px 0px 2px rgba(255,255,255,1);
box-shadow:
0px 1px 3px rgba(000,000,000,0.3),
inset 0px 0px 2px rgba(255,255,255,1);
}
ul.sets {width:200px;list-style:none;margin:10px 0 0 0;padding:0;background:#FFFFFF;border-radius:5px;padding:10px;z-index:1000000 !important;}
ul.sets li{display:block;margin:7px 0 0 0;text-indent:28px;border-bottom:1px dotted #E9E9E9;line-height:24px;}
ul.sets li a{color:#A7A7A7;text-decoration:none;font-size:.85em;}
ul.sets li a:hover{color:#707070 !important;text-decoration:none;}
ul.sets li.sett{background:url(../img/user-settings.png) no-repeat;}
ul.sets li.user{background:url(../img/user-management.png) no-repeat;}
ul.sets li.home{background:url(../img/hpage.png) no-repeat;}
ul.sets li.logt{background:url(../img/logout.png) no-repeat;}
.ad{
color:#707070;
margin:0;
padding:0;
background: transparent;
font-size:14px;
font-weight:normal;
font-weight:bold;
text-shadow: #FFFFFF 0px 2px 0px;
text-align:right;
cursor:pointer;
text-decoration:none;
}
.adh{color:red;}
.sub{
box-shadow: 5px 5px 5px #626262; /* CSS3 */
-moz-box-shadow: 5px 5px 5px #626262; /* Firefox */
-webkit-box-shadow: 5px 5px 5px #626262; /* Safari, Chrome */
}
ul li .sub {
position:absolute;top:60px;right:0;
background: #808080;
padding: 0 0 10px 10px;
-moz-border-radius-bottomleft: 5px;
-khtml-border-radius-bottomleft: 5px;
-webkit-border-bottom-left-radius: 5px;
behavior: url(js/ie-css3.htc);
display: none;
color:#333333;
min-width:20%;
}
ul li .row {clear: both; float: left; width: 100%; margin-bottom: 10px;}
ul li .sub ul{
list-style: none;
margin: 0;
padding: 0;
width: 90px;
float: left;
}
ul .sub ul li {
width: 100%;
color: #fff;
}
.sub ul li a {
float: none;
text-indent: 0; /*--Reset text indent--*/
height: auto;
padding: 7px 5px 7px 0;
font-size:.7em;
display: block;
text-decoration: none;
color: #767676;
}
.sub ul li a:hover {color: #b3b3b3;}
/*
* Themes bar
*/
.theme-bar{width:100%;float:left;}
.theme-bar a{display:inline;}
.theme-bar-pub a{display:inline;}
input.th{float:left;margin:0;text-indent:none;}
.green{
float:left;
width:24px;
height:24px;
margin:0 5px 0 10px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.blue{
float:left;
width:24px;
height:24px;
margin:0 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#44d0e5', endColorstr='#398ee4'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#44d0e5), to(#398ee4)); /* for webkit browsers */
background: -moz-linear-gradient(top, #44d0e5, #398ee4 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.purple{
float:left;
width:24px;
height:24px;
margin:0 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#c743f8', endColorstr='#8340f3'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#c743f8), to(#8340f3)); /* for webkit browsers */
background: -moz-linear-gradient(top, #c743f8, #8340f3 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.pink{
float:left;
width:24px;
height:24px;
margin:0 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f869ec', endColorstr='#f630f8'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#f869ec), to(#f630f8)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
<|start_filename|>mapmint-ui/templates/preview/modules/indexes/list.html<|end_filename|>
#import zoo
#import authenticate.service as auth
#set con=auth.getCon($conf)
#set prefix=auth.getPrefix($conf)
#set c=con.connect()
#set conn = con.conn
#set cur=conn.cursor()
#set clause=""
#for i in $conf["senv"]["group"].split(",")
#if clause!=""
#set $clause+=" or "
#end if
#set $clause+=" name = '"+$i+"' "
#end for
#set res=cur.execute('SELECT id,name from '+$prefix+'indicators where id in (select i_id from '+$prefix+'indicators_groups where g_id in (select id from '+prefix+'groups where name=\'public\' or '+$clause+')) order by id desc LIMIT 4')
#set vals=cur.fetchall()
<h3 class="idx">$zoo._("Indicators")</h2>
<ul>
#for i in range(0,len(vals))
<li><a onclick="\$('#index_id').val($vals[i][0]);setCurrentIndex();displayIndexPage();" href="#indicateur_$vals[i][0]">$vals[i][1]</a>
<div class="starc" id="vote_$vals[i][0]"></div></li>
#end for
</ul>
<div class="bottom-btm">
<a href="#indicateurs" class="indx mbutt more">Tout les indicateurs</a>
</div>
<|start_filename|>public_map/assets/js/build/build.js<|end_filename|>
({
baseUrl: ".",
paths: {
jquery: "../lib/jquery/jquery-2.1.3"
},
name: "zoo",
out: "zoo-built.js"
})
<|start_filename|>public_map/mapmint-largemap.css<|end_filename|>
/*
* PANES & CONTENT-DIVs
*/
.ui-layout-pane { /* all 'panes' */
background: transparent;
border: 0;
/* DO NOT add scrolling (or padding) to 'panes' that have a content-div,
otherwise you may get double-scrollbars - on the pane AND on the content-div
*/
padding: 0;
overflow: auto;
}
/* (scrolling) content-div inside pane allows for fixed header(s) and/or footer(s) */
.ui-layout-content {
padding: 0;
position: relative; /* contain floated or positioned elements */
overflow: auto; /* add scrolling to content-div */
}
/*
* RESIZER-BARS
*/
.ui-layout-resizer { /* all 'resizer-bars' */
background: #DDD;
border: 0;
border-width: 0;
}
.ui-layout-resizer-drag { /* REAL resizer while resize in progress */
}
.ui-layout-resizer-hover { /* affects both open and closed states */
}
/* NOTE: It looks best when 'hover' and 'dragging' are set to the same color,
otherwise color shifts while dragging when bar can't keep up with mouse */
.ui-layout-resizer-open-hover , /* hover-color to 'resize' */
.ui-layout-resizer-dragging { /* resizer beging 'dragging' */
background: #C4E1A4;
}
.ui-layout-resizer-dragging { /* CLONED resizer being dragged */
border-left: 0;
border-right: 0;
}
/* NOTE: Add a 'dragging-limit' color to provide visual feedback when resizer hits min/max size limits */
.ui-layout-resizer-dragging-limit { /* CLONED resizer at min or max size-limit */
background: #E1A4A4; /* red */
}
.ui-layout-resizer-closed-hover { /* hover-color to 'slide open' */
background: #EBD5AA;
}
.ui-layout-resizer-sliding { /* resizer when pane is 'slid open' */
opacity: .10; /* show only a slight shadow */
filter: alpha(opacity=10);
}
.ui-layout-resizer-sliding-hover { /* sliding resizer - hover */
opacity: 1.00; /* on-hover, show the resizer-bar normally */
filter: alpha(opacity=100);
}
/* sliding resizer - add 'outside-border' to resizer on-hover
* this sample illustrates how to target specific panes and states */
.ui-layout-resizer-north-sliding-hover { border-bottom-width: 1px; }
.ui-layout-resizer-south-sliding-hover { border-top-width: 1px; }
.ui-layout-resizer-west-sliding-hover { border-right-width: 1px; }
.ui-layout-resizer-east-sliding-hover { border-left-width: 1px; }
/*
* TOGGLER-BUTTONS
*/
.ui-layout-toggler {
border: 0; /* match pane-border */
background-color: #BBB;
}
.ui-layout-resizer-hover .ui-layout-toggler {
opacity: .60;
filter: alpha(opacity=60);
}
.ui-layout-toggler-hover , /* need when NOT resizable */
.ui-layout-resizer-hover .ui-layout-toggler-hover { /* need specificity when IS resizable */
background-color: #FC6;
opacity: 1.00;
filter: alpha(opacity=100);
}
.ui-layout-toggler-north ,
.ui-layout-toggler-south {
border-width: 0 1px; /* left/right borders */
}
.ui-layout-toggler-west ,
.ui-layout-toggler-east {
border-width: 1px 0; /* top/bottom borders */
}
/* hide the toggler-button when the pane is 'slid open' */
.ui-layout-resizer-sliding ui-layout-toggler {
display: none;
}
/*
* style the text we put INSIDE the togglers
*/
.ui-layout-toggler .content {
color: #666;
font-size: 12px;
font-weight: bold;
width: 100%;
padding-bottom: 0.35ex; /* to 'vertically center' text inside text-span */
}
.ui-layout-north{
padding: 0;
background:#83c849;
width:100%;
overflow:hidden;
height:90px;
}
.ui-layout-north img{float:left;margin:15px 0 0 20px;display:inline-block;}
.ui-layout-north h1{font-size:1.4em;margin:0;padding:5px;color:#FFFFFF;position:relative;top:5px;left:17px;line-height:1.3em;}
.ui-layout-west {
padding:0;
background:#FFFFFF;
}
.ui-layout-south{
padding: 0;
width:100%;
overflow:hidden;
max-height:40px;
height:40px;
background: transparent url('img/bcknav.png');
}
.ui-layout-south img {
border:0;
position:relative;
top:10px;
left:0;
}
#swc{display:none !important;}
#coords{float:left;padding:0 5px 0 0;color:#FFFFFF;font-size:.8em;text-shadow:#333333 0 1px 0;display:inline;position:absolute;right:50px;bottom:15px;}
div#map{width:100%;height:100%;margin:0;padding:0;}
div#ls-container{position:absolute;right:15px;top:0;width:auto;z-index:1000;}
div#ls-container table{position:absolute;top:110px;left:100px;margin:0;padding:0;width:160px;}
div#ls-container table td.sli{width:100px;}
#layers_list{
position:relative;
top:20px !important;
}
a.ls-toogler{float:right;background:#FFFFFF url('img/layers-icon.png') no-repeat;background-position:4px 3px;width:24px;height:24px;position:absolute;bottom:15px;right:15px;margin:0;z-index:1000;}
a.ls-toogler:hover{background:#EDEDED url('img/layers-icon.png') no-repeat;background-position:4px 3px;width:24px;height:24px;}
div#layerswitcher {background:url('img/bckw.png'); z-index:1000; overflow: hidden;display:block;}
.nav{position:absolute;top:0 !important;left:10px !important;width:auto;display:block;}
.fg-toolbar {
z-index:1000000000000;
position:relative;
top:10px;
left:6px;
width:auto;
max-width:500px;
padding:0;
margin:0;
display:block;
}
#loading{
position: absolute;
top: 10px;
left: 120px;
width:auto;
height:auto;
background:url('img/bckw.png');
text-align: left;
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
display:none;
z-index:1000000;
font-size: 11px;
color:#707070;
}
#loading ul{
list-style: none;
margin: 0;
padding: 1em;
}
<|start_filename|>public_map/mapmint-fullscreen.css<|end_filename|>
div#map{width:100%;height:100%;margin:0;padding:0;}
div#header {
position:absolute; top:15px; left:15px;width:auto;min-width:380px; height:82px;background: #83c849; z-index:1000; overflow: hidden;display:block;
-moz-border-radius:5px;
-webkit-border-radius:5px;
behavior: url(./border-radius.htc);
border-radius:5px;
}
div#header img{float:left;margin:12px 0 0 15px;display:inline-block;}
div#header h1{font-size:1.4em;margin:0;padding:5px;color:#FFFFFF;position:relative;top:3px;left:20px;line-height:1.3em;}
.fg-toolbar {
z-index:1000;
position:relative;
top:0;
left:10px;
width:100%;
height:45px;
padding:0;
margin:0;
}
.nav{position:absolute;top:32px;left:85px !important;width:auto;display:block;}
div.olControlMMPanZoom {
top: 125px !important;
left:15px;
display: block;
position: absolute;
}
div#ls-container{position:absolute;top:10px; right:10px;width:auto;z-index:1000;}
div#ls-container table.slid{position:absolute;top:110px;left:100px;margin:0;padding:0;width:160px;}
div#ls-container table td.sli{width:100px;}
#search-container{
position:absolute;
left: 50%;
margin-left: -130px;
top: 10px;
width:260px;max-width:260px;
height:82px;background: transparent url('img/bckm.png'); z-index:1000; overflow: hidden;display:block;
border-radius:5px;}
#search-container p{margin:10px 0 10px 0;}
#coords{float:left;padding:0 5px 0 0;color:#FFFFFF;font-size:.8em;text-shadow:#000000 0 1px 0;display:inline;position:absolute;right:70px !important;bottom:16px;}
#loading{
position: absolute;
top: 100px;
left: 120px;
width:auto;
height:auto;
background:url('img/bckw.png');
text-align: left;
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
display:none;
z-index:100000000;
font-size: 11px;
color:#707070;
}
#loading ul{
list-style: none;
margin: 0;
padding: 1em;
}
ul.ui-autocomplete{overflow:auto;max-height:300px;}
<|start_filename|>mapmint-ui/js/Graphs.js<|end_filename|>
function refreshGraphFields(){
var prefix="";
var vars="";
if(arguments.length>0){
prefix=arguments[0];
vars=";tid="+$("#p_tname").val();
}
if($("#graphs_steps").is(":visible") && $("#graphs_step").val()>0)
vars+=";step="+($("#graphs_step")[0].selectedIndex-1);
var tableName_G="indicateurs";
tableNameG=prefix+"graphs";
$("#graphs_id").val("");
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.details&DataInputs=table="+tableName_G+";id="+System.nodeId+vars+";tab=graph&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
try{
try{
if(System.refreshSteps)
addSteps(tableNameG+"_step");
System.refreshSteps=true;
}catch(e){}
var data=$.parseJSON(xml.responseText);
for(var i in data){
if(!$.isArray(data[i])){
if(i=="name")
$("#"+tableNameG+"_"+i+"_title").html(data[i]);
if(data[i]!=null){
if(i!="step")
$("#"+tableNameG+"_"+i).val(data[i]);
else
$("#"+tableNameG+"_"+i+" > option")[data[i]+1].selected=true;
}
else{
if($("#"+tableNameG+"_"+i).length>0 && $("#"+tableNameG+"_"+i)[0].selectedIndex)
$("#"+tableNameG+"_"+i).val(-1);
else
$("#"+tableNameG+"_"+i).val("");
}
}else{
$("#"+tableNameG+"_"+i+" option:selected").removeAttr("selected");
if(data[i].length)
for(var j=0;j<data[i].length;j++)
$("#"+tableNameG+"_"+i+' option[value="'+data[i][j]+'"]').attr("selected", "selected");
else
$('#'+tableNameG+'_'+i+' option[value="-1"]').attr("selected", "selected");
}
}
}catch(e){alert("Error : "+e);}
try{
$(".toolbar2").find("a.chart").each(function(){
$(this).removeClass("desactivated");
});
$("#"+prefix+"chart").find(".loader-container").each(function(){
$(this).hide();
});
}catch(e){}
if(System.doOnGraphLoad){
System.doOnGraphLoad();
System.doOnGraphLoad=null;
}
System.refreshSteps=true;
}
}
});
}
function refreshGraph(){
if(!System.limit)
System.limit=0;
var res=System.ffeatures;
if(res && res.featureMember)
if(!res.featureMember.length)
res.featureMember=[res.featureMember];
filter="<Filter><OR>"
if(res && res.featureMember){
for(var j=0;j<res.featureMember.length;j++){
var feature=res.featureMember[j];
filter+="<PropertyIsLike wildcard='*' singleChar='.' escape='!'><PropertyName>"+System.full_index["indicateurs_territoires_key"]+"</PropertyName><Literal>"+feature[System.full_index["indicateurs_territoires_key"]]+"</Literal></PropertyIsLike>"
}
}
filter+="</OR></Filter>";
var node=(arguments.length==0 || arguments[0]=="agregate_"?$("#ltree").tree("getSelected"):{id:arguments[0]});
System.nodeId=node.id;
System.prefix="";
var tblName="indexes.view_idx"+node.id
System.doOnGraphLoad=function(){
var suffix="";
if($("#graphs_steps").is(":visible") && $("#graphs_step").val()>0)
suffix="_step"+($("#graphs_step")[0].selectedIndex-1);
url=System.mapUrl+"?map="+(System.nodeId?System.dataPath+"/indexes_maps/project_"+(System.prefix!=""?"A"+$("#p_tname").val()+"_":"")+"GIndex"+System.nodeId+suffix+".map":System.indexMap)+"&service=WFS&version=1.0.0&request=GetFeature&typename="+tblName+"&PropertyName="+$("#"+System.prefix+"graphs_vx").val()+","+$("#graphs_vy").val()+"&maxfeatures="+(15+System.limit);
data=null;
method="GET";
if(System.cUrl!=null){
url=System.mapUrl+"?map="+(System.nodeId?System.dataPath+"/indexes_maps/project_"+(System.prefix!=""?"A"+$("#p_tname").val()+"_":"")+"GIndex"+System.nodeId+suffix+".map":System.indexMap)
method="POST";
data='<wfs:GetFeature service="WFS" version="1.0.0" outputFormat="GML2" xmlns:wfs="http://www.opengis.net/wfs" maxFeatures="'+(15+System.limit)+'" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd"><wfs:Query typeName="'+tblName+'"><wfs:PropertyName>'+$("#"+System.prefix+"graphs_vx").val()+'</wfs:PropertyName><wfs:PropertyName>'+$("#"+System.prefix+"graphs_vy").val()+'</wfs:PropertyName>'+filter+'</wfs:Query></wfs:GetFeature>';
System.graph_request=url;
}else
System.graph_request=url.replace(/&/g,"&");
System.graph_data=data;
System.graph_method=method;
$.ajax({
type: method,
url: url,
dataType: 'xml',
data: data,
contentType: 'text/xml',
complete: function(xml,status) {
if(this.type=="POST")
System.ffeatures=$.xml2json(xml.responseText);
gml=new OpenLayers.Format.GML();
var o=gml.read(xml.responseText);
var values=new Array();
var categories=new Array();
var pseries=new Array();
for(i in o)
if(o[i].data[$("#graphs_vy").val()]){
/*alert(i);
alert(o[i].data[$("#g_f_x").val()]);*/
//alert(o[i].data[$("#g_f_y").val()]);
values.push(eval(o[i].data[$("#graphs_vy").val()]));
categories.push(o[i].data[$("#"+System.prefix+"graphs_vx").val()]);
pseries.push({"name": o[i].data[$("#"+System.prefix+"graphs_vx").val()],"y":eval(o[i].data[$("#graphs_vy").val()])});
}
if($("#graphs_f_type").val()=="hist")
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: System.prefix+'graphDisplay',
type: 'column',
width:500,
height:350,
margin: [5, 20, 40, 25],
borderRadius: 0,
backgroundColor:'#efedcc'
},
credits: {
enabled: false
},
colors: [
'#72ba37',
'#AA4643',
'#89A54E',
'#80699B',
'#3D96AE',
'#DB843D',
'#92A8CD',
'#A47D7C',
'#B5CA92'
],
title: {
text: $("#graphs_title").val()
},
xAxis: {
categories: categories,
title: {
text: $("#"+System.prefix+"graphs_lx").val()
},
labels: {
rotation: -45,
align: 'right',
style: {
fontSize: '12px',
fontFamily: 'Arial, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: $("#graphs_ly").val()
}
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
if($("#graphs_tooltip").val()=="")
return '<b>'+ this.x +'</b><br/>'+
' '+ Highcharts.numberFormat(this.y, 1) +
' ';
try{
return eval($("#graphs_tooltip").val());
}catch(e){
return '<b>'+ this.x +'</b><br/>'+
' '+ Highcharts.numberFormat(this.y, 1) +
' ';
}
}
},
series: [{
name: 'Value',
pointWidth: 25,
data: values,
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
x: 0,
y: 10,
formatter: function() {
return this.y;
},
style: {
fontSize: '10px',
fontFamily: 'Verdana, sans-serif',
pointWidth: 30}
}
}]
});
});
});
else
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: System.prefix+'graphDisplay',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
borderRadius: 0,
backgroundColor:'#efedcc',
width:500,
height:350
},
title: {
text: $("#graphs_title").val()
},
credits: {
enabled: false
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#707070',
connectorColor: '#a2a2a2',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: $("#graphs_ly").val(),
data: pseries
}]
});
});
});
}
});
}
try{
if(arguments[0]=="agregate_"){
System.prefix="agregate_";
tblName="indexes.agregate_t"+$("#p_tname").val()+"_idx_"+node.id
insertGraph(arguments[0]);
}else{
if(arguments.length>0)
insertGraph(arguments[0]);
else
insertGraph();
}
}catch(e){
// in case insertGraph is not defined (not in admin interface)
System.doOnGraphLoad();
}
}
<|start_filename|>public_map/assets/js/build.js<|end_filename|>
({
baseUrl: ".",
paths: {
jquery: "../lib/jquery/jquery-2.1.3.min"
},
name: "main",
out: "main-built.js"
})
<|start_filename|>mapmint-ui/new-themes/themes/blue/tree.css<|end_filename|>
.tree-node-selected{
background:#3d93df;
background: -moz-linear-gradient(top, #7fe5f9 , #3d93df);
background: -webkit-gradient(linear, left top, left bottom, from(#7fe5f9), to(#3d93df));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#7fe5f9', endColorstr='#3d93df');
}
.menu-active{
border:1px solid #81dbf9;
background:#fafafa;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
<|start_filename|>mapmint-ui/js/Territories.js<|end_filename|>
Territories=MLayout.extend();
Territories.define({
id: 0,
layoutOptions: {
contentSelector: ".lcontent",
center__paneSelector: ".inner-center",
west__paneSelector: ".inner-west",
west__size: .28,
west__draggable: false,
west__resizable: false,
west__spacing_closed:10,
west__spacing_open:8,
east__paneSelector: ".inner-east",
east__size: .28,
east__closable: false,
east__draggable: false,
east__resizable: false,
spacing_open: 10,
south__closable: false,
south__closable:false,
south__resizable:false,
south__minSize:40,
//resizeWhileDragging: true,
onopen: function() {updateSize();},
onclose: function() {updateSize();},
onresize: function() {updateSize();}
},
initialize: function(){
this.refresh();
endLoading();
this.id++;
},
refresh: function(){
defaultInit();
}
});
$(document).ready(function () {
$(".add-territory").click(function(){
$("#eName").val("");
$('#add-territory-dialog').window({
width: 300,
height: 150,
left:150,
top:150,
maximizable:false,
minimizable:false,
resizable: false
})
});
$(".view-territory").click(function(){
if($("#territories_dataSource").val()!="-1")
preview();
else
alert("Merci de sélectionner un territoire ayant une données déjà associée");
});
$(".delete-territory").click(function(){
if(System.nodeVal){
$("#edName").val(System.nodeVal);
$('#delete-territory-dialog').window({
width: 300,
height: 150,
left:150,
top:150,
maximizable:false,
minimizable:false,
resizable: false
})
}
});
searchTable("territories");
refreshList();
});
function preview(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.getMapRequest&DataInputs=t_id="+System.nodeId+";preview=true&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
try{
$('#preview-territory-dialog').window({
width: 400,
height: 300,
left:150,
top:150,
maximizable:false,
minimizable:false,
resizable: false
});
$("#t_preview")[0].src=xml.responseText;
}catch(e){
alert(e);
}
}
}
});
}
/**
* Common part
*/
function updateElement(){
var params={id: System.nodeId};
$("#territoires_edition_ui").find("input").each(function(){
params[$(this)[0].id.replace(/territoires_/,"")]=$(this).val();
});
$("#territoires_edition_ui").find("select").each(function(){
if($(this)[0].multiple){
localId=$(this)[0].id.replace(/territoires_/,"");
params[localId]=[];
$(this).find("option:selected").each(function(){
params[localId].push($(this).val());
});
}
else{
params[$(this)[0].id.replace(/territoires_/,"")]=$(this).val();
}
});
params=[
{name: "table", value: "territories",dataType: "string"},
{name: "territories_groups_in", value: "t_id",dataType: "string"},
{name: "territories_groups_out", value: "g_id",dataType: "string"},
{name: "t_hierarchy_in", value: "o_t_id",dataType: "string"},
{name: "t_hierarchy_out", value: "p_t_id",dataType: "string"},
{name: "tuple", value: $.stringify(params), mimeType: "application/json"}
];
data=WPSGetHeader("np.updateElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
System.noSelectAgain=true;
refreshList();
}
}
});
}
function refreshDetails(){
$("#territoires_t_hierarchy option:disabled").removeAttr("disabled");
$("#territoires_t_hierarchy option:selected").removeAttr("selected");
$("#territoires_t_hierarchy option[value="+System.nodeId+"]").attr("disabled","disabled");
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.details&DataInputs=table=territories;id="+System.nodeId+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var data=$.parseJSON(xml.responseText);
for(var i in data){
if(!$.isArray(data[i])){
if(i=="name")
$("#territoires_"+i+"_title").html(data[i]);
$("#territoires_"+i).val("");
if(data[i]!=null)
$("#territoires_"+i).val(data[i]);
else
$("#territoires_"+i).val(-1);
}else{
$("#territoires_"+i+" option:selected").removeAttr("selected");
if(data[i].length)
for(var j=0;j<data[i].length;j++)
$("#territoires_"+i+' option[value="'+data[i][j]+'"]').attr("selected", "selected");
else
$('#territoires_'+i+' option[value="-1"]').attr("selected", "selected");
}
}
}
}
});
}
function getCurrentElements(obj){
var res=Array();
for(var i=0;i<obj.length;i++){
res.push({"id":obj[i]["id"],"text":obj[i]["text"]});
if(obj[i].children && obj[i].children.length>0){
var tmp=getCurrentElements(obj[i].children);
for(k=0;k<tmp.length;k++)
res.push({"id":tmp[k]["id"],"text":tmp[k]["text"]});
}
}
return res;
}
function saveOrder(){
nodes=$('#ttlo').tree('getRoots');
var params=new Array({name: "table", value: "territories",dataType: "string"});
for(i=0;i<nodes.length;i++){
params.push({name: "node", value: nodes[i].id, dataType: "string"});
}
data=WPSGetHeader("np.orderElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshList();
$('#view-order').window('close');
}
}
});
}
function setOrder(){
if(!$("#view-order")[0]){
$( "body" ).append('<div id="view-order" title="'+System.messages["Order"]+'"></div>');
}
$("#view-order").html("").append('<ul id="ttlo"></ul><div><input type="button" name="" id="" value="'+System.messages["Save"]+'" onclick="saveOrder()" /></div>');
$.ajax({
type: "GET",
url: "./Territories_order;id="+System.mmNodeId,
complete: function(xml,status) {
var data=$.parseJSON(xml.responseText);;
$('#ttlo').tree({
data: data,
dnd: true
});
$( "#view-order" ).window({
collapsible:false,
minimizable:false,
maximizable:false,
resizable: false
});
}
});
}
function refreshList(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.list&DataInputs=table=territories&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var data=$.parseJSON(xml.responseText);
$('#ltree').tree({
data: data,
onSelect: function(node){
System.nodeId=node.id;
System.nodeVal=node.text;
refreshDetails();
},
onContextMenu: function(e, node){
e.preventDefault();
$('#ltree').tree('select', node.target);
var lnode=$('#ltree').tree('getParent',node.target);
if(lnode)
System.mmNodeId=lnode.id;
else
System.mmNodeId=null;
$('#mm').emenu('show', {
left: e.pageX,
top: e.pageY
});
}
});
var tmp=getCurrentElements(data);
vals={};
orig=Array();
ord=Array();
for(i=0;i<tmp.length;i++){
vals[""+tmp[i]["id"]]=tmp[i]["text"];
orig[i]=tmp[i]["id"];
ord[i]=tmp[i]["id"];
}
ord.sort(function(a,b){return a-b});
$("#territoires_t_hierarchy option[value!='-1']").remove();
for(i=0;i<ord.length;i++){
if(i==0)
$("#territoires_t_hierarchy").append('<option value="'+ord[i]+'">'+vals[ord[i]]+'</option>');
else
if(ord[i]!=ord[i-1])
$("#territoires_t_hierarchy").append('<option value="'+ord[i]+'">'+vals[ord[i]]+'</option>');
}
if(!System.noSelectAgain){
var tmp=$("#ltree").tree('getSelected');
var tmpr=$("#ltree").tree('getRoot');
if(!tmp && tmpr){
$("#ltree").tree('select',tmpr.target);
}
}else{
var node = $('#ltree').tree('find', System.nodeId);
$("#ltree").tree('select',node.target);
}
System.noSelectAgain=false;
}
}
});
}
function deleteElement(){
params=[
{name: "table", value: "territories",dataType: "string"},
{name: "atable", value: "t_hierarchy",dataType: "sting"},
{name: "akey", value: "o_t_id",dataType: "string"},
{name: "atable", value: "territories_groups",dataType: "sting"},
{name: "akey", value: "t_id",dataType: "string"},
{name: "id", value: System.nodeId,dataType: "string"}
];
data=WPSGetHeader("np.deleteElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshList();
$('#delete-territory-dialog').window('close');
}
}
});
}
function insertElement(){
params=[
{name: "table", value: "territories",dataType: "string"},
{name: "name", value: $("#eName").val(),dataType: "string"}
];
data=WPSGetHeader("np.insertElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshList();
$('#add-territory-dialog').window('close');
}
}
});
}
function loadForm(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.details&DataInputs=table=territories;name='+arguments[0]+'&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
}
}
});
}
<|start_filename|>public_map/css/mm_icons.css<|end_filename|>
@font-face {
font-family: 'mapmint';
src:url('../fonts/mapmint.eot');
src:url('../fonts/mapmint.eot') format('embedded-opentype'),
url('../fonts/mapmint.ttf') format('truetype'),
url('../fonts/mapmint.woff') format('woff'),
url('../fonts/mapmint.svg') format('svg');
font-weight: normal;
font-style: normal;
}
.mm {
font-family: 'mapmint';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.br{
font-weight: bold;
}
.mm-postgresql:before {
content: "\e600";
}
.mm-sqlite:before {
content: "\e601";
}
.mm-mysql:before {
content: "\e602";
}
.mm-legend:before {
content: "\e603";
}
.mm-route:before {
content: "\e604";
}
.mm-line:before {
content: "\e605";
}
.mm-elevation-profile:before {
content: "\e606";
}
.mm-mapserver:before {
content: "\e607";
}
.mm-desktop:before {
content: "\e608";
}
.mm-brush:before {
content: "\e609";
}
.mm-cloud:before {
content: "\e60a";
}
.mm-compass:before {
content: "\e60b";
}
.mm-contrast:before {
content: "\e60c";
}
.mm-database:before {
content: "\e60d";
}
.mm-directory-open:before {
content: "\e60e";
}
.mm-directory:before {
content: "\e60f";
}
.mm-gdal:before {
content: "\e610";
}
.mm-geolocation-point:before {
content: "\e611";
}
.mm-geolocation-track:before {
content: "\e612";
}
.mm-geolocation-user:before {
content: "\e613";
}
.mm-geolocation:before {
content: "\e614";
}
.mm-graticule:before {
content: "\e615";
}
.mm-hatch-fill:before {
content: "\e616";
}
.mm-hue:before {
content: "\e617";
}
.mm-identify-box:before {
content: "\e618";
}
.mm-identify-circle:before {
content: "\e619";
}
.mm-identify:before {
content: "\e61a";
}
.mm-label:before {
content: "\e61b";
}
.mm-labels:before {
content: "\e61c";
}
.mm-laptop:before {
content: "\e61d";
}
.mm-layer-add:before {
content: "\e61e";
}
.mm-layer-attribute:before {
content: "\e61f";
}
.mm-layer-attribution:before {
content: "\e620";
}
.mm-layer-display:before {
content: "\e621";
}
.mm-layer-geometry:before {
content: "\e622";
}
.mm-layer-max-zoom:before {
content: "\e623";
}
.mm-layer-min-zoom:before {
content: "\e624";
}
.mm-layer-security:before {
content: "\e625";
}
.mm-layer-settings:before {
content: "\e626";
}
.mm-layer-template:before {
content: "\e627";
}
.mm-layer:before {
content: "\e628";
}
.mm-layers-base:before {
content: "\e629";
}
.mm-layers-o:before {
content: "\e62a";
}
.mm-layers-order:before {
content: "\e62b";
}
.mm-layers-overlay:before {
content: "\e62c";
}
.mm-layers:before {
content: "\e62d";
}
.mm-map-add:before {
content: "\e62e";
}
.mm-map-delete:before {
content: "\e62f";
}
.mm-map-edit:before {
content: "\e630";
}
.mm-map-export:before {
content: "\e631";
}
.mm-map-print:before {
content: "\e632";
}
.mm-map-refresh:before {
content: "\e633";
}
.mm-map-share:before {
content: "\e634";
}
.mm-map-view:before {
content: "\e635";
}
.mm-map:before {
content: "\e636";
}
.mm-mapmint:before {
content: "\e637";
}
.mm-max-extent:before {
content: "\e638";
}
.mm-maximize:before {
content: "\e639";
}
.mm-measure-area:before {
content: "\e63a";
}
.mm-measure-distance:before {
content: "\e63b";
}
.mm-min-extent:before {
content: "\e63c";
}
.mm-minimize:before {
content: "\e63d";
}
.mm-minus:before {
content: "\e63e";
}
.mm-mobile-phone:before {
content: "\e63f";
}
.mm-mosaic:before {
content: "\e640";
}
.mm-ogc-csw:before {
content: "\e641";
}
.mm-ogc-wcs:before {
content: "\e642";
}
.mm-ogc-web-services:before {
content: "\e643";
}
.mm-ogc-wfs:before {
content: "\e644";
}
.mm-ogc-wms:before {
content: "\e645";
}
.mm-ogc-wps:before {
content: "\e646";
}
.mm-openlayers:before {
content: "\e647";
}
.mm-openstreetmap:before {
content: "\e648";
}
.mm-osgeo:before {
content: "\e649";
}
.mm-palette:before {
content: "\e64a";
}
.mm-pan:before {
content: "\e64b";
}
.mm-pencil:before {
content: "\e64c";
}
.mm-permacode:before {
content: "\e64d";
}
.mm-permalink:before {
content: "\e64e";
}
.mm-plain-fill:before {
content: "\e64f";
}
.mm-plus:before {
content: "\e650";
}
.mm-point:before {
content: "\e651";
}
.mm-polygon:before {
content: "\e652";
}
.mm-process:before {
content: "\e653";
}
.mm-raster:before {
content: "\e654";
}
.mm-route-start:before {
content: "\e655";
}
.mm-search-binocular:before {
content: "\e656";
}
.mm-select-arrow:before {
content: "\e657";
}
.mm-select-box:before {
content: "\e658";
}
.mm-select-hand:before {
content: "\e659";
}
.mm-server:before {
content: "\e65a";
}
.mm-shp:before {
content: "\e65b";
}
.mm-symbol-fill:before {
content: "\e65c";
}
.mm-table:before {
content: "\e65d";
}
.mm-tablet:before {
content: "\e65e";
}
.mm-tiles-o:before {
content: "\e65f";
}
.mm-tiles:before {
content: "\e660";
}
.mm-warp:before {
content: "\e661";
}
.mm-zoo-project:before {
content: "\e662";
}
.mm-zoom-box:before {
content: "\e663";
}
.mm-zoom-in:before {
content: "\e664";
}
.mm-zoom-next:before {
content: "\e665";
}
.mm-zoom-out:before {
content: "\e666";
}
.mm-zoom-previous:before {
content: "\e667";
}
.mm-zoom-to-extent:before {
content: "\e668";
}
.mm-zoom-to-maxextent:before {
content: "\e669";
}
.mm-zoom-to-point:before {
content: "\e66a";
}
.mm-zoom-to-selection:before {
content: "\e66b";
}
.mm-zoom-to:before {
content: "\e66c";
}
.mm-zoom:before {
content: "\e66d";
}
<|start_filename|>mapmint-services/vector-tools-src/Makefile<|end_filename|>
PREFIX=/usr/local
XSLT_LDFLAGS=-lxslt -lxml2
ZOO_FILE=/home/src/zoo/zoo-project/zoo-kernel/service_internal_ms.o /home/src/zoo/zoo-project/zoo-kernel/response_print.o /home/src/zoo/zoo-project/zoo-kernel/server_internal.o /home/src/zoo/zoo-project/zoo-kernel/lex.sr.o /home/src/zoo/zoo-project/zoo-kernel/lex.cr.o /home/src/zoo/zoo-project/zoo-kernel/main_conf_read.tab.o /home/src/zoo/zoo-project/zoo-kernel/service_conf.tab.o
ZOO_DIR=/home/src/zoo/zoo-project/zoo-kernel
ZRPATH=/home/src/zoo/zoo-project/zoo-kernel/../
include ${ZOO_DIR}/ZOOMakefile.opts
CPPFLAGS := -DZOO_SERVICE -DUSE_CAIRO -DUSE_KML -DUSE_MS -I${ZOO_DIR} -I${ZOO_DIR}/../../thirds/cgic206
BIN_LIST = cgi-env/service.zo
default : $(BIN_LIST)
cgi-env/service.zo: service.c
g++ ${ZOO_CFLAGS} -I${INST_INCLUDE} ${FCGI_CFLAGS} ${YAML_CFLAGS} ${MACOS_CFLAGS} ${XML2CFLAGS} ${GDAL_CFLAGS} ${MS_CFLAGS} ${CPPFLAGS} -shared -fpic $< ${ZOO_FILE} ${XSLT_LDFLAGS} ${XML2LDFLAGS} -L${INST_LIB} -lzoo_service ${ZOO_LDFLAGS} -I${INST_INCLUDE} ${FCGI_CFLAGS} ${YAML_CFLAGS} ${MACOS_CFLAGS} ${XML2CFLAGS} ${GDAL_LIBS} ${MS_LDFLAGS} -lc ${MACOS_LD_FLAGS} ${MACOS_LD_NET_FLAGS} -lcrypto -lcurl -lfcgi ${YAML_LDFLAGS} -o $@
install:
install -d ${PREFIX}/vector-tools/
install $(BIN_LIST) ${PREFIX}/vector-tools/
install cgi-env/*.zcfg ${PREFIX}/vector-tools/
install cgi-env/*.py ${PREFIX}/vector-tools/
install cgi-env/*.js ${PREFIX}/vector-tools/
cd ${PREFIX}/vector-tools/ && ln -s ../main.cfg
cd ${PREFIX}/vector-tools/ && ln -s ../ZOO-api.js
cd ${PREFIX}/vector-tools/ && ln -s ../ZOO-proj4js.js
clean :
rm -f cgi-env/*zo
<|start_filename|>public_map/css/ol.css<|end_filename|>
.ol-box {
box-sizing: border-box;
border-radius: 2px;
border: 2px solid blue;
}
.ol-mouse-position {
right: 8px;
position: absolute;
}
.ol-scale-line {
background: rgba(0,60,136,0.3);
border-radius: 4px;
bottom: 8px;
left: 8px;
padding: 2px;
position: absolute;
}
.ol-scale-line-inner {
border: 1px solid #eee;
border-top: none;
color: #eee;
font-size: 10px;
text-align: center;
margin: 1px;
will-change: contents, width;
}
.ol-overlay-container {
will-change: left,right,top,bottom;
}
.ol-unsupported {
display: none;
}
.ol-viewport, .ol-unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
.ol-selectable {
-webkit-touch-callout: default;
-webkit-user-select: auto;
-moz-user-select: auto;
-ms-user-select: auto;
user-select: auto;
}
.ol-grabbing {
cursor: -webkit-grabbing;
cursor: -moz-grabbing;
cursor: grabbing;
}
.ol-grab {
cursor: move;
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: grab;
}
.ol-control {
position: absolute;
background-color: rgba(255,255,255,0.4);
border-radius: 4px;
padding: 2px;
}
.ol-control:hover {
background-color: rgba(255,255,255,0.6);
}
.ol-zoom {
top: .5em;
left: .5em;
}
.ol-rotate {
top: .5em;
right: .5em;
transition: opacity .25s linear, visibility 0s linear;
}
.ol-rotate.ol-hidden {
opacity: 0;
visibility: hidden;
transition: opacity .25s linear, visibility 0s linear .25s;
}
.ol-zoom-extent {
top: 4.643em;
left: .5em;
}
.ol-full-screen {
right: .5em;
top: .5em;
}
@media print {
.ol-control {
display: none;
}
}
.ol-control button {
display: block;
margin: 1px;
padding: 0;
color: white;
font-size: 1.14em;
font-weight: bold;
text-decoration: none;
text-align: center;
height: 1.375em;
width: 1.375em;
line-height: .4em;
background-color: rgba(0,60,136,0.5);
border: none;
border-radius: 2px;
}
.ol-control button::-moz-focus-inner {
border: none;
padding: 0;
}
.ol-zoom-extent button {
line-height: 1.4em;
}
.ol-compass {
display: block;
font-weight: normal;
font-size: 1.2em;
will-change: transform;
}
.ol-touch .ol-control button {
font-size: 1.5em;
}
.ol-touch .ol-zoom-extent {
top: 5.5em;
}
.ol-control button:hover,
.ol-control button:focus {
text-decoration: none;
background-color: rgba(0,60,136,0.7);
}
.ol-zoom .ol-zoom-in {
border-radius: 2px 2px 0 0;
}
.ol-zoom .ol-zoom-out {
border-radius: 0 0 2px 2px;
}
.ol-attribution {
text-align: right;
bottom: .5em;
right: .5em;
max-width: calc(100% - 1.3em);
}
.ol-attribution ul {
margin: 0;
padding: 0 .5em;
font-size: .7rem;
line-height: 1.375em;
color: #000;
text-shadow: 0 0 2px #fff;
}
.ol-attribution li {
display: inline;
list-style: none;
line-height: inherit;
}
.ol-attribution li:not(:last-child):after {
content: " ";
}
.ol-attribution img {
max-height: 2em;
max-width: inherit;
vertical-align: middle;
}
.ol-attribution ul, .ol-attribution button {
display: inline-block;
}
.ol-attribution.ol-collapsed ul {
display: none;
}
.ol-attribution:not(.ol-collapsed) {
background: rgba(255,255,255,0.8);
}
.ol-attribution.ol-uncollapsible {
bottom: 0;
right: 0;
border-radius: 4px 0 0;
height: 1.1em;
line-height: 1em;
}
.ol-attribution.ol-uncollapsible img {
margin-top: -.2em;
max-height: 1.6em;
}
.ol-attribution.ol-uncollapsible button {
display: none;
}
.ol-zoomslider {
top: 4.5em;
left: .5em;
height: 200px;
}
.ol-zoomslider button {
position: relative;
height: 10px;
}
.ol-touch .ol-zoomslider {
top: 5.5em;
}
.ol-overviewmap {
left: 0.5em;
bottom: 0.5em;
}
.ol-overviewmap.ol-uncollapsible {
bottom: 0;
left: 0;
border-radius: 0 4px 0 0;
}
.ol-overviewmap .ol-overviewmap-map,
.ol-overviewmap button {
display: inline-block;
}
.ol-overviewmap .ol-overviewmap-map {
border: 1px solid #7b98bc;
height: 150px;
margin: 2px;
width: 150px;
}
.ol-overviewmap:not(.ol-collapsed) button{
bottom: 1px;
left: 2px;
position: absolute;
}
.ol-overviewmap.ol-collapsed .ol-overviewmap-map,
.ol-overviewmap.ol-uncollapsible button {
display: none;
}
.ol-overviewmap:not(.ol-collapsed) {
background: rgba(255,255,255,0.8);
}
.ol-overviewmap-box {
border: 2px dotted rgba(0,60,136,0.7);
}
.ol-overviewmap .ol-overviewmap-box:hover {
cursor: move;
}
.ol-mouse-position {background:#FFFFFF;background:rgba(255,255,255,.9);border-radius:4px;bottom:.5em;right:8px;position:absolute;border:1px solid #CCC;padding:2px;font-size:.8em;}
.ol-scale-line {background:#FFFFFF;background:rgba(255,255,255,.9);border-radius:4px;bottom:.5em;left:8px;padding:2px;position:absolute;border:1px solid #CCC;}
.ol-scale-line-inner {border:1px solid #A5A5A5;border-top:none;color:#707070;font-size:10px;text-align:center;margin:1px;padding:0 2px}
.ol-unsupported {display:none}
.ol-viewport .ol-unselectable {-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}
.ol-control {position:absolute;background-color:#eee;background-color:rgba(255,255,255,.4);border-radius:4px;padding:2px}
.ol-control:hover {background-color:rgba(255,255,255,.6)}
.ol-zoom {top:.5em;left:.5em}
.ol-zzm{top:2.5em;}
.ol-rotate {top:.5em;right:.5em;transition:opacity .25s}
.ol-zoom-extent button {line-height:.4em}
.ol-zoom-extent { top: 4.643em;left:.5em}
.ol-zmm{ top: 6.643em;}
.ol-full-screen {right:.5em;top:.5em}
.ol-flr{top:2.5em !important;}
@media print {.ol-control {display:none}
}
.ol-control button {display:block;margin:1px;padding:0;color:#707070;font-size:1.14em;font-weight:700;text-decoration:none;text-align:center;height:1.375em;width:1.375em;line-height:.4em;background-color:#7b98bc;background-color:rgba(255,255,255,1) !important;border: 1px solid #CCCCCC !important;border-radius:2px;outline:none !important;}
.ol-control button::-moz-focus-inner {border:none;padding:0}
.ol-compass {display:block;font-family:Arial;font-weight:400;font-size:1.2em}
.ol-touch .ol-control button {font-size:1.5em}
.ol-touch .ol-zoom-extent {top:5.5em}
.ol-control button:focus,.ol-control button:hover {text-decoration:none;background-color:#4c6079;background-color:rgba(0,60,136,.7)}
.ol-zoom .ol-zoom-in {border-radius:2px 2px 0 0}
.ol-zoom .ol-zoom-out {border-radius:0 0 2px 2px}
button.ol-full-screen-false {line-height:.5em !important;}
button.ol-full-screen-true:after {content:"\00d7"}
.ol-has-tooltip [role=tooltip] {position:absolute;clip:rect(1px 1px 1px 1px);clip:rect(1px,1px,1px,1px);padding:0;border:0;height:1px;width:1px;overflow:hidden;font-weight:400;font-size:14px;text-shadow:0 0 2px #fff}
.ol-has-tooltip:focus [role=tooltip],.ol-has-tooltip:hover [role=tooltip] {-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box;clip:auto;padding:0 .4em;font-size:.8em;height:1.2em;width:auto;line-height:1.2em;z-index:1100;max-height:100px;white-space:nowrap;display:inline-block;background:#FFF;background:rgba(255,255,255,.6);color:#000;border:3px solid transparent;border-left-width:0;border-radius:0 4px 4px 0;bottom:.3em;left:2.2em}
.ol-touch .ol-has-tooltip:focus [role=tooltip],.ol-touch .ol-has-tooltip:hover [role=tooltip] {display:none}
.ol-zoom .ol-has-tooltip:focus [role=tooltip],.ol-zoom .ol-has-tooltip:hover [role=tooltip] {top:1.1em}
.ol-attribution .ol-has-tooltip:focus [role=tooltip],.ol-attribution .ol-has-tooltip:hover [role=tooltip],.ol-full-screen .ol-has-tooltip:focus [role=tooltip],.ol-full-screen .ol-has-tooltip:hover [role=tooltip],.ol-rotate .ol-has-tooltip:focus [role=tooltip],.ol-rotate .ol-has-tooltip:hover [role=tooltip] {right:2.2em;left:auto;border-radius:4px 0 0 4px;border-left-width:3px;border-right-width:0}
.ol-attribution {text-align:right;bottom:3em;right:.5em;max-width:calc(100% - 1.3em)}
.ol-attribution ul {margin:0;padding:0 .5em;font-size:.8em;line-height:1.375em;color:#707070;max-width:calc(100% - 1.6em)}
.ol-attribution li {display:inline;list-style:none;line-height:inherit}
.ol-attribution li:not(:last-child):after {content:" "}
.ol-attribution img {max-height:2em;display:none;}
.ol-attribution button,.ol-attribution ul {display:inline-block}
.ol-attribution.ol-collapsed ul,.ol-attribution:not(.ol-collapsed) button:hover [role=tooltip] {display:none}
.ol-attribution.ol-logo-only ul {display:block}
.ol-attribution:not(.ol-collapsed) {background:rgba(255,255,255,.8)}
.ol-attribution.ol-uncollapsible {bottom:0;right:0;border-radius:4px 0 0;height:1.1em;line-height:1em}
.ol-attribution.ol-logo-only {background:0 0;bottom:.4em;height:1.1em;line-height:1em}
.ol-attribution.ol-uncollapsible img {margin-top:-.2em;max-height:1.6em}
.ol-attribution.ol-logo-only button,.ol-attribution.ol-uncollapsible button {display:none}
.ol-zoomslider {position:absolute;top:7em !important;left:10px;background:#eee;background:rgba(255,255,255,.6);border-radius:3px;outline:0;overflow:hidden;width:1.5675em;height:200px;padding:3px;margin:0;border:1px solid #CCC;}
.ol-zsm{position:absolute;top:9em !important;}
.ol-zoomslider-thumb {position:absolute;display:block;background:#FFF;border-radius:2px;outline:0;overflow:hidden;cursor:pointer;font-size:1.14em;height:.8em;width:1.4em;margin:0;padding:0;}
.ol-touch .ol-zoomslider {top:5.5em;width:2.052em}
.ol-touch .ol-zoomslider-thumb {width:1.8em}
.ol-attribution,.ol-control button,.ol-has-tooltip [role=tooltip],.ol-scale-line-inner {font-family:'Lucida Grande',Verdana,Geneva,Lucida,Arial,Helvetica,sans-serif}
.ol-overviewmap{position:absolute;left:.5em;bottom:3em;border:1px solid #CCC}.ol-overviewmap.ol-uncollapsible{bottom:0;left:0;border-radius:0 4px 0 0}.ol-overviewmap .ol-overviewmap-map,.ol-overviewmap button{display:inline-block}.ol-overviewmap .ol-overviewmap-map{border:1px solid #CCC;height:150px;margin:2px;width:150px}.ol-overviewmap:not(.ol-collapsed) button{bottom:1px;left:2px;position:absolute}.ol-overviewmap.ol-collapsed .ol-overviewmap-map,.ol-overviewmap.ol-uncollapsible button{display:none}.ol-overviewmap:not(.ol-collapsed){background:rgba(255,255,255,.8)}.ol-overviewmap-box{border:2px dotted rgba(0,60,136,.7)}
.ol-popup {
display: none;
position: absolute;
background-color: white;
padding: 10px;
border: 1px solid #cccccc;
bottom: 12px;
left: -50px;
text-align:center;
}
.ol-popup a:hover{text-decoration:none !important;}
.ol-popup h2{
font-size:20px;color:#696e43;
margin:10px;padding:0;}
.ol-popup h3{
font-size:16px;color:#707070;
margin:10px;padding:0;}
.ol-popup p{
font-size:14px;color:#707070;
margin:0;padding:0;}
.ol-popup:after, .ol-popup:before {
top: 100%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.ol-popup:after {
border-top-color: white;
border-width: 10px;
left: 48px;
margin-left: -10px;
}
.ol-popup:before {
border-top-color: #cccccc;
border-width: 11px;
left: 48px;
margin-left: -11px;
}
.ol-popup-content {
min-width: 170px;
max-height: 200px;
overflow-x: auto;
}
.ol-popup p:last-child {
color: #CCCCCC !important;
}
.ol-popup-closer {
position: absolute;
top: 5px;
right: 5px;
width:20px;height:20px;
line-height:12px;
font-size: 100%;
padding: 4px;
color: #CCCCCC;
text-decoration: none;
}
.ol-popup-closer:hover{color:#333;}
.ol-popup-closer:after {
content:'\0078';
}
.ol-popup div.infoResult {
min-width: 130px;
}
.ol-popup div.infoResult p {
padding: 0.1em;
margin: 0;
}
.ol-popup-content h3 {
margin: 0.25em 0;
}
.ol-popup.marker {
margin-bottom: 30px;
}
<|start_filename|>public_map/mapmint-nude.css<|end_filename|>
.copy p {
padding: 6px 0 10px 0;
}
#coords{
bottom: 6px;
}
<|start_filename|>mapmint-ui/js/Datawarehouse.js<|end_filename|>
Datawarehouse=MLayout.extend({
id: 0,
cnt: 0,
dataTypes: [],
args: [],
postgisListRefresh: function(){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?service=WPS&version=1.0.0&request=Execute&Identifier=datastores.postgis.list&DataInputs=type="+arguments[0]+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
if($mj("postgisListing"))
$mj("postgisListing").parentNode.removeChild($mj("postgisListing"));
$('#postgisList').append(xml.responseText);
cLayout.refresh();
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
},
directoriesListRefresh: function(){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/directories&service=WPS&version=1.0.0&request=Execute&Identifier=list&DataInputs=&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
if($mj("directoriesListing"))
$mj("directoriesListing").parentNode.removeChild($mj("directoriesListing"));
$('#mainDirectoriesList').append(xml.responseText);
cLayout.refresh();
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
},
DatasourcePostGISCommit: function(){
if (arguments[0]=='cancel'){
confirm('Delete ' + $('.trSelected',grid).length + ' items?')
}
else if (arguments[0]=='add'){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=save&DataInputs=name="+$mj("Datawarehouse.pgisform.name").value+";dbname="+$mj("Datawarehouse.pgisform.dbname").value+";user="+$mj("Datawarehouse.pgisform.user").value+";password="+$mj("<PASSWORD>").value+";host="+$mj("Datawarehouse.pgisform.host").value+";port="+$mj("Datawarehouse.pgisform.port").value+";type="+$("input[type=radio][name=Datawarehouse.pgisform.type]:checked").attr('value')+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
Datawarehouse.postgisListRefresh("PostGIS");
}
});
}
},
DatasourceDirCommit: function(){
if (arguments[0]=='cancel'){
confirm('Delete ' + $('.trSelected',grid).length + ' items?')
}
else if (arguments[0]=='add'){
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/directories&service=WPS&version=1.0.0&request=Execute&Identifier=saveDir&DataInputs=name="+$mj("Datawarehouse.form.name").value+";path="+$mj("Datawarehouse.form.path").value+";type="+$("input[name=Datawarehouse.form.type]:checked")[0].value+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
Datawarehouse.directoriesListRefresh();
}
});
}
},
loadDir: function(){
if(!Datawarehouse.references)
Datawarehouse.references=[];
Datawarehouse.unloadDir(arguments[0]);
for(var i=0;i<Datawarehouse.references.length;i++)
if(arguments[0]==Datawarehouse.references[i])
return;
$.ajax({
dwDataSource: arguments[0],
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=vector-tools&service=WPS&version=1.0.0&request=Execute&Identifier=mmExtractVectorInfo&DataInputs=dataSource="+arguments[0]+(arguments.length>1?";type="+arguments[1]:"")+"&RawDataOutput=Result",
dataType: 'xml',
complete: function(xml,status){
try{
var tmp=$.xmlToJSON(xml.responseXML);
var localTmp=[];
var tt="";
for(var i=0;i<tmp.name.length;i++){
localTmp[i]=tmp.name[i].Text;
tt+=i+" = "+localTmp[i]+"\n";
}
}catch(e){alert("MM Error : "+e);}
var localCnt;
if(localTmp)
for(var localI=0;localI<localTmp.length;localI++){
var localTmp1=localTmp[localI];
var localCnt=Datawarehouse.cnt;
//Datawarehouse.references[Datawarehouse.cnt]=localTmp[localI];
$.ajax({
dwDataSource: this.dwDataSource,
dwLayer: localTmp[localI],
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=vector-tools&service=WPS&version=1.0.0&request=Execute&Identifier=mmExtractVectorInfo&DataInputs=dataSource="+this.dwDataSource+";layer="+localTmp[localI]+"&RawDataOutput=Result",
dataType: 'xml',
complete: function(xml,status) {
colModel=[];
fields=[];
try{
var tmp=$.xmlToJSON(xml.responseXML);
var nbCol=0;
for(i=0;i<tmp.fields.length;i++){
for(j=0;j<tmp.fields[i].field.length;j++){
colModel[nbCol]={display: tmp.fields[i].field[j].id[0].Text, name : tmp.fields[i].field[j].id[0].Text, width: (nbCol==0?80:120), sortable : true, align: 'center'};
fields[nbCol]=tmp.fields[i].field[j].id[0].Text;
nbCol++;
}
}
$('#datasources-container-id').append('<table id="flex'+(Datawarehouse.cnt)+'" style="display:none"></table>');
Datawarehouse.references[Datawarehouse.cnt]=this.dwDataSource;
$("#flex"+(Datawarehouse.cnt)).flexigrid({
autoload: false,
url: '/cgi-bin/zoo_loader.cgi',
dataType: 'xml',
colModel: colModel,
usepager: (tmp.featureCount[0].Text>10?true:false),
sortname: tmp.fields[0].field[0].id[0].Text,
sortorder: "asc",
fields: fields,
dwDataSource: this.dwDataSource,
dwLayer: this.dwLayer,
dwDataType: (tmp.geometry[0].Text=='Polygon'?'polygon':(tmp.geometry[0].Text=='Point'?'point':'line')),
nbElements: tmp.featureCount[0].Text,
title: this.dwDataSource+" / "+tmp.name[0].Text,
useLimit: true,
limit: 10,
showTableToggleBtn: true,
tableToggleBtns:
[
{title: "Delete",name: 'delete'},
{name: 'open-in-manager', title: "Open in Manager"},
{name: 'download',title: 'Download'},
{name: 'preview',title: 'Preview'},
{name: 'reproject',title: 'Change projection',content: '<a href="#" class="change-srs">EPSG:4326</a>'},
{name: 'convert', title: 'Change format', content: '<a href="#" class="change-format">SHP</a>',onclick: function () {
alert('ok');
$( "#change-format-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
})}}
],
width: "100%",
height: 290
});
Datawarehouse.cnt+=1;
$('.flexigrid').addClass('hideBody');
}catch(e){alert("MM Error : "+e);}
}
});
}
}
}
);
},
unloadDir: function(){
for(var i=0;i<Datawarehouse.references.length;i++){
try{
if(Datawarehouse.references[i]==arguments[0] && $mj('flex'+i)){
$mj('flex'+i).style.display=($mj('flex'+i).style.display=='none'?'block':'none');//parentNode.removeChild($mj('flex'+i));
//Datawarehouse.references[i]="";
}
}catch(e){alert("MM Error: "+e);}
}
},
last_dir: null
});
Datawarehouse.define({
loadDir: function(){
Datawarehouse.last_dir=arguments[0];
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/directories&service=WPS&version=1.0.0&request=Execute&Identifier=list&DataInputs=dir="+Datawarehouse.last_dir+(arguments.length>1?";type="+arguments[1]:"")+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
alert('lastDir : '+Datawarehouse.last_dir);
var reg=/\//g;
var tmpId='#browseDirectoriesList'+Datawarehouse.last_dir.replace(reg,"_");
alert(tmpId);
$(tmpId).append('<h1>HeyHo</h1>');
alert(tmpId);
alert($('#browseDirectoriesList'+Datawarehouse.last_dir)+'\n'+xml.responseText);
if(Datawarehouse.last_dir=='/')
$(tmpId).html('<ul id="browser4DirectoriesList'+Datawarehouse.last_dir.replace(reg,'_')+'" class="filetree treeview" style="height: 185px;overflow:auto;"><li class="collapsable lastCollapsable"><div class="hitarea expandable-hitarea" onclick=""></div>'+'<span class="folder">Directory '+Datawarehouse.last_dir+': </span>'+xml.responseText+'</li></ul>');
else
$(tmpId).append(xml.responseText);
$('#progress_bar .ui-progress').css('width', '95%');
if(!Datawarehouse.browser4DirectoriesList)
Datawarehouse.browser4DirectoriesList=$("#browser4DirectoriesList_").tree({
checkbox: true,
onClick:function(node){
alert(node.id.replace("browseDirectoriesList","").replace(/_/g,"/"));
//$("#"+node.id).append("<h1>HeyHo</h1>");
$("#browser4DirectoriesList_").tree('append',{parent: $('#browser4DirectoriesList_').tree('getSelected').target,
data:[
{
"id": 13,
"text":"Raspberry"
},{
"id": 14,
"text":"Cantaloupe"
}
]});
layouts[1].loadDir(node.id.replace("browseDirectoriesList","").replace(/_/g,"/"));
},
onCheck: function(node,check){
if(check)
Datawarehouse.loadDir(node.id);
else
Datawarehouse.unloadDir(node.id);
}
});
/*$("#directoriesList/"+Datawarehouse.last_dir).tree({checkbox: true,
onClick:function(node){
//alert("hehe"+node.id);
}});*/
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
},
initialize: function(){
$(".addDB-toolbar dt a").click(function() {
$(".addDB-toolbar dd ul").show('slow');
});
$(".addDB-toolbar dd ul").mouseleave(function() {
$(".addDB-toolbar dd ul").hide('slow');
});
Datawarehouse.dataTypes[0]={type: 'MySQL',loaded: false};
Datawarehouse.dataTypes[1]={type: 'PostGIS',loaded: false};
Datawarehouse.dataTypes[2]={type: 'dir',loaded: false};
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=list&DataInputs=type=MySQL&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
Datawarehouse.dataTypes[0]['loaded']=true;
$('#progress_bar .ui-progress').css('width', '65%');
$('#mysqlList').append(xml.responseText);
cLayout.refresh();
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/postgis&service=WPS&version=1.0.0&request=Execute&Identifier=list&DataInputs=type=PostGIS&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
Datawarehouse.dataTypes[1]['loaded']=true;
$('#progress_bar .ui-progress').css('width', '65%');
$('#postgisList').append(xml.responseText);
cLayout.refresh();
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
$.ajax({
type: "GET",
url: "/cgi-bin/zoo_loader.cgi?metapath=datastores/directories&service=WPS&version=1.0.0&request=Execute&Identifier=list&DataInputs=&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
Datawarehouse.dataTypes[2]['loaded']=true;
$('#progress_bar .ui-progress').css('width', '65%');
$('#mainDirectoriesList').append(xml.responseText);
cLayout.refresh();
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
this.loadDir("/","default");
function test(com,grid)
{
if (com=='Delete')
{
confirm('Delete ' + $('.trSelected',grid).length + ' items?')
}
else if (com=='Add')
{
alert('Add New Item');
}
}
$('b.top').click
(
function ()
{
$(this).parent().toggleClass('fh');
}
);
$(".dialog-postgis-new").dialog({
autoOpen: false,
height: 320,
width: 320,
resizable: false,
buttons: {
'Add': function() {
Datawarehouse.DatasourcePostGISCommit('add');
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$('.test-pg-connection').button({
text: false
}).click(function() {
$( '.dialog-postgis-new').dialog("close");
});
$('.db').button({
text: false
}).click(function() {
$( '.dialog-postgis-new').dialog("open");
});
$(".dialog-directory-new").dialog({
autoOpen: false,
height: 400,
width: 500,
resizable: false,
buttons: {
'Add': function() {
Datawarehouse.DatasourceDirCommit('add');
$(this).dialog('close');
},
'Cancel': function() {
Datawarehouse.DatasourceDirCommit('cacel');
$(this).dialog('close');
}
}
});
$('.dir').button({
text: false
}).click(function() {
$( '.dialog-directory-new').dialog("open");
});
$(".dialog-add-vector").dialog({
autoOpen: false,
height: 180,
width: 300,
resizable: false,
buttons: {
'Add': function() {
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$('.add-layer-vector').button({
text: false
}).click(function() {
$( '.dialog-add-vector').dialog("open");
});
$(".dialog-add-raster").dialog({
autoOpen: false,
height: 180,
width: 300,
resizable: false,
buttons: {
'Add': function() {
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$('.add-layer-raster').button({
text: false
}).click(function() {
$( '.dialog-add-raster').dialog("open");
});
},
refresh: function(){
//$("input:checkbox, input:radio, input:file").uniform();
$('.add-layer-vector, .add-layer-raster, .add-layer-wms, .add-layer-wfs, .add-layer-wcs').button({text: false});
$('a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
try{
for(var i=0;i<Datawarehouse.dataTypes.length;i++)
if(Datawarehouse.dataTypes[i].loaded==false)
return -1;
$("#browser").tree({
checkbox: true,
onClick:function(node){
//alert("hehe"+node.id);
},
onCheck:function(node, checked){
//alert(node.id+" "+checked);
reg=/browseDirectoriesList/;
if(checked)
Datawarehouse.loadDir((node.id+'').replace(reg,""));
else
Datawarehouse.unloadDir((node.id+'').replace(reg,""));
}
}
);
//$("#browser4DirectoriesList"+Datawarehouse.last_dir).tree();
}catch(e){alert("Tree error"+e);}
}
});
<|start_filename|>mapmint-ui/new-themes/themes/pink/misc.css<|end_filename|>
.tabs-right ul li:hover, .maps-container ul li:hover {cursor:pointer;
background: #f630f8; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f869ec', endColorstr='#f630f8'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#f869ec), to(#f630f8)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
}
<|start_filename|>public_map/assets/js/demo1.js<|end_filename|>
// Filename: main.js
requirejs.config({
baseUrl: 'assets',
paths: {
text: 'js/lib/require-text-2.0.12',
hgn: 'js/lib/require-hgn-0.3.0',
jquery: 'js/lib/jquery/jquery-1.11.0.min',
bootstrap: 'js/lib/bootstrap-3.1.1-dist/js/bootstrap.min',
notify: 'js/lib/bootstrap-notify',
hogan: 'js/lib/hogan/hogan-3.0.2',
xml2json: 'js/lib/xml2json/xml2json.min',
queryString: 'js/lib/query-string/query-string',
wpsPayloads: 'js/lib/zoo/payloads',
wpsPayload: 'js/lib/zoo/wps-payload',
utils: 'js/lib/zoo/utils',
zoo: 'js/lib/zoo/zoo',
domReady: 'js/lib/domReady',
app: 'js/demo1-app',
},
shim: {
bootstrap: {
deps: ['jquery'],
},
notify: {
deps: ['jquery'],
},
wpsPayloads: {
deps: ['hogan'],
},
wpsPayload: {
deps: ['wpsPayloads'],
exports: 'wpsPayload',
},
hogan: {
exports: 'Hogan',
},
xml2json: {
exports: "X2JS",
},
queryString: {
exports: 'queryString',
},
},
});
requirejs.config({
config: {
app: {
url: '/cgi-bin/zoo_loader.fcgi',
delay: 1000,
}
}
});
require(['domReady', 'app'], function(domReady, app) {
domReady(function() {
app.initialize();
});
});
<|start_filename|>mapmint-ui/templates/Distiller/PgEditorWindow0_bs.html<|end_filename|>
#import zoo
<div class="tab-content">
<div class="row">
#set inputs1=$inputs
#set $inputs1["clause"]={"value":"id="}
#set $inputs1["type"]={"value":"insert"}
$inputs1
#*
#set searchList1=$searchList
$(Template(file=$conf["main"]["templatesPath"]+"/Distiller/PgEditorWindow_bs.tmpl",searchList=[{"conf":$conf,"inputs":$inputs1}]))
</div>
<div class="row">
#set inputs1=$inputs
#import authenticate.service as auth
#set con=auth.getCon($conf)
#set cur=con.conn.cursor()
#set prefix=$auth.getPrefix($conf)
#set $inputs1["clause"]={"value":"id=1"}
#set $inputs1["type"]={"value":"delete"}
#set searchList1=$searchList
$(Template(file=$conf["main"]["templatesPath"]+"/Distiller/PgEditorWindow_bs.tmp",searchList=[{"conf":$conf,"inputs":$inputs1}]))
</div>
<div class="row">
#set inputs1=$inputs
#import authenticate.service as auth
#set con=auth.getCon($conf)
#set cur=con.conn.cursor()
#set prefix=$auth.getPrefix($conf)
#set $inputs1["clause"]={"value":"id=1"}
#set $inputs1["type"]={"value":"update"}
#set searchList1=$searchList
$(Template(file=$conf["main"]["templatesPath"]+"/Distiller/PgEditorWindow_bs.tml",searchList=[{"conf":$conf,"inputs":$inputs1}]))
</div>
*#
</div>
<|start_filename|>public_map/assets/js/lib/zoo/wps-payload.js<|end_filename|>
/**
* Author : <NAME>
*
* Copyright (c) 2014 GeoLabs SARL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
define([
'jquery', 'utils'
], function($, utils) {
/**
* The wpsPayload module is using the
* [Hogan.js]{@link http://twitter.github.io/hogan.js/} templating engine to
* generate XML requests to be sent to a WPS Server.
* In the ZOO-Client API, the Hogan.js templates have to be compiled before
* you can use them from you application. Please refer to the ZOO-Client
* installation documentation for more informations.
*
* @module wpsPayload
* @requires payloads
* @requires jquery
* @requires utils
*/
return {
/** @exports wpsPayload */
/**
* The getPayload function uses the mustache
* templates and the parameters provided to generate a valid WPS XML
* request.
*
* @static
* @param {Object} params - The object representing the request.
* @returns {string} - The corresponding XML request
* @example
* // GetCapabilities
* var request_params = {
* request: 'GetCapabilities',
* language: 'en-US'
* };
* console.wpsPayload.getPayload(request_params));
* @example
* // DescribeProcess with Identifier value set to "all".
* var request_params = {
* request: 'DescribeProcess',
* identifier: ["all"]
* };
* console.log(wpsPayload.getPayload(request_params));
* @example
* //
* var request_params = {
* request: 'Execute',
* Identifier: "Buffer",
* DataInputs: [{"identifier":"InputPolygon","href":"http://features.org/toto.xml","mimeType":"text/xml"}],
* DataOutputs: [{"identifier":"Result","mimeType":"application/json"}],
* language: 'en-US'
* };
* console.log(wpsPayload.getPayload(request_params));
*/
getPayload: function(params) {
if (params.request == 'DescribeProcess') {
return this.getPayload_DescribeProcess(params);
} else if (params.request == 'GetCapabilities') {
return this.getPayload_GetCapabilities(params);
} else if (params.request == 'Execute') {
return this.getPayload_Execute(params);
} else {
console.log("#### UNKNOWN REQUEST ####");
}
},
/**
* The getPayload_GetCapabilities function is used to generate a valid
* WPS XML GetCapabilities request using the
* [payload_GetCapabilities.mustache]{@link http://zoo-project.org/trac/browser/trunk/zoo-project/zoo-client/lib/tpl/payload_GetCapabilities.mustache}
* template.
*
* @static
* @param {Object} params - The object representing the request.
* @returns {string} - The corresponding XML request
* @example
* // log the XML request in console
* var request_params = {
* language: 'en-US'
* };
* console.log(wpsPayload.getPayload_GetCapabilities(request_params));
*/
getPayload_GetCapabilities: function(params) {
return templates["payload_GetCapabilities"].render(params);
},
/**
* The getPayload_DescribeProcess function is used to generate a valid
* WPS XML DescribeProcess request using the
* [payload_DescribeProcess.mustache]{@link http://zoo-project.org/trac/browser/trunk/zoo-project/zoo-client/lib/tpl/payload_DescribeProcess.mustache}
* template.
*
* @static
* @param {Object} params - The object representing the request.
* @returns {string} - The corresponding XML request
* @example
* // log the XML request in console
* var request_params = {
* Identifier: ["Buffer","Centroid"],
* language: 'en-US'
* };
* console.log(wpsPayload.getPayload_DescribeProcess(request_params));
*/
getPayload_DescribeProcess: function(params) {
if (params.Identifier) {
if ($.isArray(params.Identifier)) {
return templates["payload_DescribeProcess"].render({identifiers: params.Identifier,language: params.language});
}
else {
return templates["payload_DescribeProcess"].render({identifiers: [params.Identifier],language: params.language});
}
}
// TODO: no Identifier
},
/**
* The getPayload_Execute function is used to generate a valid WPS XML
* Excute request using the
* [payload_Execute.mustache]{@link http://zoo-project.org/trac/browser/trunk/zoo-project/zoo-client/lib/tpl/payload_Execute.mustache}
* template.
*
* @static
* @param {Object} params - The object representing the request.
* @returns {string} - The corresponding XML request
* @example
* // log the XML request in console
* var request_params = {
* Identifier: "Buffer",
* DataInputs: [{"identifier":"InputPolygon","href":"http://features.org/toto.xml","mimeType":"text/xml"}],
* DataOutputs: [{"identifier":"Result","mimeType":"application/json"}],
* language: 'en-US'
* };
* console.log(wpsPayload.getPayload_Execute(request_params));
*/
getPayload_Execute: function(params) {
if (params.DataInputs) {
for (var i = 0; i < params.DataInputs.length; i++) {
/**
* Define inputs type depending on presence of mimeType,
* dataType and crs or dimension for ComplexData,
* LiteralData and BoundingBox data respectively
*/
var hasType=false;
var lp={"data":"literal","mime":"complex"};
for(j in lp){
if (params.DataInputs[i][j+"Type"]) {
params.DataInputs[i]['is_'+lp[j]] = true;
params.DataInputs[i].type=lp[j];
if(j=="mime"){
params.DataInputs[i].is_XML=(params.DataInputs[i][j+"Type"]=="text/xml");
if(!params.DataInputs[i].is_XML){
var tmp=params.DataInputs[i][j+"Type"].split(";");
params.DataInputs[i].is_XML=(tmp[0]=="text/xml");
}
}
hasType=true;
}
}
if(!hasType){
if (params.DataInputs[i]["type"]=="bbox" ||
params.DataInputs[i]["dimension"] ||
params.DataInputs[i]["crs"]){
params.DataInputs[i]['is_bbox'] = true;
params.DataInputs[i].type='bbox';
hasType=true;
}
if(!hasType){
params.DataInputs[i]['is_literal'] = true;
params.DataInputs[i].type = "literal";
}
}
/*
* Set some default values and flags.
*/
if (params.DataInputs[i].type == 'bbox') {
if (!params.DataInputs[i].crs) {
params.DataInputs[i].crs = "EPSG:4326";
}
if (!params.DataInputs[i].dimension) {
params.DataInputs[i].dimension = 2;
}
}
// Complex data from payload callback.
if (params.DataInputs[i].complexPayload_callback) {
params.DataInputs[i].value = window[params.DataInputs[i].complexPayload_callback]();
console.log(params.DataInputs[i].value);
}
// Complex data from reference.
if (params.DataInputs[i].href) {
params.DataInputs[i].is_reference = true;
//params.DataInputs[i].href = utils.encodeXML(params.DataInputs[i].href);
if (params.DataInputs[i].method == 'POST') {
params.DataInputs[i].is_post = true;
} else {
params.DataInputs[i].is_get = true;
}
}
else {
// Complex data, embeded
}
} // for i loop
}
//console.log("==== OUTPUTS ====");
if (params.DataOutputs || params.storeExecuteResponse || params.status || params.lineage) {
for (var i = 0; i < params.DataOutputs.length; i++) {
//console.log(params.DataOutputs[i]);
if (params.DataOutputs[i].type) {
params.DataOutputs[i]['is_'+params.DataOutputs[i].type] = true;
}
}
}
return templates["payload_Execute"].render(params);
},
};
});
<|start_filename|>mapmint-ui/templates/preview/modules/export/init.js<|end_filename|>
#import mapfile.service as mms
function startExport(){
\$(".dialog-export").show();
\$(".dialog-export").window({
width:248,
height:174,
collapsible: false,
maximizable:false,
minimizable:false,
resizable:false
});
}
function exportData(){
#if $mms.getMetadata($m.web,'layout_t')=="mobile"
$.mobile.showPageLoadingMsg();
#end if
//alert("$conf["senv"]["last_map"] <=> "+System.mmNodeId);
\$.ajax({
type: "GET",
dataType: "html",
url: zooUrl+"?request=Execute&service=WPS&version=1.0.0&Identifier=vector-converter.exportTo"+"&DataInputs=map=$conf["senv"]["last_map"];layer="+System.mmNodeId.replace(/layer_/g,"")+";format="+\$("#select_export").val()+"&RawDataOutput=Result",
success: function(xml){
#if $mms.getMetadata($m.web,'layout_t')=="mobile"
$.mobile.hidePageLoadingMsg();
#end if
\$("#export_dl_link").attr("href",xml);
\$("#export_dl_link").show();
\$('#routingDownloadContainer').attr('href',xml);
}
});
}
<|start_filename|>public_map/mapmint-rightcol.css<|end_filename|>
/*
* PANES & CONTENT-DIVs
*/
.ui-layout-pane { /* all 'panes' */
background: transparent;
border: 0;
/* DO NOT add scrolling (or padding) to 'panes' that have a content-div,
otherwise you may get double-scrollbars - on the pane AND on the content-div
*/
padding: 0;
overflow: auto;
}
/* (scrolling) content-div inside pane allows for fixed header(s) and/or footer(s) */
.ui-layout-content {
padding: 0;
position: relative; /* contain floated or positioned elements */
overflow: auto; /* add scrolling to content-div */
}
/*
* RESIZER-BARS
*/
.ui-layout-resizer { /* all 'resizer-bars' */
background: #DDD;
border: 0;
border-width: 0;
}
.ui-layout-resizer-drag { /* REAL resizer while resize in progress */
}
.ui-layout-resizer-hover { /* affects both open and closed states */
}
/* NOTE: It looks best when 'hover' and 'dragging' are set to the same color,
otherwise color shifts while dragging when bar can't keep up with mouse */
.ui-layout-resizer-open-hover , /* hover-color to 'resize' */
.ui-layout-resizer-dragging { /* resizer beging 'dragging' */
background: #C4E1A4;
}
.ui-layout-resizer-dragging { /* CLONED resizer being dragged */
border-left: 0;
border-right: 0;
}
/* NOTE: Add a 'dragging-limit' color to provide visual feedback when resizer hits min/max size limits */
.ui-layout-resizer-dragging-limit { /* CLONED resizer at min or max size-limit */
background: #E1A4A4; /* red */
}
.ui-layout-resizer-closed-hover { /* hover-color to 'slide open' */
background: #EBD5AA;
}
.ui-layout-resizer-sliding { /* resizer when pane is 'slid open' */
opacity: .10; /* show only a slight shadow */
filter: alpha(opacity=10);
}
.ui-layout-resizer-sliding-hover { /* sliding resizer - hover */
opacity: 1.00; /* on-hover, show the resizer-bar normally */
filter: alpha(opacity=100);
}
/* sliding resizer - add 'outside-border' to resizer on-hover
* this sample illustrates how to target specific panes and states */
.ui-layout-resizer-north-sliding-hover { border-bottom-width: 1px; }
.ui-layout-resizer-south-sliding-hover { border-top-width: 1px; }
.ui-layout-resizer-west-sliding-hover { border-right-width: 1px; }
.ui-layout-resizer-east-sliding-hover { border-left-width: 1px; }
/*
* TOGGLER-BUTTONS
*/
.ui-layout-toggler {
border: 0; /* match pane-border */
background-color: #BBB;
}
.ui-layout-resizer-hover .ui-layout-toggler {
opacity: .60;
filter: alpha(opacity=60);
}
.ui-layout-toggler-hover , /* need when NOT resizable */
.ui-layout-resizer-hover .ui-layout-toggler-hover { /* need specificity when IS resizable */
background-color: #92cb4b;
opacity: 1.00;
filter: alpha(opacity=100);
}
.ui-layout-toggler-north ,
.ui-layout-toggler-south {
border-width: 0 1px; /* left/right borders */
}
.ui-layout-toggler-west ,
.ui-layout-toggler-east {
border-width: 1px 0; /* top/bottom borders */
display:none;
}
/* hide the toggler-button when the pane is 'slid open' */
.ui-layout-resizer-sliding ui-layout-toggler {
display: none;
}
ui-layout-resizer-west-closed{width:17px;}
/*
* style the text we put INSIDE the togglers
*/
.ui-layout-toggler .content {
color: #666;
font-size: 12px;
font-weight: bold;
width: 100%;
padding-bottom: 0.35ex; /* to 'vertically center' text inside text-span */
}
.nav{position:absolute;top:0;left:15px !important;width:auto;display:block;}
.fg-toolbar {
z-index:1000000000000;
position:relative;
top:0;
left:0;
width:auto;
max-width:500px;
padding:0;
margin:0;
display:block;
}
.ui-layout-north{
padding:0;
background: #83c849;
width:100%;
overflow:hidden;
height:90px;
}
.ui-layout-north img{float:left;margin:15px 0 0 20px;display:inline-block;}
.ui-layout-north h1{font-size:1.4em;margin:0;padding:5px;color:#FFFFFF;position:relative;top:5px;left:20px;line-height:1.3em;}
.ui-layout-west {
padding:0;
background:#FFFFFF;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f4f4f4'); /* for IE */
background:-webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#f4f4f4)); /* for webkit browsers */
background:-moz-linear-gradient(top, #ffffff, #f4f4f4); /* for firefox 3.6+ */
width:350px;
min-width:350px;
max-width:50%;
}
.ui-layout-east{
overflow: hidden;
}
.ui-layout-east h2{font-size:.9em;margin:0;padding:10px 0 10px 10px;color:#808080;position:relative;font-weight:bold; text-shadow: #FFFFFF 0px 1px 0px;letter-spacing:2px;}
.close {width:16px;height:17px;
float:left;
margin: 0 10px 0 0;
cursor:pointer;
background: url(img/close-sidebar-right.png) no-repeat;
text-align:center;
font-size:.7em;
}
.open {width:16px;height:17px;
position:absolute;
float:right;
top:10px;
right:10px;
cursor:pointer;
background: url(img/close-sidebar.png) no-repeat;
text-align:center;
font-size:.7em;
z-index: 1000 !important;
}
.ui-layout-south{
padding: 0;
width:100%;
overflow:hidden;
max-height:40px;
height:40px;
background: transparent url('img/bcknav.png');
}
.ui-layout-south img {
border:0;
position:relative;
top:10px;
left:0;
}
div#overviewmap {z-index:1000; overflow: hidden;position:absolute;bottom:10px;right:10px;float:right;margin:0;padding:0;}
.toolbar-noborder{background:transparent;width:100%;margin:0;padding:0;}
.toolbar-noborder a{margin:5px 0 5px 5px;}
#coords{float:left;padding:0 5px 0 0;color:#FFFFFF;font-size:.8em;text-shadow:#333333 0 1px 0;display:inline;position:absolute;right:50px;top:16px;}
div#map{width:100%;height:100%;margin:0;padding:0;}
div#ls-container{position:absolute;top:10px; right:10px;width:auto;z-index:100000000;}
div#ls-container table{position:absolute;top:110px;left:100px;margin:0;padding:0;width:160px;}
div#ls-container table td.sli{width:100px;}
#loading{
position: absolute;
top: 10px;
right: 30px;
width:auto;
height:auto;
background:url('img/bckw.png');
text-align: left;
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
display:none;
z-index:100000000;
font-size: 11px;
color:#707070;
}
#loading ul{
list-style: none;
margin: 0;
padding: 1em;
}
<|start_filename|>mapmint-ui/templates/preview/modules/indexes/_init.js<|end_filename|>
var TerritoriesSelected;
var idxPoiControl,idxStdControl,idxCirControl;
var idxCtrl={};
<|start_filename|>mapmint-ui/new-themes/themes/green/progress.css<|end_filename|>
.ui-progress-bar {
position: relative;
top:14px;
right:20px;
float:right;
height: 15px;
width:150px;
padding-right: 2px;
background-color: #abb2bc;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
behavior: url(js/ie-css3.htc);
background: -webkit-gradient(linear, left bottom, left top, color-stop(0, #b1b1b1), color-stop(1, #9D9D9D));
background: -moz-linear-gradient(left,#B1B1B1 0%, #9D9D9 100%);
-webkit-box-shadow: inset 0px 1px 1px 0px rgba(131, 200, 73, 0.3), 0px 1px 0px 0px #707070;
-moz-box-shadow: inset 0px 1px 1px 0px rgba(131, 200, 73, 0.3), 0px 1px 0px 0px #707070;
box-shadow: inset 0px 1px 1px 0px rgba(131, 200, 73, 0.3), 0px 1px 0px 0px #707070;
}
.ui-progress {
position: relative;
display: block;
overflow: hidden;
height: 13px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-webkit-background-size: 24px 24px;
background-color: #74d04c;
background: -webkit-gradient(linear, 0 0, 24 24,
color-stop(0.00, rgba(255,255,255,0.17)),
color-stop(0.25, rgba(255,255,255,0.17)),
color-stop(0.26, rgba(255,255,255,0)),
color-stop(0.50, rgba(255,255,255,0)),
color-stop(0.51, rgba(255,255,255,0.17)),
color-stop(0.75, rgba(255,255,255,0.17)),
color-stop(0.76, rgba(255,255,255,0)),
color-stop(1.00, rgba(255,255,255,0))
), -webkit-gradient(linear, left bottom, left top, color-stop(0, #8ad148), color-stop(1, #4bbf30));
background: -moz-repeating-linear-gradient(top left -30deg,
rgba(255,255,255,0.17),
rgba(255,255,255,0.17) 5px,
rgba(255,255,255,0) 5px,
rgba(255,255,255,0) 10px
), -moz-linear-gradient(#8ad148 0%, #4bbf30 100%);
-webkit-box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #83c849;
-moz-box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #83c849;
box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #83c849;
border: 1px solid #CACACA;
-webkit-animation: animate-stripes 2s linear infinite;
}
.ui-progress span.ui-label {
font-size: 0.75em;
position: absolute;
right: 0;
line-height: 13px;
padding-right: 3px;
color: rgba(0,0,0,0.6);
text-shadow: rgba(255,255,255, 0.45) 0 1px 0px;
white-space: nowrap;
}
<|start_filename|>public_map/assets/css/mapmint-fixes.css<|end_filename|>
.dataTables_wrapper .dataTables_paginate .paginate_button{
padding: 0;
}
body.dragging, body.dragging * {
cursor: move !important;
}
.dragged {
position: absolute;
opacity: 0.5;
z-index: 2000;
}
ul.draggable li{
cursor: "pointer";
}
ul.draggable li.placeholder {
position: relative;
padding: 10px 15px;
border: 1px solid #ddd;
margin-bottom: -1px;
/** More li styles **/
}
ul.draggable li.placeholder:before {
position: absolute;
content: ">";
/** Define arrowhead **/
}
#dashUsers .tab-pane{
display: none;
}
#dashUsers .tab-pane.active{
display: block;
}
i{
font-style: unset;
}
[class*=" mif-"], [class^="mif-"] {
vertical-align: unset;
}
.ds_um_groups_f .col-sm-1, .ds_um_groups_f .col-sm-2, .ds_um_groups_f .col-sm-3, .ds_um_groups_f .col-sm-4, .ds_um_groups_f .col-sm-5, .ds_um_groups_f .col-sm-6, .ds_um_groups_f .col-sm-7, .ds_um_groups_f .col-sm-8, .ds_um_groups_f .col-sm-9, .ds_um_groups_f .col-sm-10, .ds_um_groups_f .col-sm-11, .ds_um_groups_f .col-sm-12{
align-content: center;
text-align: center;
}
.symbol-up {
color: #b4b4b4;
display: inline-block;
margin-left: -1.28571em;
margin-right: -1.28571em;
margin-top: 0;
position: relative;
}
.symbol-multi{
position: relative;
display: inline-flex;
width: 1.28571em;
}
input[type="file"] {
border-radius: 4px;
display: block;
line-height: 1.02857;
padding: 0 4px;
}
.myWell{
padding: 9px;
}
/**
* Typeahead Styles
*/
.twitter-typeahead{
float:left;
background-color: #fff;
}
.typeahead,
.tt-query,
.tt-hint {
width: 100%;
height: 30px;
padding: 8px 12px;
font-size: 12px;
line-height: 30px;
border: 2px solid #ccc;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
outline: none;
}
.typeahead {
background-color: #fff;
}
.typeahead:focus {
border: 2px solid #0097cf;
}
.tt-query {
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
color: #999
}
.tt-menu {
width: 150%;
margin: 12px 0;
padding: 8px 0;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.2);
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
-moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.tt-suggestion {
padding: 3px 20px;
font-size: 14px;
line-height: 20px;
}
.tt-suggestion:hover {
cursor: pointer;
color: #fff;
background-color: #0097cf;
}
.tt-suggestion.tt-cursor {
color: #fff;
background-color: #0097cf;
}
.tt-suggestion p {
margin: 0;
}
.tt-menu {
max-height: 150px;
overflow-y: auto;
}
.fa-caret-ul::before,.fa-caret-uc::before,.fa-caret-ur::before,.fa-caret-cl::before,.fa-caret-ll::before,.fa-caret-lr::before{
content: "\f0d9";
}
.fa-caret-ul{
-ms-transform:rotate(45deg); /* Internet Explorer 9 */
-webkit-transform:rotate(45deg); /* Chrome, Safari, Opera */
transform:rotate(45deg); /* Standard syntax */
}
.fa-caret-uc{
-ms-transform:rotate(90deg); /* Internet Explorer 9 */
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}
.fa-caret-ur{
-ms-transform:rotate(135deg); /* Internet Explorer 9 */
-webkit-transform:rotate(135deg); /* Chrome, Safari, Opera */
transform:rotate(135deg); /* Standard syntax */
}
.fa-caret-cl{
}
.fa-caret-cr::before{
content: "\f0da";
}
.fa-caret-lc::before{
content: "\f0d7";
}
.fa-caret-ll{
-ms-transform:rotate(315deg); /* Internet Explorer 9 */
-webkit-transform:rotate(315deg); /* Chrome, Safari, Opera */
transform:rotate(315deg); /* Standard syntax */
}
.fa-caret-lr{
-ms-transform:rotate(225deg); /* Internet Explorer 9 */
-webkit-transform:rotate(225deg); /* Chrome, Safari, Opera */
transform:rotate(225deg); /* Standard syntax */
}
.ol-zoomslider-thumb{
left: -1px;
width: 100% !important;
}
.navbar-light .navbar-nav .nav-link {
color: rgb(64, 64, 64);
}
.btco-menu li > a {
padding: 10px 15px;
color: #000;
}
.btco-menu .active a:focus,
.btco-menu li a:focus ,
.navbar > .show > a:focus{
background: transparent;
outline: 0;
}
.dropdown-menu .show > .dropdown-toggle::after{
transform: rotate(-90deg);
}
.marginBottom-0 {margin-bottom:0;}
.dropdown-submenu{position:relative;}
.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px;}
.dropdown-submenu>a:after{display:block;content:" ";float:right;width:0;height:0;border-color:transparent;border-style:solid;border-width:5px 0 5px 5px;border-left-color:#cccccc;margin-top:5px;margin-right:-10px;}
.dropdown-submenu:hover>a:after{border-left-color:#555;}
.dropdown-submenu.pull-left{float:none;}.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px;}
.note-editor.note-frame .note-editing-area .note-editable {
margin-top: 30px;
}
.note-editor.note-frame.codeview .note-editing-area .note-codable{
margin-top: 30px;
}
.dropdown-item.active, .dropdown-item.active, .dropdown-item.active {
background-color: #2e6da4;
background-image: -webkit-linear-gradient(top,#337ab7 0,#2e6da4 100%);
background-image: -o-linear-gradient(top,#337ab7 0,#2e6da4 100%);
background-image: -webkit-gradient(linear,left top,left bottom,from(#337ab7),to(#2e6da4));
background-image: linear-gradient(to bottom,#337ab7 0,#2e6da4 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0);
background-repeat: repeat-x;
color: #fff;
}
<|start_filename|>mapmint-ui/templates/preview/modules/news/display.html<|end_filename|>
#import zoo
#from manage_users import *
#import authenticate.service as auth
#set con=auth.getCon($conf)
#set prefix=auth.getPrefix($conf)
#set c=con.connect()
#set conn = con.conn
#set cur=conn.cursor()
#set clause=""
#for i in $conf["senv"]["group"].split(",")
#if clause!=""
#set $clause+=" or "
#end if
#set $clause+=" name = '"+$i+"' "
#end for
#set res=cur.execute('SELECT title,p_date,content from '+prefix+'news where id = '+inputs["id"]["value"]+') order by p_date desc LIMIT 4')
#set vals=cur.fetchall()
<h1>$vals[i][0] ($vals[i][1])</h1>
$vals[i][2]
<|start_filename|>mapmint-services/vector-tools-src/cgi-env/service.js<|end_filename|>
var zoo_url;
function Buffer(inputData,bDist){
// Create all required ZOO.formats
var fJ=new ZOO.Format.JSON();
var fGJ=new ZOO.Format.GeoJSON();
var fWPS=new ZOO.Format.WPS();
// Pass the value as json
var myInputs = {InputPolygon: { type: 'complex', value: fGJ.write(inputData), mimeType: "application/json"}, BufferDistance: {type: 'float', "value": bDist } };
var myOutputs= {Result: { type: 'RawDatautput', "mimeType": "application/json" }};
var myProcess = new ZOO.Process(zoo_url,'vector-tools.BufferPy');
var myExecuteResult=myProcess.Execute(myInputs,myOutputs);
// Parse the result and extract JSON geometry
alert(myExecuteResult);
//var bufferResult=fWPS.read(myExecuteResult);
var bufferResultAsGeoJSON=fJ.read(myOutputs);
return fGJ.read(bufferResultAsGeoJSON);
}
function BufferWOParse(inputData,bDist){
// Create all required ZOO.formats
var fJ=new ZOO.Format.JSON();
var fGJ=new ZOO.Format.GeoJSON();
var fWPS=new ZOO.Format.WPS();
// Pass the value as json
var myInputs = {InputPolygon: { type: 'complex', value: fGJ.write(inputData), mimeType: "application/json"}, BufferDistance: {type: 'float', "value": bDist } };
var myOutputs= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
var myProcess = new ZOO.Process(zoo_url,'vector-tools.BufferPy');
var myExecuteResult=myProcess.Execute(myInputs,myOutputs);
// Parse the result and extract JSON geometry
return myExecuteResult;
}
function BufferMask(conf,inputs,outputs){
zoo_url=conf["main"]["serverAddress"];
// Create all required ZOO.formats
var fGJ=new ZOO.Format.GeoJSON();
var fGML=new ZOO.Format.GML();
alert("ok",inputs["InputData"]["value"]);
// Read the input GML
var inputData=fGML.read(inputs["InputData"]["value"]);
alert("ok");
// Compute big Buffer
zoo_url=conf["main"]["serverAddress"];
var bufferResultAsJSON=Buffer(inputData,2.5);
// Create the Buffer result BBOX
var bbox = new ZOO.Bounds();
var bounds=bufferResultAsJSON[0].geometry.getVertices();
for(var t in bounds){
bbox.extend(bounds[t]);
}
var finalG=bbox.toGeometry();
// Compute Buffer standard buffer
var bufferResultAsJSON=BufferWOParse(inputData,inputs["BufferDistance"]["value"]);
// Request Difference service using Buffer result and features in the BBOX
var result=new ZOO.Feature(finalG,{"fid": "1","name": "Result1000"});
var myProcess2 = new ZOO.Process(zoo_url,'+"vector-tools.DifferencePy');
var myInputs2 = {InputEntity1: { type: 'complex', value: fGJ.write(bbox.toGeometry()), mimeType: "application/json" }, InputEntity2: { type: 'complex', value: bufferResultAsJSON, mimeType: "application/json"} };
var myOutputs2= {Result: { type: 'RawDataOutput', "mimeType": "application/json" } };
var myExecuteResult4=myProcess2.Execute(myInputs2,myOutputs2);
return {result: ZOO.SERVICE_SUCCEEDED, outputs: [ {name:"Result", mimeType: "application/json", value: myExecuteResult4} ] };
}
function SpatialQuery(conf,inputs,outputs){
zoo_url=conf["main"]["serverAddress"];
// Create all required ZOO.formats
var fGJ=new ZOO.Format.GeoJSON();
var fGML=new ZOO.Format.GML();
// Read the input GML
var inputData=fGML.read(inputs["InputData"]["value"]);
// Compute Buffer
zoo_url=conf["main"]["serverAddress"];
var bufferResultAsJSON=BufferWOParse(inputData,inputs["BufferDistance"]["value"]);
// Create the Buffer result BBOX
var myProcess3 = new ZOO.Process(conf["main"]["serverAddress"],'vector-tools.EnvelopePy');
var myInputs3 = {InputPolygon: { type: 'complex', value: bufferResultAsJSON, mimeType: "application/json"}};
var myOutputs3= {Result: { type: 'RawDataOutput', "mimeType": "application/json" } };
var myExecuteResult3=myProcess3.Execute(myInputs3,myOutputs3);
var data=myExecuteResult3;
alert(data);
data = data.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, "");
data = new XML(data);
var lc = data..*::LowerCorner;
lc=lc.split(' ');
var uc = data..*::UpperCorner;
uc=uc.split(' ');
// Request Intersection service using Buffer result and WFS request using the
// BBOX
var myProcess2 = new ZOO.Process(conf["main"]["serverAddress"],'vector-tools.IntersectionPy');
var myInputs2 = {InputEntity1: { type: 'complex', value: bufferResultAsJSON, mimeType: "application/json"}, InputEntity2: { type: 'complex', xlink: conf["main"]["mapserverAddress"]+"?map="+conf["main"]["dataPath"]+"/public_maps/project_"+conf["senv"]["last_map"]+".map&SERVICE=WFS&version=1.0.0&request=GetFeature&typename="+inputs["layer"]["value"]+"&SRS=EPSG:4326&BBOX="+lc[0]+","+lc[1]+","+uc[0]+","+uc[1], mimeType: "text/xml" } };
var myOutputs2= {Result: { type: 'RawDataOutput', "mimeType": outputs["Result"]["mimeType"] } };
var myExecuteResult4=myProcess2.Execute(myInputs2,myOutputs2);
return {result: ZOO.SERVICE_SUCCEEDED, outputs: [ {name:"Result", mimeType: outputs["Result"]["mimeType"], value: myExecuteResult4} ] };
}
function createGrid(conf,inputs,outputs){
var myProcess1 = new ZOO.Process(conf["main"]["serverAddress"],'vector-converter.convert');
var ext=inputs["extent"]["value"].split(",");
alert("SELECT * from (SELECT geom AS geomWKT FROM ST_RegularGrid(ST_Transform(ST_SetSRID(ST_GeomFromText('LINESTRING("+ext[0]+" "+ext[1]+", "+ext[2]+" "+ext[3]+")',0),3857),32628),1,100,100,false)) as foo WHERE ST_Intersects(foo.geomWKT,(SELECT ST_Transform(wkb_geometry,32628) FROM forets where auto_id='"+inputs["id"]["value"]+"'))");
var layerData="produced_polygones_"+inputs["id"]["value"]+"_"+(conf["lenv"]["usid"].replace(/-/g,"_"));
alert(layerData);
var myInputs1 = {
"sql": { type: 'string', value: "SELECT * from (SELECT geom AS geomWKT FROM ST_RegularGrid(ST_Transform(ST_SetSRID(ST_GeomFromText('LINESTRING("+ext[0]+" "+ext[1]+", "+ext[2]+" "+ext[3]+")',0),3857),32628),1,100,100,false)) as foo WHERE ST_Intersects(foo.geomWKT,(SELECT ST_Transform(wkb_geometry,32628) FROM forets where ogc_fid='"+inputs["id"]["value"]+"'))"},
"dst_in": { type: "string", value: conf["main"]["dbuserName"] },
"dso_in": { type: "string", value: "forets" },
"dso_f": { type: "string", value: "PostgreSQL" },
"dst_out": { type: "string", value: conf["main"]["dbuserName"] },
"dso_out": { type: "string", value: layerData },
};
/* var myInputs1 = {
"sql": { type: 'string', value: "SELECT * from (SELECT geom AS geomWKT FROM ST_RegularGrid(ST_Transform(ST_SetSRID(ST_GeomFromText('LINESTRING("+ext[0]+" "+ext[1]+", "+ext[2]+" "+ext[3]+")',0),3857),32628),1,100,100,false)) as foo"},
"dst_in": { type: "string", value: conf["main"]["dbuserName"] },
"dso_in": { type: "string", value: "forets" },
"dso_f": { type: "string", value: "PostgreSQL" },
"dst_out": { type: "string", value: conf["main"]["dbuserName"] },
"dso_out": { type: "string", value: layerData },
//"dso_f": { type: "string", value: "ESRI Shapefile" },
//"dst_out": { type: "string", value: conf["main"]["dataPath"]+"/data_"+conf["lenv"]["usid"]+".shp" },
//"dso_out": { type: "string", value: "data_"+conf["lenv"]["usid"] },
};*/
var myOutputs1= {Result: { type: 'RawDataOutput', "mimeType": "application/json" } };
var myExecuteResult1=myProcess1.Execute(myInputs1,myOutputs1);
alert(myExecuteResult1);
var myProcess2 = new ZOO.Process(conf["main"]["serverAddress"],'mapfile.updateGridStyle');
var myInputs2 = {
"extent": { type: "string", value: inputs["extent"]["value"] },
"data": { type: "string", value: layerData }
};
var myOutputs2= {Result: { type: 'RawDataOutput', "mimeType": "text/plain" } };
var myExecuteResult2=myProcess2.Execute(myInputs2,myOutputs2);
alert(myExecuteResult2);
outputs["Result"]["value"]=conf["main"]["dataPath"]+"/grids/project_gridStyle_"+layerData+".map";
return {result: ZOO.SERVICE_SUCCEEDED, outputs: outputs };
}
function createTindex(conf,inputs,outputs){
var myProcess1 = new ZOO.Process(conf["main"]["serverAddress"],'datastores.directories.listJson');
var myOutputs1= {Result: { type: 'RawDataOutput', "mimeType": "application/json" } };
var myExecuteResult1=myProcess1.Execute(inputs,myOutputs1);
alert(myExecuteResult1);
var files=eval(myExecuteResult1);
var myInputs1 = {
"files": {"type": "string","isArray": "true","length": files.length, "value": files},
"OutputName": {"type": "string","value":conf["main"]["dataPath"]+"/dirs/"+inputs["idir"]["value"]+"/vtile_"+inputs["OutputName"]["value"]+".shp" }
};
var myProcess2 = new ZOO.Process(conf["main"]["serverAddress"],'vector-tools.Ogrtindex');
var myOutputs2= {Result: { type: 'RawDataOutput', "mimeType": "application/json" } };
var myExecuteResult2=myProcess2.Execute(myInputs1,myOutputs2);
alert(myExecuteResult2);
if(myExecuteResult2.indexOf("ExceptionReport")>=0){
conf["lenv"]["message"]=ZOO._("Unable to create the vector tileindex!");
return {result: ZOO.SERVICE_FAILED,conf:conf};
}
else{
outputs["Result"]["value"]=myExecuteResult2;
return {result: ZOO.SERVICE_SUCCEEDED, outputs: outputs};
}
}
<|start_filename|>mapmint-ui/templates/login_bs.html<|end_filename|>
#from Skeleton_bs import Skeleton_bs
#extends Skeleton_bs
#import zoo
#attr $ocss = ['main.css','login.css']
#attr $js = ['jquery.notifyBar.js','jquery.cookie.js','login.js','Meta.js','roundies.js']
#attr $js1 = ['minimal_js']
#def page_title
MapMint: $zoo._("Login")
#end def
#def body
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Please Sign In</h3>
</div>
<div class="panel-body">
<form role="form">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email" type="email" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="">
</div>
<div class="checkbox">
<label>
<input name="remember" type="checkbox" value="Remember Me">Remember Me
</label>
</div>
<!-- Change this to a button or input when using this as a form -->
<a href="index.html" class="btn btn-lg btn-success btn-block">Login</a>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
#end def
<|start_filename|>mapmint-ui/new-themes/themes/green/ui.css<|end_filename|>
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active {text-shadow: #777777 0px 1px 0px;background:#FFFFFF;font-weight: normal;color:#FFFFFF;}
#nav li a.ui-state-active{background:#707070 !important;}
.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555; text-decoration: none; }
.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { text-shadow: #777777 0px 1px 0px;
background:#83c849;font-weight: normal; color: #FFFFFF; }
.ui-state-hover a, .ui-state-hover a:hover { color: #FFFFFF; text-decoration: none; }
#nav li a.ui-state-focus{background:#707070;}
<|start_filename|>mapmint-ui/new-themes/themes/green/body.css<|end_filename|>
p.credits a:hover{text-decoration:underline;color:#83c849;}
<|start_filename|>mapmint-services/osm-tools/service.js<|end_filename|>
function importOSMPoints(conf,inputs,outputs){
var myProcess = new ZOO.Process(conf["main"]["serverAddress"],'osm-tools.createShpFromOSMP');
inputs["osm"]={type: "complex", xlink: conf["mm"]["osmApiUrl"]+"node[not(way)][bbox="+inputs["bbox"]["value"]+"]"};
var myOutputs= {"Result": { type: 'RawDataOutput', "mimeType": "text/plain" } };
alert(inputs["osm"]["xlink"]);
var myExecuteResult=myProcess.Execute(inputs,myOutputs);
return {result: ZOO.SERVICE_SUCCEEDED, outputs: {"Result": {"value": myExecuteResult,"dataType": "string"} }};
}
function importOSMLines(conf,inputs,outputs){
var myProcess = new ZOO.Process(conf["main"]["serverAddress"],'osm-tools.createShpFromOSML');
inputs["osm"]={type: "complex", xlink: conf["mm"]["osmApiUrl"]+"way[highway=*][bbox="+inputs["bbox"]["value"]+"]"};
var myOutputs= {"Result": { type: 'RawDataOutput', "mimeType": "text/plain" } };
var myExecuteResult=myProcess.Execute(inputs,myOutputs);
return {result: ZOO.SERVICE_SUCCEEDED, outputs: {"Result": {"value": myExecuteResult,"dataType": "string"} }};
}
<|start_filename|>public_map/window.css<|end_filename|>
.panel-tool-close{
background:url('./img/panel_tools.gif') no-repeat -16px 0px;
}
.panel-tool-min{
background:url('./img/panel_tools.gif') no-repeat 0px 0px;
}
.panel-tool-max{
background:url('./img/panel_tools.gif') no-repeat 0px -16px;
}
.panel-tool-restore{
background:url('./img/panel_tools.gif') no-repeat -16px -16px;
}
.panel-tool-collapse{
background:url('./img/panel_tool_collapse.gif') no-repeat;
}
.panel-tool-expand{
background:url('./img/panel_tool_expand.gif') no-repeat;
}
.panel-loading{
padding:11px 0px 10px 30px;
background:url('./img/panel_loading.gif') no-repeat 10px 10px;
}
a.l-btn:hover{
color:#FFFFFF;
text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F'); /* for IE */
}
#gfi-dialog{width:550px;height:400px;padding:0;}
#output-gfi{width:100%;margin:0;}
.sasc, .bbDiv{font-size:.85em;}
<|start_filename|>mapmint-ui/css/jquery.notifyBar.css<|end_filename|>
/*
* Notify Bar - jQuery plugin
*
* Copyright (c) 2009-2010 <NAME>
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Version: 1.2
*
* Project home:
* http://www.dmitri.me/blog/notify-bar
*/
.jquery-notify-bar {
width:100%;
height:25px;
position:fixed;
top:0;
left:0;
z-index:32768;
text-transform:uppercase;
font-size:1.4em;
color:#000;
text-align:center;
font-family: Verdana, sans-serif;
padding:12px 0px;
border-bottom:1px solid #bbb;
}
.jquery-notify-bar.error {
color:#f00;
background-color:#fdd;
}
.jquery-notify-bar.success {
color:#FFFFFF;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */;
}
.notify-bar-close {
position:absolute;
left:95%;
font-size:11px;
}
.dialog-loading{
background:#E0E0E0;
}
.load{
margin:0;padding:0;
}
<|start_filename|>public_map/assets/js/themes.js<|end_filename|>
// Filename: login.js
define([
'module', 'jquery', 'zoo','notify', 'metisMenu', 'summernote', 'xml2json','typeahead', 'adminBasic', 'ol','datasources','mmDataTables','rowReorder','colorpicker','slider',"sortable"
], function(module, $,Zoo,notify, metisMenu, summernote, X2JS,typeahead,adminBasic,ol,datasources,MMDataTable,rowReorder,colorpicker,slider,sortable) {
(function(){
var methods = ['addClass', 'removeClass'];
$.each(methods, function (index, method) {
var originalMethod = $.fn[method];
$.fn[method] = function () {
var oldClass = this.className;
var result = originalMethod.apply(this, arguments);
var newClass = this.className;
this.trigger(method, [oldClass, newClass]);
return result;
};
});
})();
var _x2js = new X2JS({
arrayAccessFormPaths: [
'ProcessDescriptions.ProcessDescription.DataInputs.Input',
'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
'Capabilities.ServiceIdentification.Keywords'
],
});
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
language: module.config().language
});
var llevels=["first","second","third","forth"];
var llevelInit=false;
var reg0=new RegExp("themes_","");
function addToThemes(oid,data,level,init){
var toActivate=-1;
var cnt=0;
for(var id=0;id<data.length;id++){
$("#themes_pid").append('<option value="'+data[id]["id"]+'">'+data[id]["text"]+'</option>');
console.log("addToThemes "+id);
if(data[id]["children"]){
var regs=[
new RegExp("\\[id\\]","g"),
new RegExp("\\[lid\\]","g"),
new RegExp("\\[level\\]","g")
];
var myHTML=$("#group_template")[0].innerHTML
.replace(regs[0],data[id]["text"])
.replace(regs[1],"theme_"+data[id]["id"])
.replace(regs[2],llevels[level]);
if(!llevelInit){
llevelInit=true;
$("#themeswitcher").parent().append(myHTML);
if(!init)
loadATheme(data[0]["id"]);
}
else{
if(oid=="themeswitcher")
$("#themeswitcher").parent().append(myHTML);
else
$("#themeswitcher").parent().find('ul#'+oid).last().append(myHTML);
}
addToThemes("theme_"+data[id]["id"]+"_t",data[id]["children"],level+1,init);
}else{
var regs=[
new RegExp("\\[id\\]","g"),
new RegExp("\\[lid\\]","g")
];
var myHTML=$("#item_template")[0].innerHTML
.replace(regs[0],data[id]["text"])
.replace(regs[1],"theme_"+data[id]["id"]);
if(!llevelInit){
llevelInit=true;
$("#themeswitcher").parent().append(myHTML);
if(!init)
loadATheme(data[0]["id"]);
}
else{
console.log(data);
console.log(oid);
if(oid=="themeswitcher")
$("#themeswitcher").parent().append(myHTML);
else
$("#themeswitcher").parent().find('ul#'+oid).last().append(myHTML);
}
}
}
}
function loadThemes(init){
zoo.execute({
identifier: "np.list",
type: "POST",
dataInputs: [
{"identifier": "table","value": "themes","dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log("SUCCESS");
console.log(data);
if(init)
$("#themeswitcher").parent().find(".li-theme").remove();
var cnt=0;
$("#themes_pid").find("option").each(function(){
if(cnt>0){
$(this).remove();
}
cnt+=1;
});
addToThemes("themeswitcher",data,1,init);
//$("#themeswitcher").parent().find("#theme_"+data[0]["id"]).addClass("active");
bindThemes();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function fillForm(data){
$(".project-title").html(data["name"]);
var myRootLocation=$(".themeForm");
var reg=new RegExp("themes_","");
myRootLocation.find("input,select").each(function(){
if($(this).attr("type")=="text"){
if($(this).attr("id").replace(/color/g,"")!=$(this).attr("id")){
if(data[$(this).attr("id").replace(reg,"")])
$(this).val("#"+data[$(this).attr("id").replace(reg,"")]).change();
else
$(this).val("#000").change();
}
else
$(this).val(data[$(this).attr("id").replace(reg,"")])
}else{
$(this).find('option').prop('selected', false);
if($.isArray(data[$(this).attr("id").replace(reg,"")])){
if(data[$(this).attr("id").replace(reg,"")].length==0)
$(this).find('option[value="1"]').prop("selected",true);
for(var i=0;i<data[$(this).attr("id").replace(reg,"")].length;i++){
$(this).find('option[value="'+data[$(this).attr("id").replace(reg,"")][i]+'"]').prop("selected",true);
}
}else{
$(this).val((data[$(this).attr("id").replace(reg,"")]!=null?data[$(this).attr("id").replace(reg,"")]:-1));
}
console.log($(this).val());
}
});
}
function loadATheme(id){
console.log("loadATheme -> "+id);
console.log($("#themeswitcher").parent().find("#theme_"+id));
$("#themeswitcher").parent().find("#theme_"+id).addClass("active");
$(".themeForm").find(".fa-spin").removeClass("hide");
$("#themeswitcher").find("#tdelete").removeClass("disabled");
//fillForm(null);
zoo.execute({
identifier: "np.details",
type: "POST",
dataInputs: [
{"identifier": "table","value": "themes","dataType":"string"},
{"identifier": "id","value": id,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log("SUCCESS");
fillForm(data);
$(".themeForm").find(".fa-spin").addClass("hide");
//addToThemes("themeswitcher",data,1);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function createJsonFromForm(form){
var params={};
form.find('input[type="text"]').each(function(){
if($(this).attr("id").replace(/color/g,"")!=$(this).attr("id"))
params[$(this).attr('id').replace(reg0,"")]=$(this).val().replace(/#/,"");
else
params[$(this).attr('id').replace(reg0,"")]=$(this).val();
});
form.find('select').each(function(){
if($(this).find("option:selected").length>1){
var oid=$(this).attr('id').replace(reg0,"");
params[oid]=[];
$(this).find("option:selected").each(function(){
params[oid].push($(this).val());
});
}else{
params[$(this).attr('id').replace(reg0,"")]=$(this).val();
}
});
return params;
}
function saveATheme(id){
$(".themeForm").find(".fa-spin").removeClass("hide");
var obj=createJsonFromForm($(".themeForm"));
obj["id"]=id;
console.log(obj);
zoo.execute({
identifier: "np.updateElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": "themes","dataType":"string"},
{"identifier": "themes_groups_in","value": "t_id","dataType":"string"},
{"identifier": "themes_groups_out","value": "g_id","dataType":"string"},
{"identifier": "indicators_themes_in","value": "t_id","dataType":"string"},
{"identifier": "indicators_themes_out","value": "i_id","dataType":"string"},
{"identifier": "tuple","value": JSON.stringify(obj, null, ' '),"mimeType":"application/json"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
$(".themeForm").find(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
loadATheme(id);
loadThemes(true);
//addToThemes("themeswitcher",data,1);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function addATheme(){
$(".themeForm").find(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.insertElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": "themes","dataType":"string"},
{"identifier": "name","value": $(".addForm").find('input[name="tname"]').val(),"mimeType":"application/json"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
$(".themeForm").find(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
//loadATheme(id);
loadThemes(true);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function deleteATheme(id){
$(".themeForm").find(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.deleteElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": "themes","dataType":"string"},
{"identifier": "themes_groups_in","value": "t_id","dataType":"string"},
{"identifier": "themes_groups_out","value": "g_id","dataType":"string"},
{"identifier": "indicateurs_themes_in","value": "t_id","dataType":"string"},
{"identifier": "indicateurs_themes_out","value": "i_id","dataType":"string"},
{"identifier": "id","value": id,"mimeType":"application/json"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
$(".themeForm").find(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
loadThemes(true);
//addToThemes("themeswitcher",data,1);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function bindThemes(){
$("#themeswitcher").parent().find(".theme").each(function(){
$(this).off('click');
$(this).click(function(e){
e.preventDefault();
e.stopPropagation();
$("#themeswitcher").parent().find(".theme").removeClass("active");
$(this).addClass("active");
loadATheme($(this).attr('id').replace(/theme_/g,""));
});
});
}
function bindSaveTheme(){
$(".themeForm").find("button").each(function(){
console.log($(this));
$(this).off('click');
$(this).click(function(){
console.log($(this));
try{
var elem=$("#themeswitcher").parent().find(".theme.active");
console.log(elem);
saveATheme(elem.attr('id').replace(/theme_/g,""));
}catch(e){
console.log(e);
}
return false;
});
});
}
var initialize=function(){
adminBasic.initialize(zoo);
$('[data-toggle="tooltip"]').tooltip({container: 'body'});
loadThemes();
bindSaveTheme();
console.log("Start Themes");
$(".cpicker").colorpicker({format: "hex"});
var cnt=0;
$("#themeswitcher").find(".btn-group").find('button').each(function(){
$(this).click(function(){
var cid=$(this).attr('id');
rootElement=$("."+cid.replace(/t/,"")+"Form");
if(rootElement.hasClass("hide")){
if(cid=="tdelete")
rootElement.find('input[name="tname"]').val($(".themeForm").find("#themes_name").val());
rootElement.removeClass("hide");
}
else
rootElement.addClass("hide");
});
cnt+=1;
});
$("#add-theme").click(function(){
addATheme();
$(this).parent().prev().val("");
$(".addForm").addClass("hide");
});
$("#delete-theme").click(function(){
var elem=$("#themeswitcher").parent().find(".theme.active");
console.log(elem);
deleteATheme(elem.attr('id').replace(/theme_/g,""));
$(".deleteForm").addClass("hide");
});
};
// Return public methods
return {
initialize: initialize,
};
});
<|start_filename|>mapmint-ui/css/blue-old.css<|end_filename|>
body {
font: 12px Verdana, Arial, Helvetica, sans-serif;
background: url(images/main-bg2.png);
padding: 0;
margin: 0;
}
/*** IMPORTANT - Layout container MUST have a 'height' or will be 'invisible' ***/
.inner-layout-container { height: 100%; }
.ui-layout-center ,
.ui-layout-north ,
.ui-layout-south ,
.inner-center ,
.inner-west ,
.inner-east {
/* prevent 'Flash Of Content' - panes will show automatically when layout initializes */
display: none;
}
.ui-layout-north{
overflow:hidden;
background:#565656 url(../images/mapmint-logo2.png) no-repeat;
border:0;
margin:0;
padding:0;
height:50px;
max-height:50px;
}
.ui-layout-south{
overflow:hidden;
background:#565656;
border:0;
margin:0;
padding:0;
height:50px;
max-height:50px;
}
.ui-layout-resizer { /* all 'resizer-bars' */
background: transparent;
}
.inner-center ,
.inner-west ,
.inner-east {
padding: 20px; /* SAMPLE formatting */
}
/* remove scrollbar from panes that have a 'srolling content div' */
.inner-layout-container .ui-layout-pane {
overflow: hidden; /* prevent temporary 'flash' of scrollbar - using a scrolling div instead */
}
/* format content-div */
.ui-layout-content {
padding: 10px;
overflow: auto; /* REQUIRED if you want it to 'scroll' */
}
/* add some formatting to headers */
.pane-header {
padding: 3px 10px;
margin-bottom: 10px; /* space between header and content-div below */
}
/* SAMPLE - padding on inner-layout container */
.ui-layout-center { padding:0px; }
/* add some colors to distinguish outer from inner panes */
.ui-layout-center { background: transparent ; border:0; }
#order .ui-layout-pane { background: #E7E7E7; }
#engine .ui-layout-pane { background: #E7E7E7; }
<|start_filename|>mapmint-ui/templates/preview/modules/routing/view.html<|end_filename|>
#encoding UTF-8
#import zoo
#set cnt=0
<form>
<ul data-role="listview" data-inset="true" data-theme="d" data-dividertheme="c" id="routingForm">
#set tmp=["Depart","Arrivee"]
#set kk=0
#for i in ["start","end"]
<li data-role="fieldcontain">
<fieldset class="ui-grid-a">
$kk
<a href="#" data-role="button" onclick="System.idPoint='adresse$tmp[$kk]';globalResetAction(points_layer,$kk);routingForm(\$('#${i}Type').val());;" class="ui-block-d" data-icon="${i}Point">#if cnt==0#$zoo._("Start")#else#$zoo._("Target")#end if#</a>
<select id="${i}Type" class="ui-block-d" onchange="System.idPoint='adresse$tmp[$kk]';globalResetAction(points_layer,$kk);routingForm(\$(this).val());">
<option value="geocodingPage">$zoo._("Search")</option>
<option value="mapPage">$zoo._("On map")</option>
<option value="mapPage">$zoo._("Use my geolocation")</option>
</select>
</fieldset>
</li>
#set kk=$kk+1
#set cnt=$cnt+1
#end for
<li data-role="fieldcontain">
<h1>$zoo._("Priorities")</h1>
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<input type="radio" name="priority" id="pp0" /><label for="pp0">$zoo._("Security")</label>
<input type="radio" name="priority" id="pp1" checked="true" /><label for="pp1">$zoo._("Default")</label>
<input type="radio" name="priority" id="pp2" /><label for="pp2">$zoo._("Distance")</label>
</fieldset>
</li>
<li data-role="fieldcontain">
<h1>$zoo._("Step")</h1>
<fieldset class="ui-grid-a">
<a href="#" data-role="button" onclick="routingFormAddPOI();" class="ui-block-d" data-icon="plus">$zoo._("Add")</a>
<a href="#" data-role="button" onclick="routingFormDeletePOI();" class="ui-block-d hidden" data-icon="minus" id="routingDeletePoi">$zoo._("Delete")</a>
</fieldset>
</li>
</ul>
<a href="#" data-role="button" onclick="pgrouting(points_layer);" data-icon="search"></span>$zoo._("Search")</a>
<a class="hidden" href="#routingSavePage" data-role="button" data-icon="info" id="routingSave">$zoo._("Save")</a>
<a class="hidden" href="#routingPoiListPage" data-role="button" data-icon="info" id="routingPoiInfo">$zoo._("POI Near By")</a>
<a class="hidden" href="#routingDetailsPage" data-role="button" data-icon="info" id="routingInfo">$zoo._("Informations")</a>
<a class="hidden" href="#routingProfilePage" data-role="button" data-icon="info" id="routingProfile" onclick="requestProfile();">$zoo._("Profile")</a>
<a class="hidden" href="#routingDownloadPage" data-role="button" data-icon="info" id="routingDownload" onclick="routingDownload();">$zoo._("Download")</a>
</form>
<|start_filename|>mapmint-ui/new-themes/themes/default/loader.css<|end_filename|>
.loader-container{
position: absolute;
width:100%;
height:100%;
background: url("../../img/loader-bck.png");
z-index: 1000;
}
#loader{
position:absolute;
height:50px;
width:50px;
margin:-50px 0px 0px -50px;
top: 50%;
left: 50%;
background:#000 url("../../img/loader.gif") no-repeat center center;
text-align: center;
border-radius: 10px;
-webkit-border-radius:10px;
-moz-border-radius:10px;
opacity:0.7;
z-index:1000;
}
<|start_filename|>public_map/assets/css/style_publica.css<|end_filename|>
body { overflow: hidden; }
@font-face {
font-family: 'PublicaMundi';
src:url('../fonts/publicamundi.eot');
src:url('../fonts/publicamundi.eot') format('embedded-opentype'),
url('../fonts/publicamundi.woff') format('woff'),
url('../fonts/publicamundi.ttf') format('truetype'),
url('../fonts/publicamundi.svg') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {font-family: 'GeoLabsLogo';src:url('../fonts/GeoLabsLogo.ttf') format('truetype');font-weight: normal;font-style: normal;}
[class^="icon-"], [class*=" icon-"] {
font-family: 'PublicaMundi';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-pm:before {
content: "\e601";
font-size:2em;
padding:10px 0 0 0;
}
.sml {
font-size:.6em !important;
color:#707070 !important;
padding: 0 !important;
}
[class^="icon-f-"], [class*=" icon-f-"] {
font-family: 'GeoLabsLogo';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-f-geolabs:before {
content: "\e666";
color:#707070;
}
.navbar-brand {
padding:5px 15px 5px 5px;
display: table-cell;
}
.navbar-brand i {color:#0a625c;}
.navbar-btn {
margin:7px 5px 0 0;
}
.btn-sml {
padding:7px 10px !important;
}
.navbar-offset { margin-top: 50px; }
.pm-demo-title {
color:#00a099;
padding:0 0 0 0;
margin:0 20px 0 0;
font-size:1.3em;
float:left;
line-height:50px;
}
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: 16px;
color:#707070;
font-weight:normal;
}
.panel-title a:hover {
text-decoration:none !important;
color:#00a099;
}
#map { position: absolute; top: 50px; bottom: 0px; left: 0px; right: 0px; z-index:35;}
#map .ol-zoom { font-size: 1.2em; }
.zoom-top-opened-sidebar { margin-top: 5px; }
.zoom-top-collapsed { margin-top: 45px; }
.mini-submenu{
display:none;
background-color: rgba(255, 255, 255, 0.7);
border: 1px solid #0a625c !important;
color:#0a625c;
border-radius: 4px;
padding: 9px;
width: 42px;
text-align: center;
}
.mini-submenu:hover{
background-color: rgba(255, 255, 255, 0.5);
border: 1px solid #00a099 !important;
color:#00a099;
}
.mini-submenu-left {
position: absolute;
top: 63px;
left: .5em;
z-index: 40;
}
.bl{height:24px;width:24px;border:1px solid #CCCCCC;border-radius:3px;display:inline-block;}
.osm{background:url(../img/osm.png);vertical-align:middle;}
.sidebar { z-index: 45; }
.main-row { position: relative; top: 0; }
.mini-submenu:hover{cursor: pointer;}
.slide-submenu{
background: #E0E0E0;
border:1px solid #CCCCCC;
color:#FFFFFF;
display: inline-block;
padding:4px 7px;
border-radius: 4px;
cursor: pointer;
font-size:.65em;
}
.slide-submenu:hover{
color:#00a099;
border:1px solid #00a099;
background:#FFFFFF;
}
.list-group-item{
padding:8px;
}
.list-group-item:hover{
color:#00a099 !important;
}
<|start_filename|>mapmint-ui/templates/Distiller/Projection_bs.html<|end_filename|>
#import zoo
<select id="${prefix}tprj" class="form-control">
#import sqlite3
#set conn = sqlite3.connect($conf['main']['dblink'])
#set c = $conn.cursor()
#set i=$c.execute(" SELECT code,name FROM spatial_ref_sys WHERE fav")
#set a=$c.fetchall()
#for i in $a
<option value="$i[0]" #if $selected is not None and $selected==$i[0]#selected#end if#>$i[1]</option>
#end for
</select>
<|start_filename|>public_map/assets/js/datasources.js<|end_filename|>
// Filename: login.js
define([
'module', 'jquery', 'zoo','notify', 'metisMenu', 'summernote', 'xml2json','typeahead', 'adminBasic'
], function(module, $,Zoo,notify, metisMenu, summernote, X2JS,typeahead,adminBasic) {
var _x2js = new X2JS({
arrayAccessFormPaths: [
'ProcessDescriptions.ProcessDescription.DataInputs.Input',
'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
'Capabilities.ServiceIdentification.Keywords'
],
});
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
language: module.config().language
});
function displayVector(data,param,dsid,datasource,location){
console.log(data);
//$("#DS_"+dsid+"_"+datasource).find(".panel-body").first().html('<div class="col-md-12"><table id="DS_table_'+dsid+'_'+datasource+'" ></table></div>');
location.html('<div class="col-md-12"><table id="DS_table_'+dsid+'_'+datasource+'" ></table></div>');
if(!data.datasource.fields.field.length)
data.datasource.fields.field=[data.datasource.fields.field];
var lcolumns=[];
for(var i in data.datasource.fields.field){
console.log(data.datasource.fields.field);
lcolumns.push({"data":data.datasource.fields.field[i].id,"name":data.datasource.fields.field[i].id,"title":data.datasource.fields.field[i].id});
}
var cnt=0;
var ldata=data;
$('#DS_table_'+dsid+'_'+datasource).DataTable( {
data: [],
"dom": 'Zlfrtip',
"colResize": true,
"scrollY": ($(window).height()/4)+"px",
"scrollCollapse": true,
"scrollX": true,
"sScrollX": "100%",
"sScrollXInner": "100%",
//"bAutoWidth": false,
"bProcessing": true,
"bServerSide": true,
fixedHeader: true,
//searching: true,
responsive: true,
deferRender: true,
rowId: "fid",
"sAjaxSource": "users",
select: {
info: false,
},
"lengthMenu": [[10, 25, 50, 150], [10, 25, 50, 150]],
columns: lcolumns,
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
console.log("Starting datatable download");
console.log(aoData);
var llimit=[];
for(j in {"iDisplayStart":0,"iDisplayLength":0,"iSortCol_0":0,"sSortDir_0":0,"sSearch":0})
for(i in aoData)
if(aoData[i].name==j){
if(llimit.length==4 && aoData[i].value!="")
llimit.push(aoData[i].value);
if(llimit.length<4)
llimit.push(aoData[i].value);
}
console.log(llimit);
console.log(lcolumns);
var opts=zoo.getRequest({
identifier: "vector-tools.mmExtractVectorInfo",
dataInputs: [
{"identifier":"dataSource","value":param,"dataType":"string"},
{"identifier":"layer","value":datasource,"dataType":"string"},
{"identifier":"getFeatures","value":"true","dataType":"boolean"},
{"identifier":"page","value":(llimit[0]/llimit[1])+1,"dataType":"integer"},
{"identifier":"limit","value":llimit[1],"dataType":"integer"},
{"identifier":"sortorder","value":llimit[3],"dataType":"string"},
{"identifier":"sortname","value":(lcolumns[llimit[2]].data),"dataType":"string"},
],
dataOutputs: [
{"identifier":"Result","mimeType":"text/xml","type":"raw"}
],
type: 'POST',
storeExecuteResponse: false
});
console.log(opts);
opts["success"]=function() {
console.log(arguments);
var obj=_x2js.xml_str2json( arguments[2].responseText );
var data=[];
if(!obj.FeatureCollection.featureMember.length)
obj.FeatureCollection.featureMember=[obj.FeatureCollection.featureMember];
for(var i in obj.FeatureCollection.featureMember){
data.push(obj.FeatureCollection.featureMember[i]);
data[data.length-1]["fid"]=dsid+"_"+datasource+"_"+(obj.FeatureCollection.featureMember[i][lcolumns[0].name].replace(/\./g,"__"));
}
var opts={
"sEcho": cnt++,
"iDraw": cnt++,
"iTotalRecords": ldata.datasource.featureCount,
"iTotalDisplayRecords": ldata.datasource.featureCount,
"aaData": (ldata.datasource.featureCount>0?data:[])
};
fnCallback(opts);
$('#DS_table_'+dsid+'_'+datasource).find(".selected").removeClass("selected");
if(ldata.datasource.featureCount==0){
$('#DS_table_'+dsid+'_'+datasource).DataTable().clear();
}
};
opts["error"]=function(){
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
};
oSettings.jqXHR = $.ajax( opts );
}
});
}
var defaultColors=[
"#ee0a38",
"#169211",
"#1415db",
"#000000"
];
function displayRaster(data,param,dsid,datasource,location,height){
var Bands=[];
if(data["datasource"]["Band"].length){
for(i in data["datasource"]["Band"])
Bands.push({
name: "Band "+i,
color: defaultColors[i],
data: data["datasource"]["Band"]["histogram"].split(",")
});
}
else
Bands.push({
name: "Band 1",
color: "#97b2a0",
data: data["datasource"]["Band"]["histogram"].split(",")
});
for(i in Bands)
for(j in Bands[i]["data"])
Bands[i]["data"][j]=parseFloat(Bands[i]["data"][j]);
//$("#DS_"+dsid+"_"+datasource).find(".panel-body").first().html('<div id="DS_table_'+dsid+'_'+datasource+'" class="col-md-12"></div>');
location.html('<div id="DS_table_'+dsid+'_'+datasource+'" class="col-md-12"></div>');
var chart = new Highcharts.Chart({
chart: {
height: (height?height:500),
zoomType: 'x',
renderTo: 'DS_table_'+dsid+'_'+datasource
},
title: {
text: "Raster Histogram"
},
xAxis: {
labels: {
formatter: function(){
var tmp=this.value+"";
return tmp;
}
},
title: { text: 'Points' },
maxZoom: 0
},
yAxis: {
//max: mmax*2,
title: { text: null },
startOnTick: false,
showFirstLabel: false
},
legend: {
enabled: true
},
plotOptions: {
area: {
cursor: 'pointer',
fillColor: {
linearGradient: [0, 0, 0, 300],
stops: [
[0, '#97b2a0'],
[1, 'rgba(255,255,255,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 3
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
tooltip: {
formatter: function() {
return '<h1>'+this.x+': '+Highcharts.numberFormat(this.y, 0)+"</h1>";
}
},
series: Bands
});
}
// Return public methods
return {
displayRaster: displayRaster,
displayVector: displayVector,
};
});
<|start_filename|>public_map/css/mapmint-layout.css<|end_filename|>
body {
padding-top: 50px;
overflow: hidden;
}
#wrapper {
min-height: 100%;
height: 100%;
width: 100%;
position: absolute;
top: 0px;
left: 0;
display: inline-block;
}
#main-wrapper {
min-height: 100%;
height: 100%;
overflow-y: auto;
padding:0;
}
.fw{
width:100% !important;
}
#map { top:0px;left:0px;bottom:0px;right:0px; }
#sidebar-wrapper {
padding: 0;
height: 100%;
}
#sidebar {
position: relative;
overflow-y:hidden;
}
#sidebar .list-group{
margin-bottom:0}
#sidebar .list-group-item {
border-radius: 0;
border-left: 0;
border-right: 0;
border-top: 0;
}
#mmtabs{background:#EEEEEE;}
#mmcdts{background:#EEEEEE;padding:.7em 0 0 0;font-size:.85em;position:absolute;height:30px;width:100%;bottom:0;left:0;}
#mmcdts p{margin:0;font-size:.9em;}
#mmcdts a{color:#83c849;}
#mmcdts a:hover{color:#83c849;text-decoration:underline;}
@media (max-width: 980px) {
#main-wrapper {
display:block;
display:none;
z-index:10000;
}
#sidebar-wrapper {
float:left;
display:block;
width:100%;height:100%;
}
#map{position:absolute;z-index:1;}
}
.list-group-item {
padding: 5px 5px;
padding-right: 0px;
border: none;
}
.list-group-item .blc{height:44px;margin:0;padding:5px 0;}
.baselayers{list-style:none;text-align:left;margin:0;padding:0;}
.baselayers li{display:inline-block;}
input[type="checkbox"] {
margin-top: 0px;
margin-right: 0.5em;
vertical-align: 1px;
}
.baselayers,.tree-container{overflow:scroll;}
.tree{
}
.tree label {
color: #555;
font-weight:normal;
}
.tree label:hover {
text-decoration: none;
}
.tree label.tree-parent {
color: #222;
font-weight: bold;
}
.tree .layer label.tree-parent {
font-weight: unset;
}
.tree label.tree-parent:hover {
text-decoration: none;
}
.tree-node{width:16px;height:16px;background:#FFF;color:#CCC;margin-right:5px}
.tree-node span{font-weight:100!important;}
.toolbar li {border-right:1px solid #E3E3E3;}
#context-menu li a:hover{cursor:pointer !important;}
@media (max-width: 768px) {
.toolbar li {border-right:0;}
#context-menu > ul.dropdown-menu{position:absolute !important;top:0 !important;float:none !important;}
.navbar-brand{font-size:1em;}
.navbar-nav {
margin: 0 0;
}
.toolbar li a {
margin:0;
padding:6px;
}
}
.fixed-bottom {
position: absolute;
bottom: 0;
width: 100%;
height: 50%;
background-color: #f5f5f5;
}
.base_layer{
//display: table;
}
.base_layer span{
display: table-cel;
}
.base_layer_title {
}
.baselayers .list-group-item{
width: 98%;
}
.qrcodel{
width: 100%
}
.info-img-content{
text-align: center;
}
.info-img-content img{
width: 100%
}
#mm_layers_display .carousel-caption{
color: #000;
text-align: left;
text-shadow: inherit;
}
#mm_layers_display .carousel-indicators li{
border-color: #000;
}
#mm_layers_display .carousel-indicators li.active{
background-color: #000;
}
#mm_layers_display .carousel-control{
background: transparent;
color: #000;
z-index: 99;
}
.layer-active{
background: #eee;
/*border-bottom: 2px #eee solid;
text-decoration: underline;*/
}
.mmbtn-small{
line-height: 20px;
font-size: 0.85em;
margin-top:5px;
margin-right:5px;
}
<|start_filename|>mapmint-ui/templates/preview/modules/edit/view.html<|end_filename|>
#encoding UTF-8
#import zoo
#set cnt=0
#import psycopg2
#set dbstr=""
#for i in $conf["velodb"]
#if $i!="schema"
#set dbstr=$dbstr+" "+i+"="+$conf["velodb"][i]
#end if
#end for
#set con=psycopg2.connect($dbstr)
#set cur=con.cursor()
#set ret=cur.execute("SELECT id, title from categories")
#set res=cur.fetchall()
<form>
<ul data-role="listview" data-inset="true" data-theme="d" data-dividertheme="c"id="newsEditForm">
<li data-role="fieldcontain">
<label for="ntitle">$zoo._("Title: ")</label><input type="text" name="ntitle" id="ntitle" />
</li>
<li data-role="fieldcontain">
<label for="ncontent">$zoo._("Content: ")</label><textarea id="ncontent"></textarea>
</li>
<li data-role="fieldcontain">
<h1>$zoo._("Geolocation")</h1>
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain" id="nlonLat">
<label for="nlat">$zoo._("Lat: ")</label><input type="text" id="nlat" value="" />
<label for="nlong">$zoo._("Long: ")</label><input type="text" id="nlong" value="" />
</fieldset>
<input type="submit" id="npoi" onclick="try{routingForm('mapPage','#newsEditPage'),\$('#nlonLat').hide();}catch(e){alert(e)}return false;" value="$zoo._("On Map")" />
</li>
<li data-role="fieldcontain">
<h1>$zoo._("News type")</h1>
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
#for i in res
<input type="radio" name="ntype" value="$i[0]" id="ntype$cnt" #if $cnt==0#checked="true"#end if#/><label for="ntype$cnt">$zoo._($i[1].encode("utf-8"))</label>
#set $cnt+=1
#end for
</fieldset>
</li>
</ul>
<a href="#" data-role="button" onclick="try{saveNews()}catch(e){alert(e)}return false;" data-icon="search"></span>$zoo._("Save")</a>
</form>
<|start_filename|>public_map/assets/js/datatabletest.js<|end_filename|>
var _x2js = new X2JS();
var featureCount=0;
/*$.ajax({
"type": "GET",
"url": msUrl+"?map="+oLayers[key]["map"]+"&version=1.0.0&service=WFS&request=GetFeature&propertyname="+columns[0].name+"&typename="+key,
"success": function(document,status,data){
var cnt=0;
console.log(data);
var obj=_x2js.xml_str2json( data.responseText );
console.log(obj);
featureCount=obj["FeatureCollection"]["featureMember"].length;
console.log("COUNT "+featureCount);*/
$('#mm_table-content').DataTable( {
data: [],
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
/*var params={};
console.log(aoData);
var myAoData=[];
for(i in aoData)
if(aoData[i].name=="iDisplayLength"){
myAoData.push({name:"maxfeatures",value:aoData[i].value});
break;
}
var hasProp=false;
if(!hasProp){
for(i in aoData)
if(aoData[i].name=="sColumns"){
myAoData.push({name:"propertyname",value:aoData[i].value});
break;
}
}
console.log(hasProp);
for(i in aoData)
if(aoData[i].name=="iSortCol_0"){
for(j in aoData)
if(aoData[j].name=="sColumns"){
var tmp=aoData[j].value.split(",");
myAoData.push({name:"orderby",value: tmp[aoData[i].value]});
}
}*/
console.log(aoData);
oSettings.jqXHR = $.ajax( {
"type": "GET",
"url": sSource,
"data": aoData,
"success": function(document,status,data){
console.log(data);
var _x2js = new X2JS();
var obj=_x2js.xml_str2json( data.responseText );
console.log(obj);
var tuples=[];
for(i in obj["FeatureCollection"]["featureMember"]){
var tuple=[];
for(j in obj["FeatureCollection"]["featureMember"][i])
if(j[0]!="_"){
for(k in obj["FeatureCollection"]["featureMember"][i][j]){
if(k[0]!="_" && k!="boundedBy" && k!="msGeometry"){
tuple.push(obj["FeatureCollection"]["featureMember"][i][j][k]);
}
}
}
tuples.push(tuple);
}
console.log({
"sEcho": cnt+1,
"iTotalRecords": featureCount,
"iTotalDisplayRecords": tuples.length,
"aaData": tuples
});
return fnCallback({
"sEcho": cnt++,
"iDraw": cnt++,
"iTotalRecords": featureCount,
"iTotalDisplayRecords": featureCount,//tuples.length,
"aaData": tuples
});
}
} );
},
"ajax": {
"url": msUrl+"?map="+oLayers[key]["map"]+"&version=1.0.0&service=WFS&request=GetFeature&typename="+key,
"data": function ( d ) {
console.log(d);
var params={};
d.maxfeatures=d.length;
d.propertyname="";
for(var i in d.columns){
d.propertyname+=d.columns[i]["name"]+",";
}
d.orderby=d.columns[d.order[0]["column"]]["name"];
console.log(d);
//d = params;
// d.custom = $('#myInput').val();
// etc
}
},
"dom": 'Zlfrtip',
"colResize": {
"resizeCallback": function(column) {
alert("Column Resized");
}
},
"processing": true,
//"sAjaxSource": msUrl+"?map="+oLayers[key]["map"]+"&version=1.0.0&service=WFS&request=GetFeature&typename="+key,
"serverSide": true,
colReorder: true,
fixedHeader: true,
searching: false,
responsive: true,
select: true,
columns: columns
} );
/*}
});*/
var tableDisplay=0;
var contextualMenu={
"zoomTo": {
"run": function(layer){
var key=getLayerById(layer);
var transformer = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
var extent=ol.extent.applyTransform(oLayers[key]["extent"], transformer);
map.getView().fit(extent,map.getSize());
}
},
"query": {
"run": function(layer){
var key=getLayerById(layer);
console.log(key);
$("#table-wrapper").toggleClass("collapse");
$("#table-wrapper").toggleClass("in");
$("#table-wrapper").removeAttr("style");
if(!$("#table-wrapper").hasClass("collapse")){
if(tableDisplay!=0)
$("#mm_table-content").parent().remove();
tableDisplay++;
$("#table-wrapper-container").append('<table id="mm_table-content" class="display" width="100%"></table>');
$("#mmm_table-wrapper-header").append('<li role="presentation" class="active"><a href="#">Home</a></li>');
var columns=[];
var properties="";
var order="";
var j=0;
for(var i in oLayers[key]["queryParams"]["fields"]){
columns.push({
data: oLayers[key]["queryParams"]["fields"][i],
name: oLayers[key]["queryParams"]["fields"][i],
title: oLayers[key]["queryParams"]["aliases"][i]
});
properties+=oLayers[key]["queryParams"]["fields"][i]+",";
if(i==0)
order=oLayers[key]["queryParams"]["fields"][i];
j++;
}
properties+="msGeometry";
var _x2js = new X2JS();
var featureCount=0;
var cnt=0;
$('#mm_table-content').DataTable( {
data: [],
"lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
console.log(aoData);
oSettings.jqXHR = $.ajax( {
"type": "GET",
"url": msUrl+"?map="+oLayers[key]["map"]+"&version=1.0.0&service=WFS&request=GetFeature&typename="+key,
"data": aoData,
"success": function(document,status,data){
var _x2js = new X2JS();
var obj=_x2js.xml_str2json( data.responseText );
var tuples=[];
for(i in obj["FeatureCollection"]["featureMember"]){
var tuple={};
for(j in obj["FeatureCollection"]["featureMember"][i])
if(j[0]!="_"){
for(k in obj["FeatureCollection"]["featureMember"][i][j]){
if(k[0]!="_" && k!="boundedBy" && k!="msGeometry"){
tuple[k]=obj["FeatureCollection"]["featureMember"][i][j][k];
}
}
}
tuples.push(tuple);
}
return fnCallback({
"sEcho": 1,
//"iDraw": cnt++,
"iTotalRecords": tuples.length,
"iTotalDisplayRecords": 10,
"aaData": tuples
});
}
} );
},
"ajax": msUrl+"?map="+oLayers[key]["map"]+"&version=1.0.0&service=WFS&request=GetFeature&typename="+key+"&propertyname="+properties,
fixedHeader: true,
searching: false,
responsive: true,
select: true,
columns: columns
} );
$("#mm_table-content_length").addClass("hidden");
/*}
});*/
console.log("COUNT "+featureCount);
}
}
}
};
continue;
var locali=layer;
//var layer=locali;
console.log("DEBUG I:"+layer);
window["Intersecto0_"+layer]=function(){
var format=new ol.format.WFS();
var lRequest=(format.writeGetFeature({
featureTypes: [layer]/*,
geometryName: "msGeometry",
srsName: "EPSG:4326",
/*propertyNames: lprop,*
bbox: /*(localUrl.data.bbox?
[
localUrl.data.bbox[1],
localUrl.data.bbox[0],
localUrl.data.bbox[3],
localUrl.data.bbox[2]
]
:[-180,-90,180,90]//)*/
}));
console.log(lRequest);
return lRequest.outerHTML.replace(/1.1.0/,"1.0.0");
};
(function(localId){
zoo.execute({
identifier: "vector-tools.Intersection0",
dataInputs: [
{
"identifier": "InputEntity1",
"value": sVal,
"mimeType":"application/json"
},
{
"identifier": "InputEntity2",
"href": msUrl+"?map="+pmapfile,
"method": "POST",
"mimeType":"text/xml",
"headers": [{"key": "Content-Type","value":"text/xml"}],
"complexPayload_callback": "Intersecto0_"+layer
}
],
dataOutputs: [{"identifier":"Result","mimeType":"image/png"}],
type: 'POST',
storeExecuteResponse: false,
success: function(data) {
myMMDataTableObject.display(localId,{
lurl: data["ExecuteResponse"]["ProcessOutputs"]["Output"]["Reference"]["_href"].split("&")[0]
},true);
/*var format=new ol.format.GeoJSON();
{
if(oLayers[i]["queryParams"] && oLayers[i]["queryParams"]["fields"]){
console.log(i);
var key=i;
console.log(i);
}
}*/
//console.log(extent);
/*vectorSource.forEachFeatureIntersectingExtent(extent, function(feature) {
selectedFeatures.push(feature);
info.push(feature.get('name'));
});
if (info.length > 0) {
infoBox.innerHTML = info.join(', ');
}*/
/*notify(aProcess+' service run successfully','success');
var GeoJSON = new OpenLayers.Format.GeoJSON();
var features = GeoJSON.read((data));
layer.removeFeatures(layer.features);
layer.addFeatures(features);*/
},
error: function(data) {
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
}
});
})(layer);
<|start_filename|>mapmint-ui/new-themes/themes/pink/body.css<|end_filename|>
p.credits a:hover{text-decoration:underline;color:#e60ede;}
<|start_filename|>public_map/assets/css/styles.css<|end_filename|>
/*
* Fonts.
*/
@font-face {
font-family: 'clarendon_fs_lightlight';
src: url('../fonts/clarendonfs-light-webfont.eot');
src: url('../fonts/clarendonfs-light-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/clarendonfs-light-webfont.woff') format('woff'),
url('../fonts/clarendonfs-light-webfont.ttf') format('truetype'),
url('../fonts/clarendonfs-light-webfont.svg#clarendon_fs_lightlight') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'bryant_webregular';
src: url('../fonts/bryantwebregular-webfont.eot');
src: url('../fonts/bryantwebregular-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/bryantwebregular-webfont.woff') format('woff'),
url('../fonts/bryantwebregular-webfont.ttf') format('truetype'),
url('../fonts/bryantwebregular-webfont.svg#bryant_webregular') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'bryant_webmedium';
src: url('../fonts/bryantwebmedium-webfont.eot');
src: url('../fonts/bryantwebmedium-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/bryantwebmedium-webfont.woff') format('woff'),
url('../fonts/bryantwebmedium-webfont.ttf') format('truetype'),
url('../fonts/bryantwebmedium-webfont.svg#bryant_webmedium') format('svg');
font-weight: normal;
font-style: normal;
}
/*
* Glyphs.
*/
.glyphicon-chevron-left:before {
font-family: 'icomoon';
content: "\ea31";
}
.glyphicon-chevron-right:before {
font-family: 'icomoon';
content: "\ea34";
}
.glyphicon-twitter:before {
font-family: 'icomoon';
content: "\e603";
}
.glyphicon-facebook:before {
font-family: 'icomoon';
content: "\e602";
}
.glyphicon-linkedin:before {
font-family: 'icomoon';
content: "\e613";
}
/*
* Defaults.
*/
body {
font-family: 'clarendon_fs_lightlight', serif;
font-size: 20px;
line-height: 30px;
margin: 0;
font-weight: normal;
font-style: normal;
color: #444;
background: url("../img/bg-grid.png") repeat;
}
h1,h2,h3,h4,h5 {
font-family: 'clarendon_fs_lightlight', serif;
color: #444;
}
h1 {
font-size: 48px;
line-height: 64px;
margin-bottom: 26px;
color: #000;
}
h2 {
font-size: 36px;
line-height: 60px;
}
strong {
color: #FF5200;
font-weight: normal;
font-style: normal;
}
a:link,
a:visited,
a:hover,
a:active {
color: #999999;
text-decoration: underline;
font-weight: normal;
font-style: normal;
}
/*
* Regions.
*/
#header {
font-family: 'bryant_webmedium', sans-serif;
font-size: 30px;
line-height: 72px;
}
#top {
font-size: 20px;
line-height: 30px;
padding-top: 48px;
padding-bottom: 20px;
background-color: #fff;
border-top: 1px solid #ddd;
border-bottom: 1px solid #ddd;
}
#groth {
background-color: rgba(255,255,255, 0.6);
}
#conditions {
padding-top: 50px;
padding-bottom: 20px;
background-color: #fff;
border-top: 1px solid #ddd;
border-bottom: 1px solid #ddd;
}
#winners {
background-color: rgba(255,255,255, 0.6);
overflow: hidden;
}
.winners-container {
padding-bottom: 30px;
padding-right: 0;
}
#winners .map-text {
padding-right: 0;
z-index: 10;
}
#winners .map-fig {
padding-left: 0;
padding-right: 0;
height: 496px;
z-index: 1;
}
#logos {
height: 72px;
background-color: #eee;
opacity: .5;
border-top: 1px solid #ddd;
border-bottom: 1px solid #ddd;
z-index: 10;
}
.logos-container {
padding-top: 10px;
}
#talk {
padding-top: 50px;
padding-bottom: 50px;
background-color: #fff;
border-top: 1px solid #ddd;
border-bottom: 1px solid #ddd;
}
#talk .btn {
margin-top: 20px;
width: 100%;
padding-top: 10px;
padding-bottom: 10px;
}
#talk .img-circle {
width: 85%;
height: 85%;
}
#talk-expand {
background-color: rgba(255,255,255, 0.5);
overflow: hidden;
padding-bottom: 20px;
border-bottom: 1px solid #ddd;
border-top: 1px solid #fff;
border-bottom: 1px solid #ddd;
/*
position: relative;
top: -1px;
*/
margin-top: -1px;
z-index: 20;
}
#trimask {
height: 32px;
background-color: #fff;
position: relative;
top: -32px;
}
#trimask:before {
content:"";
position: absolute;
left: -23px;
width: 50%;
height: 28px;
top: 32px;
background-color: #fff;
-webkit-transform: skew(-60deg);
-moz-transform: skew(-60deg);
-o-transform: skew(-60deg);
-ms-transform: skew(-60deg);
transform: skew(-60deg);
border-bottom: 1px solid #ddd;
border-right: 1px solid #ddd;
/*box-shadow: -2px 4px 8px #000;*/
}
#trimask:after {
content:"";
position: absolute;
right: -23px;
width: 50%;
height: 28px;
top: 32px;
background-color: #fff;
-webkit-transform: skew(60deg);
-moz-transform: skew(60deg);
-o-transform: skew(60deg);
-ms-transform: skew(60deg);
transform: skew(60deg);
border-bottom: 1px solid #ddd;
border-left: 1px solid #ddd;
/*box-shadow: 2px 4px 8px #000;*/
}
#pre-footer {
font-size: 18px;
line-height: 22px;
padding-top: 30px;
padding-bottom: 10px;
color: #999;
border-bottom: 1px solid #ddd;
}
#pre-footer strong {
line-height: 36px;
color: #444;
}
#footer {
background-color: #fff;
font-family: 'bryant_webmedium', sans-serif;
font-size: 16px;
height: 40px;
color: #999;
}
/*
* Controls.
*/
.question .title {
font-family: 'bryant_webmedium', sans-serif;
font-weight: normal;
font-style: normal;
font-size: 30px;
line-height: 36px;
padding-top: 20px;
color: #FFBA4A;
}
.icon-down {
font-weight: normal;
font-style: normal;
font-size: 80px;
line-height: 120px;
color: #FF4313;
}
.icon-down:before {
content: "\ea32";
}
.icon-left, .icon-right {
font-weight: normal;
font-style: normal;
font-size: 30px;
line-height: 120px;
color: #797979;
color: #000;
}
.icon-left:before {
content: "\ea31";
}
.icon-right:before {
content: "\ea34";
}
a.icon-down:link,
a.icon-down:visited,
a.icon-down:hover,
a.icon-down:active {
color: #FF4313;
text-decoration: none;
font-weight: normal;
font-style: normal;
}
/*
* Form elements.
*/
.btn {
margin-bottom: 0;
font-weight: normal;
font-style: normal;
border: 1px solid transparent;
font-size: 24px;
line-height: 36px;
border-radius: 4px;
text-shadow: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
input, button, select, textarea {
font-family: 'clarendon_fs_lightlight';
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
textarea {
resize: none;
}
.form-control {
color: #999;
font-size: 20px;
padding: 10px 20px;
height: 50px;
border: 1px solid #ddd;
font-size: 20px;
}
button.btn-default:focus,
button.btn-default:active,
button.btn-default:hover {
color: #fff;
text-decoration: none;
font-weight: normal;
font-style: normal;
background-color: #FF4B00;
border-color: #FF4B00;
background-image: none;
}
.btn-default {
color: #fff;
background-color: #FF4B00;
border-color: #FF4B00;
background-image: none;
}
/*
* Carousel
*/
#carousel-logos {
overflow: hidden;
}
#carousel-logos .col-xs-2 {
width: 18%;
padding-left: 0;
padding-right: 0;
}
.logos-container.container-fluid {
margin-right: 0;
margin-left: 0;
padding-left: 0;
padding-right: 0;
}
.carousel-control {
color: #797979;
width: 8.33%;
line-height: 30px;;
text-shadow: none;
opacity: 1;
}
.carousel-control:hover {
color: #FF4B00;
}
.carousel-control.left, .carousel-control.right {
background-image:none !important;
}
.carousel-inner {
margin-left: 8.33%;
}
#btn-send {
width: 100%;
}
.social .glyphicon {
font-size: 32px;
vertical-align: top;
padding-left: 8px;
}
.logo-autika-small {
background: url("../img/logo-autika.svg") no-repeat;
/*
line-height: 72px;
height: 46px;
width: 28px;
color: transparent;
padding-top: 1px;
padding-left: 5px;
padding-bottom: 12px;
*/
color: transparent;
font-size: 150%;
background-position: center center;
position: relative;
top: 11px;
left: 2px;
}
/*
* Illustrations.
*/
#top .fig {
display: block;
background: url("../img/logo-autika.svg") no-repeat;
height: 167px;
width: 107px;
margin-top: 30px;
margin-left: auto;
margin-right: auto;
color: transparent;
}
#groth .fig {
display:block;
background: url("../img/fig-groth.png") no-repeat;
height: 257px;
width: 361px;
margin-top: 72px;
margin-left: auto;
margin-right: auto;
}
#conditions .fig {
display:block;
background: url("../img/fig-conditions.svg") no-repeat;
height: 396px;
width: 396px;
margin-top: 50px;
margin-left: auto;
margin-right: auto;
}
/*
* Map.
*/
.map_image {
display: block;
width: 622px;
height: 496px;
position: absolute;
background-position: 100% 0%;
background-size: cover;
background-repeat: no-repeat;
background-image: url('../img/fig-winners.png');
right: 0px;
}
.map_image .map_link { display: block; position: absolute; text-indent: -999em; overflow: hidden; }
.map_image #map_link_0 { width: 33px; height: 36px; top: 135px; left: 159px; }
.map_image #map_link_1 { width: 30px; height: 31px; top: 153px; left: 255px; }
.map_image #map_link_2 { width: 35px; height: 34px; top: 221px; left: 211px; }
.map_image #map_link_3 { width: 30px; height: 32px; top: 189px; left: 250px; }
.map_image #map_link_4 { width: 25px; height: 31px; top: 22px; left: 347px; }
.map_image #map_link_5 { width: 28px; height: 29px; top: 103px; left: 346px; }
.map_image #map_link_6 { width: 31px; height: 32px; top: 48px; left: 406px; }
.map_image #map_link_7 { width: 29px; height: 27px; top: 166px; left: 346px; }
.map_image #map_link_8 { width: 33px; height: 34px; top: 337px; left: 81px; }
.map_image #map_link_9 { width: 32px; height: 30px; top: 254px; left: 275px; }
.map_image #map_link_10 { width: 31px; height: 29px; top: 316px; left: 250px; }
.map_image #map_link_11 { width: 32px; height: 33px; top: 285px; left: 283px; }
.map_image #map_link_12 { width: 33px; height: 34px; top: 437px; left: 489px; }
/*
* Fixes.
*/
.center-block {
float: none !important
}
.row {
margin-left: 0;
margin-right: 0;
}
[class^="col-"] > [class^="col-"]:first-child,
[class^="col-"] > [class*=" col-"]:first-child
[class*=" col-"] > [class^="col-"]:first-child,
[class*=" col-"]> [class*=" col-"]:first-child,
.row > [class^="col-"]:first-child,
.row > [class*=" col-"]:first-child{
padding-left: 0px;
}
[class^="col-"] > [class^="col-"]:last-child,
[class^="col-"] > [class*=" col-"]:last-child
[class*=" col-"] > [class^="col-"]:last-child,
[class*=" col-"]> [class*=" col-"]:last-child,
.row > [class^="col-"]:last-child,
.row > [class*=" col-"]:last-child{
padding-right: 0px;
}
.footer-container > .row,
.top-container > .row {
margin-right: 15px;
}
.groth-container > .row {
margin-left: 15px;
margin-right: 15px;
}
.pre-footer-container > .row {
margin-left: 15px;
margin-right: 15px;
}
.add-padd-right {
padding-right: 15px;
}
/*
Extra small devices ~ Phones (< 768px)
Small devices ~ Tablets (>= 768px)
Medium devices ~ Desktops (>= 992px)
Large devices ~ Desktops (>= 1200px)
*/
/* xs: Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */
/* sd: Small devices (tablets, 768px and up) */
@media (min-width: 768px) {
}
/* md: Medium devices (desktops, 992px and up) */
@media (min-width: 992px) {
}
/* lg: Large devices (large desktops, 1200px and up) */
@media (min-width: 1200px) {
}
<|start_filename|>mapmint-ui/js/Table.js<|end_filename|>
System.refreshSteps=true;
function initTableFields(){
$("#table .gen").find("input").each(function(){
$(this).val("");
});
}
function refreshTableFields(){
initTableFields();
tableName="indicateurs";
tableNameT=(arguments.length>0?arguments[0]:"")+"table";
var vars="";
if(arguments.length>1)
vars=";tid="+arguments[1];
if($("#table_steps").is(":visible") && $("#table_step").val()>0)
vars+=";step="+($("#table_step")[0].selectedIndex-1);
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.details&DataInputs=table="+tableName+";id="+System.nodeId+";tab=table"+vars+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
try{
if(System.refreshSteps)
addSteps(tableNameT+"_step");
System.refreshSteps=true;
}catch(e){
// In case addSteps is not defined
}
var data=$.parseJSON(xml.responseText);
for(var i in data){
if(!$.isArray(data[i])){
if(i=="name")
$("#"+tableNameT+"_"+i+"_title").html(data[i]);
else{
if(data[i]!=null){
if(i!="step")
$("#"+tableNameT+"_"+i).val(data[i]);
else
$("#"+tableNameT+"_"+i+" > option")[data[i]+1].selected=true;
}
else{
if($("#"+tableNameT+"_"+i)>0 && $("#"+tableNameT+"_"+i)[0].selectedIndex)
$("#"+tableNameT+"_"+i).val(-1);
else
$("#"+tableNameT+"_"+i).val("");
}
}
}else{
$("#"+tableNameT+"_"+i+" option:selected").removeAttr("selected");
if(data[i].length)
for(var j=0;j<data[i].length;j++)
$("#"+tableNameT+"_"+i+' option[value="'+data[i][j]+'"]').attr("selected", "selected");
else
$('#'+tableNameT+'_'+i+' option[value="-1"]').attr("selected", "selected");
}
}
try{
if(tableNameT=="table"){
$(".toolbar2").find("a.table").each(function(){
$(this).removeClass("desactivated");
});
$(".tabs-project").find("#table > .loader-container").each(function(){
$(this).hide();
});
}
}catch(e){}
}
}
});
}
<|start_filename|>mapmint-ui/js/Indexes.js<|end_filename|>
System.require('Distiller')
System.limit=0;
Indexes=MLayout.extend();
counter=0;
Indexes.define({
id: 0,
layoutOptions: {
contentSelector: ".lcontent",
center__paneSelector: ".inner-center",
west__paneSelector: ".inner-west",
west__size: .28,
west__draggable: false,
west__resizable: false,
west__spacing_closed:10,
west__spacing_open:8,
east__paneSelector: ".inner-east",
east__size: .28,
east__closable: false,
east__draggable: false,
east__resizable: false,
spacing_open: 4,
spacing_closed: 4,
//resizeWhileDragging: true,
onopen: function() {updateSize();},
onclose: function() {updateSize();},
onresize: function() {updateSize();}
},
initialize: function(){
this.refresh();
endLoading();
this.id++;
},
refresh: function(){
defaultInit();
}
});
$(document).ready(function () {
$("input[name$=group1]").change(function() {
var test = $(this).val();
$(".desc").hide();
$("#" + test).show();
$(".tbl_part").hide();
});
$("input[name$=group1]:checked").change();
$("#agreg").css("display","none");
$("#agregation_chk").click(function () {
if($("#p_tname").val()!=-1)
$("#agreg").toggle(this.checked);
});
$("#stemp").css("display","none");
$("#serietemporelle").click(function () {
$("#stemp").toggle(this.checked);
});
$(".add-index").click(function(){
$("#eName").val("");
$('#add-index-dialog').window({
width: 300,
height: 150,
left:80,
top:150,
maximizable:false,
minimizable:false,
resizable: false
})
});
$(".delete-index").click(function(){
$("#dName").val(System.currentList[System.nodeId]);
$('#remove-index-dialog').window({
width: 300,
height: 150,
left:80,
top:150,
maximizable:false,
minimizable:false,
resizable: false
})
});
$(".sql_test").click(function(){
testQuery();
});
$(".sql_confirm").click(function(){
runQuery();
});
$('#colorpickerHolder2').ColorPicker({
flat: true,
color: '#00ff00',
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector2 div').css('backgroundColor', '#' + hex);
$("#s_color2").val(hex);
}
});
$(' #colorpickerHolder3').ColorPicker({
flat: true,
color: '#00ff00',
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector3 div').css('backgroundColor', '#' + hex);
$("#s_color3").val(hex);
}
});
$('#colorpickerHolder2>div, #colorpickerHolder3>div').css('position', 'absolute');
var widt = false;
$('#colorSelector2').bind('click', function() {
$('#colorpickerHolder2').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
$('#colorSelector3').bind('click', function() {
$('#colorpickerHolder3').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
searchTable("indicators");
refreshList();
});
function publishIndexMap(){
params=[
{name: "id", value: System.nodeId, dataType: "sring"}
];
data=WPSGetHeader("np."+(arguments.length>0?arguments[0]:"")+"publishFullIndex")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
checkWPSResult(xml);
}
});
}
function testQuery(){
params=[
{name: "dbname", value: $("#mmDbConnection").val(), dataType: "sring"},
{name: "query", value: $("#mmSQLQuery").val(), dataType: "sring"}
];
data=WPSGetHeader("np.testQuery")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
checkWPSResult(xml);
}
});
}
function runQuery(){
params=[
{name: "map", value: (arguments.length>0?System.dbuserName:$("#mmDbConnection").val()), dataType: "sring"},
{name: "sql", value: (arguments.length>0?"SELECT * FROM "+$("#pg_table").val():$("#mmSQLQuery").val()), dataType: "sring"}
];
data=WPSGetHeader("np.createTempFile")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$("#dsContainer").html('<table id="flex_csv" class="hideBody"></table>');
dwDataSource=xml.responseText;
$.ajax({
dwDataSource: dwDataSource,
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=vector-tools.mmVectorInfo2Map&DataInputs=dataSource="+dwDataSource.replace(/__/g,"/")+";force=1&RawDataOutput=Result",
dataType: 'xml',
complete: function(xml,status) {
var tmp=$.xml2json(xml.responseXML);
var localI=0;
var localLength=0;
var localTmp=new Array();
$("#dsFileSelect").html("");
for(i in tmp.layer){
localTmp.push(tmp.layer[i]);
if(tmp.layer[i]!="None")
$("#dsFileSelect").append("<option>"+tmp.layer[i]+"</option>");
localLength+=1;
}
$("#dsFileSelect").show();
loadPageFromFile(this.dwDataSource,localLength);
}
});
}
}
});
}
function updateSelectWithFields(){
var selIds=arguments[0];
//alert(selIds);
var tid=$("#indicateurs_indicators_territoires").val();
if(arguments.length>1){
tid=arguments[1]+";layer=indexes."+($("#agregation").is(":visible")?"agregate_t"+$("#p_tname").val()+"_idx_":"view_idx_")+System.nodeId;
System.u0=true;
}else
System.u0=false;
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.getMapRequest&DataInputs=t_id="+tid+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$.ajax({
type: "GET",
url: xml.responseText,
complete: function(xml,status){
var i=0;
var tmp=$(xml.responseXML).find("element").each(
function(){
if($(this).attr("type")!="gml:GeometryPropertyType" &&
$(this).attr("type")!="ms:"+System.mmNodeId+"Type"){
if(i==0){
for(var t=0;t<selIds.length;t++)
$("#"+selIds[t]).html("");
}
for(var t=0;t<selIds.length;t++)
$("#"+selIds[t]).append('<option value="'+$(this).attr("name")+'" '+(System.selectedField0==$(this).attr("name")?'selected="true"':'')+'>'+$(this).attr("name")+" ("+$(this).attr("type")+')</option>');
i+=1;
if(System.onSelectField0){
System.onSelectField0();
System.onSelectField0=null;
}
}
});
}
});
}
}
});
}
/**
* Common part
*/
var tableName="indicators";
function updateElement(){
var params={id: System.nodeId};
$("#"+tableName+"_edition_ui_step"+arguments[0]).find("input").each(function(){
if($(this)[0].id!='indicateurs_indicators_keywords' && $(this)[0].id && $(this)[0].id.replace(/indicateurs_/,"")!=$(this)[0].id)
params[$(this)[0].id.replace(/indicateurs_/,"")]=$(this).val();
});
$("#indicateurs_description").val( CKEDITOR.instances.indicateurs_description.getData().replace(/\"/g,"\\\"") );
$("#"+tableName+"_edition_ui_step"+arguments[0]).find("textarea").each(function(){
params[$(this)[0].id.replace(/indicateurs_/,"")]=$(this).val();
});
$("#"+tableName+"_edition_ui_step"+arguments[0]).find("select").each(function(){
if($(this)[0].multiple){
localId=$(this)[0].id.replace(/indicateurs_/,"");
params[localId]=[];
$(this).find("option:selected").each(function(){
params[localId].push($(this).val());
});
}
else{
params[$(this)[0].id.replace(/indicateurs_/,"")]=$(this).val();
}
});
//alert($.stringify(params));
params=[
{name: "table", value: tableName,dataType: "string"},
{name: tableName+"_groups_in", value: "i_id",dataType: "string"},
{name: tableName+"_groups_out", value: "g_id",dataType: "string"},
{name: tableName+"_themes_in", value: "i_id",dataType: "string"},
{name: tableName+"_themes_out", value: "t_id",dataType: "string"},
{name: "t_hierarchy_in", value: "o_t_id",dataType: "string"},
{name: "t_hierarchy_out", value: "p_t_id",dataType: "string"},
{name: "keywords", value: $("#indicateurs_indicateurs_keywords").val(),dataType: "string"},
{name: "tuple", value: $.stringify(params), mimeType: "application/json"}
];
data=WPSGetHeader("np.updateElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
//alert(data);
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
System.noSelectAgain=true;
refreshList();
}
}
});
}
function cleanUpSelect(){
var localClean=arguments[1];
var localId=0;
$("#"+arguments[0]).find("option").each(function(){
if(localId>localClean)
$(this).remove();
localId+=1;
});
}
function refreshDetails(){
$(".toolbar2").find("a").each(function(){
$(this).addClass("desactivated");
});
$(".tabs-project").find(".loader-container").each(function(){
$(this).css({"height": ($("#indicateurs_edition_ui").height()-62)+"px"});
$(this).show();
});
$("#indicateurs_edition_ui_step_metadata").find("input").val("");
$(".tabs-project").find("input[type=text]").val("");
$(".tabs-project").find("select").val("-1");
$(".tabs-project").find("select").val(-1);
$(".tabs-project").find("textarea").val("");
var tmp=["mmsteps","table_step","graphs_step","repport_step"];
for(i in tmp){
$("#"+tmp[i]).val(-1);
cleanUpSelect(tmp[i],(i>0?0:1));
}
/*$("#symbology").find("select").val("-1");
$("#symbology").find("input").val("");
$("#table").find("input").val("");
$("#chart").find("input").val("");*/
$("#mmPrefix").val("indexes");
$("#mmDeleteStep").val(System.messages["Delete"]);
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.details&DataInputs=table="+tableName+";id="+System.nodeId+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$("#metadata").click();
var data=$.parseJSON(xml.responseText);
System.full_index=data;
if(!data["file"] || data["file"]==""){
$('input:radio[name=doct]')[1].checked = true;
$('#file0').hide();
$('#indicateurs_file_link0').hide();
$('#indicateurs_url').show();
}
else{
$('input:radio[name=doct]')[0].checked = true;
$('#indicateurs_url').hide();
$('#indicateurs_file_link0').html(data['file']);
$('#indicateurs_file_link0').attr("href",System.public_map_url+"/indicateurs/"+data['file']);
$('#indicateurs_file_link0').show();
//alert($('#indicateurs_file_link').attr("href"));
$('#file0').show();
}
for(var i in data){
if(!$.isArray(data[i])){
if(i=="name"){
$("#"+tableName+"_"+i+"_title").html(data[i]+(eval(data["published"])?" ("+System.messages["published"]+")":""));
}
$("#"+tableName+"_"+i).val("");
if(data[i]!=null)
$("#"+tableName+"_"+i).val(data[i]);
else{
if($("#"+tableName+"_"+i)>0 && $("#"+tableName+"_"+i)[0].selectedIndex)
$("#"+tableName+"_"+i).val(-1);
else
$("#"+tableName+"_"+i).val("");
}
}else{
$("#"+tableName+"_"+i+" option:selected").removeAttr("selected");
if(data[i].length)
for(var j=0;j<data[i].length;j++)
$("#"+tableName+"_"+i+' option[value="'+data[i][j]+'"]').attr("selected", "selected");
else
$('#'+tableName+'_'+i+' option[value="-1"]').attr("selected", "selected");
}
}
$(".toolbar2").find("a.metadata").each(function(){
$(this).removeClass("desactivated");
});
$(".tabs-project").find("#metadata > .loader-container").each(function(){
$(this).hide();
});
$(".iunpublish").removeClass("desactivated");
$(".ipublish").removeClass("desactivated");
if(data["file_link"]){
$("input[value='opt1']").prop("checked",true);
var test=$("input[value='opt1']").val();
$(".desc").hide();
$("#" + test).show();
$(".tbl_part").hide();
$("#indicateurs_file_link").html("");
$("#indicateurs_territoires_filename").val(data["filename"]);
$("#indicateurs_file_link").attr("href",data["filename"]);
if(data["query"]==null || data["query"]=="null")
loadTableForFile();
else{
$("input[value='opt3']").prop("checked",true);
var test=$("input[value='opt3']").val();
$(".desc").hide();
$("#" + test).show();
$(".tbl_part").hide();
$("#mmSQLQuery").val(data["query"]);
$("#mmDbConnection").val(data["ds"]);
runQuery();
}
System.selectedField0=data["indicateurs_territoires_key"];
System.onSelectField0=function(){
System.onIndexRefresh=function(){
refreshLayerStyle();
refreshRepport();
//alert('load graph !');
}
refreshIndex();
}
updateSelectWithFields(['indicateurs_indicateurs_territoires_key']);
}else{
//alert("First load");
$("#dsContainer").html("");
$(".toolbar2").find("a.data").each(function(){
$(this).removeClass("desactivated");
});
$(".tabs-project").find("#data > .loader-container").each(function(){
$(this).hide();
});
}
createEditor("indicateurs_description");
}
}
});
}
function refreshAggregation(){
$("#p_tname").find("option").each(function(){
var t=$(this).val()==-1;
if(t)
$(this).attr("selected","selected");
else
$(this).remove();
});
$("#agregation_chk").prop('checked', false);
$("#agreg").toggle(false);
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.details&DataInputs=table=territoires;id="+$("#indicateurs_indicateurs_territoires").val()+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$('.aggregation').removeClass('desactivated');
var data=$.parseJSON(xml.responseText);
if(System.refreshSteps)
addSteps("agregation_step");
System.refreshSteps=true;
for(var i in data){
if(i=="t_hierarchy"){
if(data[i].length)
for(var j=0;j<data[i].length;j++)
$('#p_tname').append($("<option></option>")
.attr("value",data[i][j])
.text(System.territories["id_"+data[i][j]]));
else
$('#p_tname option[value="-1"]').attr("selected", "selected");
}
}
}
}
});
}
function insertAgregate(){
var vars="";
if($("#agregate_steps").is(":visible") && $("#agregate_step").val()>0)
vars+=";step="+($("#agregate_step")[0].selectedIndex-1);
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.createAgregate&DataInputs=table=public.territoires;field="+$('#s_fname').val()+";id="+System.nodeId+";tid="+$('#p_tname').val()+";formula="+$("#agregation_formula").val()+vars+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
//alert(xml.responseText);
$("#agregate_flexi").html(xml.responseText);
startLayerStyleFlexi();
}
}
});
}
function refreshList(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.list&DataInputs=table=indicators&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var data=$.parseJSON(xml.responseText);
System.currentList={};
for(i=0;i<data.length;i++){
System.currentList[data[i]["id"]]=data[i]["text"];
}
$('#ltree').tree({
data: data,
onSelect: function(node){
System.nodeId=node.id;
System.nodeVal=node.text;
refreshDetails();
}
});
if(!System.noSelectAgain){
var tmp=$("#ltree").tree('getSelected');
var tmpr=$("#ltree").tree('getRoot');
if(!tmp && tmpr){
$("#ltree").tree('select',tmpr.target);
}
}else{
var node = $('#ltree').tree('find', System.nodeId);
$("#ltree").tree('select',node.target);
}
System.noSelectAgain=false;
}
}
});
}
function deleteElement(){
params=[
{name: "table", value: "territoires",dataType: "string"},
{name: "id", value: System.nodeId,dataType: "string"}
];
data=WPSGetHeader("np.deleteElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshList();
$('#delete-territory-dialog').window('close');
}
}
});
}
function insertGraph(){
var prefix="";
if(arguments.length>0)
prefix="agregate_";
params=[
{name: "table", value: "graphs",dataType: "string"},
{name: "name", value: $("#graphs_title").val(),dataType: "string"},
{name: "type", value: $("#graphs_f_type").val(),dataType: "string"},
{name: "lx", value: $("#"+prefix+"graphs_lx").val(),dataType: "string"},
{name: "vx", value: $("#"+prefix+"graphs_vx").val(),dataType: "string"},
{name: "ly", value: $("#graphs_ly").val(),dataType: "string"},
{name: "vy", value: $("#graphs_vy").val(),dataType: "string"},
{name: "tooltip", value: $("#graphs_tooltip").val(),dataType: "string"},
{name: "formula", value: $("#graphs_formula").val(),dataType: "string"},
{name: "it_id", value: "(SELECT id from indicateurs_territoires where i_id="+System.nodeId+($("#agregation").is(":visible")?" and t_id="+$("#p_tname").val():" and (not(agregation) or agregation is null)")+")",dataType: "string"}
];
if(arguments.length>0){
test=false;
params.push({
name: "tid",
value: $("#p_tname").val(),
dataType: "string"
});
}
test=$("#"+prefix+"graphs_id").val()!='-1' && $("#"+prefix+"graphs_id").val()!='';
if(test){
params.push({
name: "id",
value: $("#"+prefix+"graphs_id").val(),
dataType: "string"
});
}
if($("#graphs_steps").is(":visible") && $("#graphs_step").val()>0)
params.push({"name":"step","value":($("#graphs_step")[0].selectedIndex-1),dataType: "string"});
data=WPSGetHeader("np."+(test?"updateElem":"insertElem"))+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
if(prefix=="")
refreshGraphFields();
else
refreshGraphFields(prefix);
//alert("reload graph!");
}
}
});
}
function insertTable(){
//alert($(".sasc").length);
params=[
{name: "table", value: "d_table",dataType: "string"},
{name: "name", value: $("#table_title").val(),dataType: "string"},
{name: "i_id", value: System.nodeId,dataType: "string"}
];
if($("#table_steps").is(":visible") && $("#table_step").val()>0)
params.push({name: "step", value: ($("#table_step")[0].selectedIndex-1),dataType: "string"});
test=$("#table_id").val()!='-1' && $("#table_id").val()!='';
if(test){
params.push({
name: "id",
value: $("#table_id").val(),
dataType: "string"
});
}
if($(".sasc").length>1){
var cnt=0;
$(".sasc").each(function(){
if(cnt==1)
params.push({
name: "order_by",
value: $(this).html(),
dataType: "string"
});
cnt+=1;
});
}
data=WPSGetHeader("np."+(test?"updateElem":"insertElem"))+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshTableFields();
//alert("reload table!");
}
}
});
}
function insertElement(){
params=[
{name: "table", value: "indicateurs",dataType: "string"},
{name: "name", value: $("#eName").val(),dataType: "string"}
];
data=WPSGetHeader("np.insertElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshList();
$('#add-index-dialog').window('close');
}
}
});
}
function removeElement(){
params=[
{name: "table", value: "indicateurs",dataType: "string"},
{name: "atable", value: "indicateurs_groups",dataType: "string"},
{name: "akey", value: "i_id",dataType: "string"},
{name: "atable", value: "d_table",dataType: "string"},
{name: "akey", value: "i_id",dataType: "string"},
{name: "atable", value: "r_table",dataType: "string"},
{name: "akey", value: "i_id",dataType: "string"},
{name: "atable", value: "indicateurs_groups",dataType: "string"},
{name: "akey", value: "i_id",dataType: "string"},
{name: "atable", value: "indicateurs_keywords",dataType: "string"},
{name: "akey", value: "i_id",dataType: "string"},
{name: "id", value: System.nodeId,dataType: "string"}
];
data=WPSGetHeader("np.deleteElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshList();
$('#remove-index-dialog').window('close');
}
}
});
}
$(function () {
var tabContainers = $('div.tabs-project > div');
tabContainers.hide().filter(':first').show();
$('div.toolbar2 a').click(function () {
if($(this).is("._nothidable"))
;
else{
tabContainers.hide();
tabContainers.filter(this.hash).show();
}
}).filter(':first').click();
});
function loadTableForFile(){
$("#dsContainer").html('<table id="flex_csv" class="hideBody"></table>');
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.getLastFile&DataInputs=&RawDataOutput=Result",
dataType: 'xml',
complete: function(xml,status) {
dwDataSource=xml.responseText;
$("#indicateurs_territoires_filename").val(dwDataSource);
$.ajax({
dwDataSource: dwDataSource,
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=vector-tools.mmVectorInfo2Map&DataInputs=dataSource="+dwDataSource.replace(/__/g,"/")+";force=1&RawDataOutput=Result",
dataType: 'xml',
complete: function(xml,status) {
var tmp=$.xml2json(xml.responseXML);
var localI=0;
var localLength=0;
var localTmp=new Array();
$("#dsFileSelect").html("");
for(i in tmp.layer){
localTmp.push(tmp.layer[i]);
if(tmp.layer[i]!="None")
$("#dsFileSelect").append("<option>"+tmp.layer[i]+"</option>");
localLength+=1;
}
$("#dsFileSelect").show();
loadPageFromFile(this.dwDataSource,localLength);
}
});
}
});
}
function loadPageFromFile(){
System.loadId="flex_csv";
if(arguments.length>2)
System.loadId="agregate_dsContainer1";
System.dsField=(arguments.length>2?arguments[2]:$("#dsFileSelect").val());
$.ajax({
mmid: arguments[1],
dwDataSource: arguments[0],
dwLayer: System.dsField,
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=vector-tools.mmExtractVectorInfo&DataInputs=dataSource="+arguments[0]+";layer="+System.dsField+"&RawDataOutput=Result",
dataType: 'xml',
complete: function(xml,status) {
colModel=[];
fields=[];
try{
var tmp=$.xml2json(xml.responseXML);
var nbCol=0;
if(tmp.fields){
if(tmp.fields.field.length)
for(j=0;j<tmp.fields.field.length;j++){
colModel[nbCol]={display: tmp.fields.field[j].id, name : tmp.fields.field[j].id, width: (nbCol==0?80:120), sortable : true, align: 'center'};
fields[nbCol]=tmp.fields.field[j].id;
nbCol++;
}
else{
colModel[nbCol]={display: tmp.fields.field.id, name : tmp.fields.field.id, width: (nbCol==0?80:120), sortable : true, align: 'center'};
fields[nbCol]=tmp.fields.field.id;
nbCol++;
}
var localTmp1=tmp;
var lopts={
autoload: true,
url: System.zooUrl,
dataType: 'xml',
colModel: colModel,
usepager: true,
sortname: (tmp.fields.field.length?tmp.fields.field[0].id:tmp.fields.field.id),
sortorder: "asc",
id: System.flexi_cnt,
fields: fields,
dwDataSource: this.dwDataSource.replace(/__/g,"/"),
dwLayer: this.dwLayer,
dwDataType: (tmp.geometry=='Polygon'?'polygon':(tmp.geometry=='Point'?'point':'line')),
mmid: this.mmid,
nbElements: tmp.featureCount,
title: this.dwDataSource.replace(/__/g,"/")+" / "+tmp.name.replace(/__/g,"/"),
useLimit: true,
limit: 10,
showTableToggleBtn: true,
width: "100%",
height: 290
};
if(System.loadId=="agregate_dsContainer1"){
lopts["showTableToggleBtn"]=true;
lopts["tableToggleBtns"]=
[
{title: System.messages["Display parameters"],name: 'table0',onclick: function(){
var myId=this.id.split('_')[1];
loadIndexDisplaySettings($("#p_tname").val());
}}
];
}
$("#"+System.loadId).flexigrid(lopts);
if(System.loadId!="agregate_dsContainer1"){
$("#flex0").addClass('hideBody');
$(".tbl_part").show();
}
}
}catch(e){alert(e);}
}
});
}
function parseParams(){
var fields="";
var fkey="";
var fields_width="";
var cnt=0;
var params=new Array();
params=[
];
if($("input[value='opt3']").is(":checked")){
if($("#mmDbConnection").val()!="-1")
params.push({name: "dbname", value: $("#mmDbConnection").val(), dataType: "sring"});
if($("#mmSQLQuery").val()!="")
params.push({name: "query", value: $("#mmSQLQuery").val(), dataType: "sring"});
}
$("#dsContainer .hDiv").find("th").each(function(){
if(this.style.display!='none'){
if(cnt==0)
params.push({"name": "field","value":$(this).text(),dataType:"string"})
fkey=$(this).text();
fields+=(cnt>0?",":"")+$(this).text();
fields_width+=(cnt>0?',':'')+$(this).width();
params.push({"name": "rcol","value":$(this).text(),dataType:"string"})
cnt++;
}
});
// table indicateurs_indicateurs_territoires
params.push({"name": "territoire","value":$("#indicateurs_indicateurs_territoires").val(),dataType:"string"});
// field indicateurs_indicateurs_territoires_key
params.push({"name": "field","value":$("#indicateurs_indicateurs_territoires_key").val(),dataType:"string"});
// field indicateurs_territoires_filename
if($("#indicateurs_territoires_filename").val()!="" && $("#indicateurs_territoires_filename").val()!="None")
params.push({"name": "filename","value":$("#indicateurs_territoires_filename").val(),dataType:"string"});
params.push({"name": "type","value":($("input[value='opt1']").is(":checked")?"file":$("input[value='opt2']").is(":checked")?"table":"sql"),dataType:"string"});
var node=$("#ltree").tree("getSelected");
params.push({"name": "id","value":node.id,dataType:"string"})
params.push({"name": "sql","value":"SELECT "+fields+" FROM \""+$("#dsFileSelect").val()+"\"",dataType:"string"});
params.push({"name": "layer","value":$("#dsFileSelect").val(),dataType:"string"});
return params;
}
function createIndex(){
params=parseParams();
data=WPSGetHeader("np.createIndex")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
System.onIndexRefresh=function(){
refreshLayerStyle();
};
refreshIndex();
}
}
});
}
function refreshIndex(){
var node=$("#ltree").tree("getSelected");
System.mmNodeId="indexes.view_idx"+System.nodeId;
$.ajax({
type: "GET",
//contentType: "text/xml",
url: System.zooUrl+"?service=wps&version=1.0.0&request=Execute&Identifier=np.refreshIndex&DataInputs=id="+node.id+"&RawDataOutput=Result@mimeType=text/xml",
//data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
refreshAggregation();
colModel=[];
fields=[];
try{
var tmp=$.xml2json(xml.responseXML);
var nbCol=0;
$(".fselect").html("<option>"+System.messages["Choose"]+"</option>");
if(tmp.fields){
if(tmp.fields.field.length)
for(j=0;j<tmp.fields.field.length;j++){
colModel[nbCol]={display: tmp.fields.field[j].id, name : tmp.fields.field[j].id, width: (nbCol==0?80:120), sortable : true, align: 'center'};
fields[nbCol]=tmp.fields.field[j].id;
$(".fselect").append("<option>"+fields[nbCol]+"</option>");
nbCol++;
}
else{
colModel[nbCol]={display: tmp.fields.field.id, name : tmp.fields.field.id, width: (nbCol==0?80:120), sortable : true, align: 'center'};
fields[nbCol]=tmp.fields.field.id;
$(".fselect").append("<option>"+fields[nbCol]+"</option>");
nbCol++;
}
}
if(System.onIndexRefresh){
System.onIndexRefresh();
System.onIndexRefresh=null;
}
var localTmp1=tmp;
if(tmp.fields){
try{
$("#dsContainer1").html('<table id="flex_csv1" class="hideBody"></table>');
System.flex1=$("#flex_csv1").flexigrid({
autoload: true,
url: System.zooUrl,
dataType: 'xml',
colModel: colModel,
usepager: true,
sortname: (tmp.fields.field.length?tmp.fields.field[0].id:tmp.fields.field.id),
sortorder: "asc",
id: 1,
fields: fields,
dwDataSource: System.dbuser,
dwLayer: tmp.name,
dwDataType: (tmp.geometry=='Polygon'?'polygon':(tmp.geometry=='Point'?'point':'line')),
mmid: this.mmid,
nbElements: tmp.featureCount,
title: "Index ( "+tmp.name+" )",
useLimit: true,
limit: 10,
showTableToggleBtn: true,
tableToggleBtns:
[
{title: System.messages["Display parameters"],name: 'table0',onclick: function(){
var myId=this.id.split('_')[1];
loadIndexDisplaySettings();
}}
],
bottomToggleBtns:
[
{content: '<span class="pEncoding">'+System.messages["Choose encoding:"]+'<input href="#" type="text" class="change-format" style="width: 80px;margin-top: 5px;" name="swenc_1" id="swenc_1" value="'+tmp.encoding+'" /></span>'}
],
width: "100%",
height: 290
});
$(".toolbar2").find("a.data").each(function(){
$(this).removeClass("desactivated");
});
$(".tabs-project").find("#data > .loader-container").each(function(){
$(this).hide();
});
}catch(e){alert("Flexigrid failed to be created "+e);}
}
}
catch(e){
alert(e);
}
}
}
});
}
var toRunAfter=[];
function saveLayerStyle(){
var dvalue="";
try{
dvalue=$("#s_ctype").val();
if(dvalue=="timeline")
dvalue=$("#dropdown1").val();
}catch(e){
dvalue="uniqSymb";
}
localArg=arguments[0];
localArg1=(arguments>2?arguments[2]:null);
var lhatch=$("#class-hatch_check")[0]?$("#class-hatch_check")[0]:$("#hatch_check")[0];
var prefix=(arguments.length>2?"class-":(arguments.length>1?"class-style-":(arguments.length>0?"class-":"")));
var prefix1=(arguments.length>2?"class_":(arguments.length>1?"class_style_":(arguments.length>0?"class_":"")));
var localArgs=arguments;
var url=System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=mapfile.saveLayerStyle&DataInputs=";
var newcName="";
try{
url+="prefix=indexes;map="+($("#agregation").is(":visible")?"A"+$("#p_tname").val()+"_":"")+"Index"+System.nodeId;
url+=";layer=indexes."+($("#agregation").is(":visible")?"agregate_t"+$("#p_tname").val()+"_idx_":"view_idx")+System.nodeId;
url+=";mmClassName="+$("#"+prefix+"cName").val();
newCName=$("#"+prefix+"cName").val();
if($("#"+prefix+"cExpressionC")[0].checked){
url+=";mmExpr="+$("#"+prefix+"cExpression").val();
}
url+=";mmClassName="+$("#"+prefix+"cName").val();
if(arguments.length>2)
url+=";mmStep="+arguments[2];
url+=";mmType="+dvalue;
if(System.rasterLayer==1)
url+=";mmOpacity="+$("#opacity").val().replace("%","")+";resm="+$("#resMethod").val()+(arguments.length==0?";force=true":"");
else{
url+=";mmSymb="+((lhatch && lhatch.checked==true) && arguments.length<=1?"polygon_hatch;mmHatchWidth="+$("#"+(lhatch.id=="class-hatch_check"?"class-":"")+"hatch_width").val()+";mmAngle="+$("#"+(lhatch.id=="class-hatch_check"?"class-":"")+"hatch_angle").val():((lhatch && lhatch.checked==false)?"":$("#"+prefix1+"symbolSelected").val()));
url+=";mmFill="+$("#"+prefix+"fill-colorpicker").val().replace("#","");
url+=";mmStroke="+$("#"+prefix+"stroke-colorpicker").val().replace("#","");
url+=($("#"+prefix+"stroke-width")[0]?";mmStrokeWidth="+$("#"+prefix+"stroke-width").val():"");
url+=";mmWidth="+$("#"+prefix1+"layerWidth").val();
url+=";mmSize="+((lhatch && lhatch.checked==false) && arguments.length<=1?"-1.0":$("#"+(lhatch && lhatch.checked==true && arguments.length<=1?(lhatch.id=="class-hatch_check"?"class-":"")+"hatch_size":prefix1+"layerSize")).val());
url+=";mmOpacity="+$("#opacity").val().replace("%","");
url+=";"+(arguments.length>0?"mmClass="+arguments[0]:"mmClass=0");
url+=(arguments.length>1 && arguments[1]!=null?";mmStyle="+arguments[1]:"");
url+=(arguments.length==2?";mmStep="+arguments[2]:"");
url+=(arguments.length==0?";force=true":"");
url+=($('#'+prefix+'stroke-colorpicker-chk')[0]?($('#'+prefix+'stroke-colorpicker-chk')[0].checked?"":";noStroke=true"):"");
url+=($('#'+prefix+'fill-colorpicker-chk')[0]?($('#'+prefix+'fill-colorpicker-chk')[0].checked?"":";noFill=true"):"");
url+=($('#'+prefix+'pattern_check')[0]&&$('#'+prefix+'pattern_check')[0].checked?";pattern="+$('#'+prefix+'pattern').val():"");
url+=($("#"+prefix1+"layerGap")[0]?";mmGap="+$("#"+prefix1+"layerGap").val():"");
url+=($("#"+prefix1+"symbol_check")[0] && $("#"+prefix1+"symbol_check")[0].checked==false?";noSymbolFill=true":"");
}
url+="&RawDataOutput=Result";
}catch(e){
alert(e);
}
$.ajax({
localArgs: localArgs,
type: "GET",
prefix1: prefix1,
prefix: prefix,
url: url,
dataType: "xml",
complete: function(xml,status){
$.notifyBar({ cls: "success", html: xml.responseText });
if(localArg>=0){
$("#"+this.prefix1+"Legend")[0].src=System.mapUrl+"?map="+System.dataPath+"/indexes_maps/map4legend_Index"+System.nodeId+"_indexes_view_idx"+System.nodeId+(localArgs.length>2?"_step"+localArgs[2]:"")+".map&service=WMS&version=1.0.0&request=Getmap&LAYERS=indexes.view_idx"+System.nodeId+(localArg>0?"_"+(localArg+1):"")+"&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=-1.5,-1.5,7.5,7.5&SRS=EPSG:4326&WIDTH=24&HEIGHT=24&mmTime="+Math.random();
}else{
if($("#Legend")[0]){
$("#Legend")[0].src=System.mapUrl+"?map=/Users/djay/Sites/data/maps/map4legend_"+$("#mapName")[0].value+"_"+System.mmNodeId+".map&service=WMS&version=1.0.0&request=Getmap&LAYERS="+System.mmNodeId+"&SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=png&BBOX=-1.5,-1.5,7.5,7.5&SRS=EPSG:4326&WIDTH=24&HEIGHT=24&mmTime="+Math.random();
}
}
refreshLayerStyle();
}
});
}
function editClass(){
//alert($("#agregation").is(":visible"));
params=[
{"name":"prefix","value":"indexes","dataType":"string"},
{"name":"name","value":($("#agregation").is(":visible")?"A"+$("#p_tname").val()+"_":"")+"Index"+System.nodeId+($("#agregate_step").is(":visible")?"_step"+($("#agregate_step")[0].selectedIndex-1):""),"dataType":"string"},
{"name":"layer","value":"indexes."+($("#agregation").is(":visible")?"agregate_t"+$("#p_tname").val()+"_idx_"+System.nodeId:"view_idx"+System.nodeId),"dataType":"string"},
{"name":"orig","value":System.dbuserName,"dataType":"string"},
{"name":"id","value":System.nodeId,"dataType":"string"},
{"name": "mmClass","value": arguments[0],"dataType":"string"}
];
if(arguments.length>1)
params.push({"name": "mmStep","value": arguments[1],"dataType":"string"});
data=WPSGetHeader("mapfile.createLegend")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
$( "#class-dialog" ).html(xml.responseText);
$( "#class-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false,
height:260,
width:370
});
$('#class-fill-colorpicker').colorPicker();
$('#class-stroke-colorpicker').colorPicker();
for(i=0;i<toRunAfter.length;i++)
toRunAfter[i]();
$( "#slider-opacity" ).slider({
value:$("#opacity")[0].value.replace("%",""),
min: 0,
max: 100,
step: 1,
slide: function( event, ui ) {
$("#opacity").val(ui.value + "%" );
}
});
}
});
}
function classifyMap(){
var localArg=arguments[0];
if(arguments.length>1)
var localArg0="A"+arguments[1]+"_";
$.ajax({
type: "GET",
url: System.zooUrl+"?request=Execute&service=WPS&version=1.0.0&Identifier=mapfile.classifyMap&DataInputs=prefix=indexes;orig="+System.dbuserName+";layer=indexes.view_idx"+System.nodeId+";map="+(localArg0?localArg0:"")+"Index"+System.nodeId+";field="+$("#s_fname").val()+";from="+$("#s_color2").val().replace("#","")+";to="+$("#s_color3").val().replace("#","")+""+($("#s_ctype").val()=="gradSymb" || ($("#dropdown1").val()=="gradSymb" && $("#dropdown1").is(":visible"))?";type=gs":"")+($("#s_ctype").val()=="uniqVal"?"":";nbClasses="+$("#s_nbc").val())+";formula="+$("#s_formula").val()+($("#s_ctype").val()=="timeline"?";mmStep="+($("#mmsteps")[0].selectedIndex-2)+";mmType="+$("#dropdown1").val():";type="+$("#s_ctype").val())+($("#dropdownd").val()!=-1?";method="+$("#dropdownd").val().replace("%",""):"")+(localArg0?";agregate=true":"")+";mmOpacity=45&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status){
if(localArg=="cc"){
$("#ccLegend")[0].src="http://127.0.0.1/np-bin/zoo_loader.cgi?request=Execute&service=WPS&version=1.0.0&Identifier=classifier.getClassifierImage&DataInputs=from="+$("#cc-min-colorpicker").val().replace("#","")+";to="+$("#cc-max-colorpicker").val().replace("#","")+";nbClass=24&RawDataOutput=Result";
}
$("#indexStyle"+(localArg0?"A":"")).html(xml.responseText);
$(".flexiClasses"+(localArg0?"A":"")).flexigrid({
title: 'Classes',
noSelection: true,
height: 220,
rp: 4,
usepager: false,
resizable: false
});
}
});
}
System.cpi=2;
function _startColorPicker(){
tColor='#00ff00';
if(arguments.length>0){
tColor='#'+arguments[0];
}
$('#customWidget2 > div').html('<div id="colorSelector2"><div style="background-color:'+tColor+'"></div></div><div id="colorpickerHolder2"></div>');
$("#s_color2").val(tColor.replace("#",""));
$('#colorpickerHolder2').ColorPicker({
flat: true,
color: tColor,
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector2 div').css('backgroundColor', '#' + hex);
$("#s_color2").val(hex);
}
});
tColor='#00ff00';
if(arguments.length>1){
tColor='#'+arguments[1];
}
$("#s_color3").val(tColor.replace("#",""));
$('#customWidget3 > div').html('<div id="colorSelector3"><div style="background-color:'+tColor+'"></div></div><div id="colorpickerHolder3"></div>');
$(' #colorpickerHolder3').ColorPicker({
flat: true,
color: tColor,
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector3 div').css('backgroundColor', '#' + hex);
$("#s_color3").val(hex);
}
});
$('#colorpickerHolder2>div, #colorpickerHolder3>div').css('position', 'absolute');
var widt = false;
$('#colorSelector2').bind('click', function() {
$('#colorpickerHolder2').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
$('#colorSelector3').bind('click', function() {
$('#colorpickerHolder3').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
}
function startColorPicker(){
$("#customWidget2 > div").html('<div id="colorSelector2"><div style="background-color:#'+(arguments.length>0?arguments[0]:'9ACB6B')+'"></div></div><div id="colorpickerHolder2"></div>');
var tColor="ff0000";
if(arguments.length>0){
$('#colorSelector2 div').css('backgroundColor', '#' + arguments[0]);
tColor=arguments[0];
}
$('#colorpickerHolder2').ColorPicker({
flat: true,
color: "#"+tColor,
onSubmit: function(hsb, hex, rgb) {
$('#colorSelector2 div').css('backgroundColor', '#' + hex);
$("#s_color2").val(hex);
}
});
$('#colorpickerHolder2>div').css('position', 'absolute');
var widt = false;
$('#colorSelector2').bind('click', function() {
$('#colorpickerHolder2').stop().animate({height: widt ? 0 : 173}, 500);
widt = !widt;
});
}
function startLayerStyleFlexi(){
$(".flexiClassesA").flexigrid(
{
title: 'Classes',
noSelection: true,
height: 220,
rp: 4,
usepager: false,
showTableToggleBtn: true,
tableToggleBtns:
[
{
title: System.messages["Display table parameters"],name: 'table',onclick: function(){
var myId=this.id.split('_')[1];
loadAgregatedIndexDisplaySettings();
}
},
{
title: System.messages["Display graph parameters"],name: 'chart',onclick: function(){
var myId=this.id.split('_')[1];
loadAgregatedIndexGraphSettings();
}
},
{
title: System.messages["Display repport parameters"],name: 'repport',onclick: function(){
var myId=this.id.split('_')[1];
loadAgregatedIndexRepportSettings();
}
}
],
resizable: false});
}
function refreshLayerStyle(){
params=[
{"name":"prefix","value":"indexes","dataType":"string"},
{"name":"name","value":($("#agregation").is(":visible")?"A"+$("#p_tname").val()+"_":"")+"Index"+System.nodeId+($("#agregate_step").is(":visible") && $("#agregate_step")[0].selectedIndex-1>=0?"_step"+($("#agregate_step")[0].selectedIndex-1):""),"dataType":"string"},
{"name":"layer","value":"indexes."+($("#agregation").is(":visible")?"agregate_t"+$("#p_tname").val()+"_idx_":"view_idx")+System.nodeId+($("#agregate_step").is(":visible") && $("#agregate_step")[0].selectedIndex-1>=0?"_step"+($("#agregate_step")[0].selectedIndex-1):""),"dataType":"string"},
{"name":"orig","value":System.dbuserName,"dataType":"string"},
{"name":"id","value":System.nodeId,"dataType":"string"}
];
if($('.tl').is(":visible")){
lindex=-2;
$("#mmsteps option").each(function(){
if($(this).is(":selected"))
return;
else
lindex++;
});
params.push({"name": "mmStep","value": lindex,"dataType":"string"});
}
data=WPSGetHeader("mapfile.createLegend")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
if($("#agregation").is(":visible")){
$("#agregate_flexi").html(xml.responseText);
startLayerStyleFlexi();
}else{
$("#indexStyle").html(xml.responseText);
$(".flexiClasses").flexigrid({
title: 'Classes',
noSelection: true,
height: 220,
rp: 4,
usepager: false,
resizable: false
});
$(".toolbar2").find("a.symbology").each(function(){
$(this).removeClass("desactivated");
});
$(".tabs-project").find("#symbology > .loader-container").each(function(){
$(this).hide();
});
refreshGraphFields();
refreshTableFields();
}
}
}
});
params=[
{"name":"id","value":System.nodeId,"dataType":"string"}
];
if(arguments.length>0)
params.push({"name":"step","value":arguments[0],"dataType":"string"});
data=WPSGetHeader("np.getIndexStyle")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
tmp=$.parseJSON(xml.responseText);
$('#s_fname').val(tmp.var);
$('#s_formula').val(tmp.formula);
$('#s_nbc').val(tmp.nbc);
$('#s_ctype').val((tmp.ctype=="gs"?"gradSymb":(tmp.ctype=="tl"?"timeline":(tmp.ctype=="uv"?"uniqValue":""))));
$('#dropdownd').val((tmp.cmethod?tmp.cmethod:-1));
if(tmp.ctype=="tl"){
$('.tl').show();
//$("#mmsteps").val(-1);
$("#dropdown1").val(tmp.cctype);
System.runAfterStep=function(){
if(!System.break)
$("#mmsteps").val(-1);
else
$("#mmsteps").val(System.stepId0);
};
MMStyler.Timeline.refreshStepList();
System.startWindowStep=function(){
System.break=true;
System.stepId0=$("#mmsteps").val();
refreshLayerStyle($("#mmsteps")[0].selectedIndex-2);
};
}
else{
$('.tl').hide();
System.startWindowStep=function(){};
}
if($("#s_ctype").val()=='gradSymb')
$('#discret').show();
else $('#discret').hide();
_startColorPicker(tmp.icol,tmp.ocol);
}
}
});
}
function saveIndexDisplaySettings(){
params=[
{"name":"tmpl","value":"Indexes/tableDisplaySettings","dataType":"string"},
{"name":"id","value":System.nodeId,"dataType":"string"}
];
if($("#table_steps").is(":visible") && $("#table_step").val()>0)
params.push({"name":"step","value":($("#table_step")[0].selectedIndex-1),"dataType":"string"});
if(arguments.length>0)
params.push({
"name":"tid",
"value":arguments[0],
"dataType":"string"
});
if($("#agregate_step")[0] && $("#agregate_step")[0].selectedIndex-1>=0)
params.push({
"name":"step",
"value":$("#agregate_step")[0].selectedIndex-1,
"dataType":"string"
});
tuples=[]
for(var i=0;i<$("#dtable_fnb").val();i++){
var params0={
"display": $("#dtable_display_"+i).is(':checked')+"",
"search": $("#dtable_search_"+i).is(':checked')+"",
"pos": $("#dtable_pos_"+i).val(),
"var": $("#dtable_var_"+i).val(),
"label": $("#dtable_label_"+i).val(),
"value": $("#dtable_value_"+i).val(),
"width": $("#dtable_width_"+i).val(),
};
if($('#agregation').is(":visible") && $("#agregate_step")[0].selectedIndex-1>=0){
params0["step"]=$("#agregate_step")[0].selectedIndex-1;
}
params.push({
name:"tuple",
value:JSON.stringify(params0),
mimeType: "application/json"
});
}
data=WPSGetHeader("np.saveIndexDisplaySettings")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
checkWPSResult(xml);
}
});
}
function refreshIndexDisplay(){
System.removed=0;
$("#dsContainer1 .hDiv").find("th").each(function(){
for(var i=0;i<$("#dtable_fnb").val();i++){
if($("#dtable_var_"+i).val()==$(this).text()){
var ii=$("#dtable_varid_"+i).val();
ii-=3;
var ncol = $("th[axis='col"+ii+"']",$("#dsContainer1 .hDiv"))[0];
var n = $('thead th',$("#dsContainer1 .hDiv")).index(ncol);
var cb = $('input[value='+ii+']',$("#dsContainer1 .nDiv"))[0];
$('th:visible div:eq('+n+')',$("#dsContainer1 .hDiv")).css('width',$("#dtable_width_"+i).val());
$('tr',$("#dsContainer1 .bDiv")).each (
function ()
{
$('td:visible div:eq('+n+')',this).css('width',$("#dtable_width_"+i).val());
}
);
if($("#dtable_display_"+i).is(':checked')){
ncol.hide = false;
$(ncol).show();
cb.checked = true;
}
else{
ncol.hide = true;
$(ncol).hide();
cb.checked = false;
}
$('tbody tr',$("#dsContainer1 .bDiv")).each
(
function ()
{
if ($("#dtable_display_"+i).is(':checked'))
$('td:eq('+n+')',this).show();
else
$('td:eq('+n+')',this).hide();
}
);
}
}
});
}
function loadIndexDisplaySettings(){
$("#tablesettings-dialog").window("close");
$("#tablesettings-dialog").remove();
$("body").append('<div id="tablesettings-dialog" title="Paramétrage de l\'affichage"></div>');
$('#tablesettings-dialog').html("");
params=[
{"name":"tmpl","value":"Indexes/tableDisplaySettings","dataType":"string"},
{"name":"id","value":System.nodeId,"dataType":"string"}
];
if($("#table_steps").is(":visible") && $("#table_step").val()>0)
params.push({"name":"step","value":($("#table_step")[0].selectedIndex-1),"dataType":"string"});
if($("#agregate_step")[0] && $("#agregate_step")[0].selectedIndex-1>=0)
params.push({
"name":"step",
"value":$("#agregate_step")[0].selectedIndex-1,
"dataType":"string"
});
if(arguments.length>0)
params.push({
"name":"tid",
"value":arguments[0],
"dataType":"string"
});
fieldss="";
fields="";
fields_width="";
cnt=0;
$("#"+(arguments.length>0?"agregate_table":'dsContainer1')+" .hDiv").find("th").each(function(){
if(this.style.display!='none'){
if($(this).hasClass("sorted"))
fieldss+=$(this).text();
fields+=(cnt>0?",":"")+$(this).text();
fields_width+=(cnt>0?',':'')+$(this).width();
cnt+=1;
}
});
params.push({"name": "rord","value":fieldss,dataType:"string"});
params.push({"name": "rcol","value":fields,dataType:"string"});
params.push({"name": "rwidth","value":fields_width,dataType:"string"});
data=WPSGetHeader("template.display")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$('#tablesettings-dialog').append(xml.responseText);
$("#flex_display2").flexigrid();
$( "#tablesettings-dialog" ).window({
minimizable:false,
maximizable:false,
resizable: false
});
}
}
});
}
function preview(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.getMapRequest&DataInputs=t_id="+($("#agregation").is(":visible")?$("#p_tname").val():$("#indicateurs_indicateurs_territoires").val())+";preview=true&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
try{
$('#preview-territory-dialog').window({
width: 400,
height: 300,
left:150,
top:150,
maximizable:false,
minimizable:false,
resizable: false
});
var treg=new RegExp(System.indexMap,"g");
var tmpName="project_"+($("#agregation").is(":visible")?"A"+$("#p_tname").val()+"_":"")+"Index"+System.nodeId+($("#agregate_step")[0].selectedIndex-1>=0?"_step"+($("#agregate_step")[0].selectedIndex-1):"")+".map";
if($("#mmsteps")[0].selectedIndex-2>=0)
tmpName="timeline_Index"+System.nodeId+"_indexes_view_idx"+System.nodeId+(/*$("#agregate_steps").is(":visible")?*/"_step"+($("#mmsteps")[0].selectedIndex-2)/*:""*/)+".map";//project_"+($("#agregation").is(":visible")?"A"+$("#p_tname").val()+"_":"")+"Index"+System.nodeId+".map";
if($("#agregate_steps").is(":visible") && $("#agregate_steps")[0].selectedIndex>0)
tmpName="project_"+($("#agregation").is(":visible")?"A"+$("#p_tname").val()+"_":"")+"Index"+System.nodeId+($("#mmsteps")[0].selectedIndex>0?"_step"+($("#agregate_steps")[0].selectedIndex-1):"")+".map";
//alert(tmpName);
var cSrc=xml.responseText.replace(treg,System.dataPath+"/indexes_maps/"+tmpName);
var tmp=cSrc.split("LAYERS=")
cSrc=tmp[0]+"LAYERS=indexes."+($("#agregation").is(":visible")?"agregate_t"+$("#p_tname").val()+"_idx_":"view_idx")+System.nodeId+($("#agregate_steps").is(":visible") && $("#agregate_step")[0].selectedIndex>0?"_step"+($("#agregate_step")[0].selectedIndex-1):"");
if(!System._cnt)
System._cnt=0;
System._cnt+=1;
$("#t_preview")[0].src=cSrc+"&t="+System._cnt;
}catch(e){
alert(e);
}
}
}
});
}
function refreshAgregate(){
var tableName="indicateurs";
tableName2="agregation";
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.details&DataInputs=table="+tableName+";id="+System.nodeId+";tab="+tableName2+"_"+$("#p_tname").val()+($("#agregate_steps").is(":visible") && $("#agregate_step")[0].selectedIndex>0?";step="+($("#agregate_step")[0].selectedIndex-1):"")+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var data=$.parseJSON(xml.responseText);
if(System.refreshSteps)
addSteps("agregate_step");
System.refreshSteps=true;
var hasValue=false;
for(var i in data){
$("#"+tableName2+"_"+i).val("");
if(data[i]!=null){
$("#"+tableName2+"_"+i).val(data[i]);
$("#agregation_chk").prop('checked', true);
$("#agreg").toggle(true);
refreshLayerStyle();
hasValue=true;
}
}
if(!hasValue){
$("#agregation_chk").prop('checked', false);
$("#agreg").toggle(false);
}
}
}
});
}
function refreshRepport(){
$("#repport_editor").hide();
var tableName="indicateurs";
tableName2="repport";
var vars="";
if($("#repport_steps").is(":visible") && $("#repport_step").val()>0){
vars+=";step="+($("#repport_step")[0].selectedIndex-1);
}
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.details&DataInputs=table="+tableName+";id="+System.nodeId+";tab="+tableName2+vars+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var data=$.parseJSON(xml.responseText);
var hasValue=false;
for(var i in data){
$("#repport_doc_url").attr('href',data["doc_url"]);
$("#repport_doc_url").html(data["doc"]);
hasValue=true;
}
if(!hasValue){
$("#repport_doc_url").attr('href',System.public_map_url+"idx_templates/default_"+$("#graphs_f_type").val()+".odt");
$("#repport_doc_url").html("default_"+$("#graphs_f_type").val()+".odt");
}
editRepport();
}
}
});
}
function editRepport(){
System.prefix=(arguments.length>0?"agregate_":"");
var vars=(arguments.length>0?";tid="+$("#p_tname").val():"");
if($("#repport_doc_url").html()!=""){
var tableName="indicateurs";
tableName2="repport";
if($("#repport_steps").is(":visible") && $("#repport_step").val()>0){
vars+=";step="+($("#repport_step")[0].selectedIndex-1);
}
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=template.display&DataInputs=tmpl=Indexes/repportSettings;table="+tableName+";id="+System.nodeId+";tab="+tableName2+";template="+$("#repport_doc_url").html()+vars+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$(".repport").removeClass('desactivated')
$("#"+System.prefix+"repport_editor").html(xml.responseText);
if(System.refreshSteps)
addSteps(System.prefix+"repport_step");
System.refreshSteps=true;
$("#"+System.prefix+"repport_display2").flexigrid(
{
mmid: 1000,
title: 'Paramétrage de rapport',
noSelection: true,
height: 220,
rp: 4,
usepager: false,
resizable: false
}
);
$("#"+System.prefix+"repport_editor").show();
try{
$(".toolbar2").find("a.symbology").each(function(){
$(this).removeClass("desactivated");
});
}catch(e){}
}else
$("#repport_editor").hide();
}
});
}
}
function addSteps(){
var tid=arguments[0];
if($("#s_ctype").val()=="timeline"){
$('#'+tid).html("");
var $options = $("#mmsteps > option").clone();
$('#'+tid).append($options);
$('#'+tid).find('option[value="add"]').each(function(){
$(this).remove();
});
$("#"+tid+"s").show();
}else{
$("#"+tid+"s").hide();
}
}
function saveRepport(){
System.prefix=(arguments.length>0?arguments[0]:"");
var params=[
{name: "id", value: System.nodeId, dataType: "sring"}
];
if(arguments.length>0)
params.push({name: "tid", value: $("#p_tname").val(), dataType: "sring"});
$("#"+System.prefix+"repport_display2").find("input[type=checkbox]").each(function(){
var tmp=(this.id+"").split('_');
var params0={name: "tuple", value:'{"id":'+tmp[tmp.length-1]+',"display":"'+$(this).is(":checked")+'","var":"'+$("#"+System.prefix+"rtable_name_"+tmp[tmp.length-1]).val()+'","type":'+$("#"+System.prefix+"rtable_type_"+tmp[tmp.length-1]).val()+',"value":"'+ $("#"+System.prefix+"rtable_value_"+tmp[tmp.length-1]).val()+'"}',mimeType: "application/json"};
if($('#agregation').is(":visible") && $("#agregate_step")[0].selectedIndex-1>=0){
params0["step"]=$("#agregate_step")[0].selectedIndex-1;
}
params.push(params0);
});
if($("#repport_steps").is(":visible") && $("#repport_step").val()>0){
params.push({name: "step", value: ($("#repport_step")[0].selectedIndex-1), dataType: "sring"});
}
if($('#agregation').is(":visible") && $("#agregate_step")[0].selectedIndex-1>=0) {
params.push({name: "step", value: ($("#agregate_step")[0].selectedIndex-1), dataType: "sring"});
}
data=WPSGetHeader("np.saveRepportSettings")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
checkWPSResult(xml);
}
});
}
function saveRepportFile(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.saveRepportFile&DataInputs=id="+System.nodeId+"&RawDataOutput=Result",
dataType: 'xml',
complete: function(xml,status) {
if(checkWPSResult(xml))
refreshRepport();
}
});
}
function loadAgregatedIndexGraphSettings(){
$("#rgraphsettings-dialog").window('close');
$("#rgraphsettings-dialog").remove();
$("body").append('<div id="rgraphsettings-dialog" title="Paramétrage du graph / Agrégation"></div>');
$('#rgraphsettings-dialog').html("");
$.ajax({
type: "GET",
url: "./Indexes/GraphPart;prefix=a",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$('#rgraphsettings-dialog').append(xml.responseText);
$("#rgraphsettings-dialog" ).window({
minimizable:false,
maximizable:false,
height: 550,
width: 750,
resizable: false
});
System.onSelectField0=function(){
refreshGraphFields("agregate_");
}
updateSelectWithFields(['agregate_graphs_vx','agregate_graphs_vy'],$("#p_tname").val());
//refreshGraphFields("agregate_");
}
}
});
}
function loadAgregatedIndexDisplaySettings(){
$("#rtablesettings-dialog").window('close');
$("#rtablesettings-dialog").remove();
$("body").append('<div id="rtablesettings-dialog" title="Paramétrage de l\'affichage / Agrégation"></div>');
$('#rtablesettings-dialog').html("");
$.ajax({
type: "GET",
url: "./Indexes/TablePart;prefix=a",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$('#rtablesettings-dialog').append(xml.responseText);
loadPageFromFile(System.dbuserName,10,"indexes.agregate_t"+$("#p_tname").val()+"_idx_"+System.nodeId+($("#agregate_steps").is(":visible") && $("#agregate_step")[0].selectedIndex>0?"_step"+($("#agregate_step")[0].selectedIndex-1):""));
$( "#rtablesettings-dialog" ).window({
top: 200,
minimizable:false,
maximizable:false,
width: 650,
resizable: false
});
//refreshTableFields("agregate_",$("#p_tname").val());
}
}
});
}
function loadAgregatedIndexRepportSettings(){
$("#rrepportsettings-dialog").window('close');
$("#rrepportsettings-dialog").remove();
$("body").append('<div id="rrepportsettings-dialog" title="Paramétrage du repport / Agrégation"></div>');
$('#rrepportsettings-dialog').html("");
$.ajax({
type: "GET",
url: "./Indexes/DocPart;prefix=a",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
$('#rrepportsettings-dialog').append(xml.responseText);
editRepport("agregate_");
$("#rrepportsettings-dialog" ).window({
minimizable:false,
maximizable:false,
height: 350,
width: 750,
resizable: false
});
}
}
});
}
function previewRepport(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.previewDoc&DataInputs=oDoc="+$("#repport_doc_url").text()+($("#repport_step").val()!="-1" && ($("#repport_step")[0].selectedIndex-1)>=0?";step="+($("#repport_step")[0].selectedIndex-1):"")+";id="+System.nodeId+(arguments.length==1?";tid="+$("#p_tname").val():"")+($("#agregate_step")[0] && $("#agregate_step")[0].selectedIndex-1>=0?";step="+($("#agregate_step")[0].selectedIndex-1):"")+";preview=true&ResponseDocument=Result@asReference=true",
complete: function(xml,status) {
if(checkWPSResult(xml,false,true)){
try{
var lUrl="";
$(xml.responseXML).find("Reference").each(function(){
lUrl=$(this).attr("href");
});
$(xml.responseXML).find("wps\\:Reference").each(function(){
lUrl=$(this).attr("href");
});
$("#prd_link").attr("href",lUrl);
var reg=new RegExp(System.tmpUrl,"g");
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=print.preview&DataInputs=file="+lUrl.replace(reg,System.tmpPath)+";res=75&ResponseDocument=Result@asReference=true",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var lUrl="";
$(xml.responseXML).find("Reference").each(function(){
lUrl=$(this).attr("href");
});
$(xml.responseXML).find("wps\\:Reference").each(function(){
lUrl=$(this).attr("href");
});
$("#r_preview").attr("src",lUrl);
$('#preview-repport-dialog').window({
width: 450,
height: 620,
maximizable:false,
minimizable:false,
resizable: false
});
}
}
});
}catch(e){}
}
}
});
}
<|start_filename|>mapmint-ui/templates/preview/modules/addLayer/init.js<|end_filename|>
var WMSLayers=[];
function mmAddWMSLayers(){
var nodes=\$("#wms_list").tree('getChecked');
var tmp={"text":""}
var layers="";
var legend=[];
for(i in nodes)
if(nodes[i]["id"]){
if(layers!="")
layers+=",";
layers+=nodes[i]["id"];
tmp=\$("#wms_list").tree('getParent',nodes[i].target);
legend.push({
"id": "layer_"+i+"_"+(layersList.length),
"text": nodes[i]["text"],
"children": \$("#wms_list").tree('getChildren',nodes[i]["target"])
});
\$("#wms_list").tree('uncheck',nodes[i].target);
}
\$("#layers_list").tree('append',{
parent: \$("#layers_list").tree('getRoot').target,
data:[
{
"id": "layer_"+(layersList.length),
checked: true,
text: '<a href="#" class="sdelete" onclick="removeOverlays(\$(this));"></a>'+System.messages["WMS Layers"]+" "+(WMSLayers.length+1),
children: legend
}
]
});
WMSLayers[WMSLayers.length]=new OpenLayers.Layer.WMS(
"WMS Layers "+(WMSLayers.length+1),
msUrl+"?map="+System.dataPath+"/WMS/"+tmp.text+"ds_ows.map",
{layers: layers,format: "image/png"},
{useCanvas: System.useCanvas,isBaseLayer: false}
);
WMSLayers[WMSLayers.length-1].setVisibility(true);
map.addLayer(WMSLayers[WMSLayers.length-1]);
layersList[layersList.length]=WMSLayers[WMSLayers.length-1];
if(System.fullList.length>0)
System.fullList.push({name: layersList[layersList.length-1].name, id: (layersList.length-1),text: "WMS Layers "+(WMSLayers.length)});
}
<|start_filename|>public_map/css/app.v1.css<|end_filename|>
html {font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}
body {margin:0}
@font-face {font-family: 'mmFont';src: url('../fonts/mmFont.ttf') format('truetype');font-weight: normal;font-style: normal;}
[class^="icon-mm-"],
[class*=" icon-mm-"] {
font-family: 'mmFont', sans-serif;
font-weight: normal;
font-style: normal;
text-decoration: inherit;
-webkit-font-smoothing: antialiased;
}
.icon-mm-logo:before{content: "\e602";}
@font-face {font-family:'Glyphicons Halflings';src:url('../fonts/glyphicons-halflings-regular.eot');src:url('../fonts/glyphicons-halflings-regular-.eot#iefix') format('embedded-opentype'),url('../fonts/glyphicons-halflings-regular.woff') format('woff'),url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg')}
.glyphicon {position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
.glyphicon-asterisk:before {content:"\2a"}
.glyphicon-plus:before {content:"\2b"}
.glyphicon-euro:before {content:"\20ac"}
.glyphicon-minus:before {content:"\2212"}
.glyphicon-cloud:before {content:"\2601"}
.glyphicon-envelope:before {content:"\2709"}
.glyphicon-pencil:before {content:"\270f"}
.glyphicon-glass:before {content:"\e001"}
.glyphicon-music:before {content:"\e002"}
.glyphicon-search:before {content:"\e003"}
.glyphicon-heart:before {content:"\e005"}
.glyphicon-star:before {content:"\e006"}
.glyphicon-star-empty:before {content:"\e007"}
.glyphicon-user:before {content:"\e008"}
.glyphicon-film:before {content:"\e009"}
.glyphicon-th-large:before {content:"\e010"}
.glyphicon-th:before {content:"\e011"}
.glyphicon-th-list:before {content:"\e012"}
.glyphicon-ok:before {content:"\e013"}
.glyphicon-remove:before {content:"\e014"}
.glyphicon-zoom-in:before {content:"\e015"}
.glyphicon-zoom-out:before {content:"\e016"}
.glyphicon-off:before {content:"\e017"}
.glyphicon-signal:before {content:"\e018"}
.glyphicon-cog:before {content:"\e019"}
.glyphicon-trash:before {content:"\e020"}
.glyphicon-home:before {content:"\e021"}
.glyphicon-file:before {content:"\e022"}
.glyphicon-time:before {content:"\e023"}
.glyphicon-road:before {content:"\e024"}
.glyphicon-download-alt:before {content:"\e025"}
.glyphicon-download:before {content:"\e026"}
.glyphicon-upload:before {content:"\e027"}
.glyphicon-inbox:before {content:"\e028"}
.glyphicon-play-circle:before {content:"\e029"}
.glyphicon-repeat:before {content:"\e030"}
.glyphicon-refresh:before {content:"\e031"}
.glyphicon-list-alt:before {content:"\e032"}
.glyphicon-lock:before {content:"\e033"}
.glyphicon-flag:before {content:"\e034"}
.glyphicon-headphones:before {content:"\e035"}
.glyphicon-volume-off:before {content:"\e036"}
.glyphicon-volume-down:before {content:"\e037"}
.glyphicon-volume-up:before {content:"\e038"}
.glyphicon-qrcode:before {content:"\e039"}
.glyphicon-barcode:before {content:"\e040"}
.glyphicon-tag:before {content:"\e041"}
.glyphicon-tags:before {content:"\e042"}
.glyphicon-book:before {content:"\e043"}
.glyphicon-bookmark:before {content:"\e044"}
.glyphicon-print:before {content:"\e045"}
.glyphicon-camera:before {content:"\e046"}
.glyphicon-font:before {content:"\e047"}
.glyphicon-bold:before {content:"\e048"}
.glyphicon-italic:before {content:"\e049"}
.glyphicon-text-height:before {content:"\e050"}
.glyphicon-text-width:before {content:"\e051"}
.glyphicon-align-left:before {content:"\e052"}
.glyphicon-align-center:before {content:"\e053"}
.glyphicon-align-right:before {content:"\e054"}
.glyphicon-align-justify:before {content:"\e055"}
.glyphicon-list:before {content:"\e056"}
.glyphicon-indent-left:before {content:"\e057"}
.glyphicon-indent-right:before {content:"\e058"}
.glyphicon-facetime-video:before {content:"\e059"}
.glyphicon-picture:before {content:"\e060"}
.glyphicon-map-marker:before {content:"\e062"}
.glyphicon-adjust:before {content:"\e063"}
.glyphicon-tint:before {content:"\e064"}
.glyphicon-edit:before {content:"\e065"}
.glyphicon-share:before {content:"\e066"}
.glyphicon-check:before {content:"\e067"}
.glyphicon-move:before {content:"\e068"}
.glyphicon-step-backward:before {content:"\e069"}
.glyphicon-fast-backward:before {content:"\e070"}
.glyphicon-backward:before {content:"\e071"}
.glyphicon-play:before {content:"\e072"}
.glyphicon-pause:before {content:"\e073"}
.glyphicon-stop:before {content:"\e074"}
.glyphicon-forward:before {content:"\e075"}
.glyphicon-fast-forward:before {content:"\e076"}
.glyphicon-step-forward:before {content:"\e077"}
.glyphicon-eject:before {content:"\e078"}
.glyphicon-chevron-left:before {content:"\e079"}
.glyphicon-chevron-right:before {content:"\e080"}
.glyphicon-plus-sign:before {content:"\e081"}
.glyphicon-minus-sign:before {content:"\e082"}
.glyphicon-remove-sign:before {content:"\e083"}
.glyphicon-ok-sign:before {content:"\e084"}
.glyphicon-question-sign:before {content:"\e085"}
.glyphicon-info-sign:before {content:"\e086"}
.glyphicon-screenshot:before {content:"\e087"}
.glyphicon-remove-circle:before {content:"\e088"}
.glyphicon-ok-circle:before {content:"\e089"}
.glyphicon-ban-circle:before {content:"\e090"}
.glyphicon-arrow-left:before {content:"\e091"}
.glyphicon-arrow-right:before {content:"\e092"}
.glyphicon-arrow-up:before {content:"\e093"}
.glyphicon-arrow-down:before {content:"\e094"}
.glyphicon-share-alt:before {content:"\e095"}
.glyphicon-resize-full:before {content:"\e096"}
.glyphicon-resize-small:before {content:"\e097"}
.glyphicon-exclamation-sign:before {content:"\e101"}
.glyphicon-gift:before {content:"\e102"}
.glyphicon-leaf:before {content:"\e103"}
.glyphicon-fire:before {content:"\e104"}
.glyphicon-eye-open:before {content:"\e105"}
.glyphicon-eye-close:before {content:"\e106"}
.glyphicon-warning-sign:before {content:"\e107"}
.glyphicon-plane:before {content:"\e108"}
.glyphicon-calendar:before {content:"\e109"}
.glyphicon-random:before {content:"\e110"}
.glyphicon-comment:before {content:"\e111"}
.glyphicon-magnet:before {content:"\e112"}
.glyphicon-chevron-up:before {content:"\e113"}
.glyphicon-chevron-down:before {content:"\e114"}
.glyphicon-retweet:before {content:"\e115"}
.glyphicon-shopping-cart:before {content:"\e116"}
.glyphicon-folder-close:before {content:"\e117"}
.glyphicon-folder-open:before {content:"\e118"}
.glyphicon-resize-vertical:before {content:"\e119"}
.glyphicon-resize-horizontal:before {content:"\e120"}
.glyphicon-hdd:before {content:"\e121"}
.glyphicon-bullhorn:before {content:"\e122"}
.glyphicon-bell:before {content:"\e123"}
.glyphicon-certificate:before {content:"\e124"}
.glyphicon-thumbs-up:before {content:"\e125"}
.glyphicon-thumbs-down:before {content:"\e126"}
.glyphicon-hand-right:before {content:"\e127"}
.glyphicon-hand-left:before {content:"\e128"}
.glyphicon-hand-up:before {content:"\e129"}
.glyphicon-hand-down:before {content:"\e130"}
.glyphicon-circle-arrow-right:before {content:"\e131"}
.glyphicon-circle-arrow-left:before {content:"\e132"}
.glyphicon-circle-arrow-up:before {content:"\e133"}
.glyphicon-circle-arrow-down:before {content:"\e134"}
.glyphicon-globe:before {content:"\e135"}
.glyphicon-wrench:before {content:"\e136"}
.glyphicon-tasks:before {content:"\e137"}
.glyphicon-filter:before {content:"\e138"}
.glyphicon-briefcase:before {content:"\e139"}
.glyphicon-fullscreen:before {content:"\e140"}
.glyphicon-dashboard:before {content:"\e141"}
.glyphicon-paperclip:before {content:"\e142"}
.glyphicon-heart-empty:before {content:"\e143"}
.glyphicon-link:before {content:"\e144"}
.glyphicon-phone:before {content:"\e145"}
.glyphicon-pushpin:before {content:"\e146"}
.glyphicon-usd:before {content:"\e148"}
.glyphicon-gbp:before {content:"\e149"}
.glyphicon-sort:before {content:"\e150"}
.glyphicon-sort-by-alphabet:before {content:"\e151"}
.glyphicon-sort-by-alphabet-alt:before {content:"\e152"}
.glyphicon-sort-by-order:before {content:"\e153"}
.glyphicon-sort-by-order-alt:before {content:"\e154"}
.glyphicon-sort-by-attributes:before {content:"\e155"}
.glyphicon-sort-by-attributes-alt:before {content:"\e156"}
.glyphicon-unchecked:before {content:"\e157"}
.glyphicon-expand:before {content:"\e158"}
.glyphicon-collapse-down:before {content:"\e159"}
.glyphicon-collapse-up:before {content:"\e160"}
.glyphicon-log-in:before {content:"\e161"}
.glyphicon-flash:before {content:"\e162"}
.glyphicon-log-out:before {content:"\e163"}
.glyphicon-new-window:before {content:"\e164"}
.glyphicon-record:before {content:"\e165"}
.glyphicon-save:before {content:"\e166"}
.glyphicon-open:before {content:"\e167"}
.glyphicon-saved:before {content:"\e168"}
.glyphicon-import:before {content:"\e169"}
.glyphicon-export:before {content:"\e170"}
.glyphicon-send:before {content:"\e171"}
.glyphicon-floppy-disk:before {content:"\e172"}
.glyphicon-floppy-saved:before {content:"\e173"}
.glyphicon-floppy-remove:before {content:"\e174"}
.glyphicon-floppy-save:before {content:"\e175"}
.glyphicon-floppy-open:before {content:"\e176"}
.glyphicon-credit-card:before {content:"\e177"}
.glyphicon-transfer:before {content:"\e178"}
.glyphicon-cutlery:before {content:"\e179"}
.glyphicon-header:before {content:"\e180"}
.glyphicon-compressed:before {content:"\e181"}
.glyphicon-earphone:before {content:"\e182"}
.glyphicon-phone-alt:before {content:"\e183"}
.glyphicon-tower:before {content:"\e184"}
.glyphicon-stats:before {content:"\e185"}
.glyphicon-sd-video:before {content:"\e186"}
.glyphicon-hd-video:before {content:"\e187"}
.glyphicon-subtitles:before {content:"\e188"}
.glyphicon-sound-stereo:before {content:"\e189"}
.glyphicon-sound-dolby:before {content:"\e190"}
.glyphicon-sound-5-1:before {content:"\e191"}
.glyphicon-sound-6-1:before {content:"\e192"}
.glyphicon-sound-7-1:before {content:"\e193"}
.glyphicon-copyright-mark:before {content:"\e194"}
.glyphicon-registration-mark:before {content:"\e195"}
.glyphicon-cloud-download:before {content:"\e197"}
.glyphicon-cloud-upload:before {content:"\e198"}
.glyphicon-tree-conifer:before {content:"\e199"}
.glyphicon-tree-deciduous:before {content:"\e200"}
* {-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
*:before,*:after {-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
html {font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}
body {font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}
a {color:#428bca;text-decoration:none}
a:hover,a:focus {color:#2a6496;text-decoration:underline}
a:focus {outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}
figure {margin:0}
img {vertical-align:middle}
.img-responsive,.thumbnail>img,.thumbnail a>img,.carousel-inner>.item>img,.carousel-inner>.item>a>img {display:block;width:100% \9;max-width:100%;height:auto}
.img-rounded {border-radius:6px}
.img-thumbnail {display:inline-block;width:100% \9;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}
.img-circle {border-radius:50%}
hr {margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}
.sr-only {position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}
.sr-only-focusable:active,.sr-only-focusable:focus {position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}
h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6 {font-family:inherit;font-weight:500;line-height:1.1;color:inherit}
h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small,h1 .small,h2 .small,h3 .small,h4 .small,h5 .small,h6 .small,.h1 .small,.h2 .small,.h3 .small,.h4 .small,.h5 .small,.h6 .small {font-weight:normal;line-height:1;color:#777}
h1,.h1,h2,.h2,h3,.h3 {margin-top:20px;margin-bottom:10px}
h1 small,.h1 small,h2 small,.h2 small,h3 small,.h3 small,h1 .small,.h1 .small,h2 .small,.h2 .small,h3 .small,.h3 .small {font-size:65%}
h4,.h4,h5,.h5,h6,.h6 {margin-top:10px;margin-bottom:10px}
h4 small,.h4 small,h5 small,.h5 small,h6 small,.h6 small,h4 .small,.h4 .small,h5 .small,.h5 .small,h6 .small,.h6 .small {font-size:75%}
h1,.h1 {font-size:36px}
h2,.h2 {font-size:30px}
h3,.h3 {font-size:22px}
h4,.h4 {font-size:18px}
h5,.h5 {font-size:14px}
h6,.h6 {font-size:12px}
h5.sbt{color:#222;margin-bottom:5px;}
.nav {padding-left:0;margin-bottom:0;list-style:none}
.nav>li {position:relative;display:block}
.nav>li>a {position:relative;display:block;padding:10px 15px;color:#8a8a8a;}
.header>.nav>li>a {border-right:1px solid #e5e5e5;}
.nav>li>a.active {background:#f7f8fb;}
.nav>li>a:hover,.nav>li>a:focus {text-decoration:none;background-color:#eee}
.nav>li.disabled>a {color:#777}
.nav>li.disabled>a:hover,.nav>li.disabled>a:focus {color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}
.nav .open>a,.nav .open>a:hover,.nav .open>a:focus {background-color:#eee;border-color:#428bca}
.nav .nav-divider {height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}
.nav>li>a>img {max-width:none}
.nav-tabs {border-bottom:0;box-shadow:none;}
.nav-tabs>li {float:left;margin-bottom:0}
.nav-tabs>li>a {margin-right:0;line-height:1.42857143;border:1px solid transparent;border-right:1px solid #CCC !important;border-radius: 0}
.nav-tabs>li.active>a{border-right:1px solid #CCC !important;}
.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus {color:#333;cursor:default;background-color:#fff;border-bottom-color:transparent;border-right:1px solid #CCC !important;}
.nav-tabs.nav-justified {width:100%;border-bottom:0}
.nav-tabs.nav-justified>li {float:none}
.nav-tabs.nav-justified>li>a {margin-bottom:5px;text-align:center}
.nav-tabs.nav-justified>.dropdown
.nav-justified>li {float:none}
.nav-justified>li>a {margin-bottom:5px;text-align:center}
.nav-justified>.dropdown .dropdown-menu {top:auto;left:auto}
@media (min-width: 768px) {.nav-justified > li {display:table-cell;width:1%}
.nav-justified>li>a {margin-bottom:0}
}
.nav-tabs-justified {border-bottom:0}
.nav-tabs-justified>li>a {margin-right:0;border-radius:4px}
.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus {border:1px solid #ddd}
@media (min-width: 768px) {.nav-tabs-justified > li > a {border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}
.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus {border-bottom-color:#fff}
}
.tab-content>.tab-pane {display:none}
.tab-content>.active {display:block}
.nav-tabs .dropdown-menu {margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}
.navbar {position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}
@media (min-width: 768px) {.navbar {border-radius:4px}
}
@media (min-width: 768px) {.navbar-header {float:left}
}
.navbar-collapse {padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}
.navbar-collapse.in {overflow-y:auto}
@media (min-width: 768px) {.navbar-collapse {width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}
.navbar-collapse.collapse {display:block !important;height:auto !important;padding-bottom:0;overflow:visible !important}
.navbar-collapse.in {overflow-y:visible}
.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse {padding-right:0;padding-left:0}
}
.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse {max-height:340px}
@media (max-width: 480px) and (orientation: landscape) {.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse {max-height:200px}
}
.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse {margin-right:-15px;margin-left:-15px}
@media (min-width: 768px) {.container > .navbar-header,.container-fluid > .navbar-header,.container > .navbar-collapse,.container-fluid > .navbar-collapse {margin-right:0;margin-left:0}
}
.navbar-static-top {z-index:1000;border-width:0 0 1px}
@media (min-width: 768px) {.navbar-static-top {border-radius:0}
}
.navbar-fixed-top,.navbar-fixed-bottom {position:fixed;right:0;left:0;z-index:1030;-webkit-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}
@media (min-width: 768px) {.navbar-fixed-top,.navbar-fixed-bottom {border-radius:0}
}
.navbar-fixed-top {top:0;border-width:0 0 1px}
.navbar-fixed-bottom {bottom:0;margin-bottom:0;border-width:1px 0 0}
.navbar-brand {float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px;}
.navbar-brand:hover,.navbar-brand:focus {text-decoration:none}
@media (min-width: 768px) {.navbar > .container .navbar-brand,.navbar > .container-fluid .navbar-brand {margin-left:-15px}
}
.navbar-toggle {position:relative;float:right;padding:4px 10px 4px 10px;margin-top:10px;margin-right:10px;margin-bottom:6px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}
.navbar-toggle:focus {outline:0}
.navbar-toggle .icon-bar {display:block;width:22px;height:2px;border-radius:1px}
.navbar-toggle .icon-bar+.icon-bar {margin-top:4px}
@media (min-width: 768px) {.navbar-toggle {display:none}
}
.navbar-nav {margin:7.5px -15px}
.navbar-nav>li>a {padding-top:10px;padding-bottom:10px;line-height:20px}
@media (max-width: 767px) {.navbar-nav .open .dropdown-menu {position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none;}
.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header {padding:5px 15px 5px 25px}
.navbar-nav .open .dropdown-menu>li>a {line-height:20px}
.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus {background-image:none}
}
@media (min-width: 768px) {.navbar-nav {float:left;margin:0}
.navbar-nav>li {float:left}
.navbar-nav>li>a {padding-top:15px;padding-bottom:15px}
.navbar-nav.navbar-right:last-child {margin-right:-15px}
}
@media (min-width: 768px) {.navbar-left {float:left !important}
.navbar-right {float:right !important}
}
.navbar-form {padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}
@media (min-width: 768px) {.navbar-form .form-group {display:inline-block;margin-bottom:0;vertical-align:middle}
.navbar-form .form-control {display:inline-block;width:auto;vertical-align:middle}
.navbar-form .input-group {display:inline-table;vertical-align:middle}
.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn,.navbar-form .input-group .form-control {width:auto}
.navbar-form .input-group>.form-control {width:100%}
.navbar-form .control-label {margin-bottom:0;vertical-align:middle}
.navbar-form .radio,.navbar-form .checkbox {display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}
.navbar-form .radio label,.navbar-form .checkbox label {padding-left:0}
.navbar-form .radio input[type="radio"],.navbar-form .checkbox input[type="checkbox"] {position:relative;margin-left:0}
.navbar-form .has-feedback .form-control-feedback {top:0}
}
@media (max-width: 767px) {.navbar-form .form-group {margin-bottom:5px}
}
@media (min-width: 768px) {.navbar-form {width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}
.navbar-form.navbar-right:last-child {margin-right:-15px}
}
.navbar-nav>li>.dropdown-menu {margin-top:0;border-top-left-radius:0;border-top-right-radius:0}
.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu {border-bottom-right-radius:0;border-bottom-left-radius:0}
.navbar-btn {margin-top:8px;margin-bottom:8px}
.navbar-btn.btn-sm {margin-top:10px;margin-bottom:10px}
.navbar-btn.btn-xs {margin-top:14px;margin-bottom:14px}
.navbar-text {margin-top:15px;margin-bottom:15px}
@media (min-width: 768px) {.navbar-text {float:left;margin-right:15px;margin-left:15px}
.navbar-text.navbar-right:last-child {margin-right:0}
}
.navbar-default {background-color:#f8f8f8;border-color:#e7e7e7}
.navbar-default .navbar-brand {color:#777}
.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus {color:#5e5e5e;background-color:transparent}
.navbar-default .navbar-text {color:#777}
.navbar-default .navbar-nav>li>a {color:#777}
.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus {color:#333;background-color:transparent}
.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus {color:#555;background-color:#e7e7e7}
.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus {color:#ccc;background-color:transparent}
.navbar-default .navbar-toggle {border-color:#ddd}
.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus {background-color:#ddd}
.navbar-default .navbar-toggle .icon-bar {background-color:#888}
.navbar-default .navbar-collapse,.navbar-default .navbar-form {border-color:#e7e7e7}
.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus {color:#555;background-color:#e7e7e7}
@media (max-width: 767px) {.navbar-default .navbar-nav .open .dropdown-menu > li > a {color:#777}
.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus {color:#707070;background-color:transparent}
.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus {color:#555;background-color:#e7e7e7;}
.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus {color:#ccc;background-color:transparent}
}
.navbar-default .navbar-link {color:#777}
.navbar-default .navbar-link:hover {color:#333}
.navbar-default .btn-link {color:#777}
.navbar-default .btn-link:hover,.navbar-default .btn-link:focus {color:#333}
.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:hover,.navbar-default .btn-link[disabled]:focus,fieldset[disabled] .navbar-default .btn-link:focus {color:#ccc}
.navbar-inverse {background-color:#222;border-color:#080808}
.navbar-inverse .navbar-brand {color:#777}
.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus {color:#fff;background-color:transparent}
.navbar-inverse .navbar-text {color:#777}
.navbar-inverse .navbar-nav>li>a {color:#777}
.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus {color:#fff;background-color:transparent}
.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus {color:#fff;background-color:#080808}
.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus {color:#444;background-color:transparent}
.navbar-inverse .navbar-toggle {border-color:#333}
.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus {background-color:#333}
.navbar-inverse .navbar-toggle .icon-bar {background-color:#fff}
.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form {border-color:#101010}
.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus {color:#fff;background-color:#080808}
@media (max-width: 767px) {.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {border-color:#080808}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {background-color:#080808}
.navbar-inverse .navbar-nav .open .dropdown-menu>li>a {color:#777}
.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus {color:#fff;background-color:transparent}
.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus {color:#fff;background-color:#080808}
.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus {color:#444;background-color:transparent}
}
.navbar-inverse .navbar-link {color:#777}
.navbar-inverse .navbar-link:hover {color:#fff}
.navbar-inverse .btn-link {color:#777}
.navbar-inverse .btn-link:hover,.navbar-inverse .btn-link:focus {color:#fff}
.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:hover,.navbar-inverse .btn-link[disabled]:focus,fieldset[disabled] .navbar-inverse .btn-link:focus {color:#444}
@font-face {font-family:'icon';src:url('../fonts/icon.eot');src:url('../fonts/icon-.eot#iefix') format('embedded-opentype'),url('../fonts/icon.ttf') format('truetype'),url('../fonts/icon.woff') format('woff'),url('../fonts/icon.svg#icon') format('svg');font-weight:normal;font-style:normal}
.i {display:inline-block;font-family:'icon';font-style:normal;font-weight:normal;line-height:1;vertical-align:-5%;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
.i-move:before {content:"\e600"}
.i-move-vertical:before {content:"\e601"}
.i-resize-enlarge:before {content:"\e602"}
.i-resize-shrink:before {content:"\e603"}
.i-move-horizontal:before {content:"\e604"}
.i-download:before {content:"\e605"}
.i-upload:before {content:"\e606"}
.i-cloud-download:before {content:"\e607"}
.i-cloud-upload:before {content:"\e608"}
.i-circleleft:before {content:"\e609"}
.i-circledown:before {content:"\e60a"}
.i-circleup:before {content:"\e60b"}
.i-circleright:before {content:"\e60c"}
.i-home:before {content:"\e60d"}
.i-download3:before {content:"\e60e"}
.i-pin:before {content:"\e60f"}
.i-pictures:before {content:"\e610"}
.i-share3:before {content:"\e611"}
.i-pencil2:before {content:"\e612"}
.i-mail2:before {content:"\e613"}
.i-support:before {content:"\e614"}
.i-asc:before {content:"\e615"}
.i-dsc:before {content:"\e616"}
.i-ok:before {content:"\e617"}
.i-error:before {content:"\e618"}
.i-expand:before {content:"\e619"}
.i-collapse:before {content:"\e61a"}
.i-screen:before {content:"\e61b"}
.i-phone3:before {content:"\e61c"}
.i-phone-portrait:before {content:"\e61d"}
.i-phone-landscape:before {content:"\e61e"}
.i-tablet:before {content:"\e61f"}
.i-tablet-landscape:before {content:"\e620"}
.i-laptop:before {content:"\e621"}
.i-cube:before {content:"\e622"}
.i-chart:before {content:"\e623"}
.i-graph:before {content:"\e624"}
.i-meter:before {content:"\e625"}
.i-heart2:before {content:"\e626"}
.i-star2:before {content:"\e627"}
.i-stack:before {content:"\e628"}
.i-tv:before {content:"\e629"}
.i-user2:before {content:"\e62a"}
.i-users2:before {content:"\e62b"}
.i-search2:before {content:"\e62c"}
.i-zoom-in2:before {content:"\e62d"}
.i-zoom-out2:before {content:"\e62e"}
.i-slider-v:before {content:"\e62f"}
.i-slider:before {content:"\e630"}
.i-stats:before {content:"\e631"}
.i-bars:before {content:"\e632"}
.i-arrow-up-left2:before {content:"\e633"}
.i-arrow-up2:before {content:"\e634"}
.i-arrow-up-right2:before {content:"\e635"}
.i-arrow-right2:before {content:"\e636"}
.i-arrow-down-right2:before {content:"\e637"}
.i-arrow-down-2:before {content:"\e638"}
.i-arrow-down-left-2:before {content:"\e639"}
.i-arrow-left2:before {content:"\e63a"}
.i-file-pdf:before {content:"\e63b"}
.i-file-openoffice:before {content:"\e63c"}
.i-file-word:before {content:"\e63d"}
.i-file-excel:before {content:"\e63e"}
.i-file-zip:before {content:"\e63f"}
.i-file-powerpoint:before {content:"\e640"}
.i-file-xml:before {content:"\e641"}
.i-file-css:before {content:"\e642"}
.i-video:before {content:"\e643"}
.i-settings:before {content:"\e644"}
.i-camera:before {content:"\e645"}
.i-tag:before {content:"\e646"}
.i-bulb:before {content:"\e647"}
.i-location:before {content:"\e648"}
.i-eye2:before {content:"\e649"}
.i-bubble:before {content:"\e64a"}
.i-mail:before {content:"\e64b"}
.i-paperplane:before {content:"\e64c"}
.i-data:before {content:"\e64d"}
.i-t-shirt:before {content:"\e64e"}
.i-lab:before {content:"\e64f"}
.i-calendar:before {content:"\e650"}
.i-earth:before {content:"\e651"}
.i-world:before {content:"\e652"}
.i-vynil:before {content:"\e653"}
.i-gauge:before {content:"\e654"}
.i-statistics:before {content:"\e655"}
.i-arrow-left3:before {content:"\e656"}
.i-arrow-down3:before {content:"\e657"}
.i-arrow-up3:before {content:"\e658"}
.i-arrow-right3:before {content:"\e659"}
.i-arrow-left4:before {content:"\e65a"}
.i-arrow-down4:before {content:"\e65b"}
.i-arrow-up4:before {content:"\e65c"}
.i-arrow-right4:before {content:"\e65d"}
.i-arrow-left5:before {content:"\e65e"}
.i-arrow-down5:before {content:"\e65f"}
.i-arrow-up5:before {content:"\e660"}
.i-arrow-right5:before {content:"\e661"}
.i-search:before {content:"\e662"}
.i-list:before {content:"\e663"}
.i-add-to-list:before {content:"\e664"}
.i-list2:before {content:"\e665"}
.i-play:before {content:"\e666"}
.i-pause:before {content:"\e667"}
.i-stop:before {content:"\e668"}
.i-backward:before {content:"\e669"}
.i-forward:before {content:"\e66a"}
.i-feed:before {content:"\e66b"}
.i-switch:before {content:"\e66c"}
.i-clock2:before {content:"\e66d"}
.i-health:before {content:"\e66e"}
.i-pencil:before {content:"\e66f"}
.i-minus2:before {content:"\e670"}
.i-plus2:before {content:"\e671"}
.i-stats:before {content:"\e672"}
.i-paperclip:before {content:"\e673"}
.i-keyboard:before {content:"\e674"}
.i-mic:before {content:"\e675"}
.i-heart:before {content:"\e676"}
.i-layout3:before {content:"\e677"}
.i-layout2:before {content:"\e678"}
.i-cloud:before {content:"\e679"}
.i-info:before {content:"\e67a"}
.i-question:before {content:"\e67b"}
.i-notification:before {content:"\e67c"}
.i-libreoffice:before {content:"\e67d"}
.i-headphones:before {content:"\e67e"}
.i-copy2:before {content:"\e67f"}
.i-copy3:before {content:"\e680"}
.i-paste:before {content:"\e681"}
.i-spinner:before {content:"\e682"}
.i-plus:before {content:"\e683"}
.i-minus:before {content:"\e684"}
.i-cancel:before {content:"\e685"}
.i-images:before {content:"\e686"}
.i-logout:before {content:"\e687"}
.i-login:before {content:"\e688"}
.i-infinity:before {content:"\e689"}
.i-docs:before {content:"\e68a"}
.i-landscape:before {content:"\e68b"}
.i-portrait:before {content:"\e68c"}
.i-share:before {content:"\e68d"}
.i-youtube:before {content:"\e68e"}
.i-checkmark:before {content:"\e68f"}
.i-notice:before {content:"\e690"}
.i-link:before {content:"\e691"}
.i-link2:before {content:"\e692"}
.i-popup:before {content:"\e693"}
.i-publish:before {content:"\e694"}
.i-browser:before {content:"\e695"}
.i-checkmark2:before {content:"\e696"}
.i-cross2:before {content:"\e697"}
.i-question2:before {content:"\e698"}
.i-info2:before {content:"\e699"}
.i-loop:before {content:"\e69a"}
.i-retweet:before {content:"\e69b"}
.i-arrow:before {content:"\e69c"}
.i-arrow2:before {content:"\e69d"}
.i-shuffle:before {content:"\e69e"}
.i-ccw:before {content:"\e69f"}
.i-cycle:before {content:"\e6a0"}
.i-cw:before {content:"\e6a1"}
.i-switch:before {content:"\e6a2"}
.i-back:before {content:"\e6a3"}
.i-layout:before {content:"\e6a4"}
.i-code:before {content:"\e6a5"}
.i-vcard:before {content:"\e6a6"}
.i-googleplus:before {content:"\e6a7"}
.i-facebook:before {content:"\e6a8"}
.i-twitter:before {content:"\e6a9"}
.i-rss:before {content:"\e6aa"}
.i-signal:before {content:"\e6ab"}
.i-flow-tree:before {content:"\e6ac"}
.i-domain3:before {content:"\e6ad"}
.i-trashcan:before {content:"\e6ae"}
.i-book:before {content:"\e6af"}
.i-bars:before {content:"\e6b0"}
.i-stopwatch:before {content:"\e6b1"}
.i-map2:before {content:"\e6b2"}
.i-checkmark3:before {content:"\e6b3"}
.i-sun:before {content:"\e6b4"}
.i-clip:before {content:"\e6b5"}
.i-study:before {content:"\e6b6"}
.i-music:before {content:"\e6b7"}
.i-params:before {content:"\e6b8"}
.i-stack3:before {content:"\e6b9"}
.i-arrow-down:before {content:"\e6ba"}
.i-arrow-down-left:before {content:"\e6bb"}
.i-arrow-down-right:before {content:"\e6bc"}
.i-arrow-left:before {content:"\e6bd"}
.i-arrow-right:before {content:"\e6be"}
.i-arrow-up-right:before {content:"\e6bf"}
.i-arrow-up:before {content:"\e6c0"}
.i-arrow-up-left:before {content:"\e6c1"}
.i-compass:before {content:"\e6c2"}
.i-users3:before {content:"\e6c3"}
.i-user3:before {content:"\e6c4"}
.i-camera2:before {content:"\e6c5"}
.i-file:before {content:"\e6c6"}
.i-file2:before {content:"\e6c7"}
.i-file-plus:before {content:"\e6c8"}
.i-file-minus:before {content:"\e6c9"}
.i-file-check:before {content:"\e6ca"}
.i-file-remove:before {content:"\e6cb"}
.i-file-copy:before {content:"\e6cc"}
.i-stack2:before {content:"\e6cd"}
.i-folder:before {content:"\e6ce"}
.i-folder-upload:before {content:"\e6cf"}
.i-folder-download:before {content:"\e6d0"}
.i-folder-minus:before {content:"\e6d1"}
.i-folder-plus:before {content:"\e6d2"}
.i-folder2:before {content:"\e6d3"}
.i-folder-open:before {content:"\e6d4"}
.i-tag2:before {content:"\e6d5"}
.i-cart:before {content:"\e6d6"}
.i-phone:before {content:"\e6d7"}
.i-phone2:before {content:"\e6d8"}
.i-local:before {content:"\e6d9"}
.i-alarm:before {content:"\e6da"}
.i-clock:before {content:"\e6db"}
.i-history:before {content:"\e6dc"}
.i-stopclock:before {content:"\e6dd"}
.i-rotate:before {content:"\e6de"}
.i-rotate2:before {content:"\e6df"}
.i-redo:before {content:"\e6e0"}
.i-undo:before {content:"\e6e1"}
.i-chat2:before {content:"\e6e2"}
.i-chat3:before {content:"\e6e3"}
.i-chat:before {content:"\e6e4"}
.i-data2:before {content:"\e6e5"}
.i-spin:before {content:"\e6e6"}
.i-health2:before {content:"\e6e7"}
.i-cog2:before {content:"\e6e8"}
.i-bulb:before {content:"\e6e9"}
.i-rating:before {content:"\e6ea"}
.i-rating2:before {content:"\e6eb"}
.i-rating3:before {content:"\e6ec"}
.i-grid:before {content:"\e6ed"}
.i-grid2:before {content:"\e6ee"}
.i-grid3:before {content:"\e6ef"}
.i-ellipsis:before {content:"\e6f0"}
.i-dot:before {content:"\e6f1"}
.i-dots:before {content:"\e6f2"}
.i-bar:before {content:"\e6f3"}
.i-bar2:before {content:"\e6f4"}
.i-bars3:before {content:"\e6f5"}
.i-menu:before {content:"\e6f6"}
.i-menu2:before {content:"\e6f7"}
.i-download2:before {content:"\e6f8"}
.i-upload2:before {content:"\e6f9"}
.i-eye:before {content:"\e6fa"}
.i-eye-slash:before {content:"\e6fb"}
.i-bookmark:before {content:"\e6fc"}
.i-up:before {content:"\e6fd"}
.i-right:before {content:"\e6fe"}
.i-down:before {content:"\e6ff"}
.i-left:before {content:"\e700"}
.i-check:before {content:"\e701"}
.i-checked:before {content:"\e702"}
.i-popout:before {content:"\e703"}
.i-newtab:before {content:"\e704"}
.i-map:before {content:"\e705"}
.i-layer:before {content:"\e706"}
.i-layer2:before {content:"\e707"}
.i-like:before {content:"\e708"}
.i-dislike:before {content:"\e709"}
.i-football:before {content:"\e70a"}
.i-hexagon-o:before {content:"\e70b"}
.i-hexagon:before {content:"\e70c"}
.i-hexagon2-o:before {content:"\e70d"}
.i-hexagon2:before {content:"\e70e"}
.i-circle:before {content:"\e70f"}
.i-circle-o:before {content:"\e711"}
.i-circle-sm:before {content:"\e710"}
.i-circle-sm-o:before {content:"\e712"}
@font-face {font-family:'Open Sans';font-style:normal;font-weight:300;src:local('Open Sans Light'),local('OpenSans-Light'),url('../fonts/opensans/opensans-light.woff') format('woff')}
@font-face {font-family:'Open Sans';font-style:normal;font-weight:400;src:local('Open Sans'),local('OpenSans'),url('../fonts/opensans/opensans.woff') format('woff')}
@font-face {font-family:'Open Sans';font-style:normal;font-weight:700;src:local('Open Sans Bold'),local('OpenSans-Bold'),url('../fonts/opensans/opensans-bold.woff') format('woff')}
html {}
body {font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif;color:#788288;background-color:transparent;-webkit-font-smoothing:antialiased;line-height:1.53846154}
*:focus {outline:0 !important}
.h1,.h2,.h3,.h4,.h5,.h6 {margin:0}
a {color:#3c4144;text-decoration:none}
a:hover,a:focus {color:#181a1c;text-decoration:none}
label {font-weight:normal}
small,.small {font-size:12px}
.badge,.label {font-weight:bold}
.badge {background-color:#b0bcd4}
.badge.up {position:relative;top:-10px;padding:3px 6px;margin-left:-10px}
.badge-sm {font-size:85%;padding:2px 5px !important}
.label-sm {padding-top:0;padding-bottom:0}
.badge-white {background-color:transparent;border:1px solid rgba(255,255,255,0.35);padding:2px 6px}
.badge-empty {background-color:transparent;border:1px solid rgba(0,0,0,0.15);color:inherit}
.caret-white {border-top-color:#fff;border-top-color:rgba(255,255,255,0.65)}
a:hover .caret-white {border-top-color:#fff}
.thumbnail {border-color:#eaeef1}
.popover-content {font-size:12px;line-height:1.5}
.progress-xs {height:6px}
.progress-sm {height:10px}
.progress-sm .progress-bar {font-size:10px;line-height:1em}
.progress,.progress-bar {-webkit-box-shadow:none;box-shadow:none}
.breadcrumb {background-color:#fff;border:1px solid #eaeef1;padding-left:10px;margin-bottom:10px}
.breadcrumb>li+li:before,.breadcrumb>.active {color:inherit}
.accordion-group,.accordion-inner {border-color:#eaeef1;border-radius:2px}
.alert {font-size:12px;box-shadow:inset 0 1px 0 rgba(255,255,255,0.2)}
.alert .close i {font-size:12px;font-weight:normal;display:block}
.form-control {border-color:#CCCCCC;border-radius:2px}
.form-control,.form-control:focus {-webkit-box-shadow:none;box-shadow:none}
.form-control:focus {border-color:#b8b8b8}
.input-s-sm {width:120px}
.input-s {width:200px}
.input-s-lg {width:250px}
.input-lg {height:45px}
.input-group-addon {border-color:#cbd5dd;background-color:#fcfcfd}
.list-group {border-radius:2px}
.list-group.no-radius .list-group-item {border-radius:0 !important}
.list-group.no-borders .list-group-item {border:none}
.list-group.no-border .list-group-item {border-width:1px 0}
.list-group.no-bg .list-group-item {background-color:transparent}
.list-group-item {border-color:#eaeef1;padding-right:15px}
a.list-group-item:hover,a.list-group-item:focus {background-color:#f9fafc}
.list-group-item.media {margin-top:0}
.list-group-item.active {color:#fff;border-color:#1ccacc !important;background-color:#1ccacc !important}
.list-group-item.active .text-muted {color:#91eff0}
.list-group-item.active a {color:#fff}
.list-group-alt .list-group-item:nth-child(2n+2) {background-color:rgba(0,0,0,0.02) !important}
.list-group-lg .list-group-item {padding-top:15px;padding-bottom:15px}
.list-group-sp .list-group-item {margin-bottom:5px;border-radius:3px}
.list-group-item>.badge {margin-right:0}
.list-group-item>.fa-chevron-right {float:right;margin-top:4px;margin-right:-5px}
.list-group-item>.fa-chevron-right+.badge {margin-right:5px}
.nav-pills.no-radius>li>a {border-radius:0}
.nav-pills>li.active>a {color:#fff !important;background-color:#1ccacc}
.nav>li>a:hover,.nav>li>a:focus {background-color:#f7f8fb}
.nav.nav-sm>li>a {padding:6px 8px}
.nav .avatar {width:30px;margin-top:-5px;margin-right:5px}
.nav .open>a,.nav .open>a:hover,.nav .open>a:focus {background-color:#f7f8fb}
.nav-tabs {border-color:#eaeef1}
.nav-tabs>li>a {border-radius:2px 2px 0 0;border-bottom-color:#eaeef1 !important}
.nav-tabs>li.active>a {border-color:#eaeef1 !important;border-bottom-color:#fff !important;border-right-color:#CCC !important;}
.pagination>li>a {border-color:#eaeef1}
.pagination>li>a:hover,.pagination>li>a:focus {border-color:#eaeef1;background-color:#f2f4f8}
.panel {border-radius:2px}
.panel.panel-default {border-color:#eaeef1}
.panel.panel-default>.panel-heading,.panel.panel-default>.panel-footer {border-color:#eaeef1}
.panel>.list-group .list-group-item:first-child {border-top:0}
.panel .list-group-item {border-color:#f3f5f7}
.panel.no-borders {border-width:0}
.panel.no-borders .panel-heading,.panel.no-borders .panel-footer {border-width:0}
.panel .table td,.panel .table th {padding:8px 15px;border-top:1px solid #eaeef1}
.panel .table thead>tr>th {border-bottom:1px solid #eaeef1}
.panel .table-striped>tbody>tr:nth-child(odd)>td,.panel .table-striped>tbody>tr:nth-child(odd)>th {background-color:#f9fafc}
.panel .table-striped>thead th {background-color:#f9fafc;border-right:1px solid #eaeef1}
.panel .table-striped>thead th:last-child {border-right:none}
.panel-heading {border-radius:2px 2px 0 0}
.panel-default .panel-heading {background-color:#f9fafc}
.panel-heading.no-border {margin:-1px -1px 0 -1px;border:none}
.panel-heading .nav {margin:-10px -15px}
.panel-heading .nav-tabs {margin:-11px -16px}
.panel-heading .nav-tabs.nav-justified {width:auto}
.panel-heading .nav-tabs>li>a {margin:0;padding-top:11px;padding-bottom:11px}
.panel-heading .list-group {background:transparent}
.panel-footer {border-color:#eaeef1;border-radius:0 0 2px 2px;background-color:#f9fafc}
.panel-group .panel-heading+.panel-collapse .panel-body {border-top:1px solid #eaedef}
.open {z-index:1050;position:relative}
.dropdown-menu {font-size:13px;border-radius:2px;-webkit-box-shadow:0 2px 6px rgba(0,0,0,0.1);box-shadow:0 2px 6px rgba(0,0,0,0.1);border:1px solid #ddd;border:1px solid rgba(0,0,0,0.1)}
.dropdown-menu.pull-left {left:100%}
.dropdown-menu>.panel {border:none;margin:-5px 0}
.dropdown-menu>li>a {padding:5px 15px;color:#707070;}
.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus {background-image:none;filter:none;background-color:#eeeeee !important;color:#333333;text-shadow:#FFFFFF 0 1px 0;}
.dropdown-menu>li.nb>a {cursor:default !important;}
.dropdown-menu>li.nb>a:hover {background-color:transparent !important;color:#707070 !important;}
.dropdown-header {padding:5px 15px}
.dropdown-submenu {position:relative}
.dropdown-submenu:hover>a,.dropdown-submenu:focus>a {background-color:#f2f4f8 !important;color:#788288}
.dropdown-submenu:hover>.dropdown-menu,.dropdown-submenu:focus>.dropdown-menu {display:block}
.dropdown-submenu.pull-left {float:none !important}
.dropdown-submenu.pull-left>.dropdown-menu {left:-100%;margin-left:10px}
.dropdown-submenu .dropdown-menu {left:100%;top:0;margin-top:-6px;margin-left:-1px}
.dropup .dropdown-submenu>.dropdown-menu {top:auto;bottom:0}
.dropdown-select>li>a input {position:absolute;left:-9999em}
.icon-muted {color:#ccc}
.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form {border-color:transparent}
.navbar-fixed-top,.navbar-fixed-bottom {position:fixed !important}
.navbar-fixed-top+* {padding-top:50px}
.navbar-fixed-top.header-md+* {padding-top:60px}
.header,.footer {min-height:50px;padding:0 15px}
.header>p,.footer>p {margin-top:15px;display:inline-block}
.header>.btn,.header>.btn-group,.header>.btn-toolbar,.footer>.btn,.footer>.btn-group,.footer>.btn-toolbar {margin-top:10px}
.header>.btn-lg,.footer>.btn-lg {margin-top:0}
.header .nav-tabs,.footer .nav-tabs {border:none;margin-left:-15px;margin-right:-15px}
.header .nav-tabs>li a,.footer .nav-tabs>li a {border:none !important;border-radius:0;padding-top:15px;padding-bottom:15px;line-height:20px}
.header .nav-tabs>li a:hover,.header .nav-tabs>li a:focus,.footer .nav-tabs>li a:hover,.footer .nav-tabs>li a:focus {background-color:transparent}
.header .nav-tabs>li.active a,.footer .nav-tabs>li.active a {color:#788288}
.header .nav-tabs>li.active a,.header .nav-tabs>li.active a:hover,.footer .nav-tabs>li.active a,.footer .nav-tabs>li.active a:hover {background-color:#f2f4f8}
.header .nav-tabs.nav-white>li.active a,.header .nav-tabs.nav-white>li.active a:hover,.footer .nav-tabs.nav-white>li.active a,.footer .nav-tabs.nav-white>li.active a:hover {background-color:#fff}
.header.navbar,.footer.navbar {border-radius:0;border:none;margin-bottom:0;padding:0;position:relative;z-index:1000}
body.container {padding:0}
@media (orientation: landscape) {html.ios7.ipad > body {padding-bottom:20px}
}
.navbar-header {position:relative}
.navbar-header>.btn {position:absolute;font-size:1.3em;padding:9px 16px;line-height:30px;left:0}
.navbar-header .navbar-brand+.btn {right:0;top:0;left:auto}
.navbar-brand {float:none;text-align:center;font-size:18px;font-weight:300;height:auto;line-height:50px;display:inline-block;padding:0 15px}
.navbar-brand:hover {text-decoration:none}
.navbar-brand img {max-height:20px;margin-top:-4px;vertical-align:middle}
.nav-primary li>a>i {margin:-8px -10px;line-height:36px;width:36px;float:left;margin-right:5px;text-align:center;position:relative;overflow:hidden}
.nav-primary li>a>i:before {position:relative;z-index:2}
.nav-primary ul.nav>li>a {padding:8px 15px;position:relative;-webkit-transition:background-color .2s ease-in-out 0s;transition:background-color .2s ease-in-out 0s}
.no-borders .nav-primary ul.nav>li>a {border-width:0 !important}
.nav-primary ul.nav>li>a>.badge {font-size:11px;padding:2px 5px 2px 4px;margin-top:2px}
.nav-primary ul.nav>li>a>.text-muted {margin:0 3px}
.nav-primary ul.nav>li>a.active .text {display:none}
.nav-primary ul.nav>li>a.active .text-active {display:inline-block !important}
.nav-primary ul.nav>li li a {font-weight:normal;text-transform:none;padding:5px 0 5px 45px;}
.nav-primary ul.nav>li.active>ul {display:block}
.nav-primary ul.nav ul {display:none}
.bg-black .nav-primary>ul.nav-main>li:hover>a,.bg-black .nav-primary>ul.nav-main>li:focus>a,.bg-black .nav-primary>ul.nav-main>li:active>a,.bg-black .nav-primary>ul.nav-main>li.active>a {background-color:#1aae88}
.nav-main li.active {background:#F2F4F8;}
@media (min-width: 768px) {.visible-nav-xs {display:none}
.nav-xs {width:70px}
.nav-xs .slimScrollDiv,.nav-xs .slim-scroll {overflow:visible !important}
.nav-xs .slimScrollBar,.nav-xs .slimScrollRail {display:none !important}
.nav-xs .scrollable {overflow:visible}
.nav-xs .nav-primary>ul>li>a {position:relative;padding:0;font-size:11px;text-align:center;height:50px;overflow-y:hidden;border:none}
.nav-xs .nav-primary>ul>li>a span {display:table-cell;vertical-align:middle;height:50px;width:70px;}
.nav-xs .nav-primary>ul>li>a span.pull-right {display:none !important}
.nav-xs .nav-primary>ul>li>a i {width:auto;float:none;display:block;font-size:16px;margin:0;line-height:50px;border:none !important;-webkit-transition:margin-top 0.2s;transition:margin-top 0.2s}
.nav-xs .nav-primary>ul>li>a i b {left:0 !important}
.nav-xs .nav-primary>ul>li>a .badge {position:absolute;right:10px;top:4px;z-index:3}
.nav-xs .nav-primary>ul>li:hover>a i,.nav-xs .nav-primary>ul>li:focus>a i,.nav-xs .nav-primary>ul>li:active>a i,.nav-xs .nav-primary>ul>li.active>a i {margin-top:-50px}
.nav-xs .nav-primary>ul ul {display:none !important;position:absolute;left:100%;top:0;z-index:1050;width:220px;-webkit-box-shadow:0 2px 6px rgba(0,0,0,0.1);box-shadow:0 2px 6px rgba(0,0,0,0.1);padding:5px 0 5px 0;}
.nav-xs .nav-primary>ul ul li a{padding:5px 0 5px 25px;}
.nav-xs .nav-primary li:hover>ul,.nav-xs .nav-primary li:focus>ul,.nav-xs .nav-primary li:active>ul {display:block !important}
.nav-xs.nav-xs-right .nav-primary>ul ul {left:auto;right:100%}
.nav-xs>.vbox>.header,.nav-xs>.vbox>.footer {padding:0 20px}
.nav-xs .hidden-nav-xs {display:none}
.nav-xs .visible-nav-xs {display:inherit}
.nav-xs .text-center-nav-xs {text-align:center}
.nav-xs .nav-user {padding-left:0;padding-right:0}
.nav-xs .nav-user .avatar {float:none !important;margin-right:0}
.nav-xs .nav-user .dropdown>a {display:block;text-align:center}
.nav-xs .navbar-header {float:none}
.nav-xs .navbar-brand {display:block;padding:0}
.nav-xs .navbar-brand img {margin-right:0}
.nav-xs .navbar {padding:0}
.header-md .navbar-brand {line-height:60px}
.header-md .navbar-brand img {max-height:30px}
.header-md .navbar-nav>li>a {padding:20px}
}
@media (max-width: 767px) {.navbar-fixed-top-xs {position:fixed !important;left:0;width:100%;z-index:1100}
.navbar-fixed-top-xs+* {padding-top:50px !important}
.nav-bar-fixed-bottom {position:fixed;left:0;bottom:0;width:100%;z-index:1100}
html,body {overflow-x:hidden;min-height:100%}
.open,.open body {height:100%}
.nav-primary .dropdown-menu {position:relative;float:none;left:0;margin-left:0;padding:0}
.nav-primary .dropdown-menu a {padding:15px;border-bottom:1px solid #eee}
.nav-primary .dropdown-menu li:last-child a {border-bottom:none}
.navbar-header {text-align:center}
.nav-user {margin:0;padding:15px}
.nav-user.open {display:inherit !important}
.nav-user .dropdown-menu {display:block;position:static;float:none}
.nav-user .dropdown>a {display:block;text-align:center;font-size:18px;padding-bottom:10px}
.nav-user .avatar {width:160px !important;float:none !important;display:block;margin:20px auto;padding:5px;background-color:rgba(255,255,255,0.1);position:relative}
.nav-user .avatar:before {content:"";position:absolute;left:5px;right:5px;bottom:5px;top:5px;border:4px solid #fff;border-radius:500px}
.nav-off-screen {display:block !important;position:absolute;left:0;top:0;bottom:0;width:75%;visibility:visible;overflow-x:hidden;overflow-y:auto;-webkit-overflow-scrolling:touch}
.nav-off-screen .nav-primary {display:block !important}
.nav-off-screen .navbar-fixed-top-xs {width:75%}
.nav-off-screen.push-right .navbar-fixed-top-xs {left:25%}
.nav-off-screen.push-right {left:auto;right:0}
.nav-off-screen.push-right+* {-webkit-transform:translate3d(-75%,0px,0px);transform:translate3d(-75%,0px,0px)}
.nav-off-screen+* {background-color:#f2f4f8;-webkit-transition:-webkit-transform 0.2s ease-in-out;-moz-transition:-moz-transform 0.2s ease-in-out;-o-transition:-o-transform 0.2s ease-in-out;transition:transform 0.2s ease-in-out;-webkit-transition-delay:0s;transition-delay:0s;-webkit-transform:translate3d(0px,0px,0px);transform:translate3d(0px,0px,0px);-webkit-backface-visibility:hidden;-moz-backface-visibility:hidden;backface-visibility:hidden;-webkit-transform:translate3d(75%,0px,0px);transform:translate3d(75%,0px,0px);overflow:hidden;position:absolute;width:100%;top:0px;bottom:0;left:0;right:0;z-index:2}
.nav-off-screen+* .nav-off-screen-block {display:block !important;position:absolute;left:0;right:0;top:0;bottom:0;z-index:1950}
.navbar+section .nav-off-screen {top:50px}
.navbar+section .nav-off-screen+* {top:50px}
.slimScrollDiv,.slim-scroll {overflow:visible !important;height:auto !important}
.slimScrollBar,.slimScrollRail {display:none !important}
}
.arrow {border-width:8px;z-index:10}
.arrow,.arrow:after {position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}
.arrow:after {border-width:7px;content:""}
.arrow.top {left:50%;margin-left:-8px;border-top-width:0;border-bottom-color:#eee;border-bottom-color:rgba(0,0,0,0.1);top:-8px}
.arrow.top:after {content:" ";top:1px;margin-left:-7px;border-top-width:0;border-bottom-color:#fff}
.arrow.right {top:50%;right:-8px;margin-top:-8px;border-right-width:0;border-left-color:#eee;border-left-color:rgba(0,0,0,0.1)}
.arrow.right:after {content:" ";right:1px;border-right-width:0;border-left-color:#fff;bottom:-7px}
.arrow.bottom {left:50%;margin-left:-8px;border-bottom-width:0;border-top-color:#eee;border-top-color:rgba(0,0,0,0.1);bottom:-8px}
.arrow.bottom:after {content:" ";bottom:1px;margin-left:-7px;border-bottom-width:0;border-top-color:#fff}
.arrow.left {top:50%;left:-8px;margin-top:-8px;border-left-width:0;border-right-color:#eee;border-right-color:rgba(0,0,0,0.1)}
.arrow.left:after {content:" ";left:1px;border-left-width:0;border-right-color:#fff;bottom:-7px}
.btn-link {color:#788288}
.btn-link.active {webkit-box-shadow:none;box-shadow:none}
.btn-default {color:#9b9b9b !important;background-color:#fcfcfd;border-color:#CCCCCC;border-bottom-color:#cbd5dd;-webkit-box-shadow:0 1px 1px rgba(90,90,90,0.1);box-shadow:0 1px 1px rgba(90,90,90,0.1)}
.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default {color:#707070 !important;background-color:#eeeeee;border-color:#cccdce}
.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default {background-image:none}
.btn-default.disabled,.btn-default.disabled:hover,.btn-default.disabled:focus,.btn-default.disabled:active,.btn-default.disabled.active,.btn-default[disabled],.btn-default[disabled]:hover,.btn-default[disabled]:focus,.btn-default[disabled]:active,.btn-default[disabled].active,fieldset[disabled] .btn-default,fieldset[disabled] .btn-default:hover,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:active,fieldset[disabled] .btn-default.active {background-color:#fcfcfd;border-color:#d2dae1}
.btn-default.btn-bg {border-color:rgba(0,0,0,0.1);background-clip:padding-box}
.btn-primary {color:#fff !important;background-color:#177bbb;border-color:#177bbb}
.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary {color:#fff !important;background-color:#146ca4;border-color:#136397}
.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary {background-image:none}
.btn-primary.disabled,.btn-primary.disabled:hover,.btn-primary.disabled:focus,.btn-primary.disabled:active,.btn-primary.disabled.active,.btn-primary[disabled],.btn-primary[disabled]:hover,.btn-primary[disabled]:focus,.btn-primary[disabled]:active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary:hover,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary.active {background-color:#177bbb;border-color:#177bbb}
.btn-success {color:#fff !important;background-color:#1aae88;border-color:#1aae88}
.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success {color:#fff !important;background-color:#179877;border-color:#158b6c}
.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success {background-image:none}
.btn-success.disabled,.btn-success.disabled:hover,.btn-success.disabled:focus,.btn-success.disabled:active,.btn-success.disabled.active,.btn-success[disabled],.btn-success[disabled]:hover,.btn-success[disabled]:focus,.btn-success[disabled]:active,.btn-success[disabled].active,fieldset[disabled] .btn-success,fieldset[disabled] .btn-success:hover,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:active,fieldset[disabled] .btn-success.active {background-color:#1aae88;border-color:#1aae88}
.btn-info {color:#fff !important;background-color:#1ccacc;border-color:#1ccacc}
.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info {color:#fff !important;background-color:#19b4b6;border-color:#17a6a8}
.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info {background-image:none}
.btn-info.disabled,.btn-info.disabled:hover,.btn-info.disabled:focus,.btn-info.disabled:active,.btn-info.disabled.active,.btn-info[disabled],.btn-info[disabled]:hover,.btn-info[disabled]:focus,.btn-info[disabled]:active,.btn-info[disabled].active,fieldset[disabled] .btn-info,fieldset[disabled] .btn-info:hover,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:active,fieldset[disabled] .btn-info.active {background-color:#1ccacc;border-color:#1ccacc}
.btn-warning {color:#fff !important;background-color:#fcc633;border-color:#fcc633}
.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning {color:#fff !important;background-color:#fcbf1a;border-color:#fbbb0b}
.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning {background-image:none}
.btn-warning.disabled,.btn-warning.disabled:hover,.btn-warning.disabled:focus,.btn-warning.disabled:active,.btn-warning.disabled.active,.btn-warning[disabled],.btn-warning[disabled]:hover,.btn-warning[disabled]:focus,.btn-warning[disabled]:active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning,fieldset[disabled] .btn-warning:hover,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:active,fieldset[disabled] .btn-warning.active {background-color:#fcc633;border-color:#fcc633}
.btn-danger {color:#fff !important;background-color:#e33244;border-color:#e33244}
.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger {color:#fff !important;background-color:#dd1e32;border-color:#d01c2f}
.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger {background-image:none}
.btn-danger.disabled,.btn-danger.disabled:hover,.btn-danger.disabled:focus,.btn-danger.disabled:active,.btn-danger.disabled.active,.btn-danger[disabled],.btn-danger[disabled]:hover,.btn-danger[disabled]:focus,.btn-danger[disabled]:active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger,fieldset[disabled] .btn-danger:hover,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:active,fieldset[disabled] .btn-danger.active {background-color:#e33244;border-color:#e33244}
.btn-dark {color:#fff !important;background-color:#222733;border-color:#222733}
.btn-dark:hover,.btn-dark:focus,.btn-dark:active,.btn-dark.active,.open .dropdown-toggle.btn-dark {color:#fff !important;background-color:#181b24;border-color:#12141b}
.btn-dark:active,.btn-dark.active,.open .dropdown-toggle.btn-dark {background-image:none}
.btn-dark.disabled,.btn-dark.disabled:hover,.btn-dark.disabled:focus,.btn-dark.disabled:active,.btn-dark.disabled.active,.btn-dark[disabled],.btn-dark[disabled]:hover,.btn-dark[disabled]:focus,.btn-dark[disabled]:active,.btn-dark[disabled].active,fieldset[disabled] .btn-dark,fieldset[disabled] .btn-dark:hover,fieldset[disabled] .btn-dark:focus,fieldset[disabled] .btn-dark:active,fieldset[disabled] .btn-dark.active {background-color:#222733;border-color:#222733}
.btn {font-weight:500;border-radius:2px}
.btn-icon {padding-left:0 !important;padding-right:0 !important;width:34px;text-align:center}
.btn-icon.b-2x {width:36px}
.btn-icon.btn-sm {width:30px}
.btn-icon.btn-sm.b-2x {width:32px}
.btn-icon.btn-lg {width:45px}
.btn-icon.btn-lg.b-2x {width:47px}
.btn-group-justified {border-collapse:separate}
.btn-rounded {border-radius:50px;padding-left:15px;padding-right:15px}
.btn-rounded.btn-lg {padding-left:25px;padding-right:25px}
.btn>i.pull-left,.btn>i.pull-right {line-height:1.428571429}
.btn-block {padding-left:12px;padding-right:12px}
.btn-group-vertical>.btn:first-child:not(:last-child) {border-top-right-radius:2px}
.btn-group-vertical>.btn:last-child:not(:first-child) {border-bottom-left-radius:2px}
.btn-inactive {-webkit-box-shadow:none !important;box-shadow:none !important}
.i-fw {width:1.2857142857143em;text-align:center}
.i-lg {font-size:1.3333333333333em;line-height:0.75em;vertical-align:-15%}
.i-sm {font-size:0.75em}
.i-1x {font-size:1em}
.i-2x {font-size:2em}
.i-3x {font-size:3em}
.i-4x {font-size:4em}
.i-5x {font-size:5em}
.i-s {position:relative;display:inline-block;vertical-align:middle}
.i-s>i {position:absolute;left:0;width:100%;text-align:center;line-height:inherit}
.i-s-2x {width:2em;height:2em;font-size:2em;line-height:2em}
.i-s-2x .i-s-base {font-size:2em}
.i-s-3x {width:2.5em;height:2.5em;font-size:2.5em;line-height:2.5em}
.i-s-3x .i-s-base {font-size:2.5em}
.i-s-4x {width:3em;height:3em;font-size:3em;line-height:3em}
.i-s-4x .i-s-base {font-size:3em}
.i-s-5x {width:3.5em;height:3.5em;font-size:3.5em;line-height:3.5em}
.i-s-5x .i-s-base {font-size:3.5em}
.bg-light {background-color:#f2f4f8;color:#788288}
.bg-light.lt,.bg-light .lt {background-color:#f7f8fb}
.bg-light.lter,.bg-light .lter {background-color:#fcfcfd}
.bg-light.dk,.bg-light .dk {background-color:#e9edf4}
.bg-light.dker,.bg-light .dker {background-color:#e0e6f0}
.bg-light.bg,.bg-light .bg {background-color:#f2f4f8}
.bg-white {background-color:#fff;color:#788288}
.bg-white a {color:#3c4144}
.bg-white a:hover {color:#242729}
.bg-white.dk,.bg-white .dk {background-color:#FFF}
.bg-white.dker,.bg-white .dker {background-color:#FFF}
.bg-white .text-muted {color:#a1a8ac !important}
.bg-white-only {background-color:#fff}
.bg-empty {background-color:transparent}
.padd{padding:15px;}
.padder {padding-left:15px;padding-right:15px}
.padder-v {padding-top:15px;padding-bottom:15px}
.no-padder {padding:0 !important}
.mb{margin-bottom:10px;}
.tab-pane > .well{border-radius:0;background:#FFFFFF;box-shadow:none;}
.range {
display: table;
position: relative;
height: 20px !important;
width:160px;
margin:0 10px 10px 10px;
background-color: rgb(245, 245, 245);
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
cursor: pointer;
}
.range input[type="range"] {
-webkit-appearance: none !important;
-moz-appearance: none !important;
-ms-appearance: none !important;
-o-appearance: none !important;
appearance: none !important;
display: table-cell;
width: 100%;
background-color: transparent;
height: 20px !important;
cursor: pointer;
}
.range input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none !important;
-moz-appearance: none !important;
-ms-appearance: none !important;
-o-appearance: none !important;
appearance: none !important;
width: 10px;
height: 20px !important;
color: rgb(255, 255, 255);
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: 0px;
background-color: #D0D0D0;
}
.range input[type="range"]::-moz-slider-thumb {
-webkit-appearance: none !important;
-moz-appearance: none !important;
-ms-appearance: none !important;
-o-appearance: none !important;
appearance: none !important;
width: 11px;
height: 20px;
color: rgb(255, 255, 255);
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: 0px;
background-color: #D0D0D0;
}
.range output {
display: table-cell;
padding: 3px 5px 2px;
min-width: 40px;
color: rgb(255, 255, 255);
background-color: #B0B0B0;
text-align: center;
text-decoration: none;
border-radius: 4px;
border-bottom-left-radius: 0;
border-top-left-radius: 0;
width: 1%;
white-space: nowrap;
vertical-align: middle;
line-height: .9;
font-size:.85em;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
-ms-transition: all 0.5s ease;
transition: all 0.5s ease;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: -moz-none;
-o-user-select: none;
user-select: none;
}
.range input[type="range"] {
outline: none;
}
.range.range-primary input[type="range"]::-webkit-slider-thumb {
background-color: #A5A5A5;
}
.range.range-primary input[type="range"]::-moz-slider-thumb {
background-color: #A5A5A5;
}
.range.range-primary output {
background-color: rgb(66, 139, 202);
}
.range.range-primary input[type="range"] {
outline-color: rgb(66, 139, 202);
}
.range.range-success input[type="range"]::-webkit-slider-thumb {
background-color: rgb(92, 184, 92);
}
.range.range-success input[type="range"]::-moz-slider-thumb {
background-color: rgb(92, 184, 92);
}
.range.range-success output {
background-color: rgb(92, 184, 92);
}
.range.range-success input[type="range"] {
outline-color: rgb(92, 184, 92);
}
.range.range-info input[type="range"]::-webkit-slider-thumb {
background-color: rgb(91, 192, 222);
}
.range.range-info input[type="range"]::-moz-slider-thumb {
background-color: rgb(91, 192, 222);
}
.range.range-info output {
background-color: rgb(91, 192, 222);
}
.range.range-info input[type="range"] {
outline-color: rgb(91, 192, 222);
}
.range.range-warning input[type="range"]::-webkit-slider-thumb {
background-color: rgb(240, 173, 78);
}
.range.range-warning input[type="range"]::-moz-slider-thumb {
background-color: rgb(240, 173, 78);
}
.range.range-warning output {
background-color: rgb(240, 173, 78);
}
.range.range-warning input[type="range"] {
outline-color: rgb(240, 173, 78);
}
.range.range-danger input[type="range"]::-webkit-slider-thumb {
background-color: rgb(217, 83, 79);
}
.range.range-danger input[type="range"]::-moz-slider-thumb {
background-color: rgb(217, 83, 79);
}
.range.range-danger output {
background-color: rgb(217, 83, 79);
}
.range.range-danger input[type="range"] {
outline-color: rgb(217, 83, 79);
}
<|start_filename|>mapmint-ui/js/Mapmanager.js<|end_filename|>
var map;
function toggleControl(element) {
for(key in Mapmanager.mapControls) {
var control = Mapmanager.mapControls[key];
if(element.name == key){
control.activate();
} else {
control.deactivate();
}
}
};
function handleMeasurements(event) {
var geometry = event.geometry;
var units = event.units;
var order = event.order;
var measure = event.measure;
var lonlat = geometry.getBounds().getCenterLonLat();
var pixels= this.map.getPixelFromLonLat(new OpenLayers.LonLat(lonlat.lon, lonlat.lat));
var out = "";
if(order == 1) {
var element = document.getElementById('output-lenght');
out += "" + measure.toFixed(3) + " " + units;
$(".dialog-lenght").dialog({
autoOpen: false,
height: 52,
width: 200,
position: [pixels.x,pixels.y],
resizable: false,
close: function(event, ui) {}
});
$(".dialog-lenght").dialog("open");
} else {
var element = document.getElementById('output-area');
out += "" + measure.toFixed(3) + " " + units + "<sup>2</sup>";
$(".dialog-area").dialog({
autoOpen: false,
height: 52,
width: 210,
position: [pixels.x,pixels.y],
resizable: false
});
$(".dialog-area").dialog("open");
}
element.innerHTML = out;
}
Mapmanager=MLayout.extend();
Mapmanager.define({
mapControls: null,
map: null,
initialize: function(){
System.loaded=false;
System.libpath="openlayers/";
System.require("OpenLayers");
System.start=this.loadOL.mbind(this);
System.ensure_included();
},
updateSize: function(){
if(this.map){
var center = this.map.getCenter();
this.map.updateSize();
this.map.setCenter(center);
}
},
loadOL: function(){
$('.pan, .zoombox, .zoommaxextent, .identify, .measure-dist, .measure-area').button({text: false});
var extent = new OpenLayers.Bounds(-20037508, -20037508,20037508, 20037508.34)
var options = {
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.KeyboardDefaults()
],
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
units: "m",
numZoomLevels: 18,
minZoomLevel: 2,
maxResolution: 156543.0339,
maxExtent: new OpenLayers.Bounds(-20037508, -20037508,20037508, 20037508.34)
};
map = new OpenLayers.Map('map', options);
this.map=map;
var osm = new OpenLayers.Layer.OSM( {minZoomLevel: 9, maxZoomLevel:18});
this.map.addLayers([osm]);
var styleMap = new OpenLayers.StyleMap({
"default": new OpenLayers.Style(null, {
rules: [new OpenLayers.Rule({
symbolizer: {
"Point": {
pointRadius: 4,
graphicName: "circle",
fillColor: "white",
fillOpacity: 1,
strokeWidth: 1,
strokeOpacity: 1,
strokeColor: "#666666"
},
"Line": {
strokeWidth: 2,
strokeOpacity: 1,
strokeColor: "#666666",
strokeDashstyle: "dash"
},
"Polygon": {
strokeWidth: 2,
strokeOpacity: 1,
strokeColor: "#666666",
strokeDashstyle: "dash",
fillColor: "white",
fillOpacity: 0.3
}
}
})]
})
});
Mapmanager.mapControls = {
zoomtomaxextent: new OpenLayers.Control.ZoomToMaxExtent({title:"Zoom to max extent"}),
pan: new OpenLayers.Control.Pan({title:"Pan"}),
zoombox: new OpenLayers.Control.ZoomBox({title:"Zoom Box", out: false}),
measuredist: new OpenLayers.Control.Measure(OpenLayers.Handler.Path,{
persist: true,
geodesic: true,
handlerOptions: {layerOptions: {styleMap: styleMap}},
eventListeners: {
"measure": handleMeasurements
}
}),
measurearea: new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon,{
persist: true,
geodesic: true,
handlerOptions: {layerOptions: {styleMap: styleMap}},
eventListeners: {
"measure": handleMeasurements
}
})
}
for(var key in Mapmanager.mapControls) {
control = Mapmanager.mapControls[key];
this.map.addControl(control);
}
this.map.addControl(new OpenLayers.Control.MousePosition({div: document.getElementById("mposition")}));
this.map.addControl(new OpenLayers.Control.ZoomPanel());
this.map.setOptions({restrictedExtent: extent});
this.map.setCenter(extent, 2);
$('.toolbar a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
$(".close-toolbar").click(function () {
$(".map-toolbar").hide("slow");
});
$("#rasterTools").click(function () {
$(".raster-toolbar").draggable().show("slow");
});
$(".close-toolbar2").click(function () {
$(".raster-toolbar").hide("slow");
});
$(".dropdown-toolbars dt a").click(function() {
$(".dropdown-toolbars dd ul").show('slow');
});
$('.dropdown-toolbars dd ul').mouseleave(function() {
$(".dropdown-toolbars dd ul").hide('slow');
});
},
refresh: function(){
function uncheck(){
$('input[id=editingToolbar]').attr('checked', false);
}
function uncheck1(){
$('input[id=spatialToolbar]').attr('checked', false);
}
var xposEdit= ($(document).width() - 520);
var xposSpatial= ($(document).width() - 710);
$(".editing-toolbar").dialog({
autoOpen: false,
height: 72,
width: 210,
resizable: false,
position: [xposEdit, 135],
close: function(event, ui) { uncheck();}
});
$("#editingToolbar").click(function() {
$(".editing-toolbar").dialog("open");
});
$(".spatial-toolbar").dialog({
autoOpen: false,
height: 72,
width: 400,
position: [xposSpatial, 225],
resizable: false,
close: function(event, ui) { uncheck1();}
});
$("#spatialToolbar").click(function() {
$(".spatial-toolbar").dialog("open");
});
$('.pan, .zoombox, .zoom-to-max-extent, .identify, .measure-dist, .measure-area, .select-feature, .add-point, .add-line, .add-polygon, .delete-feature, .buffer, .simplify, .centroid, .boundary, .convexhull, .union, .intersection' ).button({text: false});
$('.save-as-map' ).button({text: false});
$("input:checkbox, input:radio, input:file").uniform();
;
}
});
<|start_filename|>mapmint-ui/js/datawarehouse-table.js<|end_filename|>
$(document).ready(function() {
oTable = $('#example2').dataTable({
"bJQueryUI": true
});
oTable = $('#example3').dataTable({
"bJQueryUI": true
});
oTable = $('#example4').dataTable({
"bJQueryUI": true
});
$("#example tbody, #example2 tbody, #example3 tbody, #example4 tbody").click(function(event) {
$(oTable.fnSettings().aoData).each(function (){
$(this.nTr).removeClass('row_selected');
});
$(event.target.parentNode).addClass('row_selected');
});
/* Add a click handler for the delete row */
$('#delete').click( function() {
var anSelected = fnGetSelected( oTable );
oTable.fnDeleteRow( anSelected[0] );
$.notifyBar({ cls: "success", html: "operation sucessful" });
} );
oTable = $('#example').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
/* Get the rows which are currently selected */
function fnGetSelected( oTableLocal )
{
var aReturn = new Array();
var aTrs = oTableLocal.fnGetNodes();
for ( var i=0 ; i<aTrs.length ; i++ )
{
if ( $(aTrs[i]).hasClass('row_selected') )
{
aReturn.push( aTrs[i] );
}
}
return aReturn;
}
} );
<|start_filename|>mapmint-ui/js/jquery.jgrowl.js<|end_filename|>
/**
* jGrowl 1.2.5
*
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Written by <NAME> <<EMAIL>>
* Last updated: 2009.12.15
*
*/
(function($) {
/** jGrowl Wrapper - Establish a base jGrowl Container for compatibility with older releases. **/
$.jGrowl = function( m , o ) {
// To maintain compatibility with older version that only supported one instance we'll create the base container.
if ( $('#jGrowl').size() == 0 )
$('<div id="jGrowl"></div>').addClass( (o && o.position) ? o.position : $.jGrowl.defaults.position ).appendTo('body');
// Create a notification on the container.
$('#jGrowl').jGrowl(m,o);
};
/** Raise jGrowl Notification on a jGrowl Container **/
$.fn.jGrowl = function( m , o ) {
if ( $.isFunction(this.each) ) {
var args = arguments;
return this.each(function() {
var self = this;
/** Create a jGrowl Instance on the Container if it does not exist **/
if ( $(this).data('jGrowl.instance') == undefined ) {
$(this).data('jGrowl.instance', $.extend( new $.fn.jGrowl(), { notifications: [], element: null, interval: null } ));
$(this).data('jGrowl.instance').startup( this );
}
/** Optionally call jGrowl instance methods, or just raise a normal notification **/
if ( $.isFunction($(this).data('jGrowl.instance')[m]) ) {
$(this).data('jGrowl.instance')[m].apply( $(this).data('jGrowl.instance') , $.makeArray(args).slice(1) );
} else {
$(this).data('jGrowl.instance').create( m , o );
}
});
};
};
$.extend( $.fn.jGrowl.prototype , {
/** Default JGrowl Settings **/
defaults: {
pool: 0,
header: '',
group: '',
sticky: false,
position: 'top-right',
glue: 'after',
theme: 'default',
themeState: 'highlight',
corners: '10px',
check: 250,
life: 3000,
closeDuration: 'normal',
openDuration: 'normal',
easing: 'swing',
closer: true,
closeTemplate: '×',
closerTemplate: '<div> Close all </div>',
log: function(e,m,o) {},
beforeOpen: function(e,m,o) {},
afterOpen: function(e,m,o) {},
open: function(e,m,o) {},
beforeClose: function(e,m,o) {},
close: function(e,m,o) {},
animateOpen: {
opacity: 'show'
},
animateClose: {
opacity: 'hide'
}
},
notifications: [],
/** jGrowl Container Node **/
element: null,
/** Interval Function **/
interval: null,
/** Create a Notification **/
create: function( message , o ) {
var o = $.extend({}, this.defaults, o);
/* To keep backward compatibility with 1.24 and earlier, honor 'speed' if the user has set it */
if (typeof o.speed !== 'undefined') {
o.openDuration = o.speed;
o.closeDuration = o.speed;
}
this.notifications.push({ message: message , options: o });
o.log.apply( this.element , [this.element,message,o] );
},
render: function( notification ) {
var self = this;
var message = notification.message;
var o = notification.options;
var notification = $(
'<div class="jGrowl-notification ' + o.themeState + ' ui-corner-all' +
((o.group != undefined && o.group != '') ? ' ' + o.group : '') + '">' +
'<div class="jGrowl-close">' + o.closeTemplate + '</div>' +
'<div class="jGrowl-header">' + o.header + '</div>' +
'<div class="jGrowl-message">' + message + '</div></div>'
).data("jGrowl", o).addClass(o.theme).children('div.jGrowl-close').bind("click.jGrowl", function() {
$(this).parent().trigger('jGrowl.close');
}).parent();
/** Notification Actions **/
$(notification).bind("mouseover.jGrowl", function() {
$('div.jGrowl-notification', self.element).data("jGrowl.pause", true);
}).bind("mouseout.jGrowl", function() {
$('div.jGrowl-notification', self.element).data("jGrowl.pause", false);
}).bind('jGrowl.beforeOpen', function() {
if ( o.beforeOpen.apply( notification , [notification,message,o,self.element] ) != false ) {
$(this).trigger('jGrowl.open');
}
}).bind('jGrowl.open', function() {
if ( o.open.apply( notification , [notification,message,o,self.element] ) != false ) {
if ( o.glue == 'after' ) {
$('div.jGrowl-notification:last', self.element).after(notification);
} else {
$('div.jGrowl-notification:first', self.element).before(notification);
}
$(this).animate(o.animateOpen, o.openDuration, o.easing, function() {
// Fixes some anti-aliasing issues with IE filters.
if ($.browser.msie && (parseInt($(this).css('opacity'), 10) === 1 || parseInt($(this).css('opacity'), 10) === 0))
this.style.removeAttribute('filter');
$(this).data("jGrowl").created = new Date();
$(this).trigger('jGrowl.afterOpen');
});
}
}).bind('jGrowl.afterOpen', function() {
o.afterOpen.apply( notification , [notification,message,o,self.element] );
}).bind('jGrowl.beforeClose', function() {
if ( o.beforeClose.apply( notification , [notification,message,o,self.element] ) != false )
$(this).trigger('jGrowl.close');
}).bind('jGrowl.close', function() {
// Pause the notification, lest during the course of animation another close event gets called.
$(this).data('jGrowl.pause', true);
$(this).animate(o.animateClose, o.closeDuration, o.easing, function() {
$(this).remove();
var close = o.close.apply( notification , [notification,message,o,self.element] );
if ( $.isFunction(close) )
close.apply( notification , [notification,message,o,self.element] );
});
}).trigger('jGrowl.beforeOpen');
/** Optional Corners Plugin **/
if ( o.corners != '' && $.fn.corner != undefined ) $(notification).corner( o.corners );
/** Add a Global Closer if more than one notification exists **/
if ( $('div.jGrowl-notification:parent', self.element).size() > 1 &&
$('div.jGrowl-closer', self.element).size() == 0 && this.defaults.closer != false ) {
$(this.defaults.closerTemplate).addClass('jGrowl-closer ui-corner-all').addClass(this.defaults.theme)
.appendTo(self.element).animate(this.defaults.animateOpen, this.defaults.speed, this.defaults.easing)
.bind("click.jGrowl", function() {
$(this).siblings().trigger("jGrowl.beforeClose");
if ( $.isFunction( self.defaults.closer ) ) {
self.defaults.closer.apply( $(this).parent()[0] , [$(this).parent()[0]] );
}
});
};
},
/** Update the jGrowl Container, removing old jGrowl notifications **/
update: function() {
$(this.element).find('div.jGrowl-notification:parent').each( function() {
if ( $(this).data("jGrowl") != undefined && $(this).data("jGrowl").created != undefined &&
($(this).data("jGrowl").created.getTime() + parseInt($(this).data("jGrowl").life)) < (new Date()).getTime() &&
$(this).data("jGrowl").sticky != true &&
($(this).data("jGrowl.pause") == undefined || $(this).data("jGrowl.pause") != true) ) {
// Pause the notification, lest during the course of animation another close event gets called.
$(this).trigger('jGrowl.beforeClose');
}
});
if ( this.notifications.length > 0 &&
(this.defaults.pool == 0 || $(this.element).find('div.jGrowl-notification:parent').size() < this.defaults.pool) )
this.render( this.notifications.shift() );
if ( $(this.element).find('div.jGrowl-notification:parent').size() < 2 ) {
$(this.element).find('div.jGrowl-closer').animate(this.defaults.animateClose, this.defaults.speed, this.defaults.easing, function() {
$(this).remove();
});
}
},
/** Setup the jGrowl Notification Container **/
startup: function(e) {
this.element = $(e).addClass('jGrowl').append('<div class="jGrowl-notification"></div>');
this.interval = setInterval( function() {
$(e).data('jGrowl.instance').update();
}, parseInt(this.defaults.check));
if ($.browser.msie && parseInt($.browser.version) < 7 && !window["XMLHttpRequest"]) {
$(this.element).addClass('ie6');
}
},
/** Shutdown jGrowl, removing it and clearing the interval **/
shutdown: function() {
$(this.element).removeClass('jGrowl').find('div.jGrowl-notification').remove();
clearInterval( this.interval );
},
close: function() {
$(this.element).find('div.jGrowl-notification').each(function(){
$(this).trigger('jGrowl.beforeClose');
});
}
});
/** Reference the Defaults Object for compatibility with older versions of jGrowl **/
$.jGrowl.defaults = $.fn.jGrowl.prototype.defaults;
})(jQuery);
<|start_filename|>mapmint-ui/new-themes/themes/purple/icons.css<|end_filename|>
/*
* MapMint Icons CSS
*/
.maincfg1 {border:1px solid #8f8f8f;background-image:url(../img/monitor-purple.png) !important;}
.maincfg2 {border:1px solid #8f8f8f;background-image:url(../img/security-purple.png) !important;}
.maincfg3 {border:1px solid #8f8f8f;background-image:url(../img/user-purple.png) !important;}
.projects {border:1px solid #8f8f8f;background-image:url(../img/process-purple.png) !important;}
.documents {border:1px solid #8f8f8f;background-image:url(../img/docs-purple.png) !important;}
.add-database {border:1px solid #8f8f8f;background-image:url(../img/add-database-default-purple.png) !important;}
.add-directory {border:1px solid #8f8f8f;background-image:url(../img/add-directory-default-purple.png) !important;}
.add-vector {border:1px solid #8f8f8f;background-image:url(../img/add-vector-purple.png) !important;}
.add-raster {border:1px solid #8f8f8f;background-image:url(../img/add-raster-purple.png) !important;}
.add-wms {border:1px solid #8f8f8f;background-image:url(../img/add-wms-purple.png) !important;}
.add-wfs {border:1px solid #8f8f8f;background-image:url(../img/add-wfs-purple.png) !important;}
.add-wcs {border:1px solid #8f8f8f;background-image:url(../img/add-wcs-purple.png) !important;}
.add-layer {border:1px solid #8f8f8f;background-image:url(../img/add-layer-purple.png) !important;}
.open-map {border:1px solid #8f8f8f;background-image:url(../img/open-map-purple.png) !important;}
.pan {border:1px solid #8f8f8f;background-image:url(../img/pan-purple.png) !important;}
.zoom-box {border:1px solid #8f8f8f;background-image:url(../img/zoom-in-purple.png) !important;}
.zoom-in {border:1px solid #8f8f8f;background-image:url(../img/zoomin-purple.png) !important;}
.zoom-in:hover {border:1px solid #8f8f8f;background: #73C354 url(../img/zoomin-hover-purple.png) !important;
}
.zoom-to-max-extent {border:1px solid #8f8f8f;background-image:url(../img/zoomtomaxextent-purple.png) !important;}
.zoom-to-max-extent:hover {border:1px solid #8f8f8f;background-image:url(../img/zoomtomaxextent-hover-purple.png) !important;}
.zoom-out {border:1px solid #8f8f8f;background-image:url(../img/zoomout-purple.png) !important;}
.zoom-out:hover {border:1px solid #8f8f8f;background: #73C354 url(../img/zoomout-hover-purple.png) !important;}
.zoom-to-point {border:1px solid #8f8f8f;background-image:url(../img/zoom-to-point-purple.png) !important;}
.identify {border:1px solid #8f8f8f;background-image:url(../img/identify-purple.png) !important;}
.mesure-distance {border:1px solid #8f8f8f;background-image:url(../img/ruler-purple.png) !important;}
.mesure-area {border:1px solid #8f8f8f;background-image:url(../img/ruler-crop-purple.png) !important;}
.select {border:1px solid #8f8f8f;background-image:url(../img/select-purple.png) !important;}
.edit-point {border:1px solid #8f8f8f;background-image:url(../img/edit-point-purple.png) !important;}
.edit-line {border:1px solid #8f8f8f;background-image:url(../img/edit-line-purple.png) !important;}
.edit-polygon {border:1px solid #8f8f8f;background-image:url(../img/edit-polygon-purple.png) !important;}
.delete-feature {border:1px solid #8f8f8f;background-image:url(../img/delete-feature-purple.png) !important;}
.buffer {border:1px solid #8f8f8f;background-image:url(../img/buffer-purple.png) !important;}
.centroid {border:1px solid #8f8f8f;background-image:url(../img/centroid-purple.png) !important;}
.boundary {border:1px solid #8f8f8f;background-image:url(../img/boundary-purple.png) !important;}
.convexhull {border:1px solid #8f8f8f;background-image:url(../img/convexhull-purple.png) !important;}
.simplify {border:1px solid #8f8f8f;background-image:url(../img/simplify-purple.png) !important;}
.union {border:1px solid #8f8f8f;background-image:url(../img/union-purple.png) !important;}
.intersection {border:1px solid #8f8f8f;background-image:url(../img/intersection-purple.png) !important;}
.symdifference {border:1px solid #8f8f8f;background-image:url(../img/symdifference-purple.png) !important;}
.difference {border:1px solid #8f8f8f;background-image:url(../img/difference-purple.png) !important;}
.raster-histogram {border:1px solid #8f8f8f;background-image:url(../img/raster-histogram-purple.png) !important;}
.clip-raster {border:1px solid #8f8f8f;background-image:url(../img/clip-layer-purple.png) !important;}
.merge-rasters {border:1px solid #8f8f8f;background-image:url(../img/merge-layer-purple.png) !important;}
.polygons-from-raster {border:1px solid #8f8f8f;background-image:url(../img/polygons-from-raster-purple.png) !important;}
.raster-from-csv {border:1px solid #8f8f8f;background-image:url(../img/raster-from-csv-purple.png) !important;}
.terrain-profile {border:1px solid #8f8f8f;background-image:url(../img/terrain-profile-purple.png) !important;}
.contours-from-dem {border:1px solid #8f8f8f;background-image:url(../img/contours-from-dem-purple.png) !important;}
.shaded-relief {border:1px solid #8f8f8f;background-image:url(../img/shaded-relief-purple.png) !important;}
.color-relief {border:1px solid #8f8f8f;background-image:url(../img/color-relief-purple.png) !important;}
.slope-map {border:1px solid #8f8f8f;background-image:url(../img/slope-map-purple.png) !important;}
.main-configuration {border:1px solid #8f8f8f;background-image:url(../img/process-purple.png) !important;}
.layout-settings {border:1px solid #8f8f8f;background-image:url(../img/layout-settings-purple.png) !important;}
.map-settings {border:1px solid #8f8f8f;background-image:url(../img/map-settings-purple.png) !important;}
.layers-settings {border:1px solid #8f8f8f;background-image:url(../img/layers-settings-purple.png) !important;}
.controls-settings {border:1px solid #8f8f8f;background-image:url(../img/controls-settings-purple.png) !important;}
<|start_filename|>mapmint-ui/new-themes/themes/pink/ui.css<|end_filename|>
.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555; text-decoration: none; }
.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { text-shadow: #777777 0px 1px 0px;
background: #f630f8; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f869ec', endColorstr='#f630f8'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#f869ec), to(#f630f8)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
font-weight: normal; color: #FFFFFF; }
.ui-state-hover a, .ui-state-hover a:hover { color: #FFFFFF; text-decoration: none; }
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active {text-shadow: #777777 0px 1px 0px;
background: #f630f8; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f869ec', endColorstr='#f630f8'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#f869ec), to(#f630f8)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
font-weight: normal; color: #FFFFFF; }
<|start_filename|>mapmint-ui/templates/preview/modules/getFeature/control.js<|end_filename|>
,getFeature: gfiControl
<|start_filename|>public_map/MMMap/mmlib/MMPanZoom.js<|end_filename|>
/*global OpenLayers, $, MMMap */
/*
* @requires ../lib/OpenLayers/Control.js
*/
OpenLayers.Control.MMPanZoom = OpenLayers.Class(OpenLayers.Control, {
initialize: function ()
{
OpenLayers.Control.prototype.initialize.apply(this, arguments);
},
/**
* APIMethod: destroy
*/
destroy: function ()
{
OpenLayers.Event.stopObservingElement(this.div);
this._removeZoomBar();
this._removePanButtons();
this.map.events.un({
"changebaselayer": this.redraw,
scope: this
});
this.removeButtons();
this.buttons = null;
$(this.div).unbind("hover");
this.div.innerHTML = "";
OpenLayers.Control.prototype.destroy.apply(this, arguments);
},
show: function (show)
{
if (show)
{
$(this.div).show();
}
else
{
$(this.div).hide();
}
},
getVisibility: function ()
{
return $(this.div).is(":visible");
},
draw: function ()
{
OpenLayers.Control.prototype.draw.apply(this, arguments);
this.buttons = [];
$(this.div).hover(OpenLayers.Function.bindAsEventListener(this.showButtons, this), OpenLayers.Function.bindAsEventListener(this.hideButtons, this));
//OpenLayers.Event.observe(this.div, "mouseover",OpenLayers.Function.bindAsEventListener(this.showButtons, this));
//OpenLayers.Event.observe(this.div, "mouseout",OpenLayers.Function.bindAsEventListener(this.hideButtons, this));
this._addPanButtons();
this._addZoomBar();
this.hideButtons();
return this.div;
},
_addPanButtons: function ()
{
this.panWrapper = document.createElement("div");
this.panWrapper.className = this.displayClass + "PanWrapper";
this.pan = document.createElement("div");
this.pan.className = this.displayClass + "Pan";
this.panJoy = OpenLayers.Util.createAlphaImageDiv(this.id + "_" + "pan", { x: 6, y: 6 }, { h: 17, w: 17 }, MMMap.getImagesLocation() + "sgpan_barjoy.png", "absolute");
this.panJoy.className = this.displayClass + "PanJoystick"
this.panLeft = this._addButton("panleft", { x: 20, y: 32 }, { h: 11, w: 7 }, "sgpan_panLeft.png");
this.panRight = this._addButton("panright", { x: 56, y: 32 }, { h: 11, w: 7 }, "sgpan_panRight.png");
this.panTop = this._addButton("panup", { x: 36, y: 12 }, { h: 7, w: 11 }, "sgpan_panTop.png");
this.panBottom = this._addButton("pandown", { x: 36, y: 48 }, { h: 7, w: 11 }, "sgpan_panBottom.png");
var joystickWrapper = document.createElement("div");
joystickWrapper.className = this.displayClass + "JoystickWrapper";
joystickWrapper.appendChild(this.panJoy);
var $this = this;
$(this.panJoy).draggable(
{
containment: $(joystickWrapper),
revert: true,
revertDuration: 0,
drag: function (evt, ui)
{
var location = 6; // joystiq location is 6,6
var xOffest = (ui.position.left - location);
if (xOffest < 0)
{
xOffest = -1;
}
if (xOffest > 0)
{
xOffest = 1;
}
var yOffest = (ui.position.top - location);
if (yOffest < 0)
{
yOffest = -1;
}
if (yOffest > 0)
{
yOffest = 1;
}
var x = 100 * xOffest;
var y = 100 * yOffest;
$this.inPanJoystiqDrag = true;
$this.startPanning(x, y);
},
stop: function ()
{
$this.inPanJoystiqDrag = false;
if ($this.hideButtonsAtPanJoystiqDragEnd)
{
$this.hideButtons();
}
$this.stopPanning();
}
})
.bind("mousedown click dblclick", function (evt)
{
evt.preventDefault();
return false;
});
this.pan.appendChild(this.panLeft);
this.pan.appendChild(this.panRight);
this.pan.appendChild(this.panTop);
this.pan.appendChild(this.panBottom);
this.pan.appendChild(joystickWrapper);
this.panWrapper.appendChild(this.pan);
this.div.appendChild(this.panWrapper);
},
_zoomLevels: [
{ name: System.messages['globe'], level: 0 },
{ name: System.messages['country'], level: 4 },
{ name: System.messages['state'], level: 6 },
{ name: System.messages['city'], level: 13 },
{ name: System.messages['street'], level: 16 },
{ name: System.messages['house'], level: 18 }
],
_addZoomBar: function ()
{
this.zoomWrapper = document.createElement("div");
this.zoomWrapper.className = this.displayClass + 'ZoomWrapper';
this.map.events.register("zoomend", this, this.moveZoomBar);
this.div.appendChild(this.zoomWrapper);
var $this = this;
var maxLevel = this.map.getNumZoomLevels();
this.zoomSlider = $("<div></div>").appendTo(this.zoomWrapper).slider({
animate: true,
orientation: 'vertical',
min: 0,
max: maxLevel-System.initZoomLevel,
step: 1,
value: maxLevel - this.map.getZoom(),
change: function (evt, ui)
{
var newZoomLevel = maxLevel - ui.value;
if ($this.map.getZoom() != newZoomLevel)
{
$this.map.zoomTo(newZoomLevel);
}
}
})
.bind('mousedown', this.doubleClick);
var zoomLevelsHtml = "<div class=olControlMMPanZoomZoomLevels>";
for (var i = 0; i < this._zoomLevels.length; i++)
{
if(this._zoomLevels[i].level>=System.initZoomLevel)
zoomLevelsHtml += "<div class='zoomLevel' style='top:" + (Math.round((this._zoomLevels[i].level-System.initZoomLevel) * 130 / (maxLevel-System.initZoomLevel))-2) + "px' zoom='" + this._zoomLevels[i].level + "'>" + this._zoomLevels[i].name + "</div>";
}
zoomLevelsHtml += "</div>";
this.zoomLevels = $(zoomLevelsHtml).appendTo(this.zoomWrapper);
$(".zoomLevel", this.zoomLevels).mousedown(function (evt)
{
// if not left click do nothing
if (evt.which !== 1)
{
return true;
}
evt.preventDefault();
$this.map.zoomTo(parseInt($(this).attr("zoom"), 10));
return false;
});
},
_removePanButtons: function ()
{
this.div.removeChild(this.panWrapper);
},
/**
* Method: _removeZoomBar
*/
_removeZoomBar: function ()
{
this.div.removeChild(this.zoomWrapper);
$(".zoomLevel", this.zoomLevels).unbind();
this.map.events.unregister("zoomend", this, this.moveZoomBar);
this.zoomSlider.unbind();
this.zoomWrapper = null;
this.zoomSlider = null;
this.zoomLevels = null;
},
/**
* Method: setMap
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function (map)
{
OpenLayers.Control.prototype.setMap.apply(this, arguments);
this.map.events.register("changebaselayer", this, this.redraw);
},
/**
* Method: redraw
* clear the div and start over.
*/
redraw: function ()
{
if (this.div)
{
this.removeButtons();
this._removeZoomBar();
this._removePanButtons();
}
this.draw();
},
hideButtons: function ()
{
if (this.inPanJoystiqDrag)
{
this.hideButtonsAtPanJoystiqDragEnd = true;
return;
}
// ie <9 does not support png transparency animation
if ($('body').is('.lt-ie9 *'))
return;
$(this.div).stop().css({ opacity: 1 }).animate({ opacity: 0.25 }, 1200);
},
showButtons: function ()
{
this.hideButtonsAtPanJoystiqDragEnd = false;
// ie <9 does not support png transparency animation
if ($('body').is('.lt-ie9 *'))
return;
$(this.div).stop().css({ opacity: 0.25 }).animate({ opacity: 1 }, "slow");
},
/**
* Method: _addButton
*
* Parameters:
* id - {String}
* img - {String}
* xy - {<OpenLayers.Pixel>}
* sz - {<OpenLayers.Size>}
*
* Returns:
* {DOMElement} A Div (an alphaImageDiv, to be precise) that contains the
* image of the button, and has all the proper event handlers set.
*/
_addButton: function (id, xy, sz, img)
{
var imgLocation = MMMap.getImagesLocation() + img;
var btn = OpenLayers.Util.createAlphaImageDiv(
this.id + "_" + id,
xy, sz, imgLocation, "absolute");
btn.className = this.displayClass + "PanButton";
OpenLayers.Event.observe(btn, "mousedown",
OpenLayers.Function.bindAsEventListener(this.buttonDown, btn));
OpenLayers.Event.observe(btn, "mouseup",
OpenLayers.Function.bindAsEventListener(this.buttonUp, this));
OpenLayers.Event.observe(btn, "dblclick",
OpenLayers.Function.bindAsEventListener(this.doubleClick, btn));
OpenLayers.Event.observe(btn, "click",
OpenLayers.Function.bindAsEventListener(this.doubleClick, btn));
btn.action = id;
btn.map = this.map;
btn.parent = this;
this.buttons.push(btn);
return btn;
},
/**
* Method: _removeButton
*
* Parameters:
* btn - {Object}
*/
_removeButton: function (btn)
{
OpenLayers.Event.stopObservingElement(btn);
btn.map = null;
btn.getSlideFactor = null;
this.pan.removeChild(btn);
OpenLayers.Util.removeItem(this.buttons, btn);
},
/**
* Method: removeButtons
*/
removeButtons: function ()
{
for (var i = this.buttons.length - 1; i >= 0; --i)
{
this._removeButton(this.buttons[i]);
}
},
/**
* Method: doubleClick
*
* Parameters:
* evt - {Event}
*
* Returns:
* {Boolean}
*/
doubleClick: function (evt)
{
OpenLayers.Event.stop(evt);
return false;
},
/**
* Method: buttonDown
*
* Parameters:
* evt - {Event}
*/
buttonDown: function (evt)
{
if (!OpenLayers.Event.isLeftClick(evt))
{
return;
}
// if user moves his mouse from over the button, the map/another div on window recieves the mous up event and pannng does not stop. So lets catch this event if we in pan mode
if (!this.parent.windowButtonUpObserver)
{
this.parent.windowButtonUpObserver = OpenLayers.Function.bindAsEventListener(this.parent.buttonUp, this.parent);
}
OpenLayers.Event.observe(window.document, "mouseup", this.parent.windowButtonUpObserver);
var pan = 200;
switch (this.action)
{
case "panup":
this.parent.startPanning(0, -pan);
break;
case "pandown":
this.parent.startPanning(0, pan);
break;
case "panleft":
this.parent.startPanning(-pan, 0);
break;
case "panright":
this.parent.startPanning(pan, 0);
break;
}
OpenLayers.Event.stop(evt);
},
buttonUp: function (evt)
{
OpenLayers.Event.stopObserving(window.document, "mouseup", this.windowButtonUpObserver);
this.stopPanning();
OpenLayers.Event.stop(evt);
},
startPanning: function (x, y)
{
this.stopPanning();
var $this = this;
// first pann at least once, to suport simple clicking in pan button
$this.map.pan(x, y);
// then start an interval to support holding the button down
this.panInterval = setInterval(function ()
{
$this.map.pan(x, y);
}, 100);
},
stopPanning: function ()
{
if (this.panInterval)
{
clearInterval(this.panInterval);
this.panInterval = null;
}
},
/*
* Method: moveZoomBar
* Change the location of the slider to match the current zoom level.
*/
moveZoomBar: function ()
{
this.zoomSlider.slider("option", "value", this.map.getNumZoomLevels() - this.map.getZoom());
this.zoomSlider.attr("title", System.messages["Zoom: "] + (this.map.getZoom() + 1));
},
CLASS_NAME: "OpenLayers.Control.MMPanZoom"
});
<|start_filename|>mapmint-ui/new-themes/themes/purple/tree.css<|end_filename|>
.tree-node-selected{
background: #8340f3; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#c743f8', endColorstr='#8340f3'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#c743f8), to(#8340f3)); /* for webkit browsers */
background: -moz-linear-gradient(top, #c743f8, #8340f3 ); /* for firefox 3.6+ */
}
.menu-active{
border:1px solid #a182f9;
background:#fafafa;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
<|start_filename|>mapmint-ui/templates/preview/modules/links/display.html<|end_filename|>
#import zoo
#from manage_users import *
#import authenticate.service as auth
#set con=auth.getCon($conf)
#set prefix=auth.getPrefix($conf)
#set c=con.connect()
#set conn = con.conn
#set cur=conn.cursor()
#set clause=""
#for i in $conf["senv"]["group"].split(",")
#if clause!=""
#set $clause+=" or "
#end if
#set $clause+=" name = '"+$i+"' "
#end for
#set res=cur.execute('SELECT id,title,url from '+$prefix+'links where id in (select l_id from '+prefix+'links_groups where g_id in (select id from '+$prefix+'groups where name=\'public\' or '+$clause+')) order by id desc LIMIT 4')
#set vals=cur.fetchall()
#if len(vals)>0
<h3 class="lgb">$zoo._("Links")</h3>
<ul>
#for i in range(0,len(vals))
<li><a target="_blank" href="$vals[i][2]">$vals[i][1]</a></li>
#end for
</ul>
#end if
<|start_filename|>mapmint-ui/templates/preview/modules/addLayer/display_bs.html<|end_filename|>
#import zoo
#import mapfile.service as mms
#if $mms.getMetadata($m.web,'mmOT')
#set f0=$mms.getMetadata($m.web,'mmOT').split(',')
#if $f0.count('AddLayer')>0 or $f0.count('AddWMSLayer')>0
<div role="tabpanel" class="tab-pane" id="addLayer-ui">
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
#if $f0.count('AddLayer')>0
<li role="presentation"><a href="#mm_overlays_display" aria-controls="home" role="tab" data-toggle="tab">$zoo._("Layers")</a>
</li>
#end if
#if $f0.count('AddWMSLayer')>0
<li role="presentation" class="active"><a
href="#mm_overlays_wms_display" aria-controls="profile" role="tab"
data-toggle="tab">$zoo._("WMS Layers")</a>
</li>
#end if
<button class="btn btn-default pull-right mmbtn-small">
$zoo._("Add")
</button>
</ul>
<div class="tab-content">
#end if
#set itemId=0
#if $f0.count('AddLayer')>0
<div role="tabpanel" class="tab-pane#if $itemId==0# active#end if#" id="mm_overlays_display">
<div id="tab1" class="sources-container" style="overflow:auto">
#from Cheetah.Template import Template
#import mapscript
#set m0=mapscript.mapObj($conf["main"]["dataPath"]+"/maps/project_Overlays.map")
$(Template(file=$conf["main"]["templatesPath"]+"/preview/modules/addLayer/OverlayLayers_bs.html",searchList={"m":$m0,"conf":$conf}))
</div>
</div>
#set itemId+=1
#end if
#if $f0.count('AddWMSLayer')>0
<div role="tabpanel" class="tab-pane#if $itemId==0# active#end if#" id="mm_overlays_wms_display">
<div id="tab2" class="sources-container" style="overflow:auto">
$(Template(file=$conf["main"]["templatesPath"]+"/preview/modules/addLayer/WMSLayers_bs.html",searchList={"m":$m,"conf":$conf}))
</div>
</div>
#end if
#if $f0.count('AddLayer')>0 or $f0.count('AddWMSLayer')>0
</div>
</div>
#end if
#end if
<|start_filename|>public_map/assets/css/app.v1.css<|end_filename|>
html {font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}
body {margin:0}
@font-face {font-family: 'mmFont';src: url('../fonts/mmFont.ttf') format('truetype');font-weight: normal;font-style: normal;}
[class^="icon-mm-"],
[class*=" icon-mm-"] {
font-family: 'mmFont', sans-serif;
font-weight: normal;
font-style: normal;
text-decoration: inherit;
-webkit-font-smoothing: antialiased;
}
.icon-mm-logo:before{content: "\e602";}
@font-face {font-family:'Glyphicons Halflings';src:url('../fonts/glyphicons-halflings-regular.eot');src:url('../fonts/glyphicons-halflings-regular-.eot#iefix') format('embedded-opentype'),url('../fonts/glyphicons-halflings-regular.woff') format('woff'),url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg')}
.glyphicon {position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
.glyphicon-asterisk:before {content:"\2a"}
.glyphicon-plus:before {content:"\2b"}
.glyphicon-euro:before {content:"\20ac"}
.glyphicon-minus:before {content:"\2212"}
.glyphicon-cloud:before {content:"\2601"}
.glyphicon-envelope:before {content:"\2709"}
.glyphicon-pencil:before {content:"\270f"}
.glyphicon-glass:before {content:"\e001"}
.glyphicon-music:before {content:"\e002"}
.glyphicon-search:before {content:"\e003"}
.glyphicon-heart:before {content:"\e005"}
.glyphicon-star:before {content:"\e006"}
.glyphicon-star-empty:before {content:"\e007"}
.glyphicon-user:before {content:"\e008"}
.glyphicon-film:before {content:"\e009"}
.glyphicon-th-large:before {content:"\e010"}
.glyphicon-th:before {content:"\e011"}
.glyphicon-th-list:before {content:"\e012"}
.glyphicon-ok:before {content:"\e013"}
.glyphicon-remove:before {content:"\e014"}
.glyphicon-zoom-in:before {content:"\e015"}
.glyphicon-zoom-out:before {content:"\e016"}
.glyphicon-off:before {content:"\e017"}
.glyphicon-signal:before {content:"\e018"}
.glyphicon-cog:before {content:"\e019"}
.glyphicon-trash:before {content:"\e020"}
.glyphicon-home:before {content:"\e021"}
.glyphicon-file:before {content:"\e022"}
.glyphicon-time:before {content:"\e023"}
.glyphicon-road:before {content:"\e024"}
.glyphicon-download-alt:before {content:"\e025"}
.glyphicon-download:before {content:"\e026"}
.glyphicon-upload:before {content:"\e027"}
.glyphicon-inbox:before {content:"\e028"}
.glyphicon-play-circle:before {content:"\e029"}
.glyphicon-repeat:before {content:"\e030"}
.glyphicon-refresh:before {content:"\e031"}
.glyphicon-list-alt:before {content:"\e032"}
.glyphicon-lock:before {content:"\e033"}
.glyphicon-flag:before {content:"\e034"}
.glyphicon-headphones:before {content:"\e035"}
.glyphicon-volume-off:before {content:"\e036"}
.glyphicon-volume-down:before {content:"\e037"}
.glyphicon-volume-up:before {content:"\e038"}
.glyphicon-qrcode:before {content:"\e039"}
.glyphicon-barcode:before {content:"\e040"}
.glyphicon-tag:before {content:"\e041"}
.glyphicon-tags:before {content:"\e042"}
.glyphicon-book:before {content:"\e043"}
.glyphicon-bookmark:before {content:"\e044"}
.glyphicon-print:before {content:"\e045"}
.glyphicon-camera:before {content:"\e046"}
.glyphicon-font:before {content:"\e047"}
.glyphicon-bold:before {content:"\e048"}
.glyphicon-italic:before {content:"\e049"}
.glyphicon-text-height:before {content:"\e050"}
.glyphicon-text-width:before {content:"\e051"}
.glyphicon-align-left:before {content:"\e052"}
.glyphicon-align-center:before {content:"\e053"}
.glyphicon-align-right:before {content:"\e054"}
.glyphicon-align-justify:before {content:"\e055"}
.glyphicon-list:before {content:"\e056"}
.glyphicon-indent-left:before {content:"\e057"}
.glyphicon-indent-right:before {content:"\e058"}
.glyphicon-facetime-video:before {content:"\e059"}
.glyphicon-picture:before {content:"\e060"}
.glyphicon-map-marker:before {content:"\e062"}
.glyphicon-adjust:before {content:"\e063"}
.glyphicon-tint:before {content:"\e064"}
.glyphicon-edit:before {content:"\e065"}
.glyphicon-share:before {content:"\e066"}
.glyphicon-check:before {content:"\e067"}
.glyphicon-move:before {content:"\e068"}
.glyphicon-step-backward:before {content:"\e069"}
.glyphicon-fast-backward:before {content:"\e070"}
.glyphicon-backward:before {content:"\e071"}
.glyphicon-play:before {content:"\e072"}
.glyphicon-pause:before {content:"\e073"}
.glyphicon-stop:before {content:"\e074"}
.glyphicon-forward:before {content:"\e075"}
.glyphicon-fast-forward:before {content:"\e076"}
.glyphicon-step-forward:before {content:"\e077"}
.glyphicon-eject:before {content:"\e078"}
.glyphicon-chevron-left:before {content:"\e079"}
.glyphicon-chevron-right:before {content:"\e080"}
.glyphicon-plus-sign:before {content:"\e081"}
.glyphicon-minus-sign:before {content:"\e082"}
.glyphicon-remove-sign:before {content:"\e083"}
.glyphicon-ok-sign:before {content:"\e084"}
.glyphicon-question-sign:before {content:"\e085"}
.glyphicon-info-sign:before {content:"\e086"}
.glyphicon-screenshot:before {content:"\e087"}
.glyphicon-remove-circle:before {content:"\e088"}
.glyphicon-ok-circle:before {content:"\e089"}
.glyphicon-ban-circle:before {content:"\e090"}
.glyphicon-arrow-left:before {content:"\e091"}
.glyphicon-arrow-right:before {content:"\e092"}
.glyphicon-arrow-up:before {content:"\e093"}
.glyphicon-arrow-down:before {content:"\e094"}
.glyphicon-share-alt:before {content:"\e095"}
.glyphicon-resize-full:before {content:"\e096"}
.glyphicon-resize-small:before {content:"\e097"}
.glyphicon-exclamation-sign:before {content:"\e101"}
.glyphicon-gift:before {content:"\e102"}
.glyphicon-leaf:before {content:"\e103"}
.glyphicon-fire:before {content:"\e104"}
.glyphicon-eye-open:before {content:"\e105"}
.glyphicon-eye-close:before {content:"\e106"}
.glyphicon-warning-sign:before {content:"\e107"}
.glyphicon-plane:before {content:"\e108"}
.glyphicon-calendar:before {content:"\e109"}
.glyphicon-random:before {content:"\e110"}
.glyphicon-comment:before {content:"\e111"}
.glyphicon-magnet:before {content:"\e112"}
.glyphicon-chevron-up:before {content:"\e113"}
.glyphicon-chevron-down:before {content:"\e114"}
.glyphicon-retweet:before {content:"\e115"}
.glyphicon-shopping-cart:before {content:"\e116"}
.glyphicon-folder-close:before {content:"\e117"}
.glyphicon-folder-open:before {content:"\e118"}
.glyphicon-resize-vertical:before {content:"\e119"}
.glyphicon-resize-horizontal:before {content:"\e120"}
.glyphicon-hdd:before {content:"\e121"}
.glyphicon-bullhorn:before {content:"\e122"}
.glyphicon-bell:before {content:"\e123"}
.glyphicon-certificate:before {content:"\e124"}
.glyphicon-thumbs-up:before {content:"\e125"}
.glyphicon-thumbs-down:before {content:"\e126"}
.glyphicon-hand-right:before {content:"\e127"}
.glyphicon-hand-left:before {content:"\e128"}
.glyphicon-hand-up:before {content:"\e129"}
.glyphicon-hand-down:before {content:"\e130"}
.glyphicon-circle-arrow-right:before {content:"\e131"}
.glyphicon-circle-arrow-left:before {content:"\e132"}
.glyphicon-circle-arrow-up:before {content:"\e133"}
.glyphicon-circle-arrow-down:before {content:"\e134"}
.glyphicon-globe:before {content:"\e135"}
.glyphicon-wrench:before {content:"\e136"}
.glyphicon-tasks:before {content:"\e137"}
.glyphicon-filter:before {content:"\e138"}
.glyphicon-briefcase:before {content:"\e139"}
.glyphicon-fullscreen:before {content:"\e140"}
.glyphicon-dashboard:before {content:"\e141"}
.glyphicon-paperclip:before {content:"\e142"}
.glyphicon-heart-empty:before {content:"\e143"}
.glyphicon-link:before {content:"\e144"}
.glyphicon-phone:before {content:"\e145"}
.glyphicon-pushpin:before {content:"\e146"}
.glyphicon-usd:before {content:"\e148"}
.glyphicon-gbp:before {content:"\e149"}
.glyphicon-sort:before {content:"\e150"}
.glyphicon-sort-by-alphabet:before {content:"\e151"}
.glyphicon-sort-by-alphabet-alt:before {content:"\e152"}
.glyphicon-sort-by-order:before {content:"\e153"}
.glyphicon-sort-by-order-alt:before {content:"\e154"}
.glyphicon-sort-by-attributes:before {content:"\e155"}
.glyphicon-sort-by-attributes-alt:before {content:"\e156"}
.glyphicon-unchecked:before {content:"\e157"}
.glyphicon-expand:before {content:"\e158"}
.glyphicon-collapse-down:before {content:"\e159"}
.glyphicon-collapse-up:before {content:"\e160"}
.glyphicon-log-in:before {content:"\e161"}
.glyphicon-flash:before {content:"\e162"}
.glyphicon-log-out:before {content:"\e163"}
.glyphicon-new-window:before {content:"\e164"}
.glyphicon-record:before {content:"\e165"}
.glyphicon-save:before {content:"\e166"}
.glyphicon-open:before {content:"\e167"}
.glyphicon-saved:before {content:"\e168"}
.glyphicon-import:before {content:"\e169"}
.glyphicon-export:before {content:"\e170"}
.glyphicon-send:before {content:"\e171"}
.glyphicon-floppy-disk:before {content:"\e172"}
.glyphicon-floppy-saved:before {content:"\e173"}
.glyphicon-floppy-remove:before {content:"\e174"}
.glyphicon-floppy-save:before {content:"\e175"}
.glyphicon-floppy-open:before {content:"\e176"}
.glyphicon-credit-card:before {content:"\e177"}
.glyphicon-transfer:before {content:"\e178"}
.glyphicon-cutlery:before {content:"\e179"}
.glyphicon-header:before {content:"\e180"}
.glyphicon-compressed:before {content:"\e181"}
.glyphicon-earphone:before {content:"\e182"}
.glyphicon-phone-alt:before {content:"\e183"}
.glyphicon-tower:before {content:"\e184"}
.glyphicon-stats:before {content:"\e185"}
.glyphicon-sd-video:before {content:"\e186"}
.glyphicon-hd-video:before {content:"\e187"}
.glyphicon-subtitles:before {content:"\e188"}
.glyphicon-sound-stereo:before {content:"\e189"}
.glyphicon-sound-dolby:before {content:"\e190"}
.glyphicon-sound-5-1:before {content:"\e191"}
.glyphicon-sound-6-1:before {content:"\e192"}
.glyphicon-sound-7-1:before {content:"\e193"}
.glyphicon-copyright-mark:before {content:"\e194"}
.glyphicon-registration-mark:before {content:"\e195"}
.glyphicon-cloud-download:before {content:"\e197"}
.glyphicon-cloud-upload:before {content:"\e198"}
.glyphicon-tree-conifer:before {content:"\e199"}
.glyphicon-tree-deciduous:before {content:"\e200"}
* {-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
*:before,*:after {-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
html {font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}
body {font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}
a {color:#428bca;text-decoration:none}
a:hover,a:focus {color:#2a6496;text-decoration:underline}
a:focus {outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}
figure {margin:0}
img {vertical-align:middle}
.img-responsive,.thumbnail>img,.thumbnail a>img,.carousel-inner>.item>img,.carousel-inner>.item>a>img {display:block;width:100% \9;max-width:100%;height:auto}
.img-rounded {border-radius:6px}
.img-thumbnail {display:inline-block;width:100% \9;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}
.img-circle {border-radius:50%}
hr {margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}
.sr-only {position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}
.sr-only-focusable:active,.sr-only-focusable:focus {position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}
h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6 {font-family:inherit;font-weight:500;line-height:1.1;color:inherit}
h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small,h1 .small,h2 .small,h3 .small,h4 .small,h5 .small,h6 .small,.h1 .small,.h2 .small,.h3 .small,.h4 .small,.h5 .small,.h6 .small {font-weight:normal;line-height:1;color:#777}
h1,.h1,h2,.h2,h3,.h3 {margin-top:20px;margin-bottom:10px}
h1 small,.h1 small,h2 small,.h2 small,h3 small,.h3 small,h1 .small,.h1 .small,h2 .small,.h2 .small,h3 .small,.h3 .small {font-size:65%}
h4,.h4,h5,.h5,h6,.h6 {margin-top:10px;margin-bottom:10px}
h4 small,.h4 small,h5 small,.h5 small,h6 small,.h6 small,h4 .small,.h4 .small,h5 .small,.h5 .small,h6 .small,.h6 .small {font-size:75%}
h1,.h1 {font-size:36px}
h2,.h2 {font-size:30px}
h3,.h3 {font-size:22px}
h4,.h4 {font-size:18px}
h5,.h5 {font-size:14px}
h6,.h6 {font-size:12px}
h1.mm {
font-size:1.3em;
margin: 14px 0 10px 0;
font-weight: 200;
letter-spacing: 1px;
color:#A5A5A5;
vertical-align: middle;
}
h1.mm i{font-size:1em;position:relative;top:3px; color: #83c849;margin:0;padding:0;}
.green {
color: #83c849;
}
h3.module-title{margin-top:14px;}
p {margin:0 0 10px}
.lead {margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}
@media (min-width: 768px) {.lead {font-size:21px}
}
small,.small {font-size:85%}
cite {font-style:normal}
.mr{margin-right:10px;}
mark,.mark {padding:.2em;background-color:#fcf8e3}
.text-left {text-align:left}
.text-right {text-align:right}
.text-center {text-align:center}
.text-justify {text-align:justify}
.text-nowrap {white-space:nowrap}
.text-lowercase {text-transform:lowercase}
.text-uppercase {text-transform:uppercase}
.text-capitalize {text-transform:capitalize}
.text-muted {color:#777}
.text-mutedl {color:#b8b8b8}
.text-primary {color:#428bca}
a.text-primary:hover {color:#3071a9}
.text-success {color:#3c763d}
a.text-success:hover {color:#2b542c}
.text-info {color:#31708f}
a.text-info:hover {color:#245269}
.text-warning {color:#8a6d3b}
a.text-warning:hover {color:#66512c}
.text-danger {color:#a94442}
a.text-danger:hover {color:#843534}
.bg-primary {color:#fff;background-color:#428bca}
a.bg-primary:hover {background-color:#3071a9}
.bg-success {background-color:#dff0d8}
a.bg-success:hover {background-color:#c1e2b3}
.bg-info {background-color:#d9edf7}
a.bg-info:hover {background-color:#afd9ee}
.bg-warning {background-color:#fcf8e3}
a.bg-warning:hover {background-color:#f7ecb5}
.bg-danger {background-color:#f2dede}
a.bg-danger:hover {background-color:#e4b9b9}
.page-header {padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}
ul,ol {margin-top:0;margin-bottom:10px}
ul ul,ol ul,ul ol,ol ol {margin-bottom:0}
.list-unstyled {padding-left:0;list-style:none}
.list-inline {padding-left:0;margin-left:-5px;list-style:none}
.list-inline>li {display:inline-block;padding-right:5px;padding-left:5px}
dl {margin-top:0;margin-bottom:20px}
dt,dd {line-height:1.42857143}
dt {font-weight:bold}
dd {margin-left:0}
@media (min-width: 768px) {.dl-horizontal dt {float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}
.dl-horizontal dd {margin-left:180px}
}
abbr[title],abbr[data-original-title] {cursor:help;border-bottom:1px dotted #777}
.initialism {font-size:90%;text-transform:uppercase}
blockquote {padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}
blockquote p:last-child,blockquote ul:last-child,blockquote ol:last-child {margin-bottom:0}
blockquote footer,blockquote small,blockquote .small {display:block;font-size:80%;line-height:1.42857143;color:#777}
blockquote footer:before,blockquote small:before,blockquote .small:before {content:'\2014 \00A0'}
.blockquote-reverse,blockquote.pull-right {padding-right:15px;padding-left:0;text-align:right;border-right:5px solid #eee;border-left:0}
.blockquote-reverse footer:before,blockquote.pull-right footer:before,.blockquote-reverse small:before,blockquote.pull-right small:before,.blockquote-reverse .small:before,blockquote.pull-right .small:before {content:''}
.blockquote-reverse footer:after,blockquote.pull-right footer:after,.blockquote-reverse small:after,blockquote.pull-right small:after,.blockquote-reverse .small:after,blockquote.pull-right .small:after {content:'\00A0 \2014'}
blockquote:before,blockquote:after {content:""}
address {margin-bottom:20px;font-style:normal;line-height:1.42857143}
code,kbd,pre,samp {font-family:Menlo,Monaco,Consolas,"Courier New",monospace}
code {padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}
kbd {padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}
kbd kbd {padding:0;font-size:100%;-webkit-box-shadow:none;box-shadow:none}
pre {display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}
pre code {padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}
.pre-scrollable {max-height:340px;overflow-y:scroll}
.container {padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}
@media (min-width: 768px) {.container {width:750px}
}
@media (min-width: 992px) {.container {width:970px}
}
@media (min-width: 1200px) {.container {width:1170px}
}
.container-fluid {padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}
.row {margin-right:-15px;margin-left:-15px}
.col-xs-1,.col-sm-1,.col-md-1,.col-lg-1,.col-xs-2,.col-sm-2,.col-md-2,.col-lg-2,.col-xs-3,.col-sm-3,.col-md-3,.col-lg-3,.col-xs-4,.col-sm-4,.col-md-4,.col-lg-4,.col-xs-5,.col-sm-5,.col-md-5,.col-lg-5,.col-xs-6,.col-sm-6,.col-md-6,.col-lg-6,.col-xs-7,.col-sm-7,.col-md-7,.col-lg-7,.col-xs-8,.col-sm-8,.col-md-8,.col-lg-8,.col-xs-9,.col-sm-9,.col-md-9,.col-lg-9,.col-xs-10,.col-sm-10,.col-md-10,.col-lg-10,.col-xs-11,.col-sm-11,.col-md-11,.col-lg-11,.col-xs-12,.col-sm-12,.col-md-12,.col-lg-12 {position:relative;min-height:1px;padding-right:15px;padding-left:15px}
.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12 {float:left}
.col-xs-12 {width:100%}
.col-xs-11 {width:91.66666667%}
.col-xs-10 {width:83.33333333%}
.col-xs-9 {width:75%}
.col-xs-8 {width:66.66666667%}
.col-xs-7 {width:58.33333333%}
.col-xs-6 {width:50%}
.col-xs-5 {width:41.66666667%}
.col-xs-4 {width:33.33333333%}
.col-xs-3 {width:25%}
.col-xs-2 {width:16.66666667%}
.col-xs-1 {width:8.33333333%}
.col-xs-pull-12 {right:100%}
.col-xs-pull-11 {right:91.66666667%}
.col-xs-pull-10 {right:83.33333333%}
.col-xs-pull-9 {right:75%}
.col-xs-pull-8 {right:66.66666667%}
.col-xs-pull-7 {right:58.33333333%}
.col-xs-pull-6 {right:50%}
.col-xs-pull-5 {right:41.66666667%}
.col-xs-pull-4 {right:33.33333333%}
.col-xs-pull-3 {right:25%}
.col-xs-pull-2 {right:16.66666667%}
.col-xs-pull-1 {right:8.33333333%}
.col-xs-pull-0 {right:auto}
.col-xs-push-12 {left:100%}
.col-xs-push-11 {left:91.66666667%}
.col-xs-push-10 {left:83.33333333%}
.col-xs-push-9 {left:75%}
.col-xs-push-8 {left:66.66666667%}
.col-xs-push-7 {left:58.33333333%}
.col-xs-push-6 {left:50%}
.col-xs-push-5 {left:41.66666667%}
.col-xs-push-4 {left:33.33333333%}
.col-xs-push-3 {left:25%}
.col-xs-push-2 {left:16.66666667%}
.col-xs-push-1 {left:8.33333333%}
.col-xs-push-0 {left:auto}
.col-xs-offset-12 {margin-left:100%}
.col-xs-offset-11 {margin-left:91.66666667%}
.col-xs-offset-10 {margin-left:83.33333333%}
.col-xs-offset-9 {margin-left:75%}
.col-xs-offset-8 {margin-left:66.66666667%}
.col-xs-offset-7 {margin-left:58.33333333%}
.col-xs-offset-6 {margin-left:50%}
.col-xs-offset-5 {margin-left:41.66666667%}
.col-xs-offset-4 {margin-left:33.33333333%}
.col-xs-offset-3 {margin-left:25%}
.col-xs-offset-2 {margin-left:16.66666667%}
.col-xs-offset-1 {margin-left:8.33333333%}
.col-xs-offset-0 {margin-left:0}
@media (min-width: 768px) {.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12 {float:left}
.col-sm-12 {width:100%}
.col-sm-11 {width:91.66666667%}
.col-sm-10 {width:83.33333333%}
.col-sm-9 {width:75%}
.col-sm-8 {width:66.66666667%}
.col-sm-7 {width:58.33333333%}
.col-sm-6 {width:50%}
.col-sm-5 {width:41.66666667%}
.col-sm-4 {width:33.33333333%}
.col-sm-3 {width:25%}
.col-sm-2 {width:16.66666667%}
.col-sm-1 {width:8.33333333%}
.col-sm-pull-12 {right:100%}
.col-sm-pull-11 {right:91.66666667%}
.col-sm-pull-10 {right:83.33333333%}
.col-sm-pull-9 {right:75%}
.col-sm-pull-8 {right:66.66666667%}
.col-sm-pull-7 {right:58.33333333%}
.col-sm-pull-6 {right:50%}
.col-sm-pull-5 {right:41.66666667%}
.col-sm-pull-4 {right:33.33333333%}
.col-sm-pull-3 {right:25%}
.col-sm-pull-2 {right:16.66666667%}
.col-sm-pull-1 {right:8.33333333%}
.col-sm-pull-0 {right:auto}
.col-sm-push-12 {left:100%}
.col-sm-push-11 {left:91.66666667%}
.col-sm-push-10 {left:83.33333333%}
.col-sm-push-9 {left:75%}
.col-sm-push-8 {left:66.66666667%}
.col-sm-push-7 {left:58.33333333%}
.col-sm-push-6 {left:50%}
.col-sm-push-5 {left:41.66666667%}
.col-sm-push-4 {left:33.33333333%}
.col-sm-push-3 {left:25%}
.col-sm-push-2 {left:16.66666667%}
.col-sm-push-1 {left:8.33333333%}
.col-sm-push-0 {left:auto}
.col-sm-offset-12 {margin-left:100%}
.col-sm-offset-11 {margin-left:91.66666667%}
.col-sm-offset-10 {margin-left:83.33333333%}
.col-sm-offset-9 {margin-left:75%}
.col-sm-offset-8 {margin-left:66.66666667%}
.col-sm-offset-7 {margin-left:58.33333333%}
.col-sm-offset-6 {margin-left:50%}
.col-sm-offset-5 {margin-left:41.66666667%}
.col-sm-offset-4 {margin-left:33.33333333%}
.col-sm-offset-3 {margin-left:25%}
.col-sm-offset-2 {margin-left:16.66666667%}
.col-sm-offset-1 {margin-left:8.33333333%}
.col-sm-offset-0 {margin-left:0}
}
@media (min-width: 992px) {.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12 {float:left}
.col-md-12 {width:100%}
.col-md-11 {width:91.66666667%}
.col-md-10 {width:83.33333333%}
.col-md-9 {width:75%}
.col-md-8 {width:66.66666667%}
.col-md-7 {width:58.33333333%}
.col-md-6 {width:50%}
.col-md-5 {width:41.66666667%}
.col-md-4 {width:33.33333333%}
.col-md-3 {width:25%}
.col-md-2 {width:16.66666667%}
.col-md-1 {width:8.33333333%}
.col-md-pull-12 {right:100%}
.col-md-pull-11 {right:91.66666667%}
.col-md-pull-10 {right:83.33333333%}
.col-md-pull-9 {right:75%}
.col-md-pull-8 {right:66.66666667%}
.col-md-pull-7 {right:58.33333333%}
.col-md-pull-6 {right:50%}
.col-md-pull-5 {right:41.66666667%}
.col-md-pull-4 {right:33.33333333%}
.col-md-pull-3 {right:25%}
.col-md-pull-2 {right:16.66666667%}
.col-md-pull-1 {right:8.33333333%}
.col-md-pull-0 {right:auto}
.col-md-push-12 {left:100%}
.col-md-push-11 {left:91.66666667%}
.col-md-push-10 {left:83.33333333%}
.col-md-push-9 {left:75%}
.col-md-push-8 {left:66.66666667%}
.col-md-push-7 {left:58.33333333%}
.col-md-push-6 {left:50%}
.col-md-push-5 {left:41.66666667%}
.col-md-push-4 {left:33.33333333%}
.col-md-push-3 {left:25%}
.col-md-push-2 {left:16.66666667%}
.col-md-push-1 {left:8.33333333%}
.col-md-push-0 {left:auto}
.col-md-offset-12 {margin-left:100%}
.col-md-offset-11 {margin-left:91.66666667%}
.col-md-offset-10 {margin-left:83.33333333%}
.col-md-offset-9 {margin-left:75%}
.col-md-offset-8 {margin-left:66.66666667%}
.col-md-offset-7 {margin-left:58.33333333%}
.col-md-offset-6 {margin-left:50%}
.col-md-offset-5 {margin-left:41.66666667%}
.col-md-offset-4 {margin-left:33.33333333%}
.col-md-offset-3 {margin-left:25%}
.col-md-offset-2 {margin-left:16.66666667%}
.col-md-offset-1 {margin-left:8.33333333%}
.col-md-offset-0 {margin-left:0}
}
@media (min-width: 1200px) {.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12 {float:left}
.col-lg-12 {width:100%}
.col-lg-11 {width:91.66666667%}
.col-lg-10 {width:83.33333333%}
.col-lg-9 {width:75%}
.col-lg-8 {width:66.66666667%}
.col-lg-7 {width:58.33333333%}
.col-lg-6 {width:50%}
.col-lg-5 {width:41.66666667%}
.col-lg-4 {width:33.33333333%}
.col-lg-3 {width:25%}
.col-lg-2 {width:16.66666667%}
.col-lg-1 {width:8.33333333%}
.col-lg-pull-12 {right:100%}
.col-lg-pull-11 {right:91.66666667%}
.col-lg-pull-10 {right:83.33333333%}
.col-lg-pull-9 {right:75%}
.col-lg-pull-8 {right:66.66666667%}
.col-lg-pull-7 {right:58.33333333%}
.col-lg-pull-6 {right:50%}
.col-lg-pull-5 {right:41.66666667%}
.col-lg-pull-4 {right:33.33333333%}
.col-lg-pull-3 {right:25%}
.col-lg-pull-2 {right:16.66666667%}
.col-lg-pull-1 {right:8.33333333%}
.col-lg-pull-0 {right:auto}
.col-lg-push-12 {left:100%}
.col-lg-push-11 {left:91.66666667%}
.col-lg-push-10 {left:83.33333333%}
.col-lg-push-9 {left:75%}
.col-lg-push-8 {left:66.66666667%}
.col-lg-push-7 {left:58.33333333%}
.col-lg-push-6 {left:50%}
.col-lg-push-5 {left:41.66666667%}
.col-lg-push-4 {left:33.33333333%}
.col-lg-push-3 {left:25%}
.col-lg-push-2 {left:16.66666667%}
.col-lg-push-1 {left:8.33333333%}
.col-lg-push-0 {left:auto}
.col-lg-offset-12 {margin-left:100%}
.col-lg-offset-11 {margin-left:91.66666667%}
.col-lg-offset-10 {margin-left:83.33333333%}
.col-lg-offset-9 {margin-left:75%}
.col-lg-offset-8 {margin-left:66.66666667%}
.col-lg-offset-7 {margin-left:58.33333333%}
.col-lg-offset-6 {margin-left:50%}
.col-lg-offset-5 {margin-left:41.66666667%}
.col-lg-offset-4 {margin-left:33.33333333%}
.col-lg-offset-3 {margin-left:25%}
.col-lg-offset-2 {margin-left:16.66666667%}
.col-lg-offset-1 {margin-left:8.33333333%}
.col-lg-offset-0 {margin-left:0}
}
table {background-color:transparent}
th {text-align:left}
.table {width:100%;max-width:100%;margin-bottom:20px}
.table>thead>tr>th,.table>tbody>tr>th,.table>tfoot>tr>th,.table>thead>tr>td,.table>tbody>tr>td,.table>tfoot>tr>td {padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}
.table>thead>tr>th {vertical-align:bottom;border-bottom:2px solid #ddd}
.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>th,.table>caption+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>td,.table>thead:first-child>tr:first-child>td {border-top:0}
.table>tbody+tbody {border-top:2px solid #ddd}
.table .table {background-color:#fff}
.table-condensed>thead>tr>th,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>tbody>tr>td,.table-condensed>tfoot>tr>td {padding:5px}
.table-bordered {border:1px solid #ddd}
.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td {border:1px solid #ddd}
.table-bordered>thead>tr>th,.table-bordered>thead>tr>td {border-bottom-width:2px}
.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th {background-color:#f9f9f9}
.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th {background-color:#f5f5f5}
table col[class*="col-"] {position:static;display:table-column;float:none}
table td[class*="col-"],table th[class*="col-"] {position:static;display:table-cell;float:none}
.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th {background-color:#f5f5f5}
.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover,.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr.active:hover>th {background-color:#e8e8e8}
.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th {background-color:#dff0d8}
.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr.success:hover>th {background-color:#d0e9c6}
.table>thead>tr>td.info,.table>tbody>tr>td.info,.table>tfoot>tr>td.info,.table>thead>tr>th.info,.table>tbody>tr>th.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>tbody>tr.info>td,.table>tfoot>tr.info>td,.table>thead>tr.info>th,.table>tbody>tr.info>th,.table>tfoot>tr.info>th {background-color:#d9edf7}
.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover,.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr.info:hover>th {background-color:#c4e3f3}
.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th {background-color:#fcf8e3}
.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr.warning:hover>th {background-color:#faf2cc}
.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th {background-color:#f2dede}
.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr.danger:hover>th {background-color:#ebcccc}
@media screen and (max-width: 767px) {.table-responsive {width:100%;margin-bottom:15px;overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}
.table-responsive>.table {margin-bottom:0}
.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td {white-space:nowrap}
.table-responsive>.table-bordered {border:0}
.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child {border-left:0}
.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child {border-right:0}
.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td {border-bottom:0}
}
fieldset {min-width:0;padding:0;margin:0;border:0}
legend {display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}
label {display:inline-block;max-width:100%;margin-bottom:5px;font-weight:bold}
input[type="search"] {-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
input[type="radio"],input[type="checkbox"] {margin:4px 0 0;margin-top:1px \9;line-height:normal}
input[type="file"] {display:block}
input[type="range"] {display:block;width:100%}
select[multiple],select[size] {height:auto}
input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus {outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}
output {display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}
.form-control {display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}
.form-control:focus {border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}
.form-control::-moz-placeholder {color:#777;opacity:1}
.form-control:-ms-input-placeholder {color:#777}
.form-control::-webkit-input-placeholder {color:#777}
.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control {cursor:not-allowed;background-color:#eee;opacity:1}
textarea.form-control {height:auto}
input[type="search"] {-webkit-appearance:none}
input[type="date"],input[type="time"],input[type="datetime-local"],input[type="month"] {line-height:34px;line-height:1.42857143 \0}
input[type="date"].input-sm,input[type="time"].input-sm,input[type="datetime-local"].input-sm,input[type="month"].input-sm {line-height:30px}
input[type="date"].input-lg,input[type="time"].input-lg,input[type="datetime-local"].input-lg,input[type="month"].input-lg {line-height:46px}
.form-group {margin-bottom:15px}
.radio,.checkbox {position:relative;display:block;min-height:20px;margin-top:10px;margin-bottom:10px}
.radio label,.checkbox label {padding-left:20px;margin-bottom:0;font-weight:normal;cursor:pointer}
.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"] {position:absolute;margin-top:4px \9;margin-left:-20px}
.radio+.radio,.checkbox+.checkbox {margin-top:-5px}
.radio-inline,.checkbox-inline {display:inline-block;padding-left:20px;margin-bottom:0;font-weight:normal;vertical-align:middle;cursor:pointer}
.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline {margin-top:0;margin-left:10px}
input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"].disabled,input[type="checkbox"].disabled,fieldset[disabled] input[type="radio"],fieldset[disabled] input[type="checkbox"] {cursor:not-allowed}
.radio-inline.disabled,.checkbox-inline.disabled,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox-inline {cursor:not-allowed}
.radio.disabled label,.checkbox.disabled label,fieldset[disabled] .radio label,fieldset[disabled] .checkbox label {cursor:not-allowed}
.form-control-static {padding-top:7px;padding-bottom:7px;margin-bottom:0}
.form-control-static.input-lg,.form-control-static.input-sm {padding-right:0;padding-left:0}
.input-sm,.form-horizontal .form-group-sm .form-control {height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}
select.input-sm {height:30px;line-height:30px}
textarea.input-sm,select[multiple].input-sm {height:auto}
.input-lg,.form-horizontal .form-group-lg .form-control {height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}
select.input-lg {height:46px;line-height:46px}
textarea.input-lg,select[multiple].input-lg {height:auto}
.has-feedback {position:relative}
.has-feedback .form-control {padding-right:42.5px}
.form-control-feedback {position:absolute;top:25px;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center}
.input-lg+.form-control-feedback {width:46px;height:46px;line-height:46px}
.input-sm+.form-control-feedback {width:30px;height:30px;line-height:30px}
.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline {color:#3c763d}
.has-success .form-control {border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}
.has-success .form-control:focus {border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}
.has-success .input-group-addon {color:#3c763d;background-color:#dff0d8;border-color:#3c763d}
.has-success .form-control-feedback {color:#3c763d}
.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline {color:#8a6d3b}
.has-warning .form-control {border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}
.has-warning .form-control:focus {border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}
.has-warning .input-group-addon {color:#8a6d3b;background-color:#fcf8e3;border-color:#8a6d3b}
.has-warning .form-control-feedback {color:#8a6d3b}
.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline {color:#a94442}
.has-error .form-control {border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}
.has-error .form-control:focus {border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}
.has-error .input-group-addon {color:#a94442;background-color:#f2dede;border-color:#a94442}
.has-error .form-control-feedback {color:#a94442}
.has-feedback label.sr-only ~ .form-control-feedback {top:0}
.help-block {display:block;margin-top:5px;margin-bottom:10px;color:#737373}
@media (min-width: 768px) {.form-inline .form-group {display:inline-block;margin-bottom:0;vertical-align:middle}
.form-inline .form-control {display:inline-block;width:auto;vertical-align:middle}
.form-inline .input-group {display:inline-table;vertical-align:middle}
.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn,.form-inline .input-group .form-control {width:auto}
.form-inline .input-group>.form-control {width:100%}
.form-inline .control-label {margin-bottom:0;vertical-align:middle}
.form-inline .radio,.form-inline .checkbox {display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}
.form-inline .radio label,.form-inline .checkbox label {padding-left:0}
.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"] {position:relative;margin-left:0}
.form-inline .has-feedback .form-control-feedback {top:0}
}
.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline {padding-top:7px;margin-top:0;margin-bottom:0}
.form-horizontal .radio,.form-horizontal .checkbox {min-height:27px}
.form-horizontal .form-group {margin-right:-15px;margin-left:-15px}
@media (min-width: 768px) {.form-horizontal .control-label {padding-top:7px;margin-bottom:0;text-align:right}
}
.form-horizontal .has-feedback .form-control-feedback {top:0;right:15px}
@media (min-width: 768px) {.form-horizontal .form-group-lg .control-label {padding-top:14.3px}
}
@media (min-width: 768px) {.form-horizontal .form-group-sm .control-label {padding-top:6px}
}
.nav {padding-left:0;margin-bottom:0;list-style:none}
.nav>li {position:relative;display:block}
.nav>li>a {position:relative;display:block;padding:10px 15px;color:#8a8a8a;}
.header>.nav>li>a {border-right:1px solid #e5e5e5;}
.nav>li>a.active {background:#f7f8fb;}
.nav>li>a:hover,.nav>li>a:focus {text-decoration:none;background-color:#eee}
.nav>li.disabled>a {color:#777}
.nav>li.disabled>a:hover,.nav>li.disabled>a:focus {color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}
.nav .open>a,.nav .open>a:hover,.nav .open>a:focus {background-color:#eee;border-color:#428bca}
.nav .nav-divider {height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}
.nav>li>a>img {max-width:none}
.nav-tabs {border-bottom:1px solid #ddd}
.nav-tabs>li {float:left;margin-bottom:0}
.nav-tabs>li>a {margin-right:0;line-height:1.42857143;border:1px solid transparent;border-right:1px solid #CCC !important;border-radius: 0}
.nav-tabs>li.active>a{border-right:1px solid #CCC !important;}
.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus {color:#333;cursor:default;background-color:#fff;border-bottom-color:transparent;border-right:1px solid #CCC !important;}
.nav-tabs.nav-justified {width:100%;border-bottom:0}
.nav-tabs.nav-justified>li {float:none}
.nav-tabs.nav-justified>li>a {margin-bottom:5px;text-align:center}
.nav-tabs.nav-justified>.dropdown .dropdown-menu {top:auto;left:auto}
@media (min-width: 768px) {.nav-tabs.nav-justified > li {display:table-cell;width:1%}
.nav-tabs.nav-justified>li>a {margin-bottom:0}
}
.nav-tabs.nav-justified>li>a {margin-right:0;border-radius:4px}
.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus {border:1px solid #ddd}
@media (min-width: 768px) {.nav-tabs.nav-justified > li > a {border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}
.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus {border-bottom-color:#fff}
}
.nav-pills>li {float:left}
.nav-pills>li>a {border-radius:4px}
.nav-pills>li+li {margin-left:2px}
.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus {color:#fff;background-color:#428bca}
.nav-stacked>li {float:none}
.nav-stacked>li+li {margin-top:2px;margin-left:0}
.nav-justified {width:100%}
.nav-justified>li {float:none}
.nav-justified>li>a {margin-bottom:5px;text-align:center}
.nav-justified>.dropdown .dropdown-menu {top:auto;left:auto}
@media (min-width: 768px) {.nav-justified > li {display:table-cell;width:1%}
.nav-justified>li>a {margin-bottom:0}
}
.nav-tabs-justified {border-bottom:0}
.nav-tabs-justified>li>a {margin-right:0;border-radius:4px}
.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus {border:1px solid #ddd}
@media (min-width: 768px) {.nav-tabs-justified > li > a {border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}
.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus {border-bottom-color:#fff}
}
.tab-content>.tab-pane {display:none}
.tab-content>.active {display:block}
.nav-tabs .dropdown-menu {margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}
.navbar {position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}
@media (min-width: 768px) {.navbar {border-radius:4px}
}
@media (min-width: 768px) {.navbar-header {float:left}
}
.navbar-collapse {padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}
.navbar-collapse.in {overflow-y:auto}
@media (min-width: 768px) {.navbar-collapse {width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}
.navbar-collapse.collapse {display:block !important;height:auto !important;padding-bottom:0;overflow:visible !important}
.navbar-collapse.in {overflow-y:visible}
.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse {padding-right:0;padding-left:0}
}
.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse {max-height:340px}
@media (max-width: 480px) and (orientation: landscape) {.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse {max-height:200px}
}
.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse {margin-right:-15px;margin-left:-15px}
@media (min-width: 768px) {.container > .navbar-header,.container-fluid > .navbar-header,.container > .navbar-collapse,.container-fluid > .navbar-collapse {margin-right:0;margin-left:0}
}
.navbar-static-top {z-index:1000;border-width:0 0 1px}
@media (min-width: 768px) {.navbar-static-top {border-radius:0}
}
.navbar-fixed-top,.navbar-fixed-bottom {position:fixed;right:0;left:0;z-index:1030;-webkit-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}
@media (min-width: 768px) {.navbar-fixed-top,.navbar-fixed-bottom {border-radius:0}
}
.navbar-fixed-top {top:0;border-width:0 0 1px}
.navbar-fixed-bottom {bottom:0;margin-bottom:0;border-width:1px 0 0}
.navbar-brand {float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px}
.navbar-brand:hover,.navbar-brand:focus {text-decoration:none}
@media (min-width: 768px) {.navbar > .container .navbar-brand,.navbar > .container-fluid .navbar-brand {margin-left:-15px}
}
.navbar-toggle {position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}
.navbar-toggle:focus {outline:0}
.navbar-toggle .icon-bar {display:block;width:22px;height:2px;border-radius:1px}
.navbar-toggle .icon-bar+.icon-bar {margin-top:4px}
@media (min-width: 768px) {.navbar-toggle {display:none}
}
.navbar-nav {margin:7.5px -15px}
.navbar-nav>li>a {padding-top:10px;padding-bottom:10px;line-height:20px}
@media (max-width: 767px) {.navbar-nav .open .dropdown-menu {position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none}
.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header {padding:5px 15px 5px 25px}
.navbar-nav .open .dropdown-menu>li>a {line-height:20px}
.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus {background-image:none}
}
@media (min-width: 768px) {.navbar-nav {float:left;margin:0}
.navbar-nav>li {float:left}
.navbar-nav>li>a {padding-top:15px;padding-bottom:15px}
.navbar-nav.navbar-right:last-child {margin-right:-15px}
}
@media (min-width: 768px) {.navbar-left {float:left !important}
.navbar-right {float:right !important}
}
.navbar-form {padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}
@media (min-width: 768px) {.navbar-form .form-group {display:inline-block;margin-bottom:0;vertical-align:middle}
.navbar-form .form-control {display:inline-block;width:auto;vertical-align:middle}
.navbar-form .input-group {display:inline-table;vertical-align:middle}
.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn,.navbar-form .input-group .form-control {width:auto}
.navbar-form .input-group>.form-control {width:100%}
.navbar-form .control-label {margin-bottom:0;vertical-align:middle}
.navbar-form .radio,.navbar-form .checkbox {display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}
.navbar-form .radio label,.navbar-form .checkbox label {padding-left:0}
.navbar-form .radio input[type="radio"],.navbar-form .checkbox input[type="checkbox"] {position:relative;margin-left:0}
.navbar-form .has-feedback .form-control-feedback {top:0}
}
@media (max-width: 767px) {.navbar-form .form-group {margin-bottom:5px}
}
@media (min-width: 768px) {.navbar-form {width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}
.navbar-form.navbar-right:last-child {margin-right:-15px}
}
.navbar-nav>li>.dropdown-menu {margin-top:0;border-top-left-radius:0;border-top-right-radius:0}
.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu {border-bottom-right-radius:0;border-bottom-left-radius:0}
.navbar-btn {margin-top:8px;margin-bottom:8px}
.navbar-btn.btn-sm {margin-top:10px;margin-bottom:10px}
.navbar-btn.btn-xs {margin-top:14px;margin-bottom:14px}
.navbar-text {margin-top:15px;margin-bottom:15px}
@media (min-width: 768px) {.navbar-text {float:left;margin-right:15px;margin-left:15px}
.navbar-text.navbar-right:last-child {margin-right:0}
}
.navbar-default {background-color:#f8f8f8;border-color:#e7e7e7}
.navbar-default .navbar-brand {color:#777}
.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus {color:#5e5e5e;background-color:transparent}
.navbar-default .navbar-text {color:#777}
.navbar-default .navbar-nav>li>a {color:#777}
.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus {color:#333;background-color:transparent}
.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus {color:#555;background-color:#e7e7e7}
.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus {color:#ccc;background-color:transparent}
.navbar-default .navbar-toggle {border-color:#ddd}
.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus {background-color:#ddd}
.navbar-default .navbar-toggle .icon-bar {background-color:#888}
.navbar-default .navbar-collapse,.navbar-default .navbar-form {border-color:#e7e7e7}
.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus {color:#555;background-color:#e7e7e7}
@media (max-width: 767px) {.navbar-default .navbar-nav .open .dropdown-menu > li > a {color:#777}
.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus {color:#333;background-color:transparent}
.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus {color:#555;background-color:#e7e7e7}
.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus {color:#ccc;background-color:transparent}
}
.navbar-default .navbar-link {color:#777}
.navbar-default .navbar-link:hover {color:#333}
.navbar-default .btn-link {color:#777}
.navbar-default .btn-link:hover,.navbar-default .btn-link:focus {color:#333}
.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:hover,.navbar-default .btn-link[disabled]:focus,fieldset[disabled] .navbar-default .btn-link:focus {color:#ccc}
.navbar-inverse {background-color:#222;border-color:#080808}
.navbar-inverse .navbar-brand {color:#777}
.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus {color:#fff;background-color:transparent}
.navbar-inverse .navbar-text {color:#777}
.navbar-inverse .navbar-nav>li>a {color:#777}
.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus {color:#fff;background-color:transparent}
.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus {color:#fff;background-color:#080808}
.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus {color:#444;background-color:transparent}
.navbar-inverse .navbar-toggle {border-color:#333}
.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus {background-color:#333}
.navbar-inverse .navbar-toggle .icon-bar {background-color:#fff}
.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form {border-color:#101010}
.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus {color:#fff;background-color:#080808}
@media (max-width: 767px) {.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {border-color:#080808}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {background-color:#080808}
.navbar-inverse .navbar-nav .open .dropdown-menu>li>a {color:#777}
.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus {color:#fff;background-color:transparent}
.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus {color:#fff;background-color:#080808}
.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus {color:#444;background-color:transparent}
}
.navbar-inverse .navbar-link {color:#777}
.navbar-inverse .navbar-link:hover {color:#fff}
.navbar-inverse .btn-link {color:#777}
.navbar-inverse .btn-link:hover,.navbar-inverse .btn-link:focus {color:#fff}
.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:hover,.navbar-inverse .btn-link[disabled]:focus,fieldset[disabled] .navbar-inverse .btn-link:focus {color:#444}
@font-face {font-family:'icon';src:url('../fonts/icon.eot');src:url('../fonts/icon-.eot#iefix') format('embedded-opentype'),url('../fonts/icon.ttf') format('truetype'),url('../fonts/icon.woff') format('woff'),url('../fonts/icon.svg#icon') format('svg');font-weight:normal;font-style:normal}
.i {display:inline-block;font-family:'icon';font-style:normal;font-weight:normal;line-height:1;vertical-align:-5%;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
.i-move:before {content:"\e600"}
.i-move-vertical:before {content:"\e601"}
.i-resize-enlarge:before {content:"\e602"}
.i-resize-shrink:before {content:"\e603"}
.i-move-horizontal:before {content:"\e604"}
.i-download:before {content:"\e605"}
.i-upload:before {content:"\e606"}
.i-cloud-download:before {content:"\e607"}
.i-cloud-upload:before {content:"\e608"}
.i-circleleft:before {content:"\e609"}
.i-circledown:before {content:"\e60a"}
.i-circleup:before {content:"\e60b"}
.i-circleright:before {content:"\e60c"}
.i-home:before {content:"\e60d"}
.i-download3:before {content:"\e60e"}
.i-pin:before {content:"\e60f"}
.i-pictures:before {content:"\e610"}
.i-share3:before {content:"\e611"}
.i-pencil2:before {content:"\e612"}
.i-mail2:before {content:"\e613"}
.i-support:before {content:"\e614"}
.i-asc:before {content:"\e615"}
.i-dsc:before {content:"\e616"}
.i-ok:before {content:"\e617"}
.i-error:before {content:"\e618"}
.i-expand:before {content:"\e619"}
.i-collapse:before {content:"\e61a"}
.i-screen:before {content:"\e61b"}
.i-phone3:before {content:"\e61c"}
.i-phone-portrait:before {content:"\e61d"}
.i-phone-landscape:before {content:"\e61e"}
.i-tablet:before {content:"\e61f"}
.i-tablet-landscape:before {content:"\e620"}
.i-laptop:before {content:"\e621"}
.i-cube:before {content:"\e622"}
.i-chart:before {content:"\e623"}
.i-graph:before {content:"\e624"}
.i-meter:before {content:"\e625"}
.i-heart2:before {content:"\e626"}
.i-star2:before {content:"\e627"}
.i-stack:before {content:"\e628"}
.i-tv:before {content:"\e629"}
.i-user2:before {content:"\e62a"}
.i-users2:before {content:"\e62b"}
.i-search2:before {content:"\e62c"}
.i-zoom-in2:before {content:"\e62d"}
.i-zoom-out2:before {content:"\e62e"}
.i-slider-v:before {content:"\e62f"}
.i-slider:before {content:"\e630"}
.i-stats:before {content:"\e631"}
.i-bars:before {content:"\e632"}
.i-arrow-up-left2:before {content:"\e633"}
.i-arrow-up2:before {content:"\e634"}
.i-arrow-up-right2:before {content:"\e635"}
.i-arrow-right2:before {content:"\e636"}
.i-arrow-down-right2:before {content:"\e637"}
.i-arrow-down-2:before {content:"\e638"}
.i-arrow-down-left-2:before {content:"\e639"}
.i-arrow-left2:before {content:"\e63a"}
.i-file-pdf:before {content:"\e63b"}
.i-file-openoffice:before {content:"\e63c"}
.i-file-word:before {content:"\e63d"}
.i-file-excel:before {content:"\e63e"}
.i-file-zip:before {content:"\e63f"}
.i-file-powerpoint:before {content:"\e640"}
.i-file-xml:before {content:"\e641"}
.i-file-css:before {content:"\e642"}
.i-video:before {content:"\e643"}
.i-settings:before {content:"\e644"}
.i-camera:before {content:"\e645"}
.i-tag:before {content:"\e646"}
.i-bulb:before {content:"\e647"}
.i-location:before {content:"\e648"}
.i-eye2:before {content:"\e649"}
.i-bubble:before {content:"\e64a"}
.i-mail:before {content:"\e64b"}
.i-paperplane:before {content:"\e64c"}
.i-data:before {content:"\e64d"}
.i-t-shirt:before {content:"\e64e"}
.i-lab:before {content:"\e64f"}
.i-calendar:before {content:"\e650"}
.i-earth:before {content:"\e651"}
.i-world:before {content:"\e652"}
.i-vynil:before {content:"\e653"}
.i-gauge:before {content:"\e654"}
.i-statistics:before {content:"\e655"}
.i-arrow-left3:before {content:"\e656"}
.i-arrow-down3:before {content:"\e657"}
.i-arrow-up3:before {content:"\e658"}
.i-arrow-right3:before {content:"\e659"}
.i-arrow-left4:before {content:"\e65a"}
.i-arrow-down4:before {content:"\e65b"}
.i-arrow-up4:before {content:"\e65c"}
.i-arrow-right4:before {content:"\e65d"}
.i-arrow-left5:before {content:"\e65e"}
.i-arrow-down5:before {content:"\e65f"}
.i-arrow-up5:before {content:"\e660"}
.i-arrow-right5:before {content:"\e661"}
.i-search:before {content:"\e662"}
.i-list:before {content:"\e663"}
.i-add-to-list:before {content:"\e664"}
.i-list2:before {content:"\e665"}
.i-play:before {content:"\e666"}
.i-pause:before {content:"\e667"}
.i-stop:before {content:"\e668"}
.i-backward:before {content:"\e669"}
.i-forward:before {content:"\e66a"}
.i-feed:before {content:"\e66b"}
.i-switch:before {content:"\e66c"}
.i-clock2:before {content:"\e66d"}
.i-health:before {content:"\e66e"}
.i-pencil:before {content:"\e66f"}
.i-minus2:before {content:"\e670"}
.i-plus2:before {content:"\e671"}
.i-stats:before {content:"\e672"}
.i-paperclip:before {content:"\e673"}
.i-keyboard:before {content:"\e674"}
.i-mic:before {content:"\e675"}
.i-heart:before {content:"\e676"}
.i-layout3:before {content:"\e677"}
.i-layout2:before {content:"\e678"}
.i-cloud:before {content:"\e679"}
.i-info:before {content:"\e67a"}
.i-question:before {content:"\e67b"}
.i-notification:before {content:"\e67c"}
.i-libreoffice:before {content:"\e67d"}
.i-headphones:before {content:"\e67e"}
.i-copy2:before {content:"\e67f"}
.i-copy3:before {content:"\e680"}
.i-paste:before {content:"\e681"}
.i-spinner:before {content:"\e682"}
.i-plus:before {content:"\e683"}
.i-minus:before {content:"\e684"}
.i-cancel:before {content:"\e685"}
.i-images:before {content:"\e686"}
.i-logout:before {content:"\e687"}
.i-login:before {content:"\e688"}
.i-infinity:before {content:"\e689"}
.i-docs:before {content:"\e68a"}
.i-landscape:before {content:"\e68b"}
.i-portrait:before {content:"\e68c"}
.i-share:before {content:"\e68d"}
.i-youtube:before {content:"\e68e"}
.i-checkmark:before {content:"\e68f"}
.i-notice:before {content:"\e690"}
.i-link:before {content:"\e691"}
.i-link2:before {content:"\e692"}
.i-popup:before {content:"\e693"}
.i-publish:before {content:"\e694"}
.i-browser:before {content:"\e695"}
.i-checkmark2:before {content:"\e696"}
.i-cross2:before {content:"\e697"}
.i-question2:before {content:"\e698"}
.i-info2:before {content:"\e699"}
.i-loop:before {content:"\e69a"}
.i-retweet:before {content:"\e69b"}
.i-arrow:before {content:"\e69c"}
.i-arrow2:before {content:"\e69d"}
.i-shuffle:before {content:"\e69e"}
.i-ccw:before {content:"\e69f"}
.i-cycle:before {content:"\e6a0"}
.i-cw:before {content:"\e6a1"}
.i-switch:before {content:"\e6a2"}
.i-back:before {content:"\e6a3"}
.i-layout:before {content:"\e6a4"}
.i-code:before {content:"\e6a5"}
.i-vcard:before {content:"\e6a6"}
.i-googleplus:before {content:"\e6a7"}
.i-facebook:before {content:"\e6a8"}
.i-twitter:before {content:"\e6a9"}
.i-rss:before {content:"\e6aa"}
.i-signal:before {content:"\e6ab"}
.i-flow-tree:before {content:"\e6ac"}
.i-domain3:before {content:"\e6ad"}
.i-trashcan:before {content:"\e6ae"}
.i-book:before {content:"\e6af"}
.i-bars:before {content:"\e6b0"}
.i-stopwatch:before {content:"\e6b1"}
.i-map2:before {content:"\e6b2"}
.i-checkmark3:before {content:"\e6b3"}
.i-sun:before {content:"\e6b4"}
.i-clip:before {content:"\e6b5"}
.i-study:before {content:"\e6b6"}
.i-music:before {content:"\e6b7"}
.i-params:before {content:"\e6b8"}
.i-stack3:before {content:"\e6b9"}
.i-arrow-down:before {content:"\e6ba"}
.i-arrow-down-left:before {content:"\e6bb"}
.i-arrow-down-right:before {content:"\e6bc"}
.i-arrow-left:before {content:"\e6bd"}
.i-arrow-right:before {content:"\e6be"}
.i-arrow-up-right:before {content:"\e6bf"}
.i-arrow-up:before {content:"\e6c0"}
.i-arrow-up-left:before {content:"\e6c1"}
.i-compass:before {content:"\e6c2"}
.i-users3:before {content:"\e6c3"}
.i-user3:before {content:"\e6c4"}
.i-camera2:before {content:"\e6c5"}
.i-file:before {content:"\e6c6"}
.i-file2:before {content:"\e6c7"}
.i-file-plus:before {content:"\e6c8"}
.i-file-minus:before {content:"\e6c9"}
.i-file-check:before {content:"\e6ca"}
.i-file-remove:before {content:"\e6cb"}
.i-file-copy:before {content:"\e6cc"}
.i-stack2:before {content:"\e6cd"}
.i-folder:before {content:"\e6ce"}
.i-folder-upload:before {content:"\e6cf"}
.i-folder-download:before {content:"\e6d0"}
.i-folder-minus:before {content:"\e6d1"}
.i-folder-plus:before {content:"\e6d2"}
.i-folder2:before {content:"\e6d3"}
.i-folder-open:before {content:"\e6d4"}
.i-tag2:before {content:"\e6d5"}
.i-cart:before {content:"\e6d6"}
.i-phone:before {content:"\e6d7"}
.i-phone2:before {content:"\e6d8"}
.i-local:before {content:"\e6d9"}
.i-alarm:before {content:"\e6da"}
.i-clock:before {content:"\e6db"}
.i-history:before {content:"\e6dc"}
.i-stopclock:before {content:"\e6dd"}
.i-rotate:before {content:"\e6de"}
.i-rotate2:before {content:"\e6df"}
.i-redo:before {content:"\e6e0"}
.i-undo:before {content:"\e6e1"}
.i-chat2:before {content:"\e6e2"}
.i-chat3:before {content:"\e6e3"}
.i-chat:before {content:"\e6e4"}
.i-data2:before {content:"\e6e5"}
.i-spin:before {content:"\e6e6"}
.i-health2:before {content:"\e6e7"}
.i-cog2:before {content:"\e6e8"}
.i-bulb:before {content:"\e6e9"}
.i-rating:before {content:"\e6ea"}
.i-rating2:before {content:"\e6eb"}
.i-rating3:before {content:"\e6ec"}
.i-grid:before {content:"\e6ed"}
.i-grid2:before {content:"\e6ee"}
.i-grid3:before {content:"\e6ef"}
.i-ellipsis:before {content:"\e6f0"}
.i-dot:before {content:"\e6f1"}
.i-dots:before {content:"\e6f2"}
.i-bar:before {content:"\e6f3"}
.i-bar2:before {content:"\e6f4"}
.i-bars3:before {content:"\e6f5"}
.i-menu:before {content:"\e6f6"}
.i-menu2:before {content:"\e6f7"}
.i-download2:before {content:"\e6f8"}
.i-upload2:before {content:"\e6f9"}
.i-eye:before {content:"\e6fa"}
.i-eye-slash:before {content:"\e6fb"}
.i-bookmark:before {content:"\e6fc"}
.i-up:before {content:"\e6fd"}
.i-right:before {content:"\e6fe"}
.i-down:before {content:"\e6ff"}
.i-left:before {content:"\e700"}
.i-check:before {content:"\e701"}
.i-checked:before {content:"\e702"}
.i-popout:before {content:"\e703"}
.i-newtab:before {content:"\e704"}
.i-map:before {content:"\e705"}
.i-layer:before {content:"\e706"}
.i-layer2:before {content:"\e707"}
.i-like:before {content:"\e708"}
.i-dislike:before {content:"\e709"}
.i-football:before {content:"\e70a"}
.i-hexagon-o:before {content:"\e70b"}
.i-hexagon:before {content:"\e70c"}
.i-hexagon2-o:before {content:"\e70d"}
.i-hexagon2:before {content:"\e70e"}
.i-circle:before {content:"\e70f"}
.i-circle-o:before {content:"\e711"}
.i-circle-sm:before {content:"\e710"}
.i-circle-sm-o:before {content:"\e712"}
@font-face {font-family:'Open Sans';font-style:normal;font-weight:300;src:local('Open Sans Light'),local('OpenSans-Light'),url('../fonts/opensans/opensans-light.woff') format('woff')}
@font-face {font-family:'Open Sans';font-style:normal;font-weight:400;src:local('Open Sans'),local('OpenSans'),url('../fonts/opensans/opensans.woff') format('woff')}
@font-face {font-family:'Open Sans';font-style:normal;font-weight:700;src:local('Open Sans Bold'),local('OpenSans-Bold'),url('../fonts/opensans/opensans-bold.woff') format('woff')}
html {}
body {font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif;color:#788288;background-color:transparent;-webkit-font-smoothing:antialiased;line-height:1.53846154}
*:focus {outline:0 !important}
.h1,.h2,.h3,.h4,.h5,.h6 {margin:0}
a {color:#3c4144;text-decoration:none}
a:hover,a:focus {color:#181a1c;text-decoration:none}
label {font-weight:normal}
small,.small {font-size:12px}
.badge,.label {font-weight:bold}
.badge {background-color:#b0bcd4}
.badge.up {position:relative;top:-10px;padding:3px 6px;margin-left:-10px}
.badge-sm {font-size:85%;padding:2px 5px !important}
.label-sm {padding-top:0;padding-bottom:0}
.badge-white {background-color:transparent;border:1px solid rgba(255,255,255,0.35);padding:2px 6px}
.badge-empty {background-color:transparent;border:1px solid rgba(0,0,0,0.15);color:inherit}
.caret-white {border-top-color:#fff;border-top-color:rgba(255,255,255,0.65)}
a:hover .caret-white {border-top-color:#fff}
.thumbnail {border-color:#eaeef1}
.popover-content {font-size:12px;line-height:1.5}
.progress-xs {height:6px}
.progress-sm {height:10px}
.progress-sm .progress-bar {font-size:10px;line-height:1em}
.progress,.progress-bar {-webkit-box-shadow:none;box-shadow:none}
.breadcrumb {background-color:#fff;border:1px solid #eaeef1;padding-left:10px;margin-bottom:10px}
.breadcrumb>li+li:before,.breadcrumb>.active {color:inherit}
.accordion-group,.accordion-inner {border-color:#eaeef1;border-radius:2px}
.alert {font-size:12px;box-shadow:inset 0 1px 0 rgba(255,255,255,0.2)}
.alert .close i {font-size:12px;font-weight:normal;display:block}
.form-control {border-color:#cbd5dd;border-radius:2px}
.form-control,.form-control:focus {-webkit-box-shadow:none;box-shadow:none}
.form-control:focus {border-color:#177bbb}
.input-s-sm {width:120px}
.input-s {width:200px}
.input-s-lg {width:250px}
.input-lg {height:45px}
.input-group-addon {border-color:#cbd5dd;background-color:#fcfcfd}
.list-group {border-radius:2px}
.list-group.no-radius .list-group-item {border-radius:0 !important}
.list-group.no-borders .list-group-item {border:none}
.list-group.no-border .list-group-item {border-width:1px 0}
.list-group.no-bg .list-group-item {background-color:transparent}
.list-group-item {border-color:#eaeef1;padding-right:15px}
a.list-group-item:hover,a.list-group-item:focus {background-color:#f9fafc}
.list-group-item.media {margin-top:0}
.list-group-item.active {color:#fff;border-color:#1ccacc !important;background-color:#1ccacc !important}
.list-group-item.active .text-muted {color:#91eff0}
.list-group-item.active a {color:#fff}
.list-group-alt .list-group-item:nth-child(2n+2) {background-color:rgba(0,0,0,0.02) !important}
.list-group-lg .list-group-item {padding-top:15px;padding-bottom:15px}
.list-group-sp .list-group-item {margin-bottom:5px;border-radius:3px}
.list-group-item>.badge {margin-right:0}
.list-group-item>.fa-chevron-right {float:right;margin-top:4px;margin-right:-5px}
.list-group-item>.fa-chevron-right+.badge {margin-right:5px}
.nav-pills.no-radius>li>a {border-radius:0}
.nav-pills>li.active>a {color:#fff !important;background-color:#1ccacc}
.nav>li>a:hover,.nav>li>a:focus {background-color:#f7f8fb}
.nav.nav-sm>li>a {padding:6px 8px}
.nav .avatar {width:30px;margin-top:-5px;margin-right:5px}
.nav .open>a,.nav .open>a:hover,.nav .open>a:focus {background-color:#f7f8fb}
.nav-tabs {border-color:#eaeef1}
.nav-tabs>li>a {border-radius:2px 2px 0 0;border-bottom-color:#eaeef1 !important}
.nav-tabs>li.active>a {border-color:#eaeef1 !important;border-bottom-color:#fff !important;border-right-color:#CCC !important;}
.pagination>li>a {border-color:#eaeef1}
.pagination>li>a:hover,.pagination>li>a:focus {border-color:#eaeef1;background-color:#f2f4f8}
.panel {border-radius:2px}
.panel.panel-default {border-color:#eaeef1}
.panel.panel-default>.panel-heading,.panel.panel-default>.panel-footer {border-color:#eaeef1}
.panel>.list-group .list-group-item:first-child {border-top:0}
.panel .list-group-item {border-color:#f3f5f7}
.panel.no-borders {border-width:0}
.panel.no-borders .panel-heading,.panel.no-borders .panel-footer {border-width:0}
.panel .table td,.panel .table th {padding:8px 15px;border-top:1px solid #eaeef1}
.panel .table thead>tr>th {border-bottom:1px solid #eaeef1}
.panel .table-striped>tbody>tr:nth-child(odd)>td,.panel .table-striped>tbody>tr:nth-child(odd)>th {background-color:#f9fafc}
.panel .table-striped>thead th {background-color:#f9fafc;border-right:1px solid #eaeef1}
.panel .table-striped>thead th:last-child {border-right:none}
.panel-heading {border-radius:2px 2px 0 0}
.panel-default .panel-heading {background-color:#f9fafc}
.panel-heading.no-border {margin:-1px -1px 0 -1px;border:none}
.panel-heading .nav {margin:-10px -15px}
.panel-heading .nav-tabs {margin:-11px -16px}
.panel-heading .nav-tabs.nav-justified {width:auto}
.panel-heading .nav-tabs>li>a {margin:0;padding-top:11px;padding-bottom:11px}
.panel-heading .list-group {background:transparent}
.panel-footer {border-color:#eaeef1;border-radius:0 0 2px 2px;background-color:#f9fafc}
.panel-group .panel-heading+.panel-collapse .panel-body {border-top:1px solid #eaedef}
.open {z-index:1050;position:relative}
.dropdown-menu {font-size:13px;border-radius:2px;-webkit-box-shadow:0 2px 6px rgba(0,0,0,0.1);box-shadow:0 2px 6px rgba(0,0,0,0.1);border:1px solid #ddd;border:1px solid rgba(0,0,0,0.1)}
.dropdown-menu.pull-left {left:100%}
.dropdown-menu>.panel {border:none;margin:-5px 0}
.dropdown-menu>li>a {padding:5px 15px}
.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus {background-image:none;filter:none;background-color:#f2f4f8 !important;color:#181a1c}
.dropdown-header {padding:5px 15px}
.dropdown-submenu {position:relative}
.dropdown-submenu:hover>a,.dropdown-submenu:focus>a {background-color:#f2f4f8 !important;color:#788288}
.dropdown-submenu:hover>.dropdown-menu,.dropdown-submenu:focus>.dropdown-menu {display:block}
.dropdown-submenu.pull-left {float:none !important}
.dropdown-submenu.pull-left>.dropdown-menu {left:-100%;margin-left:10px}
.dropdown-submenu .dropdown-menu {left:100%;top:0;margin-top:-6px;margin-left:-1px}
.dropup .dropdown-submenu>.dropdown-menu {top:auto;bottom:0}
.dropdown-select>li>a input {position:absolute;left:-9999em}
.carousel-control {width:40px;color:#999;text-shadow:none}
.carousel-control:hover,.carousel-control:focus {color:#ccc;text-decoration:none;opacity:0.9;filter:alpha(opacity=90)}
.carousel-control.left,.carousel-control.right {background-image:none;filter:none}
.carousel-control i {position:absolute;top:50%;left:50%;z-index:5;display:inline-block;width:20px;height:20px;margin-top:-10px;margin-left:-10px}
.carousel-indicators.out {bottom:-5px}
.carousel-indicators li {-webkit-transition:background-color .25s;transition:background-color .25s;background:#ddd;background-color:rgba(0,0,0,0.2);border:none}
.carousel-indicators .active {background:#f0f0f0;background-color:rgba(200,200,200,0.2);width:10px;height:10px;margin:1px}
.carousel.carousel-fade .item {-webkit-transition:opacity .25s;transition:opacity .25s;-webkit-backface-visibility:hidden;-moz-backface-visibility:hidden;backface-visibility:hidden;opacity:0;filter:alpha(opacity=0)}
.carousel.carousel-fade .active {opacity:1;filter:alpha(opacity=1)}
.carousel.carousel-fade .active.left,.carousel.carousel-fade .active.right {left:0;z-index:2;opacity:0;filter:alpha(opacity=0)}
.carousel.carousel-fade .next,.carousel.carousel-fade .prev {left:0;z-index:1}
.carousel.carousel-fade .carousel-control {z-index:3}
.col-lg-2-4 {position:relative;min-height:1px;padding-left:15px;padding-right:15px}
.col-0 {clear:left}
.row.no-gutter {margin-left:0;margin-right:0}
.no-gutter [class*="col"] {padding:0}
.modal-backdrop {background-color:#222733}
.modal-backdrop.in {opacity:0.8;filter:alpha(opacity=80)}
.modal-over {width:100%;height:100%;position:relative;background:#222733}
.modal-center {position:absolute;left:50%;top:50%}
.modal-content {-webkit-box-shadow:0 2px 10px rgba(0,0,0,0.25);box-shadow:0 2px 10px rgba(0,0,0,0.25)}
.icon-muted {color:#ccc}
.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form {border-color:transparent}
.navbar-fixed-top,.navbar-fixed-bottom {position:fixed !important}
.navbar-fixed-top+* {padding-top:50px}
.navbar-fixed-top.header-md+* {padding-top:60px}
.header,.footer {min-height:50px;padding:0 15px}
.header>p,.footer>p {margin-top:15px;display:inline-block}
.header>.btn,.header>.btn-group,.header>.btn-toolbar,.footer>.btn,.footer>.btn-group,.footer>.btn-toolbar {margin-top:10px}
.header>.btn-lg,.footer>.btn-lg {margin-top:0}
.header .nav-tabs,.footer .nav-tabs {border:none;margin-left:-15px;margin-right:-15px}
.header .nav-tabs>li a,.footer .nav-tabs>li a {border:none !important;border-radius:0;padding-top:15px;padding-bottom:15px;line-height:20px}
.header .nav-tabs>li a:hover,.header .nav-tabs>li a:focus,.footer .nav-tabs>li a:hover,.footer .nav-tabs>li a:focus {background-color:transparent}
.header .nav-tabs>li.active a,.footer .nav-tabs>li.active a {color:#788288}
.header .nav-tabs>li.active a,.header .nav-tabs>li.active a:hover,.footer .nav-tabs>li.active a,.footer .nav-tabs>li.active a:hover {background-color:#f2f4f8}
.header .nav-tabs.nav-white>li.active a,.header .nav-tabs.nav-white>li.active a:hover,.footer .nav-tabs.nav-white>li.active a,.footer .nav-tabs.nav-white>li.active a:hover {background-color:#fff}
.header.navbar,.footer.navbar {border-radius:0;border:none;margin-bottom:0;padding:0;position:relative;z-index:1000}
body.container {padding:0}
@media (orientation: landscape) {html.ios7.ipad > body {padding-bottom:20px}
}
@media (min-width: 768px) {body.container {-webkit-box-shadow:0 3px 60px rgba(0,0,0,0.3);box-shadow:0 3px 60px rgba(0,0,0,0.3);border-left:1px solid #cbd5dd;border-right:1px solid #cbd5dd}
.app,.app body {height:100%;overflow:hidden}
.app .hbox.stretch {height:100%}
.app .vbox>section,.app .vbox>footer {position:absolute}
.app .vbox.flex>section>section {overflow:auto}
.hbox {display:table;table-layout:fixed;border-spacing:0;width:100%}
.hbox>aside,.hbox>section {display:table-cell;vertical-align:top;height:100%;float:none}
.hbox>aside.show,.hbox>aside.hidden-sm,.hbox>section.show,.hbox>section.hidden-sm {display:table-cell !important}
.vbox {display:table;border-spacing:0;position:relative;height:100%;width:100%}
.vbox>section,.vbox>footer {top:0;bottom:0;width:100%}
.vbox>header ~ section {top:50px}
.vbox>header.header-md ~ section {top:60px}
.vbox>section.w-f {bottom:50px}
.vbox>section.w-f-md {bottom:60px}
.vbox>footer {top:auto;z-index:1000}
.vbox.flex>header,.vbox.flex>section,.vbox.flex>footer {position:inherit}
.vbox.flex>section {display:table-row;height:100%}
.vbox.flex>section>section {position:relative;height:100%;-webkit-overflow-scrolling:touch}
.ie .vbox.flex>section>section {display:table-cell}
.vbox.flex>section>section>section {position:absolute;top:0;bottom:0;left:0;right:0}
.aside-xs {width:60px}
.aside-sm {width:150px}
.aside {width:240px}
.aside-md {width:300px}
.aside-lg {width:300px}
.aside-xl {width:360px}
.aside-xxl {width:480px}
.header-md {min-height:60px}
.header-md .navbar-form {margin-top:15px;margin-bottom:15px}
.scrollable {-webkit-overflow-scrolling:touch}
::-webkit-scrollbar {width:10px;height:10px}
::-webkit-scrollbar-thumb {background-color:rgba(50,50,50,0.25);border:2px solid transparent;border-radius:10px;background-clip:padding-box}
::-webkit-scrollbar-thumb:hover {background-color:rgba(50,50,50,0.5)}
::-webkit-scrollbar-track {background-color:rgba(50,50,50,0.05)}
}
.scrollable {overflow-x:hidden;overflow-y:auto}
.no-touch .scrollable.hover {overflow-y:hidden}
.no-touch .scrollable.hover:hover {overflow:visible;overflow-y:auto}
.no-touch ::-webkit-scrollbar-button {width:10px;height:6px;background-color:rgba(50,50,50,0.05)}
.slimScrollBar {border-radius:5px;border:2px solid transparent;border-radius:10px;background-clip:padding-box !important}
@media print {html,body,.hbox,.vbox {height:auto}
.vbox>section,.vbox>footer {position:relative}
}
.navbar-header {position:relative}
.navbar-header>.btn {position:absolute;font-size:1.3em;padding:9px 16px;line-height:30px;left:0}
.navbar-header .navbar-brand+.btn {right:0;top:0;left:auto}
.navbar-brand {float:none;text-align:center;font-size:20px;font-weight:700;height:auto;line-height:50px;display:inline-block;padding:0 15px}
.navbar-brand:hover {text-decoration:none}
.navbar-brand img {max-height:20px;margin-top:-4px;vertical-align:middle}
.nav-primary li>a>i {margin:-8px -10px;line-height:36px;width:36px;float:left;margin-right:5px;text-align:center;position:relative;overflow:hidden}
.nav-primary li>a>i:before {position:relative;z-index:2}
.nav-primary ul.nav>li>a {padding:8px 15px;position:relative;-webkit-transition:background-color .2s ease-in-out 0s;transition:background-color .2s ease-in-out 0s}
.no-borders .nav-primary ul.nav>li>a {border-width:0 !important}
.nav-primary ul.nav>li>a>.badge {font-size:11px;padding:2px 5px 2px 4px;margin-top:2px}
.nav-primary ul.nav>li>a>.text-muted {margin:0 3px}
.nav-primary ul.nav>li>a.active .text {display:none}
.nav-primary ul.nav>li>a.active .text-active {display:inline-block !important}
.nav-primary ul.nav>li li a {font-weight:normal;text-transform:none;padding:5px 0 5px 45px;}
.nav-primary ul.nav>li.active>ul {display:block}
.nav-primary ul.nav ul {display:none}
.bg-black .nav-primary>ul.nav-main>li:hover>a,.bg-black .nav-primary>ul.nav-main>li:focus>a,.bg-black .nav-primary>ul.nav-main>li:active>a,.bg-black .nav-primary>ul.nav-main>li.active>a {background-color:#1aae88}
.nav-main li.active {background:#F2F4F8;}
@media (min-width: 768px) {.visible-nav-xs {display:none}
.nav-xs {width:70px}
.nav-xs .slimScrollDiv,.nav-xs .slim-scroll {overflow:visible !important}
.nav-xs .slimScrollBar,.nav-xs .slimScrollRail {display:none !important}
.nav-xs .scrollable {overflow:visible}
.nav-xs .nav-primary>ul>li>a {position:relative;padding:0;font-size:11px;text-align:center;height:50px;overflow-y:hidden;border:none}
.nav-xs .nav-primary>ul>li>a span {display:table-cell;vertical-align:middle;height:50px;width:70px;}
.nav-xs .nav-primary>ul>li>a span.pull-right {display:none !important}
.nav-xs .nav-primary>ul>li>a i {width:auto;float:none;display:block;font-size:16px;margin:0;line-height:50px;border:none !important;-webkit-transition:margin-top 0.2s;transition:margin-top 0.2s}
.nav-xs .nav-primary>ul>li>a i b {left:0 !important}
.nav-xs .nav-primary>ul>li>a .badge {position:absolute;right:10px;top:4px;z-index:3}
.nav-xs .nav-primary>ul>li:hover>a i,.nav-xs .nav-primary>ul>li:focus>a i,.nav-xs .nav-primary>ul>li:active>a i,.nav-xs .nav-primary>ul>li.active>a i {margin-top:-50px}
.nav-xs .nav-primary>ul ul {display:none !important;position:absolute;left:100%;top:0;z-index:1050;width:220px;-webkit-box-shadow:0 2px 6px rgba(0,0,0,0.1);box-shadow:0 2px 6px rgba(0,0,0,0.1);padding:5px 0 5px 0;}
.nav-xs .nav-primary>ul ul li a{padding:5px 0 5px 25px;}
.nav-xs .nav-primary li:hover>ul,.nav-xs .nav-primary li:focus>ul,.nav-xs .nav-primary li:active>ul {display:block !important}
.nav-xs.nav-xs-right .nav-primary>ul ul {left:auto;right:100%}
.nav-xs>.vbox>.header,.nav-xs>.vbox>.footer {padding:0 20px}
.nav-xs .hidden-nav-xs {display:none}
.nav-xs .visible-nav-xs {display:inherit}
.nav-xs .text-center-nav-xs {text-align:center}
.nav-xs .nav-user {padding-left:0;padding-right:0}
.nav-xs .nav-user .avatar {float:none !important;margin-right:0}
.nav-xs .nav-user .dropdown>a {display:block;text-align:center}
.nav-xs .navbar-header {float:none}
.nav-xs .navbar-brand {display:block;padding:0}
.nav-xs .navbar-brand img {margin-right:0}
.nav-xs .navbar {padding:0}
.header-md .navbar-brand {line-height:60px}
.header-md .navbar-brand img {max-height:30px}
.header-md .navbar-nav>li>a {padding:20px}
}
@media (max-width: 767px) {.navbar-fixed-top-xs {position:fixed !important;left:0;width:100%;z-index:1100}
.navbar-fixed-top-xs+* {padding-top:50px !important}
.nav-bar-fixed-bottom {position:fixed;left:0;bottom:0;width:100%;z-index:1100}
html,body {overflow-x:hidden;min-height:100%}
.open,.open body {height:100%}
.nav-primary .dropdown-menu {position:relative;float:none;left:0;margin-left:0;padding:0}
.nav-primary .dropdown-menu a {padding:15px;border-bottom:1px solid #eee}
.nav-primary .dropdown-menu li:last-child a {border-bottom:none}
.navbar-header {text-align:center}
.nav-user {margin:0;padding:15px}
.nav-user.open {display:inherit !important}
.nav-user .dropdown-menu {display:block;position:static;float:none}
.nav-user .dropdown>a {display:block;text-align:center;font-size:18px;padding-bottom:10px}
.nav-user .avatar {width:160px !important;float:none !important;display:block;margin:20px auto;padding:5px;background-color:rgba(255,255,255,0.1);position:relative}
.nav-user .avatar:before {content:"";position:absolute;left:5px;right:5px;bottom:5px;top:5px;border:4px solid #fff;border-radius:500px}
.nav-off-screen {display:block !important;position:absolute;left:0;top:0;bottom:0;width:75%;visibility:visible;overflow-x:hidden;overflow-y:auto;-webkit-overflow-scrolling:touch}
.nav-off-screen .nav-primary {display:block !important}
.nav-off-screen .navbar-fixed-top-xs {width:75%}
.nav-off-screen.push-right .navbar-fixed-top-xs {left:25%}
.nav-off-screen.push-right {left:auto;right:0}
.nav-off-screen.push-right+* {-webkit-transform:translate3d(-75%,0px,0px);transform:translate3d(-75%,0px,0px)}
.nav-off-screen+* {background-color:#f2f4f8;-webkit-transition:-webkit-transform 0.2s ease-in-out;-moz-transition:-moz-transform 0.2s ease-in-out;-o-transition:-o-transform 0.2s ease-in-out;transition:transform 0.2s ease-in-out;-webkit-transition-delay:0s;transition-delay:0s;-webkit-transform:translate3d(0px,0px,0px);transform:translate3d(0px,0px,0px);-webkit-backface-visibility:hidden;-moz-backface-visibility:hidden;backface-visibility:hidden;-webkit-transform:translate3d(75%,0px,0px);transform:translate3d(75%,0px,0px);overflow:hidden;position:absolute;width:100%;top:0px;bottom:0;left:0;right:0;z-index:2}
.nav-off-screen+* .nav-off-screen-block {display:block !important;position:absolute;left:0;right:0;top:0;bottom:0;z-index:1950}
.navbar+section .nav-off-screen {top:50px}
.navbar+section .nav-off-screen+* {top:50px}
.slimScrollDiv,.slim-scroll {overflow:visible !important;height:auto !important}
.slimScrollBar,.slimScrollRail {display:none !important}
}
.arrow {border-width:8px;z-index:10}
.arrow,.arrow:after {position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}
.arrow:after {border-width:7px;content:""}
.arrow.top {left:50%;margin-left:-8px;border-top-width:0;border-bottom-color:#eee;border-bottom-color:rgba(0,0,0,0.1);top:-8px}
.arrow.top:after {content:" ";top:1px;margin-left:-7px;border-top-width:0;border-bottom-color:#fff}
.arrow.right {top:50%;right:-8px;margin-top:-8px;border-right-width:0;border-left-color:#eee;border-left-color:rgba(0,0,0,0.1)}
.arrow.right:after {content:" ";right:1px;border-right-width:0;border-left-color:#fff;bottom:-7px}
.arrow.bottom {left:50%;margin-left:-8px;border-bottom-width:0;border-top-color:#eee;border-top-color:rgba(0,0,0,0.1);bottom:-8px}
.arrow.bottom:after {content:" ";bottom:1px;margin-left:-7px;border-bottom-width:0;border-top-color:#fff}
.arrow.left {top:50%;left:-8px;margin-top:-8px;border-left-width:0;border-right-color:#eee;border-right-color:rgba(0,0,0,0.1)}
.arrow.left:after {content:" ";left:1px;border-left-width:0;border-right-color:#fff;bottom:-7px}
.btn-link {color:#788288}
.btn-link.active {webkit-box-shadow:none;box-shadow:none}
.btn-default {color:#788288 !important;background-color:#fcfcfd;border-color:#d2dae1;border-bottom-color:#cbd5dd;-webkit-box-shadow:0 1px 1px rgba(90,90,90,0.1);box-shadow:0 1px 1px rgba(90,90,90,0.1)}
.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default {color:#788288 !important;background-color:#ebeef4;border-color:#b9c6d0}
.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default {background-image:none}
.btn-default.disabled,.btn-default.disabled:hover,.btn-default.disabled:focus,.btn-default.disabled:active,.btn-default.disabled.active,.btn-default[disabled],.btn-default[disabled]:hover,.btn-default[disabled]:focus,.btn-default[disabled]:active,.btn-default[disabled].active,fieldset[disabled] .btn-default,fieldset[disabled] .btn-default:hover,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:active,fieldset[disabled] .btn-default.active {background-color:#fcfcfd;border-color:#d2dae1}
.btn-default.btn-bg {border-color:rgba(0,0,0,0.1);background-clip:padding-box}
.btn-primary {color:#fff !important;background-color:#177bbb;border-color:#177bbb}
.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary {color:#fff !important;background-color:#146ca4;border-color:#136397}
.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary {background-image:none}
.btn-primary.disabled,.btn-primary.disabled:hover,.btn-primary.disabled:focus,.btn-primary.disabled:active,.btn-primary.disabled.active,.btn-primary[disabled],.btn-primary[disabled]:hover,.btn-primary[disabled]:focus,.btn-primary[disabled]:active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary:hover,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary.active {background-color:#177bbb;border-color:#177bbb}
.btn-success {color:#fff !important;background-color:#1aae88;border-color:#1aae88}
.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success {color:#fff !important;background-color:#179877;border-color:#158b6c}
.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success {background-image:none}
.btn-success.disabled,.btn-success.disabled:hover,.btn-success.disabled:focus,.btn-success.disabled:active,.btn-success.disabled.active,.btn-success[disabled],.btn-success[disabled]:hover,.btn-success[disabled]:focus,.btn-success[disabled]:active,.btn-success[disabled].active,fieldset[disabled] .btn-success,fieldset[disabled] .btn-success:hover,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:active,fieldset[disabled] .btn-success.active {background-color:#1aae88;border-color:#1aae88}
.btn-info {color:#fff !important;background-color:#1ccacc;border-color:#1ccacc}
.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info {color:#fff !important;background-color:#19b4b6;border-color:#17a6a8}
.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info {background-image:none}
.btn-info.disabled,.btn-info.disabled:hover,.btn-info.disabled:focus,.btn-info.disabled:active,.btn-info.disabled.active,.btn-info[disabled],.btn-info[disabled]:hover,.btn-info[disabled]:focus,.btn-info[disabled]:active,.btn-info[disabled].active,fieldset[disabled] .btn-info,fieldset[disabled] .btn-info:hover,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:active,fieldset[disabled] .btn-info.active {background-color:#1ccacc;border-color:#1ccacc}
.btn-warning {color:#fff !important;background-color:#fcc633;border-color:#fcc633}
.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning {color:#fff !important;background-color:#fcbf1a;border-color:#fbbb0b}
.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning {background-image:none}
.btn-warning.disabled,.btn-warning.disabled:hover,.btn-warning.disabled:focus,.btn-warning.disabled:active,.btn-warning.disabled.active,.btn-warning[disabled],.btn-warning[disabled]:hover,.btn-warning[disabled]:focus,.btn-warning[disabled]:active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning,fieldset[disabled] .btn-warning:hover,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:active,fieldset[disabled] .btn-warning.active {background-color:#fcc633;border-color:#fcc633}
.btn-danger {color:#fff !important;background-color:#e33244;border-color:#e33244}
.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger {color:#fff !important;background-color:#dd1e32;border-color:#d01c2f}
.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger {background-image:none}
.btn-danger.disabled,.btn-danger.disabled:hover,.btn-danger.disabled:focus,.btn-danger.disabled:active,.btn-danger.disabled.active,.btn-danger[disabled],.btn-danger[disabled]:hover,.btn-danger[disabled]:focus,.btn-danger[disabled]:active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger,fieldset[disabled] .btn-danger:hover,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:active,fieldset[disabled] .btn-danger.active {background-color:#e33244;border-color:#e33244}
.btn-dark {color:#fff !important;background-color:#222733;border-color:#222733}
.btn-dark:hover,.btn-dark:focus,.btn-dark:active,.btn-dark.active,.open .dropdown-toggle.btn-dark {color:#fff !important;background-color:#181b24;border-color:#12141b}
.btn-dark:active,.btn-dark.active,.open .dropdown-toggle.btn-dark {background-image:none}
.btn-dark.disabled,.btn-dark.disabled:hover,.btn-dark.disabled:focus,.btn-dark.disabled:active,.btn-dark.disabled.active,.btn-dark[disabled],.btn-dark[disabled]:hover,.btn-dark[disabled]:focus,.btn-dark[disabled]:active,.btn-dark[disabled].active,fieldset[disabled] .btn-dark,fieldset[disabled] .btn-dark:hover,fieldset[disabled] .btn-dark:focus,fieldset[disabled] .btn-dark:active,fieldset[disabled] .btn-dark.active {background-color:#222733;border-color:#222733}
.btn {font-weight:500;border-radius:2px}
.btn-icon {padding-left:0 !important;padding-right:0 !important;width:34px;text-align:center}
.btn-icon.b-2x {width:36px}
.btn-icon.btn-sm {width:30px}
.btn-icon.btn-sm.b-2x {width:32px}
.btn-icon.btn-lg {width:45px}
.btn-icon.btn-lg.b-2x {width:47px}
.btn-group-justified {border-collapse:separate}
.btn-rounded {border-radius:50px;padding-left:15px;padding-right:15px}
.btn-rounded.btn-lg {padding-left:25px;padding-right:25px}
.btn>i.pull-left,.btn>i.pull-right {line-height:1.428571429}
.btn-block {padding-left:12px;padding-right:12px}
.btn-group-vertical>.btn:first-child:not(:last-child) {border-top-right-radius:2px}
.btn-group-vertical>.btn:last-child:not(:first-child) {border-bottom-left-radius:2px}
.btn-inactive {-webkit-box-shadow:none !important;box-shadow:none !important}
.chat-item:before,.chat-item:after {content:" ";display:table}
.chat-item:after {clear:both}
.chat-item .arrow {top:20px}
.chat-item .arrow.right:after {border-left-color:#f2f4f8}
.chat-item .chat-body {position:relative;margin-left:45px;min-height:30px}
.chat-item .chat-body .panel {margin:0 -1px}
.chat-item.right .chat-body {margin-left:0;margin-right:45px}
.chat-item+.chat-item {margin-top:15px}
.comment-list {position:relative}
.comment-list .comment-item {margin-top:0;position:relative}
.comment-list .comment-item>.thumb-sm {width:36px}
.comment-list .comment-item .arrow.left {top:20px;left:39px}
.comment-list .comment-item .comment-body {margin-left:46px}
.comment-list .comment-item .panel-body {padding:10px 15px}
.comment-list .comment-item .panel-heading,.comment-list .comment-item .panel-footer {position:relative;font-size:12px;background-color:#fff}
.comment-list .comment-reply {margin-left:46px}
.comment-list:before {position:absolute;top:0;bottom:35px;left:18px;width:1px;background:#e0e4e8;content:''}
.timeline {display:table;width:100%;border-spacing:0;table-layout:fixed;position:relative;border-collapse:collapse}
.timeline:before {content:"";width:1px;margin-left:-1px;position:absolute;left:50%;top:0;bottom:30px;background-color:#ddd;z-index:0}
.timeline .timeline-date {position:absolute;width:150px;left:-200px;top:50%;margin-top:-9px;text-align:right}
.timeline .timeline-icon {position:absolute;left:-41px;top:-2px;top:50%;margin-top:-15px}
.timeline .time-icon {width:30px;height:30px;line-height:30px;display:inline-block !important;z-index:10;border-radius:20px;text-align:center}
.timeline .time-icon:before {font-size:14px;margin-top:5px}
.timeline-item {display:table-row}
.timeline-item:before,.timeline-item.alt:after {content:"";display:block;width:50%}
.timeline-item.alt {text-align:right}
.timeline-item.alt:before {display:none}
.timeline-item.alt .panel {margin-right:25px;margin-left:0}
.timeline-item.alt .timeline-date {left:auto;right:-200px;text-align:left}
.timeline-item.alt .timeline-icon {left:auto;right:-41px}
.timeline-item.active {display:table-caption;text-align:center}
.timeline-item.active:before {width:1%}
.timeline-item.active .timeline-caption {display:inline-block;width:auto}
.timeline-item.active .timeline-caption h5 span {color:#fff}
.timeline-item.active .panel {margin-left:0}
.timeline-item.active .timeline-date,.timeline-item.active .timeline-icon {position:static;margin-bottom:10px;display:inline-block;width:auto}
.timeline-caption {display:table-cell;vertical-align:top;width:50%}
.timeline-caption .panel {position:relative;margin-left:25px;text-align:left}
.timeline-caption h5 {margin:0}
.timeline-caption h5 span {display:block;color:#999;margin-bottom:4px;font-size:12px}
.timeline-caption p {font-size:12px;margin-bottom:0;margin-top:10px}
.timeline-footer {display:table-row}
.timeline-footer a {display:table-cell;text-align:right}
.timeline-footer .time-icon {margin-right:-15px;z-index:5}
.post-item {border-radius:3px;background-color:#fff;-webkit-box-shadow:0px 1px 2px rgba(0,0,0,0.15);box-shadow:0px 1px 2px rgba(0,0,0,0.15);margin-bottom:15px}
.post-item .post-title {margin-top:0}
.post-item .post-media {text-align:center}
.post-item .post-media img {border-radius:3px 3px 0 0}
.paper {position:relative;background:-webkit-linear-gradient(top,#f0f0f0 0%,white 5%) 0 0;background:-moz-linear-gradient(top,#f0f0f0 0%,white 5%) 0 0;background:linear-gradient(top,#f0f0f0 0%,white 5%) 0 0;-webkit-background-size:100% 30px;-moz-background-size:100% 30px;-ms-background-size:100% 30px;background-size:100% 30px}
.paper:before {content:'';position:absolute;width:0px;top:0;left:39px;bottom:0;border-left:1px solid #1ccacc}
.paper textarea {border:none;background-color:transparent;height:100%;padding:30px 0 0 55px;line-height:30px;min-height:210px}
.i-fw {width:1.2857142857143em;text-align:center}
.i-lg {font-size:1.3333333333333em;line-height:0.75em;vertical-align:-15%}
.i-sm {font-size:0.75em}
.i-1x {font-size:1em}
.i-2x {font-size:2em}
.i-3x {font-size:3em}
.i-4x {font-size:4em}
.i-5x {font-size:5em}
.i-s {position:relative;display:inline-block;vertical-align:middle}
.i-s>i {position:absolute;left:0;width:100%;text-align:center;line-height:inherit}
.i-s-2x {width:2em;height:2em;font-size:2em;line-height:2em}
.i-s-2x .i-s-base {font-size:2em}
.i-s-3x {width:2.5em;height:2.5em;font-size:2.5em;line-height:2.5em}
.i-s-3x .i-s-base {font-size:2.5em}
.i-s-4x {width:3em;height:3em;font-size:3em;line-height:3em}
.i-s-4x .i-s-base {font-size:3em}
.i-s-5x {width:3.5em;height:3.5em;font-size:3.5em;line-height:3.5em}
.i-s-5x .i-s-base {font-size:3.5em}
.switch {cursor:pointer;position:relative}
.switch input {position:absolute;opacity:0;filter:alpha(opacity=0)}
.switch input:checked+span {background-color:#1aae88}
.switch input:checked+span:after {left:31px}
.switch span {position:relative;width:60px;height:30px;border-radius:30px;background-color:#fff;border:1px solid #eee;border-color:rgba(0,0,0,0.1);display:inline-block;-webkit-transition:background-color 0.2s;transition:background-color 0.2s}
.switch span:after {content:"";position:absolute;background-color:#fff;width:26px;top:1px;bottom:1px;border-radius:30px;-webkit-box-shadow:1px 1px 3px rgba(0,0,0,0.25);box-shadow:1px 1px 3px rgba(0,0,0,0.25);-webkit-transition:left 0.2s;transition:left 0.2s}
.nav-docs>ul>li>a {padding-top:5px !important;padding-bottom:5px !important}
.dropfile {border:2px dashed #e0e4e8;text-align:center;min-height:20px}
.dropfile.hover {border-color:#aac3cc}
.dropfile small {margin:50px 0;display:block}
.portlet {min-height:30px}
.jqstooltip {-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}
.easypiechart {position:relative;text-align:center}
.easypiechart>div {position:relative;z-index:1}
.easypiechart>div .text {position:absolute;width:100%;top:60%;line-height:1}
.easypiechart>div img {margin-top:-4px}
.easypiechart canvas {position:absolute;top:0;left:0;z-index:0}
.flot-legend .legend>div {display:none}
.flot-legend .legend .legendColorBox>div {border:none !important;margin:5px}
.flot-legend .legend .legendColorBox>div>div {border-radius:10px}
.doc-buttons .btn {margin-bottom:5px}
.list-icon i {font-size:14px;width:40px;vertical-align:middle;margin:0;display:inline-block;text-align:center;-webkit-transition:font-size .2s;transition:font-size .2s}
.list-icon div {line-height:40px;white-space:nowrap}
.list-icon div:hover i {font-size:26px}
.th-sortable {cursor:pointer}
.th-sortable .th-sort {float:right;position:relative}
.th-sort i {position:relative;z-index:1}
.th-sort .fa-sort {position:absolute;left:0;top:3px;color:#bac3cc;z-index:0}
.th-sortable.active .text {display:none !important}
.th-sortable.active .text-active {display:inline-block !important}
.sortable-placeholder {list-style:none;border:1px dashed #CCC;min-height:50px;margin-bottom:5px}
.input-append.date .add-on i,.input-prepend.date .add-on i {display:block;cursor:pointer;width:16px;height:16px}
.parsley-error-list {margin:0;padding:0;list-style:none;margin-top:6px;font-size:12px}
.parsley-error {border-color:#ff5f5f !important}
.datepicker td.active,.datepicker td.active:hover,.datepicker td.active:hover.active,.datepicker td.active.active {background:#177bbb}
#flotTip {padding:3px 5px;background-color:#000;z-index:100;color:#fff;opacity:.7;filter:alpha(opacity=70);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}
.bg-gradient {background-image:-webkit-gradient(linear,left 0,left 100%,from(rgba(40,50,60,0)),to(rgba(40,50,60,0.05)));background-image:-webkit-linear-gradient(top,rgba(40,50,60,0),0,rgba(40,50,60,0.05),100%);background-image:-moz-linear-gradient(top,rgba(40,50,60,0) 0,rgba(40,50,60,0.05) 100%);background-image:linear-gradient(to bottom,rgba(40,50,60,0) 0,rgba(40,50,60,0.05) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#0028323c',endColorstr='#0c28323c',GradientType=0);filter:none}
.bg-light {background-color:#f2f4f8;color:#788288}
.bg-light.lt,.bg-light .lt {background-color:#f7f8fb}
.bg-light.lter,.bg-light .lter {background-color:#fcfcfd}
.bg-light.dk,.bg-light .dk {background-color:#e9edf4}
.bg-light.dker,.bg-light .dker {background-color:#e0e6f0}
.bg-light.bg,.bg-light .bg {background-color:#f2f4f8}
.bg-dark {background-color:#222733;color:#7a87a7}
.bg-dark.lt,.bg-dark .lt {background-color:#2e3341}
.bg-dark.lter,.bg-dark .lter {background-color:#3a404e}
.bg-dark.dk,.bg-dark .dk {background-color:#171b24}
.bg-dark.dker,.bg-dark .dker {background-color:#0d0f15}
.bg-dark.bg,.bg-dark .bg {background-color:#222733}
.bg-dark a {color:#99a3bb}
.bg-dark a:hover {color:#fff}
.bg-dark a.list-group-item:hover,.bg-dark a.list-group-item:focus {background-color:inherit}
.bg-dark .nav>li:hover>a,.bg-dark .nav>li:focus>a,.bg-dark .nav>li:active>a,.bg-dark .nav>li.active>a {color:#fff;background-color:#12151d}
.bg-dark .nav>li>a {color:#99a3bb}
.bg-dark .nav>li>a:hover,.bg-dark .nav>li>a:focus {background-color:#171b24}
.bg-dark .nav .open>a {background-color:#12151d}
.bg-dark .caret {border-top-color:#7a87a7;border-bottom-color:#7a87a7}
.bg-dark.navbar .nav>li.active>a {color:#fff;background-color:#171b24}
.bg-dark .open>a,.bg-dark .open>a:hover,.bg-dark .open>a:focus {color:#fff}
.bg-dark .text-muted {color:#5f6d8f !important}
.bg-dark .text-lt {color:#c7ccda !important}
.bg-dark .icon-muted {color:#5f6d8f !important}
.bg-dark.auto .list-group-item,.bg-dark .auto .list-group-item {border-color:#282e3c !important;background-color:transparent}
.bg-dark.auto .list-group-item:hover,.bg-dark.auto .list-group-item:focus,.bg-dark.auto .list-group-item:active,.bg-dark.auto .list-group-item.active,.bg-dark .auto .list-group-item:hover,.bg-dark .auto .list-group-item:focus,.bg-dark .auto .list-group-item:active,.bg-dark .auto .list-group-item.active {background-color:#171b24 !important}
.bg-black {background-color:#12131a;color:#656b93}
.bg-black.lt,.bg-black .lt {background-color:#1d1f28}
.bg-black.lter,.bg-black .lter {background-color:#292b36}
.bg-black.dk,.bg-black .dk {background-color:#07080b}
.bg-black.dker,.bg-black .dker {background-color:#000000}
.bg-black.bg,.bg-black .bg {background-color:#12131a}
.bg-black a {color:#8287a9}
.bg-black a:hover {color:#fff}
.bg-black a.list-group-item:hover,.bg-black a.list-group-item:focus {background-color:inherit}
.bg-black .nav>li:hover>a,.bg-black .nav>li:focus>a,.bg-black .nav>li:active>a,.bg-black .nav>li.active>a {color:#fff;background-color:#020203}
.bg-black .nav>li>a {color:#8287a9}
.bg-black .nav>li>a:hover,.bg-black .nav>li>a:focus {background-color:#07080b}
.bg-black .nav .open>a {background-color:#020203}
.bg-black .caret {border-top-color:#656b93;border-bottom-color:#656b93}
.bg-black.navbar .nav>li.active>a {color:#fff;background-color:#07080b}
.bg-black .open>a,.bg-black .open>a:hover,.bg-black .open>a:focus {color:#fff}
.bg-black .text-muted {color:#515574 !important}
.bg-black .text-lt {color:#b0b3c8 !important}
.bg-black .icon-muted {color:#515574 !important}
.bg-black.auto .list-group-item,.bg-black .auto .list-group-item {border-color:#181a23 !important;background-color:transparent}
.bg-black.auto .list-group-item:hover,.bg-black.auto .list-group-item:focus,.bg-black.auto .list-group-item:active,.bg-black.auto .list-group-item.active,.bg-black .auto .list-group-item:hover,.bg-black .auto .list-group-item:focus,.bg-black .auto .list-group-item:active,.bg-black .auto .list-group-item.active {background-color:#07080b !important}
.bg-primary {background-color:#177bbb;color:#aad7f4}
.bg-primary.lt,.bg-primary .lt {background-color:#1d89cf}
.bg-primary.lter,.bg-primary .lter {background-color:#2796de}
.bg-primary.dk,.bg-primary .dk {background-color:#126da7}
.bg-primary.dker,.bg-primary .dker {background-color:#0d5e92}
.bg-primary.bg,.bg-primary .bg {background-color:#177bbb}
.bg-primary-ltest {background-color:#ecf6fb}
.bg-primary a {color:#d7ecfa}
.bg-primary a:hover {color:#fff}
.bg-primary a.list-group-item:hover,.bg-primary a.list-group-item:focus {background-color:inherit}
.bg-primary .nav>li:hover>a,.bg-primary .nav>li:focus>a,.bg-primary .nav>li:active>a,.bg-primary .nav>li.active>a {color:#fff;background-color:#11659b}
.bg-primary .nav>li>a {color:#d7ecfa}
.bg-primary .nav>li>a:hover,.bg-primary .nav>li>a:focus {background-color:#126da7}
.bg-primary .nav .open>a {background-color:#11659b}
.bg-primary .caret {border-top-color:#aad7f4;border-bottom-color:#aad7f4}
.bg-primary.navbar .nav>li.active>a {color:#fff;background-color:#126da7}
.bg-primary .open>a,.bg-primary .open>a:hover,.bg-primary .open>a:focus {color:#fff}
.bg-primary .text-muted {color:#7cc2ef !important}
.bg-primary .text-lt {color:#ffffff !important}
.bg-primary .icon-muted {color:#7cc2ef !important}
.bg-primary.auto .list-group-item,.bg-primary .auto .list-group-item {border-color:#1984c9 !important;background-color:transparent}
.bg-primary.auto .list-group-item:hover,.bg-primary.auto .list-group-item:focus,.bg-primary.auto .list-group-item:active,.bg-primary.auto .list-group-item.active,.bg-primary .auto .list-group-item:hover,.bg-primary .auto .list-group-item:focus,.bg-primary .auto .list-group-item:active,.bg-primary .auto .list-group-item.active {background-color:#126da7 !important}
.bg-success {background-color:#1aae88;color:#a3f1dd}
.bg-success.lt,.bg-success .lt {background-color:#20c198}
.bg-success.lter,.bg-success .lter {background-color:#27d4a8}
.bg-success.dk,.bg-success .dk {background-color:#159a78}
.bg-success.dker,.bg-success .dker {background-color:#108567}
.bg-success.bg,.bg-success .bg {background-color:#1aae88}
.bg-success-ltest {background-color:#f1ffed}
.bg-success a {color:#cff8ed}
.bg-success a:hover {color:#fff}
.bg-success a.list-group-item:hover,.bg-success a.list-group-item:focus {background-color:inherit}
.bg-success .nav>li:hover>a,.bg-success .nav>li:focus>a,.bg-success .nav>li:active>a,.bg-success .nav>li.active>a {color:#fff;background-color:#138f6f}
.bg-success .nav>li>a {color:#cff8ed}
.bg-success .nav>li>a:hover,.bg-success .nav>li>a:focus {background-color:#159a78}
.bg-success .nav .open>a {background-color:#138f6f}
.bg-success .caret {border-top-color:#a3f1dd;border-bottom-color:#a3f1dd}
.bg-success.navbar .nav>li.active>a {color:#fff;background-color:#159a78}
.bg-success .open>a,.bg-success .open>a:hover,.bg-success .open>a:focus {color:#fff}
.bg-success .text-muted {color:#76ebcd !important}
.bg-success .text-lt {color:#ffffff !important}
.bg-success .icon-muted {color:#76ebcd !important}
.bg-success.auto .list-group-item,.bg-success .auto .list-group-item {border-color:#1cbb92 !important;background-color:transparent}
.bg-success.auto .list-group-item:hover,.bg-success.auto .list-group-item:focus,.bg-success.auto .list-group-item:active,.bg-success.auto .list-group-item.active,.bg-success .auto .list-group-item:hover,.bg-success .auto .list-group-item:focus,.bg-success .auto .list-group-item:active,.bg-success .auto .list-group-item.active {background-color:#159a78 !important}
.bg-module {background-color:#83c849;}
.bg-info {background-color:#1ccacc;color:#bef5f6}
.bg-info.lt,.bg-info .lt {background-color:#24dbdd}
.bg-info.lter,.bg-info .lter {background-color:#3ddcde}
.bg-info.dk,.bg-info .dk {background-color:#16b6b8}
.bg-info.dker,.bg-info .dker {background-color:#11a2a4}
.bg-info.bg,.bg-info .bg {background-color:#1ccacc}
.bg-info-ltest {background-color:#ecfcff}
.bg-info a {color:#ebfcfc}
.bg-info a:hover {color:#fff}
.bg-info a.list-group-item:hover,.bg-info a.list-group-item:focus {background-color:inherit}
.bg-info .nav>li:hover>a,.bg-info .nav>li:focus>a,.bg-info .nav>li:active>a,.bg-info .nav>li.active>a {color:#fff;background-color:#15abad}
.bg-info .nav>li>a {color:#ebfcfc}
.bg-info .nav>li>a:hover,.bg-info .nav>li>a:focus {background-color:#16b6b8}
.bg-info .nav .open>a {background-color:#15abad}
.bg-info .caret {border-top-color:#bef5f6;border-bottom-color:#bef5f6}
.bg-info.navbar .nav>li.active>a {color:#fff;background-color:#16b6b8}
.bg-info .open>a,.bg-info .open>a:hover,.bg-info .open>a:focus {color:#fff}
.bg-info .text-muted {color:#91eff0 !important}
.bg-info .text-lt {color:#ffffff !important}
.bg-info .icon-muted {color:#91eff0 !important}
.bg-info.auto .list-group-item,.bg-info .auto .list-group-item {border-color:#1ed7d9 !important;background-color:transparent}
.bg-info.auto .list-group-item:hover,.bg-info.auto .list-group-item:focus,.bg-info.auto .list-group-item:active,.bg-info.auto .list-group-item.active,.bg-info .auto .list-group-item:hover,.bg-info .auto .list-group-item:focus,.bg-info .auto .list-group-item:active,.bg-info .auto .list-group-item.active {background-color:#16b6b8 !important}
.bg-warning {background-color:#fcc633;color:#fffefc}
.bg-warning.lt,.bg-warning .lt {background-color:#facc4e}
.bg-warning.lter,.bg-warning .lter {background-color:#f9d269}
.bg-warning.dk,.bg-warning .dk {background-color:#ffc017}
.bg-warning.dker,.bg-warning .dker {background-color:#fcb800}
.bg-warning.bg,.bg-warning .bg {background-color:#fcc633}
.bg-warning-ltest {background-color:#fffee6}
.bg-warning a {color:#ffffff}
.bg-warning a:hover {color:#fff}
.bg-warning a.list-group-item:hover,.bg-warning a.list-group-item:focus {background-color:inherit}
.bg-warning .nav>li:hover>a,.bg-warning .nav>li:focus>a,.bg-warning .nav>li:active>a,.bg-warning .nav>li.active>a {color:#fff;background-color:#ffbd0a}
.bg-warning .nav>li>a {color:#ffffff}
.bg-warning .nav>li>a:hover,.bg-warning .nav>li>a:focus {background-color:#ffc017}
.bg-warning .nav .open>a {background-color:#ffbd0a}
.bg-warning .caret {border-top-color:#fffefc;border-bottom-color:#fffefc}
.bg-warning.navbar .nav>li.active>a {color:#fff;background-color:#ffc017}
.bg-warning .open>a,.bg-warning .open>a:hover,.bg-warning .open>a:focus {color:#fff}
.bg-warning .text-muted {color:#fef0ca !important}
.bg-warning .text-lt {color:#ffffff !important}
.bg-warning .icon-muted {color:#fef0ca !important}
.bg-warning.auto .list-group-item,.bg-warning .auto .list-group-item {border-color:#fcca42 !important;background-color:transparent}
.bg-warning.auto .list-group-item:hover,.bg-warning.auto .list-group-item:focus,.bg-warning.auto .list-group-item:active,.bg-warning.auto .list-group-item.active,.bg-warning .auto .list-group-item:hover,.bg-warning .auto .list-group-item:focus,.bg-warning .auto .list-group-item:active,.bg-warning .auto .list-group-item.active {background-color:#ffc017 !important}
.bg-danger {background-color:#e33244;color:#fce5e8}
.bg-danger.lt,.bg-danger .lt {background-color:#e34b5b}
.bg-danger.lter,.bg-danger .lter {background-color:#e56371}
.bg-danger.dk,.bg-danger .dk {background-color:#e01b2f}
.bg-danger.dker,.bg-danger .dker {background-color:#cc1628}
.bg-danger.bg,.bg-danger .bg {background-color:#e33244}
.bg-danger-ltest {background-color:#fbedec}
.bg-danger a {color:#ffffff}
.bg-danger a:hover {color:#fff}
.bg-danger a.list-group-item:hover,.bg-danger a.list-group-item:focus {background-color:inherit}
.bg-danger .nav>li:hover>a,.bg-danger .nav>li:focus>a,.bg-danger .nav>li:active>a,.bg-danger .nav>li.active>a {color:#fff;background-color:#d51a2d}
.bg-danger .nav>li>a {color:#ffffff}
.bg-danger .nav>li>a:hover,.bg-danger .nav>li>a:focus {background-color:#e01b2f}
.bg-danger .nav .open>a {background-color:#d51a2d}
.bg-danger .caret {border-top-color:#fce5e8;border-bottom-color:#fce5e8}
.bg-danger.navbar .nav>li.active>a {color:#fff;background-color:#e01b2f}
.bg-danger .open>a,.bg-danger .open>a:hover,.bg-danger .open>a:focus {color:#fff}
.bg-danger .text-muted {color:#f5b9bf !important}
.bg-danger .text-lt {color:#ffffff !important}
.bg-danger .icon-muted {color:#f5b9bf !important}
.bg-danger.auto .list-group-item,.bg-danger .auto .list-group-item {border-color:#e53f50 !important;background-color:transparent}
.bg-danger.auto .list-group-item:hover,.bg-danger.auto .list-group-item:focus,.bg-danger.auto .list-group-item:active,.bg-danger.auto .list-group-item.active,.bg-danger .auto .list-group-item:hover,.bg-danger .auto .list-group-item:focus,.bg-danger .auto .list-group-item:active,.bg-danger .auto .list-group-item.active {background-color:#e01b2f !important}
.bg-white {background-color:#fff;color:#788288}
.bg-white a {color:#3c4144}
.bg-white a:hover {color:#242729}
.bg-white.dk,.bg-white .dk {background-color:#FFF}
.bg-white.dker,.bg-white .dker {background-color:#FFF}
.bg-white .text-muted {color:#a1a8ac !important}
.bg-white-only {background-color:#fff}
.bg-empty {background-color:transparent}
.text-primary {color:#177bbb}
.text-primary-lt {color:#1a8ad2}
.text-primary-lter {color:#2198e4}
.text-primary-dk {color:#146ca4}
.text-primary-dker {color:#115d8e}
.text-info {color:#1ccacc}
.text-info-lt {color:#21dee1}
.text-info-lter {color:#37e2e4}
.text-info-dk {color:#19b4b6}
.text-info-dker {color:#169e9f}
.text-success {color:#1aae88}
.text-success-lt {color:#1dc499}
.text-success-lter {color:#21daab}
.text-success-dk {color:#179877}
.text-success-dker {color:#138265}
.text-warning {color:#fcc633}
.text-warning-lt {color:#fccd4c}
.text-warning-lter {color:#fdd465}
.text-warning-dk {color:#fcbf1a}
.text-warning-dker {color:#f8b704}
.text-danger {color:#e33244}
.text-danger-lt {color:#e64858}
.text-danger-lter {color:#e95f6d}
.text-danger-dk {color:#dd1e32}
.text-danger-dker {color:#c71b2d}
.text-dark {color:#222733}
.text-dark-lt {color:#2c3342}
.text-dark-lter {color:#363e52}
.text-dark-dk {color:#181b24}
.text-dark-dker {color:#0e1014}
.text-black {color:#000;color:rgba(0,0,0,0.8)}
.text-grey {color:#707070;text-shadow:#FFFFFF 0 1px 0;}
.text-white {color:#fff;color:rgba(255,255,255,1)}
.text-muted {color:#a1a8ac}
.pos-rlt {position:relative}
.pos-stc {position:static}
.pos-abt {position:absolute}
.line {*width:100%;height:2px;margin:10px 0;font-size:0;overflow:hidden}
.line-xs {margin:0}
.line-lg {margin-top:15px;margin-bottom:15px}
.line-dashed {border-style:dashed !important;background-color:transparent;border-width:0}
.no-line {border-width:0}
.no-border,.no-borders {border-color:transparent;border-width:0}
.no-radius {border-radius:0}
.block {display:block}
.block.hide {display:none}
.inline {display:inline-block !important}
.none {display:none}
.pull-right-lg {float:right}
.pull-none {float:none}
.rounded {border-radius:500px}
.btn-s-xs {min-width:90px}
.btn-s-sm {min-width:100px}
.btn-s-md {min-width:120px}
.btn-s-lg {min-width:150px}
.btn-s-xl {min-width:200px}
.l-h-2x {line-height:2em}
.l-h-1x {line-height:1.2}
.l-h {line-height:1.5}
.v-middle {vertical-align:middle !important}
.v-top {vertical-align:top !important}
.v-bottom {vertical-align:bottom !important}
.font-normal {font-weight:normal}
.font-thin {font-weight:300}
.font-bold {font-weight:700}
.text-lg {font-size:16px}
.text-md {font-size:14px}
.text-sm {font-size:12px}
.text-xs {font-size:11px}
.text-ellipsis {display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.text-u-c {text-transform:uppercase}
.text-l-t {text-decoration:line-through}
.text-u-l {text-decoration:underline}
.text-active,.active>.text,.active>.auto .text {display:none !important}
.active>.text-active,.active>.auto .text-active {display:inline-block !important}
.box-shadow {box-shadow:0 2px 2px rgba(0,0,0,0.05),0 1px 0 rgba(0,0,0,0.05)}
.wrapper-xxs {padding:2px 6px}
.wrapper-xs {padding:4px 8px}
.wrapper-sm {padding:5px 10px}
.wrapper {padding:15px}
.wrapper-md {padding:20px}
.wrapper-lg {padding:30px}
.wrapper-xl {padding:50px}
.padder {padding-left:15px;padding-right:15px}
.padder-v {padding-top:15px;padding-bottom:15px}
.no-padder {padding:0 !important}
.pull-in {margin-left:-15px;margin-right:-15px}
.pull-out {margin:-10px -15px}
.b {border:1px solid rgba(0,0,0,0.05)}
.b-a {border:1px solid #eaeef1}
.b-t {border-top:1px solid #eaeef1}
.b-r {border-right:1px solid #eaeef1}
.b-b {border-bottom:1px solid #eaeef1}
.b-l {border-left:1px solid #eaeef1}
.b-light {border-color:#e1e6ef}
.b-dark {border-color:#2c3342}
.b-primary {border-color:#1a8ad2}
.b-success {border-color:#1dc499}
.b-info {border-color:#21dee1}
.b-warning {border-color:#fccd4c}
.b-danger {border-color:#e64858}
.b-black {border-color:#1c1e29}
.b-white {border-color:#fff}
.b-dashed {border-style:dashed !important}
.b-2x {border-width:2px}
.b-3x {border-width:3px}
.b-4x {border-width:4px}
.b-5x {border-width:5px}
.r {border-radius:2px 2px 2px 2px}
.r-l {border-radius:2px 0 0 2px}
.r-r {border-radius:0 2px 2px 0}
.r-t {border-radius:2px 2px 0 0}
.r-b {border-radius:0 0 2px 2px}
.m-xxs {margin:2px 4px}
.m-xs {margin:5px}
.m-sm {margin:10px}
.m {margin:15px}
.m-md {margin:20px}
.m-lg {margin:30px}
.m-xl {margin:50px}
.m-n {margin:0 !important}
.m-l-none {margin-left:0}
.m-l-xs {margin-left:5px}
.m-l-sm {margin-left:10px}
.m-l {margin-left:15px}
.m-l-md {margin-left:20px}
.m-l-lg {margin-left:30px}
.m-l-xl {margin-left:40px}
.m-l-n-xxs {margin-left:-1px}
.m-l-n-xs {margin-left:-5px}
.m-l-n-sm {margin-left:-10px}
.m-l-n {margin-left:-15px}
.m-l-n-md {margin-left:-20px}
.m-l-n-lg {margin-left:-30px}
.m-l-n-xl {margin-left:-40px}
.m-t-none {margin-top:0}
.m-t-xxs {margin-top:1px}
.m-t-xs {margin-top:5px}
.m-t-sm {margin-top:10px}
.m-t {margin-top:15px}
.m-t-md {margin-top:20px}
.m-t-lg {margin-top:30px}
.m-t-xl {margin-top:40px}
.m-t-n-xxs {margin-top:-1px}
.m-t-n-xs {margin-top:-5px}
.m-t-n-sm {margin-top:-10px}
.m-t-n {margin-top:-15px}
.m-t-n-md {margin-top:-20px}
.m-t-n-lg {margin-top:-30px}
.m-t-n-xl {margin-top:-40px}
.m-r-none {margin-right:0}
.m-r-xxs {margin-right:1px}
.m-r-xs {margin-right:5px}
.m-r-sm {margin-right:10px}
.m-r {margin-right:15px}
.m-r-md {margin-right:20px}
.m-r-lg {margin-right:30px}
.m-r-xl {margin-right:40px}
.m-r-n-xxs {margin-right:-1px}
.m-r-n-xs {margin-right:-5px}
.m-r-n-sm {margin-right:-10px}
.m-r-n {margin-right:-15px}
.m-r-n-md {margin-right:-20px}
.m-r-n-lg {margin-right:-30px}
.m-r-n-xl {margin-right:-40px}
.m-b-none {margin-bottom:0}
.m-b-xxs {margin-bottom:1px}
.m-b-xs {margin-bottom:5px}
.m-b-sm {margin-bottom:10px}
.m-b {margin-bottom:15px}
.m-b-md {margin-bottom:20px}
.m-b-lg {margin-bottom:30px}
.m-b-xl {margin-bottom:40px}
.m-b-n-xxs {margin-bottom:-1px}
.m-b-n-xs {margin-bottom:-5px}
.m-b-n-sm {margin-bottom:-10px}
.m-b-n {margin-bottom:-15px}
.m-b-n-md {margin-bottom:-20px}
.m-b-n-lg {margin-bottom:-30px}
.m-b-n-xl {margin-bottom:-40px}
.media-xs {min-width:50px}
.media-sm {min-width:80px}
.media-md {min-width:90px}
.media-lg {min-width:120px}
.avatar {position:relative;display:block;border-radius:500px;white-space:nowrap}
.avatar img {border-radius:500px;width:100%}
.avatar i {position:absolute;left:0;top:0;width:10px;height:10px;border-width:2px;border-style:solid;border-radius:100%}
.avatar i.md {width:12px;height:12px;margin:1px}
.avatar i.right {left:auto;right:0}
.avatar i.bottom {left:auto;top:auto;bottom:0;right:0}
.avatar i.on {background-color:#1aae88}
.avatar i.off {background-color:#a1a8ac}
.avatar i.busy {background-color:#e33244}
.avatar i.away {background-color:#fcc633}
.thumb-lg {width:128px;display:inline-block}
.thumb-md {width:64px;display:inline-block}
.thumb {width:50px;display:inline-block}
.thumb-sm {width:34px;display:inline-block}
.thumb-xs {width:24px;display:inline-block}
.thumb-wrapper {padding:2px;border:1px solid #ddd}
.thumb img,.thumb-xs img,.thumb-sm img,.thumb-md img,.thumb-lg img,.thumb-btn img {height:auto;max-width:100%;vertical-align:middle}
.img-full {max-width:100%}
.img-full>img {max-width:100%}
.clear {display:block;overflow:hidden}
.row-sm {margin-left:-10px;margin-right:-10px}
.row-sm>div {padding-left:10px;padding-right:10px}
.i-checks input {width:auto !important;height:auto !important;opacity:0}
.i-checks input:checked+i {border-color:#177bbb}
.i-checks input:checked+i:before {position:absolute;left:0px;width:100%;top:2px;text-align:center;font-family:"FontAwesome";font-style:normal;font-weight:normal;color:#177bbb}
.i-checks input[type="radio"]+i {border-radius:100%}
.i-checks input[type="checkbox"]:checked+i:before {content:"\f00c"}
.i-checks input[type="radio"]:checked+i:before {content:"\f111"}
.i-checks input[disabled]+i,fieldset[disabled] .i-checks input+i {border-color:#dbe2e7}
.i-checks input[disabled]+i:before,fieldset[disabled] .i-checks input+i:before {color:#cbd5dd}
.i-checks i {width:18px;height:18px;line-height:1;border:1px solid #cbd5dd;background-color:#fff;margin-left:-20px;margin-top:-2px;display:inline-block;vertical-align:middle;margin-right:4px;position:relative;font-size:12px}
.ie8 .i-checks i {display:none}
.scroll-x,.scroll-y {overflow:hidden;-webkit-overflow-scrolling:touch}
.scroll-y {overflow-y:auto}
.scroll-x {overflow-x:auto}
.no-touch .scroll-x,.no-touch .scroll-y {overflow:hidden}
.no-touch .scroll-x:hover,.no-touch .scroll-x:focus,.no-touch .scroll-x:active {overflow-x:auto}
.no-touch .scroll-y:hover,.no-touch .scroll-y:focus,.no-touch .scroll-y:active {overflow-y:auto}
.no-touch .hover-action {display:none}
.no-touch .hover:hover .hover-action {display:inherit}
.hover-rotate {-webkit-transition:all .2s ease-in-out .1s;transition:all .2s ease-in-out .1s}
.hover:hover .hover-rotate,.hover:active .hover-rotate {-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}
.backdrop {position:absolute;top:0;right:0;bottom:0;left:0;z-index:1050;background-color:#fff}
.backdrop.fade {opacity:0;filter:alpha(opacity=0)}
.backdrop.in {opacity:0.8;filter:alpha(opacity=80)}
.h {font-size:170px;font-weight:300;text-shadow:0 1px 0 #d9d9d9,0 2px 0 #d0d0d0,0 5px 10px rgba(0,0,0,0.125),0 10px 20px rgba(0,0,0,0.2)}
@media screen and (min-width: 992px) {.col-lg-2-4 {width:20.000%;float:left}
}
@media (max-width: 767px) {.shift {display:none !important}
.shift.in {display:block !important}
.row-2 [class*="col"] {width:50%;float:left}
.row-2 .col-0 {clear:none}
.row-2 li:nth-child(odd) {clear:left;margin-left:0}
.text-center-xs {text-align:center}
.text-left-xs {text-align:left}
.pull-none-xs {float:none !important}
.dropdown-menu.pull-none-xs {left:0}
.hidden-xs.show {display:inherit !important}
.wrapper-lg {padding:15px}
}
/* Localized */
<|start_filename|>public_map/assets/js/admin-cfg.js<|end_filename|>
// Filename: admin-cfg.js
requirejs.config({
baseUrl: 'assets',
paths: {
text: 'js/lib/require-text-2.0.12',
hgn: 'js/lib/require-hgn-0.3.0',
ol: 'js/lib/openlayers/ol',
olpopup: 'js/lib/openlayers/ol-popup',
jquery: 'js/lib/jquery/jquery-2.1.3.min',
bootstrap: 'js/lib/bootstrap-3.1.1-dist/js/bootstrap.min',
bootselect: 'js/lib/bootstrap-select.min',
notify: 'js/lib/bootstrap-notify',
hogan: 'js/lib/hogan/hogan-3.0.2',
xml2json: 'js/lib/xml2json/xml2json.min',
queryString: 'js/lib/query-string/query-string',
wpsPayloads: 'js/lib/zoo/payloads',
wpsPayload: 'js/lib/zoo/wps-payload',
utils: 'js/lib/zoo/utils',
zoo: 'js/lib/zoo/zoo',
domReady: 'js/lib/domReady',
app: 'js/login.js',
},
shim: {
mmDataTables: {
deps: ['notify']
},
datepicker: {
deps: ['bootstrap'],
},
bootstrap: {
deps: ['jquery'],
},
cmenu: {
deps: ['jquery'],
},
treeview: {
deps: ['jquery'],
},
bootselect: {
deps: ['bootstrap'],
},
slider: {
deps: ['bootstrap'],
},
dataTables: {
deps: ['jquery'],
},
buttons: {
deps: ['dataTables'],
},
buttonsCol: {
deps: ['buttons'],
},
colReorder: {
deps: ['dataTables'],
},
responsive: {
deps: ['dataTables'],
},
select: {
deps: ['dataTables'],
},
colResize: {
deps: ['dataTables'],
},
/*datatables: {
deps: ['dataTables',]
},*/
notify: {
deps: ['jquery','bootstrap'],
},
olpopup: {
deps: ['ol'],
},
highcharts: {
exports: "Highcharts",
deps: ["jquery"]
},
wpsPayloads: {
deps: ['hogan'],
},
wpsPayload: {
deps: ['wpsPayloads'],
exports: 'wpsPayload',
},
hogan: {
exports: 'Hogan',
},
xml2json: {
exports: "X2JS",
},
queryString: {
exports: 'queryString',
},
ol: {
exports: 'ol',
},
app: {
deps: ['highcharts','mmDataTables','olpopup', 'slider','cmenu','treeview','notify','colResize','enquire','bootselect','select','responsive','notify']
}
},
waitSeconds: 0
});
requirejs.config({
config: {
app: {
url: 'http://zoo.dev.publicamundi.eu/cgi-bin/zoo_loader.fcgi',
delay: 2000,
}
}
});
requirejs.onResourceLoad = function (context, map, depArray) {
console.log(map.name + ' : ' + map.url);
};
require(['domReady', 'app'], function(domReady, app) {
domReady(function() {
app.initialize();
});
window.cgalProcessing=app.cgalProcessing;
window.app=app;
if(app.datepicker)
window.datepicker=app.datepicker;
});
<|start_filename|>mapmint-ui/new-themes/themes/blue/ui.css<|end_filename|>
.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555; text-decoration: none; }
.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #7fe5f9 , #3d93df);
background: -webkit-gradient(linear, left top, left bottom, from(#7fe5f9), to(#3d93df));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#7fe5f9', endColorstr='#3d93df');
font-weight: normal; color: #FFFFFF; }
.ui-state-hover a, .ui-state-hover a:hover { color: #FFFFFF; text-decoration: none; }
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active {text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #7fe5f9 , #3d93df);
background: -webkit-gradient(linear, left top, left bottom, from(#7fe5f9), to(#3d93df));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#7fe5f9', endColorstr='#3d93df'); font-weight: normal; color: #FFFFFF; }
<|start_filename|>mapmint-ui/new-themes/themes/blue/window.css<|end_filename|>
.panel-tool-close{
background:url('../img/panel_tools-blue.gif') no-repeat -16px 0px;
}
.panel-tool-min{
background:url('../img/panel_tools-blue.gif') no-repeat 0px 0px;
}
.panel-tool-max{
background:url('../img/panel_tools-blue.gif') no-repeat 0px -16px;
}
.panel-tool-restore{
background:url('../img/panel_tools-blue.gif') no-repeat -16px -16px;
}
.panel-tool-collapse{
background:url('../img/panel_tool_collapse-blue.gif') no-repeat;
}
.panel-tool-expand{
background:url('../img/panel_tool_expand-blue.gif') no-repeat;
}
.panel-loading{
padding:11px 0px 10px 30px;
background:url('../img/panel_loading.gif') no-repeat 10px 10px;
}
a.l-btn:hover{
color:#FFFFFF;
text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #7fe5f9 , #3d93df);
background: -webkit-gradient(linear, left top, left bottom, from(#7fe5f9), to(#3d93df));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#7fe5f9', endColorstr='#3d93df');
}
<|start_filename|>public_map/assets/js/login.js<|end_filename|>
// Filename: login.js
define([
'module', 'jquery', 'zoo','notify'
], function(module, $,Zoo,notify) {
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
language: module.config().language
});
function createParam(obj){
return {
"identifier": $(obj).attr("name"),
"value": $(obj).val(),
"dataType": "string"
}
}
function react(obj){
console.log($(obj).parent());
console.log($(obj).parent().parent().parent());
var myRoot=null;
if($(obj).parent().is("form"))
myRoot=$(obj).parent();
else
myRoot=$(obj).parent().parent().parent();
var serviceName=$(obj).data("service");
var params=[];
myRoot.find("input").each(function(){
console.log($(this).attr("type"));
if($(this).attr("type")!="submit"){
if($(this).attr("type")=="checkbox"){
if($(this).is(":checked"))
params.push(createParam(this));
}else{
params.push(createParam(this));
}
}
});
zoo.execute({
identifier: "authenticate."+serviceName,
type: "POST",
dataInputs: params,
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
document.location.reload(false);
},
error: function(data){
console.log(data);
if($.isArray(data["ExceptionReport"]["Exception"])){
for(var i=0;i<data["ExceptionReport"]["Exception"].length;i++)
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"][i]["ExceptionText"] },
type: 'danger',
}).show();
}
else
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"] },
type: 'danger',
}).show();
}
});
return false;
}
var initialize=function(){
console.log("Start application");
$(".bg_load").fadeOut("slow");
$(".bg_load_wrapper").fadeOut("slow");
$("form").on("submit",function(){
var closure=$(".btn-lg");
return react(closure);
});
$(".btn-lg").on("click",function(){
return react(this);
});
};
// Return public methods
return {
initialize: initialize
};
});
<|start_filename|>mapmint-ui/templates/preview/modules/routing/init.js<|end_filename|>
#encoding UTF-8
#import zoo
var points_layer=false,dd_layer=false,route_layer=false,route_layer1=false,points_layer1=false;
var geographic = new OpenLayers.Projection("EPSG:4326"),
mercator = new OpenLayers.Projection("EPSG:900913");
var totalLength=0;
var sspoints=[];
var draw_points;
var drag_points;
var route_layer2=false;
//System.idPoint = null;
System.routingPoiCnt=0;
System.nbEtapes = 0;
System.nbEtapeFlags = 0;
// Vitesse par défaut : 15km/h en vélo
var defaultSpeed = 15;
var currentIdStepDisplayed = 0;
var previousIdStepDisplayed = -1;
var nbSteps = 0;
var lookup = {
"start": {pointRadius: 14,graphicYOffset: -24,graphicXOffset: -6,'externalGraphic': '$conf['main']['publicationUrl']/img/startMarker0.png'},
"end": {pointRadius: 14,graphicYOffset: -24,graphicXOffset: -6,'externalGraphic': '$conf['main']['publicationUrl']/img/endMarker.png'},
"inter": {pointRadius: 14,graphicYOffset: -24,graphicXOffset: -6,'externalGraphic': '$conf['main']['publicationUrl']/img/interMarker0.png'},
"incident": {pointRadius: 14,graphicYOffset: -24,graphicXOffset: -6,'externalGraphic': '$conf['main']['publicationUrl']/img/design/danger_bleu.png'}
}
function parseDistance(){
if(arguments[0]/1000>=1){
var tmp=(arguments[0]/1000)+"";
var tmp1=tmp.split(".");
var tmp2=arguments[0]-(eval(tmp1[0])*1000);
var tmp3=(tmp2+"").split('.');
tmp3=tmp3[0]+"";
return " "+tmp1[0]+(tmp2>=1?","+(tmp3[0]+tmp3[1])+" km ":"");
}else{
var tmp=arguments[0]+"";
var tmp1=tmp.split(".");
return " "+tmp1[0]+" m ";
}
}
function parseMeter(){
if(arguments[0]/1000>=0){
var tmp=(arguments[0]/1000)+"";
var tmp1=tmp.split(".");
var tmp2=arguments[0]-(tmp1[0]*1000);
var tmp3=(tmp2+"").split('.');
return " "+tmp1[0]+" km "+(tmp2>=1?"et "+tmp3[0]+" m":"");
}else{
var tmp=(arguments[0]/1000)+"";
var tmp1=tmp.split(".");
return " "+tmp1[0]+" m";
}
}
System.points=[];
function mmGeocode(obj,feature){
if(feature){
tmp=feature.geometry;
System.idPoint=feature.attributes["idPoint"];
}
else{
tmp=obj.layer.features[obj.layer.features.length-1].geometry;
if(System.idPoint.indexOf("step")<0)
obj.layer.features[obj.layer.features.length-1].attributes["idPoint"]=System.idPoint;
else{
var tmpv=eval(System.idPoint.replace(/stepPoint/g,""));
obj.layer.features[2+tmpv].attributes["idPoint"]=System.idPoint;
tmp=obj.layer.features[2+tmpv].geometry;
}
}
var lonlat=new OpenLayers.LonLat(tmp.x,tmp.y).transform(map.getProjectionObject(),wgs84);
if(System.idPoint){
System.points[System.points.length]=System.idPoint;
}
System.n=System.points[System.points.length-1];
\$.ajax({
type: "GET",
url: "$conf["main"]["serverAddress"]?service=WPS&version=1.0.0&request=Execute&Identifier=routing.reverseGeocode&DataInputs=x="+lonlat.lon+";y="+lonlat.lat+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
try{
var results=\$.parseJSON(xml.responseText);
\$('#search_geocoding_results').empty();
\$("#"+System.n).val("");
\$("#"+System.n).val(results[0][0]);
}catch(e){
//loadGCPWindow("windows/popupmessage?msg="+"$zoo._('No address found')","$zoo._('Information')",400,50);
}
}
});
}
DrawPoints = OpenLayers.Class(OpenLayers.Control.DrawFeature, {
// this control is active by default
autoActivate: false,
initialize: function(layer, options) {
// only points can be drawn
this.handler = OpenLayers.Handler.Point;
OpenLayers.Control.DrawFeature.prototype.initialize.apply(
this, [layer, this.handler, options]
);
},
mmGeoCode: function(n){
mmGeocode(this,false);
},
setCurrentFlag: function(idPoint){
//alert(idPoint)
if((idPoint=="startPoint") || (idPoint.indexOf("startPoint") != -1)){
if(this.layer.features.length>1){
var saveds=[];
for(var i=0;i<this.layer.features.length;i++){
saveds.push(this.layer.features[i].clone());
}
this.layer.removeFeatures(this.layer.features);
this.layer.addFeatures([saveds[saveds.length-1]]);
this.layer.addFeatures([saveds[0]]);
for(var i=1;i<saveds.length-1;i++)
this.layer.addFeatures([saveds[i]]);
this.layer.features[1].attributes["type"]="end";
}
this.layer.features[0].attributes["type"]="start";
}
else if(idPoint.indexOf("endPoint") != -1){
if(this.layer.features.length>2){
var saveds=[];
for(var i=1;i<this.layer.features.length;i){
saveds.push(this.layer.features[i].clone());
this.layer.removeFeatures(this.layer.features[i]);
}
this.layer.addFeatures([saveds[saveds.length-1]]);
for(var i=0;i<saveds.length-1;i++)
this.layer.addFeatures([saveds[i]]);
this.layer.features[0].attributes["type"]="start";
}
this.layer.features[1].attributes["type"]="end";
}
else if(idPoint.indexOf("stepPoint") != -1 ){
if(this.layer.features.length>3){
var saveds=[];
var tmps=eval(idPoint.replace(/stepPoint/g,""));
var saveds=[];
for(var i=2+tmps;i<this.layer.features.length;i){
saveds.push(this.layer.features[i].clone());
this.layer.removeFeatures(this.layer.features[i]);
}
this.layer.addFeatures([saveds[saveds.length-1]]);
this.layer.features[this.layer.features.length-1].attributes["type"]="inter";
this.layer.features[this.layer.features.length-1].attributes["idPoint"]="stepPoint0";
for(var i=0;i<saveds.length-1;i++){
this.layer.addFeatures([saveds[i]]);
this.layer.features[this.layer.features.length-1].attributes["idPoint"]="stepPoint"+(i+1);
this.layer.features[this.layer.features.length-1].attributes["type"]="inter";
}
this.layer.features[0].attributes["type"]="start";
this.layer.features[1].attributes["type"]="end";
}
this.layer.features[this.layer.features.length-1].attributes["type"]="inter";
}
else alert("flag error: " + idPoint);
},
drawFeature: function(geometry) {
OpenLayers.Control.DrawFeature.prototype.drawFeature.apply(
this, arguments
);
if (this.layer.features.length>0){
#if $m.web.metadata.get('layout_t')!="mobile"
// Attribution du drapeau selon le type
this.setCurrentFlag(System.idPoint);
this.mmGeoCode(System.idPoint);
// Zoom sur lieu
if(System.idPoint=="entityPoint")
map.zoomToExtent(points_layer.getDataExtent());
#end if
}
\$("#"+System.idPoint).trigger("onchange");
System.idPoint=false;
this.deactivate();
this.layer.redraw(true);
}
}
);
function _getSitesAround(){
var params1=[
{name: "InputEntity1","xlink:href": System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=vector-tools.BufferUnion&DataInputs=InputPolygon=Reference@xlink:href="+encodeURIComponent(System.mapUrl+"&service=WFS&version=1.0.0&request=GetFeature&typename=Result")+";BufferDistance=0.02&RawDataOutput=Result", mimeType: "application/json"},
{name: "InputEntity2","xlink:href": msUrl+"?map="+pmapfile+"&service=WFS&version=1.0.0&request=GetFeature&typename=Sites",mimeType: "text/xml"},
{name: "line","xlink:href": System.mapUrl+"&service=WFS&version=1.0.0&request=GetFeature&typename=Result", mimeType: "text/xml"}
];
//alert("ok");
var data1=WPSGetHeader("vector-tools.orderedIntersection")+WPSGetInputs(params1)+WPSGetOutput({name: "Result"})+WPSGetFooter();
//alert("ok "+data1);
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data1,
complete: function(xml,status) {
try{
#if $m.web.metadata.get('layout_t')=="mobile"
var gml=new OpenLayers.Format.GML();
System.features=gml.read(xml.responseText);
var chk=\$('#searchPOIType').val();
var aDisplay=[];
System.featuresf=[];
for(i=0;i<System.features.length;i++){
try{
if(System.features[i].attributes["ID_TEMPLAT"]==chk){
var display=true;
for(var j=0;j<aDisplay.length;j++){
//alert(aDisplay[j]+" "+System.features[i].attributes["NOM_SITE"]);
if(aDisplay[j]==System.features[i].attributes["NOM_SITE"]){
display=false;
//alert(display);
break;
}
}
if(display){
\$('<li>', {
"data-role": "fieldcontain"
})
.append(\$('<a />', {
text: System.features[i].attributes["NOM_SITE"]
})
.click(function() {
try{
//alert("ok");
routingFormAddPOI();
alert(System.featuresf[i]);
var stmp=System.featuresf[i].geometry;
stmp1=stmp.transform(geographic,mercator);
alert(stmp);
points_layer.addFeatures([new OpenLayers.Feature.Vector(stmp,{id:points_layer.features.length, type: (points_layer.features.length==0?"start":(points_layer.features.length==1?"end":"inter"))},null)]);
\$.mobile.changePage('#routingPage');
}catch(e){alert(e);}
})
)
.appendTo('#routingPoiListContainer');
aDisplay[aDisplay.length]=System.features[i].attributes["NOM_SITE"];
alert(aDisplay[aDisplay.length-1]+" "+display);
System.featuresf[System.featuresf.length]=System.features[i];
alert(System.featuresf);
}
}
}catch(e){alert(e)}
}
#if $m.web.metadata.get('layout_t')=="mobile"
\$('#routingPoiListPage').trigger('pagecreate');
\$('#routingPoiListPage').listview("refresh");
#end if
#else
/*startpoint = points_layer.features[0].geometry.clone();
startpoint.transform(mercator, geographic);
endpoint = points_layer.features[1].geometry.clone();
endpoint.transform(mercator, geographic);
var params1=[
{name: "line","xlink:href": System.mapUrl+"&service=WFS&version=1.0.0&request=GetFeature&typename=Result", mimeType: "text/xml"},
{name: "points",value: xml.responseText,mimeType: "application/json"},
{name: "spoint",value: startpoint.x+","+startpoint.y,dataType: "string"},
{name: "epoint",value: endpoint.x+","+endpoint.y,dataType: "string"}
];
var data1=WPSGetHeader("vector-tools.orderPoiAlongLine")+WPSGetInputs(params1)+WPSGetOutput({name: "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data1,
complete: function(xml,status) {*/
loadPOI(xml);
/*}
});*/
#end if
}catch(e){}
}
});
}
function getSitesAround(){
//alert("ok");
loadGCPWindow('windows/selectitineraire;std=true',
"$zoo._("Select arrival")",
400,
350,
null,
function(){
if(System.func){
//initChamps();
//removeAllFeatures();
//mmLayout.open('west');
System.func=false;
}
},
function(){
_getSitesAround();
}
);
#* var params=[
{name: "InputPolygon","xlink:href": System.mapUrl+"&service=WFS&version=1.0.0&request=GetFeature&typename=Result",mimeType: "text/xml"},
{name: "Distance","value": 0.001,dataType: "string"}
];
var data=WPSGetHeader("vector-tools.Buffer")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
//alert(data);
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
try{
var params1=[
{name: "InputEntity1","value": xml.responseText, mimeType: "text/json"},
{name: "InputEntity2","xlink:href": msUrl+"?map="+pmapfile+"&service=WFS&version=1.0.0&request=GetFeature&typename=Sites",mimeType: "text/xml"}
];
var data1=WPSGetHeader("vector-tools.Intersection")+WPSGetInputs(params1)+WPSGetOutput({name: "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data1,
complete: function(xml,status) {
try{
var gml=new OpenLayers.Format.GML();
System.features=gml.read(xml.responseText);
var chk=\$('#searchPOIType').val();
var aDisplay=[];
System.featuresf=[];
for(i=0;i<System.features.length;i++){
try{
if(System.features[i].attributes["ID_TEMPLAT"]==chk){
var display=true;
for(var j=0;j<aDisplay.length;j++){
//alert(aDisplay[j]+" "+System.features[i].attributes["NOM_SITE"]);
if(aDisplay[j]==System.features[i].attributes["NOM_SITE"]){
display=false;
//alert(display);
break;
}
}
if(display){
\$('<li>', {
"data-role": "fieldcontain"
})
.append(\$('<a />', {
text: System.features[i].attributes["NOM_SITE"]
})
.click(function() {
try{
//alert("ok");
routingFormAddPOI();
//alert(System.featuresf[i]);
var stmp=System.featuresf[i].geometry;
stmp1=stmp.transform(geographic,mercator);
//alert(stmp);
points_layer.addFeatures([new OpenLayers.Feature.Vector(stmp,{id:points_layer.features.length, type: (points_layer.features.length==0?"start":(points_layer.features.length==1?"end":"inter"))},null)]);
\$.mobile.changePage('#routingPage');
}catch(e){alert(e);}
})
)
.appendTo('#routingPoiListContainer');
aDisplay[aDisplay.length]=System.features[i].attributes["NOM_SITE"];
//alert(aDisplay[aDisplay.length-1]+" "+display);
System.featuresf[System.featuresf.length]=System.features[i];
//alert(System.featuresf);
#else
#end if
}
}
}catch(e){alert(e)}
}
#if $m.web.metadata.get('layout_t')=="mobile"
\$('#routingPoiListPage').trigger('pagecreate');
\$('#routingPoiListPage').listview("refresh");
#end if
}catch(e){}
}
});
}catch(e){alert(e);}
}
});
*#
}
function zoomOnPoi(c){
var tmp=new OpenLayers.Bounds(c[0]-0.001,c[1]-0.001,c[0]+0.001,c[1]+0.001);
var stmp=new OpenLayers.Geometry.Point(c[0],c[1]);
stmp1=stmp.transform(geographic,mercator);
points_layer.addFeatures([new OpenLayers.Feature.Vector(stmp1,{id:points_layer.features.length, type: (points_layer.features.length==0?"start":(points_layer.features.length==1?"end":"inter"))},null)]);
map.zoomToExtent(tmp.transform(geographic,mercator))
#if $m.web.metadata.get('layout_t')=="mobile"
\$('#mapPage').trigger("pageshow");
\$.mobile.changePage("#mapPage");
#end if
}
function loadTrace(){
try{
#if $m.web.metadata.get('layout_t')!="mobile"
hideProfil('true');
#end if
RoutingReinit();
var params=[
{name: "trace",value: arguments[0],dataType: "string"}
];
var data=WPSGetHeader("routing.loadRoute")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
System.toLoad=arguments[0];
System.routingProfileComputed=false;
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.showPageLoadingMsg();
#end if
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
try{
var resObj=\$.parseJSON(xml.responseText);
for(i=0;i<resObj["points"].length;i++){
var stmp=new OpenLayers.Geometry.Point(resObj["points"][i].coordinates[0],resObj["points"][i].coordinates[1]);
stmp1=stmp.transform(geographic,map.getProjection());
points_layer.addFeatures([new OpenLayers.Feature.Vector(stmp1,{id:points_layer.features.length, type: (points_layer.features.length==0?"start":(points_layer.features.length==1?"end":"inter"))},null)]);
}
}catch(e){alert(e);}
#if $m.web.metadata.get('layout_t')=="mobile"
\$.mobile.hidePageLoadingMsg();
\$("#toolbarLink").attr("href","#routingPage");
\$("#routingInfo").removeClass("hidden");
\$("#routingSave").removeClass("hidden");
\$("#routingProfile").removeClass("hidden");
\$("#routingDownload").removeClass("hidden");
#else
\$("#routingProfile").removeClass("hidden");
#end if
System.toLoad=resObj.trace;
System.mapUrl="$conf["main"]["mapserverAddress"]?map=$conf["main"]["dataPath"]/Paths/Saved_Result_"+System.toLoad+".map";
if(!route_layer){
route_layer=new OpenLayers.Layer.WMS("Result",
"$conf["main"]["mapserverAddress"]?map=$conf["main"]["dataPath"]/Paths/Saved_Result_"+System.toLoad+".map",
{layers: "Result",format: "image/png"},
{isBaseLayer: false, singleTile: false, ratio: 1}
);
map.addLayer(route_layer);
}
try{
map.setLayerIndex(points_layer,map.layers.length-2);
map.setLayerIndex(route_layer,map.layers.length-4);
if(route_layer1)
map.setLayerIndex(route_layer1,map.layers.length-5);
}catch(e){}
route_layer.setVisibility(true);
\$.ajax({
type: "GET",
url: "$conf["main"]["mapserverAddress"]?map=$conf["main"]["dataPath"]/Paths/Saved_Result_"+System.toLoad+".map&service=WMS&version=1.0.0&request=GetCapabilities",
dataType: "xml",
complete: function(xml,status) {
var localCnt=0;
var tmp=\$(xml.responseXML).find("Layer").each(
function(){
\$(this).find('Layer').each(
function(){
\$(this).find('LatLonBoundingBox').each(
function(){
var tmp=new OpenLayers.Bounds(\$(this).attr("minx"),\$(this).attr("miny"),\$(this).attr("maxx"),\$(this).attr("maxy"));
tmp.transform(geographic,mercator);
System.curExtent=tmp;
map.zoomToExtent(tmp);
#if $m.web.metadata.get('layout_t')=="mobile"
\$('#mapPage').trigger("pageshow");
\$.mobile.changePage("#mapPage");
#end if
RoutingDisplayStep(0);
try{
startpoint = points_layer.features[0].geometry.clone();
startpoint.transform(mercator, geographic);
finalpoint = points_layer.features[1].geometry.clone();
finalpoint.transform(mercator, geographic);
System.inputs1=System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=vector-tools.UnionOneGeom&DataInputs=InputEntity=Reference@xlink:href="+encodeURIComponent(System.mapUrl+"&service=WFS&version=1.0.0&request=GetFeature&typename=Result")+"&RawDataOutput=Result"
requestProfile();
}catch(e){alert(e);}
}
);
localCnt+=1;
}
);
});
}});
#if $m.web.metadata.get('layout_t')=="mobile"
\$.mobile.hidePageLoadingMsg();
#end if
}
});
}catch(e){
alert(e);
}
}
function deleteTrace(){
try{
var params=[
{name: "trace",value: arguments[0],dataType: "string"}
];
var data=WPSGetHeader("routing.removeRoute")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
tmp=arguments[0];
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
tmp: tmp,
complete: function(xml,status) {
listSavedPaths();
}
});
}catch(e){
alert(e);
}
}
function addOption(){
var o = new Option(arguments[1][1],arguments[1][0]);
\$(o).html(arguments[1][1]);
\$("#"+arguments[0]).append(o);
}
function listSavedPaths(){
try{
var params=[
{name: "trace",value: arguments[0],dataType: "string"}
];
var data=WPSGetHeader("routing.listRoute")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
tmp=arguments[0];
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
tmp: tmp,
complete: function(xml,status) {
var results=\$.parseJSON(xml.responseText);
\$("#select_sauvegardes").html("");
for(i=0;i<results.length;i++){
var o = new Option(results[i][1],results[i][0]);
\$(o).html(results[i][1]);
\$("#select_sauvegardes").append(o);
results
}
}
});
}catch(e){
alert(e);
}
}
function routingSave(){
try{
var params=[
{name: "url",value: System.mapUrl,dataType: "string"},
{name: "name",value: \$("#rname").val(),dataType: "string"}
];
for(var i=0;i<points_layer.features.length;i++){
var geo=points_layer.features[i].geometry;
var tmp=geo.transform(mercator,geographic);
params[params.length]={name: "point",value: tmp.x+","+tmp.y ,dataType: "string"};
}
System.shouldDisplay=true;
if(arguments.length==1){
params[params.length]={name: "user",value: "anonymous",dataType: "string"};
System.shouldDisplay=false;
}
var data=WPSGetHeader("routing.saveRouteForUser")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
if(System.shouldDisplay){
listSavedPaths();
}else{
System.shouldDisplay=true;
if(System.toCall)
System.toCall(xml.responseText);
}
}
});
}catch(e){
alert(e);
}
}
function saveNews(){
try{
var params=[
{name: "title",value: \$("#ntitle").val(),dataType: "string"},
{name: "content",value: \$("#ncontent").val(),dataType: "string"}
];
if(points_layer.features && points_layer.features.length)
for(var i=0;i<points_layer.features.length;i++){
var geo=points_layer.features[i].geometry;
var tmp=geo.transform(mercator,geographic);
params[params.length]={name: "point",value: tmp.x+","+tmp.y ,dataType: "string"};
}
else{
params[params.length]={name: "lat",value: \$("#nlat").val(),dataType: "string"};
params[params.length]={name: "long",value: \$("#nlong").val(),dataType: "string"};
}
params[params.length]={name: "type",value: "2",dataType: "string"};
if(\$("#ntype0")[0].checked)
params[params.length]={name: "type_incident",value: \$("#ntype0").val(),dataType: "string"};
else
params[params.length]={name: "type_incident",value: \$("#ntype1").val(),dataType: "string"};
var data=WPSGetHeader("routing.savePOIUser")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.showPageLoadingMsg();
#end if
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
RoutingReinit();
//loadGCPWindow(false,'Actualités',300,200,{txt: xml.responseText});
//loadGCPWindow("windows/popupmessage?msg="+"$zoo._('The reported incident has been recorded. Thank you for your participation.')","$zoo._('Information')",400,50);
#if $m.web.metadata.get('layout_t')=="mobile"
\$.mobile.hidePageLoadingMsg();
#end if
}
});
}catch(e){
alert(e);
}
}
var startpoint = false;
var finalpoint = false;
var url=false;
System.mapUrl="";
var searchFunction;
var btRecherche="";
function runRouting(layer){
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.showPageLoadingMsg();
#end if
System.routingProfileComputed=false;
// transform the two geometries from EPSG:900913 to EPSG:4326
startpoint = layer.features[0].geometry.clone();
startpoint.transform(mercator, geographic);
finalpoint = layer.features[1].geometry.clone();
finalpoint.transform(mercator, geographic);
var interpoint=[];
suffix="";
for(var i=2;i<layer.features.length;i++){
interpoint.push(layer.features[i].geometry.clone());
interpoint[interpoint.length-1].transform(mercator, geographic);
suffix+=","+interpoint[interpoint.length-1].x+","+interpoint[interpoint.length-1].y;
}
if(route_layer){
try{
map.removeLayer(route_layer);
map.removeLayer(route_layer1);
route_layer=false;
route_layer1=false;
}catch(e){}
}
#if $m.web.metadata.get('layout_t')=="mobile"
\$("#routingInfo").addClass("hidden");
\$("#routingDownload").addClass("hidden");
#end if
\$("#routingProfile").addClass("hidden");
\$("#routingSave").addClass("hidden");
requestedProfile=false;
\$.ajax({
type: "GET",
url: zooUrl+"?service=WPS&request=Execute&version=1.0.0&Identifier=routing.do&DataInputs=startPoint="+startpoint.x+","+startpoint.y+suffix+";endPoint="+finalpoint.x+","+finalpoint.y+"&ResponseDocument=Result@asReference=true@mimeType=application/json@useMapserver=true@mimeType=application/json",
dataType: 'xml',
complete:function(xml,status){
if(status=="success"){
if(!checkWPSResult(xml,false)){
//loadGCPWindow("windows/popupmessage?msg="+"$zoo._('Please set flags on a road or near by')","$zoo._('Information')",400,50);
//\$("#bt_recherche").removeAttr("disabled");
if(btRecherche!=""){
document.getElementById(btRecherche).onclick = searchFunction;
}
\$("#link_export").hide();
\$("#link_print").hide();
return;
}
#if $m.web.metadata.get('layout_t')=="mobile"
\$.mobile.hidePageLoadingMsg();
\$("#toolbarLink").attr("href","#routingPage");
\$("#routingInfo").removeClass("hidden");
\$("#routingSave").removeClass("hidden");
\$("#routingProfile").removeClass("hidden");
\$("#routingDownload").removeClass("hidden");
#else
\$("#routingProfile").removeClass("hidden");
#end if
//backButtonForGeocoding("#routingPage");
#if $m.web.metadata.get('layout_t')=="mobile"
\$('#mapPage').trigger("pageshow");
\$.mobile.changePage("#mapPage");
#end if
if(route_layer){
try{
map.removeLayer(route_layer);
route_layer=false;
map.removeLayer(route_layer1);
route_layer1=false;
}catch(e){}
}
/*if(!System.selectPoi)
hideProfil('false');*/
var mapUrl="";
\$(xml.responseXML).find("wps\\:Reference").each(function(){var tmp=this.getAttribute('href').split('\&');mapUrl=tmp;});
\$(xml.responseXML).find("Reference").each(function(){var tmp=this.getAttribute('href').split('\&');mapUrl=tmp;});
/**
* Display the resulting WMS layer
*/
var tmp=mapUrl[0].split("=");
route_layer=new OpenLayers.Layer.WMS("Result",
mapUrl[0],
{layers: "Result",format: "image/png"},
{isBaseLayer: false, singleTile: false, ratio: 1}
);
map.addLayers([route_layer]);
try{
map.setLayerIndex(route_layer,map.layers.length-4);
}catch(e){}
\$.ajax({
type: "GET",
url: zooUrl+"?service=WPS&request=Execute&version=1.0.0&Identifier=routing.applyStyleToRouteMap&DataInputs=map="+tmp[1]+"&RawDataOutput=Result",
dataType: 'xml',
complete:function(xml,status){
route_layer.redraw(true);
if(btRecherche!=""){
document.getElementById(btRecherche).onclick = searchFunction;
}
}
});
System.mapUrl=mapUrl[0];
\$.ajax({
type: "GET",
url: mapUrl[0]+"&service=WMS&version=1.0.0&request=GetCapabilities",
dataType: "xml",
complete: function(xml,status) {
var localCnt=0;
var tmp=\$(xml.responseXML).find("Layer").each(
function(){
\$(this).find('Layer').each(
function(){
\$(this).find('LatLonBoundingBox').each(
function(){
var tmp=new OpenLayers.Bounds(\$(this).attr("minx"),\$(this).attr("miny"),\$(this).attr("maxx"),\$(this).attr("maxy"));
tmp.transform(geographic,mercator);
System.curExtent=tmp;
//alert("ok");
map.zoomToExtent(tmp);
//alert("ok");
//System.mapUrl=mapUrl[0];
//alert("ok");
RoutingDisplayStep(0);
//alert("ok");
\$("#link_export").show();
\$("#link_print").show();
}
);
}
);
});
//map.addLayers([route_layer]);
#if $m.web.metadata.get('layout_t')!="mobile"
System.inputs1=System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=vector-tools.UnionOneGeom&DataInputs=InputEntity=Reference@xlink:href="+encodeURIComponent(System.mapUrl+"&service=WFS&version=1.0.0&request=GetFeature&typename=Result")+"&RawDataOutput=Result"
//alert(System.selectPoi);
if(!System.selectPoi)
requestProfile();
else
getSitesAround();
#end if
}});
//getSitesAround();
//alert(mapUrl);
}
}
});
suffix="";
var layer=points_layer;
for(var i=2;i<layer.features.length;i++){
interpoint.push(layer.features[i].geometry.clone());
interpoint[interpoint.length-1].transform(mercator, geographic);
suffix+=","+interpoint[interpoint.length-1].x+","+interpoint[interpoint.length-1].y;
}
url="/cgi-bin/zoo_loader.cgi?service=WPS&request=Execute&version=1.0.0&Identifier=routing.computeRouteProfile&DataInputs=startPoint="+startpoint.x+","+startpoint.y+suffix+";endPoint="+finalpoint.x+","+finalpoint.y+";mult=15&RawDataOutput=Result";
}
function pgrouting(layer) {
btRecherche="";
#if $m.web.metadata.get('layout_t')!="mobile"
//hideProfil('true');
//initFdrMode();
#end if
if (layer.features.length >= 2) {
if(arguments.length>1){
btRecherche = arguments[1].toString();
searchFunction = document.getElementById(btRecherche).onclick;
document.getElementById(btRecherche).onclick = '';
}
//\$("#bt_recherche").removeAttr("onclick");
#if $m.web.metadata.get('layout_t')!="mobile"
//loadGCPWindow('windows/chargement','$zoo._("Calculation in progress ...")',385,40,null,function(){},function(){
runRouting(layer);
//});
#else
runRouting(layer);
#end if
}
}
function stringTimeToMinutes(time) {
time = time.split(/:/);
return time[0] * 3600 + time[1] * 60;
}
function decimalTimeToHourMinutes(minutes) {
var nbHeures = Math.floor(minutes);
var nbMinutes = minutes - Math.floor(minutes);
//alert("nb minutes = " + nbMinutes);
nbMinutes = nbMinutes*60;
nbMinutes = Math.round(nbMinutes);
if(nbMinutes==60){
nbHeures+=1;
nbMinutes = 0;
}
znbMinutes = nbMinutes.toString();
if(znbMinutes.length==1)
znbMinutes = "0"+znbMinutes;
return nbHeures + "h" + znbMinutes;
}
function calculDistance(time,speed){
return (time * speed)/3600;
}
function calculTempsParcours(distance,speed){
return distance/speed;
}
function drivingDistance(layer,mode) {
btRecherche="";
#if $m.web.metadata.get('layout_t')!="mobile"
initFdrMode();
#end if
if (layer.features.length == 1) {
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.showPageLoadingMsg();
#else
if(arguments.length>2){
btRecherche = arguments[2].toString();
//alert(btRecherche);
searchFunction = document.getElementById(btRecherche).onclick;
document.getElementById(btRecherche).onclick = '';
}
//loadGCPWindow('windows/chargement','$zoo._("Calculation in progress ...")',385,40);
#end if
// transform the two geometries from EPSG:900913 to EPSG:4326
startpoint = layer.features[0].geometry.clone();
startpoint.transform(mercator, geographic);
if(dd_layer){
try{
map.removeLayer(dd_layer);
dd_layer=false;
/*map.removeLayer(route_layer1);
route_layer1=false;*/
}catch(e){}
}
var distance;
if(mode=="rayon"){
distance = \$("#dd_distance").val();
}
else if(mode=="temps"){
var time = stringTimeToMinutes(\$("#dd_time").val());
//alert("time:"+time);
var speed = \$("#dd_speed").val();
//alert("speed:"+speed);
distance = calculDistance(time,speed);
}
//alert("distance = "+distance+"km");
\$.ajax({
type: "GET",
url: zooUrl+"?service=WPS&request=Execute&version=1.0.0&Identifier=routing.doDDPolygon&DataInputs=startPoint="+startpoint.x+","+startpoint.y+";distance="+((\$("#dd_distance").val()*1000)/111120)+"&ResponseDocument=Result@asReference=true@mimeType=image/png",
dataType: 'xml',
complete:function(xml,status){
if(status=="success"){
//alert("success dd");
#if $m.web.metadata.get('layout_t')=="mobile"
\$.mobile.hidePageLoadingMsg();
\$("#toolbarLink").attr("href","#ddPage");
#end if
//backButtonForGeocoding("#routingPage");
#if $m.web.metadata.get('layout_t')=="mobile"
\$('#mapPage').trigger("pageshow");
\$.mobile.changePage("#mapPage");
#end if
if(!checkWPSResult(xml,false,false)){
try{
if(\$( "#loadgcp-window" ).length>0){
\$("#loadgcp-window").remove();
}
}catch(e){}
initChamps();
removeAllFeatures();
if(btRecherche!=""){
document.getElementById(btRecherche).onclick = searchFunction;
}
// We sould probably add here some window providing information to the user that something went wrong when processing his request.
return false;
}
var mapUrl="";
var mapUrl1="";
\$(xml.responseXML).find("wps\\:Reference").each(function(){mapUrl1=this.getAttribute('href');var tmp=this.getAttribute('href').split('\&');mapUrl=tmp;});
\$(xml.responseXML).find("Reference").each(function(){mapUrl1=this.getAttribute('href');var tmp=this.getAttribute('href').split('\&');mapUrl=tmp;});
dd_layer=new OpenLayers.Layer.WMS("ResultDDP",
mapUrl[0],
{layers: "Result",format: "image/png"},
{isBaseLayer: false}
);
dd_layer.setVisibility(true);
map.addLayers([dd_layer]);
try{
map.setLayerIndex(dd_layer,map.layers.length-4);
}catch(e){}
System.mapUrl=mapUrl;
if(btRecherche!=""){
document.getElementById(btRecherche).onclick = searchFunction;
}
System.selectPoi=true;
for(var i=0;i<layersList.length;i++){
if(layersList[i].real_name=="Sites"){
layersList[i].setVisibility(true);
layersList[i].removeFeatures(layersList[i].features);
}
}
loadGCPWindow('windows/selectitineraire','Sélection itinéraire',400,350,
null,
function(){
if(System.func){
//initChamps();
//removeAllFeatures();
//mmLayout.open('west');
removePolygon();
if(System.selectPoi && points_layer.features.length>1)
points_layer.removeFeatures([points_layer.features[points_layer.features.length-1]]);
System.func=false;
System.selectPoi=flase;
}
},
function(){
try{
\$.ajax({
type: "GET",
url: System.mapUrl[0]+"&service=WMS&version=1.0.0&request=GetCapabilities",
dataType: "xml",
complete: function(xml,status) {
var localCnt=0;
var tmp=\$(xml.responseXML).find("Layer").each(
function(){
\$(this).find('Layer').each(
function(){
\$(this).find('LatLonBoundingBox').each(
function(){
var tmp=new OpenLayers.Bounds(\$(this).attr("minx"),\$(this).attr("miny"),\$(this).attr("maxx"),\$(this).attr("maxy"));
tmp1=tmp.clone();
tmp.transform(geographic,mercator);
System.curExtent=tmp;
map.zoomToExtent(tmp);
//alert(tmp1);
var params=[
{"name":"InputEntity1","xlink:href":mapUrl[0]+"&service=WFS&version=1.0.0&request=GetFeature&typename=Result","mimeType":"text/xml"},
{"name":"InputEntity2","xlink:href":"$conf["main"]["mapserverAddress"]?service=WFS&request=GetFeature&version=1.0.0&typename=Sites&bbox="+tmp1+"&map="+System.mapfile,"mimeType":"text/xml"}
];
var data=WPSGetHeader("vector-tools.Intersection")+WPSGetInputs(params)+WPSGetOutput({name: "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
try{
for(var i=0;i<layersList.length;i++){
if(layersList[i].real_name=="Sites"){
var results=\$.parseJSON(xml.responseText);
layersList[i].setVisibility(true);
layersList[i].removeFeatures(layersList[i].features);
//alert(layersList[i].features.length);
for(var j=0;j<results.features.length;j++){
var stmp=new OpenLayers.Geometry.Point(results.features[j].geometry.coordinates[0],results.features[j].geometry.coordinates[1]);
var extent= new OpenLayers.Bounds(stmp.x-0.001,stmp.y-0.001,stmp.x+0.001,stmp.y+0.001);
stmp.transform(geographic,mercator);
layersList[i].addFeatures([new OpenLayers.Feature.Vector(stmp,results.features[j].properties)]);
}
//alert(layersList[i].real_name);
//layersList[i].redraw(false);
map.setLayerIndex(layersList[i],map.layers.length-2);
//alert(layersList[i].features.length);
}
}
//loadPOI(xml);
}catch(e){
alert("Handled error: "+e);
}
}
});
System.mapUrl=mapUrl[0];
RoutingDisplayStep(0);
\$("#link_export").show();
\$("#link_print").show();
}
);
}
);
});
//map.addLayers([dd_layer]);
}
});
}catch(e){alert(e);}
});
}
else{
//alert("echec dd");
if(btRecherche!=""){
document.getElementById(btRecherche).onclick = searchFunction;
}
#if $m.web.metadata.get('layout_t')!="mobile"
removeGCPWindow();
#end if
\$("#link_export").hide();
\$("#link_print").hide();
}
}
});
}
}
function loadPOI(){
var results=\$.parseJSON(arguments[0].responseText);
System.addresses=new Array();
\$('#select_itineraire').empty();
for(var i=0;i<results.features.length;i++){
try{
System.addresses[i]=results.features[i];
var o = new Option(results.features[i].properties["NOM_SITE"],i);
\$(o).html(results.features[i].properties["NOM_SITE"]);
\$("#select_itineraire").append(o);
\$(o).hover(function(){
if(this.parentNode.selectedIndex<0 && !this.parentNode.multiple)
try{
addPOI(System.addresses[this.value].geometry);
}catch(e){}
else
if(this.parentNode.multiple){
addPOI(System.addresses[this.value].geometry);
}
});
\$(o).click(function(){
try{
if(!this.parentNode.multiple){
points_layer.removeFeatures([points_layer.features[points_layer.features.length-1]]);
}
addPOI(System.addresses[this.value].geometry);
}catch(e){}
});
}catch(e){
alert(e);
}
}
}
function addPOI(){
if(!System.flagStep){
if(points_layer.features.length>=2)
points_layer.removeFeatures(points_layer.features[points_layer.features.length-1]);
var geometry=arguments[0];
var stmp=new OpenLayers.Geometry.Point(geometry.coordinates[0],geometry.coordinates[1]);
var extent= new OpenLayers.Bounds(stmp.x-0.001,stmp.y-0.001,stmp.x+0.001,stmp.y+0.001);
stmp.transform(geographic,mercator);
points_layer.addFeatures([new OpenLayers.Feature.Vector(stmp,{id:points_layer.features.length, type: (points_layer.features.length==0?"start":(points_layer.features.length==1?"end":"inter"))})]);
}else{
var nb=0;
var opts=\$("#select_itineraire")[0].options;
for(var i=0;i<opts.length;i++)
if(opts[i].selected){
nb+=1;
}
if(nb==1)
nb=0;
var len=points_layer.features.length;
//alert(len+" "+nb);
for(var i=2;i<len;i++)
points_layer.removeFeatures(points_layer.features[points_layer.features.length-1]);
for(var i=0;i<opts.length;i++)
if(opts[i].selected){
var geometry=System.addresses[i].geometry;
var stmp=new OpenLayers.Geometry.Point(geometry.coordinates[0],geometry.coordinates[1]);
var extent= new OpenLayers.Bounds(stmp.x-0.001,stmp.y-0.001,stmp.x+0.001,stmp.y+0.001);
stmp.transform(geographic,mercator);
points_layer.addFeatures([new OpenLayers.Feature.Vector(stmp,{id:points_layer.features.length, type: (points_layer.features.length==0?"start":(points_layer.features.length==1?"end":"inter"))})]);
}
}
}
function routingDownload(){
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.showPageLoadingMsg();
#end if
var tmp=System.mapUrl.split('=');
var tmp1=tmp[1].split('_');
var tmp2=tmp1[1].split('.');
\$.ajax({
type: "GET",
dataType: "html",
url: "/cgi-bin/zoo_loader.cgi?request=Execute&service=WPS&version=1.0.0&Identifier=vector-converter."+(arguments[0]?"convertTo":"convertToKML")+"&DataInputs=InputDSTN=${conf["main"]["dataPath"]}/ZOO_DATA_Result_"+tmp2[0]+".json"+(arguments[0]?";format="+arguments[0]:"")+"&RawDataOutput=Result",
success: function(xml){
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.hidePageLoadingMsg();
#end if
\$("#export_dl_link").attr("href",xml);
\$("#export_dl_link").show();
\$('#routingDownloadContainer').attr('href',xml);
}
});
}
function routingDetailsNext_old(){
if(arguments[0]>=0)
RoutingDisplayStep(System.routingCnt+2);
else{
if(System.routingCnt-2>0)
RoutingDisplayStep(System.routingCnt-2);
else
RoutingDisplayStep(0);
}
//\$('#routingDetailsPage').page('destroy').page();
}
function routingDetailsNext(){
if(arguments[0]>=0)
RoutingDisplayStep(System.routingCnt+9);
else{
if(System.routingCnt-9>0)
RoutingDisplayStep(System.routingCnt-9);
else
RoutingDisplayStep(0);
}
}
#*
System.pictos={
#import authenticate.service as auth
#import psycopg2
#set dbstr=auth.parseDb($conf["velodb"])
#set con=psycopg2.connect($dbstr)
#set cur=con.cursor()
#set ret=cur.execute("SELECT name,filename from velo.amenagements")
#set res=cur.fetchall()
#set j=0
#for i in $res
"$i[0]": "$i[1]"#if $j+1<len($res)#,#end if#
#set j=$j+1
#end for
};
System.pictosRev={
#set cur=con.cursor()
#set ret=cur.execute("SELECT name,filename from velo.revetements")
#set res=cur.fetchall()
#set j=0
#for i in $res
"$i[0]": "$i[1]"#if $j+1<len($res)#,#end if#
#set j=$j+1
#end for
};
*#
function routingDisplayCurrentStep(){
if(arguments[0]>=0){
routingZoomOnStepsFDR(arguments[0]);
previousIdStepDisplayed = currentIdStepDisplayed;
\$("#step_"+previousIdStepDisplayed).removeClass('step_selected');
currentIdStepDisplayed = arguments[0];
\$("#step_"+currentIdStepDisplayed).addClass('step_selected');
\$("#step_"+currentIdStepDisplayed).focus();
}
}
function routingDisplayPreviousStep(){
previousIdStepDisplayed = currentIdStepDisplayed;
\$("#step_"+previousIdStepDisplayed).removeClass('step_selected');
currentIdStepDisplayed -= 1;
if(currentIdStepDisplayed < 0)
currentIdStepDisplayed = 0;
routingDisplayCurrentStep(currentIdStepDisplayed);
}
function routingDisplayNextStep(){
previousIdStepDisplayed = currentIdStepDisplayed;
\$("#step_"+previousIdStepDisplayed).removeClass('step_selected');
currentIdStepDisplayed += 1;
//alert("nbSteps = " + nbSteps);
if(currentIdStepDisplayed > nbSteps)
currentIdStepDisplayed = nbSteps;
routingDisplayCurrentStep(currentIdStepDisplayed);
}
function StopRoutingFDR(){
routingDisplayCurrentStep(0);
currentIdStepDisplayed = 0;
previousIdStepDisplayed = -1;
}
var modePictos = "amenagement";
function ChangeRoutingDisplayStepMode(){
System.routingCnt-=1;
RoutingDisplayStep(0);
}
function RoutingDisplayStep(){
System.routingCnt=arguments[0]+1;
// if(arguments.length>1){
// modePictos = arguments[1];
// }
// alert("mode = " + modePictos);
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.showPageLoadingMsg();
\$.ajax({
type: "GET",
dataType: "xml",
url: System.mapUrl+"&request=GetFeature&service=WFS&version=1.0.0&typename=Result&featureid=Result."+(arguments[0])+",Result."+(arguments[0]+1)+",Result."+(arguments[0]+2)+",Result."+(arguments[0]+3)+",Result."+(arguments[0]+4),
success: function(xml){
var gml = new OpenLayers.Format.GML();
var features=gml.read(xml);
if(features.length<2){
$.mobile.hidePageLoadingMsg();
System.routingCnt-=1;
return;
}
var data=[];
var j=0;
var nbkm = 0;
System.steps=[];
System.stepsFDR=[];
for(var i=0;i<5;i++){
\$("#_route_"+i).empty();
}
for(i in features){
if(features[i].data){
var tmp=(features[i].data["length"]*111120)+"";
var tmp1=tmp.split(".");
var dtype="revetement"
var curPicto="$conf["main"]["publicationUrl"]/img/design/amenagements/"+(features[i].data["tid"]!="1"?"route_danger.png":System.pictos[features[i].data[dtype]]);
\$('<span>$zoo._("Step") '+eval(System.routingCnt+"+"+i)+": "+" $zoo.("advance for") "+(tmp1[0])+' $zoo._("meters") $zoo._("on") '+(features[i].attributes["name"]?features[i].attributes["name"]:"$zoo._("Unknown road")")+'.<img src="'+curPicto+'" title="'+features[i].data[dtype]+'" alt="'+features[i].data["nature"]+'" />'+"</span>")
.appendTo(\$("#_route_"+i));
\$("#_route_"+i).parent().listview();
}
//alert(features[i].geometry);
features[j].geometry=features[j].geometry.transform(geographic,map.getProjectionObject());
System.steps[j]=features[j];
System.stepsFDR[j]=features[j];
j++;
}
}});
#else
\$("#fdr_cadre").empty();
\$.ajax({
type: "GET",
dataType: "xml",
url: System.mapUrl+"&request=GetFeature&service=WFS&version=1.0.0&typename=Result"/*&featureid=Result."+(arguments[0])+",Result."+(arguments[0]+1)+",Result."+(arguments[0]+2)+",Result."+(arguments[0]+3)+",Result."+(arguments[0]+4)+",Result."+(arguments[0]+5)+",Result."+(arguments[0]+6)+",Result."+(arguments[0]+7)+",Result."+(arguments[0]+8)+",Result."+(arguments[0]+9)*/,
success: function(xml){
var gml = new OpenLayers.Format.GML();
try{
var features=gml.read(xml);
// if(features.length<8){
// System.routingCnt-=1;
// clearTimeout(timeOut);
// return;
// }
var data=[];
var j=0;
var nbkm = 0;
var tempsParcours = 0;
System.steps=[];
System.stepsFDR=[];
for(var i=0;i<10;i++){
\$("#_route_"+i).empty();
}
//alert("nb Features = " + features.length);
$.ajax({
url: "./modules/routing/roadmap",
complete: function(xml,status){
if(!\$('#roadmap-dialog')[0])
\$("body").append('<div id="roadmap-dialog" title="'+"$zoo._("Roadmap")"+'"></div>');
\$('#roadmap-dialog').html("");
\$('#roadmap-dialog').append(xml.responseText);
\$('#roadmap-dialog').window({
width: 325,
height: 220,
maximizable:false,
resizable: false
});
for(i in features){
try{
if(features[i].data){
var tmp=(features[i].data["length"]*111120)+"";
var tmp1=tmp.split(".");
var classStep;
// Elimination des étapes sur 0 mètres
if(tmp1[0]!=0){
if(i % 2 == 0)
classStep = "step_odd";
else
classStep = "step_even";
if(j==0)
\$('<tr onclick=\'routingDisplayCurrentStep('+i+');\'><td id="step_'+i+'" class="'+classStep+'"><span class="fdr_etape">$zoo._("Starting point:") '+(features[i].attributes["name"]?features[i].attributes["name"]:"$zoo._("Unknown road")")+".</span></td><td><img id='img_picto"+i+"' class='fdr_img_picto' src='$conf['main']['publicationUrl']/img/startMarker.png' title='starting point' alt='starting point'/></td></tr>").appendTo(\$("#fdr_cadre"));
else if (j==features.length-1)
\$('<tr onclick=\'routingDisplayCurrentStep('+i+');\'><td id="step_'+i+'" class="'+classStep+'"><span class="fdr_etape">$zoo._("Destination:") '+(features[i].attributes["name"]?features[i].attributes["name"]:"$zoo._("Unknown road")")+".</span></td><td><img id='img_picto"+i+"' class='fdr_img_picto' src='$conf['main']['publicationUrl']/img/endMarker.png' title='destination' alt='destination'/></td></tr>").appendTo(\$("#fdr_cadre"));
else
{
var idEtape = i-1;
var curPicto="/img/"+features[i].attributes["highway"]+".png";
var titlePicto=features[i].attributes["highway"];
\$('<tr onclick=\'routingDisplayCurrentStep('+i+');\'><td id="step_'+i+'" class="'+classStep+'"><span class="fdr_etape">$zoo._("Step") '+eval(System.routingCnt+"+"+idEtape)+" : "+" $zoo._("advance for") "+(tmp1[0])+' $zoo._("meters") $zoo._("on") '+(features[i].attributes["name"]?features[i].attributes["name"]:"$zoo._("Unknown road")")+".</span></td><td><img id='img_picto"+i+"' class='fdr_img_picto' alt='"+titlePicto+"' title='"+titlePicto+"' src='"+curPicto+"'/></td></tr>")
.appendTo(\$("#fdr_cadre"));
}
}
}
}catch(e){alert(e);}
//alert(features[i].geometry);
features[j].geometry=features[j].geometry.transform(geographic,map.getProjectionObject());
System.steps[j]=features[j];
System.stepsFDR[j]=features[j];
nbkm += parseInt(tmp1[0])/1000;
j++;
}
}});
//\$(".fdr_img_picto").tipsy({title: 'alt'});
//alert("nb Features end = " + features.length);
//alert("nb km = " + nbkm + "km");
nbSteps = features.length;
nbkm = nbkm.toFixed(2);
document.getElementById('distancevalue').innerHTML = nbkm + " km";
tempsParcours = calculTempsParcours(nbkm,defaultSpeed);
zTemps = decimalTimeToHourMinutes(tempsParcours);
document.getElementById('chronovalue').innerHTML = zTemps;
document.getElementById('defaultspeedvalue').innerHTML = defaultSpeed + " km/h";
nbkm = 0;
tempsParcours = 0;
}catch(e){
System.retryRouteDisplay+=1;
//RoutingDisplayStep(System.cStep);
}
}});
#end if
}
#if $m.web.metadata.get('layout_t')=="mobile"
function routingFormAddPOI(){
\$('<li data-role="fieldcontain" id="routingAddedPoi'+System.routingPoiCnt+'">')
.append(\$('<fieldset class="ui-grid-a"><a data-role="button" onclick="routingForm(\$(\'#interType'+System.routingPoiCnt+'\').val());" class="ui-block-d" data-icon="interPoint" id="interPoint_'+System.routingPoiCnt+'">Étape</a><select id="interType'+System.routingPoiCnt+'" class="ui-block-d" onchange="routingForm(\$(this).val());"><option value="geocodingPage">Rechercher</option><option value="mapPage">Sur la carte</option><option value="mapPage">Ma position</option></select></fieldset>'))
.appendTo(\$("#routingForm"));
\$("#routingAddedPoi"+System.routingPoiCnt).fadeIn( 400, function(){\$(this).trigger("create");\$("#routingForm").listview("refresh");\$('interPoint_'+System.routingPoiCnt).trigger("create");\$('interType'+System.routingPoiCnt).selectmenu("refresh");\$("#routingDeletePoi").removeClass("hidden"); });
System.routingPoiCnt+=1;
}
function routingFormDeletePOI(){
if(System.routingPoiCnt>0){
System.routingPoiCnt-=1;
\$('#routingAddedPoi'+System.routingPoiCnt+'').fadeOut( 400, function(){\$(this).remove();\$("#routingForm").listview("refresh");
//\$('#routingAddedPoi'+index+'').fadeOut( 400, function(){\$(this).remove();\$("#routingForm").listview("refresh");
points_layer.removeFeatures([points_layer.features[points_layer.features.length-1]]);});
//System.routingPoiCnt=points_layer.features.length;
if(System.routingPoiCnt==0)
\$("#routingDeletePoi").addClass("hidden");
}
}
#else
function routingFormAddPOI(){
if(points_layer.features.length > 1){
System.routingPoiCnt+=1;
var currentIndex = System.nbEtapes+2;
\$("#etapes_2").append('<form id="routingAddedPoi'+System.routingPoiCnt+'" action="#" onsubmit="return false;">'+
'<div>'+
//'<img src="$conf['main']['publicationUrl']/img/design/etape.png" alt="Etape" class="img_recherche" style="margin-bottom:0px;"/>'+
'<label class="lb_section_recherche txt_orange_black">$zoo._('STEP')</label>'+
'<img id="adresse_add_'+System.routingPoiCnt+'" src="$conf['main']['publicationUrl']/img/interMarker0.png" title="$zoo._('Set a step place')" class="button-no-border icon_recherche" height="18px" width="16px"'+
' onclick="System.idPoint=\'stepPoint'+System.nbEtapes+'\';globalResetAction(points_layer,'+currentIndex+');_routingForm();return false;" />'+
'</div>'+
'<div>'+
'<input id="stepPoint'+System.nbEtapes+'" name="adresseEtape'+System.nbEtapes+'" type="text" class="champ_recherche" value="" onfocus="System.idPoint=\'stepPoint'+ System.nbEtapes+'\';globalResetAction(points_layer,'+currentIndex+');return false;" onblur="if(this.value != \'\') {System.nbEtapeFlags +=1;}" onmouseover="this.title=this.value;" />'+
'</div>'+
'</form>');
\$("#routingAddedPoi"+System.routingPoiCnt).fadeIn( 400, function(){
\$("#routingDeletePoi").removeClass("hidden");
});
startSearch1('adresseEtape'+ System.nbEtapes);
eval('\$( "#adresse_add_'+System.routingPoiCnt+'").draggable({'+
'start: function() {'+
' System.idPoint="adresseEtape'+(System.routingPoiCnt-1)+'";'+
' globalResetAction(points_layer,'+(System.routingPoiCnt+1)+');'+
' _routingForm();'+
'},'+
'stop: function(){'+
' draw_points.handler.finalize();'+
'},'+
'scroll: false, revert: true, helper: "clone" });');
System.nbEtapes += 1;
}
}
function routingFormDeletePOI(){
if(System.nbEtapes>0)
System.nbEtapes -= 1;
var currentIndex = System.nbEtapes+2;
for(i in points_layer.features){
if(points_layer.features[i].attributes["idPoint"]=="stepPoint"+System.nbEtapes)
points_layer.removeFeatures([points_layer.features[i]]);
}
\$('#routingAddedPoi'+System.routingPoiCnt).fadeOut( 400, function(){
\$(this).remove();
if(points_layer.features.length > 2 && System.nbEtapeFlags > System.nbEtapes){
//if(testNbPoints())
//points_layer.removeFeatures([points_layer.features[points_layer.features.length-1]]);
//alert('delete ' + currentIndex);
if(System.nbEtapeFlags>0)
System.nbEtapeFlags -= 1;
points_layer.removeFeatures([points_layer.features[currentIndex]]);
//pgrouting(points_layer);
}
});
System.routingPoiCnt-=1;
//System.routingPoiCnt=points_layer.features.length;
//}
if(System.routingPoiCnt==0)
\$("#routingDeletePoi").addClass("hidden");
//alertAction('routingFormDeletePOI end');
}
#end if
// Compare le nombre réel de points et le nombre attendu
function testNbPoints(){
alert("Features count="+points_layer.features.length + ", System count="+System.routingPoiCnt);
if(points_layer.features.length == System.routingPoiCnt)
return true;
else
return false;
}
function routingZoomOnSteps(){
// if(route_layer2.length>0)
// route_layer2.removeFeatures(route_layer2.features);
if(!route_layer1){
route_layer1 = new OpenLayers.Layer.Vector("Route details",{
styleMap: new OpenLayers.Style({
fillColor:"red",
fillOpacity:1,
strokeOpacity:1,
fillColor:"red",
strokeColor:"red",
pointRadius: 10,
strokeWidth:16
}),renderers: System.renderer
});
map.addLayers([route_layer1]);
}
else
route_layer1.removeFeatures(route_layer1.features);
map.setLayerIndex(route_layer1,map.layers.length-5);
route_layer1.addFeatures(System.steps);
map.zoomToExtent(route_layer1.getDataExtent());
}
function routingZoomOnStepsFDR(index){
// if(route_layer1.length>0)
// route_layer1.removeFeatures(route_layer1.features);
if(!route_layer2){
route_layer2 = new OpenLayers.Layer.Vector("Route details",{
styleMap: new OpenLayers.Style({
fillOpacity:1,
strokeOpacity:1,
fillColor:"black",
strokeColor:"#F1E82F",
pointRadius:10,
strokeWidth:16
}),renderers: System.renderer
});
map.addLayers([route_layer2]);
}
else
route_layer2.removeFeatures(route_layer2.features);
route_layer2.addFeatures(System.stepsFDR[index]);
map.setLayerIndex(route_layer2,map.layers.length-6);
var extent = route_layer2.getDataExtent();
var marker = extent.getCenterLonLat();
// var bounds = new OpenLayers.Bounds();
// bounds.extend(new OpenLayers.LonLat(marker.lon,marker.lat));
// bounds.toBBOX();
//var extent2 = new OpenLayers.Bounds(extent.x,extent.y,extent.x,extent.y);
//var extent2 = new OpenLayers.Bounds(extent.x-0.001,extent.y-0.001,extent.x+0.001,extent.y+0.001);
// map.zoomToExtent(bounds);
//alert(map.getZoomForExtent(extent));
var zoomLevel = map.getZoomForExtent(extent)-2;
map.setCenter(new OpenLayers.LonLat(marker.lon,marker.lat), zoomLevel);
//map.zoomToExtent(route_layer2.getDataExtent());
}
var requestedProfile=false;
function requestProfile(){
#import routing.service as routing
#set cl=routing.getRasterLayer($conf)
#if cl is not None
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.showPageLoadingMsg();
#end if
if(System.routingProfileComputed){
#if $m.web.metadata.get('layout_t')=="mobile"
\$.mobile.hidePageLoadingMsg();
#end if
return;
}
var params1=[
{name: "Geometry","xlink:href": System.inputs1, mimeType: "application/json"},
{name: "mult","value": "10",dataTye: "string"},
{name: "RasterFile","value": "$cl.data.replace($conf["main"]["dataPath"],"")",dataType: "string"}
];
var data1=WPSGetHeader("raster-tools.GdalExtractProfile")+WPSGetInputs(params1)+WPSGetOutput({name: "Profile","form":"ResponseDocument","asReference": "true"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data1,
complete: function(xml,status) {
loadProfileAndDisplay(xml);
}
});
#end if
}
function loadProfileAndDisplay(){
//alert("ok");
System.lineUrl=WPSParseReference(arguments[0]);
\$.ajax({
type: "GET",
url: zooUrl+"?service=WPS&request=Execute&version=1.0.0&Identifier=routing.computeDistanceAlongLine&DataInputs=line=Reference@xlink:href="+System.lineUrl+"&RawDataOutput=Result@mimeType=application/json",
complete:function(request,status){
//alert("ok");
var coord;
var distances=new Array();
var json=new OpenLayers.Format.JSON()
try{
tmp=json.read(request.responseText);
distances.push(0.0);
distances0=json.read(tmp["features"][0]["properties"]["distance"]);
for(i=0;i<distances0.length;i++){
distances0[i]=((distances0[i])+(i>0?distances0[i-1]:0));
distances.push(distances0[i]);
}
coord=tmp["features"][0]["geometry"]["coordinates"];
map.updateSize();
//alert("ok");
}catch(e){
alert(e);
}
var values=[];
var j=0;
sspoints=[];
var stmp=new OpenLayers.Geometry.Point(coord[0][0],coord[0][1]);
var ttmp=new OpenLayers.Geometry.Point(coord[coord.length-1][0],coord[coord.length-1][1]);
if(startpoint.distanceTo(ttmp)<=startpoint.distanceTo(stmp))
for(i=coord.length-1;i>=0;i--){
{
if(coord[i][2]>=0)
values[j]=coord[i][2];
else
values[j]=0;
sspoints[j]=[coord[i][0],coord[i][1]];
j+=1;
}
}
else
for(i=0;i<coord.length;i++){
{
if(coord[i][2]>=0)
values[j]=coord[i][2];
else
values[j]=0;
sspoints[j]=[coord[i][0],coord[i][1]];
j+=1;
}
}
//alert("ok");
#if $m.web.metadata.get('layout_t')!="mobile"
//\$('#routingProfileContainer').css({'height':'148px', 'width': (\$(document).width()-415)+'px','z-index': 1000});
\$('#divInnerNorth').css({'height':'50px', 'width': (\$(document).width()-415)+'px','z-index': 1000});
//\$('#map').css({'height': (\$(document).height()-450)+"px"});
//alert("ok");
// Masquage de la zone de recherche
//mmLayout.close('west');
map.updateSize();
//alert("ok");
map.zoomToExtent(System.curExtent);
//alert("ok");
// Premier affichage de la feuille de route
//\$('#feuillederoute').removeClass('hidden');
// Ouverture du panneau de feuille de route
//mmLayout.open('east');
// var innerLayout = \$('.middle-center').layout();
//Ouverture du panneau de profil
// innerLayout.open('south');
// Alerte sécurité
//loadGCPWindow('windows/alerte_securite',' ',280,28);
//loadCenterPopup('windows/alerte_securite','Alerte',280,28);
#end if
var mmax=0;
for(var t=0;t<values.length;t++)
if(values[t]>mmax)
mmax=values[t];
$.ajax({
url: "./modules/routing/profile",
complete: function(xml,status){
if(!\$('#profile-dialog')[0])
\$("body").append('<div id="profile-dialog" title="'+"$zoo._("Profile")"+'"></div>');
\$('#profile-dialog').html("");
\$('#profile-dialog').append(xml.responseText);
\$('#profile-dialog').window({
width: 625,
height: 420,
maximizable:false,
resizable: false
});
Highcharts.setOptions({
lang: {
resetZoomTitle: "$zoo._("Reset to initial zoom level")",
resetZoom: "$zoo._("Reset zoom")"
}
});
var chart = new Highcharts.Chart({
chart: {
zoomType: 'x',
renderTo: 'routingProfileContainer'
},
title: {
text: "$zoo._('Elevation profile')"
},
xAxis: {
labels: {
formatter: function(){
var tmp=this.value+"";
if(tmp.indexOf('.')!=0)
if(distances[tmp])
return parseDistance(Math.round(distances[tmp]*111120));
}
},
title: { text: "$zoo._("Distance")" },
events: {
afterSetExtremes: function(){
if(\$("#profileZoomOnMap").is(':checked')){
if(!sspoints[parseInt(this.min)])
this.min=0;
if(!sspoints[parseInt(this.max)])
this.max=sspoints.length-1;
if(this.min==0 && this.max==sspoints.length-1){
if(route_layer1)
route_layer1.removeFeatures(route_layer1.features);
map.zoomToExtent(System.curExtent);
return false;
}
\$.ajax({
type: "GET",
url: zooUrl+"?service=WPS&request=Execute&version=1.0.0&Identifier=routing.splitLine&DataInputs=startPoint="+sspoints[parseInt(this.min)]+";endPoint="+sspoints[parseInt(this.max)]+";line=Reference@xlink:href="+encodeURIComponent(System.lineUrl)+"&ResponseDocument=Result@asReference=true@mimeType=text/xml",
dataType: 'xml',
complete:function(xml,status){
System.tmpMUrl=WPSParseReference(xml);
\$.ajax({
type: "GET",
dataType: "xml",
url: System.tmpMUrl+"&request=GetFeature&service=WFS&version=1.0.0&typename=Result",
success: function(xml){
if(route_layer1)
route_layer1.removeFeatures(route_layer1.features);
var gml = new OpenLayers.Format.GML();
var features=gml.read(xml);
for(var j=0;j<features.length;j++)
features[j].geometry=features[j].geometry.transform(geographic,map.getProjectionObject());
if(\$("#profileZoomOnMap").val()=='on'){
System.steps=features;
//System.stepsFDR=features;
routingZoomOnSteps();
}
}
});
}
});
}
else{
if(\$("#profileZoomOnMap").is(':checked')){
if(route_layer1)
route_layer1.removeFeatures(route_layer1.features);
map.zoomToExtent(System.curExtent);
}
if(route_layer1)
route_layer1.removeFeatures(route_layer1.features);
}
//alert("ZOOM End : "+sspoints[parseInt(this.min)]+" "+sspoints[parseInt(this.max)]);
}
},
maxZoom: 0
},
yAxis: {
max: mmax*2,
title: { text: null },
startOnTick: false,
showFirstLabel: false
},
legend: {
enabled: false
},
plotOptions: {
area: {
cursor: 'pointer',
point: {
events: {
click: function() {
if(\$("#profileZoomOnMap").is(':checked'))
map.zoomToExtent(System.curExtent);
if(points_layer1.features.length>0)
points_layer1.removeFeatures(points_layer1.features);
var tmp=new OpenLayers.Geometry.Point(sspoints[this.x][0],sspoints[this.x][1]);
tmp.transform(wgs84,mercator);
points_layer1.removeFeatures(points_layer1.features);
points_layer1.addFeatures([new OpenLayers.Feature.Vector(tmp,null,null)]);
}
}
},
fillColor: {
linearGradient: [0, 0, 0, 300],
stops: [
[0, '#74B042'],
[1, 'rgba(255,255,255,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 3
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
tooltip: {
formatter: function() {
if(points_layer1.features.length>0)
points_layer1.removeFeatures(points_layer1.features);
var tmp=new OpenLayers.Geometry.Point(sspoints[this.x][0],sspoints[this.x][1]);
tmp.transform(wgs84,mercator);
points_layer1.removeFeatures(points_layer1.features);
points_layer1.addFeatures([new OpenLayers.Feature.Vector(tmp,null,null)]);
return '<h1>$zoo._("Altitude: ")'+Highcharts.numberFormat(this.y, 0)+"</h1>";
}
},
series: [{
name: "$zoo._('Elevation')",
type: 'area',
data: values
}]
});
\$('.highcharts-tracker').mouseleave(function(){
if(points_layer1.features.length>0)
points_layer1.removeFeatures(points_layer1.features);
});
\$('#routingProfileContainer').mouseleave(function(){
if(points_layer1.features.length>0)
points_layer1.removeFeatures(points_layer1.features);
});
map.zoomToExtent(System.curExtent);
System.routingProfileComputed=true;
}});
}
});
}
function RoutingReinit(){
if(route_layer){
try{
points_layer.removeFeatures(points_layer.features);
map.removeLayer(route_layer);
route_layer=false;
map.removeLayer(route_layer1);
route_layer1=false;
}catch(e){}
}
else{
if(dd_layer)
try{
points_layer.removeFeatures(points_layer.features);
map.removeLayer(dd_layer);
dd_layer=false;
}
catch(e){
}
}
//\$("#link_export").hide();
#if $m.web.metadata.get('layout_t')=="mobile"
\$("#toolbarLink").attr("href","#toolbarPage");
\$('#mapPage').trigger("pageshow");
//\$('#mapPage').page('destroy').page();
\$.mobile.changePage('#mapPage');
\$.mobile.changePage('#toolbarPage');
#end if
}
function backButtonForGeocoding(backLink){
\$("#toolbarLink").attr("href",backLink);
/*\$('<div class="ui-loader1 ui-overlay-shadow ui-body-d ui-corner-all"><div data-role="controlgroup" data-type="horizontal"><a href="'+backLink+'" class="bckBtn" data-role="button" data-inline="true" data-icon="arrow-l" onclick="\$(this).fadeOut( 400, function(){\$(this).parent().remove();});">Retour</a>'+
(backLink=="#geocodingPage"?'<a href="#routingPage" data-role="button" data-inline="true" class="bckBtn" onclick="\$(this).fadeOut( 400, function(){\$(this).parent().remove();});">Choisir</a>':'')
+'</div>')
.css({ "display": "block", "opacity": 0.96, "top": \$(window).scrollTop() + 100, "position": "absolute", "left": "50%", "z-index": "10000", "margin-left": "-130px", "margin-top": "-35px" })
.appendTo( \$("#mapPage") );*/
//\$('#mapPage').page('destroy').page();
}
function doRun(){
toggleControl({"name":"search"});
toggleControl({name: 'draw_points'});
toggleControl({name: 'drag_points'});
tselect[tselect.length-1].activate();
/*try{
tselect[tselect.length-1].deactivate();
}catch(e){}*/
}
function codeAddressOld(address) {
//var address = \$("#address")[0].value+" FRANCE";
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.showPageLoadingMsg();
#end if
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.hidePageLoadingMsg();
#end if
System.addresses=new Array();
\$('#search_geocoding_results').empty();
for(var i=0;i<results.length;i++){
System.addresses[i]=results[i];
\$('<li id="place_'+i+'" data-icon="arrow-r" data-theme="d">')
.hide()
.append(\$('<a />', {
href: "#mapPage",
text: results[i].formatted_address,
onclick: doRun()
}).append(\$('<span class="ui-icon-arrow-r">')))
.appendTo('#search_geocoding_results')
.click(function() {
var tmp=this.id.split('_');
geolocation.removeFeatures(geolocation.features);
var tmp=this.id.split('_');
backButtonForGeocoding("#geocodingPage");
var sw = System.addresses[tmp[1]].geometry.viewport.getSouthWest();
var ne = System.addresses[tmp[1]].geometry.viewport.getNorthEast();
var extent= new OpenLayers.Bounds(sw.lng(),sw.lat(),ne.lng(),ne.lat()).transform(wgs84,mercator);
var marker = extent.getCenterLonLat();
map.zoomToExtent(extent);
//geolocation.addMarker(new OpenLayers.Marker(marker,icon));
//System.searchFields[\$("#slayer")[0].value][2][tmp[1]].geometry.transform(wgs84,mercator);
//alert(marker.lat+" "+marker.lon);
points_layer.addFeatures([new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(marker.lon,marker.lat),{id:points_layer.features.length, name: System.addresses[tmp[1]]["formatted_address"], type: (points_layer.features.length==0?"start":(points_layer.features.length==1?"end":"inter"))})]);
mapControls["drag_points"].activate();
#if $m.web.metadata.get('layout_t')=="mobile"
\$.mobile.changePage('#mapPage');
#end if
//map.zoomToExtent(System.searchFields[\$("#slayer")[0].value][2][tmp[1]].geometry.bounds);
})
.show();
\$('#search_geocoding_results').listview('refresh');
}
/*if(System.defaultBounds.contains(extent)){
map.zoomToExtent(extent);
markers.addMarker(new OpenLayers.Marker(marker,icon));
}else
alert("Adresse non trouvee.dans votre RVS");
*/
} else {
alert("Adresse non trouvee.");
for(i=0;i<markers.markers.length;i++)
markers.markers[i].erase();
}
});
}
function codeAddress(address) {
//var address = \$("#address")[0].value+" FRANCE";
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.showPageLoadingMsg();
#end if
System.address=address;
\$.ajax({
type: "GET",
url: "$conf["main"]["serverAddress"]?service=WPS&version=1.0.0&request=Execute&Identifier=routing.geocodeAdresse&DataInputs=search="+System.address+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
#if $m.web.metadata.get('layout_t')=="mobile"
$.mobile.hidePageLoadingMsg();
#end if
try{
var results=\$.parseJSON(xml.responseText);
System.addresses=new Array();
\$('#search_geocoding_results').empty();
for(var i=0;i<results.length;i++){
System.addresses[i]=results[i];
\$('<li id="place_'+i+'" data-icon="arrow-r" data-theme="d">')
.hide()
.append(\$('<a />', {
href: "#mapPage",
text: results[i].label,
onclick: doRun()
}).append(\$('<span class="ui-icon-arrow-r">')))
.appendTo('#search_geocoding_results')
.click(function() {
var tmpId=this.id.split('_');
geolocation.removeFeatures(geolocation.features);
backButtonForGeocoding("#geocodingPage");
var stmp=new OpenLayers.Geometry.Point(System.addresses[tmpId[1]].geometry.coordinates[0],System.addresses[tmpId[1]].geometry.coordinates[1]);
var extent= new OpenLayers.Bounds(stmp.x-0.001,stmp.y-0.001,stmp.x+0.001,stmp.y+0.001);
stmp1=stmp.transform(geographic,mercator);
points_layer.addFeatures([new OpenLayers.Feature.Vector(stmp,{id:points_layer.features.length, name: System.addresses[tmpId[1]]["label"], type: (points_layer.features.length==0?"start":(points_layer.features.length==1?"end":"inter"))})]);
map.zoomToExtent(extent.transform(geographic,mercator));
mapControls["drag_points"].activate();
#if $m.web.metadata.get('layout_t')=="mobile"
\$.mobile.changePage('#mapPage');
#end if
})
.show();
\$('#search_geocoding_results').listview('refresh');
}
}catch(e){
alert(e);
alert("$zoo._("No address found")");
for(i=0;i<markers.markers.length;i++)
markers.markers[i].erase();
}
}
});
}
function routingForm(a){
if(a=="mapPage"){
if(arguments.length>1)
backButtonForGeocoding(arguments[1]);
else
backButtonForGeocoding('#routingPage');
//toggleControl({name: 'draw_points'});
mapControls['draw_points'].activate();
mapControls["drag_points"].activate();
//try{tselect[tselect.length-1].deactivate();}catch(e){}
}
$.mobile.changePage("#"+a);
}
function _routingForm(){
//toggleControl({name: 'draw_points'});
for(i in map.controls){
if(map.controls[i] && map.controls[i].active){
System.revActivated=map.controls[i];
map.controls[i].deactivate();
}
}
for(i in points_layer.features)
if(points_layer.features[i].attributes["idPoint"]==System.idPoint)
points_layer.removeFeatures([points_layer.features[i]]);
mapControls['draw_points'].activate();
mapControls["drag_points"].activate();
//try{tselect[tselect.length-1].deactivate();}catch(e){}
}
function displayRoadmap(a){
if(a>0){
\$('.ui-layout-east').removeClass('hidden');
\$(".ui-layout-east").css({"z-index": "1"});
\$('.ui-layout-center').css({"width": (\$(document).width()-(260+295))+"px"});
map.updateSize();
\$('#routingProfileContainer').css({"width": (\$(document).width()-(260+295))+"px"});
}
else{
\$('.ui-layout-east').addClass('hidden');
\$(".ui-layout-east").css({"z-index": "0"});
\$('.ui-layout-center').css({"width": (\$(document).width()-(280+0))+"px"});
map.updateSize();
\$('#routingProfileContainer').css({"width": (\$(document).width()-(280+0))+"px"});
}
}
var timeOut;
\$("#jFlowNext0").click(function(e,simulated){
if(!simulated){
clearTimeout(timeOut);
}
});
function autoAdvance(){
\$("#jFlowNext0").trigger('click',[true]);
timeOut = setTimeout(autoAdvance,4000);
};
function aZoomTo(){
var geometry=arguments[0];
var stmp=new OpenLayers.Geometry.Point(geometry.coordinates[0],geometry.coordinates[1]);
var extent= new OpenLayers.Bounds(stmp.x-0.001,stmp.y-0.001,stmp.x+0.001,stmp.y+0.001);
stmp.transform(geographic,mercator);
points_layer.removeFeatures(points_layer.features);
points_layer.addFeatures([new OpenLayers.Feature.Vector(stmp,{id:points_layer.features.length, type: (points_layer.features.length==0?"start":(points_layer.features.length==1?"end":"inter"))})]);
map.zoomToExtent(extent.transform(geographic,mercator));
}
var currentTerm="";
function startSearch1(){
System.addresses=new Array();
\$( "#"+arguments[0] ).autocomplete({
source: function(request,response){
//codeAddress(request.term);
currentTerm = SansAccents(request.term);
//alert(currentTerm);
System.address=currentTerm;
\$.ajax({
type: "GET",
url: "$conf["main"]["serverAddress"]?service=WPS&version=1.0.0&request=Execute&Identifier=routing.geocodeAdresse&DataInputs=search="+System.address+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
try{
var results=\$.parseJSON(xml.responseText);
\$('#search_geocoding_results').empty();
var data=[];
for(var i=0;i<results.length;i++){
System.addresses[i]=results[i];
data[data.length]={
id: i,
label: results[i].label,
tabindex: i
}
}
response(data);
}catch(e){
alert(e);
alert("$zoo._("No address found")");
for(i=0;i<markers.markers.length;i++)
markers.markers[i].erase();
}
}
});
},
select: function( event, ui ) {
geolocation.removeFeatures(geolocation.features);
var tmp=["",ui.item.id];
#if $m.web.metadata.get('layout_t')!="mobile"
backButtonForGeocoding("#geocodingPage");
#end if
var tmpId=ui.item.id;
var stmp=new OpenLayers.Geometry.Point(System.addresses[tmpId].geometry.coordinates[0],System.addresses[tmpId].geometry.coordinates[1]);
var extent= new OpenLayers.Bounds(stmp.x-0.001,stmp.y-0.001,stmp.x+0.001,stmp.y+0.001);
stmp1=stmp.transform(geographic,mercator);
points_layer.addFeatures([new OpenLayers.Feature.Vector(stmp,{id:points_layer.features.length, name: System.addresses[tmpId]["label"], type: (points_layer.features.length==0?"start":(points_layer.features.length==1?"end":"inter"))})]);
map.zoomToExtent(extent.transform(geographic,mercator));
mapControls["drag_points"].activate();
toggleControl({"name":"draw_points"})
mapControls["drag_points"].activate();
if(System.idPoint.indexOf("adresseEtape") != -1)
System.nbEtapeFlags +=1;
}
});
#if $m.web.metadata.get('layout_t')!="mobile"
\$("#"+System.idPoint).trigger("onchange");
#end if
}
function updateAdressTitle(){
var adresse = \$( "#" + System.idPoint ).val();
\$( "#"+ System.idPoint ).attr('title', adresse);
//alert(adresse);
}
function globalResetAction(layer,index){
if((System.idPoint=="adresseLieu") || (System.idPoint.indexOf("adresseDepart") != -1)){
if(layer.features.length>0)
layer.removeFeatures([layer.features[0]]);
}
else if(System.idPoint.indexOf("adresseArrivee") != -1){
if(layer.features.length>1)
layer.removeFeatures([layer.features[1]]);
}
else if(System.idPoint.indexOf("adresseEtape") != -1){
var tmpi=eval(System.idPoint.replace(/adresseEtape/g,""));
if(layer.features.length>tmpi+2){
layer.removeFeatures([layer.features[tmpi+2]]);
}
}
}
function alertAction(call){
alert(call + ': NbEtapes=' + System.nbEtapes + ', NbEtapeFlags=' + System.nbEtapeFlags + ', NbFeatures=' + points_layer.features.length);
}
function removeFeatureIndex(layer,mode){
//alert("Features count="+layer.features.length + ", System count="+System.routingPoiCnt);
if(mode=='depart')
index = 0;
else if(mode=='arrivee')
index = 1;
else if(mode=='etape'){
//alert("Etape : Features count="+layer.features.length + ", System count="+System.routingPoiCnt);
//index = System.routingPoiCnt;
index = layer.features.length;
if (index < 2)
index = 2;
}
if(layer.features.length > index){
//alert('remove ' + index);
layer.removeFeatures([layer.features[index]]);
// if(System.routingPoiCnt>0)
// if(idPoint.indexOf("adresseEtape") == -1)
//System.routingPoiCnt-=1;
//System.routingPoiCnt=points_layer.features.length;
}
}
function removePolygon(){
try{
if(dd_layer){
map.removeLayer(dd_layer);
dd_layer=false;
}
}catch(e){
//alert(e);
//alert(e.message);
}
}
function removeAllFeatures(){
try{
\$("#link_export").hide();
\$("#link_print").hide();
initFdrMode();
System.routingPoiCnt=0;
System.nbEtapes = 0;
System.nbEtapeFlags = 0;
currentIdStepDisplayed = 0;
previousIdStepDisplayed = 0;
nbSteps = 0;
if(route_layer){
map.removeLayer(route_layer);
route_layer=false;
}
if(route_layer1){
map.removeLayer(route_layer1);
route_layer1=false;
}
if(route_layer2){
map.removeLayer(route_layer2);
route_layer2=false;
}
if(dd_layer){
map.removeLayer(dd_layer);
dd_layer=false;
}
for(var i=0;i<layersList.length;i++){
if(layersList[i].real_name=="Sites"){
layersList[i].removeFeatures(layersList[i].features);
}
}
map.setLayerIndex(System.hover,map.layers.length-1);
map.setLayerIndex(points_layer,map.layers.length-2);
map.setLayerIndex(points_layer1,map.layers.length-3);
if(points_layer.features.length > 0)
points_layer.removeFeatures(points_layer.features);
if(points_layer1.features.length > 0)
points_layer1.removeFeatures(points_layer1.features);
\$("#etapes_2").empty();
map.updateSize();
#if $m.web.metadata.get('layout_t')!="mobile"
hideProfil('true');
#end if
map.updateSize();
}catch(e){
alert("OK"+e);
//alert(e.message);
}
}
/*
* Sans Accents
*/
function SansAccents (my_string) {
var new_string = "";
//Const ACCENT = "àáâãäåòóôõöøèéêëìíîïùúûüÿñç-'&?|+*=]["
var pattern_accent = new Array("à", "á", "â", "ã", "ä", "å", "ò", "ó", "ô", "õ", "ö", "ø", "é", "è", "ê", "ë", "ç", "ì", "í", "î", "ï", "ù","ú","û","ü","ÿ","ñ", "-", "'", "&", "=", "_");
var pattern_replace_accent = new Array("a", "a", "a", "a", "a", "a", "o", "o", "o", "o", "o", "o", "e", "e", "e", "e", "c", "i", "i", "i", "i", "u","u","u","u","y","n", " ", " ", " ", " ", " ");
if (my_string && my_string!= "") {
new_string = preg_replace(pattern_accent, pattern_replace_accent, my_string.toLowerCase());
}
return new_string;
}
function preg_replace (array_pattern, array_pattern_replace, my_string) {
var new_string = String (my_string);
for (i=0; i<array_pattern.length; i++) {
var reg_exp= RegExp(array_pattern[i], "gi");
var val_to_replace = array_pattern_replace[i];
new_string = new_string.replace (reg_exp, val_to_replace);
}
return new_string;
}
/* Fin Sans Accents */
<|start_filename|>mapmint-ui/new-themes/themes/pink/forms.css<|end_filename|>
ul.style-tabs-nav1 li a.selected,
ul.style-tabs-nav1 li a:hover, a.classify:hover {
color:#FFFFFF;position:relative;top:1px;left:0px;text-shadow:#333333 0 1px 0;
background: #f630f8; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f869ec', endColorstr='#f630f8'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#f869ec), to(#f630f8)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
}
ul.style-tabs-nav li a.selected,
ul.style-tabs-nav li a:hover, a.classify:hover {
color:#FFFFFF;position:relative;top:1px;left:0px;text-shadow:#333333 0 1px 0;
background: #f630f8; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f869ec', endColorstr='#f630f8'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#f869ec), to(#f630f8)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
}
.customfile-hover .customfile-button, .customfile-focus .customfile-button { color:#111; background: #f51aed; border-color:#FFFFFF;padding: .3em .6em;}
<|start_filename|>mapmint-ui/js/main.js<|end_filename|>
System.libpath="http://localhost/mm-trunk/mapmint-ui//js/";
System.require("MLayout");
System.require("Dashboard");
System.require("Territories");
System.require("Datawarehouse");
System.require("Styler");
System.require("Mapmanager");
System.shouldStart=true;
var layouts=[];
var cLayout=null;
function showInnerLayout ( name ) {
cLayout=layouts[0];
var altName=cLayout.name;
for(var i=0;i<layouts.length;i++){
if(name != layouts[i].name){
altName = layouts[i].name;
$( "#"+altName+"_button" )[0].parentNode.className="current";
$( "#"+ altName ).hide(); // hide OTHER layout container
}
else
cLayout=layouts[i];
}
$( "#"+name+"_button" )[0].parentNode.className="dashboard";
if($( "#"+ name ).length==1)
$( "#"+ name ).show(); // show THIS layout container
// if layout is already initialized, then just resize it
if(cLayout.layout)
cLayout.layout.resizeAll();
if($("#"+name).length==0){
$('#progress_bar .ui-progress .ui-label').hide();
$.ajax({
type: "GET",
url: System.libpath+"../layouts/"+name+".xml",
dataType: "xml",
complete: function(xml,status) {
$('#progress_bar .ui-progress').css('width', '65%');
$(".ui-layout-center").append(xml.responseText);
$('#progress_bar .ui-progress').css('width', '85%');
$('#progress_bar .ui-progress').css('width', '95%');
$('#'+name).css('height', '100%');
cLayout.layout=$('#'+name).layout( cLayout.layoutOptions );
cLayout.initialize();
//showInnerLayout(name);
$('#progress_bar .ui-progress').animateProgress(100, function() {
$('#progress_bar .ui-progress').fadeOut(1000);
});
}
});
}
cLayout.refresh();
$('a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
$('.ui-layout-toggler').tipsy({fade: true, offset:3, opacity: 1, gravity: 'w'});
$('.toolbar a').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
};
function resizeInnerLayout () {
for(var i=0;i<layouts.length;i++)
if(layouts[i].layout && $("#"+layouts[i].name).is(":visible"))
layouts[i].layout.resizeAll();
};
function updateSize(){
var li=0;
for(var l in layouts){
if(layouts[l].updateSize){
try{
layouts[l].updateSize();
}catch(e){alert(e);}
}
li++;
}
}
$(document).ready(function () {
System.start=function(){
outerLayout = $('body').layout({
// resizable: false
//, closable: false
spacing_closed: 0
, spacing_open: 4
, south__size: 40
, south__spacing_open:0
, south__spacing_closed:0
, south__resizable: false // OVERRIDE the pane-default of 'resizable=true'
, south__slidable: false
, south__closable: false
, north__size: 100
, north__slidable: false
, north__spacing_open:0
, north__spacing_closed:0
, north__closable: false
, north__resizable: false
, north__showOverflowOnHover: true
, north__togglerLength_closed: '100%' // toggle-button is full-width of resizer-bar
,center__showOverflowOnHover: true
, center__onresize: resizeInnerLayout
, resizeWhileDragging: true
, triggerEventsWhileDragging: false
, onopen: function() {updateSize();}
, onclose: function() {updateSize();}
, onresize: function() {updateSize();}
});
layouts=[new Dashboard("Dashboard")];
$('.inner-center').html('<p><img src="../images/ajax-loader.gif" width="220" height="19" /></p>');
showInnerLayout( "Dashboard" );
for(var i=0;i<layouts.length;i++){
$("#"+layouts[i].name+"_button").click( showInnerLayout.mbindWithArg($('testing'),layouts[i].name) );
}
}
System.ensure_included();
});
<|start_filename|>mapmint-services/datastores/service.js<|end_filename|>
var zoo_url;
function mmVectorInfo2MapJs(conf,inputs,outputs){
var myInputs=inputs;
var myOutputs= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
zoo_url=conf["main"]["serverAddress"];
var myProcess = new ZOO.Process(zoo_url,'mapfile.mmDataStoreHasMap');
var myExecuteResult=myProcess.Execute(myInputs,myOutputs,"Cookie: MMID="+conf["senv"]["MMID"]+";");
alert("ok",myExecuteResult);
var myExecuteResult1;
/*try{*/
if(!eval(myExecuteResult)){
var myInputs1=inputs;
myInputs1["dataSource"]=myInputs1["dataStore"];
zoo_url=conf["main"]["serverAddress"];
var myProcess = new ZOO.Process(zoo_url,'vector-tools.mmVectorInfo2Map');
var myOutputs1= {Result: { type: 'RawDataOutput', "mimeType": "text/xml" }};
myExecuteResult1=myProcess.Execute(myInputs1,myOutputs1,"Cookie: MMID="+conf["senv"]["MMID"]+";");
alert(myExecuteResult1);
return {result: ZOO.SERVICE_SUCCEEDED, outputs: {"Result":{"mimeType":"text/xml","encoding":"utf-8","value":myExecuteResult1}} };
}
/*}catch(e){
var conf1=conf
conf["lenv"]["message"]="Error in mapfile.mmDataStoreHasMap"
return result: ZOO.SERVICE_SUCCEEDED, conf: conf1}
}*/
zoo_url=conf["main"]["serverAddress"];
var myProcess = new ZOO.Process(zoo_url,'mapfile.mmVectorInfo2MapPy');
myExecuteResult1=myProcess.Execute(myInputs,myOutputs,"Cookie: MMID="+conf["senv"]["MMID"]+";");
return {result: ZOO.SERVICE_SUCCEEDED, outputs: {"Result":{"mimeType":"text/xml","encoding":"utf-8","value":myExecuteResult1}} };
}
<|start_filename|>mapmint-services/mapfile/service.js<|end_filename|>
/******************************************************************************
* Author: <NAME>, <EMAIL>
* Copyright (c) 2011-2014, Cartoworks Inc.
******************************************************************************
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************/
function getInitialInfo(conf,inputs,outputs){
// Pass the value as json
//var myInputs = {map: { type: 'string', value: fGJ.write(inputData), mimeType: "application/json"}, BufferDistance: {type: 'float', "value": bDist } };
var myOutputs0= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
var myProcess0 = new ZOO.Process(conf["main"]["serverAddress"],'mapfile.canAccessLayer');
alert(inputs);
var myExecuteResult0=myProcess0.Execute(inputs,myOutputs0,"Cookie: MMID="+conf["senv"]["MMID"]);
alert(myExecuteResult0);
if(myExecuteResult0=="false"){
conf["lenv"]["message"]="You're not allowed to access this ressource !";
alert(conf["lenv"]["message"]);
return {result: ZOO.SERVICE_FAILED, conf: conf}
}
var myOutputs= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
var myProcess = new ZOO.Process(conf["main"]["serverAddress"],'mapfile.getMapLayersInfo');
alert(inputs);
var myExecuteResult=myProcess.Execute(inputs,myOutputs);
alert(myExecuteResult);
try{
var tmp=eval(myExecuteResult.replace(/None/g,"null"));
var myInputs;
alert(tmp[0]);
if((tmp[0][0]=='P' && tmp[0][1]=='G' && tmp[0][2]==':') || (tmp[0][0]=='M' && tmp[0][1]=='y' && tmp[0][5]==':')){
alert("OK");
myInputs = {"dataSource": { type: 'string', "value": tmp[0] }, "layer": { type: 'string', "value": tmp[1] }};
}
else
myInputs = {"dataSource": { type: 'string', "value": tmp[0] }, "layer": { type: 'string', "value": tmp[1] }};
alert("OK0");
alert(myInputs["dataSource"]["value"]);
var myOutputs1= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
var myProcess1 = new ZOO.Process(conf["main"]["serverAddress"],'vector-tools.mmExtractVectorInfo');
var myExecuteResult1=myProcess1.Execute(myInputs,myOutputs);
alert("OK1");
alert(myExecuteResult1);
alert("OK1");
return {result: ZOO.SERVICE_SUCCEEDED, outputs: {"Result": {"mimeType": "text/xml",encoding: "utf-8", value: myExecuteResult1}}};
}catch(e){
conf["lenv"]["message"]=e;
alert(conf["lenv"]["message"]);
return {result: ZOO.SERVICE_FAILED, conf: conf}
}
}
function saveLabelJS(conf,inputs,outputs){
try{
var myOutputs0= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
var myProcess0 = new ZOO.Process(conf["main"]["serverAddress"],'mapfile.isPolygon');
var myExecuteResult0=myProcess0.Execute(inputs,myOutputs0,"Cookie: MMID="+conf["senv"]["MMID"]);
alert(myExecuteResult0);
if(myExecuteResult0=="True"){
if(inputs["layer"]["value"].indexOf("vtile_")<0){
var hasFill=false;
for(i in inputs)
if(i=="mmFill"){
hasFill=true;
break;
}
if(hasFill){
url=conf["main"]["mapserverAddress"]+"?map="+conf["main"]["dataPath"]+"/maps/search_"+conf["senv"]["last_map"]+"_"+inputs["layer"]["value"]+".map&request=GetFeature&service=WFS&version=1.0.0&typename="+inputs["layer"]["value"];
var inputs1= {"InputPolygon": { "type": "reference", "value": url, "mimeType": "text/xml"}};
var myOutputs1= {"Result": { type: 'ResponseDocument', "mimeType": "text/xml", "asReference": true }};
var myProcess1 = new ZOO.Process(conf["main"]["serverAddress"],'vector-tools.PointOnSurface');
var myExecuteResult1=myProcess1.Execute(inputs1,myOutputs1,"Cookie: MMID="+conf["senv"]["MMID"]);
var w=new ZOO.Format.WPS();
try{
tmp=w.read(myExecuteResult1);
for(i in tmp)
alert(i,tmp[i]);
alert("Reference: ",tmp.value);
var mapfile=tmp.value.split('&');
mapfile=mapfile[0].split("=");
var inputs2=inputs;
/* Convert GML to Shapefile */
var inputs22={"InputDS":{"type":"reference","value":conf["main"]["mapserverAddress"]+"?map="+mapfile[1]+"&request=GetFeature&service=WFS&version=1.0.0&typename=Result","mimeType": "text/xml"}};
var mpp=mapfile[1].split("/");
var mp=mpp[mpp.length-1].split(".")[0];
inputs22["InputDSN"]={"type":"string","value":mp+".shp"};
inputs22["OutputDSN"]={"type":"string","value":mp+".shp"};
inputs22["F"]={"type":"string","value":"ESRI Shapefile"};
var myOutputs22= {"OutputedDataSourceName": { type: 'ResponseDocument',"asReference": true, "mimeType":"application/unknown" }};
var myProcess22=new ZOO.Process(conf["main"]["serverAddress"],'vector-converter.Ogr2Ogr');
var myExecuteResult22=myProcess22.Execute(inputs22,myOutputs22,"Cookie: MMID="+conf["senv"]["MMID"]);
var omap=inputs["map"]["value"];
inputs2["map"]["value"]=mapfile[1];
var lname=inputs["layer"]["value"];
inputs2["layer"]["value"]="Result";
inputs2["fullPath"]={"type": "boolean","value": "true"};
alert(mapfile[1]);
var myOutputs2= {"Result": { type: 'RawDataOutput'}};
var myProcess2 = new ZOO.Process(conf["main"]["serverAddress"],'mapfile.saveLabel');
var myExecuteResult2=myProcess2.Execute(inputs2,myOutputs2,"Cookie: MMID="+conf["senv"]["MMID"]);
alert(myExecuteResult2);
inputs2["omap"]={"type": "string","value": omap};
inputs2["layer"]["value"]=lname;
var myOutputs2= {"Result": { type: 'RawDataOutput'}};
var myProcess2 = new ZOO.Process(conf["main"]["serverAddress"],'mapfile.addLabelLayer0');
var myExecuteResult2=myProcess2.Execute(inputs2,myOutputs2,"Cookie: MMID="+conf["senv"]["MMID"]);
alert(myExecuteResult2);
outputs["Result"]["value"]=myExecuteResult2;
return {result: ZOO.SERVICE_SUCCEEDED, outputs: outputs};
}catch(e){
alert(e);
conf["lenv"]["message"]=e;
return {result: ZOO.SERVICE_FAILED, conf: conf};
}
}else{
var myOutputs2= {"Result": { type: 'RawDataOutput'}};
var myProcess2 = new ZOO.Process(conf["main"]["serverAddress"],'mapfile.removeLabelLayer');
var myExecuteResult2=myProcess2.Execute(inputs,myOutputs2,"Cookie: MMID="+conf["senv"]["MMID"]);
alert(myExecuteResult2);
return {result: ZOO.SERVICE_SUCCEEDED, outputs: {"Result":{"dataType": "string","value": myExecuteResult2}}};
}
}else{
alert('PROCESS VECTOR TILEINDEX');
conf["lenv"]["message"]="Not capable to create labels for vector tileindex yet.";
// List datasources present in the index
var myInputs= {
"map": { "type": "string", "value": inputs["map"]["value"]},
"layer": { "type": "string", "value": inputs["layer"]["value"]},
};
var myOutputs= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
var myProcess = new ZOO.Process(conf["main"]["serverAddress"],'mapfile.getMapLayersInfo');
var myExecuteResult=myProcess.Execute(inputs,myOutputs);
alert(myExecuteResult);
try{
var tmpData=eval(myExecuteResult);
}catch(e){
conf["lenv"]["message"]="Unable to parse layer informations!";
return {result: ZOO.SERVICE_FAILED,conf: conf};
}
var myInputs0= {
"dstName": {"type":"string","value":tmpData[0]},
"dsoName": {"type":"string","value":tmpData[1]},
"q": {"type":"string","value": "SELECT LOCATION FROM "+inputs["layer"]["value"]+" ORDER BY LOCATION ASC"},
"dialect": {"type":"string","value":"sqlite"}//{ "type": "reference", "value": "file://"+tmpData[0]+"/"+tmpData[1]+".shp", "mimeType": "text/xml"}
};
var myOutputs0= {"Result": { type: 'RawDataOutput'}};
var myProcess0 = new ZOO.Process(conf["main"]["serverAddress"],'vector-tools.vectInfo');
var myExecuteResult0=myProcess0.Execute(myInputs0,myOutputs0,"Cookie: MMID="+conf["senv"]["MMID"]);
alert(myExecuteResult0);
try{
var tmpDataSet=eval(myExecuteResult0);
}catch(e){
conf["lenv"]["message"]="Unable to parse layer informations! "+e;
return {result: ZOO.SERVICE_FAILED,conf: conf};
}
var filesToRemove=[];
var filesToIndex=[];
// Compute PointOnSurface for each datasource
for(var i=0;i<tmpDataSet.length;i++){
alert(tmpDataSet[i]["LOCATION"].split(',')[0]);
url="file://"+tmpDataSet[i]["LOCATION"].split(',')[0];
alert(url);
var inputs1= {"InputPolygon": { "type": "reference", "value": url, "mimeType": "text/xml"}};
var myOutputs1= {"Result": { type: 'ResponseDocument', "mimeType": "text/xml", "asReference": true }};
var myProcess1 = new ZOO.Process(conf["main"]["serverAddress"],'vector-tools.PointOnSurface');
var myExecuteResult1=myProcess1.Execute(inputs1,myOutputs1,"Cookie: MMID="+conf["senv"]["MMID"]);
//alert(myExecuteResult1);
// Parse response
var w=new ZOO.Format.WPS();
tmp=w.read(myExecuteResult1);
alert("Reference: ",tmp.value);
var mapfile=tmp.value.split('&');
mapfile=mapfile[0].split("=");
var inputs2=inputs;
// Retrive datasource information from the Mapfile
var inputs2= {
"fullPath": { "type": "string","value":"true" },
"map": { "type": "string", "value": mapfile[1] },
"layer": { "type": "string", value: "Result" }
};
var myOutputs2= {
"Result": { type: 'RawDataOutput' }
};
var myProcess2 = new ZOO.Process(conf["main"]["serverAddress"],'mapfile.getMapLayersInfo');
var myExecuteResult2=myProcess2.Execute(inputs2,myOutputs2,"Cookie: MMID="+conf["senv"]["MMID"]);
alert(myExecuteResult2);
var tmpData1=eval(myExecuteResult2.replace(/None/g,"null"));
filesToRemove+=[tmpData[0]];
// Convert GML to Shapefile
alert("Convert GML to Shapefile");
var inputs22={"InputDS":{"type":"reference","value":"file://"+tmpData1[0]/*conf["main"]["mapserverAddress"]+"?map="+mapfile[1]+"&request=GetFeature&service=WFS&version=1.0.0&typename=Result"*/,"mimeType": "text/xml"}};
var mpp=mapfile[1].split("/");
var mp=mpp[mpp.length-1].split(".")[0];
inputs22["InputDSN"]={"type":"string","value":mp+".shp"};
inputs22["OutputDSN"]={"type":"string","value":mp+".shp"};
inputs22["F"]={"type":"string","value":"ESRI Shapefile"};
var myOutputs22= {"OutputedDataSourceName": { type: 'ResponseDocument',"asReference": true, "mimeType":"application/unknown" }};
var myProcess22=new ZOO.Process(conf["main"]["serverAddress"],'vector-converter.Ogr2Ogr');
var myExecuteResult22=myProcess22.Execute(inputs22,myOutputs22,"Cookie: MMID="+conf["senv"]["MMID"]);
alert("Converted GML to Shapefile",mp+".shp");
if(myExecuteResult22.indexOf("ExceptionReport")>=0){
alert(myExecuteResult22);
conf["lenv"]["message"]=ZOO._("Error when converting GML to Shapefile!");
return {result: ZOO.SERVICE_FAILED,conf:conf};
}
filesToIndex+=[mp+".shp"];
filesToRemove+=[mapfile[1]];
}
// Create vector tileindex for the labels
var myInputs2 = {
"files": {"type": "string","isArray": "true","length": filesToIndex.length, "value": filesToIndex},
"OutputName": {"type": "string","value":conf["main"]["dataPath"]+"/vtile_labels_"+conf["lenv"]["usid"]+".shp" }
};
var myProcess2 = new ZOO.Process(conf["main"]["serverAddress"],'vector-tools.Ogrtindex');
var myOutputs2= {Result: { type: 'RawDataOutput', "mimeType": "application/json" } };
var myExecuteResult2=myProcess2.Execute(myInputs2,myOutputs2);
alert(myExecuteResult2);
if(myExecuteResult2.indexOf("ExceptionReport")>=0){
conf["lenv"]["message"]=ZOO._("Unable to create the vector tileindex!");
return {result: ZOO.SERVICE_FAILED,conf:conf};
}
// Add Label Layer
return {result: ZOO.SERVICE_FAILED, conf: conf}
}
}else{
var myProcess1 = new ZOO.Process(conf["main"]["serverAddress"],'mapfile.saveLabel');
var myOutputs1= {"Result": { type: 'RawDataOutput', "dataType": "string" }};
var myExecuteResult1=myProcess1.Execute(inputs,myOutputs1,"Cookie: MMID="+conf["senv"]["MMID"]);
return {result: ZOO.SERVICE_SUCCEEDED, outputs: {"Result":{"dataType": "string",value: myExecuteResult1}}};
}
}catch(e){
conf["lenv"]["message"]=e;
alert(conf["lenv"]["message"]);
return {result: ZOO.SERVICE_FAILED, conf: conf}
}
}
<|start_filename|>mapmint-ui/templates/Distiller/db/display_bs.html<|end_filename|>
#import zoo
#set tmpl=$conf['main']['templatesPath']+"/Distiller/form_line.html"
#include $tmpl
#set ftmpl=$self._CHEETAH__cheetahIncludes[$tmpl]
<div id="database_add">
<h2>$zoo._("Add Database")</h2>
<div>
<form class="form-horizontal mtpp" method="get" >
$ftmpl.printLine({"id":"name","name":$zoo._("Name")})
$ftmpl.printLine({"id":"host","name":$zoo._("Host")})
$ftmpl.printLine({"id":"port","name":$zoo._("Port")})
$ftmpl.printLine({"id":"user","name":$zoo._("Login")})
$ftmpl.printLine({"id":"password","name":$zoo._("Password"),"type":"password"})
$ftmpl.printLine({"id":"type","name":$zoo._("Type"),"type":"select","options":["PostGIS","MySQL"]})
$ftmpl.printLine({"id":"dbname","name":$zoo._("Database")})
$ftmpl.printButton({"id":"test","name":$zoo._("Test")})
$ftmpl.printButton({"id":"add","name":$zoo._("Add")})
</form>
</div>
</div>
<|start_filename|>mapmint-ui/css/mm-blue.css<|end_filename|>
/*
* MapMint blue theme CSS
*/
body{font-family:Lucida Grande;font-size:1em;}
a { outline: none; }
input {border:1px solid #9f9f9f; outline: none;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff'); /* for IE */
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
border-radius: 4px;
}
input.rounded{width:100%;height:20px;margin:1px;border:1px solid #9f9f9f; outline: none;
background:#EBEBEB;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
input:focus, select:focus{
-webkit-box-shadow: 0px 0px 5px #9e9e9e;
-moz-box-shadow: 0px 0px 5px #9e9e9e;
}
input.name{width:65%;height:20px;margin:1px;-moz-border-radius:5px;border:1px solid #9f9f9f;margin-left:10px;}
textarea.maincfg{width:100%;height:100px;margin:1px;outline: none;border:1px solid #9f9f9f;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff'); /* for IE */
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
select{
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff'); /* for IE */
border:1px solid #9f9f9f;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
padding:2px;
font-size:1em;
}
select option{
font-size:1em;
}
select.select-window{margin:0;width:100%;}
select.select-window-short{margin:0;width:85%;}
label.up{ display: block; margin: 0 10px 3px 0; }
label.up-small{ display: block; margin: 10px 10px .5em 0; font-size:.95em;font-style:italic; }
/*custom upload elements*/
.customfile-input { position: absolute; height: 100px;cursor: pointer;background: transparent; border: 0; opacity: 0; -moz-opacity: 0; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0); z-index: 999; }
.customfile {background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff'); /* for IE */
border:1px solid #9f9f9f; cursor: pointer; overflow: hidden; padding: 0px; -moz-border-radius:4px; -webkit-border-radius:4px; border-radius:4px; position: relative;color:#333333;}
.customfile-disabled { opacity: .5; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0); cursor: default; }
.customfile-feedback { display: block; margin: 1px 1px 1px 5px;color: #A9A9A9; font-style: italic; padding: .3em; }
.customfile-feedback-populated { color: #33333; font-style: normal; font-weight: normal;}
.customfile-button {border: 1px solid #FFFFFF;background: #E9E9E9; color: #333333; float: right; width: 70px; padding: .3em .6em; text-align: center; text-decoration: none;-moz-border-radius:5px; -webkit-border-radius:5px; border-radius:5px;color:#333333; }
.customfile-hover .customfile-button, .customfile-focus .customfile-button { color:#111; background: #45abe4; border-color:#FFFFFF;padding: .3em .6em; }
.customfile-focus .customfile-button { outline: 1px dotted #ccc; }
h3.title{margin:0;padding:5px 0 0 10px;font-size:1em;color:#545454;text-shadow: 0 1px 0 rgba(255, 255, 255, 1);}
.ui-layout-pane {
background: #eaeaea;
border:0;
padding: 0px;
overflow: auto;
}
.ui-layout-content {
padding: 10px;
position: relative; /* contain floated or positioned elements */
overflow: auto; /* add scrolling to content-div */
}
/*
* Resizer-Bars
*/
.ui-layout-resizer { /* all 'resizer-bars' */
background: #808080;
border: 1px solid #BBB;
border-width: 0;
}
div.ui-layout-resizer-open span.close {
display:none;
}
div.ui-layout-resizer-open span.close-inv {
display:none;
}
.ui-layout-resizer-drag {/* REAL resizer while resize in progress */}
.ui-layout-resizer-hover { /* affects both open and closed states */
}
/* NOTE: It looks best when 'hover' and 'dragging' are set to the same color,
otherwise color shifts while dragging when bar can't keep up with mouse */
.ui-layout-resizer-open-hover , /* hover-color to 'resize' */
.ui-layout-resizer-dragging { /* resizer beging 'dragging' */
background: #C4E1A4;
}
.ui-layout-resizer-dragging { /* CLONED resizer being dragged */
border-left: 1px solid #BBB;
border-right: 1px solid #BBB;
}
/* NOTE: Add a 'dragging-limit' color to provide visual feedback when resizer hits min/max size limits */
.ui-layout-resizer-dragging-limit { /* CLONED resizer at min or max size-limit */
background: #E1A4A4; /* red */
}
.ui-layout-resizer-closed-hover { /* hover-color to 'slide open' */
background: #EBD5AA;
}
.ui-layout-resizer-sliding { /* resizer when pane is 'slid open' */
opacity: .10; /* show only a slight shadow */
filter: alpha(opacity=10);
}
.ui-layout-resizer-sliding-hover { /* sliding resizer - hover */
opacity: 1.00; /* on-hover, show the resizer-bar normally */
filter: alpha(opacity=100);
}
/* sliding resizer - add 'outside-border' to resizer on-hover
* this sample illustrates how to target specific panes and states */
.ui-layout-resizer-north-sliding-hover { border-bottom-width: 1px; }
.ui-layout-resizer-south-sliding-hover { border-top-width: 1px; }
.ui-layout-resizer-west-sliding-hover { border-right-width: 1px; }
.ui-layout-resizer-east-sliding-hover { border-left-width: 1px; }
h1.pane-title{margin:0;padding:5px 0 3px 5px;font-size:.9em;font-weight:normal;
text-shadow: #FFFFFF 0px 1px 0px;
background: #b6b6b6;
background: -moz-linear-gradient(top, #E9E9E9, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#E9E9E9), to(#b6b6b6));
}
.ui-layout-north{
background: url(../img/mm-logo-blue.png) no-repeat, -moz-linear-gradient(top, #333333, #808080);
background: url(../img/mm-logo-blue.png) no-repeat, -webkit-gradient(linear, left top, left bottom, from(#333333), to(#808080));
overflow:hidden;
}
ui-layout-west{
overflow:hidden;
}
.close {width:16px;height:17px;
float:right;
margin: 0 5px 0 0;
cursor:pointer;
background: url(../img/close-sidebar.png) no-repeat;
text-align:center;
font-size:.7em;}
.close:hover {width:16px;height:17px;cursor:pointer;margin: 0 5px 0 0;background: url(../img/close-sidebar-hover-blue.png) no-repeat;}
.close-inv {width:17px;height:16px;
background: url(../img/close-sidebar-right.png) no-repeat;
font-size:.7em;cursor:pointer;position:absolute;margin: 0 0 0 1px;}
.close-inv:hover {width:16px;height:17px;float:left;cursor:pointer;background: url(../img/close-sidebar-right-hover-blue.png) no-repeat;margin: 0 0 0 1px;}
#nav {
position:relative;
top:12px;
left:250px;
margin: 0;
padding:0;
background: transparent;
border:0;
font-size:.8em;
float:left;
}
#nav li {
margin: 0 5px;
padding: 0 0 8px;
float: left;
position: relative;
list-style: none;
}
.ui-layout-south{
background: -moz-linear-gradient(top,#808080,#333333);
background: -webkit-gradient(linear, left top, left bottom, from(#808080), to(#333333));
}
.toolbar, .toolbar2{background:#B6B6B6;width:100%;margin:0;padding:0;height:31px;}
.toolbar-noborder{background:transparent;width:100%;margin:4px 0;padding:0;}
a.fg-button {background:#E9E9E9;float:left;width:24px;height:24px;margin:0 0 0 5px;padding:0; text-decoration:none !important; cursor:pointer; position: relative; text-align: center;}
a.fg-button:hover {background:#FFFFFF;}
a.fg-button-s {background:#E9E9E9;float:left;width:20px;height:20px;margin:0 0 0 5px;padding:0; text-decoration:none !important; cursor:pointer; position: relative; text-align: center;}
.maincfg1 {border:1px solid #8f8f8f;background-image:url(../img/monitor-blue.png) !important;}
.maincfg2 {border:1px solid #8f8f8f;background-image:url(../img/security-blue.png) !important;}
.maincfg3 {border:1px solid #8f8f8f;background-image:url(../img/user-blue.png) !important;}
.projects {border:1px solid #8f8f8f;background-image:url(../img/process-blue.png) !important;}
.documents {border:1px solid #8f8f8f;background-image:url(../img/docs-blue.png) !important;}
.add-database {border:1px solid #8f8f8f;background-image:url(../img/add-database-blue.png) !important;}
.add-directory {border:1px solid #8f8f8f;background-image:url(../img/add-directory-blue.png) !important;}
.add-vector {border:1px solid #8f8f8f;background-image:url(../img/add-vector-blue.png) !important;}
.add-raster {border:1px solid #8f8f8f;background-image:url(../img/add-raster-blue.png) !important;}
.add-wms {border:1px solid #8f8f8f;background-image:url(../img/add-wms-blue.png) !important;}
.add-wfs {border:1px solid #8f8f8f;background-image:url(../img/add-wfs-blue.png) !important;}
.add-wcs {border:1px solid #8f8f8f;background-image:url(../img/add-wcs-blue.png) !important;}
.add-layer {border:1px solid #8f8f8f;background-image:url(../img/add-layer-blue.png) !important;}
.open-map {border:1px solid #8f8f8f;background-image:url(../img/open-map-blue.png) !important;}
a.save-as-map{font-size:.8em;text-decoration:none;border:1px solid #888888;padding:4px;color:#777777;position:relative;top:1px;left:20px;text-shadow:#E9E9E9 0 1px 0;}
a.save-as-map:hover{color:#FFFFFF;position:relative;top:1px;left:20px;text-shadow:#333333 0 1px 0;background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */); /* for IE */}
a.view-site{font-size:.8em;text-decoration:none;border:1px solid #888888;padding:4px;color:#777777;position:relative;top:1px;left:20px;text-shadow:#E9E9E9 0 1px 0;}
a.view-site:hover{color:#FFFFFF;position:relative;top:1px;left:20px;text-shadow:#333333 0 1px 0;background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */); /* for IE */}
a.view-all-project{float:right;font-size:.8em;text-decoration:none;border:1px solid #888888;padding:4px;color:#777777;position:relative;top:0;right:10px;text-shadow:#E9E9E9 0 1px 0;}
a.view-all-project:hover{color:#FFFFFF;position:relative;top:0;right:10px;text-shadow:#333333 0 1px 0;background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */); /* for IE */}
.pan {border:1px solid #8f8f8f;background-image:url(../img/pan-blue.png) !important;}
.zoom-box {border:1px solid #8f8f8f;background-image:url(../img/zoom-in-blue.png) !important;}
.zoom-in {border:1px solid #8f8f8f;background-image:url(../img/zoomin.png) !important;}
.zoom-in:hover {border:1px solid #8f8f8f;background: #4BA3E5 url(../img/zoomin-hover.png) !important; }
.zoom-to-max-extent {border:1px solid #8f8f8f;background-image:url(../img/zoomtomaxextent.png) !important;}
.zoom-to-max-extent:hover {border:1px solid #8f8f8f;background-image:url(../img/zoomtomaxextent-hover.png) !important;}
.zoom-out {border:1px solid #8f8f8f;background-image:url(../img/zoomout.png) !important;}
.zoom-out:hover {border:1px solid #8f8f8f;background: #4BA3E5 url(../img/zoomout-hover.png) !important;}
.zoom-to-point {border:1px solid #8f8f8f;background-image:url(../img/zoom-to-point-blue.png) !important;}
.identify {border:1px solid #8f8f8f;background-image:url(../img/identify-blue.png) !important;}
.mesure-distance {border:1px solid #8f8f8f;background-image:url(../img/ruler-blue.png) !important;}
.mesure-area {border:1px solid #8f8f8f;background-image:url(../img/ruler2-blue.png) !important;}
.select {border:1px solid #8f8f8f;background-image:url(../img/select.png) !important;}
.edit-point {border:1px solid #8f8f8f;background-image:url(../img/edit-point-blue.png) !important;}
.edit-line {border:1px solid #8f8f8f;background-image:url(../img/edit-line-blue.png) !important;}
.edit-polygon {border:1px solid #8f8f8f;background-image:url(../img/edit-polygon-blue.png) !important;}
.delete-feature {border:1px solid #8f8f8f;background-image:url(../img/delete-feature.png) !important;}
.buffer {border:1px solid #8f8f8f;background-image:url(../img/buffer-blue.png) !important;}
.centroid {border:1px solid #8f8f8f;background-image:url(../img/centroid-blue.png) !important;}
.boundary {border:1px solid #8f8f8f;background-image:url(../img/boundary-blue.png) !important;}
.convexhull {border:1px solid #8f8f8f;background-image:url(../img/convexhull-blue.png) !important;}
.simplify {border:1px solid #8f8f8f;background-image:url(../img/simplify-blue.png) !important;}
.union {border:1px solid #8f8f8f;background-image:url(../img/union-blue.png) !important;}
.intersection {border:1px solid #8f8f8f;background-image:url(../img/intersection-blue.png) !important;}
.symdifference {border:1px solid #8f8f8f;background-image:url(../img/symdifference-blue.png) !important;}
.difference {border:1px solid #8f8f8f;background-image:url(../img/difference.png) !important;}
.raster-histogram {border:1px solid #8f8f8f;background-image:url(../img/raster-histogram-blue.png) !important;}
.clip-raster {border:1px solid #8f8f8f;background-image:url(../img/clip-layer.png) !important;}
.merge-rasters {border:1px solid #8f8f8f;background-image:url(../img/merge-layer.png) !important;}
.polygons-from-raster {border:1px solid #8f8f8f;background-image:url(../img/polygons-from-raster.png) !important;}
.raster-from-csv {border:1px solid #8f8f8f;background-image:url(../img/raster-from-csv.png) !important;}
.terrain-profile {border:1px solid #8f8f8f;background-image:url(../img/terrain-profile.png) !important;}
.contours-from-dem {border:1px solid #8f8f8f;background-image:url(../img/contours-from-dem.png) !important;}
.shaded-relief {border:1px solid #8f8f8f;background-image:url(../img/shaded-relief.png) !important;}
.color-relief {border:1px solid #8f8f8f;background-image:url(../img/color-relief.png) !important;}
.slope-map {border:1px solid #8f8f8f;background-image:url(../img/slope-map.png) !important;}
.main-configuration {border:1px solid #8f8f8f;background-image:url(../img/process-blue.png) !important;}
.layout-settings {border:1px solid #8f8f8f;background-image:url(../img/layout-settings-blue.png) !important;}
.map-settings {border:1px solid #8f8f8f;background-image:url(../img/map-settings-blue.png) !important;}
.layers-settings {border:1px solid #8f8f8f;background-image:url(../img/layers-settings-blue.png) !important;}
.controls-settings {border:1px solid #8f8f8f;background-image:url(../img/controls-settings-blue.png) !important;}
ul.nav-toolbar {position:absolute;top:100px;left:5px;margin:0;padding:2px;list-style:none;z-index:1000000000;width:32px;height:57px;background:url(../img/bcknav.png);border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
ul.nav-toolbar li a{margin: 3px 0 3px 5px;}
.dropdown-toolbars {width:150px;max-width:150px;margin:0;padding:0;font-size:.8em;font-weight:normal;position:absolute;left:250px;}
.dropdown-toolbars dd, .dropdown-toolbars dt, .dropdown-toolbars ul {margin:0px; padding:0px;font-weight:normal;}
.dropdown-toolbars dd {position:absolute;}
.dropdown-toolbars a, .dropdown a:visited {color:#777777; text-decoration:none;outline:none;width:140px;max-width:140px;padding:0;}
.dropdown-toolbars a:hover {color:#333333;width:140px;max-width:140px;}
.dropdown-toolbars dt a:hover {color:#000000;border:1px solid #7d7d7d;}
.dropdown-toolbars dt a {background:#E0E0E0 url(../img/arrow.png) no-repeat scroll right center; display:block; padding-right:10px;border:1px solid #8F8F8F; width:140px;}
.dropdown-toolbars dt a:hover {background:#E4E4E4 url(../img/arrow.png) no-repeat scroll right center; }
.dropdown-toolbars dt a span {cursor:pointer; display:block;padding:4px;}
.dropdown-toolbars dd ul {font-size:.95em;z-index:10000000000;color:#333333; display:none;left:0px; padding:5px 0px; position:absolute; top:2px; width:130px; min-width:130px; list-style:none; background:#f0f0f0; -moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
margin:0;
border:1px solid #ccc;
overflow:hidden;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;}
.dropdown-toolbars span.value { display:none;}
.dropdown-toolbars dd ul li a { padding:5px; display:block;width:120px;max-width:120px;cursor:pointer;}
.dropdown-toolbars dd ul li a:hover { background-color:#C5C5C5;width:120px;max-width:120px;cursor:pointer;}
.dropdown-toolbars dd ul li a label{cursor:pointer;}
/*
* Tooltips
*/
.tipsy { padding: 5px; font-size: 10px; position: absolute; z-index: 1;}
.tipsy-inner { padding: 5px 8px 4px 8px; background-color:#808080; color: white; max-width: 200px; text-align: center; }
.tipsy-inner { border-radius: 3px; -moz-border-radius:3px; -webkit-border-radius:3px; }
.tipsy-arrow { position: absolute; background:transparent no-repeat top left; width: 9px; height: 5px; }
.tipsy-n .tipsy-arrow { top: 0; left: 50%; margin-left: -4px; }
.tipsy-nw .tipsy-arrow { top: 0; left: 10px; }
.tipsy-ne .tipsy-arrow { top: 0; right: 10px; }
.tipsy-s .tipsy-arrow { bottom: 0; left: 50%; margin-left: -4px; background-position: bottom left; }
.tipsy-sw .tipsy-arrow { bottom: 0; left: 10px; background-position: bottom left; }
.tipsy-se .tipsy-arrow { bottom: 0; right: 10px; background-position: bottom left; }
.tipsy-e .tipsy-arrow { top: 50%; margin-top: -4px; right: 0; width: 5px; height: 9px; background-position: top right; }
.tipsy-w .tipsy-arrow { top: 50%; margin-top: -4px; left: 0; width: 5px; height: 9px; }
p.hour{margin:0;padding:0;font-size:.8em;color:#777777;padding:3px 0 0 5px;}
.log-out{font-size:.7em;}
.admin{display:inline;float:right;margin:5px;background:transparent;}
ul.sets {list-style:none;margin:0;padding:0;}
ul.sets li{display:inline;margin:0 5px;}
ul.sets li a{color:#A7A7A7;text-decoration:none;font-size:.8em;}
ul.sets li a:hover{color:#FFFFFF;text-decoration:none;}
h2.ad{
color:#FFFFFF;
margin:0;padding:5px;background: transparent;
font-size:.8em;font-weight:bold;
text-shadow: #000000 0px 2px 0px;
text-align:right;
}
ul.sets li:hover a {color:#FFFFFF; }
.sub{
box-shadow: 5px 5px 5px #626262; /* CSS3 */
-moz-box-shadow: 5px 5px 5px #626262; /* Firefox */
-webkit-box-shadow: 5px 5px 5px #626262; /* Safari, Chrome */
}
ul li .sub {
position: absolute;
top: 60px; right: 0;
background: #808080;
padding: 0 0 10px 10px;
float: left;
/*--Bottom left rounded corner--*/
-moz-border-radius-bottomleft: 5px;
-khtml-border-radius-bottomleft: 5px;
-webkit-border-bottom-left-radius: 5px;
display: none;
color:#333333;
min-width:20%;
}
ul li .row {clear: both; float: left; width: 100%; margin-bottom: 10px;}
ul li .sub ul{
list-style: none;
margin: 0;
padding: 0;
width: 90px;
float: left;
}
ul .sub ul li {
width: 100%;
color: #fff;
}
.sub ul li a {
float: none;
text-indent: 0; /*--Reset text indent--*/
height: auto;
padding: 7px 5px 7px 0;
font-size:.7em;
display: block;
text-decoration: none;
color: #767676;
}
.sub ul li a:hover {color: #008B62;}
.jPaginate{
height:40px;
position:fixed;
bottom:50px;
color:#a5a5a5;
font-size:small;
width:100%;
background:url(../img/wbg.png) repeat-x;
}
.jPaginate a{
line-height:15px;
height:18px;
cursor:pointer;
padding:2px 5px;
margin:2px;
float:left;
}
.jPag-control-back{
position:absolute;
left:0px;
padding:7px 0 0 5px;
}
.jPag-control-front{
position:absolute;
top:0px;
padding:7px 0 0 5px;
}
.jPaginate span{
cursor:pointer;
}
ul.jPag-pages{
float:left;
list-style-type:none;
margin:0 auto;
padding:7px 0 0 5px;
}
ul.jPag-pages li{
display:inline;
float:left;
padding:0px;
margin:0px;
}
ul.jPag-pages li a{
float:left;
padding:2px 5px;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
span.jPag-current{
cursor:default;
font-weight:normal;
line-height:15px;
height:18px;
padding:2px 5px;
margin:2px;
float:left;
padding:2px 5px;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
ul.jPag-pages li span.jPag-previous,
ul.jPag-pages li span.jPag-next,
span.jPag-sprevious,
span.jPag-snext,
ul.jPag-pages li span.jPag-previous-img,
ul.jPag-pages li span.jPag-next-img,
span.jPag-sprevious-img,
span.jPag-snext-img{
height:22px;
margin:2px;
float:left;
line-height:18px;
}
ul.jPag-pages li span.jPag-previous,
ul.jPag-pages li span.jPag-previous-img{
margin:2px 0px 2px 2px;
font-size:12px;
font-weight:bold;
width:10px;
}
ul.jPag-pages li span.jPag-next,
ul.jPag-pages li span.jPag-next-img{
margin:2px 2px 2px 0px;
font-size:12px;
font-weight:bold;
width:10px;
}
span.jPag-sprevious,
span.jPag-sprevious-img{
margin:2px 0px 2px 2px;
font-size:18px;
width:15px;
text-align:right;
}
span.jPag-snext,
span.jPag-snext-img{
margin:2px 2px 2px 0px;
font-size:18px;
width:15px;
text-align:right;
}
.jPag-first{
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
.jPag-last{
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
/*
* Themes bar
*/
.theme-bar{width:100%;float:left;}
.theme-bar a{display:inline;}
.theme-bar-pub a{display:inline;}
input.th{float:left;margin:0;text-indent:none;}
.green{
float:left;
width:24px;
height:24px;
margin:0 5px 0 10px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.blue{
float:left;
width:24px;
height:24px;
margin:0 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#44d0e5', endColorstr='#398ee4'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#44d0e5), to(#398ee4)); /* for webkit browsers */
background: -moz-linear-gradient(top, #44d0e5, #398ee4 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.purple{
float:left;
width:24px;
height:24px;
margin:0 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#c743f8', endColorstr='#8340f3'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#c743f8), to(#8340f3)); /* for webkit browsers */
background: -moz-linear-gradient(top, #c743f8, #8340f3 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.pink{
float:left;
width:24px;
height:24px;
margin:0 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f869ec', endColorstr='#f630f8'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#f869ec), to(#f630f8)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.tabs-left, .tabs-right, .tabs-project, .maps-container {background:url(../img/wbg.png) repeat-x; color: #565656;
font-size:.8em;overflow:hidden;}
.tabs-right p {padding:0 0 0 10px;}
.tabs-left table{font-size:0.95em;}
.tabs-project table{padding:0px 0 0 8px;font-size:0.95em;width:99%;}
.tabs-project p{padding:10px 0 0 10px;margin:0;font-size:0.95em;}
table.layouts {width:98%;margin:0;padding:0px 0 0 8px;font-size:0.95em;background:#EBEBEB;background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));background: -moz-linear-gradient(top, #ebebeb, #ffffff); -moz-border-radius:4px;color:#565656;;border:1px solid #9f9f9f;margin:3px 0 0 12px;}
table.layouts tr td {width:15%;}
table.layouts img {border:1px solid #9f9f9f;margin-left:20px;}
table.themz {width:98%;font-size:0.95em;background:#EBEBEB;background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));background: -moz-linear-gradient(top, #ebebeb, #ffffff); -moz-border-radius:4px;color:#000000;border:1px solid #9f9f9f;margin:3px 0 0 12px;padding: 2px 0 25px 12px;}
table.themz th span {float:left;margin:0 0 5px 0;padding:0;font-weight:normal;text-align:left;padding:5px;background:#FFFFFF;-moz-border-radius:4px;}
table.themz tr td {width:10%;}
table.themz tr td a {text-decoration:none;cursor:default;color:#565656;}
table.themz tr td a:hover {cursor:default;}
table.themz tr td a span{position:relative;top:30px;left:0;}
table.font {margin:0 0 0 0;padding:0 0 0 8px;}
table.font th span {float:left;margin:0 0 5px 0;padding:0;font-weight:normal;text-align:left;padding:5px;background:#FFFFFF;-moz-border-radius:4px;}
table.font td span.fcolor {width:50%;display:block;margin:0 5px 0 0;padding:3px;background:#EBEBEB;background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));background: -moz-linear-gradient(top, #ebebeb, #ffffff); -moz-border-radius:4px;color:#000000;border:1px solid #9f9f9f;valign:middle;}
table.font td .color_picker { height: 13px;
width: 14px;
padding: 0 !important;
float:right;
cursor: pointer;
line-height: 16px;
display:inline-block;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius: 2px;
}
table.datasources {width:98%;margin:0;padding:0px 0 5px 0;font-size:0.95em;background:#EBEBEB;background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));background: -moz-linear-gradient(top, #ebebeb, #ffffff); -moz-border-radius:4px;color:#000000;border:1px solid #9f9f9f;margin:3px 0 0 12px;}
table.datasources th {color:#333333;font-weight:normal;padding: 2px 0 6px 0 ;background:#FFFFFF;}
table.datasources th.name {text-align:left;text-indent:5px;}
table.datasources tr td {text-align:center;color:#565656;}
table.datasources tr td.layerName {width:50%;text-align:left;}
table.logo {margin:10px 0 0 0;padding:0 0 0 8px;}
table.logo th span {float:left;margin:0 0 5px 0;padding:0;font-weight:normal;text-align:left;padding:5px;background:#FFFFFF;-moz-border-radius:4px;}
table.layers-gen {margin:10px 0 0 0;padding:0 0 0 8px;width:60%;}
table.layers-gen th span {float:left;margin:0 0 5px 0;padding:0;font-weight:normal;text-align:left;padding:5px;background:#FFFFFF;-moz-border-radius:4px;}
.ui-progress-bar {
/* Usual setup stuff */
position: relative;
top:9px;
right:30px;
float:right;
height: 15px;
width:150px;
/* Pad right so we don't cover the borders when fully progressed */
padding-right: 2px;
/* For browser that don't support gradients, we'll set a blanket background colour */
background-color: #abb2bc;
/* Rounds the ends, we specify an excessive amount to make sure they are completely rounded */
/* Adjust to your liking, and don't forget to adjust to the same amount in .ui-progress */
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
/* Webkit background gradient */
background: -webkit-gradient(linear, left bottom, left top, color-stop(0, #b6bcc6), color-stop(1, #9da5b0));
/* Mozilla background gradient */
background: -moz-linear-gradient(#9da5b0 0%, #b6bcc6 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#9da5b0', endColorstr='#b6bcc6'); /* for IE */
/* Give it the inset look by adding some shadows and highlights */
-webkit-box-shadow: inset 0px 1px 2px 0px rgba(, 0, 0, 0.5), 0px 1px 0px 0px #565656;
-moz-box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #565656;
box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #565656;
}
/* Progress part of the progress bar */
.ui-progress {
/* Usual setup stuff */
position: relative;
display: block;
overflow: hidden;
/* Height should be 2px less than .ui-progress-bar so as to not cover borders and give it a look of being inset */
height: 13px;
/* Rounds the ends, we specify an excessive amount to make sure they are completely rounded */
/* Adjust to your liking, and don't forget to adjust to the same amount in .ui-progress-bar */
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
/* Set the background size so the stripes work correctly */
-webkit-background-size: 24px 24px; /* Webkit */
/* For browser that don't support gradients, we'll set a blanket background colour */
background-color: #74d04c;
/* Webkit background stripes and gradient */
background: -webkit-gradient(linear, 0 0, 24 24,
color-stop(0.00, rgba(255,255,255,0.17)),
color-stop(0.25, rgba(255,255,255,0.17)),
color-stop(0.26, rgba(255,255,255,0)),
color-stop(0.50, rgba(255,255,255,0)),
color-stop(0.51, rgba(255,255,255,0.17)),
color-stop(0.75, rgba(255,255,255,0.17)),
color-stop(0.76, rgba(255,255,255,0)),
color-stop(1.00, rgba(255,255,255,0))
), -webkit-gradient(linear, left bottom, left top, color-stop(0, #82e9fa), color-stop(1, #398ee4));
/* Mozilla (Firefox etc) background stripes */
/* Note: Mozilla's support for gradients is more true to the original design, allowing gradients at 30 degrees, as apposed to 45 degress in webkit. */
background: -moz-repeating-linear-gradient(top left -30deg,
rgba(255,255,255,0.17),
rgba(255,255,255,0.17) 5px,
rgba(255,255,255,0) 5px,
rgba(255,255,255,0) 10px
), -moz-linear-gradient(#82e9fa 0%, #398ee4 100%);
/* Webkit embossing */
-webkit-box-shadow: inset 0px 1px 0px 0px #93faf9, inset 0px -1px 1px #58c43a;
/* Mozilla embossing */
-moz-box-shadow: inset 0px 1px 0px 0px #93faf9, inset 0px -1px 1px #58c43a;
/* IE9 and Opera embossing */
box-shadow: inset 0px 1px 0px 0px #93faf9, inset 0px -1px 1px #58c43a;
/* Give it a higher contrast outline */
border: 1px solid #3482d1;
/* Webkit magic */
-webkit-animation: animate-stripes 2s linear infinite;
/* TODO: Wait for Mozilla to support animation, then implement */
}
/* Progress indicator text */
.ui-progress span.ui-label {
font-size: 0.7em;
position: absolute;
right: 0;
line-height: 13px;
padding-right: 3px;
color: rgba(0,0,0,0.6);
text-shadow: rgba(255,255,255, 0.45) 0 1px 0px;
white-space: nowrap;
}
.nb-container{float:right;margin:0;padding:0;height:90%;}
.tt-container{float:left;margin:0;padding:0;height:50px;}
span.inlinebar{margin:25%;}
.distiller {width:100%;height:78px;margin:0;background: #FFFFFF url(../img/wbg.png) repeat-x;}
.distiller img {display:inline;float:left;margin:0;padding:0;position:relative;top:20px;left:20px;}
.distiller p{margin:0;padding:0;}
.distiller p a{width:130px;text-align:center;display:block;font-size:.8em;text-decoration:none;padding:0;margin:7px 10px;}
.distiller p a:hover{width:130px;text-decoration:none;padding:0;margin:7px 10px;}
.manager, .publisher, .printer {width:100%;height:78px;background: #FFFFFF url(../img/wbg.png) repeat-x;}
.manager img, .publisher img, .printer img {display:inline;float:left;margin:0;padding:0;position:relative;top:20px;left:20px;}
.manager p a, .publisher p a, .printer p a{width:130px;text-align:center;display:block;font-size:.8em;text-decoration:none;margin:25px 10px 0 0;}
.manager p a:hover, .publisher p a:hover, .printer p a:hover {width:130px;padding:0;text-decoration:none;margin:25px 10px 0 0;}
.distiller h2,.styler h2, .manager h2, .printer h2, .publisher h2{color:#545454;
margin:0;padding:15px 0 0 40px;background:transparent; display:block;float:left;
;font-size:.8em;text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
}
.distiller h3, .styler h3, .manager h3, .printer h3, .publisher h3{
position:absolute;margin:0;padding:40px 0 0 72px;background:transparent;font-size:.8em;font-weight:normal;color:#7a7a7a;
}
.save-config{position:relative;top:5px;right:10px;font-size:1em;float:right;}
.maps-container ul{margin:0;padding:0;list-style:none;}
.tabs-right ul{margin:10px 0;padding:0;list-style:none;}
.tabs-right ul li, .maps-container ul li{font-size:.95em;margin:0;padding:10px;text-indent:0;
background: -moz-linear-gradient(top, #FFFFFF, #eaeaea);
background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#eaeaea));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eaeaea'); /* for IE */
}
.tabs-right ul li:hover, .maps-container ul li:hover {cursor:pointer;
background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */
}
.maps-container ul li a.default-map {color:#4EB1E8;background-image:url(../img/icon-active-blue.png);
background-repeat:no-repeat;
background-position:right;}
.tabs-right ul li a, .maps-container ul li a{text-decoration:none;color:#565656;display:block;}
.tabs-right ul li a:hover, .maps-container ul li a:hover{text-decoration:none;color:#000000;}
.tabs-right ul li a span, .maps-container ul li a span{display:block;text-decoration:none;color:#777777;font-size:.9em;}
.tabs-right ul li:hover a span, .maps-container ul li:hover a span{color:#FFFFFF;}
//.probox-title{border-top-left-radius:5px;-moz-border-radius-topleft:5px;-webkit-border-top-left-radius:5px;
//border-bottom-left-radius:0px;-moz-border-radius-bottomleft:0px;-webkit-border-bottom-left-radius:0px;
//}
//.probox{background:#565656;position:fixed;bottom:50px;right:0px;max-height:400px;border:0;}
//.probox-inner{background-color:#565656 !important;}
.progress_box_call{float:right;height:15px;width:15px;position:relative;
border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;
top:9px;
right:10px;
background: -moz-linear-gradient(top, #e2e2e2, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e2e2e2', endColorstr='#b6b6b6'); /* for IE */
text-align:center;
font-size:.7em;
}
.progress_box_call:hover{
background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));color: #FFFFFF;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */
cursor:pointer;}
div.jGrowl {
padding: 10px;
z-index: 9999;
color: #fff;
}
/** Special IE6 Style Positioning **/
div.ie6 {
position: absolute;
}
div.ie6.top-right {
right: auto;
bottom: auto;
left: expression( ( 0 - jGrowl.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
top: expression( ( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}
div.ie6.top-left {
left: expression( ( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
top: expression( ( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}
div.ie6.bottom-right {
left: expression( ( 0 - jGrowl.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
top: expression( ( 0 - jGrowl.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}
div.ie6.bottom-left {
left: expression( ( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
top: expression( ( 0 - jGrowl.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}
div.ie6.center {
left: expression( ( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
top: expression( ( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
width: 100%;
}
/** Normal Style Positions **/
div.jGrowl {
position: absolute;
}
body > div.jGrowl {
position: fixed;
}
div.jGrowl.top-left {
left: 0px;
top: 0px;
}
div.jGrowl.top-right {
right: 0px;
top: 0px;
}
div.jGrowl.bottom-left {
left: 0px;
bottom: 0px;
}
div.jGrowl.bottom-right {
right: 0px;
bottom: 43px;
}
div.jGrowl.center {
top: 0px;
width: 50%;
left: 25%;
}
/** Cross Browser Styling **/
div.center div.jGrowl-notification, div.center div.jGrowl-closer {
margin-left: auto;
margin-right: auto;
}
div.jGrowl div.jGrowl-notification, div.jGrowl div.jGrowl-closer {
background:url(../img/bcknav.png);
zoom: 1;
width: 235px;
padding: 10px;
margin-top: 5px;
margin-bottom: 5px;
font-size: .7em;
text-align: left;
display: none;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
div.jGrowl div.jGrowl-notification {
min-height: 50px;
}
div.jGrowl div.jGrowl-notification div.jGrowl-header {
font-weight: bold;
font-size: .85em;
}
div.jGrowl div.jGrowl-notification div.jGrowl-close {
z-index: 99;
float: right;
font-weight: bold;
font-size: 1em;
cursor: pointer;
}
div.jGrowl div.jGrowl-closer {
padding-top: 4px;
padding-bottom: 4px;
cursor: pointer;
font-size: .8em;
font-weight: bold;
text-align: center;
text-shadow: #FFFFFF 0px 1px 0px;
background: -moz-linear-gradient(top, #e2e2e2, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e2e2e2', endColorstr='#b6b6b6'); /* for IE */
font-weight: normal; color: #333333;}
div.jGrowl div.jGrowl-closer:hover {
text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */
font-weight: normal; color: #FFFFFF;
}
/** Hide jGrowl when printing **/
@media print {
div.jGrowl {
display: none;
}
}
#logout-message{font-size:.7em ;}
#logout-message p{margin:0;padding:10px;}
p.credits{float:left;margin:5px;color:#FFFFFF;font-size:.8em;}
p.credits a{text-decoration:none;color:#FFFFFF;}
p.credits a:hover{text-decoration:underline;color:#75D9F6;}
.tree{
font-size:.8em;
margin:0;
color:#565656;
padding:0;
list-style-type:none;
}
.tree li{
white-space:nowrap;
font-size:.95em;
color:#333333;
font-weight:bold;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
}
.tree li ul{
list-style-type:none;
margin:0;
padding:0;
}
.tree li ul li{
font-size:1em;
color:#565656;
font-weight:normal;
text-shadow: none;
}
.tree-node{
height:18px;
padding: 5px 0 3px 0;
white-space:nowrap;
cursor:pointer;
}
.tree-indent{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-hit{
cursor:pointer;
}
.tree-expanded{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
background:url('../img/tree_arrows.png') no-repeat -18px 0px;
}
.tree-expanded-hover{
background:url('../img/tree_arrows.png') no-repeat -50px 0px;
}
.tree-collapsed{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
background:url('../img/tree_arrows.png') no-repeat 0px 0px;
}
.tree-collapsed-hover{
background:url('../img/tree_arrows.png') no-repeat -32px 0px;
}
.tree-folder{
display:inline-block;
background:url('../img/tree_folder.png') no-repeat;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-folder-open{
background:url('../img/tree_folder_open.png') no-repeat;
}
.tree-file{
display:inline-block;
background:url('../img/tree_file.png') no-repeat;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-loading{
background:url('../img/tree_loading.gif') no-repeat;
}
.tree-title{
display:inline-block;
text-decoration:none;
vertical-align:middle;
padding:1px 2px 1px 2px;
white-space:nowrap;
}
.tree-node-hover{
background:#ffffff;background: -moz-linear-gradient(top, #FFFFFF, #eaeaea);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#eaeaea));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#eaeaea'); /* for IE */
}
.tree-node-selected{
background:#82e9fa;
background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */
}
.tree-checkbox{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-checkbox0{
background:url('../img/tree_checkbox_0.png') no-repeat;
}
.tree-checkbox1{
background:url('../img/tree_checkbox_1-blue.png') no-repeat;
}
.tree-checkbox2{
background:url('../img/tree_checkbox_2-blue.png') no-repeat;
}
.tree-node-proxy{
font-size:12px;
padding:1px 2px 1px 18px;
background:#fafafa;
border:1px solid #ccc;
z-index:9900000;
}
.tree-dnd-yes{
background:url('../img/tree_dnd_yes.png') no-repeat 0 center;
}
.tree-dnd-no{
background:url('../img/tree_dnd_no.png') no-repeat 0 center;
}
.tree-node-top{
border-top:1px dotted red;
}
.tree-node-bottom{
border-bottom:1px dotted red;
}
.tree-node-append .tree-title{
border:1px dotted red;
}
.tree-editor{
border:1px solid #ccc;
font-size:12px;
line-height:16px;
width:80px;
position:absolute;
top:0;
}
.menu{
position:absolute;
background:#f0f0f0 url('../img/menu.gif') repeat-y;
margin:0;
padding:2px;
border:1px solid #ccc;
overflow:hidden;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
.menu-item{
position:relative;
margin:0;
padding:0;
height:22px;
line-height:20px;
overflow:hidden;
font-size:.8em;
color:#565656;
cursor:pointer;
border:1px solid transparent;
_border:1px solid #f0f0f0;
}
.menu-text{
position:absolute;
left:28px;
top:0px;
}
.menu-icon{
position:absolute;
width:16px;
height:16px;
top:3px;
left:2px;
}
.menu-rightarrow{
position: absolute;
width:4px;
height:7px;
top:7px;
right:5px;
background:url('../img/menu_rightarrow.png') no-repeat;
}
.menu-sep{
margin:3px 0px 3px 24px;
line-height:2px;
font-size:2px;
background:url('../img/menu_sep.png') repeat-x;
}
.menu-active{
border:1px solid #73D6F6;
background:#fafafa;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
.menu-shadow{
position:absolute;
background:#ddd;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.5);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.5);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.5);
}
.icon-db{
background:url('../img/db-icon.png') no-repeat;
}
.icon-blank{
background:url('../img/blank.gif') no-repeat;
}
.icon-add{
background:url('../img/edit_add.png') no-repeat;
}
.icon-edit{
background:url('../img/pencil.png') no-repeat;
}
.icon-remove{
background:url('../img/edit_remove.png') no-repeat;
}
.icon-table{
background:url('../img/table.png') no-repeat;
}
.icon-style{
background:url('../img/palette.png') no-repeat;
}
.icon-properties{
background:url('../img/properties.png') no-repeat;
}
.icon-save{
background:url('../img/filesave.png') no-repeat;
}
.icon-cut{
background:url('../img/cut.png') no-repeat;
}
.icon-ok{
background:url('../img/ok.png') no-repeat;
}
.icon-no{
background:url('../img/no.png') no-repeat;
}
.icon-cancel{
background:url('../img/cancel.png') no-repeat;
}
.icon-reload{
background:url('../img/reload.png') no-repeat;
}
.icon-search{
background:url('../img/search.png') no-repeat;
}
.icon-print{
background:url('../img/print.png') no-repeat;
}
.icon-help{
background:url('../img/help.png') no-repeat;
}
.icon-undo{
background:url('../img/undo.png') no-repeat;
}
.icon-redo{
background:url('../img/redo.png') no-repeat;
}
.icon-back{
background:url('../img/back.png') no-repeat;
}
.icon-sum{
background:url('../img/sum.png') no-repeat;
}
/* CSS Document */
.flexigrid {
font-size: .8em;
position: relative;
border: 0px solid #eee;
overflow: hidden;
color: #000;
}
.flexigrid.hideBody {
height: 26px !important;
border-bottom: 1px solid #ccc;
}
.ie6fullwidthbug {
border-right: 0px solid #ccc;
padding-right: 2px;
}
.flexigrid div.nDiv {
background: #eee url(../img/line.gif) repeat-y -1px top;
border: 1px solid #ccc;
border-top: 0px;
overflow: auto;
left: 0px;
position: absolute;
z-index: 999;
float: left;
}
.flexigrid div.nDiv table {
margin: 2px;
}
.flexigrid div.hDivBox {
float: left;
padding-right: 40px;
}
.flexigrid div.bDiv table {
margin-bottom: 10px;
}
.flexigrid div.bDiv table.autoht {
border-bottom: 0px;
margin-bottom: 0px;
}
.flexigrid div.nDiv td {
padding: 2px 3px;
border: 1px solid #eee;
cursor: default;
}
.flexigrid div.nDiv tr:hover td,.flexigrid div.nDiv tr.ndcolover td {
background: #d5effc url(../img/hl.png) repeat-x top;
border: 1px solid #a8d8eb;
}
.flexigrid div.nDiv td.ndcol1 {
border-right: 1px solid #ccc;
}
.flexigrid div.nDiv td.ndcol2 {
border-left: 1px solid #fff;
padding-right: 10px;
}
.flexigrid div.nDiv tr:hover td.ndcol1,.flexigrid div.nDiv tr.ndcolover td.ndcol1
{
border-right: 1px solid #d2e3ec;
}
.flexigrid div.nDiv tr:hover td.ndcol2,.flexigrid div.nDiv tr.ndcolover td.ndcol2
{
border-left: 1px solid #eef8ff;
}
.flexigrid div.nBtn {
position: absolute;
height: 24px;
width: 14px;
z-index: 900;
background: #fafafa url(../img/fhbg.gif) repeat-x bottom;
border: 0px solid #ccc;
border-left: 1px solid #ccc;
top: 0px;
left: 0px;
margin-top: 1px;
cursor: pointer;
display: none;
}
.flexigrid div.nBtn div {
height: 24px;
width: 12px;
border-left: 1px solid #fff;
float: left;
background: url(../img/ddn.png) no-repeat center;
}
.flexigrid div.nBtn.srtd {
background: url(../img/wbg.gif) repeat-x 0px -1px;
}
.flexigrid div.mDiv {
background: url(../img/wbg.gif) repeat-x top;
border: 1px solid #ccc;
border-bottom: 0px;
border-top: 0px;
font-weight: bold;
display: block;
overflow: hidden;
white-space: nowrap;
position: relative;
font-size:.95em;
color:#333333;
font-weight:bold;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
}
.flexigrid div.mDiv div {
padding: 6px;
white-space: nowrap;
}
.flexigrid div.mDiv div.ptogtitle {
position: absolute;
top: 4px;
right: 3px;
padding: 0px;
height: 16px;
width: 16px;
overflow: hidden;
border: 1px solid #ccc;
cursor: pointer;
}
.flexigrid div.mDiv div.ptogtitle:hover {
background-position: left -2px;
border-color: #9a9a9a;
background: #FFFFFF;
}
.flexigrid div.mDiv div.ptogtitle span {
display: block;
border-left: 1px solid #eee;
border-top: 1px solid #fff;
border-bottom: 1px solid #ddd;
width: 14px;
height: 14px;
background: url(../img/uup.png) no-repeat center;
}
.flexigrid div.mDiv div.ptogtitle span:hover {
background: url(../img/uup-hover-blue.png) no-repeat center;
}
.flexigrid div.mDiv div.ptogtitle.vsble span {
background: url(../img/ddn.png) no-repeat center;
}
.flexigrid div.mDiv div.preview {
position: absolute;
top: 4px;
right: 69px;
padding: 0px;
height: 16px;
width: 16px;
overflow: hidden;
background:url(../img/preview.png);
border: 1px solid #ccc;
cursor: pointer;
}
.flexigrid div.mDiv div.preview:hover {
background: #FFFFFF url(../img/preview-hover-blue.png);
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.download {
position: absolute;
top: 4px;
right: 91px;
padding: 0px;
height: 16px;
width: 16px;
overflow: hidden;
background:url(../img/download.png);
border: 1px solid #ccc;
cursor: pointer;
}
.flexigrid div.mDiv div.download:hover {
background: #FFFFFF url(../img/download-hover-blue.png);
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.open-in-manager {
position: absolute;
top: 4px;
right: 47px;
padding: 0px;
height: 16px;
width: 16px;
overflow: hidden;
border: 1px solid #ccc;
background:url(../img/open-in-manager.png);
cursor: pointer;
}
.flexigrid div.mDiv div.open-in-manager:hover {
background:#FFFFFF url(../img/open-in-manager-hover-blue.png);
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.delete {
position: absolute;
top: 4px;
right: 25px;
padding: 0px;
height: 16px;
width: 16px;
overflow: hidden;
background:url(../img/delete-datasource.png);
border: 1px solid #ccc;
cursor: pointer;
}
.flexigrid div.mDiv div.delete:hover {
background: #FFFFFF url(../img/delete-datasource-hover-blue.png);
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.reproject {
position: absolute;
top: 4px;
right: 113px;
padding: 0px;
height: 16px;
width: auto;
overflow: hidden;
border: 1px solid #ccc;
cursor: pointer;
}
.flexigrid div.mDiv div.reproject:hover {
background: #FFFFFF;
border-color: #9a9a9a;
}
.flexigrid div.mDiv div.convert {
position: absolute;
top: 4px;
right: 188px;
padding: 0px;
height: 16px;
width: auto;
overflow: hidden;
border: 1px solid #ccc;
cursor: pointer;
}
.flexigrid div.mDiv div.convert:hover {
background: #FFFFFF;
border-color: #9a9a9a;
}
.change-srs{text-decoration:none;color:#808080;text-shadow:none;font-weight:normal;padding: 0 3px 0 3px;}
.change-srs:hover{color:#45a0f3;}
.change-format{text-decoration:none;color:#808080;text-shadow:none;font-weight:normal;padding: 0 3px 0 3px;}
.change-format:hover{color:#45a0f3;}
.flexigrid div.tDiv /*toolbar*/ {
background: #fafafa url(../img/bg.gif) repeat-x top;
position: relative;
border: 1px solid #ccc;
border-bottom: 0px;
overflow: hidden;
}
.flexigrid div.tDiv2 {
float: left;
clear: both;
padding: 1px;
}
.flexigrid div.sDiv /*toolbar*/ {
background: #fafafa url(../img/bg.gif) repeat-x top;
position: relative;
border: 1px solid #ccc;
border-top: 0px;
overflow: hidden;
display: none;
}
.flexigrid div.sDiv2 {
float: left;
clear: both;
padding: 5px;
padding-left: 5px;
width: 1024px;
}
.flexigrid div.sDiv2 input,.flexigrid div.sDiv2 select {
vertical-align: middle;
}
.flexigrid div.btnseparator {
float: left;
height: 22px;
border-left: 1px solid #ccc;
border-right: 1px solid #fff;
margin: 1px;
}
.flexigrid div.fbutton {
float: left;
display: block;
cursor: pointer;
padding: 1px;
}
.flexigrid div.fbutton div {
float: left;
padding: 1px 3px;
}
.flexigrid div.fbutton span {
float: left;
display: block;
padding: 3px;
}
.flexigrid div.fbutton:hover,.flexigrid div.fbutton.fbOver {
padding: 0px;
border: 1px solid #ccc;
}
.flexigrid div.fbutton:hover div,.flexigrid div.fbutton.fbOver div {
padding: 0px 2px;
border-left: 1px solid #fff;
border-top: 1px solid #fff;
border-right: 1px solid #eee;
border-bottom: 1px solid #eee;
}
/* end toolbar*/
.flexigrid div.hDiv {
background: #fafafa url(../img/fhbg.gif) repeat-x bottom;
position: relative;
border: 1px solid #ccc;
border-bottom: 0px;
overflow: hidden;
}
.flexigrid div.hDiv table {
border-right: 1px solid #fff;
}
.flexigrid div.cDrag {
float: left;
position: absolute;
z-index: 2;
overflow: visible;
}
.flexigrid div.cDrag div {
float: left;
background: none;
display: block;
position: absolute;
height: 24px;
width: 5px;
cursor: col-resize;
}
.flexigrid div.cDrag div:hover,.flexigrid div.cDrag div.dragging {
background: url(../img/line.gif) repeat-y 2px center;
}
.flexigrid div.iDiv {
border: 1px solid #316ac5;
position: absolute;
overflow: visible;
background: none;
}
.flexigrid div.iDiv input,.flexigrid div.iDiv select,.flexigrid div.iDiv textarea
{
font-size: .95em;
}
.flexigrid div.iDiv input.tb {
border: 0px;
padding: 0px;
width: 100%;
height: 100%;
padding: 0px;
background: none;
}
.flexigrid div.bDiv {
border: 1px solid #ccc;
border-top: 0px;
background: #fff;
overflow: auto;
position: relative;
}
.flexigrid div.bDiv table {
border-bottom: 1px solid #ccc;
}
.flexigrid div.hGrip {
position: absolute;
top: 0px;
right: 0px;
height: 5px;
width: 5px;
background: url(../img/line.gif) repeat-x center;
margin-right: 1px;
cursor: col-resize;
}
.flexigrid div.hGrip:hover,.flexigrid div.hGrip.hgOver {
border-right: 1px solid #999;
margin-right: 0px;
}
.flexigrid div.vGrip {
height: 5px;
overflow: hidden;
position: relative;
background: #fafafa url(../img/wbg.gif) repeat-x 0px -1px;
border: 1px solid #ccc;
border-top: 0px;
text-align: center;
cursor: row-resize;
}
.flexigrid div.vGrip span {
display: block;
margin: 1px auto;
width: 20px;
height: 1px;
overflow: hidden;
border-top: 1px solid #aaa;
border-bottom: 1px solid #aaa;
background: none;
}
.flexigrid div.hDiv th,.flexigrid div.bDiv td
/* common cell properties*/ {
text-align: left;
border-right: 1px solid #ddd;
border-left: 1px solid #fff;
overflow: hidden;
vertical-align: top !important;
padding-left: 0;
padding-right: 0;
}
.flexigrid div.hDiv th div,.flexigrid div.bDiv td div,div.colCopy div
/* common inner cell properties*/ {
padding: 5px;
border-left: 0px solid #fff;
}
.flexigrid div.hDiv th,div.colCopy {
font-weight: normal;
height: 24px;
cursor: default;
white-space: nowrap;
overflow: hidden;
}
div.colCopy {
font-family: Arial, Helvetica, sans-serif;
font-size: 11px;
background: #fafafa url(../img/fhbg.gif) repeat-x bottom;
border: 1px solid #ccc;
border-bottom: 0px;
overflow: hidden;
}
.flexigrid div.hDiv th.sorted {
background: url(../img/wbg.gif) repeat-x 0px -1px;
border-bottom: 0px solid #ccc;
}
.flexigrid div.hDiv th.thOver {
}
.flexigrid div.hDiv th.thOver div,.flexigrid div.hDiv th.sorted.thOver div
{
border-bottom: 1px solid #808080;
padding-bottom: 4px;
}
.flexigrid div.hDiv th.sorted div {
border-bottom: 0px solid #ccc;
padding-bottom: 5px;
}
.flexigrid div.hDiv th{
font-size:.95em;
}
.flexigrid div.hDiv th.thMove {
background: #fff;
color: #fff;
}
.flexigrid div.hDiv th.sorted.thMove div {
border-bottom: 1px solid #fff;
padding-bottom: 4px
}
.flexigrid div.hDiv th.thMove div {
background: #fff !important;
}
.flexigrid div.hDiv th div.sdesc {
background: url(../img/dn.png) no-repeat center top;
}
.flexigrid div.hDiv th div.sasc {
background: url(../img/up.png) no-repeat center top;
}
.flexigrid div.bDiv td {
border-bottom: 1px solid #fff;
vertical-align: top;
white-space: nowrap;
}
.flexigrid div.hDiv th div {
}
.flexigrid span.cdropleft {
display: block;
background: url(../img/prev.gif) no-repeat -4px center;
width: 24px;
height: 24px;
position: relative;
top: -24px;
margin-bottom: -24px;
z-index: 3;
}
.flexigrid div.hDiv span.cdropright {
display: block;
background: url(../img/next.gif) no-repeat 12px center;
width: 24px;
height: 24px;
float: right;
position: relative;
top: -24px;
margin-bottom: -24px;
}
.flexigrid div.bDiv td div {
border-top: 0px solid #fff;
padding-bottom: 4px;
}
.flexigrid tr td.sorted {
background: #f3f3f3;
border-right: 1px solid #ddd;
border-bottom: 1px solid #f3f3f3;
}
.flexigrid tr td.sorted div {
}
.flexigrid tr.erow td {
background: #f7f7f7;
border-bottom: 1px solid #f7f7f7;
}
.flexigrid tr.erow td.sorted {
background: #e3e3e3;
border-bottom: 1px solid #e3e3e3;
}
.flexigrid tr.erow td.sorted div {
}
.flexigrid div.bDiv tr:hover td,.flexigrid div.bDiv tr:hover td.sorted,.flexigrid div.bDiv tr.trOver td.sorted,.flexigrid div.bDiv tr.trOver td
{
background:#ffffff;background: -moz-linear-gradient(top, #FFFFFF, #eaeaea);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#eaeaea));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eaeaea'); /* for IE */
border-left: 1px solid #eef8ff;
border-bottom: 1px solid #d3d3d3;
}
.flexigrid div.bDiv tr.trSelected:hover td,.flexigrid div.bDiv tr.trSelected:hover td.sorted,.flexigrid div.bDiv tr.trOver.trSelected td.sorted,.flexigrid div.bDiv tr.trOver.trSelected td,.flexigrid tr.trSelected td.sorted,.flexigrid tr.trSelected td
{
background:#82e9fa;
background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */
border-right: 1px solid #82e9fa;
border-left: 1px solid #82e9fa;
border-bottom: 1px solid #82e9fa;
}
/* novstripe adjustments */
.flexigrid.novstripe .bDiv table {
border-bottom: 1px solid #ccc;
border-right: 1px solid #ccc;
}
.flexigrid.novstripe div.bDiv td {
border-right-color: #fff;
}
.flexigrid.novstripe div.bDiv tr.erow td.sorted {
border-right-color: #e3e3e3;
}
.flexigrid.novstripe div.bDiv tr td.sorted {
border-right-color: #f3f3f3;
}
.flexigrid.novstripe div.bDiv tr.erow td {
border-right-color: #f7f7f7;
border-left-color: #f7f7f7;
}
.flexigrid.novstripe div.bDiv tr.trSelected:hover td,.flexigrid.novstripe div.bDiv tr.trSelected:hover td.sorted,.flexigrid.novstripe div.bDiv tr.trOver.trSelected td.sorted,.flexigrid.novstripe div.bDiv tr.trOver.trSelected td,.flexigrid.novstripe tr.trSelected td.sorted,.flexigrid.novstripe tr.trSelected td
{
border-right: 1px solid #0066FF;
border-left: 1px solid #0066FF;
}
.flexigrid.novstripe div.bDiv tr.trOver td,.flexigrid.novstripe div.bDiv tr:hover td
{
border-left-color: #d9ebf5;
border-right-color: #d9ebf5;
}
/* end novstripe */
.flexigrid div.pDiv {
background: url(../img/wbg.gif) repeat-x 0 -1px;
border: 1px solid #ccc;
border-top: 0px;
overflow: hidden;
white-space: nowrap;
position: relative;
}
.flexigrid div.pDiv div.pDiv2 {
margin: 3px;
margin-left: -2px;
float: left;
width: 1024px;
}
div.pGroup {
float: left;
background: none;
height: 24px;
margin: 0px 5px;
}
.flexigrid div.pDiv .pPageStat,.flexigrid div.pDiv .pcontrol {
position: relative;
top: 5px;
overflow: visible;
font-size:.9em;
}
.flexigrid div.pDiv input {
vertical-align: text-top;
position: relative;
top: -5px;
}
.flexigrid div.pDiv div.pButton {
float: left;
width: 22px;
height: 22px;
border: 0px;
cursor: pointer;
overflow: hidden;
}
.flexigrid div.pDiv div.pButton:hover,.flexigrid div.pDiv div.pButton.pBtnOver
{
width: 20px;
height: 20px;
border: 1px solid #ccc;
cursor: pointer;
}
.flexigrid div.pDiv div.pButton span {
width: 20px;
height: 20px;
display: block;
float: left;
}
.flexigrid div.pDiv div.pButton:hover span,.flexigrid div.pDiv div.pButton.pBtnOver span
{
width: 19px;
height: 19px;
border-top: 1px solid #fff;
border-left: 1px solid #fff;
}
.flexigrid .pSearch {
background: url(../img/magnifier.png) no-repeat center;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
.flexigrid .pSearch:hover {
background: url(../img/magnifier-hover-blue.png) no-repeat center;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
.flexigrid .pFirst {
background: url(../img/first.png) no-repeat center;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
.flexigrid .pFirst:hover {
background: #FFFFFF url(../img/first-hover-blue.png) no-repeat center;
}
.flexigrid .pPrev {
background: url(../img/prev.png) no-repeat center;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
.flexigrid .pPrev:hover {
background: #FFFFFF url(../img/prev-hover-blue.png) no-repeat center;
}
.flexigrid .pNext {
background: url(../img/next.png) no-repeat center;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
.flexigrid .pNext:hover {
background: #FFFFFF url(../img/next-hover-blue.png) no-repeat center;
}
.flexigrid .pLast {
background: url(../img/last.png) no-repeat center;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
.flexigrid .pLast:hover {
background: #FFFFFF url(../img/last-hover-blue.png) no-repeat center;
}
.flexigrid .pReload {
background: url(../img/load.png) no-repeat center;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
.flexigrid .pReload.loading {
background: url(../img/load.gif) no-repeat center;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
}
/* ie adjustments */
.flexigrid.ie div.hDiv th div,.flexigrid.ie div.bDiv td div,div.colCopy.ie div
/* common inner cell properties*/ {
overflow: hidden;
}
.log-out{width:350px;height:auto;}
#logout-message p{margin:0;padding:0 0 0 0;}
#add-database-dialog{width:350px;height:auto;}
#add-database-dialog table{margin:5px 0 0 0;width:100%;}
#add-directory-dialog{width:350px;height:auto;}
#add-directory-dialog table{margin:5px 0 0 0;width:100%;}
#add-directory-dialog ul {margin:5px 0 0 0;padding:0;}
#add-directory-dialog ul li {margin:0;padding:0;display:inline;}
#add-layer-dialog{width:350px;height:auto;}
#add-layer-dialog p{margin:0;padding:10px 0 0 0;}
#open-map-dialog{width:350px;height:auto;}
#open-map-dialog p{margin:0;padding:10px 0 0 0;}
#save-as-map-dialog{width:350px;height:auto;}
#save-as-map-dialog table {margin:5px 0 0 0;width:100%;}
#zoom-to-point-dialog{width:350px;height:auto;}
#zoom-to-point-dialog table {margin:5px 0 0 0;width:100%;margin:0 auto;}
#zoom-to-point-dialog table tr td{padding:5px;}
input-zoom{width:70%;}
#change-srs-dialog{width:350px;height:auto;}
#change-srs-dialog table{margin:5px 0 0 0;width:100%;}
#change-format-dialog{width:350px;height:auto;}
#change-format-dialog table{margin:5px 0 0 0;width:100%;}
#preview-dialog{width:350px;height:auto;}
#view-table-dialog{width:550px;height:auto;}
#view-table-dialog.window-body{padding:0;font-size:1.3em;}
#editing-toolbar{width:350px;height:auto;}
#editing-toolbar.window-body, #spatial-toolbar.window-body,#raster-toolbar.window-body, #terrain-toolbar.window-body {padding:0px;border:0;background: -moz-linear-gradient(top, #B6B6B6, #c7c7c7);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E2E2E2', endColorstr='#B6B6B6');}
#style-dialog{width:350px;height:auto;}
#style-dialog table{width:100%;margin 0 auto;}
#style-dialog table tr td{padding: 5px ;}
#style-dialog table tr td.title{width:110px;}
input.opacity{width:50px;border:0;background:#FFFFFF;border:0;display:inline;font-weight:bold;text-indent:10px;}
.point-symbol-container{width:100%;background:#FFFFFF;height:30%;margin:0;border:0;-moz-border-radius:4px;-webkit-border-radius: 4px;border-radius:4px;border:1px solid #9f9f9f;}
.point-symbol-container img{margin:3px;margin-right:0;background:#E6E6E6;moz-border-radius:4px;-webkit-border-radius: 4px;border-radius:4px;}
.point-symbol-container img.active{margin:3px;margin-right:0;background:#60b1f0;}
.point-symbol-container img:hover{margin-right:0;background:#FFFFFF;}
div.color_picker {
height: 20px;
width: 20px;
padding: 0 !important;
border: 1px solid #9f9f9f;
background: url(../img/arrow.gif) no-repeat top right;
cursor: pointer;
line-height: 20px;
display:inline-block;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius: 2px;
}
div#color_selector {
width: 150px;
position: absolute;
padding:2px;
border:1px solid #ccc;
overflow:hidden;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
background-color: #EFEFEF;
padding: 5px;
z-index:10000000000;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
}
div#color_custom {width: 100%; float:left }
div#color_custom label {font-size: .8em; color: #2F2F2F; margin: 5px 2px; width: 25%}
div#color_custom input {margin: 5px 2px; padding: 0; font-size: .8em; border: 1px solid #9F9F9F; width: 65%; }
div.color_swatch {
height: 12px;
width: 12px;
border: 1px solid #000;
margin: 2px;
float: left;
cursor: pointer;
line-height: 12px;
}
#map{width:100%;height:90%;}
.window {
position:absolute;
overflow:hidden;
background: -moz-linear-gradient(top, #EEEEEE, #c7c7c7);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E2E2E2', endColorstr='#B6B6B6');
padding:5px;
border:1px solid #949494;
-moz-border-radius:5px;
-webkit-border-radius: 5px;
}
.window-shadow{
position:absolute;
background:#ddd;
-moz-border-radius:5px;
-webkit-border-radius: 5px;
-moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2);
filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2);
}
.window .window-header{
background:transparent;
padding:2px 0px 4px 0px;
}
.window .window-body{
background:#fff;
border:1px solid #B6B6B6;
border-top-width:0px;
padding:10px;
}
.window .window-header .panel-icon{
left:1px;
top:1px;
}
.window .window-header .panel-with-icon{
padding-left:18px;
}
.window .window-header .panel-tool{
top:0px;
right:1px;
}
.window-proxy{
position:absolute;
overflow:hidden;
border:1px dashed #15428b;
}
.window-proxy-mask{
position:absolute;
background:#fafafa;
filter:alpha(opacity=10);
opacity:0.10;
}
.window-mask{
position:absolute;
left:0;
top:0;
width:100%;
height:100%;
filter:alpha(opacity=40);
opacity:0.40;
background:#ccc;
display1:none;
font-size:1px;
*zoom:1;
overflow:hidden;
}
.panel{
overflow:hidden;
font-size:12px;
}
.panel-header{
padding:5px;
line-height:15px;
font-size:1em;
color:#333333;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
font-weight:bold;
font-size:12px;
background:url('../img/panel_title.png') repeat-x;
position:relative;
border:1px solid #B6B6B6;
}
.panel-header-noborder{
border-width:0px;
border-bottom:1px solid #909090;
}
.panel-body{
overflow:auto;
border:1px solid #99BBE8;
border-top-width:0px;
}
.panel-body-noheader{
border-top-width:1px;
}
.panel-body-noborder{
border-width:0px;
}
.panel-with-icon{
padding-left:18px;
}
.panel-icon{
position:absolute;
left:5px;
top:4px;
width:16px;
height:16px;
}
.panel-tool{
position:absolute;
right:5px;
top:4px;
}
.panel-tool div{
display:block;
float:right;
width:16px;
height:16px;
margin-left:2px;
cursor:pointer;
opacity:0.6;
filter:alpha(opacity=60);
}
.panel-tool div.panel-tool-over{
opacity:1;
filter:alpha(opacity=100);
}
.panel-tool-close{
background:url('../img/panel_tools-blue.gif') no-repeat -16px 0px;
}
.panel-tool-min{
background:url('../img/panel_tools-blue.gif') no-repeat 0px 0px;
}
.panel-tool-max{
background:url('../img/panel_tools-blue.gif') no-repeat 0px -16px;
}
.panel-tool-restore{
background:url('../img/panel_tools-blue.gif') no-repeat -16px -16px;
}
.panel-tool-collapse{
background:url('../img/panel_tool_collapse-blue.gif') no-repeat;
}
.panel-tool-expand{
background:url('../img/panel_tool_expand-blue.gif') no-repeat;
}
.panel-loading{
padding:11px 0px 10px 30px;
background:url('../img/panel_loading.gif') no-repeat 10px 10px;
}
a.l-btn{
float:right;
color:#333333;
background: -moz-linear-gradient(top, #e2e2e2, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E2E2E2', endColorstr='#B6B6B6');
font-size:12px;
text-decoration:none;
display:inline-block;
zoom:1;
height:24px;
padding-right:18px;
cursor:pointer;
outline:none;
margin:15px 0 5px 5px;
-moz-border-radius:4px;
border-radius:4px;
-webkit-border-radius:4px;
text-shadow: #FFFFFF 0px 1px 0px;
}
a.l-btn:hover{
text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */
font-weight: normal; color: #FFFFFF;
}
a.l-btn-plain{
background:transparent;
padding-right:5px;
border:1px solid transparent;
_border:0px solid #efefef;
_padding:1px 6px 1px 1px;
}
a.l-btn-disabled{
color:#ccc;
opacity:0.5;
filter:alpha(opacity=50);
cursor:default;
}
a.l-btn span.l-btn-left{
display:inline-block;
padding:4px 0px 4px 18px;
line-height:16px;
height:16px;
-moz-border-radius:4px;
border-radius:4px;
-webkit-border-radius:4px;
}
a.l-btn-plain span.l-btn-left{
background:transparent;
padding-left:5px;
}
a.l-btn span span.l-btn-text{
display:inline-block;
height:16px;
line-height:16px;
padding:0px;
}
a.l-btn span span span.l-btn-empty{
display:inline-block;
padding:0px;
width:16px;
}
a:hover.l-btn{
background-position: bottom right;
outline:none;
}
a:hover.l-btn span.l-btn-left{
background-position: bottom left;
}
a:hover.l-btn-plain{
border:1px solid #7eabcd;
background:url('../img/button_plain_hover.png') repeat-x left bottom;
_padding:0px 5px 0px 0px;
-moz-border-radius:3px;
-webkit-border-radius: 3px;
}
a:hover.l-btn-disabled{
background-position:top right;
}
a:hover.l-btn-disabled span.l-btn-left{
background-position:top left;
}
/*
* jQuery UI CSS Framework 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Theming/API
*/
/* Layout helpers
----------------------------------*/
.ui-helper-hidden { display: none; }
.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); }
.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; }
.ui-helper-clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
.ui-helper-clearfix { display: inline-block; }
/* required comment for clearfix to work in Opera \*/
* html .ui-helper-clearfix { height:1%; }
.ui-helper-clearfix { display:block; }
/* end clearfix */
.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); }
/* Interaction Cues
----------------------------------*/
.ui-state-disabled { cursor: default !important; }
/* Icons
----------------------------------*/
/* states and images */
.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; }
/* Misc visuals
----------------------------------*/
/* Overlays */
.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
/*
* jQuery UI CSS Framework 1.8.12
*/
/* Component containers
----------------------------------*/
.ui-widget { font-family: Verdana,Arial,sans-serif; font-size: 1.1em; }
.ui-widget .ui-widget { font-size: 1em; }
.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Verdana,Arial,sans-serif; font-size: 1em; }
.ui-widget-content { border: 1px solid #aaaaaa; background: #ffffff url(../img/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x; color: #222222; }
.ui-widget-content a { color: #222222; }
.ui-widget-header { border:0; background: #cccccc url(../img/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x; color: #222222; font-weight: bold; font-size: .7em; color: #545454;text-shadow: #FFFFFF 0px 1px 0px; }
.ui-widget-header a { color: #222222; }
/* Interaction states
----------------------------------*/
.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default {text-shadow: #FFFFFF 0px 1px 0px;
background: -moz-linear-gradient(top, #e2e2e2, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e2e2e2', endColorstr='#b6b6b6'); /* for IE */ font-weight: normal; color: #333333; }
.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555; text-decoration: none; }
.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */
font-weight: normal; color: #FFFFFF; }
.ui-state-hover a, .ui-state-hover a:hover { color: #FFFFFF; text-decoration: none; }
.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active {text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #82e9fa , #398ee4);
background: -webkit-gradient(linear, left top, left bottom, from(#82e9fa), to(#398ee4));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#82e9fa', endColorstr='#398ee4'); /* for IE */
font-weight: normal; color: #FFFFFF; }
.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #FFFFFF; text-decoration: none; }
.ui-widget :active { outline: none; }
/* Interaction Cues
----------------------------------*/
.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #fcefa1; background: #fbf9ee url(../img/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x; color: #363636; }
.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; }
.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #fef1ec url(../img/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x; color: #cd0a0a; }
.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #cd0a0a; }
.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #cd0a0a; }
.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; }
.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; }
.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; }
/* Icons
----------------------------------*/
/* states and images */
.ui-icon { width: 16px; height: 16px; background-image: url(../img/ui-icons_222222_256x240.png); }
.ui-widget-content .ui-icon {background-image: url(../img/ui-icons_222222_256x240.png); }
.ui-widget-header .ui-icon {background-image: url(../img/ui-icons_222222_256x240.png); }
.ui-state-default .ui-icon { background-image: url(../img/ui-icons_888888_256x240.png); }
.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(../img/ui-icons_454545_256x240.png); }
.ui-state-active .ui-icon {background-image: url(../img/ui-icons_454545_256x240.png); }
.ui-state-highlight .ui-icon {background-image: url(../img/ui-icons_2e83ff_256x240.png); }
.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(../img/ui-icons_cd0a0a_256x240.png); }
/* positioning */
.ui-icon-carat-1-n { background-position: 0 0; }
.ui-icon-carat-1-ne { background-position: -16px 0; }
.ui-icon-carat-1-e { background-position: -32px 0; }
.ui-icon-carat-1-se { background-position: -48px 0; }
.ui-icon-carat-1-s { background-position: -64px 0; }
.ui-icon-carat-1-sw { background-position: -80px 0; }
.ui-icon-carat-1-w { background-position: -96px 0; }
.ui-icon-carat-1-nw { background-position: -112px 0; }
.ui-icon-carat-2-n-s { background-position: -128px 0; }
.ui-icon-carat-2-e-w { background-position: -144px 0; }
.ui-icon-triangle-1-n { background-position: 0 -16px; }
.ui-icon-triangle-1-ne { background-position: -16px -16px; }
.ui-icon-triangle-1-e { background-position: -32px -16px; }
.ui-icon-triangle-1-se { background-position: -48px -16px; }
.ui-icon-triangle-1-s { background-position: -64px -16px; }
.ui-icon-triangle-1-sw { background-position: -80px -16px; }
.ui-icon-triangle-1-w { background-position: -96px -16px; }
.ui-icon-triangle-1-nw { background-position: -112px -16px; }
.ui-icon-triangle-2-n-s { background-position: -128px -16px; }
.ui-icon-triangle-2-e-w { background-position: -144px -16px; }
.ui-icon-arrow-1-n { background-position: 0 -32px; }
.ui-icon-arrow-1-ne { background-position: -16px -32px; }
.ui-icon-arrow-1-e { background-position: -32px -32px; }
.ui-icon-arrow-1-se { background-position: -48px -32px; }
.ui-icon-arrow-1-s { background-position: -64px -32px; }
.ui-icon-arrow-1-sw { background-position: -80px -32px; }
.ui-icon-arrow-1-w { background-position: -96px -32px; }
.ui-icon-arrow-1-nw { background-position: -112px -32px; }
.ui-icon-arrow-2-n-s { background-position: -128px -32px; }
.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }
.ui-icon-arrow-2-e-w { background-position: -160px -32px; }
.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }
.ui-icon-arrowstop-1-n { background-position: -192px -32px; }
.ui-icon-arrowstop-1-e { background-position: -208px -32px; }
.ui-icon-arrowstop-1-s { background-position: -224px -32px; }
.ui-icon-arrowstop-1-w { background-position: -240px -32px; }
.ui-icon-arrowthick-1-n { background-position: 0 -48px; }
.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }
.ui-icon-arrowthick-1-e { background-position: -32px -48px; }
.ui-icon-arrowthick-1-se { background-position: -48px -48px; }
.ui-icon-arrowthick-1-s { background-position: -64px -48px; }
.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }
.ui-icon-arrowthick-1-w { background-position: -96px -48px; }
.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }
.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }
.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }
.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }
.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }
.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }
.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }
.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }
.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }
.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }
.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }
.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }
.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }
.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }
.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }
.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }
.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }
.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }
.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }
.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }
.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }
.ui-icon-arrow-4 { background-position: 0 -80px; }
.ui-icon-arrow-4-diag { background-position: -16px -80px; }
.ui-icon-extlink { background-position: -32px -80px; }
.ui-icon-newwin { background-position: -48px -80px; }
.ui-icon-refresh { background-position: -64px -80px; }
.ui-icon-shuffle { background-position: -80px -80px; }
.ui-icon-transfer-e-w { background-position: -96px -80px; }
.ui-icon-transferthick-e-w { background-position: -112px -80px; }
.ui-icon-folder-collapsed { background-position: 0 -96px; }
.ui-icon-folder-open { background-position: -16px -96px; }
.ui-icon-document { background-position: -32px -96px; }
.ui-icon-document-b { background-position: -48px -96px; }
.ui-icon-note { background-position: -64px -96px; }
.ui-icon-mail-closed { background-position: -80px -96px; }
.ui-icon-mail-open { background-position: -96px -96px; }
.ui-icon-suitcase { background-position: -112px -96px; }
.ui-icon-comment { background-position: -128px -96px; }
.ui-icon-person { background-position: -144px -96px; }
.ui-icon-print { background-position: -160px -96px; }
.ui-icon-trash { background-position: -176px -96px; }
.ui-icon-locked { background-position: -192px -96px; }
.ui-icon-unlocked { background-position: -208px -96px; }
.ui-icon-bookmark { background-position: -224px -96px; }
.ui-icon-tag { background-position: -240px -96px; }
.ui-icon-home { background-position: 0 -112px; }
.ui-icon-flag { background-position: -16px -112px; }
.ui-icon-calendar { background-position: -32px -112px; }
.ui-icon-cart { background-position: -48px -112px; }
.ui-icon-pencil { background-position: -64px -112px; }
.ui-icon-clock { background-position: -80px -112px; }
.ui-icon-disk { background-position: -96px -112px; }
.ui-icon-calculator { background-position: -112px -112px; }
.ui-icon-zoomin { background-position: -128px -112px; }
.ui-icon-zoomout { background-position: -144px -112px; }
.ui-icon-search { background-position: -160px -112px; }
.ui-icon-wrench { background-position: -176px -112px; }
.ui-icon-gear { background-position: -192px -112px; }
.ui-icon-heart { background-position: -208px -112px; }
.ui-icon-star { background-position: -224px -112px; }
.ui-icon-link { background-position: -240px -112px; }
.ui-icon-cancel { background-position: 0 -128px; }
.ui-icon-plus { background-position: -16px -128px; }
.ui-icon-plusthick { background-position: -32px -128px; }
.ui-icon-minus { background-position: -48px -128px; }
.ui-icon-minusthick { background-position: -64px -128px; }
.ui-icon-close { background-position: -80px -128px; }
.ui-icon-closethick { background-position: -96px -128px; }
.ui-icon-key { background-position: -112px -128px; }
.ui-icon-lightbulb { background-position: -128px -128px; }
.ui-icon-scissors { background-position: -144px -128px; }
.ui-icon-clipboard { background-position: -160px -128px; }
.ui-icon-copy { background-position: -176px -128px; }
.ui-icon-contact { background-position: -192px -128px; }
.ui-icon-image { background-position: -208px -128px; }
.ui-icon-video { background-position: -224px -128px; }
.ui-icon-script { background-position: -240px -128px; }
.ui-icon-alert { background-position: 0 -144px; }
.ui-icon-info { background-position: -16px -144px; }
.ui-icon-notice { background-position: -32px -144px; }
.ui-icon-help { background-position: -48px -144px; }
.ui-icon-check { background-position: -64px -144px; }
.ui-icon-bullet { background-position: -80px -144px; }
.ui-icon-radio-off { background-position: -96px -144px; }
.ui-icon-radio-on { background-position: -112px -144px; }
.ui-icon-pin-w { background-position: -128px -144px; }
.ui-icon-pin-s { background-position: -144px -144px; }
.ui-icon-play { background-position: 0 -160px; }
.ui-icon-pause { background-position: -16px -160px; }
.ui-icon-seek-next { background-position: -32px -160px; }
.ui-icon-seek-prev { background-position: -48px -160px; }
.ui-icon-seek-end { background-position: -64px -160px; }
.ui-icon-seek-start { background-position: -80px -160px; }
/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */
.ui-icon-seek-first { background-position: -80px -160px; }
.ui-icon-stop { background-position: -96px -160px; }
.ui-icon-eject { background-position: -112px -160px; }
.ui-icon-volume-off { background-position: -128px -160px; }
.ui-icon-volume-on { background-position: -144px -160px; }
.ui-icon-power { background-position: 0 -176px; }
.ui-icon-signal-diag { background-position: -16px -176px; }
.ui-icon-signal { background-position: -32px -176px; }
.ui-icon-battery-0 { background-position: -48px -176px; }
.ui-icon-battery-1 { background-position: -64px -176px; }
.ui-icon-battery-2 { background-position: -80px -176px; }
.ui-icon-battery-3 { background-position: -96px -176px; }
.ui-icon-circle-plus { background-position: 0 -192px; }
.ui-icon-circle-minus { background-position: -16px -192px; }
.ui-icon-circle-close { background-position: -32px -192px; }
.ui-icon-circle-triangle-e { background-position: -48px -192px; }
.ui-icon-circle-triangle-s { background-position: -64px -192px; }
.ui-icon-circle-triangle-w { background-position: -80px -192px; }
.ui-icon-circle-triangle-n { background-position: -96px -192px; }
.ui-icon-circle-arrow-e { background-position: -112px -192px; }
.ui-icon-circle-arrow-s { background-position: -128px -192px; }
.ui-icon-circle-arrow-w { background-position: -144px -192px; }
.ui-icon-circle-arrow-n { background-position: -160px -192px; }
.ui-icon-circle-zoomin { background-position: -176px -192px; }
.ui-icon-circle-zoomout { background-position: -192px -192px; }
.ui-icon-circle-check { background-position: -208px -192px; }
.ui-icon-circlesmall-plus { background-position: 0 -208px; }
.ui-icon-circlesmall-minus { background-position: -16px -208px; }
.ui-icon-circlesmall-close { background-position: -32px -208px; }
.ui-icon-squaresmall-plus { background-position: -48px -208px; }
.ui-icon-squaresmall-minus { background-position: -64px -208px; }
.ui-icon-squaresmall-close { background-position: -80px -208px; }
.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }
.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }
.ui-icon-grip-solid-vertical { background-position: -32px -224px; }
.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }
.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }
.ui-icon-grip-diagonal-se { background-position: -80px -224px; }
/* Misc visuals
----------------------------------*/
/* Corner radius */
.ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; border-top-left-radius: 4px; }
.ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; border-top-right-radius: 4px; }
.ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; }
.ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; }
.ui-corner-top { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; border-top-left-radius: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; border-top-right-radius: 4px; }
.ui-corner-bottom { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; }
.ui-corner-right { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; border-top-right-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; border-bottom-right-radius: 4px; }
.ui-corner-left { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; border-top-left-radius: 4px; -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; border-bottom-left-radius: 4px; }
.ui-corner-all { -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px; }
/* Overlays */
.ui-widget-overlay { background: #aaaaaa url(../img/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); }
.ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url(../img/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; opacity: .30;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; }/*
* jQuery UI Resizable 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Resizable#theming
*/
.ui-resizable { position: relative;}
.ui-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block;
/* http://bugs.jqueryui.com/ticket/7233
- Resizable: resizable handles fail to work in IE if transparent and content overlaps
*/
background-image:url(data:);
}
.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; }
.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; }
.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; }
.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; }
.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; }
.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; }
.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; }
.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; }
.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}/*
* jQuery UI Selectable 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Selectable#theming
*/
.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; }
/*
* jQuery UI Accordion 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Accordion#theming
*/
/* IE/Win - Fix animation bug - #4615 */
.ui-accordion { width: 100%; }
.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; }
.ui-accordion .ui-accordion-li-fix { display: inline; }
.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; }
.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .5em .5em .5em .7em; }
.ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; }
.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; }
.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; zoom: 1; }
.ui-accordion .ui-accordion-content-active { display: block; }
/*
* jQuery UI Autocomplete 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Autocomplete#theming
*/
.ui-autocomplete { position: absolute; cursor: default; }
/* workarounds */
* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */
/*
* jQuery UI Menu 1.8.12
*
* Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Menu#theming
*/
.ui-menu {
list-style:none;
padding: 2px;
margin: 0;
display:block;
float: left;
}
.ui-menu .ui-menu {
margin-top: -3px;
}
.ui-menu .ui-menu-item {
margin:0;
padding: 0;
zoom: 1;
float: left;
clear: left;
width: 100%;
}
.ui-menu .ui-menu-item a {
text-decoration:none;
display:block;
padding:.2em .4em;
line-height:1.5;
zoom:1;
}
.ui-menu .ui-menu-item a.ui-state-hover,
.ui-menu .ui-menu-item a.ui-state-active {
font-weight: normal;
margin: -1px;
}
/*
* jQuery UI Button 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Button#theming
*/
.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; text-decoration: none !important; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */
.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */
button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */
.ui-button-icons-only { width: 3.4em; }
button.ui-button-icons-only { width: 3.7em; }
/*button text element */
.ui-button .ui-button-text { display: block; line-height: 1.4; }
.ui-button-text-only .ui-button-text { padding: .4em 1em; }
.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; }
.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; }
.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; }
.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; }
/* no icon support for input elements, provide padding by default */
input.ui-button { padding: .4em 1em; }
/*button icon element(s) */
.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; }
.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; }
.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; }
.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; }
.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; }
/*button sets*/
.ui-buttonset { margin-right: 7px; }
.ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; }
/* workarounds */
button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */
/*
* jQuery UI Dialog 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Dialog#theming
*/
.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; }
.ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; }
.ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; }
.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; }
.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; }
.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; }
.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; }
.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width:0; background-image: none; margin: .5em 0 0 0; padding:0;font-size:.7em;}
.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; }
.ui-dialog .ui-dialog-buttonpane button { margin:5px; cursor: pointer; }
.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; }
.ui-draggable .ui-dialog-titlebar { cursor: move; }
/*
* jQuery UI Slider 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Slider#theming
*/
.ui-slider { position: relative; text-align: left; }
.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; }
.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; }
.ui-slider-horizontal { height: .8em; }
.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; }
.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; }
.ui-slider-horizontal .ui-slider-range-min { left: 0; }
.ui-slider-horizontal .ui-slider-range-max { right: 0; }
.ui-slider-vertical { width: .8em; height: 100px; }
.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; }
.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; }
.ui-slider-vertical .ui-slider-range-min { bottom: 0; }
.ui-slider-vertical .ui-slider-range-max { top: 0; }/*
* jQuery UI Tabs 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Tabs#theming
*/
.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */
.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; }
.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 1px; margin: 0 .2em 1px 0; border-bottom: 0 !important; padding: 0; white-space: nowrap; }
.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; }
.ui-tabs .ui-tabs-nav li.ui-tabs-selected { margin-bottom: 0; padding-bottom: 1px; }
.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; }
.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */
.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; }
.ui-tabs .ui-tabs-hide { display: none !important; }
/*
* jQuery UI Datepicker 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Datepicker#theming
*/
.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; }
.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; }
.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; }
.ui-datepicker .ui-datepicker-prev { left:2px; }
.ui-datepicker .ui-datepicker-next { right:2px; }
.ui-datepicker .ui-datepicker-prev-hover { left:1px; }
.ui-datepicker .ui-datepicker-next-hover { right:1px; }
.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; }
.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; }
.ui-datepicker select.ui-datepicker-month-year {width: 100%;}
.ui-datepicker select.ui-datepicker-month,
.ui-datepicker select.ui-datepicker-year { width: 49%;}
.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; }
.ui-datepicker td { border: 0; padding: 1px; }
.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; }
/* with multiple calendars */
.ui-datepicker.ui-datepicker-multi { width:auto; }
.ui-datepicker-multi .ui-datepicker-group { float:left; }
.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; }
.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; }
.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; }
.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; }
.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; }
.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; }
.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; }
.ui-datepicker-row-break { clear:both; width:100%; }
/* RTL support */
.ui-datepicker-rtl { direction: rtl; }
.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; }
.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; }
.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; }
.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; }
.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; }
.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; }
.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; }
.ui-datepicker-rtl .ui-datepicker-group { float:right; }
.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; }
/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */
.ui-datepicker-cover {
display: none; /*sorry for IE5*/
display/**/: block; /*sorry for IE5*/
position: absolute; /*must have*/
z-index: -1; /*must have*/
filter: mask(); /*must have*/
top: -4px; /*must have*/
left: -4px; /*must have*/
width: 200px; /*must have*/
height: 200px; /*must have*/
}/*
* jQuery UI Progressbar 1.8.12
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Progressbar#theming
*/
.ui-progressbar { height:2em; text-align: left; }
.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; }
.jquery-notify-bar {
width:100%;
position:fixed;
top:0;
left:0;
z-index:32768;
background-color:#efefef;
font-size:18px;
color:#929292;
text-align:center;
padding:12px 0px;
border-bottom:1px solid #cacaca;
}
.jquery-notify-bar.error {
color:#f00;
background-color:#fdd;
}
.jquery-notify-bar.success {
color:#060;
background-color:#BBFFB6;
}
.notify-bar-close {
position:absolute;
left:95%;
font-size:11px;
}
<|start_filename|>mapmint-ui/templates/preview/modules/getFeatureCircle/_init.js<|end_filename|>
gfiControlCircle = new OpenLayers.Control();
OpenLayers.Util.extend(gfiControlCircle, {
draw: function () {
// this Handler.Box will intercept the shift-mousedown
// before Control.MouseDefault gets to see it
this.box = new OpenLayers.Handler.RegularPolygon( gfiControlCircle,
{"done": this.notice},
{sides: 40});
this.box.activate();
},
notice: function (bounds) {
var gml = new OpenLayers.Format.GeoJSON;
featureGML=gml.write(new OpenLayers.Feature.Vector(bounds.transform(mercator,wgs84)));
\$('#output-gfi').html("");
for(var i=0;i<queryLayersList.length;i++){
if(queryLayersList[i].visibility){
req=WPSGetHeader("Intersection")+WPSGetInputs([{"name": "InputEntity1","value": featureGML,"mimeType": "application/json"},{"name": "InputEntity2", "xlink:href": msUrl+"?map="+mapPath+"/project_${conf["senv"]["last_map"]}.map&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=ms:"+queryLayersList[i].local_id,"mimeType": "text/xml"}])+WPSGetOutput({"name": "Result","mimeType": "text/xml"})+WPSGetFooter();
var localI=i;
\$.ajax({
localI: i,
type: "GET",
url: zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=mapfile.getInitialInfo&DataInputs=map="+lastMap+";layer="+queryLayersList[i].real_name+"&RawDataOutput=Result",
dataType: 'xml',
complete:function(xml,status){
var tmp=\$(xml.responseXML).find("ows\\:ExceptionText").text();
if(tmp!=""){
alert(tmp);
return;
}
colModel=[];
fields=[];
var localI=this.localI;
if(queryLayersList[this.localI].displayed_fields=="all"){
var nbCol=0;
\$(xml.responseXML).find("field").each(function(){
\$(this).find("id").each(function(){
colModel[nbCol]={display: \$(this).text(), name : \$(this).text(), width: (nbCol==0?80:120), sortable : true, align: 'center'};
fields[nbCol]=\$(this).text();
nbCol++;
});
});
}else{
var tmp=queryLayersList[this.localI].displayed_fields.split(',');
var tmp1=queryLayersList[this.localI].displayed_fields_width.split(',');
var tmp2=queryLayersList[this.localI].displayed_fields_aliases.split(',');
var nbCol=0;
\$(xml.responseXML).find("field").each(function(){
\$(this).find("id").each(function(){
for(var j=0;j<tmp.length;j++)
if(tmp[j]==\$(this).text()){
colModel[nbCol]={display: (tmp2[j]&&tmp2[j]!="all"?tmp2[j]:\$(this).text()), name : \$(this).text(), width: (tmp1[j]?tmp1[j]:120), sortable : false, align: 'center'};
fields[nbCol]=\$(this).text();
nbCol++;
}
});
});
}
\$('#output-gfi').append('<table id="flex'+localI+'" style="display:none"></table>');
try{
var tmpName="#flex"+localI;
\$("#flex"+localI).flexigrid({
autoload: true,
url: msUrl,
ogcProtocol: "WFS",
ogcUrl: zooUrl,
autozoom: false,
dataType: 'xml',
contentType: 'text/xml',
colModel: colModel,
usepager: false,
ltoolbar: true,
id: localI,
fields: fields,
sortname: fields[0],
method: "post",
sortorder: "asc",
dwDataSource: pmapfiles[queryLayersList[localI].real_name][0],
dwLayer: queryLayersList[localI].real_name,
#if $m.web.metadata.get("mmVT")
#set vt=$m.web.metadata.get("mmVT").split(',')
#set nb=len($vt)+1
#set cnt=1
mmVectorOps: (vtLayers[queryLayersList[this.localI].real_name]?[
#if $vt.count("buffer")>0
{"process": "BufferPy","class":"buffer","lib":"Buffer","hasText":true,"unit": "#if $m.web.metadata.get('tuom')=="metric"#m#else##if $m.web.metadata.get('tuom')=="geographic"#°#else#foot#end if##end if#"}#if $cnt <$nb#,#end if#
#set cnt=$cnt+1
#end if
#if $vt.count("spatial-buffer")
#set cnt=$cnt+1
{"process": "BufferMask","class":"spatial-buffer","lib":"Mask"#if $vt.count("buffer")==0#,"hasText":true,"unit": "#if $m.web.metadata.get('tuom')=="metric"#m#else##if $m.web.metadata.get('tuom')=="geographic"#°#else#foot#end if##end if##end if#}#if $cnt<$nb#,#end if#
#end if
#if $vt.count("centroid")
#set cnt=$cnt+1
{"process": "CentroidPy","class":"centroid","lib":"Centroid"}#if $cnt <$nb#,#end if#
#end if
#if $vt.count("boundary")
#set cnt=$cnt+1
{"process": "BoundaryPy","class":"boundary","lib":"Boundary"}#if $cnt<$nb#,#end if#
#end if
#if $vt.count("convexhull")
#set cnt=$cnt+1
{"process": "ConvexHullPy","class":"convexhull","lib":"ConvexHull"}#if $cnt<$nb#,#end if#
#end if
#if $vt.count("spatial-query")
#set cnt=$cnt+1
#set lq=[]
#for ll in range($m.numlayers)
#set lll=$m.getLayer($ll)
#if $lll.metadata.get("mmSpatialQueryType")!="none"
#if $lll.metadata.get("mmSpatialQueryType")=="contained" or $lll.metadata.get("mmSpatialQueryType")=="both"
#set $lq+=[$ll]
#end if
#end if
#end for
#set l=0
#if len($lq)>0
,(svtLayers[queryLayersList[this.localI].real_name]?{"process": "SpatialQuery","class":"spatial-query","lib":"SpatialQuery","hasChoice":[{
#for i in $lq
"value":"$m.getLayer($i).name","text":"#if $m.getLayer($i).metadata.get("ows_title")==""#$m.getLayer($i).name#else#$m.getLayer($i).metadata.get("ows_title")#end if#"
#if $l+1<len($lq)
,
#end if
#set l=$l+1
#end for
}]}:null)
#if cnt<$nb#,#end if#
#end if
#end if
]:null),
#end if
title: queryLayersList[localI].name,
useLimit: false,
noSelection: false,
showTableToggleBtn: true,
width: "100%",
height: 290,
onHide: function(hidden) {
finalLayers[(this.id*4)].setVisibility(!hidden);
finalLayers[(this.id*4)+1].setVisibility(!hidden);
finalLayers[(this.id*4)+2].setVisibility(!hidden);
finalLayers[(this.id*4)+3].setVisibility(!hidden);
},
pparams: req,
tableToggleBtns: [{name: 'zoomToSetExtent',title: 'Zoom to set extent', onclick: function(){
map.zoomToExtent(finalLayers[(this.id.replace(/zoomToSetExtent_/,"")*4)].getDataExtent());
}}]
});
}catch(e){alert(e);}
\$('.dialog-gfi').window({
width: 625,
height: 400,
maximizable:false,
resizable: false,
onClose: function(){
for(var i=0;i<finalLayers.length;i++){
try{
finalLayers[i].removeFeatures(finalLayers[i].features);
}catch(e){}
}
processResultLayer.removeFeatures(processResultLayer.features);
}
});
}
});
}
System.flexi_cnt++;
}
}
});
<|start_filename|>mapmint-ui/new-themes/themes/purple/window.css<|end_filename|>
.panel-tool-close{
background:url('../img/panel_tools-purple.gif') no-repeat -16px 0px;
}
.panel-tool-min{
background:url('../img/panel_tools-purple.gif') no-repeat 0px 0px;
}
.panel-tool-max{
background:url('../img/panel_tools-purple.gif') no-repeat 0px -16px;
}
.panel-tool-restore{
background:url('../img/panel_tools-purple.gif') no-repeat -16px -16px;
}
.panel-tool-collapse{
background:url('../img/panel_tool_collapse-purple.gif') no-repeat;
}
.panel-tool-expand{
background:url('../img/panel_tool_expand-purple.gif') no-repeat;
}
.panel-loading{
padding:11px 0px 10px 30px;
background:url('../img/panel_loading.gif') no-repeat 10px 10px;
}
a.l-btn:hover{
color:#FFFFFF;
text-shadow: #777777 0px 1px 0px;
background: #8340f3; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#c743f8', endColorstr='#8340f3'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#c743f8), to(#8340f3)); /* for webkit browsers */
background: -moz-linear-gradient(top, #c743f8, #8340f3 ); /* for firefox 3.6+ */
}
<|start_filename|>mapmint-ui/new-themes/themes/default/notification.css<|end_filename|>
/*
* MapMint Notification CSS
*/
/*
* Notification Top (red or green)
*/
.jquery-notify-bar {
width:100%;
position:fixed;
top:0;
left:0;
z-index:32768;
background-color:#efefef;
font-size:18px;
color:#929292;
text-align:center;
padding:25px 0px;
height:40px;
border-bottom:1px solid #cacaca;
}
.jquery-notify-bar.error {
color:#f00;
background-color:#fdd;
}
.jquery-notify-bar.success {
color:#060;
background-color:#BBFFB6;
}
.notify-bar-close {
position:absolute;
left:95%;
font-size:11px;
}
/*
* Notification Bottom (growl-like boxes)
*/
.progress_box_call{float:right;height:15px;width:15px;position:relative;
border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px;
top:9px;
right:10px;
background: -moz-linear-gradient(top, #e2e2e2, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E2E2E2', endColorstr='#b6b6b6'); /* for IE */
text-align:center;
font-size:.7em;
}
.progress_box_call:hover{
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F'); /* for IE */
color: #FFFFFF;
cursor:pointer;}
div.jGrowl {
padding: 10px;
z-index: 9999;
color: #fff;
}
/** Special IE6 Style Positioning **/
div.ie6 {
position: absolute;
}
div.ie6.top-right {
right: auto;
bottom: auto;
left: expression( ( 0 - jGrowl.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
top: expression( ( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}
div.ie6.top-left {
left: expression( ( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
top: expression( ( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}
div.ie6.bottom-right {
left: expression( ( 0 - jGrowl.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
top: expression( ( 0 - jGrowl.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}
div.ie6.bottom-left {
left: expression( ( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
top: expression( ( 0 - jGrowl.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
}
div.ie6.center {
left: expression( ( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
top: expression( ( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px' );
width: 100%;
}
/** Normal Style Positions **/
div.jGrowl {
position: absolute;
}
body > div.jGrowl {
position: fixed;
}
div.jGrowl.top-left {
left: 0px;
top: 0px;
}
div.jGrowl.top-right {
right: 0px;
top: 0px;
}
div.jGrowl.bottom-left {
left: 0px;
bottom: 0px;
}
div.jGrowl.bottom-right {
right: 0px;
bottom: 43px;
}
div.jGrowl.center {
top: 0px;
width: 50%;
left: 25%;
}
/** Cross Browser Styling **/
div.center div.jGrowl-notification, div.center div.jGrowl-closer {
margin-left: auto;
margin-right: auto;
}
div.jGrowl div.jGrowl-notification, div.jGrowl div.jGrowl-closer {
background:url(../img/bcknav.png);
zoom: 1;
width: 235px;
padding: 10px;
margin-top: 5px;
margin-bottom: 5px;
font-size: .7em;
text-align: left;
display: none;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
div.jGrowl div.jGrowl-notification {
min-height: 50px;
}
div.jGrowl div.jGrowl-notification div.jGrowl-header {
font-weight: bold;
font-size: .85em;
}
div.jGrowl div.jGrowl-notification div.jGrowl-close {
z-index: 99;
float: right;
font-weight: bold;
font-size: 1em;
cursor: pointer;
}
div.jGrowl div.jGrowl-closer {
padding-top: 4px;
padding-bottom: 4px;
cursor: pointer;
font-size: .8em;
font-weight: bold;
text-align: center;
text-shadow: #FFFFFF 0px 1px 0px;
background: -moz-linear-gradient(top, #e2e2e2, #b6b6b6);
background: -webkit-gradient(linear, left top, left bottom, from(#e2e2e2), to(#b6b6b6));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e2e2e2', endColorstr='#b6b6b6'); /* for IE */
font-weight: normal; color: #333333;}
div.jGrowl div.jGrowl-closer:hover {
text-shadow: #777777 0px 1px 0px;
background: -moz-linear-gradient(top, #C2FF7E , #4FA33F);
background: -webkit-gradient(linear, left top, left bottom, from(#C2FF7E), to(#4FA33F));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C2FF7E', endColorstr='#4FA33F'); /* for IE */
font-weight: normal; color: #FFFFFF;
}
/** Hide jGrowl when printing **/
@media print {
div.jGrowl {
display: none;
}
}
<|start_filename|>mapmint-ui/templates/preview/modules/addLayer/WMSLayers_bs.html<|end_filename|>
#encoding UTF-8
#import zoo
#import mapscript
#import mm_access
#from Cheetah.Template import Template
<div id="wms_layerswitcher">
<ul id="wms_list">
#import glob
#for files in glob.glob($conf["main"]["dataPath"]+"/WMS/*.map"):
#set file=$files.replace($conf["main"]["dataPath"]+"/WMS/","").replace($conf["main"]["dataPath"]+"/WMS\\","").replace("ds_ows.map","")
<li iconCls="tree_group" closed="true" class="list-group-item">
<label class="tree-toggle tree-parent"><span class="fa fa-caret-square-o-down tree-node text-center ud"></span>$file
</label>
#set m=mapscript.mapObj($files)
<ul class="list-group tree">
#for l in range($m.numlayers)
#if $mm_access.checkLayerPriv($conf,$m,$m.getLayer($l).name,"r")
<li id="$m.getLayer($l).name" class="list-group-item layer"><input type="checkbox" id="WMSLayer_$l" value="$(file)"/>$m.getLayer($l).metadata.get('ows_title')</li>
#end if
#end for
</ul>
</li>
#end for
</ul>
</div>
<|start_filename|>mapmint-ui/templates/Tables/Report.html<|end_filename|>
#import zoo
#encoding UTF-8
#import zoo
#import mm_access
#import authenticate.service as auth
#set con=auth.getCon($conf)
#set cur=con.conn.cursor()
#set prefix=auth.getPrefix($conf)
<script type="template/text" id="report_template">
<h3>$zoo._("Table configuration")</h3>
<table id="report_table_display">
<thead>
<tr>
<th style="width:25px"></th>
<th style="width:25px">$zoo._("Name")</th>
<th style="width:25px">$zoo._("Type")</th>
<th style="width:25px">$zoo._("Value")</th>
</tr>
</thead>
<tbody>
[tbody]
</tbody>
</table>
</script>
<script type="template/text" id="report_line_template">
<tr>
<td>
<i class="fa fa-arrows-v"> </i> [id]
<input type="hidden" name="field_id" value="[id]" />
</td>
<td>
[name]
<input name="oname" type="hidden" value="[name]" />
</td>
<td>
<select class="form-control" name="ftype">
#set res=$cur.execute("select id,name from mm_tables.ftypes where ftype='r' order by id")
#set res=$cur.fetchall()
#for i in range(len(res))
<option value="$res[$i][0]">$zoo._($res[$i][1])</option>
#end for
</select>
</td>
<td><textarea class="form-control" name="value">[value]</textarea></td>
</tr>
</script>
#set tmpl=$conf['main']['templatesPath']+"/Distiller/form_line.html"
#include $tmpl
#set ftmpl=$self._CHEETAH__cheetahIncludes[$tmpl]
<div class="form-group">
<label class="col-sm-3 control-label">
$zoo._("Document model")
</label>
<div class="col-sm-9">
<form id="afileUpload" class="col-sm-9" action="$conf["main"]["serverAddress"]?request=Execute&service=WPS&version=1.0.0&Identifier=upload.saveOnServer&dataInputs=file=upload" method="post" enctype="multipart/form-data" target="auploader">
<input type="file" name="file" id="file" class="form-control file" />
<a id="documents_afile_link" href="" target="_blank"></a>
<input type="hidden" id="documents_afilename" class="form-control" />
</form>
$ftmpl.printButton({"id":"import-doc","name":$zoo._("Import"),"classes":"btn-small col-sm-3" })
<iframe name="auploader" id="auploader" style="display:none"></iframe>
</div>
</div>
<div role="tabpanel" class="tab-pane" id="mm_report_table_display">
</div>
<|start_filename|>public_map/css/fonts.css<|end_filename|>
/* MapMint logo icon font */
@font-face {font-family: 'mmFont';src: url('../fonts/mmFont.ttf') format('truetype');font-weight: normal;font-style: normal;}
[class^="iconmm-"],[class*=" iconmm-"] {font-family: 'mmFont', sans-serif;font-weight: normal;font-style: normal;text-decoration: inherit;-webkit-font-smoothing: antialiased;}
.iconmm-logo:before{content: "\e602";color:#83c849;}
/* MetroUI icon font */
@font-face{font-family:'iconFont';src:url(../fonts/iconFont.eot);src:url(../fonts/iconFont.eot?#iefix) format("embedded-opentype"),url(../fonts/iconFont.woff) format("woff"),url(../fonts/iconFont.ttf) format("truetype"),url(../fonts/iconFont.svg#iconFont) format("svg");font-weight:400;font-style:normal}
[data-icon]:before{font-family:'iconFont';content:attr(data-icon);speak:none;font-weight:400;font-variant:normal;text-transform:none;line-height:1;-webkit-font-smoothing:antialiased}
[class*="icon-"]{font-family:'iconFont';speak:none;font-style:normal;font-weight:400!important;font-variant:normal;text-transform:none;text-decoration:inherit;line-height:1;display:inline-block;vertical-align:-8%;-webkit-font-smoothing:antialiased;font-size:inherit}
[class*="icon-"].smaller{font-size:.7em;vertical-align:6%}
[class*="icon-"].large{font-size:1.2em;vertical-align:-10%}
.icon-newspaper:before{content:"\e001"}
.icon-pencil:before{content:"\e002"}
.icon-droplet:before{content:"\e003"}
.icon-pictures:before{content:"\e004"}
.icon-camera:before{content:"\e005"}
.icon-music:before{content:"\e006"}
.icon-film:before{content:"\e007"}
.icon-camera-2:before{content:"\e008"}
.icon-spades:before{content:"\e009"}
.icon-clubs:before{content:"\e00a"}
.icon-diamonds:before{content:"\e00b"}
.icon-broadcast:before{content:"\e00c"}
.icon-mic:before{content:"\e00d"}
.icon-book:before{content:"\e00e"}
.icon-file:before{content:"\e00f"}
.icon-new:before{content:"\e010"}
.icon-copy:before{content:"\e011"}
.icon-folder:before{content:"\e012"}
.icon-folder-2:before{content:"\e013"}
.icon-tag:before{content:"\e014"}
.icon-cart:before{content:"\e015"}
.icon-basket:before{content:"\e016"}
.icon-calculate:before{content:"\e017"}
.icon-support:before{content:"\e018"}
.icon-phone:before{content:"\e019"}
.icon-mail:before{content:"\e01a"}
.icon-location:before{content:"\e01b"}
.icon-compass:before{content:"\e01c"}
.icon-history:before{content:"\e01d"}
.icon-clock:before{content:"\e01e"}
.icon-bell:before{content:"\e01f"}
.icon-calendar:before{content:"\e020"}
.icon-printer:before{content:"\e021"}
.icon-mouse:before{content:"\e022"}
.icon-screen:before{content:"\e023"}
.icon-laptop:before{content:"\e024"}
.icon-mobile:before{content:"\e025"}
.icon-cabinet:before{content:"\e026"}
.icon-drawer:before{content:"\e027"}
.icon-drawer-2:before{content:"\e028"}
.icon-box:before{content:"\e029"}
.icon-box-add:before{content:"\e02a"}
.icon-box-remove:before{content:"\e02b"}
.icon-download:before{content:"\e02c"}
.icon-upload:before{content:"\e02d"}
.icon-database:before{content:"\e02e"}
.icon-flip:before{content:"\e02f"}
.icon-flip-2:before{content:"\e030"}
.icon-undo:before{content:"\e031"}
.icon-redo:before{content:"\e032"}
.icon-forward:before{content:"\e033"}
.icon-reply:before{content:"\e034"}
.icon-reply-2:before{content:"\e035"}
.icon-comments:before{content:"\e036"}
.icon-comments-2:before{content:"\e037"}
.icon-comments-3:before{content:"\e038"}
.icon-comments-4:before{content:"\e039"}
.icon-comments-5:before{content:"\e03a"}
.icon-user:before{content:"\e03b"}
.icon-user-2:before{content:"\e03c"}
.icon-user-3:before{content:"\e03d"}
.icon-busy:before{content:"\e03e"}
.icon-loading:before{content:"\e03f"}
.icon-loading-2:before{content:"\e040"}
.icon-search:before{content:"\e041"}
.icon-zoom-in:before{content:"\e042"}
.icon-zoom-out:before{content:"\e043"}
.icon-key:before{content:"\e044"}
.icon-key-2:before{content:"\e045"}
.icon-locked:before{content:"\e046"}
.icon-unlocked:before{content:"\e047"}
.icon-wrench:before{content:"\e048"}
.icon-equalizer:before{content:"\e049"}
.icon-cog:before{content:"\e04a"}
.icon-pie:before{content:"\e04b"}
.icon-bars:before{content:"\e04c"}
.icon-stats-up:before{content:"\e04d"}
.icon-gift:before{content:"\e04e"}
.icon-trophy:before{content:"\e04f"}
.icon-diamond:before{content:"\e050"}
.icon-coffee:before{content:"\e051"}
.icon-rocket:before{content:"\e052"}
.icon-meter-slow:before{content:"\e053"}
.icon-meter-medium:before{content:"\e054"}
.icon-meter-fast:before{content:"\e055"}
.icon-dashboard:before{content:"\e056"}
.icon-fire:before{content:"\e057"}
.icon-lab:before{content:"\e058"}
.icon-remove:before{content:"\e059"}
.icon-briefcase:before{content:"\e05a"}
.icon-briefcase-2:before{content:"\e05b"}
.icon-cars:before{content:"\e05c"}
.icon-bus:before{content:"\e05d"}
.icon-cube:before{content:"\e05e"}
.icon-cube-2:before{content:"\e05f"}
.icon-puzzle:before{content:"\e060"}
.icon-glasses:before{content:"\e061"}
.icon-glasses-2:before{content:"\e062"}
.icon-accessibility:before{content:"\e063"}
.icon-accessibility-2:before{content:"\e064"}
.icon-target:before{content:"\e065"}
.icon-target-2:before{content:"\e066"}
.icon-lightning:before{content:"\e067"}
.icon-power:before{content:"\e068"}
.icon-power-2:before{content:"\e069"}
.icon-clipboard:before{content:"\e06a"}
.icon-clipboard-2:before{content:"\e06b"}
.icon-playlist:before{content:"\e06c"}
.icon-grid-view:before{content:"\e06d"}
.icon-tree-view:before{content:"\e06e"}
.icon-cloud:before{content:"\e06f"}
.icon-cloud-2:before{content:"\e070"}
.icon-download-2:before{content:"\e071"}
.icon-upload-2:before{content:"\e072"}
.icon-upload-3:before{content:"\e073"}
.icon-link:before{content:"\e074"}
.icon-link-2:before{content:"\e075"}
.icon-flag:before{content:"\e076"}
.icon-flag-2:before{content:"\e077"}
.icon-attachment:before{content:"\e078"}
.icon-eye:before{content:"\e079"}
.icon-bookmark:before{content:"\e07a"}
.icon-bookmark-2:before{content:"\e07b"}
.icon-star:before{content:"\e07c"}
.icon-star-2:before{content:"\e07d"}
.icon-star-3:before{content:"\e07e"}
.icon-heart:before{content:"\e07f"}
.icon-heart-2:before{content:"\e080"}
.icon-thumbs-up:before{content:"\e081"}
.icon-thumbs-down:before{content:"\e082"}
.icon-plus:before{content:"\e083"}
.icon-minus:before{content:"\e084"}
.icon-help:before{content:"\e085"}
.icon-help-2:before{content:"\e086"}
.icon-blocked:before{content:"\e087"}
.icon-cancel:before{content:"\e088"}
.icon-cancel-2:before{content:"\e089"}
.icon-checkmark:before{content:"\e08a"}
.icon-minus-2:before{content:"\e08b"}
.icon-plus-2:before{content:"\e08c"}
.icon-enter:before{content:"\e08d"}
.icon-exit:before{content:"\e08e"}
.icon-loop:before{content:"\e08f"}
.icon-arrow-up-left:before{content:"\e090"}
.icon-arrow-up:before{content:"\e091"}
.icon-arrow-up-right:before{content:"\e092"}
.icon-arrow-right:before{content:"\e093"}
.icon-arrow-down-right:before{content:"\e094"}
.icon-arrow-down:before{content:"\e095"}
.icon-arrow-down-left:before{content:"\e096"}
.icon-arrow-left:before{content:"\e097"}
.icon-arrow-up-2:before{content:"\e098"}
.icon-arrow-right-2:before{content:"\e099"}
.icon-arrow-down-2:before{content:"\e09a"}
.icon-arrow-left-2:before{content:"\e09b"}
.icon-arrow-up-3:before{content:"\e09c"}
.icon-arrow-right-3:before{content:"\e09d"}
.icon-arrow-down-3:before{content:"\e09e"}
.icon-arrow-left-3:before{content:"\e09f"}
.icon-menu:before{content:"\e0a0"}
.icon-enter-2:before{content:"\e0a1"}
.icon-backspace:before{content:"\e0a2"}
.icon-backspace-2:before{content:"\e0a3"}
.icon-tab:before{content:"\e0a4"}
.icon-tab-2:before{content:"\e0a5"}
.icon-checkbox:before{content:"\e0a6"}
.icon-checkbox-unchecked:before{content:"\e0a7"}
.icon-checkbox-partial:before{content:"\e0a8"}
.icon-radio-checked:before{content:"\e0a9"}
.icon-radio-unchecked:before{content:"\e0aa"}
.icon-font:before{content:"\e0ab"}
.icon-paragraph-left:before{content:"\e0ac"}
.icon-paragraph-center:before{content:"\e0ad"}
.icon-paragraph-right:before{content:"\e0ae"}
.icon-paragraph-justify:before{content:"\e0af"}
.icon-left-to-right:before{content:"\e0b0"}
.icon-right-to-left:before{content:"\e0b1"}
.icon-share:before{content:"\e0b2"}
.icon-new-tab:before{content:"\e0b3"}
.icon-new-tab-2:before{content:"\e0b4"}
.icon-embed:before{content:"\e0b5"}
.icon-code:before{content:"\e0b6"}
.icon-bluetooth:before{content:"\e0b7"}
.icon-share-2:before{content:"\e0b8"}
.icon-share-3:before{content:"\e0b9"}
.icon-mail-2:before{content:"\e0ba"}
.icon-google:before{content:"\e0bb"}
.icon-google-plus:before{content:"\e0bc"}
.icon-google-drive:before{content:"\e0bd"}
.icon-facebook:before{content:"\e0be"}
.icon-instagram:before{content:"\e0bf"}
.icon-twitter:before{content:"\e0c0"}
.icon-feed:before{content:"\e0c1"}
.icon-youtube:before{content:"\e0c2"}
.icon-vimeo:before{content:"\e0c3"}
.icon-flickr:before{content:"\e0c4"}
.icon-picassa:before{content:"\e0c5"}
.icon-dribbble:before{content:"\e0c6"}
.icon-deviantart:before{content:"\e0c7"}
.icon-github:before{content:"\e0c8"}
.icon-github-2:before{content:"\e0c9"}
.icon-github-3:before{content:"\e0ca"}
.icon-github-4:before{content:"\e0cb"}
.icon-github-5:before{content:"\e0cc"}
.icon-git:before{content:"\e0cd"}
.icon-github-6:before{content:"\e0ce"}
.icon-wordpress:before{content:"\e0cf"}
.icon-joomla:before{content:"\e0d0"}
.icon-blogger:before{content:"\e0d1"}
.icon-tumblr:before{content:"\e0d2"}
.icon-yahoo:before{content:"\e0d3"}
.icon-amazon:before{content:"\e0d4"}
.icon-tux:before{content:"\e0d5"}
.icon-apple:before{content:"\e0d6"}
.icon-finder:before{content:"\e0d7"}
.icon-android:before{content:"\e0d8"}
.icon-windows:before{content:"\e0d9"}
.icon-soundcloud:before{content:"\e0da"}
.icon-skype:before{content:"\e0db"}
.icon-reddit:before{content:"\e0dc"}
.icon-linkedin:before{content:"\e0dd"}
.icon-lastfm:before{content:"\e0de"}
.icon-delicious:before{content:"\e0df"}
.icon-stumbleupon:before{content:"\e0e0"}
.icon-pinterest:before{content:"\e0e1"}
.icon-xing:before{content:"\e0e2"}
.icon-flattr:before{content:"\e0e3"}
.icon-foursquare:before{content:"\e0e4"}
.icon-paypal:before{content:"\e0e5"}
.icon-yelp:before{content:"\e0e6"}
.icon-libreoffice:before{content:"\e0e7"}
.icon-file-pdf:before{content:"\e0e8"}
.icon-file-openoffice:before{content:"\e0e9"}
.icon-file-word:before{content:"\e0ea"}
.icon-file-excel:before{content:"\e0eb"}
.icon-file-powerpoint:before{content:"\e0ec"}
.icon-file-zip:before{content:"\e0ed"}
.icon-file-xml:before{content:"\e0ee"}
.icon-file-css:before{content:"\e0ef"}
.icon-html5:before{content:"\e0f0"}
.icon-html5-2:before{content:"\e0f1"}
.icon-css3:before{content:"\e0f2"}
.icon-chrome:before{content:"\e0f3"}
.icon-firefox:before{content:"\e0f4"}
.icon-IE:before{content:"\e0f5"}
.icon-opera:before{content:"\e0f6"}
.icon-safari:before{content:"\e0f7"}
.icon-IcoMoon:before{content:"\e0f8"}
.icon-sunrise:before{content:"\e0f9"}
.icon-sun:before{content:"\e0fa"}
.icon-moon:before{content:"\e0fb"}
.icon-sun-2:before{content:"\e0fc"}
.icon-windy:before{content:"\e0fd"}
.icon-wind:before{content:"\e0fe"}
.icon-snowflake:before{content:"\e0ff"}
.icon-cloudy:before{content:"\e100"}
.icon-cloud-3:before{content:"\e101"}
.icon-weather:before{content:"\e102"}
.icon-weather-2:before{content:"\e103"}
.icon-weather-3:before{content:"\e104"}
.icon-lines:before{content:"\e105"}
.icon-cloud-4:before{content:"\e106"}
.icon-lightning-2:before{content:"\e107"}
.icon-lightning-3:before{content:"\e108"}
.icon-rainy:before{content:"\e109"}
.icon-rainy-2:before{content:"\e10a"}
.icon-windy-2:before{content:"\e10b"}
.icon-windy-3:before{content:"\e10c"}
.icon-snowy:before{content:"\e10d"}
.icon-snowy-2:before{content:"\e10e"}
.icon-snowy-3:before{content:"\e10f"}
.icon-weather-4:before{content:"\e110"}
.icon-cloudy-2:before{content:"\e111"}
.icon-cloud-5:before{content:"\e112"}
.icon-lightning-4:before{content:"\e113"}
.icon-sun-3:before{content:"\e114"}
.icon-moon-2:before{content:"\e115"}
.icon-cloudy-3:before{content:"\e116"}
.icon-cloud-6:before{content:"\e117"}
.icon-cloud-7:before{content:"\e118"}
.icon-lightning-5:before{content:"\e119"}
.icon-rainy-3:before{content:"\e11a"}
.icon-rainy-4:before{content:"\e11b"}
.icon-windy-4:before{content:"\e11c"}
.icon-windy-5:before{content:"\e11d"}
.icon-snowy-4:before{content:"\e11e"}
.icon-snowy-5:before{content:"\e11f"}
.icon-weather-5:before{content:"\e120"}
.icon-cloudy-4:before{content:"\e121"}
.icon-lightning-6:before{content:"\e122"}
.icon-thermometer:before{content:"\e123"}
.icon-compass-2:before{content:"\e124"}
.icon-none:before{content:"\e125"}
.icon-Celsius:before{content:"\e126"}
.icon-Fahrenheit:before{content:"\e127"}
.icon-forrst:before{content:"\e128"}
.icon-headphones:before{content:"\e129"}
.icon-bug:before{content:"\e12a"}
.icon-cart-2:before{content:"\e12b"}
.icon-earth:before{content:"\e12c"}
.icon-battery:before{content:"\e12d"}
.icon-list:before{content:"\e12e"}
.icon-grid:before{content:"\e12f"}
.icon-alarm:before{content:"\e130"}
.icon-location-2:before{content:"\e131"}
.icon-pointer:before{content:"\e132"}
.icon-diary:before{content:"\e133"}
.icon-eye-2:before{content:"\e134"}
.icon-console:before{content:"\e135"}
.icon-location-3:before{content:"\e136"}
.icon-move:before{content:"\e137"}
.icon-gift-2:before{content:"\e138"}
.icon-monitor:before{content:"\e139"}
.icon-mobile-2:before{content:"\e13a"}
.icon-switch:before{content:"\e13b"}
.icon-star-4:before{content:"\e13c"}
.icon-address-book:before{content:"\e13d"}
.icon-shit:before{content:"\e13e"}
.icon-cone:before{content:"\e13f"}
.icon-credit-card:before{content:"\e140"}
.icon-type:before{content:"\e141"}
.icon-volume:before{content:"\e142"}
.icon-volume-2:before{content:"\e143"}
.icon-locked-2:before{content:"\e144"}
.icon-warning:before{content:"\e145"}
.icon-info:before{content:"\e146"}
.icon-filter:before{content:"\e147"}
.icon-bookmark-3:before{content:"\e148"}
.icon-bookmark-4:before{content:"\e149"}
.icon-stats:before{content:"\e14a"}
.icon-compass-3:before{content:"\e14b"}
.icon-keyboard:before{content:"\e14c"}
.icon-award-fill:before{content:"\e14d"}
.icon-award-stroke:before{content:"\e14e"}
.icon-beaker-alt:before{content:"\e14f"}
.icon-beaker:before{content:"\e150"}
.icon-move-vertical:before{content:"\e151"}
.icon-move-horizontal:before{content:"\e152"}
.icon-steering-wheel:before{content:"\e153"}
.icon-volume-3:before{content:"\e154"}
.icon-volume-mute:before{content:"\e155"}
.icon-play:before{content:"\e156"}
.icon-pause:before{content:"\e157"}
.icon-stop:before{content:"\e158"}
.icon-eject:before{content:"\e159"}
.icon-first:before{content:"\e15a"}
.icon-last:before{content:"\e15b"}
.icon-play-alt:before{content:"\e15c"}
.icon-battery-charging:before{content:"\e160"}
.icon-left-quote:before{content:"\e161"}
.icon-right-quote:before{content:"\e162"}
.icon-left-quote-alt:before{content:"\e163"}
.icon-right-quote-alt:before{content:"\e164"}
.icon-smiley:before{content:"\e165"}
.icon-umbrella:before{content:"\e166"}
.icon-info-2:before{content:"\e167"}
.icon-chart-alt:before{content:"\e168"}
.icon-at:before{content:"\e169"}
.icon-hash:before{content:"\e16a"}
.icon-pilcrow:before{content:"\e16b"}
.icon-fullscreen-alt:before{content:"\e16c"}
.icon-fullscreen-exit-alt:before{content:"\e16d"}
.icon-layers-alt:before{content:"\e16e"}
.icon-layers:before{content:"\e16f"}
.icon-floppy:before{content:"\e170"}
.icon-rainbow:before{content:"\e000"}
.icon-air:before{content:"\e171"}
.icon-home:before{content:"\e172"}
.icon-spin:before{content:"\e173"}
.icon-auction:before{content:"\e174"}
.icon-dollar:before{content:"\e175"}
.icon-dollar-2:before{content:"\e176"}
.icon-coins:before{content:"\e177"}
.icon-file-2:before{content:"\e186"}
.icon-file-3:before{content:"\e187"}
.icon-file-4:before{content:"\e188"}
.icon-files:before{content:"\e189"}
.icon-phone-2:before{content:"\e18a"}
.icon-tablet:before{content:"\e18b"}
.icon-monitor-2:before{content:"\e18c"}
.icon-window:before{content:"\e18d"}
.icon-tv:before{content:"\e18e"}
.icon-camera-3:before{content:"\e18f"}
.icon-image:before{content:"\e190"}
.icon-open:before{content:"\e191"}
.icon-sale:before{content:"\e192"}
.icon-direction:before{content:"\e193"}
.icon-medal:before{content:"\e194"}
.icon-medal-2:before{content:"\e195"}
.icon-satellite:before{content:"\e196"}
.icon-discout:before{content:"\e197"}
.icon-barcode:before{content:"\e198"}
.icon-ticket:before{content:"\e199"}
.icon-shipping:before{content:"\e19a"}
.icon-globe:before{content:"\e19b"}
.icon-anchor:before{content:"\e19c"}
.icon-pop-out:before{content:"\e19d"}
.icon-pop-in:before{content:"\e19e"}
.icon-resize:before{content:"\e178"}
.icon-battery-2:before{content:"\e179"}
.icon-battery-3:before{content:"\e17a"}
.icon-battery-4:before{content:"\e17b"}
.icon-battery-5:before{content:"\e17c"}
.icon-tools:before{content:"\e17d"}
.icon-alarm-2:before{content:"\e17e"}
.icon-alarm-cancel:before{content:"\e17f"}
.icon-alarm-clock:before{content:"\e180"}
.icon-chronometer:before{content:"\e181"}
.icon-ruler:before{content:"\e182"}
.icon-lamp:before{content:"\e183"}
.icon-lamp-2:before{content:"\e184"}
.icon-scissors:before{content:"\e185"}
.icon-volume-4:before{content:"\e19f"}
.icon-volume-5:before{content:"\e1a0"}
.icon-volume-6:before{content:"\e1a1"}
.icon-battery-full:before{content:"\e15f"}
.icon-battery-empty:before{content:"\e15d"}
.icon-battery-half:before{content:"\e15e"}
.icon-zip:before{content:"\e1a2"}
.icon-zip-2:before{content:"\e1a3"}
.icon-play-2:before{content:"\e1a4"}
.icon-pause-2:before{content:"\e1a5"}
.icon-record:before{content:"\e1a6"}
.icon-stop-2:before{content:"\e1a7"}
.icon-next:before{content:"\e1a8"}
.icon-previous:before{content:"\e1a9"}
.icon-first-2:before{content:"\e1aa"}
.icon-last-2:before{content:"\e1ab"}
.icon-arrow-left-4:before{content:"\e1ac"}
.icon-arrow-down-4:before{content:"\e1ad"}
.icon-arrow-up-4:before{content:"\e1ae"}
.icon-arrow-right-4:before{content:"\e1af"}
.icon-arrow-left-5:before{content:"\e1b0"}
.icon-arrow-down-5:before{content:"\e1b1"}
.icon-arrow-up-5:before{content:"\e1b2"}
.icon-arrow-right-5:before{content:"\e1b3"}
.icon-cc:before{content:"\e1b4"}
.icon-cc-by:before{content:"\e1b5"}
.icon-cc-nc:before{content:"\e1b6"}
.icon-cc-nc-eu:before{content:"\e1b7"}
.icon-cc-nc-jp:before{content:"\e1b8"}
.icon-cc-sa:before{content:"\e1b9"}
.icon-cc-nd:before{content:"\e1ba"}
.icon-cc-pd:before{content:"\e1bb"}
.icon-cc-zero:before{content:"\e1bc"}
.icon-cc-share:before{content:"\e1bd"}
.icon-cc-share-2:before{content:"\e1be"}
.icon-cycle:before{content:"\e1bf"}
.icon-stop-3:before{content:"\e1c0"}
.icon-stats-2:before{content:"\e1c1"}
.icon-stats-3:before{content:"\e1c2"}
/* Glyphicons icons font */
@font-face {font-family:'Glyphicons Halflings';src:url('../fonts/glyphicons-halflings-regular.eot');src:url('../fonts/glyphicons-halflings-regular-.eot#iefix') format('embedded-opentype'),url('../fonts/glyphicons-halflings-regular.woff') format('woff'),url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg')}
.glyphicon {position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
.glyphicon-asterisk:before {content:"\2a"}
.glyphicon-plus:before {content:"\2b"}
.glyphicon-euro:before {content:"\20ac"}
.glyphicon-minus:before {content:"\2212"}
.glyphicon-cloud:before {content:"\2601"}
.glyphicon-envelope:before {content:"\2709"}
.glyphicon-pencil:before {content:"\270f"}
.glyphicon-glass:before {content:"\e001"}
.glyphicon-music:before {content:"\e002"}
.glyphicon-search:before {content:"\e003"}
.glyphicon-heart:before {content:"\e005"}
.glyphicon-star:before {content:"\e006"}
.glyphicon-star-empty:before {content:"\e007"}
.glyphicon-user:before {content:"\e008"}
.glyphicon-film:before {content:"\e009"}
.glyphicon-th-large:before {content:"\e010"}
.glyphicon-th:before {content:"\e011"}
.glyphicon-th-list:before {content:"\e012"}
.glyphicon-ok:before {content:"\e013"}
.glyphicon-remove:before {content:"\e014"}
.glyphicon-zoom-in:before {content:"\e015"}
.glyphicon-zoom-out:before {content:"\e016"}
.glyphicon-off:before {content:"\e017"}
.glyphicon-signal:before {content:"\e018"}
.glyphicon-cog:before {content:"\e019"}
.glyphicon-trash:before {content:"\e020"}
.glyphicon-home:before {content:"\e021"}
.glyphicon-file:before {content:"\e022"}
.glyphicon-time:before {content:"\e023"}
.glyphicon-road:before {content:"\e024"}
.glyphicon-download-alt:before {content:"\e025"}
.glyphicon-download:before {content:"\e026"}
.glyphicon-upload:before {content:"\e027"}
.glyphicon-inbox:before {content:"\e028"}
.glyphicon-play-circle:before {content:"\e029"}
.glyphicon-repeat:before {content:"\e030"}
.glyphicon-refresh:before {content:"\e031"}
.glyphicon-list-alt:before {content:"\e032"}
.glyphicon-lock:before {content:"\e033"}
.glyphicon-flag:before {content:"\e034"}
.glyphicon-headphones:before {content:"\e035"}
.glyphicon-volume-off:before {content:"\e036"}
.glyphicon-volume-down:before {content:"\e037"}
.glyphicon-volume-up:before {content:"\e038"}
.glyphicon-qrcode:before {content:"\e039"}
.glyphicon-barcode:before {content:"\e040"}
.glyphicon-tag:before {content:"\e041"}
.glyphicon-tags:before {content:"\e042"}
.glyphicon-book:before {content:"\e043"}
.glyphicon-bookmark:before {content:"\e044"}
.glyphicon-print:before {content:"\e045"}
.glyphicon-camera:before {content:"\e046"}
.glyphicon-font:before {content:"\e047"}
.glyphicon-bold:before {content:"\e048"}
.glyphicon-italic:before {content:"\e049"}
.glyphicon-text-height:before {content:"\e050"}
.glyphicon-text-width:before {content:"\e051"}
.glyphicon-align-left:before {content:"\e052"}
.glyphicon-align-center:before {content:"\e053"}
.glyphicon-align-right:before {content:"\e054"}
.glyphicon-align-justify:before {content:"\e055"}
.glyphicon-list:before {content:"\e056"}
.glyphicon-indent-left:before {content:"\e057"}
.glyphicon-indent-right:before {content:"\e058"}
.glyphicon-facetime-video:before {content:"\e059"}
.glyphicon-picture:before {content:"\e060"}
.glyphicon-map-marker:before {content:"\e062"}
.glyphicon-adjust:before {content:"\e063"}
.glyphicon-tint:before {content:"\e064"}
.glyphicon-edit:before {content:"\e065"}
.glyphicon-share:before {content:"\e066"}
.glyphicon-check:before {content:"\e067"}
.glyphicon-move:before {content:"\e068"}
.glyphicon-step-backward:before {content:"\e069"}
.glyphicon-fast-backward:before {content:"\e070"}
.glyphicon-backward:before {content:"\e071"}
.glyphicon-play:before {content:"\e072"}
.glyphicon-pause:before {content:"\e073"}
.glyphicon-stop:before {content:"\e074"}
.glyphicon-forward:before {content:"\e075"}
.glyphicon-fast-forward:before {content:"\e076"}
.glyphicon-step-forward:before {content:"\e077"}
.glyphicon-eject:before {content:"\e078"}
.glyphicon-chevron-left:before {content:"\e079"}
.glyphicon-chevron-right:before {content:"\e080"}
.glyphicon-plus-sign:before {content:"\e081"}
.glyphicon-minus-sign:before {content:"\e082"}
.glyphicon-remove-sign:before {content:"\e083"}
.glyphicon-ok-sign:before {content:"\e084"}
.glyphicon-question-sign:before {content:"\e085"}
.glyphicon-info-sign:before {content:"\e086"}
.glyphicon-screenshot:before {content:"\e087"}
.glyphicon-remove-circle:before {content:"\e088"}
.glyphicon-ok-circle:before {content:"\e089"}
.glyphicon-ban-circle:before {content:"\e090"}
.glyphicon-arrow-left:before {content:"\e091"}
.glyphicon-arrow-right:before {content:"\e092"}
.glyphicon-arrow-up:before {content:"\e093"}
.glyphicon-arrow-down:before {content:"\e094"}
.glyphicon-share-alt:before {content:"\e095"}
.glyphicon-resize-full:before {content:"\e096"}
.glyphicon-resize-small:before {content:"\e097"}
.glyphicon-exclamation-sign:before {content:"\e101"}
.glyphicon-gift:before {content:"\e102"}
.glyphicon-leaf:before {content:"\e103"}
.glyphicon-fire:before {content:"\e104"}
.glyphicon-eye-open:before {content:"\e105"}
.glyphicon-eye-close:before {content:"\e106"}
.glyphicon-warning-sign:before {content:"\e107"}
.glyphicon-plane:before {content:"\e108"}
.glyphicon-calendar:before {content:"\e109"}
.glyphicon-random:before {content:"\e110"}
.glyphicon-comment:before {content:"\e111"}
.glyphicon-magnet:before {content:"\e112"}
.glyphicon-chevron-up:before {content:"\e113"}
.glyphicon-chevron-down:before {content:"\e114"}
.glyphicon-retweet:before {content:"\e115"}
.glyphicon-shopping-cart:before {content:"\e116"}
.glyphicon-folder-close:before {content:"\e117"}
.glyphicon-folder-open:before {content:"\e118"}
.glyphicon-resize-vertical:before {content:"\e119"}
.glyphicon-resize-horizontal:before {content:"\e120"}
.glyphicon-hdd:before {content:"\e121"}
.glyphicon-bullhorn:before {content:"\e122"}
.glyphicon-bell:before {content:"\e123"}
.glyphicon-certificate:before {content:"\e124"}
.glyphicon-thumbs-up:before {content:"\e125"}
.glyphicon-thumbs-down:before {content:"\e126"}
.glyphicon-hand-right:before {content:"\e127"}
.glyphicon-hand-left:before {content:"\e128"}
.glyphicon-hand-up:before {content:"\e129"}
.glyphicon-hand-down:before {content:"\e130"}
.glyphicon-circle-arrow-right:before {content:"\e131"}
.glyphicon-circle-arrow-left:before {content:"\e132"}
.glyphicon-circle-arrow-up:before {content:"\e133"}
.glyphicon-circle-arrow-down:before {content:"\e134"}
.glyphicon-globe:before {content:"\e135"}
.glyphicon-wrench:before {content:"\e136"}
.glyphicon-tasks:before {content:"\e137"}
.glyphicon-filter:before {content:"\e138"}
.glyphicon-briefcase:before {content:"\e139"}
.glyphicon-fullscreen:before {content:"\e140"}
.glyphicon-dashboard:before {content:"\e141"}
.glyphicon-paperclip:before {content:"\e142"}
.glyphicon-heart-empty:before {content:"\e143"}
.glyphicon-link:before {content:"\e144"}
.glyphicon-phone:before {content:"\e145"}
.glyphicon-pushpin:before {content:"\e146"}
.glyphicon-usd:before {content:"\e148"}
.glyphicon-gbp:before {content:"\e149"}
.glyphicon-sort:before {content:"\e150"}
.glyphicon-sort-by-alphabet:before {content:"\e151"}
.glyphicon-sort-by-alphabet-alt:before {content:"\e152"}
.glyphicon-sort-by-order:before {content:"\e153"}
.glyphicon-sort-by-order-alt:before {content:"\e154"}
.glyphicon-sort-by-attributes:before {content:"\e155"}
.glyphicon-sort-by-attributes-alt:before {content:"\e156"}
.glyphicon-unchecked:before {content:"\e157"}
.glyphicon-expand:before {content:"\e158"}
.glyphicon-collapse-down:before {content:"\e159"}
.glyphicon-collapse-up:before {content:"\e160"}
.glyphicon-log-in:before {content:"\e161"}
.glyphicon-flash:before {content:"\e162"}
.glyphicon-log-out:before {content:"\e163"}
.glyphicon-new-window:before {content:"\e164"}
.glyphicon-record:before {content:"\e165"}
.glyphicon-save:before {content:"\e166"}
.glyphicon-open:before {content:"\e167"}
.glyphicon-saved:before {content:"\e168"}
.glyphicon-import:before {content:"\e169"}
.glyphicon-export:before {content:"\e170"}
.glyphicon-send:before {content:"\e171"}
.glyphicon-floppy-disk:before {content:"\e172"}
.glyphicon-floppy-saved:before {content:"\e173"}
.glyphicon-floppy-remove:before {content:"\e174"}
.glyphicon-floppy-save:before {content:"\e175"}
.glyphicon-floppy-open:before {content:"\e176"}
.glyphicon-credit-card:before {content:"\e177"}
.glyphicon-transfer:before {content:"\e178"}
.glyphicon-cutlery:before {content:"\e179"}
.glyphicon-header:before {content:"\e180"}
.glyphicon-compressed:before {content:"\e181"}
.glyphicon-earphone:before {content:"\e182"}
.glyphicon-phone-alt:before {content:"\e183"}
.glyphicon-tower:before {content:"\e184"}
.glyphicon-stats:before {content:"\e185"}
.glyphicon-sd-video:before {content:"\e186"}
.glyphicon-hd-video:before {content:"\e187"}
.glyphicon-subtitles:before {content:"\e188"}
.glyphicon-sound-stereo:before {content:"\e189"}
.glyphicon-sound-dolby:before {content:"\e190"}
.glyphicon-sound-5-1:before {content:"\e191"}
.glyphicon-sound-6-1:before {content:"\e192"}
.glyphicon-sound-7-1:before {content:"\e193"}
.glyphicon-copyright-mark:before {content:"\e194"}
.glyphicon-registration-mark:before {content:"\e195"}
.glyphicon-cloud-download:before {content:"\e197"}
.glyphicon-cloud-upload:before {content:"\e198"}
.glyphicon-tree-conifer:before {content:"\e199"}
.glyphicon-tree-deciduous:before {content:"\e200"}
/* Additional custom icon font */
@font-face {font-family:'icon';src:url('../fonts/icon.eot');src:url('../fonts/icon-.eot#iefix') format('embedded-opentype'),url('../fonts/icon.ttf') format('truetype'),url('../fonts/icon.woff') format('woff'),url('../fonts/icon.svg#icon') format('svg');font-weight:normal;font-style:normal}
.i {display:inline-block;font-family:'icon';font-style:normal;font-weight:normal;line-height:1;vertical-align:-5%;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
.i-move:before {content:"\e600"}
.i-move-vertical:before {content:"\e601"}
.i-resize-enlarge:before {content:"\e602"}
.i-resize-shrink:before {content:"\e603"}
.i-move-horizontal:before {content:"\e604"}
.i-download:before {content:"\e605"}
.i-upload:before {content:"\e606"}
.i-cloud-download:before {content:"\e607"}
.i-cloud-upload:before {content:"\e608"}
.i-circleleft:before {content:"\e609"}
.i-circledown:before {content:"\e60a"}
.i-circleup:before {content:"\e60b"}
.i-circleright:before {content:"\e60c"}
.i-home:before {content:"\e60d"}
.i-download3:before {content:"\e60e"}
.i-pin:before {content:"\e60f"}
.i-pictures:before {content:"\e610"}
.i-share3:before {content:"\e611"}
.i-pencil2:before {content:"\e612"}
.i-mail2:before {content:"\e613"}
.i-support:before {content:"\e614"}
.i-asc:before {content:"\e615"}
.i-dsc:before {content:"\e616"}
.i-ok:before {content:"\e617"}
.i-error:before {content:"\e618"}
.i-expand:before {content:"\e619"}
.i-collapse:before {content:"\e61a"}
.i-screen:before {content:"\e61b"}
.i-phone3:before {content:"\e61c"}
.i-phone-portrait:before {content:"\e61d"}
.i-phone-landscape:before {content:"\e61e"}
.i-tablet:before {content:"\e61f"}
.i-tablet-landscape:before {content:"\e620"}
.i-laptop:before {content:"\e621"}
.i-cube:before {content:"\e622"}
.i-chart:before {content:"\e623"}
.i-graph:before {content:"\e624"}
.i-meter:before {content:"\e625"}
.i-heart2:before {content:"\e626"}
.i-star2:before {content:"\e627"}
.i-stack:before {content:"\e628"}
.i-tv:before {content:"\e629"}
.i-user2:before {content:"\e62a"}
.i-users2:before {content:"\e62b"}
.i-search2:before {content:"\e62c"}
.i-zoom-in2:before {content:"\e62d"}
.i-zoom-out2:before {content:"\e62e"}
.i-slider-v:before {content:"\e62f"}
.i-slider:before {content:"\e630"}
.i-stats:before {content:"\e631"}
.i-bars:before {content:"\e632"}
.i-arrow-up-left2:before {content:"\e633"}
.i-arrow-up2:before {content:"\e634"}
.i-arrow-up-right2:before {content:"\e635"}
.i-arrow-right2:before {content:"\e636"}
.i-arrow-down-right2:before {content:"\e637"}
.i-arrow-down-2:before {content:"\e638"}
.i-arrow-down-left-2:before {content:"\e639"}
.i-arrow-left2:before {content:"\e63a"}
.i-file-pdf:before {content:"\e63b"}
.i-file-openoffice:before {content:"\e63c"}
.i-file-word:before {content:"\e63d"}
.i-file-excel:before {content:"\e63e"}
.i-file-zip:before {content:"\e63f"}
.i-file-powerpoint:before {content:"\e640"}
.i-file-xml:before {content:"\e641"}
.i-file-css:before {content:"\e642"}
.i-video:before {content:"\e643"}
.i-settings:before {content:"\e644"}
.i-camera:before {content:"\e645"}
.i-tag:before {content:"\e646"}
.i-bulb:before {content:"\e647"}
.i-location:before {content:"\e648"}
.i-eye2:before {content:"\e649"}
.i-bubble:before {content:"\e64a"}
.i-mail:before {content:"\e64b"}
.i-paperplane:before {content:"\e64c"}
.i-data:before {content:"\e64d"}
.i-t-shirt:before {content:"\e64e"}
.i-lab:before {content:"\e64f"}
.i-calendar:before {content:"\e650"}
.i-earth:before {content:"\e651"}
.i-world:before {content:"\e652"}
.i-vynil:before {content:"\e653"}
.i-gauge:before {content:"\e654"}
.i-statistics:before {content:"\e655"}
.i-arrow-left3:before {content:"\e656"}
.i-arrow-down3:before {content:"\e657"}
.i-arrow-up3:before {content:"\e658"}
.i-arrow-right3:before {content:"\e659"}
.i-arrow-left4:before {content:"\e65a"}
.i-arrow-down4:before {content:"\e65b"}
.i-arrow-up4:before {content:"\e65c"}
.i-arrow-right4:before {content:"\e65d"}
.i-arrow-left5:before {content:"\e65e"}
.i-arrow-down5:before {content:"\e65f"}
.i-arrow-up5:before {content:"\e660"}
.i-arrow-right5:before {content:"\e661"}
.i-search:before {content:"\e662"}
.i-list:before {content:"\e663"}
.i-add-to-list:before {content:"\e664"}
.i-list2:before {content:"\e665"}
.i-play:before {content:"\e666"}
.i-pause:before {content:"\e667"}
.i-stop:before {content:"\e668"}
.i-backward:before {content:"\e669"}
.i-forward:before {content:"\e66a"}
.i-feed:before {content:"\e66b"}
.i-switch:before {content:"\e66c"}
.i-clock2:before {content:"\e66d"}
.i-health:before {content:"\e66e"}
.i-pencil:before {content:"\e66f"}
.i-minus2:before {content:"\e670"}
.i-plus2:before {content:"\e671"}
.i-stats:before {content:"\e672"}
.i-paperclip:before {content:"\e673"}
.i-keyboard:before {content:"\e674"}
.i-mic:before {content:"\e675"}
.i-heart:before {content:"\e676"}
.i-layout3:before {content:"\e677"}
.i-layout2:before {content:"\e678"}
.i-cloud:before {content:"\e679"}
.i-info:before {content:"\e67a"}
.i-question:before {content:"\e67b"}
.i-notification:before {content:"\e67c"}
.i-libreoffice:before {content:"\e67d"}
.i-headphones:before {content:"\e67e"}
.i-copy2:before {content:"\e67f"}
.i-copy3:before {content:"\e680"}
.i-paste:before {content:"\e681"}
.i-spinner:before {content:"\e682"}
.i-plus:before {content:"\e683"}
.i-minus:before {content:"\e684"}
.i-cancel:before {content:"\e685"}
.i-images:before {content:"\e686"}
.i-logout:before {content:"\e687"}
.i-login:before {content:"\e688"}
.i-infinity:before {content:"\e689"}
.i-docs:before {content:"\e68a"}
.i-landscape:before {content:"\e68b"}
.i-portrait:before {content:"\e68c"}
.i-share:before {content:"\e68d"}
.i-youtube:before {content:"\e68e"}
.i-checkmark:before {content:"\e68f"}
.i-notice:before {content:"\e690"}
.i-link:before {content:"\e691"}
.i-link2:before {content:"\e692"}
.i-popup:before {content:"\e693"}
.i-publish:before {content:"\e694"}
.i-browser:before {content:"\e695"}
.i-checkmark2:before {content:"\e696"}
.i-cross2:before {content:"\e697"}
.i-question2:before {content:"\e698"}
.i-info2:before {content:"\e699"}
.i-loop:before {content:"\e69a"}
.i-retweet:before {content:"\e69b"}
.i-arrow:before {content:"\e69c"}
.i-arrow2:before {content:"\e69d"}
.i-shuffle:before {content:"\e69e"}
.i-ccw:before {content:"\e69f"}
.i-cycle:before {content:"\e6a0"}
.i-cw:before {content:"\e6a1"}
.i-switch:before {content:"\e6a2"}
.i-back:before {content:"\e6a3"}
.i-layout:before {content:"\e6a4"}
.i-code:before {content:"\e6a5"}
.i-vcard:before {content:"\e6a6"}
.i-googleplus:before {content:"\e6a7"}
.i-facebook:before {content:"\e6a8"}
.i-twitter:before {content:"\e6a9"}
.i-rss:before {content:"\e6aa"}
.i-signal:before {content:"\e6ab"}
.i-flow-tree:before {content:"\e6ac"}
.i-domain3:before {content:"\e6ad"}
.i-trashcan:before {content:"\e6ae"}
.i-book:before {content:"\e6af"}
.i-bars:before {content:"\e6b0"}
.i-stopwatch:before {content:"\e6b1"}
.i-map2:before {content:"\e6b2"}
.i-checkmark3:before {content:"\e6b3"}
.i-sun:before {content:"\e6b4"}
.i-clip:before {content:"\e6b5"}
.i-study:before {content:"\e6b6"}
.i-music:before {content:"\e6b7"}
.i-params:before {content:"\e6b8"}
.i-stack3:before {content:"\e6b9"}
.i-arrow-down:before {content:"\e6ba"}
.i-arrow-down-left:before {content:"\e6bb"}
.i-arrow-down-right:before {content:"\e6bc"}
.i-arrow-left:before {content:"\e6bd"}
.i-arrow-right:before {content:"\e6be"}
.i-arrow-up-right:before {content:"\e6bf"}
.i-arrow-up:before {content:"\e6c0"}
.i-arrow-up-left:before {content:"\e6c1"}
.i-compass:before {content:"\e6c2"}
.i-users3:before {content:"\e6c3"}
.i-user3:before {content:"\e6c4"}
.i-camera2:before {content:"\e6c5"}
.i-file:before {content:"\e6c6"}
.i-file2:before {content:"\e6c7"}
.i-file-plus:before {content:"\e6c8"}
.i-file-minus:before {content:"\e6c9"}
.i-file-check:before {content:"\e6ca"}
.i-file-remove:before {content:"\e6cb"}
.i-file-copy:before {content:"\e6cc"}
.i-stack2:before {content:"\e6cd"}
.i-folder:before {content:"\e6ce"}
.i-folder-upload:before {content:"\e6cf"}
.i-folder-download:before {content:"\e6d0"}
.i-folder-minus:before {content:"\e6d1"}
.i-folder-plus:before {content:"\e6d2"}
.i-folder2:before {content:"\e6d3"}
.i-folder-open:before {content:"\e6d4"}
.i-tag2:before {content:"\e6d5"}
.i-cart:before {content:"\e6d6"}
.i-phone:before {content:"\e6d7"}
.i-phone2:before {content:"\e6d8"}
.i-local:before {content:"\e6d9"}
.i-alarm:before {content:"\e6da"}
.i-clock:before {content:"\e6db"}
.i-history:before {content:"\e6dc"}
.i-stopclock:before {content:"\e6dd"}
.i-rotate:before {content:"\e6de"}
.i-rotate2:before {content:"\e6df"}
.i-redo:before {content:"\e6e0"}
.i-undo:before {content:"\e6e1"}
.i-chat2:before {content:"\e6e2"}
.i-chat3:before {content:"\e6e3"}
.i-chat:before {content:"\e6e4"}
.i-data2:before {content:"\e6e5"}
.i-spin:before {content:"\e6e6"}
.i-health2:before {content:"\e6e7"}
.i-cog2:before {content:"\e6e8"}
.i-bulb:before {content:"\e6e9"}
.i-rating:before {content:"\e6ea"}
.i-rating2:before {content:"\e6eb"}
.i-rating3:before {content:"\e6ec"}
.i-grid:before {content:"\e6ed"}
.i-grid2:before {content:"\e6ee"}
.i-grid3:before {content:"\e6ef"}
.i-ellipsis:before {content:"\e6f0"}
.i-dot:before {content:"\e6f1"}
.i-dots:before {content:"\e6f2"}
.i-bar:before {content:"\e6f3"}
.i-bar2:before {content:"\e6f4"}
.i-bars3:before {content:"\e6f5"}
.i-menu:before {content:"\e6f6"}
.i-menu2:before {content:"\e6f7"}
.i-download2:before {content:"\e6f8"}
.i-upload2:before {content:"\e6f9"}
.i-eye:before {content:"\e6fa"}
.i-eye-slash:before {content:"\e6fb"}
.i-bookmark:before {content:"\e6fc"}
.i-up:before {content:"\e6fd"}
.i-right:before {content:"\e6fe"}
.i-down:before {content:"\e6ff"}
.i-left:before {content:"\e700"}
.i-check:before {content:"\e701"}
.i-checked:before {content:"\e702"}
.i-popout:before {content:"\e703"}
.i-newtab:before {content:"\e704"}
.i-map:before {content:"\e705"}
.i-layer:before {content:"\e706"}
.i-layer2:before {content:"\e707"}
.i-like:before {content:"\e708"}
.i-dislike:before {content:"\e709"}
.i-football:before {content:"\e70a"}
.i-hexagon-o:before {content:"\e70b"}
.i-hexagon:before {content:"\e70c"}
.i-hexagon2-o:before {content:"\e70d"}
.i-hexagon2:before {content:"\e70e"}
.i-circle:before {content:"\e70f"}
.i-circle-o:before {content:"\e711"}
.i-circle-sm:before {content:"\e710"}
.i-circle-sm-o:before {content:"\e712"}
<|start_filename|>mapmint-ui/css/style.css<|end_filename|>
body {
font: 11px Verdana, Arial, Helvetica, sans-serif;
background: #ffffff url(../images/main-bg2.png);
padding: 0;
margin: 0;
}
img {
border: none;
}
fieldset{position:absolute;top:0;left:0;margin:0;padding:0;width:100%;border:0;background:#E7E7E7;}
form{margin:0;padding:0;}
select{margin:0 auto;padding:0;width:50%;margin-bottom:5px;margin-right:5px;font-size:1em;}
dl, dt {margin:0;padding:0;}
dd {margin:0;padding:5px;font-size:.9em;}
label {display:block;margin:0;padding:5px;font-size:.9em;}
h1{
margin:0;padding:5px;background: #d1d1d1; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#a1a1a1'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#a1a1a1)); /* for webkit browsers */
background: -moz-linear-gradient(top, #ebebeb, #a1a1a1); /* for firefox 3.6+ */
;font-size:1.1em;font-weight:normal;text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
.close{width:17px;height:16px;background:url(../images/close-sidebar.png);float:right;}
.close:hover{width:17px;height:16px;background:url(../images/close-sidebar-hover.png);float:right;}
/*Main Layout*/
.ui-layout-pane { /* all 'panes' */
background: #FFF;
border: 1px solid #BBB;
padding: 10px;
overflow: auto;
}
.ui-layout-resizer, { /* all 'resizer-bars' */
background: transparent;
}
.ui-layout-toggler { /* all 'toggler-buttons' */
background: #AAA;
}
.ui-layout-north{
overflow:hidden;
background:#565656 url(../images/mapmint-logo.png) no-repeat;
border:0;
margin:0;
padding:0;
height:50px;
max-height:50px;
}
.ui-layout-south{
overflow:hidden;
background:#565656;
border:0;
margin:0;
padding:0;
min-height:50px;
}
.ui-layout-west{
overflow:hidden;
border:0;
margin:0;
padding:0;
}
.ui-layout-center{
border:0;
margin:0;
padding:0;
}
.ui-layout-subcenter{
width:100%;
height:91%;
border:0;
margin:0;
padding:0;
}
.middle-center{
margin:0;
padding:0;
}
.middle-south{
margin:0;
padding:0;
border:0;
background:#E7E7E7;
}
.toolbar{background:#a1a1a1;width:100%;height:30px;}
.fg-button {outline:0;width:24px;height:24px;margin:0 4px;margin-bottom:0; padding: 4px 8px; text-decoration:none !important; cursor:pointer; position: relative; text-align: center; zoom: 1;}
.fg-button2 {outline:0;width:24px;height:16px;margin:0 4px;margin-bottom:0; padding: 4px 8px; text-decoration:none !important; cursor:normal; position: relative; text-align: center; zoom: 1;}
a.fg-button { float:left;}
button.fg-button { width:auto; overflow:visible; }
.fg-button-icon-left { padding-left: 0; }
.fg-button-icon-right { padding-right: 0; }
.fg-button-icon-left .ui-icon { right: auto; left: 0 margin-left: 0; }
.fg-button-icon-right .ui-icon { left: auto; right: 0; margin-left: 0; }
.fg-button-icon-solo { display:block; width:8px; text-indent: -9999px; } /* solo icon buttons must have block properties for the text-indent to work */
.fg-buttonset { float:left;margin-right: 1.5em; }
.fg-buttonset .fg-button { float: left; }
.fg-buttonset-single .fg-button,
.fg-buttonset-multi .fg-button { margin-right: -1px;}
.db {background-image:url(../images/add-layer-pg.png) !important;}
.dir {background-image:url(../images/dir.png) !important;}
.add-layer-vector {background-image:url(../images/add-layer-vector.png) !important;}
.add-layer-raster {background-image:url(../images/add-layer-raster.png) !important;}
.add-layer-wfs {background-image:url(../images/add-layer-wfs.png) !important;}
.add-layer-wms {background-image:url(../images/add-layer-wms.png) !important;}
.add-layer-wcs {background-image:url(../images/add-layer-wcs.png) !important;}
.get-layer-info {background-image:url(../images/get-layer-info.png) !important;}
.export-layer {background-image:url(../images/export-layer.png) !important;}
.delete-layer {background-image:url(../images/delete-layer.png) !important;}
.maincfg1 {background-image:url(../images/main-config-server-icon.png) !important;}
.maincfg2 {background-image:url(../images/main-config-people-icon.png) !important;}
.separator{display:inline;width:24px;height:24px;}
.buttform{float:right;margin-right:15px;}
.buttcheck{float:left;width:80%;margin-left:10px;}
.buttcheck label{font-size:0.9em;position:relative;top:-5px;left:0;color:#636363;}
.formz {width:100%;margin:10px;font-size:1em;cell-spacing:10px;}
.formz td {color:#636363;}
.formz td.small {font-weight:normal;color:#636363;}
.footer{width:100%;height:50px;background:#000000;position:absolute;bottom:0;left:0;}
#nav {
position:relative;
top:7px;
left:295px;
margin: 0;
padding: 5px 4px 0;
line-height: 100%;
background: transparent;
border:0;
height:50px;
font-size:1.1em;
}
#nav li {
margin: 0 5px;
padding: 0 0 8px;
float: left;
position: relative;
list-style: none;
}
/* main level link */
#nav a {
font-weight: normal;
color: #e7e5e5;
text-decoration: none;
display: block;
padding: 8px 20px;
margin: 0;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
text-shadow: 0 1px 1px rgba(0, 0, 0, .3);
}
/* main level link hover */
#nav .current a {
background: #d1d1d1; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#a1a1a1'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#a1a1a1)); /* for webkit browsers */
background: -moz-linear-gradient(top, #ebebeb, #a1a1a1); /* for firefox 3.6+ */
color: #333333;
border-top: solid 1px #f8f8f8;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
#nav .datawarehousenav a, #nav .dashboard a {
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */
color: #FFFFFF;
border-top: solid 1px #4bbf30;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(0, 0, 0, .8);
}
#nav .datawarehousenav a:hover, #nav .dashboard a:hover {
color: #FFFFFF;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(0, 0, 0, .8);
}
#nav li.datawarehousenav:hover > a, #nav li.dashboard:hover > a {
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */
border-top: solid 1px #4bbf30;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(0,0,0, .8);
}
#nav li:hover > a {
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */
border-top: solid 1px #4bbf30;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
/* sub levels link hover */
#nav ul li:hover a, #nav li:hover li a {
background: none;
border: none;
color: #666;
-webkit-box-shadow: none;
-moz-box-shadow: none;
}
/* level 2 list */
#nav ul {
background: #ddd; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#cfcfcf'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#cfcfcf)); /* for webkit browsers */
background: -moz-linear-gradient(top, #ffffff, #cfcfcf); /* for firefox 3.6+ */
display: none;
margin: 0;
padding: 0;
width: 185px;
position: absolute;
top: 38px;
left: 0;
border: solid 1px #b4b4b4;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
}
/* dropdown */
#nav li:hover > ul {
display: block;
}
#nav ul li {
float: none;
margin: 0;
padding: 0;
}
#nav ul a {
font-weight: normal;
text-shadow: 0 1px 1px rgba(255, 255, 255, .9);
}
/* level 3+ list */
#nav ul ul {
left: 181px;
top: -3px;
}
/* rounded corners for first and last child */
#nav ul li:first-child > a, #nav ul.orange li:first-child > a, #nav ul.purple li:first-child > a {
-webkit-border-top-left-radius: 9px;
-moz-border-radius-topleft: 9px;
-webkit-border-top-right-radius: 9px;
-moz-border-radius-topright: 9px;
}
#nav ul li:last-child > a, #nav ul.orange li:last-child > a, #nav ul.purple li:last-child > a {
-webkit-border-bottom-left-radius: 9px;
-moz-border-radius-bottomleft: 9px;
-webkit-border-bottom-right-radius: 9px;
-moz-border-radius-bottomright: 9px;
}
/* clearfix */
#nav:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#nav {
display: inline-block;
}
html[xmlns] #nav {
display: block;
}
* html #nav {
height: 1%;
}
p.top{margin:0;padding:5px;background:transparent;border:none;color:#333333;}
.maincfg{position:relative;}
h2.module{
margin:0;padding:0;background:transparent;
font-size:1.3em;font-weight:normal;text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
position:relative;top:15px;left:70px;
}
h3.submodule{
margin:0;padding:0;background:transparent;
;font-size:1.1em;font-weight:normal;color:#333333;
position:relative;top:17px;left:70px;
}
#first{background:#E7E7E7;}
#second{background:#E7E7E7;}
.datawarehouse {width:100%;height:60px;margin:0;padding:0;border-bottom:1px solid #bababa;background: #E7E7E7 url(../images/datawarehouse-icon.png) no-repeat;background-position:3px 3px;}
.hover {background: #7dff26}
.layermanager {width:100%;height:60px;margin:0;padding:0;border-bottom:1px solid #bababa;background:#E7E7E7 url(../images/layermanager-icon.png) no-repeat;background-position:3px 3px;}
.printpublisher {width:100%;height:60px;margin:0;padding:0;border-bottom:1px solid #bababa;background:#E7E7E7 url(../images/printpublisher-icon.png) no-repeat;background-position:3px 3px;}
.webpublisher {width:100%;height:60px;margin:0;padding:0;border-bottom:1px solid #bababa;background:#E7E7E7 url(../images/webpublisher-icon.png) no-repeat;background-position:3px 3px;}
.documentation {width:100%;height:60px;margin:0;padding:0;border-bottom:1px solid #bababa;background:#E7E7E7 url(../images/documentation-icon.png) no-repeat;background-position:3px 3px;}
.datawarehouse h2, .layermanager h2, .printpublisher h2, .webpublisher h2, .documentation h2{
float:left;margin:0;padding:10px 0 0 70px;background:transparent;
;font-size:1.2em;font-weight:normal;text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
.datawarehouse h3, .layermanager h3, .printpublisher h3, .webpublisher h3, .documentation h3{
float:left;position:absolute;margin:0;padding:30px 0 0 70px;background:transparent;font-size:1.1em;font-weight:normal;color:#333333;
}
.start-stop{float:right;position:relative;top:15px;right:10px;}
.colorpicker{width:100%;background:#E7E7E7;}
.theme-bar{width:100%;height:40px;}
.green{
float:left;
width:24px;
height:24px;
margin:10px 5px 0 10px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.blue{
float:left;
width:24px;
height:24px;
margin:10px 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #44d0e5, #398ee4 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.purple{
float:left;
width:24px;
height:24px;
margin:10px 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #c743f8, #8340f3 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.pink{
float:left;
width:24px;
height:24px;
margin:10px 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
<|start_filename|>mapmint-ui/templates/Georeferencer/Georeference_bs.html<|end_filename|>
#import zoo
<li class="col-xs-12">
<label for="trans">$zoo._("Transformation type:")</label>
</li>
<li class="col-xs-12">
<select id="trans" name="trans">
<option value="1">$zoo._("Polynomial one")</option>
<option value="2">$zoo._("Polynomial two")</option>
<option value="3">$zoo._("Polynomial three")</option>
<option value="tps">$zoo._("Thin Plate Spline")</option>
</select>
</li>
<li class="col-xs-12">
<label for="resample">$zoo._("Resampling method:")</label>
<select id="resample" name="r">
<option value="near">$zoo._("Nearest Neighbour")</option>
<option value="bilinear">$zoo._("Bilinear")</option>
<option value="cubic">$zoo._("Cubic")</option>
<option value="cubicspline">$zoo._("Cubic Spline")</option>
<option value="lanczos">$zoo._("Lanczos")</option>
</select>
</li>
<li class="col-xs-12">
<label for="comp">$zoo._("Compression:")</label>
</li>
<li class="col-xs-12">
<select id="comp" name="COMPRESSION">
#for i in ["NONE","LZW","PACKBITS","JPEG","CCITTRLE","CCITTFAX3","CCITTFAX4","DEFLATE"]
<option value="$i">$i</option>
#end for
</select>
</li>
<li class="col-xs-12">
<label for="diro">$zoo._("Datastore:")</label>
</li>
<li class="col-xs-12">
#import datastores.service as ds
#import mapfile.service as ms
#set outputs={"Result":{"value":""}}
#set tt=ds.list($conf,$inputs,$outputs)
#set elements=eval($outputs["Result"]["value"])
<select id="diro" name="dst">
#for ij in $elements
#if $ij!="WFS" and $ij!="WMS" and $ij!="PostGIS"
<option disabled="true" style="font-weight: bold;color: #111">$ij</option>
#for jk in $elements[$ij]
<option>$jk.name</option>
#end for
#end if
#end for
</select>
</li>
<li class="col-xs-12">
<label for="fileo">$zoo._("Raster filename:")</label>
</li>
<li class="col-xs-12">
<input type="text" id="fileo" name="dso" value=""/>
</li>
<li class="col-xs-12">
<fieldset>
<legend>$zoo._("Set target resolution") <input type="checkbox" id="resolution" onclick="if(this.checked)\$('#reso').show();else \$('#reso').hide()" /></legend>
<div id="reso" style="display: none;">
<div>
<label for="th">$zoo._("Horizontal:")</label>
<input type="text" id="th" value=""/>
</div>
<div>
<label for="tv">$zoo._("Vertical:")</label>
<input type="text" id="tv" value=""/>
</div>
</div>
</fieldset>
</li>
<li class="col-xs-12">
<button class="btn btn-default" onclick="try{app.georeferenceImage();}catch(e){alert(e);}return false;">
$zoo._("Run")
</button>
<i class="fa fa-spinner fa-spin hide"> </i>
</li>
<|start_filename|>mapmint-ui/css/error.css<|end_filename|>
html{height: 100%;}
body{
padding:0;
margin:0;
font-family:Lucida Grande, Trebuchet MS, arial, verdana;
height:100%;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF',endColorstr='#a1d954');
background: -webkit-gradient(linear,left top,left bottom,from(#FFFFFF),to(#a1d954));
background: -moz-linear-gradient(top,#FFFFFF,#a1d954);
}
#container{
position:absolute;
height:200px;
width:400px;
margin:-100px 0px 0px -200px;
top: 40%;
left: 50%;
background:url(../img/error-logo.png) no-repeat;
text-align: center;
border-radius: 10px;
-webkit-border-radius:10px;
-moz-border-radius:10px;
}
a{outline:0;}
#error-box {
position:relative;
margin:90px 0 0 0;
width: 400px;
height:170px;
background:transparent;
}
#error-box p {
font-size:.9em;
color:#7A7A7A;
text-shadow:#FFFFFF 0 1px 0;
}
#projects-box {
position:relative;
margin:90px 0 0 0;
width: 400px;
height:auto;
min-height:170px;
background:transparent;
}
#projects-box p {
font-size:.9em;
color:#7A7A7A;
text-shadow:#FFFFFF 0 1px 0;
}
#projects-box ul {
list-style:none;
}
#projects-box ul li {
font-size:.9em;
padding: 0 0 10px 0;
display:inline;
}
#projects-box ul li a {
color:#707070;
background:transparent;
padding:5px;
text-decoration:none;
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
behavior: url(ie-css3.htc);
display:inline;
}
#projects-box ul li a:hover {
color:#333333;
background:#FFFFFF;
padding:5px;
text-decoration:none;
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
behavior: url(ie-css3.htc);
}
.butt{
width:40%;
min-width:40%;
margin:0 30% 0 30%;
color:#333333;
outline: 0;
position:relative;
top:20px;
left:0;
font-size:0.8em;
font-weight:bold;
padding: 5px 10px 5px 10px;
text-decoration:none !important;
cursor:pointer;
text-align: center;
border:1px solid #B8B8B8;
background:#E9E9E9;
background: -webkit-gradient(linear,left top,left bottom,from(#FFFFFF),to(#B8B8B8));
background: -moz-linear-gradient(top,#FFFFFF,#B8B8B8);
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
behavior: url(ie-css3.htc);
}
.butt:hover{
color:#333333;
outline: 0;
position:relative;
top:20px;
left:0;
font-size:0.8em;
font-weight:bold;
padding: 5px 10px 5px 10px;
text-decoration:none !important;
cursor:pointer;
text-align: center;
border:1px solid #91C960;
background:#8edc07;
background: -webkit-gradient(linear,left top,left bottom,from(#FFFFFF),to(#a1d954));
background: -moz-linear-gradient(top,#FFFFFF,#a1d954); }
ul.links{list-style:none;position: relative; top:50px;
text-align: center; }
ul.links li{display:inline;padding:0 ;}
ul.links li a{font-size:.8em;color:#777777;text-decoration:none;text-shadow:#FFFFFF 0 1px 0;padding:5px 10px 5px 10px;}
ul.links li a:hover{color:#333333;}
ul.credits{
list-style:none;
display:block;
position:fixed;
bottom:0;
text-align:center;
width:100%;
margin:0;
padding:10px 0 10px 0;
margin:0;
background:#a1d954;filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF',endColorstr='#cacaca');background: -webkit-gradient(linear,left top,left bottom,from(#FFFFFF),to(#cacaca));background: -moz-linear-gradient(top,#FFFFFF,#cacaca);border-top:1px solid #cacaca;
}
ul.credits li{display:inline;padding:0;margin:0;font-size:.8em;color:#808080;text-decoration:none;}
ul.credits li a{font-size:1em;color:#808080;text-decoration:none;padding:0 10px 0 0;}
ul.credits li a:hover{text-decoration:underline;color:#62AC47;}
<|start_filename|>mapmint-ui/new-themes/themes/blue/forms.css<|end_filename|>
ul.style-tabs-nav1 li a.selected,
ul.style-tabs-nav1 li a:hover, a.classify:hover {
color:#FFFFFF;position:relative;top:1px;left:0px;text-shadow:#333333 0 1px 0;
background: #8340f3; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#c743f8', endColorstr='#8340f3'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#c743f8), to(#8340f3)); /* for webkit browsers */
background: -moz-linear-gradient(top, #c743f8, #8340f3 ); /* for firefox 3.6+ */
}
ul.style-tabs-nav li a.selected,
ul.style-tabs-nav li a:hover, a.classify:hover {
color:#FFFFFF;position:relative;top:1px;left:0px;text-shadow:#333333 0 1px 0;
background: -moz-linear-gradient(top, #7fe5f9 , #3d93df);
background: -webkit-gradient(linear, left top, left bottom, from(#7fe5f9), to(#3d93df));
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#7fe5f9', endColorstr='#3d93df'); /* for IE */
}
.customfile-hover .customfile-button, .customfile-focus .customfile-button { color:#111; background: #17b9f5; border-color:#FFFFFF;padding: .3em .6em;}
<|start_filename|>mapmint-ui/new-themes/themes/purple/body.css<|end_filename|>
p.credits a:hover{text-decoration:underline;color:#c926ff;}
<|start_filename|>mapmint-ui/templates/preview/modules/routing/ddview.html<|end_filename|>
#encoding UTF-8
#import zoo
#set cnt=0
<form>
<ul data-role="listview" data-inset="true" data-theme="d" data-dividertheme="c" id="routingDDForm">
#for i in ["start"]
<li data-role="fieldcontain">
<fieldset class="ui-grid-a">
<a href="#" data-role="button" onclick="routingForm(\$('#${i}Type').val());;" class="ui-block-d" data-icon="${i}Point">#if cnt==0#$zoo._("Start")#else#$zoo._("Target")#end if#</a>
<select id="${i}Type" class="ui-block-d" onchange="routingForm(\$(this).val(),'#ddPage');">
<option value="geocodingPage">$zoo._("Search")</option>
<option value="mapPage">$zoo._("On the map")</option>
<option value="mapPage">$zoo._("Use my position")</option>
</select>
</fieldset>
</li>
#set cnt=$cnt+1
#end for
<li data-role="fieldcontain">
<fieldset class="ui-grid-a">
<label for="dd_distance">$zoo._("Distance:")</label>
<input type="text" id="dd_distance" value="" length="10" />
</fieldset>
</li>
</ul>
<a href="#" data-role="button" onclick="drivingDistance(points_layer);" data-icon="search"></span>$zoo._("Search")</a>
</form>
<|start_filename|>mapmint-ui/templates/preview/modules/profile/init.js<|end_filename|>
#import zoo
var points_layers1=false;
function loadProfile(){
var json=new OpenLayers.Format.JSON();
tmp=json.read(arguments[0]);
coord=tmp["coordinates"];
var values=[];
var j=0;
sspoints=[];
for(i=0;i<coord.length;i++){
{
if(coord[i][2]>=0)
values[j]=coord[i][2];
else
values[j]=0;
sspoints[j]=[coord[i][0],coord[i][1]];
j+=1;
}
}
var lonlat = arguments[1].getBounds().getCenterLonLat();
var pixels= this.map.getPixelFromLonLat(new OpenLayers.LonLat(lonlat.lon, lonlat.lat));
#if $m.web.metadata.get('layout_t')=="mobile"
\$("<div class='ui-loader ui-overlay-shadow ui-body-d ui-corner-all'><h1>"+out+"</h1></div>").css({ "z-index": 10000, "display": "block", "opacity": 0.96, "top": \$(window).scrollTop() + 100 })
.appendTo( \$("#map") )
.delay( 1500 )
.fadeOut( 400, function(){
\$(this).remove();
if(mapControls.line.active){
mapControls.line.deactivate();
toggleControl({"name":"line"});
}else{
mapControls.polygon.deactivate();
toggleControl({"name":"polygon"});
}
});
#else
\$(".dialog-profile").dialog({
autoOpen: false,
height: 430,
width: 500,
position: [pixels.x,pixels.y],
resizable: false,
onClose: function(event, ui) {
if(points_layer1.features.length>0)
points_layer1.removeFeatures(points_layer1.features);
mapControls["profile_line"].handler.destroyPersistedFeature();
}
});
\$(".output-profile").css({"height": "340px"});
\$(".dialog-profile").dialog("open");
#end if
if(points_layers1==false){
points_layer1 = new OpenLayers.Layer.Vector("points1");
points_layer1.styleMap=new OpenLayers.StyleMap({pointRadius: 4, fillColor: "#3E576F",
fillOpacity: 0.8, strokeColor: "white"});
map.addLayers([points_layer1]);
}
Highcharts.setOptions({
lang: {
resetZoomTitle: "$zoo._("Reset to initial zoom level")",
resetZoom: "$zoo._("Reset zoom")"
}
});
var chart = new Highcharts.Chart({
chart: {
zoomType: 'x',
renderTo: 'output-profile'
},
title: {
text: "$zoo._('Elevation profile')"
},
xAxis: {
labels: {
formatter: function(){
var tmp=this.value+"";
return tmp;
/*if(tmp.indexOf('.')!=0)
if(distances[tmp])
return parseDistance(Math.round(distances[tmp]*111120));*/
}
},
title: { text: 'Points' },
maxZoom: 0
},
yAxis: {
//max: mmax*2,
title: { text: null },
startOnTick: false,
showFirstLabel: false
},
legend: {
enabled: false
},
plotOptions: {
area: {
cursor: 'pointer',
point: {
events: {
click: function() {
if(\$("#profileZoomOnMap").is(':checked'))
map.zoomToExtent(System.curExtent);
if(!points_layers1){
points_layer1 = new OpenLayers.Layer.Vector("points1");
points_layer1.styleMap=new OpenLayers.StyleMap();
map.addLayers([points_layer1]);
}
if(points_layer1.features.length>0)
points_layer1.removeFeatures(points_layer1.features);
var tmp=new OpenLayers.Geometry.Point(sspoints[this.x][0],sspoints[this.x][1]);
tmp.transform(wgs84,mercator);
points_layer1.removeFeatures(points_layer1.features);
points_layer1.addFeatures([new OpenLayers.Feature.Vector(tmp,null,null)]);
}
}
},
fillColor: {
linearGradient: [0, 0, 0, 300],
stops: [
[0, '#74B042'],
[1, 'rgba(255,255,255,0)']
]
},
lineWidth: 1,
marker: {
enabled: false,
states: {
hover: {
enabled: true,
radius: 3
}
}
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
}
}
},
tooltip: {
formatter: function() {
if(points_layer1.features.length>0)
points_layer1.removeFeatures(points_layer1.features);
var tmp=new OpenLayers.Geometry.Point(sspoints[this.x][0],sspoints[this.x][1]);
tmp.transform(wgs84,mercator);
points_layer1.removeFeatures(points_layer1.features);
points_layer1.addFeatures([new OpenLayers.Feature.Vector(tmp,null,null)]);
return '<h1>$zoo._("Altitude: ")'+Highcharts.numberFormat(this.y, 0)+"</h1>";
}
},
series: [{
name: '$zoo._('Elevation')',
type: 'area',
data: values
}]
});
}
function handleProfile(event) {
var geometry = event.geometry;
var units = event.units;
var order = event.order;
var measure = event.measure;
var lonlat = geometry.getBounds().getCenterLonLat();
var pixels= this.map.getPixelFromLonLat(new OpenLayers.LonLat(lonlat.lon, lonlat.lat));
var geojson=new OpenLayers.Format.GeoJSON();
var params=[];
var params0=[{name: "tmpl",value:"public/project_js",dataType: "string"}];
for(i in pmapfiles){
if(pmapfiles[i][pmapfiles[i].length-1]!=-1){
params[params.length]={name: "RasterFile",value:pmapfiles[i][pmapfiles[i].length-1],dataType: "string"};
params0[params0.length]={name: "layer",value:i,dataType: "string"};
//alert(i+" "+pmapfiles[i][pmapfiles[i].length-1]);
}
}
params0[params0.length]={name: "geometry",value: geojson.write(event.geometry.transform(mercator,wgs84),false),mimeType: "application/json"};
data=WPSGetHeader("template.display")+WPSGetInputs(params0)+WPSGetOutput({name:"Result"})+WPSGetFooter();
params[params.length]={name: "Geometry","xlink:href": zooUrl, "method":"POST","headers":[{"key":"Content-Type","value":"text/xml"},{"key":"Cookie","value":"MMID=$conf["senv"]["MMID"]"}], "body": "<wps:Body>"+data+"</wps:Body>", mimeType: "application/json"};
data=WPSGetHeader("raster-tools.GdalExtractProfile")+WPSGetInputs(params)+WPSGetOutput({name:"Profile"})+WPSGetFooter();
params0[0]["value"]="public/project_inv_js";
params0[params0.length-1]={name: "geometry","xlink:href": zooUrl, "method":"POST","headers":[{"key":"Content-Type","value":"text/xml"},{"key":"Cookie","value":"MMID=$conf["senv"]["MMID"]"}], "body": "<wps:Body>"+data+"</wps:Body>",mimeType: "application/json"};
data=WPSGetHeader("template.display")+WPSGetInputs(params0)+WPSGetOutput({name:"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
//urlContext = xml.responseText;
loadProfile(xml.responseText,geometry);
}
});
}
<|start_filename|>mapmint-ui/templates/preview/modules/measure/init.js<|end_filename|>
function handleMeasurements(event) {
var geometry = event.geometry;
var units = event.units;
var order = event.order;
var measure = event.measure;
var lonlat = geometry.getBounds().getCenterLonLat();
var pixels= this.map.getPixelFromLonLat(new OpenLayers.LonLat(lonlat.lon, lonlat.lat));
var out = "";
if(order == 1) {
var element = document.getElementById('output-lenght');
out += "" + measure.toFixed(3) + " " + units;
#if $m.web.metadata.get('layout_t')=="mobile"
\$("<div class='ui-loader ui-overlay-shadow ui-body-d ui-corner-all'><h1>"+out+"</h1></div>").css({ "z-index": 10000, "display": "block", "opacity": 0.96, "top": \$(window).scrollTop() + 100 })
.appendTo( \$("#map") )
.delay( 1500 )
.fadeOut( 400, function(){
\$(this).remove();
if(mapControls.line.active){
mapControls.line.deactivate();
toggleControl({"name":"line"});
}else{
mapControls.polygon.deactivate();
toggleControl({"name":"polygon"});
}
});
#else
\$(".dialog-lenght").dialog({
autoOpen: false,
height: 50,
width: 200,
position: [pixels.x,pixels.y],
resizable: false,
close: function(event, ui) {
}
});
\$(".dialog-lenght").dialog("open");
#end if
} else {
var element = document.getElementById('output-area');
out += "" + measure.toFixed(3) + " " + units + "<sup>2</sup>";
#if $m.web.metadata.get('layout_t')=="mobile"
\$("<div class='ui-loader ui-overlay-shadow ui-body-d ui-corner-all'><h1>"+out+"</h1></div>").css({ "z-index": 10000, "display": "block", "opacity": 0.96, "top": \$(window).scrollTop() + 100 })
.appendTo( \$("#map") )
.delay( 1500 )
.fadeOut( 400, function(){
\$(this).remove();
if(mapControls.line.active){
mapControls.line.deactivate();
toggleControl({"name":"line"});
}else{
mapControls.polygon.deactivate();
toggleControl({"name":"polygon"});
}
});
#else
\$(".dialog-area").dialog({
autoOpen: false,
height: 52,
width: 210,
position: [pixels.x,pixels.y],
resizable: false,
close: function(event, ui) {
}
});
\$(".dialog-area").dialog("open");
#end if
}
#if $m.web.metadata.get('layout_t')!="mobile"
element.innerHTML = out;
#end if
}
<|start_filename|>modules/AndroidPosition/demo.js<|end_filename|>
function setLocation(conf,inputs,outputs){
var zoo_url=conf["main"]["serverAddress"];
var myProcess = new ZOO.Process(zoo_url,'modules.AndroidPosition.defineLocation');
var myOutputs1= {Result: { type: 'RawDataOutput', "mimeType": "application/json" }};
myExecuteResult1=myProcess.Execute(inputs,myOutputs1,"Cookie: MMID="+inputs["MMID"]["value"]+";");
outputs["Result"]["value"]="Done ("+myExecuteResult1+")";
return {"result": ZOO.SERVICE_SUCCEEDED, "outputs": outputs};
}
<|start_filename|>public_map/css/mapmint-default.css<|end_filename|>
* {-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
*:before,*:after {-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
html {font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}
body {margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff;color:#788288;background-color:transparent;-webkit-font-smoothing:antialiased;}
a {color:#83c849;text-decoration:none;outline:none;}
figure {margin:0}
img {vertical-align:middle}
.img-responsive,.thumbnail>img,.thumbnail a>img,.carousel-inner>.item>img,.carousel-inner>.item>a>img {display:block;width:100% \9;max-width:100%;height:auto}
.img-rounded {border-radius:6px}
.img-thumbnail {display:inline-block;width:100% \9;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}
.img-circle {border-radius:50%}
hr {margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}
.sr-only {position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}
.sr-only-focusable:active,.sr-only-focusable:focus {position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}
h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6 {font-family:inherit;font-weight:500;line-height:1.1;color:inherit}
h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small,h1 .small,h2 .small,h3 .small,h4 .small,h5 .small,h6 .small,.h1 .small,.h2 .small,.h3 .small,.h4 .small,.h5 .small,.h6 .small {font-weight:normal;line-height:1;color:#777}
h1,.h1,h2,.h2,h3,.h3 {margin-top:20px;margin-bottom:10px}
h1 small,.h1 small,h2 small,.h2 small,h3 small,.h3 small,h1 .small,.h1 .small,h2 .small,.h2 .small,h3 .small,.h3 .small {font-size:65%}
h4,.h4,h5,.h5,h6,.h6 {margin-top:10px;margin-bottom:10px}
h4 small,.h4 small,h5 small,.h5 small,h6 small,.h6 small,h4 .small,.h4 .small,h5 .small,.h5 .small,h6 .small,.h6 .small {font-size:75%}
h1,.h1 {font-size:36px}
h2,.h2 {font-size:30px}
h3,.h3 {font-size:22px}
h4,.h4 {font-size:18px}
h5,.h5 {font-size:14px}
h6,.h6 {font-size:12px}
h5.sbt{color:#222;margin:8px 0 5px 0;font-weight:normal;}
.nav {padding-left:0;margin-bottom:0;list-style:none}
.nav>li {position:relative;display:block}
.nav>li>a {position:relative;display:block;padding:10px 15px;color:#8a8a8a;}
.header>.nav>li>a {border-right:1px solid #e5e5e5;}
.nav>li>a.active {background:#f7f8fb;}
.nav>li>a:hover,.nav>li>a:focus {text-decoration:none;background-color:#eee}
.nav>li.disabled>a {color:#777}
.nav>li.disabled>a:hover,.nav>li.disabled>a:focus {color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}
.nav .open>a,.nav .open>a:hover,.nav .open>a:focus {background-color:#eee;border-color:#428bca}
.nav .nav-divider {height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}
.nav>li>a>img {max-width:none}
.nav-tabs {border-bottom:0;box-shadow:none;}
.nav-tabs>li {float:left;margin-bottom:0}
.nav-tabs>li>a {margin-right:0;line-height:1.42857143;border:1px solid transparent;border-right:1px solid #CCC !important;border-radius: 0}
.nav-tabs>li.active>a{border-right:1px solid #CCC !important;}
.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus {color:#333;cursor:default;background-color:#fff;border-bottom-color:transparent;border-right:1px solid #CCC !important;}
.nav-tabs.nav-justified {width:100%;border-bottom:0}
.nav-tabs.nav-justified>li {float:none}
.nav-tabs.nav-justified>li>a {margin-bottom:5px;text-align:center}
.nav-tabs.nav-justified>.dropdown
.nav-justified>li {float:none}
.nav-justified>li>a {margin-bottom:5px;text-align:center}
.nav-justified>.dropdown .dropdown-menu {top:auto;left:auto}
@media (min-width: 768px) {.nav-justified > li {display:table-cell;width:1%}
.nav-justified>li>a {margin-bottom:0}}
.nav-tabs-justified {border-bottom:0}
.nav-tabs-justified>li>a {margin-right:0;border-radius:4px}
.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus {border:1px solid #ddd}
@media (min-width: 768px) {.nav-tabs-justified > li > a {border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}
.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus {border-bottom-color:#fff}}
.tab-content>.tab-pane {display:none}
.tab-content>.active {display:block}
.nav-tabs .dropdown-menu {margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}
.navbar {position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}
@media (min-width: 768px) {.navbar {border-radius:4px}}
@media (min-width: 768px) {.navbar-header {float:left}}
.navbar-collapse {padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}
.navbar-collapse.in {overflow-y:auto}
@media (min-width: 768px) {.navbar-collapse {width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}
.navbar-collapse.collapse {display:block !important;height:auto !important;padding-bottom:0;overflow:visible !important}
.navbar-collapse.in {overflow-y:visible}
.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse {padding-right:0;padding-left:0}}
.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse {max-height:340px}
@media (max-width: 480px) and (orientation: landscape) {.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse {max-height:200px}}
.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse {margin-right:-15px;margin-left:-15px}
@media (min-width: 768px) {.container > .navbar-header,.container-fluid > .navbar-header,.container > .navbar-collapse,.container-fluid > .navbar-collapse {margin-right:0;margin-left:0}
}
.navbar-static-top {z-index:1000;border-width:0 0 1px}
@media (min-width: 768px) {.navbar-static-top {border-radius:0}}
.navbar-fixed-top,.navbar-fixed-bottom {position:fixed;right:0;left:0;z-index:1030;-webkit-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}
@media (min-width: 768px) {.navbar-fixed-top,.navbar-fixed-bottom {border-radius:0}}
.navbar-fixed-top {top:0;border-width:0 0 1px}
.navbar-fixed-bottom {bottom:0;margin-bottom:0;border-width:1px 0 0}
.navbar-brand {float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px;}
.navbar-brand:hover,.navbar-brand:focus {text-decoration:none}
@media (min-width: 768px) {.navbar > .container .navbar-brand,.navbar > .container-fluid .navbar-brand {margin-left:-15px}}
.navbar-toggle {position:relative;float:right;padding:4px 10px 4px 10px;margin-top:10px;margin-right:10px;margin-bottom:6px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}
.navbar-toggle:focus {outline:0}
.navbar-toggle .icon-bar {display:block;width:22px;height:2px;border-radius:1px}
.navbar-toggle .icon-bar+.icon-bar {margin-top:4px}
@media (min-width: 768px) {.navbar-toggle {display:none}}
.navbar-nav {margin:7.5px -15px}
.navbar-nav>li>a {padding-top:10px;padding-bottom:10px;line-height:20px}
@media (max-width: 767px) {.navbar-nav .open .dropdown-menu {position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none;}
.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header {padding:5px 15px 5px 25px}
.navbar-nav .open .dropdown-menu>li>a {line-height:20px}
.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus {background-image:none}
}
@media (min-width: 768px) {.navbar-nav {float:left;margin:0}
.navbar-nav>li {float:left}
.navbar-nav>li>a {padding-top:15px;padding-bottom:15px}
.navbar-nav.navbar-right:last-child {margin-right:-15px}}
@media (min-width: 768px) {.navbar-left {float:left !important}
.navbar-right {float:right !important}}
.navbar-form {padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}
@media (min-width: 768px) {.navbar-form .form-group {display:inline-block;margin-bottom:0;vertical-align:middle}
.navbar-form .form-control {display:inline-block;width:auto;vertical-align:middle}
.navbar-form .input-group {display:inline-table;vertical-align:middle}
.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn,.navbar-form .input-group .form-control {width:auto}
.navbar-form .input-group>.form-control {width:100%}
.navbar-form .control-label {margin-bottom:0;vertical-align:middle}
.navbar-form .radio,.navbar-form .checkbox {display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}
.navbar-form .radio label,.navbar-form .checkbox label {padding-left:0}
.navbar-form .radio input[type="radio"],.navbar-form .checkbox input[type="checkbox"] {position:relative;margin-left:0}
.navbar-form .has-feedback .form-control-feedback {top:0}
}
@media (max-width: 767px) {.navbar-form .form-group {margin-bottom:5px}}
@media (min-width: 768px) {.navbar-form {width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}
.navbar-form.navbar-right:last-child {margin-right:-15px}}
.navbar-nav>li>.dropdown-menu {margin-top:0;border-top-left-radius:0;border-top-right-radius:0}
.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu {border-bottom-right-radius:0;border-bottom-left-radius:0}
.navbar-btn {margin-top:8px;margin-bottom:8px}
.navbar-btn.btn-sm {margin-top:10px;margin-bottom:10px}
.navbar-btn.btn-xs {margin-top:14px;margin-bottom:14px}
.navbar-text {margin-top:15px;margin-bottom:15px}
@media (min-width: 768px) {.navbar-text {float:left;margin-right:15px;margin-left:15px}.navbar-text.navbar-right:last-child {margin-right:0}}
.navbar-default {background-color:#f8f8f8;border-color:#e7e7e7}
.navbar-default .navbar-brand {color:#777}
.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus {color:#5e5e5e;background-color:transparent}
.navbar-default .navbar-text {color:#777}
.navbar-default .navbar-nav>li>a {color:#777}
.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus {color:#333;background-color:transparent}
.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus {color:#555;background-color:#e7e7e7}
.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus {color:#ccc;background-color:transparent}
.navbar-default .navbar-toggle {border-color:#ddd}
.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus {background-color:#ddd}
.navbar-default .navbar-toggle .icon-bar {background-color:#888}
.navbar-default .navbar-collapse,.navbar-default .navbar-form {border-color:#e7e7e7}
.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus {color:#555;background-color:#e7e7e7}
@media (max-width: 767px) {.navbar-default .navbar-nav .open .dropdown-menu > li > a {color:#777}
.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus {color:#707070;background-color:transparent}
.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus {color:#555;background-color:#e7e7e7;}
.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus {color:#ccc;background-color:transparent}
}
.navbar-default .navbar-link {color:#777}
.navbar-default .navbar-link:hover {color:#333}
.navbar-default .btn-link {color:#777}
.navbar-default .btn-link:hover,.navbar-default .btn-link:focus {color:#333}
.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:hover,.navbar-default .btn-link[disabled]:focus,fieldset[disabled] .navbar-default .btn-link:focus {color:#ccc}
.navbar-inverse {background-color:#222;border-color:#080808}
.navbar-inverse .navbar-brand {color:#777}
.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus {color:#fff;background-color:transparent}
.navbar-inverse .navbar-text {color:#777}
.navbar-inverse .navbar-nav>li>a {color:#777}
.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus {color:#fff;background-color:transparent}
.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus {color:#fff;background-color:#080808}
.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus {color:#444;background-color:transparent}
.navbar-inverse .navbar-toggle {border-color:#333}
.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus {background-color:#333}
.navbar-inverse .navbar-toggle .icon-bar {background-color:#fff}
.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form {border-color:#101010}
.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus {color:#fff;background-color:#080808}
@media (max-width: 767px) {.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {border-color:#080808}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {background-color:#080808}
.navbar-inverse .navbar-nav .open .dropdown-menu>li>a {color:#777}
.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus {color:#fff;background-color:transparent}
.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus {color:#fff;background-color:#080808}
.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus {color:#444;background-color:transparent}
}
.navbar-inverse .navbar-link {color:#777}
.navbar-inverse .navbar-link:hover {color:#fff}
.navbar-inverse .btn-link {color:#777}
.navbar-inverse .btn-link:hover,.navbar-inverse .btn-link:focus {color:#fff}
.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:hover,.navbar-inverse .btn-link[disabled]:focus,fieldset[disabled] .navbar-inverse .btn-link:focus {color:#444}
.badge,.label {font-weight:bold}
.badge {background-color:#b0bcd4}
.badge.up {position:relative;top:-10px;padding:3px 6px;margin-left:-10px}
.badge-sm {font-size:85%;padding:2px 5px !important}
.label-sm {padding-top:0;padding-bottom:0}
.badge-white {background-color:transparent;border:1px solid rgba(255,255,255,0.35);padding:2px 6px}
.badge-empty {background-color:transparent;border:1px solid rgba(0,0,0,0.15);color:inherit}
.caret-white {border-top-color:#fff;border-top-color:rgba(255,255,255,0.65)}
.ncaret {display: inline-block;width:8px;height: 0;margin-left: 2px;vertical-align: middle;}
.ttl{padding-left:10px;}
a:hover .caret-white {border-top-color:#fff}
.thumbnail {border-color:#eaeef1}
.popover-content {font-size:12px;line-height:1.5}
.progress-xs {height:6px}
.progress-sm {height:10px}
.progress-sm .progress-bar {font-size:10px;line-height:1em}
.progress,.progress-bar {-webkit-box-shadow:none;box-shadow:none}
.breadcrumb {background-color:#fff;border:1px solid #eaeef1;padding-left:10px;margin-bottom:10px}
.breadcrumb>li+li:before,.breadcrumb>.active {color:inherit}
.accordion-group,.accordion-inner {border-color:#eaeef1;border-radius:2px}
.alert {font-size:12px;box-shadow:inset 0 1px 0 rgba(255,255,255,0.2)}
.alert .close i {font-size:12px;font-weight:normal;display:block}
.form-control {border-color:#CCCCCC;border-radius:2px}
.form-control,.form-control:focus {-webkit-box-shadow:none;box-shadow:none}
.form-control:focus {border-color:#b8b8b8}
.input-s-sm {width:120px}
.input-s {width:200px}
.input-s-lg {width:250px}
.input-lg {height:45px}
.input-group-addon {border-color:#cbd5dd;background-color:#fcfcfd}
.list-group {border-radius:2px}
.list-group.no-radius .list-group-item {border-radius:0 !important}
.list-group.no-borders .list-group-item {border:none}
.list-group.no-border .list-group-item {border-width:1px 0}
.list-group.no-bg .list-group-item {background-color:transparent}
.list-group-item {border-color:#eaeef1;padding-right:15px}
a.list-group-item:hover,a.list-group-item:focus {background-color:#f9fafc}
.list-group-item.media {margin-top:0}
.list-group-item.active {color:#fff;border-color:#1ccacc !important;background-color:#1ccacc !important}
.list-group-item.active .text-muted {color:#91eff0}
.list-group-item.active a {color:#fff}
.list-group-alt .list-group-item:nth-child(2n+2) {background-color:rgba(0,0,0,0.02) !important}
.list-group-lg .list-group-item {padding-top:15px;padding-bottom:15px}
.list-group-sp .list-group-item {margin-bottom:5px;border-radius:3px}
.list-group-item>.badge {margin-right:0}
.list-group-item>.fa-chevron-right {float:right;margin-top:4px;margin-right:-5px}
.list-group-item>.fa-chevron-right+.badge {margin-right:5px}
.nav-pills.no-radius>li>a {border-radius:0}
.nav-pills>li.active>a {color:#fff !important;background-color:#1ccacc}
.nav>li>a:hover,.nav>li>a:focus {background-color:#f7f8fb}
.nav.nav-sm>li>a {padding:6px 8px}
.nav .avatar {width:30px;margin-top:-5px;margin-right:5px}
.nav .open>a,.nav .open>a:hover,.nav .open>a:focus {background-color:#f7f8fb}
.nav-tabs {border-color:#eaeef1}
.nav-tabs>li>a {border-radius:2px 2px 0 0;border-bottom-color:#eaeef1 !important}
.nav-tabs>li.active>a {border-color:#eaeef1 !important;border-bottom-color:#fff !important;border-right-color:#CCC !important;}
.pagination>li>a {border-color:#eaeef1}
.pagination>li>a:hover,.pagination>li>a:focus {border-color:#eaeef1;background-color:#f2f4f8}
.panel {border-radius:2px}
.panel.panel-default {border-color:#eaeef1}
.panel.panel-default>.panel-heading,.panel.panel-default>.panel-footer {border-color:#eaeef1}
.panel>.list-group .list-group-item:first-child {border-top:0}
.panel .list-group-item {border-color:#f3f5f7}
.panel.no-borders {border-width:0}
.panel.no-borders .panel-heading,.panel.no-borders .panel-footer {border-width:0}
.panel .table td,.panel .table th {padding:8px 15px;border-top:1px solid #eaeef1}
.panel .table thead>tr>th {border-bottom:1px solid #eaeef1}
.panel .table-striped>tbody>tr:nth-child(odd)>td,.panel .table-striped>tbody>tr:nth-child(odd)>th {background-color:#f9fafc}
.panel .table-striped>thead th {background-color:#f9fafc;border-right:1px solid #eaeef1}
.panel .table-striped>thead th:last-child {border-right:none}
.panel-heading {border-radius:2px 2px 0 0}
.panel-default .panel-heading {background-color:#f9fafc}
.panel-heading.no-border {margin:-1px -1px 0 -1px;border:none}
.panel-heading .nav {margin:-10px -15px}
.panel-heading .nav-tabs {margin:-11px -16px}
.panel-heading .nav-tabs.nav-justified {width:auto}
.panel-heading .nav-tabs>li>a {margin:0;padding-top:11px;padding-bottom:11px}
.panel-heading .list-group {background:transparent}
.panel-footer {border-color:#eaeef1;border-radius:0 0 2px 2px;background-color:#f9fafc}
.panel-group .panel-heading+.panel-collapse .panel-body {border-top:1px solid #eaedef}
.open {z-index:999 !important;position:relative}
.dropdown-menu {font-size:13px;border-radius:2px;-webkit-box-shadow:0 2px 6px rgba(0,0,0,0.1);box-shadow:0 2px 6px rgba(0,0,0,0.1);border:1px solid #ddd;border:1px solid rgba(0,0,0,0.1)}
.dropdown-menu.pull-left {left:100%}
.dropdown-menu>.panel {border:none;margin:-5px 0}
.dropdown-menu>li>a {padding:5px 15px;color:#707070;}
.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus {background-image:none;filter:none;background-color:#eeeeee !important;color:#333333;text-shadow:#FFFFFF 0 1px 0;}
.dropdown-menu>li.nb>a {cursor:default !important;}
.dropdown-menu>li.nb>a:hover {background-color:transparent !important;color:#707070 !important;}
.dropdown-header {padding:5px 15px}
.dropdown-submenu {position:relative}
.dropdown-submenu:hover>a,.dropdown-submenu:focus>a {background-color:#f2f4f8 !important;color:#788288}
.dropdown-submenu:hover>.dropdown-menu,.dropdown-submenu:focus>.dropdown-menu {display:block}
.dropdown-submenu.pull-left {float:none !important}
.dropdown-submenu.pull-left>.dropdown-menu {left:-100%;margin-left:10px}
.dropdown-submenu .dropdown-menu {left:100%;top:0;margin-top:-6px;margin-left:-1px}
.dropup .dropdown-submenu>.dropdown-menu {top:auto;bottom:0}
.dropdown-select>li>a input {position:absolute;left:-9999em}
.icon-muted {color:#ccc}
.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form {border-color:transparent}
.navbar-fixed-top,.navbar-fixed-bottom {position:fixed !important}
.navbar-fixed-top+* {padding-top:50px}
.navbar-fixed-top.header-md+* {padding-top:60px}
.header,.footer {min-height:50px;padding:0 15px}
.header>p,.footer>p {margin-top:15px;display:inline-block}
.header>.btn,.header>.btn-group,.header>.btn-toolbar,.footer>.btn,.footer>.btn-group,.footer>.btn-toolbar {margin-top:10px}
.header>.btn-lg,.footer>.btn-lg {margin-top:0}
.header .nav-tabs,.footer .nav-tabs {border:none;margin-left:-15px;margin-right:-15px}
.header .nav-tabs>li a,.footer .nav-tabs>li a {border:none !important;border-radius:0;padding-top:15px;padding-bottom:15px;line-height:20px}
.header .nav-tabs>li a:hover,.header .nav-tabs>li a:focus,.footer .nav-tabs>li a:hover,.footer .nav-tabs>li a:focus {background-color:transparent}
.header .nav-tabs>li.active a,.footer .nav-tabs>li.active a {color:#788288}
.header .nav-tabs>li.active a,.header .nav-tabs>li.active a:hover,.footer .nav-tabs>li.active a,.footer .nav-tabs>li.active a:hover {background-color:#f2f4f8}
.header .nav-tabs.nav-white>li.active a,.header .nav-tabs.nav-white>li.active a:hover,.footer .nav-tabs.nav-white>li.active a,.footer .nav-tabs.nav-white>li.active a:hover {background-color:#fff}
.header.navbar,.footer.navbar {border-radius:0;border:none;margin-bottom:0;padding:0;position:relative;z-index:1000}
body.container {padding:0}
@media (orientation: landscape) {html.ios7.ipad > body {padding-bottom:20px}
}
.navbar-header {position:relative}
.navbar-header>.btn {position:absolute;font-size:1.3em;padding:9px 16px;line-height:30px;left:0}
.navbar-header .navbar-brand+.btn {right:0;top:0;left:auto}
.navbar-brand {float:none;text-align:center;font-size:18px;font-weight:300;height:auto;line-height:50px;display:inline-block;padding:0 15px}
.navbar-brand:hover {text-decoration:none}
.navbar-brand img {max-height:20px;margin-top:-4px;vertical-align:middle}
.nav-primary li>a>i {margin:-8px -10px;line-height:36px;width:36px;float:left;margin-right:5px;text-align:center;position:relative;overflow:hidden}
.nav-primary li>a>i:before {position:relative;z-index:2}
.nav-primary ul.nav>li>a {padding:8px 15px;position:relative;-webkit-transition:background-color .2s ease-in-out 0s;transition:background-color .2s ease-in-out 0s}
.no-borders .nav-primary ul.nav>li>a {border-width:0 !important}
.nav-primary ul.nav>li>a>.badge {font-size:11px;padding:2px 5px 2px 4px;margin-top:2px}
.nav-primary ul.nav>li>a>.text-muted {margin:0 3px}
.nav-primary ul.nav>li>a.active .text {display:none}
.nav-primary ul.nav>li>a.active .text-active {display:inline-block !important}
.nav-primary ul.nav>li li a {font-weight:normal;text-transform:none;padding:5px 0 5px 45px;}
.nav-primary ul.nav>li.active>ul {display:block}
.nav-primary ul.nav ul {display:none}
.bg-black .nav-primary>ul.nav-main>li:hover>a,.bg-black .nav-primary>ul.nav-main>li:focus>a,.bg-black .nav-primary>ul.nav-main>li:active>a,.bg-black .nav-primary>ul.nav-main>li.active>a {background-color:#1aae88}
.nav-main li.active {background:#F2F4F8;}
@media (min-width: 768px) {.visible-nav-xs {display:none}
.nav-xs {width:70px}
.nav-xs .slimScrollDiv,.nav-xs .slim-scroll {overflow:visible !important}
.nav-xs .slimScrollBar,.nav-xs .slimScrollRail {display:none !important}
.nav-xs .scrollable {overflow:visible}
.nav-xs .nav-primary>ul>li>a {position:relative;padding:0;font-size:11px;text-align:center;height:50px;overflow-y:hidden;border:none}
.nav-xs .nav-primary>ul>li>a span {display:table-cell;vertical-align:middle;height:50px;width:70px;}
.nav-xs .nav-primary>ul>li>a span.pull-right {display:none !important}
.nav-xs .nav-primary>ul>li>a i {width:auto;float:none;display:block;font-size:16px;margin:0;line-height:50px;border:none !important;-webkit-transition:margin-top 0.2s;transition:margin-top 0.2s}
.nav-xs .nav-primary>ul>li>a i b {left:0 !important}
.nav-xs .nav-primary>ul>li>a .badge {position:absolute;right:10px;top:4px;z-index:3}
.nav-xs .nav-primary>ul>li:hover>a i,.nav-xs .nav-primary>ul>li:focus>a i,.nav-xs .nav-primary>ul>li:active>a i,.nav-xs .nav-primary>ul>li.active>a i {margin-top:-50px}
.nav-xs .nav-primary>ul ul {display:none !important;position:absolute;left:100%;top:0;z-index:1050;width:220px;-webkit-box-shadow:0 2px 6px rgba(0,0,0,0.1);box-shadow:0 2px 6px rgba(0,0,0,0.1);padding:5px 0 5px 0;}
.nav-xs .nav-primary>ul ul li a{padding:5px 0 5px 25px;}
.nav-xs .nav-primary li:hover>ul,.nav-xs .nav-primary li:focus>ul,.nav-xs .nav-primary li:active>ul {display:block !important}
.nav-xs.nav-xs-right .nav-primary>ul ul {left:auto;right:100%}
.nav-xs>.vbox>.header,.nav-xs>.vbox>.footer {padding:0 20px}
.nav-xs .hidden-nav-xs {display:none}
.nav-xs .visible-nav-xs {display:inherit}
.nav-xs .text-center-nav-xs {text-align:center}
.nav-xs .nav-user {padding-left:0;padding-right:0}
.nav-xs .nav-user .avatar {float:none !important;margin-right:0}
.nav-xs .nav-user .dropdown>a {display:block;text-align:center}
.nav-xs .navbar-header {float:none}
.nav-xs .navbar-brand {display:block;padding:0}
.nav-xs .navbar-brand img {margin-right:0}
.nav-xs .navbar {padding:0}
.header-md .navbar-brand {line-height:60px}
.header-md .navbar-brand img {max-height:30px}
.header-md .navbar-nav>li>a {padding:20px}
}
@media (max-width: 767px) {.navbar-fixed-top-xs {position:fixed !important;left:0;width:100%;z-index:1100}
.navbar-fixed-top-xs+* {padding-top:50px !important}
.nav-bar-fixed-bottom {position:fixed;left:0;bottom:0;width:100%;z-index:1100}
html,body {overflow-x:hidden;min-height:100%}
.open,.open body {height:100%}
.nav-primary .dropdown-menu {position:relative;float:none;left:0;margin-left:0;padding:0}
.nav-primary .dropdown-menu a {padding:15px;border-bottom:1px solid #eee}
.nav-primary .dropdown-menu li:last-child a {border-bottom:none}
.navbar-header {text-align:center}
.nav-user {margin:0;padding:15px}
.nav-user.open {display:inherit !important}
.nav-user .dropdown-menu {display:block;position:static;float:none}
.nav-user .dropdown>a {display:block;text-align:center;font-size:18px;padding-bottom:10px}
.nav-user .avatar {width:160px !important;float:none !important;display:block;margin:20px auto;padding:5px;background-color:rgba(255,255,255,0.1);position:relative}
.nav-user .avatar:before {content:"";position:absolute;left:5px;right:5px;bottom:5px;top:5px;border:4px solid #fff;border-radius:500px}
.nav-off-screen {display:block !important;position:absolute;left:0;top:0;bottom:0;width:75%;visibility:visible;overflow-x:hidden;overflow-y:auto;-webkit-overflow-scrolling:touch}
.nav-off-screen .nav-primary {display:block !important}
.nav-off-screen .navbar-fixed-top-xs {width:75%}
.nav-off-screen.push-right .navbar-fixed-top-xs {left:25%}
.nav-off-screen.push-right {left:auto;right:0}
.nav-off-screen.push-right+* {-webkit-transform:translate3d(-75%,0px,0px);transform:translate3d(-75%,0px,0px)}
.nav-off-screen+* {background-color:#f2f4f8;-webkit-transition:-webkit-transform 0.2s ease-in-out;-moz-transition:-moz-transform 0.2s ease-in-out;-o-transition:-o-transform 0.2s ease-in-out;transition:transform 0.2s ease-in-out;-webkit-transition-delay:0s;transition-delay:0s;-webkit-transform:translate3d(0px,0px,0px);transform:translate3d(0px,0px,0px);-webkit-backface-visibility:hidden;-moz-backface-visibility:hidden;backface-visibility:hidden;-webkit-transform:translate3d(75%,0px,0px);transform:translate3d(75%,0px,0px);overflow:hidden;position:absolute;width:100%;top:0px;bottom:0;left:0;right:0;z-index:2}
.nav-off-screen+* .nav-off-screen-block {display:block !important;position:absolute;left:0;right:0;top:0;bottom:0;z-index:1950}
.navbar+section .nav-off-screen {top:50px}
.navbar+section .nav-off-screen+* {top:50px}
.slimScrollDiv,.slim-scroll {overflow:visible !important;height:auto !important}
.slimScrollBar,.slimScrollRail {display:none !important}
}
.arrow {border-width:8px;z-index:10}
.arrow,.arrow:after {position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}
.arrow:after {border-width:7px;content:""}
.arrow.top {left:50%;margin-left:-8px;border-top-width:0;border-bottom-color:#eee;border-bottom-color:rgba(0,0,0,0.1);top:-8px}
.arrow.top:after {content:" ";top:1px;margin-left:-7px;border-top-width:0;border-bottom-color:#fff}
.arrow.right {top:50%;right:-8px;margin-top:-8px;border-right-width:0;border-left-color:#eee;border-left-color:rgba(0,0,0,0.1)}
.arrow.right:after {content:" ";right:1px;border-right-width:0;border-left-color:#fff;bottom:-7px}
.arrow.bottom {left:50%;margin-left:-8px;border-bottom-width:0;border-top-color:#eee;border-top-color:rgba(0,0,0,0.1);bottom:-8px}
.arrow.bottom:after {content:" ";bottom:1px;margin-left:-7px;border-bottom-width:0;border-top-color:#fff}
.arrow.left {top:50%;left:-8px;margin-top:-8px;border-left-width:0;border-right-color:#eee;border-right-color:rgba(0,0,0,0.1)}
.arrow.left:after {content:" ";left:1px;border-left-width:0;border-right-color:#fff;bottom:-7px}
.btn-link {color:#788288}
.btn-link.active {webkit-box-shadow:none;box-shadow:none}
.btn-bl {border-color:#E3E3E3;border-radius:3px;width:32px;height:32px;}
.btn-cp {font-size:.85em;margin:10px;color:#E3E3E3;border:1px solid #E3E3E3;border-radius:3px;width:22px;height:22px;line-height:20px;text-align:center;}
.btn-cp:hover {color:#707070;border:1px solid #b6b6b6;background:#FFFFFF;}
.btn-default {color:#9b9b9b !important;background-color:#fcfcfd;border-color:#CCCCCC;border-bottom-color:#cbd5dd;-webkit-box-shadow:0 1px 1px rgba(90,90,90,0.1);box-shadow:0 1px 1px rgba(90,90,90,0.1)}
.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default {color:#707070 !important;background-color:#eeeeee;border-color:#cccdce}
.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default {background-image:none}
.btn-default.disabled,.btn-default.disabled:hover,.btn-default.disabled:focus,.btn-default.disabled:active,.btn-default.disabled.active,.btn-default[disabled],.btn-default[disabled]:hover,.btn-default[disabled]:focus,.btn-default[disabled]:active,.btn-default[disabled].active,fieldset[disabled] .btn-default,fieldset[disabled] .btn-default:hover,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:active,fieldset[disabled] .btn-default.active {background-color:#fcfcfd;border-color:#d2dae1}
.btn-default.btn-bg {border-color:rgba(0,0,0,0.1);background-clip:padding-box}
.btn-primary {color:#fff !important;background-color:#177bbb;border-color:#177bbb}
.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary {color:#fff !important;background-color:#146ca4;border-color:#136397}
.btn-primary:active,.btn-primary.active,.open .dropdown-toggle.btn-primary {background-image:none}
.btn-primary.disabled,.btn-primary.disabled:hover,.btn-primary.disabled:focus,.btn-primary.disabled:active,.btn-primary.disabled.active,.btn-primary[disabled],.btn-primary[disabled]:hover,.btn-primary[disabled]:focus,.btn-primary[disabled]:active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary:hover,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary.active {background-color:#177bbb;border-color:#177bbb}
.btn-success {color:#fff !important;background-color:#1aae88;border-color:#1aae88}
.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success {color:#fff !important;background-color:#179877;border-color:#158b6c}
.btn-success:active,.btn-success.active,.open .dropdown-toggle.btn-success {background-image:none}
.btn-success.disabled,.btn-success.disabled:hover,.btn-success.disabled:focus,.btn-success.disabled:active,.btn-success.disabled.active,.btn-success[disabled],.btn-success[disabled]:hover,.btn-success[disabled]:focus,.btn-success[disabled]:active,.btn-success[disabled].active,fieldset[disabled] .btn-success,fieldset[disabled] .btn-success:hover,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:active,fieldset[disabled] .btn-success.active {background-color:#1aae88;border-color:#1aae88}
.btn-info {color:#fff !important;background-color:#1ccacc;border-color:#1ccacc}
.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info {color:#fff !important;background-color:#19b4b6;border-color:#17a6a8}
.btn-info:active,.btn-info.active,.open .dropdown-toggle.btn-info {background-image:none}
.btn-info.disabled,.btn-info.disabled:hover,.btn-info.disabled:focus,.btn-info.disabled:active,.btn-info.disabled.active,.btn-info[disabled],.btn-info[disabled]:hover,.btn-info[disabled]:focus,.btn-info[disabled]:active,.btn-info[disabled].active,fieldset[disabled] .btn-info,fieldset[disabled] .btn-info:hover,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:active,fieldset[disabled] .btn-info.active {background-color:#1ccacc;border-color:#1ccacc}
.btn-warning {color:#fff !important;background-color:#fcc633;border-color:#fcc633}
.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning {color:#fff !important;background-color:#fcbf1a;border-color:#fbbb0b}
.btn-warning:active,.btn-warning.active,.open .dropdown-toggle.btn-warning {background-image:none}
.btn-warning.disabled,.btn-warning.disabled:hover,.btn-warning.disabled:focus,.btn-warning.disabled:active,.btn-warning.disabled.active,.btn-warning[disabled],.btn-warning[disabled]:hover,.btn-warning[disabled]:focus,.btn-warning[disabled]:active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning,fieldset[disabled] .btn-warning:hover,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:active,fieldset[disabled] .btn-warning.active {background-color:#fcc633;border-color:#fcc633}
.btn-danger {color:#fff !important;background-color:#e33244;border-color:#e33244}
.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger {color:#fff !important;background-color:#dd1e32;border-color:#d01c2f}
.btn-danger:active,.btn-danger.active,.open .dropdown-toggle.btn-danger {background-image:none}
.btn-danger.disabled,.btn-danger.disabled:hover,.btn-danger.disabled:focus,.btn-danger.disabled:active,.btn-danger.disabled.active,.btn-danger[disabled],.btn-danger[disabled]:hover,.btn-danger[disabled]:focus,.btn-danger[disabled]:active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger,fieldset[disabled] .btn-danger:hover,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:active,fieldset[disabled] .btn-danger.active {background-color:#e33244;border-color:#e33244}
.btn-dark {color:#fff !important;background-color:#222733;border-color:#222733}
.btn-dark:hover,.btn-dark:focus,.btn-dark:active,.btn-dark.active,.open .dropdown-toggle.btn-dark {color:#fff !important;background-color:#181b24;border-color:#12141b}
.btn-dark:active,.btn-dark.active,.open .dropdown-toggle.btn-dark {background-image:none}
.btn-dark.disabled,.btn-dark.disabled:hover,.btn-dark.disabled:focus,.btn-dark.disabled:active,.btn-dark.disabled.active,.btn-dark[disabled],.btn-dark[disabled]:hover,.btn-dark[disabled]:focus,.btn-dark[disabled]:active,.btn-dark[disabled].active,fieldset[disabled] .btn-dark,fieldset[disabled] .btn-dark:hover,fieldset[disabled] .btn-dark:focus,fieldset[disabled] .btn-dark:active,fieldset[disabled] .btn-dark.active {background-color:#222733;border-color:#222733}
.btn {font-weight:500;border-radius:2px}
.btn-icon {padding-left:0 !important;padding-right:0 !important;width:34px;text-align:center}
.btn-icon.b-2x {width:36px}
.btn-icon.btn-sm {width:30px}
.btn-icon.btn-sm.b-2x {width:32px}
.btn-icon.btn-lg {width:45px}
.btn-icon.btn-lg.b-2x {width:47px}
.btn-group-justified {border-collapse:separate}
.btn-rounded {border-radius:50px;padding-left:15px;padding-right:15px}
.btn-rounded.btn-lg {padding-left:25px;padding-right:25px}
.btn>i.pull-left,.btn>i.pull-right {line-height:1.428571429}
.btn-block {padding-left:12px;padding-right:12px}
.btn-group-vertical>.btn:first-child:not(:last-child) {border-top-right-radius:2px}
.btn-group-vertical>.btn:last-child:not(:first-child) {border-bottom-left-radius:2px}
.btn-inactive {-webkit-box-shadow:none !important;box-shadow:none !important}
.bg-light {background-color:#f2f4f8;color:#788288}
.bg-light.lt,.bg-light .lt {background-color:#f7f8fb}
.bg-light.lter,.bg-light .lter {background-color:#fcfcfd}
.bg-light.dk,.bg-light .dk {background-color:#e9edf4}
.bg-light.dker,.bg-light .dker {background-color:#e0e6f0}
.bg-light.bg,.bg-light .bg {background-color:#f2f4f8}
.bg-white {background-color:#fff;color:#788288}
.bg-white a {color:#3c4144}
.bg-white a:hover {color:#242729}
.bg-white.dk,.bg-white .dk {background-color:#FFF}
.bg-white.dker,.bg-white .dker {background-color:#FFF}
.bg-white .text-muted {color:#a1a8ac !important}
.bg-white-only {background-color:#fff}
.bg-empty {background-color:transparent}
.fill{height:100%;min-height:100%;}
.padd{padding:15px;}
.padder {padding-left:15px;padding-right:15px}
.padder-v {padding-top:15px;padding-bottom:15px}
.no-padder {padding:0 !important}
.mb{margin-bottom:10px;}
.tab-pane > .well{border-radius:0;background:#FFFFFF;box-shadow:none;border:0;}
.range {
display: table;
position: relative;
height: 20px !important;
width:160px;
margin:0 10px 10px 10px;
background-color: rgb(245, 245, 245);
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
cursor: pointer;
}
.range input[type="range"] {
-webkit-appearance: none !important;
-moz-appearance: none !important;
-ms-appearance: none !important;
-o-appearance: none !important;
appearance: none !important;
display: table-cell;
width: 100%;
background-color: transparent;
height: 20px !important;
cursor: pointer;
}
.range input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none !important;
-moz-appearance: none !important;
-ms-appearance: none !important;
-o-appearance: none !important;
appearance: none !important;
width: 10px;
height: 20px !important;
color: rgb(255, 255, 255);
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: 0px;
background-color: #D0D0D0;
}
.range input[type="range"]::-moz-slider-thumb {
-webkit-appearance: none !important;
-moz-appearance: none !important;
-ms-appearance: none !important;
-o-appearance: none !important;
appearance: none !important;
width: 11px;
height: 20px;
color: rgb(255, 255, 255);
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: 0px;
background-color: #D0D0D0;
}
.range output {
display: table-cell;
padding: 3px 5px 2px;
min-width: 40px;
color: rgb(255, 255, 255);
background-color: #B0B0B0;
text-align: center;
text-decoration: none;
border-radius: 4px;
border-bottom-left-radius: 0;
border-top-left-radius: 0;
width: 1%;
white-space: nowrap;
vertical-align: middle;
line-height: .9;
font-size:.85em;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
-ms-transition: all 0.5s ease;
transition: all 0.5s ease;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: -moz-none;
-o-user-select: none;
user-select: none;
}
.range input[type="range"] {
outline: none;
}
.range.range-primary input[type="range"]::-webkit-slider-thumb {
background-color: #A5A5A5;
}
.range.range-primary input[type="range"]::-moz-slider-thumb {
background-color: #A5A5A5;
}
.range.range-primary output {
background-color: rgb(66, 139, 202);
}
.range.range-primary input[type="range"] {
outline-color: rgb(66, 139, 202);
}
.range.range-success input[type="range"]::-webkit-slider-thumb {
background-color: rgb(92, 184, 92);
}
.range.range-success input[type="range"]::-moz-slider-thumb {
background-color: rgb(92, 184, 92);
}
.range.range-success output {
background-color: rgb(92, 184, 92);
}
.range.range-success input[type="range"] {
outline-color: rgb(92, 184, 92);
}
.range.range-info input[type="range"]::-webkit-slider-thumb {
background-color: rgb(91, 192, 222);
}
.range.range-info input[type="range"]::-moz-slider-thumb {
background-color: rgb(91, 192, 222);
}
.range.range-info output {
background-color: rgb(91, 192, 222);
}
.range.range-info input[type="range"] {
outline-color: rgb(91, 192, 222);
}
.range.range-warning input[type="range"]::-webkit-slider-thumb {
background-color: rgb(240, 173, 78);
}
.range.range-warning input[type="range"]::-moz-slider-thumb {
background-color: rgb(240, 173, 78);
}
.range.range-warning output {
background-color: rgb(240, 173, 78);
}
.range.range-warning input[type="range"] {
outline-color: rgb(240, 173, 78);
}
.range.range-danger input[type="range"]::-webkit-slider-thumb {
background-color: rgb(217, 83, 79);
}
.range.range-danger input[type="range"]::-moz-slider-thumb {
background-color: rgb(217, 83, 79);
}
.range.range-danger output {
background-color: rgb(217, 83, 79);
}
.range.range-danger input[type="range"] {
outline-color: rgb(217, 83, 79);
}
.op{
display:none;
position:absolute;
top:.5em;left:10px;
z-index:1000;
width:22px;height:22px;
color: #707070;
font-size: .85em;
text-align: center;
line-height: 20px;
background-color: #7b98bc;
background-color: rgba(255,255,255,1) !important;
border: 1px solid #CCCCCC !important;
border-radius: 2px;
outline: none !important;
}
.opr{
display:none;
position:absolute;
top:.5em;right:10px;
z-index:1000;
width:22px;height:22px;
color: #707070;
font-size: .85em;
text-align: center;
line-height: 20px;
background-color: #7b98bc;
background-color: rgba(255,255,255,1) !important;
border: 1px solid #CCCCCC !important;
border-radius: 2px;
outline: none !important;
}
.info{
background-color: #FFF;
overflow: hidden;
box-shadow: 0 0 1px #CCC;
margin-top:12px;
}
.info .content{
padding:0 15px 15px 15px;
}
.info .content p{
padding:0;
font-size:12px;
}
.info .info-title{
margin:10px 0 10px 0;
}
.info .info-date
{
font-size: 12px;
color: #737373;
padding: 0 0 10px 0;
}
.info .info-img-content
{
height: 160px;
position: relative;
}
.info .info-img-content img
{
position: absolute;
}
@media (max-width: 480px) {
.pull-right {
float: right;/*none!important;*/
}
}
.well-table{
margin-bottom:0;
padding: 10px 18px;
background: #fff;
border-top: none;
}
.symb-inner {
font-size: 8px;
margin-left: -4px;
padding-right: 0px;
clear: none;
display: inline;
}
/*table.display {
table-layout: fixed;
}*/
<|start_filename|>public_map/assets/css/login.css<|end_filename|>
/*!
* MapMint Login
*/
html,body{ min-height: 100%;height:100%;}
body {
width: 100%;
color:#707070;
background-color: #FFF;
webkit-tap-highlight-color: rgba(255,255,255,.2);
}
html {
width: 100%;
}
@font-face {font-family: 'mmFont';src: url('../fonts/mmFont.ttf') format('truetype');font-weight: normal;font-style: normal;}
[class^="icon-mm-"],
[class*=" icon-mm-"] {
font-family: 'mmFont', sans-serif;
font-weight: normal;
font-style: normal;
text-decoration: inherit;
font-size: 1em;
-webkit-font-smoothing: antialiased;
}
.icon-mm-logo:before{content: "\e602";}
::-moz-selection {
text-shadow: none;
background: #fcfcfc;
background: rgba(255,255,255,.2);
}
::selection {
text-shadow: none;
background: #fcfcfc;
background: rgba(255,255,255,.2);
}
img::selection {
background: 0 0;
}
img::-moz-selection {
background: 0 0;
}
h1 {
font-size:3.2em;
margin: 0 0 35px;
font-weight: 200;
letter-spacing: 1px;
color:#A5A5A5;
vertical-align: middle;
}
h1 i{font-size:1em;position:relative;top:4px; color: #83c849;margin:0;padding:0;}
p {
margin: 0 0 25px;
font-size: 18px;
line-height: 1.5;
}
@media(min-width:767px) {
p {
margin: 0 0 35px;
font-size: 20px;
line-height: 1.6;
}
}
a {
color: #eaeaea;
-webkit-transition: all .2s ease-in-out;
-moz-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
a:hover,
a:focus {
color: #fdfdfd;
text-decoration: none;
}
.green {
font-weight: 200;
color: #83c849;
}
.sml{font-size:.85em;}
.navbar-mm {
margin-bottom: 0;
border-bottom: 1px solid rgba(255,255,255,.3);
}
.navbar-mm .navbar-brand {
font-size:2em;
}
.navbar-mm .navbar-brand:focus {
outline: 0;
}
.navbar-mm .navbar-brand .navbar-toggle {
padding: 4px 6px;
font-size: 16px;
color: #707070;
}
.navbar-mm .navbar-brand .navbar-toggle:focus,
.navbar-mm .navbar-brand .navbar-toggle:active {
outline: 0;
}
.navbar-mm a {
color: #707070;
}
.navbar-mm .nav li.active {
outline: nonte;
background-color: rgba(255,255,255,.3);
}
.navbar-mm .nav li a {
-webkit-transition: background .3s ease-in-out;
-moz-transition: background .3s ease-in-out;
transition: background .3s ease-in-out;
padding:2px;
margin:20px 5px;
color:#E0E0E0;
}
.navbar-mm .nav li a:hover,
.navbar-mm .nav li a:focus,
.navbar-mm .nav li a.active {
outline: 0;
background-color: rgba(255,255,255,.3);
color: #83c849;
text-decoration:underline;
}
@media(min-width:767px) {
.navbar {
padding: 20px 0;
border-bottom: 0;
letter-spacing: 1px;
background: 0 0;
-webkit-transition: background .5s ease-in-out,padding .5s ease-in-out;
-moz-transition: background .5s ease-in-out,padding .5s ease-in-out;
transition: background .5s ease-in-out,padding .5s ease-in-out;
}
.top-nav-collapse {
padding: 0;
background-color: #000;
}
.navbar-custom.top-nav-collapse {
border-bottom: 1px solid rgba(255,255,255,.3);
}
}
.login-container {
display: table;
width: 100%;
height: 100%;
padding:0;
text-align: center;
color: #707070;
background: rgb(254,255,255);
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIzNiUiIHN0b3AtY29sb3I9IiNmZWZmZmYiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjODNjODQ5IiBzdG9wLW9wYWNpdHk9IjEiLz4KICA8L2xpbmVhckdyYWRpZW50PgogIDxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9InVybCgjZ3JhZC11Y2dnLWdlbmVyYXRlZCkiIC8+Cjwvc3ZnPg==);
background: -moz-linear-gradient(top, rgba(254,255,255,1) 36%, rgba(131,200,73,1) 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(36%,rgba(254,255,255,1)), color-stop(100%,rgba(131,200,73,1)));
background: -webkit-linear-gradient(top, rgba(254,255,255,1) 36%,rgba(131,200,73,1) 100%);
background: -o-linear-gradient(top, rgba(254,255,255,1) 36%,rgba(131,200,73,1) 100%);
background: -ms-linear-gradient(top, rgba(254,255,255,1) 36%,rgba(131,200,73,1) 100%);
background: linear-gradient(to bottom, rgba(254,255,255,1) 36%,rgba(131,200,73,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#feffff', endColorstr='#83c849',GradientType=0 );
}
.login-container .intro-body {
display: table-cell;
vertical-align: middle;
}
.login-container .intro-body .brand-heading {
font-size: 40px;
}
.login-container .intro-body .intro-text {
font-size: 18px;
}
@media(min-width:767px) {
.login-container {
height: 100%;
padding: 0;
}
.login-container .intro-body .brand-heading {
font-size: 100px;
}
.login-container .intro-body .intro-text {
font-size: 25px;
}
}
.input-group-addon{color:#A5A5A5;text-shadow:#FFFFFF 0 1px 0;}
.iga-focuss{color:green;text-shadow:#FFFFFF 0 1px 0;}
.btn {
-webkit-transition: all .3s ease-in-out;
-moz-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.btn-default {
border: 1px solid #219ab3;
color: #219ab3;
background-color: transparent;
}
.btn-default:hover,
.btn-default:focus {
border: 1px solid #219ab3;
outline: 0;
color: #000;
background-color: #219ab3;
}
.btn-mm {
border: 1px solid #b4e58b;
color: #83c849;
background-color: transparent;
}
.btn-mm:hover,
.btn-mm:focus {
border: 1px solid #83c849;
outline: 0;
color: #FFF;
background-color: #83c849;
}
.bmm {
border: 1px solid #CCC;
color: #CCC;
background-color: transparent;
}
.bmm:hover,
.bmm:focus {
border: 1px solid #CCC;
outline: 0;
color: #CCC;
background-color: #CCC;
}
ul.banner-social-buttons {
margin-top: 0;
}
@media(max-width:1199px) {
ul.banner-social-buttons {
margin-top: 15px;
}
}
@media(max-width:767px) {
ul.banner-social-buttons li {
display: block;
margin-bottom: 20px;
padding: 0;
}
ul.banner-social-buttons li:last-child {
margin-bottom: 0;
}
}
.panel-heading h3{
color:#707070;
font-weight:bold;
text-shadow:#FFFFFF 0 1px 0;}
footer{
position:fixed;
bottom:0;
padding:20px 0;
background:transparent;
border-top:1px solid #b4e58b;
width:100%;
}
footer p {
margin: 0;
font-size:1em;
color:#f8f8f8;
}
<|start_filename|>mapmint-ui/templates/preview/modules/other_tools/default.js<|end_filename|>
#import mapfile.service as mms
/*zoomTo slider*/
var numzoomlevels = map.getNumZoomLevels();
System.slider = \$('span.slider').slider({
orientation: "vertical",
range: "min",
animate: true,
min: System.initZoomLevel/*-1*/,
max: numzoomlevels,
value: map.getZoom(),
step: 1,
slide: function(event, ui) {
map.zoomTo(ui.value);
},
change: function(event, ui) {
map.zoomTo(ui.value);
}
}).hover(function(){
#if $mms.getMetadata($m.web,'layout_t')!="mobile"
\$('.ui-slider-vertical .ui-slider-handle').tipsy({live: true,title: function() { return (map.getZoom()); }, gravity: 'w'})
#end if
});
/*zoom controls*/
\$('a.zoomTo_in').click(function(ev){
ev.stopPropagation();
ev.preventDefault();
var tmp=System.slider.slider("option",'value');
System.slider.slider("option",'value', tmp + 1);
return false;
});
\$('a.zoomTo_out').click(function(ev){
ev.stopPropagation();
ev.preventDefault();
var tmp=System.slider.slider('option','value');
System.slider.slider('option','value', tmp - 1);
return false;
});
<|start_filename|>mapmint-ui/new-themes/themes/pink/window.css<|end_filename|>
.panel-tool-close{
background:url('../img/panel_tools-pink.gif') no-repeat -16px 0px;
}
.panel-tool-min{
background:url('../img/panel_tools-pink.gif') no-repeat 0px 0px;
}
.panel-tool-max{
background:url('../img/panel_tools-pink.gif') no-repeat 0px -16px;
}
.panel-tool-restore{
background:url('../img/panel_tools-pink.gif') no-repeat -16px -16px;
}
.panel-tool-collapse{
background:url('../img/panel_tool_collapse-pink.gif') no-repeat;
}
.panel-tool-expand{
background:url('../img/panel_tool_expand-pink.gif') no-repeat;
}
.panel-loading{
padding:11px 0px 10px 30px;
background:url('../img/panel_loading.gif') no-repeat 10px 10px;
}
a.l-btn:hover{
color:#FFFFFF;
text-shadow: #777777 0px 1px 0px;
background: #f630f8; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f869ec', endColorstr='#f630f8'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#f869ec), to(#f630f8)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
}
<|start_filename|>mapmint-services/wfs-t-src/Makefile<|end_filename|>
PREFIX=/usr/local
XSLT_LDFLAGS=-lxslt -lxml2
ZOO_DIR=/home/src/zoo/zoo-project/zoo-kernel
ZRPATH=/home/src/zoo/zoo-project/zoo-kernel/../
include ${ZRPATH}/zoo-kernel/ZOOMakefile.opts
CPPFLAGS := -DUSE_CAIRO -DUSE_KML -DUSE_MS -I${ZOO_DIR}
BIN_LIST = cgi-env/wfst_sp.zo
default : $(BIN_LIST)
cgi-env/wfst_sp.zo: service.c
g++ ${XML2_CPPFLAGS} ${GDAL_CFLAGS} ${MS_CFLAGS} ${CPPFLAGS} -shared -fpic $< ${XSLT_LDFLAGS} ${XML2LDFLAGS} ${ZRPATH}/zoo-kernel/${MS_FILE} ${MS_LIB} -lc -lcrypto -lcurl -lfcgi -o $@ ${GDAL_LIBS}
install:
install -d ${PREFIX}/wfs-t/
install $(BIN_LIST) ${PREFIX}/wfs-t/
install cgi-env/*.zcfg ${PREFIX}/wfs-t/
cd ${PREFIX}/wfs-t/ && ln -s ../main.cfg
cd ${PREFIX}/wfs-t/ && ln -s ../ZOO-api.js
cd ${PREFIX}/wfs-t/ && ln -s ../ZOO-proj4js.js
clean :
rm -f cgi-env/*zo
<|start_filename|>public_map/assets/js/indicators.js<|end_filename|>
// Filename: login.js
define([
'module', 'jquery', 'zoo','notify', 'metisMenu', 'summernote', 'xml2json','typeahead', 'adminBasic', 'ol','datasources','mmDataTables','rowReorder','colorpicker','slider',"sortable","colReorder","managerTools"
], function(module, $,Zoo,notify, metisMenu, summernote, X2JS,typeahead,adminBasic,ol,datasources,MMDataTable,rowReorder,colorpicker,slider,sortable,colReorder,managerTools) {
(function(){
var methods = ['addClass', 'removeClass'];
$.each(methods, function (index, method) {
var originalMethod = $.fn[method];
$.fn[method] = function () {
var oldClass = this.className;
var result = originalMethod.apply(this, arguments);
var newClass = this.className;
this.trigger(method, [oldClass, newClass]);
return result;
};
});
})();
var _x2js = new X2JS({
arrayAccessFormPaths: [
'ProcessDescriptions.ProcessDescription.DataInputs.Input',
'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
'Capabilities.ServiceIdentification.Keywords'
],
});
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
language: module.config().language
});
var llevels=["first","second","third","forth"];
var llevelInit=false;
var reg0=new RegExp("documents_","");
var reloadElement=true;
var tableName="indicators";
var fileName="";
function loadElements(table,init){
zoo.execute({
identifier: "np.list",
type: "POST",
dataInputs: [
{"identifier": "table","value": table,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
if(!reloadElement)
return;
if(init){
if($("#listElements").find("#document_"+localId).length){
console.log($("#listElements").find("#document_"+localId).hasClass("selected"));
if(!$("#listElements").find("#document_"+localId).hasClass("selected"))
$("#listElements").find("#document_"+localId).click();
else{
for(var i=0;i<2;i++)
$("#listElements").find("#document_"+localId).click();
}
}else{
loadAnElement(localId);
}
}
else
for(var i=0;i<data.length;i++){
if(data[i]["selected"]){
if($("#listElements").find("#document_"+data[i]["id"]).length){
$("#listElements").find("#document_"+data[i]["id"]).click();
}else{
loadAnElement(data[i]["id"]);
}
break;
}
}
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function fileUrlSelection(data){
$("input#file").val("");
if(data["url"]==null){
$("input[name=doct]").first().prop("checked",true);
$("input[name=doct]").first().click();
$("#documents_file_link").attr("href",module.config().publicationUrl+"/documents/"+data["file"]);
$("#documents_file_link").html(data["file"]);
}
else{
$("input[name=doct]").last().prop("checked",true);
$("input[name=doct]").last().click();
$("#documents_file_link").attr("href","");
$("#documents_file_link").html("");
}
}
function fillForm(data){
$(".project-title").html(data["name"]+' <i class="fa fa-'+(data["published"]=="false"?"exclamation":"check")+'"> </i>');
var myRootLocation=$(".theForm");
var reg=new RegExp("documents_","");
myRootLocation.find("textarea").each(function(){
if(!$(this).attr("id"))
return;
if($(this).attr("id").replace(reg,"")=="description"){
$(this).code(data[$(this).attr("id").replace(reg,"")]);
}
else
$(this).val(data[$(this).attr("id").replace(reg,"")]).change();
});
myRootLocation.find("input[type=text],select").each(function(){
if(!$(this).attr("id"))
return;
if($(this).attr("type")=="text"){
if($(this).attr("id").replace(/color/g,"")!=$(this).attr("id")){
if(data[$(this).attr("id").replace(reg,"")])
$(this).val("#"+data[$(this).attr("id").replace(reg,"")]).change();
else
$(this).val("#000").change();
}
else
$(this).val(data[$(this).attr("id").replace(reg,"")])
}else{
$(this).find('option').prop('selected', false);
if($.isArray(data[$(this).attr("id").replace(reg,"")])){
var obj=data[$(this).attr("id").replace(reg,"")];
var oid=$(this).attr("id").replace(reg,"");
if(obj.length==0)
$(this).find('option[value="-1"]').prop("selected",true);
for(var i=0;i<obj.length;i++){
$(this).find('option[value="'+obj[i]+'"]').prop("selected",true);
}
}else{
$(this).val((data[$(this).attr("id").replace(reg,"")]!=null?data[$(this).attr("id").replace(reg,"")]:-1));
}
}
});
}
function fillGraphForm(data){
var myRootLocation=$("#indicators_form_pie-chart");
var prefix="documents_graphs_";
myRootLocation.find("input[type=text],input[type=hidden],select,textarea").each(function(){
if(!$(this).attr("id"))
return;
var myReg=new RegExp(prefix,"g");
var cid=$(this).attr("id").replace(myReg,"");
console.log(cid);
if($(this).attr("type")=="text" || !$(this).attr("type") || $(this).attr("type")=="hidden"){
if(cid.replace(/color/g,"")!=cid){
if(data[cid])
$(this).val("#"+data[cid]).change();
else
$(this).val("#000").change();
}
else
$(this).val(data[cid])
}else{
$(this).find('option').prop('selected', false);
if($.isArray(data[cid])){
var obj=data[cid];
var oid=cid;
if(obj.length==0)
$(this).find('option[value="-1"]').prop("selected",true);
for(var i=0;i<obj.length;i++){
$(this).find('option[value="'+obj[i]+'"]').prop("selected",true);
}
}else{
$(this).val((data[cid]!=null?data[cid]:-1));
}
}
});
}
function fillDefaultRepport(data){
var myRootLocation=$("#indicators_form_file-text-o");
var lines="";
var freg=new RegExp("\\[content\\]","g");
var regs=[
new RegExp("\\[x\\]","g"),
new RegExp("\\[name\\]","g")
];
var tmpl=$("#document_settings_line_template")[0].innerHTML;
for(var i=0;i<data.length;i++){
lines+=tmpl.replace(regs[0],i).replace(regs[1],data[i]);
}
var content=$("#document_settings_container_template")[0].innerHTML.replace(freg,lines);
$("#documents_repport_editor").html(content);
var defaultTypes={
"map": 1,
"table": 3,
"diag": 4
};
var noOptionTypes=[
"1","2","5","6","7"
];
$("#documents_repport_editor").find("table").find("select").each(function(){
if(defaultTypes[$(this).parent().prev().find('input').val()]){
$(this).val(defaultTypes[$(this).parent().prev().find('input').val()]);
$(this).prop("disabled",true);
$(this).parent().prev().prev().find('input').prop("disabled",true);
$(this).parent().next().find('textarea').hide();
}else{
$(this).change(function(){
if($.inArray($(this).val(),noOptionTypes)>=0)
$(this).parent().next().find("textarea").hide();
else
$(this).parent().next().find("textarea").show();
});
}
});
$("#documents_repport_editor").find("table").DataTable({
"bPaginate": false,
"bFilter": false,
"bInfo": false,
"bAutoWidth": false,
"scrollY": ($(window).height()/2)+"px",
});
$("[data-mmaction=save-doc]").click(function(){
saveRepport();
});
}
function fillRepport(data){
for(var i=0;i<data.length;i++){
for(var a in data[i]){
if($("#rtable_"+a+"_"+i).attr("type")!="checkbox")
$("#rtable_"+a+"_"+i).val(data[i][a]);
else
$("#rtable_"+a+"_"+i).prop("checked",data[i][a]);
}
}
}
function saveRepport(){
var params=[
{identifier: "id", value: localId, dataType: "sring"}
];
if(arguments.length>0)
params.push({name: "tid", value: $("#p_tname").val(), dataType: "sring"});
$("#repport_display2").find("input[type=checkbox]").each(function(){
var tmp=($(this).attr("id")+"").split('_');
var params0={identifier: "tuple", value:'{"id":'+tmp[tmp.length-1]+',"display":"'+$(this).is(":checked")+'","var":"'+$("#rtable_name_"+tmp[tmp.length-1]).val()+'","type":'+$("#rtable_type_"+tmp[tmp.length-1]).val()+',"value":"'+ $("#rtable_value_"+tmp[tmp.length-1]).val()+'"}',mimeType: "application/json"};
var obj={
"id":tmp[tmp.length-1],
"display":$(this).is(":checked")+"",
"var":$("#rtable_name_"+tmp[tmp.length-1]).val(),
"type":$("#rtable_type_"+tmp[tmp.length-1]).val(),
"value":$("#rtable_value_"+tmp[tmp.length-1]).val()
};
params.push({identifier: "tuple", value:JSON.stringify(obj, null, ' '),mimeType: "application/json"});
});
if($("#repport_steps").is(":visible") && $("#repport_step").val()>0){
params.push({identifier: "step", value: ($("#repport_step")[0].selectedIndex-1), dataType: "sring"});
}
if($('#agregation').is(":visible") && $("#agregate_step")[0].selectedIndex-1>=0) {
params.push({identifier: "step", value: ($("#agregate_step")[0].selectedIndex-1), dataType: "sring"});
}
callService("np.saveRepportSettings",params,function(data){
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
});
}
function loadAnElement(id){
localId=id;
//console.log("loadATheme -> "+id);
$(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.details",
type: "POST",
dataInputs: [
{"identifier": "table","value": tableName,"dataType":"string"},
{"identifier": "id","value": id,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
fileUrlSelection(data);
$("#indicatorForm").find(".nav").find("li").first().trigger("click");
if(data.it_id){
console.log(data["_style"]);
//managerTools.loadStyleDisplay(data["_style"]);
//bindClassifier(data["_style"]);
fetchIndexTableAndDisplay(data["_style"],function(d){
var lcnt0=0;
$("#layer_property_table_table_display_wrapper").find("table tbody").find("tr").each(function(){
var lcnt=0;
var fields=["pos","display","search","var","label","value","width"]
if(data["_table"]["fields"])
$(this).find("td").each(function(){
if($(this).find("input").length){
if($(this).find("input").attr("type")!="checkbox")
$(this).find("input").val(data["_table"]["fields"][lcnt0][fields[lcnt]]);
else
$(this).find("input").prop("checked",data["_table"]["fields"][lcnt0][fields[lcnt]]);
}
if(lcnt==3){
var tmp=$(this).children().first().html();
$(this).html(data["_table"]["fields"][lcnt0][fields[lcnt]]+tmp);
}
lcnt+=1;
});
lcnt0+=1;
});
if(data["_repport"]["docFields"]){
$("#documents_afile_link").attr("href",data["_repport"]["doc"]);
$("#documents_afile_link").attr("href",data["_repport"]["docUrl"]).text(data["_repport"]["docUrl"]);
fillDefaultRepport(data["_repport"]["docFields"]);
if(data["_repport"]["fields"])
fillRepport(data["_repport"]["fields"]);
}else{
}
if(data["_table"]["id"]){
$("#documents_table_title").val(data["_table"]["title"]);
$("#documents_table_id").val(data["_table"]["id"]);
}else{
$("#documents_table_title").val("");
$("#documents_table_id").val(-1);
}
fillGraphForm(data["_graph"]);
});
$("#documents_indicators_table").val(data["indicators_territories"]).change();
console.log(data["query"]);
console.log(data["query"]);
console.log(data["query"]!=null);
console.log((data["query"]?"query":"file"));
//$("input[name=indicator_data_type]").val((data["query"]?"query":"file")).change();
$("input[name=indicator_data_type]").each(function(){
console.log((data["query"]?"query":"file"));
console.log($(this).val()==(data["query"]?"query":"file"));
if($(this).val()==(data["query"]?"query":"file"))
$(this).trigger("click");
});
var fields=["query"];
for(var i=0;i<fields.length;i++)
$("#documents_data_"+fields[i]).val(data[fields[i]]);
console.log($("#DS_indicatorTable_indicator"));
if(data["file_link"] && !data["query"]){
$("#documents_ifile_link").attr("href",data["file_url"]).text(data["file_name"]);
fetchInfoAndDisplay(data["file_link"]);
}else{
if(data["query"])
runSql(true);
else{
$("#DS_indicatorTable_indicator").remove();
$("#documents_ifile_link").attr('href','#').text('');
}
}
var lcnt=0;
$("#indicatorForm").find('.nav').first().find('[role=presentation]').each(function(){
if(lcnt>1){
$(this).removeClass("disabled");
$(this).prop("disabled",false);
}
lcnt+=1;
});
}else{
console.log($("#DS_indicatorTable_indicator"));
$("#DS_indicatorTable_indicator").remove();
$("#documents_ifile_link").attr('href','#').text('');
var lcnt=0;
console.log($("#indicatorForm").find('.nav').first());
console.log($("#indicatorForm").find('.nav').first().find('[role=presentation]'));
$("#indicatorForm").find('.nav').first().find('[role=presentation]').each(function(){
if(lcnt>1){
$(this).prop("disabled",true);
$(this).addClass("disabled");
}
lcnt+=1;
});
}
$(".fa-spin").addClass("hide");
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function createJsonFromForm(form){
var params={};
form.find('textarea').each(function(){
if(!$(this).attr("id"))
return;
var cid=$(this).attr('id').replace(reg0,"");
if(cid=="description")
params[cid]=$(this).code();
else
params[cid]=$(this).val();
});
form.find('input[type="text"]').each(function(){
if(!$(this).attr("id") || $(this).attr("id")=="indicators_keywords")
return;
if($(this).attr("id").replace(/color/g,"")!=$(this).attr("id"))
params[$(this).attr('id').replace(reg0,"")]=$(this).val().replace(/#/,"");
else
params[$(this).attr('id').replace(reg0,"")]=$(this).val();
});
form.find('select').each(function(){
if(!$(this).attr("id"))
return;
if($(this).find("option:selected").length>1){
params[$(this).attr('id').replace(reg0,"")]=[];
var oid=$(this).attr('id').replace(reg0,"");
$(this).find("option:selected").each(function(){
params[oid].push($(this).val());
});
}else
params[$(this).attr('id').replace(reg0,"")]=$(this).val();
});
return params;
}
function bindSave(){
$(".theForm").find("button").click(function(){
$('#documents_filename').val($('#file').val());$('#fileUpload').submit();
});
}
var lid="listElements";
function saveAnElement(){
var id=localId;
$(".fa-spin").removeClass("hide");
var obj=createJsonFromForm($(".theForm"));
obj["id"]=id;
localId=id;
obj["filename"]=$('input#file').val();
localInit=true;
zoo.execute({
identifier: "np.updateElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": tableName,"dataType":"string"},
{"identifier": "keywords", value: $("#indicators_keywords").val(),dataType: "string"},
{"identifier": "indicators_groups_in", value: "i_id",dataType: "string"},
{"identifier": "indicators_groups_out", value: "g_id",dataType: "string"},
{"identifier": "indicators_themes_in", value: "i_id",dataType: "string"},
{"identifier": "indicators_themes_out", value: "t_id",dataType: "string"},
{"identifier": "tuple","value": JSON.stringify(obj, null, ' '),"mimeType":"application/json"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
$(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
reloadElement=true;
$("#"+lid).dataTable().fnDraw();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function addAnElement(){
$(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.insertElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": tableName,"dataType":"string"},
{"identifier": "name","value": $("#adder").find('input[name="dname"]').val(),"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
$(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
localInit=false;
reloadElement=true;
$("#"+lid).dataTable().fnDraw();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function deleteAnElement(id){
$(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.deleteElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": tableName,"dataType":"string"},
{"identifier": "atable","value": "documents_themes","dataType":"string"},
{"identifier": "akey","value": "d_id","dataType":"string"},
{"identifier": "atable","value": "documents_groups","dataType":"string"},
{"identifier": "akey","value": "d_id","dataType":"string"},
{"identifier": "id","value": id,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
$(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
localInit=false;
reloadElement=true;
$("#"+lid).dataTable().fnDraw();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
var localInit=false;
var localItem=-1;
function startDataTable(rfields,fields){
var cnt=0;
var CRowSelected=[];
var CFeaturesSelected=[];
var CFeatures=[];
var lid="listElements";
$('#listElements').DataTable( {
language: {
url: module.config().translationUrl
},
data: [],
"dom": 'Zlfrtip',
"colResize": true,
autoWidth: false,
"scrollY": ($(window).height()/2)+"px",
"scrollCollapse": true,
"scrollX": true,
//"sScrollX": "100%",
//"sScrollXInner": "100%",
"bAutoWidth": false,
"bProcessing": true,
"bServerSide": true,
fixedHeader: true,
//searching: true,
responsive: true,
deferRender: true,
crollCollapse: true,
ordering: "id",
rowId: 'fid',
"sAjaxSource": "users",
select: {
info: false,
},
"lengthMenu": [[5, 10, 25, 50, 1000], [5, 10, 25, 50, "All"]],
columns: fields,
"rowCallback": function( row, data ) {
$(row).removeClass('selected');
if ( $.inArray(data.DT_RowId, CRowSelected) !== -1 ) {
$('#'+lid).DataTable().row($(row)).select();
}else{
$('#'+lid).DataTable().row($(row)).deselect();
}
},
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
var llimit=[];
for(j in {"iDisplayStart":0,"iDisplayLength":0,"iSortCol_0":0,"sSortDir_0":0,"sSearch":0})
for(i in aoData)
if(aoData[i].name==j){
if(llimit.length==4 && aoData[i].value!="")
llimit.push(aoData[i].value);
if(llimit.length<4)
llimit.push(aoData[i].value);
}
var closestproperties=rfields;
var page=llimit[0]+1;
if(page!=1){
page=(llimit[0]/llimit[1])+1;
}
var opts=zoo.getRequest({
identifier: "datastores.postgis.getTableContent",
dataInputs: [
{"identifier":"dataStore","value":module.config().db,"dataType":"string"},
{"identifier":"table","value":"mm.indicators","dataType":"string"},
{"identifier":"offset","value":llimit[0],"dataType":"int"},
{"identifier":"limit","value":llimit[1],"dataType":"int"},
{"identifier":"page","value":page,"dataType":"int"},
{"identifier":"sortorder","value":llimit[3],"dataType":"string"},
{"identifier":"search","value":llimit[llimit.length-1],"dataType":"string"},
{"identifier":"sortname","value":(closestproperties.split(",")[llimit[2]]),"dataType":"string"},
{"identifier":"fields","value":closestproperties.replace(/,msGeometry/g,""),"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","mimeType":"application/json","type":"raw"}
],
type: 'POST',
storeExecuteResponse: false
});
opts["success"]=function(rdata) {
features=rdata;
featureCount=rdata["total"];
var data=[];
CFeatures=[];
for(var i in features.rows){
var lparams={
"fid": "document_"+features.rows[i].id
}
var tmp=rfields.split(',');
for(var kk=0;kk<tmp.length;kk++)
lparams[tmp[kk]]=features.rows[i].cell[kk];
data.push(lparams);
CFeatures.push(data[data.length-1]);
}
var opts={
"sEcho": cnt++,
"iDraw": cnt++,
"iTotalRecords": featureCount,
"iTotalDisplayRecords": featureCount,
"aaData": (featureCount>0?data:[])
};
fnCallback(opts);
for(d in data){
if ( $.inArray(data[d].fid+"", CRowSelected) !== -1 ) {
$('#'+lid).DataTable().row($("#"+data[d].fid)).select();
}else{
$('#'+lid).DataTable().row($("#"+data[d].fid)).deselect();
}
}
if(featureCount==0){
$('#'+lid+'Table').DataTable().clear();
}
var existing=$('#'+lid+'_info').children('span.select-info');
if(existing.length)
existing.remove();
$('#'+lid+'_info').append($('<span class="select-info"/>').append(
$('<span class="select-item"/>').append('dd rows selected'.replace(/dd/g,CRowSelected.length))
));
loadElements(tableName,localInit);
};
opts["error"]=function(){
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
};
oSettings.jqXHR = $.ajax( opts );
}
});
var ltype="document";
//var myRootElement=$('#'+lid).parent().find(".btn-group").first().parent();
$('#'+lid+' tbody').on('click', 'tr', function () {
if(!this.id)
return;
var id = this.id+"";
var reg0=new RegExp(ltype+'s_',"g");
var index = $.inArray(id, CRowSelected);
if ( index == -1 ) {
if(CRowSelected.length>0){
$('#'+lid).DataTable().row($("#"+CRowSelected[0])).deselect();
CRowSelected.pop(CRowSelected[0]);
CFeaturesSelected.pop(CFeaturesSelected[0]);
}
/*if(CFeaturesSelected.length==0)
myRootElement.find(".require-select").removeClass("disabled");*/
CRowSelected.push( id );
$('#'+lid).DataTable().row("#"+id).select();
for(var i=0;i<CFeatures.length;i++){
if(CFeatures[i]["fid"]==id)
CFeaturesSelected.push( CFeatures[i] );
}
reg=new RegExp(ltype+"_","g");
localId=id.replace(reg,"");
reloadElement=false;
loadAnElement(localId);
} else {
$("."+lid+"BaseEditForm").removeClass("in");
CRowSelected.pop(index);
CFeaturesSelected.pop(index);
$('#'+lid).DataTable().row("#"+id).deselect();
}
var existing=$('#'+lid+'_info').children('span.select-info');
if(existing.length)
existing.remove();
$('#'+lid+'_info').append($('<span class="select-info"/>').append(
$('<span class="select-item"/>').append((CFeaturesSelected.length!=CRowSelected.length?'dd rows selected (ee total selected)'.replace(/dd/g,CRowSelected.length).replace(/ee/g,CFeaturesSelected.length):'dd rows selected'.replace(/dd/g,CRowSelected.length)))
));
});
}
function runSql(execute,dbname,sql){
zoo.execute({
identifier: (execute?"np.createTempFile":"np.testQuery"),
type: "POST",
dataInputs: [
{"identifier":(execute?"map":"dbname"),"value":(dbname?dbname:$("#documents_indicators_database").val()),"dataType":"string"},
{"identifier":(execute?"sql":"query"),"value":(sql?sql:$("#documents_data_query").val()),"dataType":"integer"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
if(execute)
fetchInfoAndDisplay(data);
else
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
var fetchInfoAndDisplay=function(data){
fileName=data;
var ldata=data;
zoo.execute({
identifier: "vector-tools.mmVectorInfo2Map",
type: "POST",
dataInputs: [
{"identifier":"dataSource","value":ldata,"dataType":"string"},
{"identifier":"force","value":"1","dataType":"integer"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
if(data.datasource){
var val="";
$("select[name=ifile_page]").html('');
if($.isArray(data.datasource.layer)){
for(var i=0;i<data.datasource.layer.length;i++){
if(i==0)
val=data.datasource.layer[i].name;
$("select[name=ifile_page]").append("<option>"+data.datasource.layer[i].name+"</option>");
}
$("select[name=ifile_page]").change(function(){
var lval=$(this).val();
getVectorInfo(ldata,$(this).val(),function(data){
var reg=new RegExp("\\[datasource\\]","g");
var reg1=new RegExp("\\[font\\]","g");
font="fa fa-table";
console.log("FONT !! "+font);
console.log($("#DS_indicatorTable_indicator"));
if($("#DS_indicatorTable_indicator").length)
$("#DS_indicatorTable_indicator").remove();
$("[data-mmaction=join]").first().parent().append($($("#dataSource_template")[0].innerHTML.replace(reg1,font).replace(reg,val)).attr("id","DS_indicatorTable_indicator"));
managerTools.displayVector(data,ldata,"indicatorTable","indicator",lval,
function(){
$("#DS_indicatorTable_indicator").find(".panel").addClass("panel-warning").removeClass("panel-default");
$("[data-mmaction=join]").addClass("disabled");
},
function(){
$("#DS_indicatorTable_indicator").find(".panel").removeClass("panel-warning").addClass("panel-default");
$("[data-mmaction=join]").removeClass("disabled");
});
});
});
$("select[name=ifile_page]").find('option').first().prop("selected",true).change();
}else{
val=data.datasource.layer.name;
$("select[name=ifile_page]").append("<option>"+val+"</option>");
}
getVectorInfo(ldata,val,function(data){
var reg=new RegExp("\\[datasource\\]","g");
var reg1=new RegExp("\\[font\\]","g");
font="fa fa-table";
console.log("FONT !! "+font);
console.log($("#DS_indicatorTable_indicator"));
if($("#DS_indicatorTable_indicator").length)
$("#DS_indicatorTable_indicator").remove();
$("[data-mmaction=join]").first().parent().append($($("#dataSource_template")[0].innerHTML.replace(reg1,font).replace(reg,val)).attr("id","DS_indicatorTable_indicator"));
managerTools.displayVector(data,ldata,"indicatorTable","indicator",val,
function(){
$("#DS_indicatorTable_indicator").find(".panel").addClass("panel-warning").removeClass("panel-default");
$("[data-mmaction=join]").addClass("disabled");
},
function(){
$("#DS_indicatorTable_indicator").find(".panel").removeClass("panel-warning").addClass("panel-default");
$("[data-mmaction=join]").removeClass("disabled");
});
});
}
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function getLastFile(func){
zoo.execute({
identifier: "np.getLastFile",
type: "POST",
dataInputs: [ ],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function getIndicatorInfo(func){
zoo.execute({
identifier: "np.refreshIndex",
type: "POST",
dataInputs: [
{"identifier":"id","value":localId,"dataType":"integer"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function getVectorInfo(dataSource,layer,func){
zoo.execute({
identifier: "vector-tools.mmExtractVectorInfo",
type: "POST",
dataInputs: [
{"identifier":"dataSource","value":dataSource,"dataType":"string"},
{"identifier":"layer","value":layer,"dataType":"integer"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function fetchFields(datasource,func){
zoo.execute({
identifier: "np.getMapRequest0",
type: "POST",
dataInputs: [
{"identifier":"t_id","value":datasource,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
//var obj=_x2js.xml_str2json( data );
console.log(data.schema.complexType.complexContent.extension.sequence.element);
if($.isArray(data.schema.complexType.complexContent.extension.sequence.element)){
$("#documents_indicators_field").html("");
for(var i=0;i<data.schema.complexType.complexContent.extension.sequence.element.length;i++){
var cname=data.schema.complexType.complexContent.extension.sequence.element[i]._name;
if(cname!="msGeometry")
$("#documents_indicators_field").append('<option>'+cname+'</option>');
}
}
if(func)
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
var llcnt=0;
function insertElem(params,func){
zoo.execute({
identifier: "np."+(test?"updateElem":"insertElem"),
type: "POST",
dataInputs: params,
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log(data);
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function callService(service,params,func,outputs){
var dataOutputs=[
{"identifier":"Result","type":"raw"},
];
if(outputs)
dataOutputs=outputs;
zoo.execute({
identifier: service,
type: "POST",
dataInputs: params,
dataOutputs: dataOutputs,
success: function(data){
func(data);
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function fetchIndicatorInfo(lfunc){
getIndicatorInfo(function(data){
$(".class-switcher").off('change');
$(".class-switcher").change(function(){
console.log(".class-switcher CHANGE ! "+llcnt);
llcnt+=1;
var myRootLocation=$(this).parent().parent().parent();
var index=0;
var hasElement=true;
var closure=$(this);
myRootLocation.find('.no-us').show();
myRootLocation.find('.class-switcher').each(function(){
if(closure[0]==$(this)[0]){
hasElement=false;
}
else
if(hasElement)
index+=1;
});
$(this).find('option').each(function(){
if(!$(this).is(':selected'))
myRootLocation.find('.no-'+$(this).attr('value')).show();
});
$(this).find('option:selected').each(function(){
myRootLocation.find('.no-'+$(this).attr('value')).hide();
});
if(index>0)
myRootLocation.find(".require-tl").show();
if(data.type!=3)
myRootLocation.find(".require-raster").hide();
myRootLocation.find(".require-add-step").hide();
});
managerTools.displayVector(data,module.config().db,"indicatorTable","dataTable","indexes.view_idx"+localId,
function(){
$("#DS_indicatorTable_dataTable").find(".panel").addClass("panel-warning").removeClass("panel-default");
},
function(){
$("#DS_indicatorTable_dataTable").find(".panel").removeClass("panel-warning").addClass("panel-default");
});
//$(".class-switcher").trigger("change");
if(lfunc)
lfunc(data);
});
}
function fetchIndexTableAndDisplay(ldata,func){
managerTools.getTableDesc(module.config().msUrl,module.config().dataPath+"/PostGIS/"+module.config().db+"ds_ows.map","indexes.view_idx"+localId,ldata,function(obj,rdata,idata){
managerTools.loadTableDefinition(obj,idata,function(elem){
console.log('toto');
var prefix="";
if(arguments.length>1)
prefix="agregate_";
///var params=produceParams(prefix);
var params=[
{identifier: "table", value: "d_table",dataType: "string"},
{identifier: "name", value: $("#documents_table_title").val(),dataType: "string"},
{identifier: "i_id", value: localId,dataType: "string"}
];
if($("#agregation").is(":visible")){
test=false;
params.push({
identifier: "tid",
value: $("#p_tname").val(),
dataType: "string"
});
}
test=$("#documents_"+prefix+"table_id")[0] && $("#documents_"+prefix+"table_id").val()!='-1' && $("#documents_"+prefix+"table_id").val()!='';
if(test){
params.push({
identifier: "id",
value: localId,
dataType: "string"
});
}
if($("#documents_table_steps").is(":visible") && $("#table_step").val()>0)
params.push({"identifier":"step","value":($("#documents_table_step")[0].selectedIndex-1),dataType: "string"});
$("#mm_layer_property_table_display").find("tbody").find("tr").each(function(){
var params0={
"pos":"",
"display":"",
"search":"",
"var":"",
"label":"",
"value":"",
"width":""
};
var cnt=0;
$(this).find("td").find("input").each(function(){
if($(this).attr('type')=="checkbox"){
var lcnt1=0;
for(var k in params0){
if(lcnt1==cnt)
params0[k]=$(this).prop('checked')+"";
lcnt1+=1;
}
}else{
var lcnt1=0;
for(var k in params0){
if(lcnt1==cnt)
params0[k]=$(this).val();
lcnt1+=1;
}
}
cnt+=1;
});
params.push({
identifier:"tuple",
value:JSON.stringify(params0),
mimeType: "application/json"
});
});
params.push({
"identifier": "map",
"value": $("#save-map").val(),
"dataType": "string"
});
params.push({
"identifier": "layer",
"value": ldata.name,
"dataType": "string"
});
callService("np.saveIndexTable",params,function(data){
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
});
});
console.log("getTableDesc end");
console.log($(".mmFields"));
$(".mmFields,.mmField").html("");
console.log(rdata);
for(var i=0;i<rdata.fields.length;i++){
if(rdata.fields[i]!="msGeometry")
$(".mmFields,.mmField").append('<option>'+rdata.fields[i]+'</option>');
console.log($(".mmFields"));
}
/*$("#indicators_form_table").find("button").first().click(function(){
});*/
if(func)
func(rdata);
managerTools.loadStyleDisplay(ldata,[
{"identifier": "map","value": "Index"+localId,"dataType":"string"},
{"identifier": "prefix","value": "indexes","dataType":"string"},
{"identifier": "name","value": "Index"+localId,"dataType":"string"},
{"identifier": "orig","value": module.config().db,"dataType":"string"},
{"identifier": "id","value": localId,"dataType":"int"},
{"identifier": "formula","value": $('#mm_layer_property_style_display').find("textarea[name=formula]").val(),"dataType":"int"},
]);
bindClassifier(ldata);
});
var reg=new RegExp("\\[datasource\\]","g");
var reg1=new RegExp("\\[font\\]","g");
font="fa fa-table";
if($("#DS_indicatorTable_dataTable").length)
$("#DS_indicatorTable_dataTable").remove();
$("#indicators_form_table").append($($("#dataSource_template")[0].innerHTML.replace(reg1,font).replace(reg,"indexes.view_idx"+localId)).attr("id","DS_indicatorTable_dataTable"));
fetchIndicatorInfo();
}
function bindClassifier(ldata){
$("#mm_layer_property_style_display").find("button.mmClassifier").off("click");
$("#mm_layer_property_style_display").find("button.mmClassifier").click(function(e){
var params=[
{"identifier": "prefix","value": "indexes","dataType":"string"},
{"identifier": "name","value": "Index"+localId,"dataType":"string"},
{"identifier": "orig","value": module.config().db,"dataType":"string"},
{"identifier": "id","value": localId,"dataType":"int"},
{"identifier": "formula","value": $('#mm_layer_property_style_display').find("textarea[name=formula]").val(),"dataType":"int"},
];
try{
managerTools.classifyMap(this,"Index"+localId,ldata,params,function(data){
console.log(data);
});
}catch(e){
console.log(e);
}
return false;
});
}
function refreshLayerStyle(){
var params=[
{"identifier":"prefix","value":"indexes","dataType":"string"},
{"identifier":"name","value":"Index"+localId,"dataType":"string"},
{"identifier":"orig","value":module.config().db,"dataType":"string"},
{"identifier":"id","value":localId,"dataType":"string"}
];
console.log(params);
managerTools.callCreateLegend(null,"indexes.view_idx"+localId,null,params,function(data){
console.log(data);
try{
fetchIndexTableAndDisplay(data);
//fetchIndicatorInfo(data);
}catch(e){
console.log(e);
}
console.log(data);
});
}
var initialize=function(){
adminBasic.initialize(zoo);
managerTools.initialize(zoo);
window.setTimeout(function () {
$("textarea#documents_description").summernote();
},10);
$('[data-toggle="tooltip"]').tooltip({container: 'body'});
startDataTable("id,name",[
{
"data": "id",
"name": "id",
"sWidth": "10%"
},
{
"data": "name",
"name": "name",
"sWidth": "80%"
},
]);
bindSave();
$("#adder").find("button").click(function(){
addAnElement();
$("#adder").removeClass("in");
});
$("#deleter").find("button").click(function(){
deleteAnElement(localId);
$("#deleter").removeClass("in");
});
$(".tab-pane").css({"max-height":($(window).height()-($(".navbar").height()*3.5))+"px","overflow-y":"auto","overflow-x":"hidden"});
$("#page-wrapper").find("[role=presentation]").first().children().first().click();
$("[data-mmaction=testSql]").click(function(){
runSql();
});
$("[data-mmaction=runSql]").click(function(){
runSql(true);
});
$("#indicators_form_pie-chart").find("button").last().click(function(){
var prefix="";
/*if(arguments.length>1)
prefix="agregate_"; */
var params=[
{identifier: "table", value: "graphs",dataType: "string"},
{identifier: "name", value: $("#documents_graphs_title").val(),dataType: "string"},
{identifier: "type", value: $("#documents_graphs_type").val(),dataType: "string"},
{identifier: "lx", value: $("#documents_"+prefix+"graphs_lx").val(),dataType: "string"},
{identifier: "vx", value: $("#documents_"+prefix+"graphs_vx").val(),dataType: "string"},
{identifier: "ly", value: $("#documents_"+prefix+"graphs_ly").val(),dataType: "string"},
{identifier: "vy", value: $("#documents_"+prefix+"graphs_vy").val(),dataType: "string"},
{identifier: "tooltip", value: $("#documents_graphs_tooltip").val(),dataType: "string"},
{identifier: "formula", value: $("#documents_graphs_formula").val(),dataType: "string"},
{identifier: "it_id", value: "(SELECT id from "+module.config().dbschema+".indicators_territories where i_id="+localId+($("#agregation").is(":visible")?" and t_id="+$("#p_tname").val():" and (not(agregation) or agregation is null)")+")",dataType: "string"}
];
if($("#agregation").is(":visible")){
test=false;
params.push({
identifier: "tid",
value: $("#p_tname").val(),
dataType: "string"
});
}
test=$("#documents_"+prefix+"graphs_id")[0] && $("#documents_"+prefix+"graphs_id").val()!='-1' && $("#"+prefix+"graphs_id").val()!='';
if(test){
params.push({
identifier: "id",
value: $("#documents_"+prefix+"graphs_id").val(),
dataType: "string"
});
}
if($("#documents_graphs_steps").is(":visible") && $("#graphs_step").val()>0)
params.push({"identifier":"step","value":($("#documents_graphs_step")[0].selectedIndex-1),dataType: "string"});
insertElem(params,function(data){
console.log(data);
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
});
});
$("[data-mmaction=join]").click(function(){
var table=$("#DS_table_indicatorTable_indicator").DataTable();
var params=[];
console.log(table.columns());
console.log(table.columns().name);
var res=[];
var elemChecked=0;
var hasElem=false;
$("input[name=indicator_data_type]").each(function(){
if($(this).is(":checked")){
hasElem=true;
return;
}
if(!hasElem)
elemChecked+=1;
});
console.log(elemChecked);
if(elemChecked==2){
params.push({
identifier: "dbname",
value: $("input[name=documents_database]").val(),
dataType: "string"
});
params.push({
identifier: "query",
value: $("#documents_data_query").val(),
dataType: "string"
});
}
if(elemChecked==1){
params.push({
identifier: "dbname",
value: module.config().db,
dataType: "string"
});
params.push({
identifier: "query",
value: "SELECT * FROM "+$("#pg_table").val(),
dataType: "string"
});
}
for(var i=0;i<table.columns()[0].length;i++){
res.push($(table.column( i ).header()).html());
if(i==0)
params.push({
identifier: "field",
value: $(table.column( i ).header()).html(),
dataType: "string"
});
params.push({
identifier: "rcol",
value: $(table.column( i ).header()).html(),
dataType: "string"
});
var title = table.column( i ).header();
console.log( 'Column title clicked on: '+$(title).html() );
console.log(table.columns()[0][i]);
}
params.push({
identifier: "territory",
value: $("#documents_indicators_table").val(),
dataType: "string"
});
params.push({
identifier: "field",
value: $("#documents_indicators_field").val(),
dataType: "string"
});
params.push({
identifier: "filename",
value: fileName,
dataType: "string"
});
params.push({
identifier: "type",
value: (elemChecked==2?"sql":(elemChecked==1?"table":"file")),
dataType: "string"
});
params.push({"identifier": "sql","value":"SELECT "+res.join(',')+' FROM "'+$("#documents_ifile_page").val()+'"',dataType:"string"});
params.push({"identifier": "layer","value":$("#documents_ifile_page").val(),dataType:"string"});
params.push({"identifier": "id","value":localId,dataType:"string"});
console.log(res);
console.log(params);
zoo.execute({
identifier: "np.createIndex",
type: "POST",
dataInputs: params,
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
/*fetchIndexTableAndDisplay(data,function(data){
refreshLayerStyle();
});*/
fetchIndicatorInfo(function(data){
refreshLayerStyle();
//fetchIndicatorInfo(data);
});
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
});
$("#pg_schema").change(function(){
adminBasic.loadTablesList($("input[name=data_table_dbname]").val(),$(this).val(),$("#pg_table"));
});
$("#pg_table").change(function(){
runSql(true,$("input[name=data_table_dbname]").val(),"SELECT * FROM "+$(this).val());
});
$("#documents_indicators_table").change(function(){
if($(this).val()!=-1)
fetchFields($(this).val());
});
$("[data-mmaction=import-doc]").click(function(){
$("#auploader").off("load");
$("#auploader").on("load",function(){
callService("np.saveRepportFile0",[{"identifier":"id","value":localId,"dataType":"integer"}],function(d){
console.log(d);
$(".notifications").notify({
message: { text: d["ExecuteResponse"]["ProcessOutputs"]["Output"][0]["Data"]["ComplexData"]["__text"] },
type: 'success',
}).show();
var localData=JSON.parse(d["ExecuteResponse"]["ProcessOutputs"]["Output"][1]["Data"]["ComplexData"]["__cdata"]);
fillDefaultRepport(localData);
},[
{"identifier": "Message"},
{"identifier": "Result"}
]);
});
$("#afileUpload").submit();
});
$("[data-mmaction=import]").click(function(){
$("#iuploader").off("load");
$("#iuploader").on("load",function(){
console.log(arguments);
getLastFile(fetchInfoAndDisplay);
});
$("#ifileUpload").submit();
});
$("[data-mmaction=publish]").click(function(){
callService("np.publishFullIndex",[
{identifier:"id",value:localId,dataType:"string"}
],function(data){
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
$("#name_title").removeClass("fa-exclamation").addClass('fa-check');
});
});
console.log($("#page-wrapper").find("[role=presentation]").first());
console.log("Start Indicators");
$("#mm_layer_property_style_display").find(".cpicker").each(function(){
$(this).colorpicker({format: "hex",input: $(this).find("input[type=text]")});
});
};
// Return public methods
return {
initialize: initialize,
saveAnElement: saveAnElement
};
});
<|start_filename|>mapmint-ui/js/login.js<|end_filename|>
$(document).ready(function() {
$(".loader-container").hide();
$.cookie('style', null, { expires: null, path: '/' });
$.cookie('MMID', null, { expires: null, path: '/' });
$.cookie('MMID', null, { expires: null, path: '/' });
$.cookie('MMID', null, { expires: null, path: '/' });
$("#validate").click(function(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=authenticate.logIn&DataInputs=login="+$('#email')[0].value+";password="+$('#password')[0].value+"&RawDataOutput=Result",
dataType: "xml",
complete: function(xml,status) {
if(xml.responseXML){
var elog=$(xml.responseXML).find("ows\\:ExceptionText").text();
if(elog=="")
elog=$(xml.responseXML).find("ExceptionText").text();
$.notifyBar({ cssClass: "error", html: elog});
}
else{
$.notifyBar({ cssClass: "success", html: xml.responseText });
document.location.reload(true);
}
}
});
});
});
<|start_filename|>mapmint-ui/js/np-map.js<|end_filename|>
var map, vectorLayer,osm;
var mybounds;
var wgs84,mercator;
function init(){
map = new OpenLayers.Map('map',
{
controls: [],
displayProjection: new OpenLayers.Projection("EPSG:4326"),
projection: new OpenLayers.Projection("EPSG:900913"),
units: "m",
maxExtent: mybounds
}
);
wgs84=new OpenLayers.Projection("EPSG:4326");
mercator=new OpenLayers.Projection("EPSG:900913");
mybounds = new OpenLayers.Bounds(1.44059549462,48.1108970807,3.56582363189,49.248280617).transform(wgs84,mercator);
arrayOSM = ["http://otile1.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png",
"http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png",
"http://otile3.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png",
"http://otile4.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png"];
osm=new OpenLayers.Layer.OSM("MapQuest Streets", arrayOSM, {attribution: "Données <a href='http://www.mapquest.com/' target='_blank'><img src='http://developer.mapquest.com/content/osm/mq_logo.png' /> MapQuest</a>"});
map.addLayer(osm);
var style = new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
pointRadius: "${type}", // sized according to type attribute
fillColor: "#88B33A",
cursor:"pointer",
fillOpacity: 0.3,
strokeColor: "#6C5F59",
strokeWidth: 2,
graphicZIndex: 1
}),
"select": new OpenLayers.Style({
fillColor: "#E3682F",
fillOpacity:0.5,
strokeColor: "#E31224",
strokeWidth:3,
graphicZIndex: 2
})
});
var vectorLayer = new OpenLayers.Layer.Vector("Departements", {
strategies: [new OpenLayers.Strategy.BBOX()],
projection: wgs84,
styleMap: style,
attribution: "<a href='http://data.un.org'>IGN GeoFLA ©</a>",
protocol: new OpenLayers.Protocol.HTTP({
url: "http://np.trial.mapmint.com/dep.json",
format: new OpenLayers.Format.GeoJSON()
})
});
map.addLayers([vectorLayer]);
// OpenLayers.Control.Attribution is one of the default
// controls - only needs to be added when the map instance is
// created with the controls option
//map.addControl(new OpenLayers.Control.Attribution());
var options = {
hover: true,
onSelect: function(feature) {
var ndp= feature.attributes.name;
var nbr= feature.attributes.dep;
$("#info").html("<h1 class='inf'>" + nbr + "<span>" + ndp + "</span></h1>");
$("#info").show();
},
onUnselect:function() {
$("#info").hide();
}
}
var select = new OpenLayers.Control.SelectFeature(vectorLayer, options);
map.addControl(select);
select.activate();
$("#info").hide();
map.addControl(new OpenLayers.Control.Attribution());
map.zoomToExtent(mybounds);
map.zoomIn();
}
$(document).ready(function(){
var items = $('#stage li'),
itemsByTags = {};
// Looping though all the li items:
items.each(function(i){
var elem = $(this),
tags = elem.data('tags').split(',');
// Adding a data-id attribute. Required by the Quicksand plugin:
elem.attr('data-id',i);
$.each(tags,function(key,value){
// Removing extra whitespace:
value = $.trim(value);
if(!(value in itemsByTags)){
// Create an empty array to hold this item:
itemsByTags[value] = [];
}
// Each item is added to one array per tag:
itemsByTags[value].push(elem);
});
});
// Creating the "Everything" option in the menu:
createList('Tout les thèmes',items);
// Looping though the arrays in itemsByTags:
$.each(itemsByTags,function(k,v){
createList(k,v);
});
$('#filter a').click(function(e){
var link = $(this);
link.addClass('active').siblings().removeClass('active');
// Using the Quicksand plugin to animate the li items.
// It uses data('list') defined by our createList function:
$('#stage').quicksand(link.data('list').find('li'));
e.preventDefault();
});
$('#filter a:first').click();
function createList(text,items){
// This is a helper function that takes the
// text of a menu button and array of li items
// Creating an empty unordered list:
var ul = $('<ul>',{'class':'hidden'});
$.each(items,function(){
// Creating a copy of each li item
// and adding it to the list:
$(this).clone().appendTo(ul);
});
ul.appendTo('#container');
// Creating a menu item. The unordered list is added
// as a data parameter (available via .data('list'):
var a = $('<a>',{
html: text,
href:'#',
data: {list:ul}
}).appendTo('#filter');
}
});
<|start_filename|>mapmint-ui/js/Documents.js<|end_filename|>
var counter=0;
Documents=MLayout.extend();
Documents.define({
id: 0,
layoutOptions: {
contentSelector: ".lcontent",
center__paneSelector: ".inner-center",
west__paneSelector: ".inner-west",
west__size: .28,
west__draggable: false,
west__resizable: false,
west__spacing_closed:10,
west__spacing_open:8,
east__paneSelector: ".inner-east",
east__size: .28,
east__closable: false,
east__draggable: false,
east__resizable: false,
spacing_open: 4,
spacing_closed: 4,
//resizeWhileDragging: true,
onopen: function() {updateSize();},
onclose: function() {updateSize();},
onresize: function() {updateSize();}
},
initialize: function(){
this.refresh();
endLoading();
this.id++;
},
refresh: function(){
defaultInit();
}
});
$(document).ready(function () {
$("#add-documents").click(function(){
$("#eName").val("");
$('#add-documents-dialog').window({
width: 300,
height: 150,
left:150,
top:150,
maximizable:false,
minimizable:false,
resizable: false
})
});
$("#delete-documents").click(function(){
if(System.nodeVal){
$("#edName").val(System.nodeVal);
$('#delete-documents-dialog').window({
width: 300,
height: 150,
left:150,
top:150,
maximizable:false,
minimizable:false,
resizable: false
});
}
});
searchTable("documents");
refreshList();
});
/**
* Common part
*/
function updateElement(){
$("#documents_description").val( CKEDITOR.instances.documents_description.getData().replace(/\"/g,"\\\"") );
var params={id: System.nodeId};
$("#documents_edition_ui").find("input").each(function(){
if($(this)[0].id && $(this)[0].id.replace(/documents_/,"")!=$(this)[0].id)
params[$(this)[0].id.replace(/documents_/,"")]=$(this).val();
});
$("#documents_edition_ui").find("textarea").each(function(){
if($(this)[0].id && $(this)[0].id.replace(/documents_/,"")!=$(this)[0].id)
params[$(this)[0].id.replace(/documents_/,"")]=$(this).val();
});
$("#documents_edition_ui").find("select").each(function(){
if($(this)[0].multiple){
localId=$(this)[0].id.replace(/documents_/,"");
params[localId]=[];
$(this).find("option:selected").each(function(){
params[localId].push($(this).val());
});
}
else{
params[$(this)[0].id.replace(/documents_/,"")]=$(this).val();
}
});
params=[
{name: "table", value: "documents",dataType: "string"},
{name: "documents_groups_in", value: "d_id",dataType: "string"},
{name: "documents_groups_out", value: "g_id",dataType: "string"},
{name: "documents_themes_in", value: "d_id",dataType: "string"},
{name: "documents_themes_out", value: "t_id",dataType: "string"},
{name: "tuple", value: $.stringify(params), mimeType: "application/json"}
];
data=WPSGetHeader("np.updateElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
System.noSelectAgain=true;
refreshList();
}
}
});
}
function refreshDetails(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.details&DataInputs=table=documents;id="+System.nodeId+"&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var data=$.parseJSON(xml.responseText);
if(!data["file"] || data["file"]==""){
$('input:radio[name=doct]')[1].checked = true;
$('#file').hide();
$('#documents_file_link').hide();
$('#documents_url').show();
}
else{
$('input:radio[name=doct]')[0].checked = true;
$('#documents_url').hide();
$('#documents_file_link').html(data['file']);
$('#documents_file_link').attr("href",System.public_map_url+"/documents/"+data['file']);
$('#documents_file_link').show();
$('#file').show();
}
for(var i in data){
if(!$.isArray(data[i])){
if(i=="name")
$("#documents_"+i+"_title").html(data[i]);
$("#documents_"+i).val("");
if(data[i]!=null)
$("#documents_"+i).val(data[i]);
else
$("#documents_"+i).val(-1);
}else{
$("#documents_"+i+" option:selected").removeAttr("selected");
if(data[i].length)
for(var j=0;j<data[i].length;j++)
$("#documents_"+i+' option[value="'+data[i][j]+'"]').prop("selected", "selected");
else
$('#documents_'+i+' option[value="-1"]').prop("selected", "selected");
}
}
createEditor("documents_description");
}
}
});
}
function refreshList(){
$.ajax({
type: "GET",
url: System.zooUrl+"?service=WPS&version=1.0.0&request=Execute&Identifier=np.list&DataInputs=table=documents&RawDataOutput=Result",
complete: function(xml,status) {
if(checkWPSResult(xml,false)){
var data=$.parseJSON(xml.responseText);
$('#ltree').tree({
data: data,
onSelect: function(node){
System.nodeId=node.id;
System.nodeVal=node.text;
refreshDetails();
}
});
if(!System.noSelectAgain){
var tmp=$("#ltree").tree('getSelected');
var tmpr=$("#ltree").tree('getRoot');
if(!tmp && tmpr){
$("#ltree").tree('select',tmpr.target);
}
}else{
var node = $('#ltree').tree('find', System.nodeId);
$("#ltree").tree('select',node.target);
}
System.noSelectAgain=false;
}
}
});
}
function deleteElement(){
params=[
{name: "table", value: "documents",dataType: "string"},
{name: "atable", value: "documents_themes",dataType: "sting"},
{name: "akey", value: "d_id",dataType: "string"},
{name: "atable", value: "documents_groups",dataType: "sting"},
{name: "akey", value: "d_id",dataType: "string"},
{name: "id", value: System.nodeId,dataType: "string"}
];
data=WPSGetHeader("np.deleteElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshList();
$('#delete-documents-dialog').window('close');
}
}
});
}
function insertElement(){
params=[
{name: "table", value: "documents",dataType: "string"},
{name: "name", value: $("#eName").val(),dataType: "string"}
];
data=WPSGetHeader("np.insertElement")+WPSGetInputs(params)+WPSGetOutput({"name": "Result"})+WPSGetFooter();
$.ajax({
type: "POST",
contentType: "text/xml",
url: System.zooUrl,
data: data,
complete: function(xml,status) {
if(checkWPSResult(xml)){
refreshList();
$('#add-documents-dialog').window('close');
}
}
});
}
<|start_filename|>mapmint-ui/js/MLayout.js<|end_filename|>
MLayout=Class.create();
MLayout.define({
_init: function(){
//name: the id of DOM element representing the layout
this.name=arguments[0];
},
layout: null,
layoutOptions: {
contentSelector: ".lcontent",
center__paneSelector: ".inner-center",
west__paneSelector: ".inner-west",
west__size: .28,
west__draggable: false,
west__resizable: false,
east__paneSelector: ".inner-east",
east__size: .28,
east__closable: false,
east__draggable: false,
spacing_open: 8,
spacing_closed: 8,
resizeWhileDragging: true,
onopen: function() {updateSize();},
onclose: function() {updateSize();},
onresize: function() {updateSize();}
},
initialize: function(){
},
refresh: function(){
$('.ui-layout-toggler').tipsy({fade: true, offset:3, opacity: 1, gravity: 'w'});
}
});
<|start_filename|>mapmint-ui/css/main.css<|end_filename|>
.jquery-notify-bar {
width:100%;
position:fixed;
top:0;
left:0;
z-index:32768;
background-color:#efefef;
font-size:18px;
color:#929292;
text-align:center;
padding:0;
line-height:1em;
margin:0;
border-bottom:1px solid #cacaca;
}
.jquery-notify-bar.error {
color:#f00;
background-color:#fdd;
}
.jquery-notify-bar.success {
color:#060;
background-color:#BBFFB6;
}
.notify-bar-close {
position:absolute;
left:95%;
font-size:11px;
}
<|start_filename|>modules/AndroidPosition/functions.js<|end_filename|>
define([
'module', 'jquery', 'zoo', 'xml2json', 'ol', 'mmDataTables','typeahead',"managerTools"
], function(module, $, Zoo, X2JS,ol,MMDataTable,typeahead,managerTools) {
var title="MapMint4ME GPS";
var initialize = function(zoo,app) {
console.log("Map-Client Module: Call invoke method");
console.log("Map-Client Module: -- Register any event for adding your tool");
this.cnt = 0;
this.zoo = zoo;
console.log(this.zoo);
this.app=app;
console.log(navigator.userAgent);
if(navigator.userAgent.indexOf("Android")>=0)
loadInMainModuleBar(zoo,app);
//app.load_menu();
}
var mm4mefeaturesOverlay=null;
var mm4meTrackGPS=function(){
console.log("mm4meTrackGPS");
var closure=this;
zoo.execute({
identifier: "modules.AndroidPosition.getLocation",
dataInputs: [
{"identifier":"res","value":"32","dataType":"integer"},
],
dataOutputs: [
{"identifier":"Result","mimeType":"application/json","type":"raw"},
],
type: 'POST',
success: function(data){
console.log("mm4meTrackGPS SUCCESS");
console.log(closure.app);
console.log(JSON.stringify(data));
var geom=new ol.geom.Point(ol.proj.transform([parseFloat(data[0]),parseFloat(data[1])], 'EPSG:4326','EPSG:3857'));
//var geom=new ol.geom.Point(ol.proj.transform(data, 'EPSG:4326','EPSG:3857'));
if(mm4mefeaturesOverlay==null){
console.log("mm4meTrackGPS ");
console.log("mm4meTrackGPS ");
mm4mefeaturesOverlay = new ol.layer.Vector({
source: new ol.source.Vector({
})
});
app.getMap().addLayer(mm4mefeaturesOverlay);
console.log("mm4meTrackGPS ");
mm4mefeaturesOverlay.getSource().addFeatures([new ol.Feature({geometry: geom})]);
console.log("mm4meTrackGPS ");
console.log("mm4meTrackGPS ");
}else{
console.log("mm4meTrackGPS ");
console.log("mm4meTrackGPS ");
mm4mefeaturesOverlay.getSource().clear();
console.log("mm4meTrackGPS ");
mm4mefeaturesOverlay.getSource().addFeatures([new ol.Feature({geometry: geom})]);
console.log("mm4meTrackGPS ");
}
/*else{
featuresOverlay.getSource().clear();
featuresOverlay.getSource().addFeature(new ol.geom.Point(data));
}*/
//app.pointFeature.setGeometry(data);
console.log("mm4meTrackGPS ");
/*app.getMap().setView(new ol.View({
center: geom.coordinates,
zoom: 15
})); */
console.log(JSON.stringify(ol.extent.buffer(geom.getExtent(),2)));
app.getMap().getView().fit(ol.extent.buffer(geom.getExtent(),200),app.getMap().getSize());
console.log(data);
},
error: function(data){
console.log("mm4meTrackGPS ERROR");
console.log("mm4meTrackGPS ");
console.log(JSON.stringify(data));
}
});
console.log("/mm4meTrackGPS");
if(isActive)
setTimeout(function(){mm4meTrackGPS();},2000);
}
var loadInMainModuleBar = function(zoo){
$(".toolbar").append('<li data-toggle="tooltip" data-placement="bottom" title="'+title+'"> <a href="#" id="mm4megpsAction" class="mm-action "><i class="fa fa-android"></i><b class="ncaret hidden-sm hidden-md hidden-lg"></b><span class="hidden-sm hidden-md hidden-lg">'+title+'</span></a> </li>');
var closure=this;
closure.zoo=zoo;
$("#mm4megpsAction").off('click');
$("#mm4megpsAction").on('click',function(){
if($(this).parent().hasClass("active")){
}
else{
isActive=true;
$(this).parent().parent().find(".active").removeClass("active");
$(this).parent().addClass("active");
$(".navbar").find(".navbar-collapse.in").collapse("hide");
var saveLoc=document.location.href;
document.location.href="intent://coillte.mapmint.com/getLocation?"+_MMID+"#Intent;scheme=https;category=android.intent.category.BROWSABLE;launchFlags=0x10000000;component=fr.geolabs.dev.mapmint4me/.MapMint4ME;end";
setTimeout(function(){mm4meTrackGPS();},2000);
}
});
};
function deactivate(){
console.log("DEACTIVATE MODULE!!!")
$("#mm4megpsAction").parent().removeClass("active");
isActive=false;
}
var isActive=false;
var name = "My demo module";
var id = "MyDemoModule";
this.feature=null;
this.zoo=null;
// Return public methods
return {
initialize: initialize,
name: name,
id: id,
deactivate: deactivate
};
});
<|start_filename|>mapmint-services/raster-tools-src/Makefile<|end_filename|>
PREFIX=/usr/local
XSLT_LDFLAGS=-lxslt -lxml2
ZOO_FILE=
ZOO_DIR=/home/src/zoo/zoo-project/zoo-kernel
ZRPATH=/home/src/zoo/zoo-project/zoo-kernel/../
include ${ZOO_DIR}/ZOOMakefile.opts
CPPFLAGS := -DZOO_SERVICE ${JSLDFLAGS} ${JS_ENABLED} ${JSCFLAGS} -DUSE_CAIRO -DUSE_KML -DUSE_MS -I${ZOO_DIR} -I${ZOO_DIR}/../../thirds/cgic206
BIN_LIST = cgi-env/service.zo
cgi-env/service.zo: service.c service1.c
g++ ${ZOO_CFLAGS} -I${INST_INCLUDE} ${XML2_CPPFLAGS} ${GDAL_CFLAGS} ${MS_CFLAGS} ${CPPFLAGS} -shared -fpic $< service1.c ${ZOO_LDFLAGS} ${XSLT_LDFLAGS} ${XML2LDFLAGS} ${MACOS_LD_NET_FLAGS} ${MS_LDFLAGS} ${GDAL_LIBS} -lc -lcrypto -lcurl -lfcgi ${MACOS_CFLAGS} ${MACOS_LD_FLAGS} -L${INST_LIB} -lzoo_service -o $@
install:
install -d ${PREFIX}/raster-tools/
install $(BIN_LIST) ${PREFIX}/raster-tools/
install cgi-env/*.zcfg ${PREFIX}/raster-tools/
install cgi-env/*.py ${PREFIX}/raster-tools/
install cgi-env/*.js ${PREFIX}/raster-tools/
cd ${PREFIX}/raster-tools/ && ln -s ../main.cfg
cd ${PREFIX}/raster-tools/ && ln -s ../ZOO-api.js
cd ${PREFIX}/raster-tools/ && ln -s ../ZOO-proj4js.js
clean :
rm -f cgi-env/*zo
<|start_filename|>mapmint-services/wfs-t-src/service.c<|end_filename|>
extern "C" {
#include "mapogcfilter.h"
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
}
#include "cpl_error.h"
#include "ogr_api.h"
#include "service.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
//#include "mapserver.h"
//#include "mapows.h"
//#include "cpl_minixml.h"
#ifdef WIN32
#include <windows.h>
#endif
extern "C" {
void getLockOnMap4Layer(char* mname,char* lname){
char *lockOnMap4Layer=(char*)malloc((strlen(mname)+strlen(lname)+5)*sizeof(char));
sprintf(lockOnMap4Layer,"%s_%s.lck",mname,lname);
struct stat file_status;
int istat = stat(lockOnMap4Layer, &file_status);
while(true){
if(istat==0 && file_status.st_size>0){
#ifndef WIN32
sleep(1);
#else
Sleep(10);
#endif
istat = stat(lockOnMap4Layer, &file_status);
fprintf(stderr,"waiting for %s",lockOnMap4Layer);
continue;
}else{
//create the file !!
int f=open(lockOnMap4Layer,O_CREAT|O_TRUNC|O_RDWR,S_IWRITE | S_IREAD);
write(f,"12\n",4*sizeof(char));
close(f);
return;
}
}
};
void releaseLockOnMap4Layer(char* mname,char* lname){
char *lockOnMap4Layer=(char*)malloc((strlen(mname)+strlen(lname)+5)*sizeof(char));
sprintf(lockOnMap4Layer,"%s_%s.lck",mname,lname);
struct stat file_status;
int istat = stat(lockOnMap4Layer, &file_status);
if(istat==0 && file_status.st_size>0){
unlink(lockOnMap4Layer);
}
};
#ifdef WIN32
__declspec(dllexport)
#endif
int Transaction(maps*& conf,maps*& inputs,maps*& outputs){
int hasLock=-1;
map* tmp=getMapFromMaps(inputs,"MapFile","value");
fprintf(stderr,"[ZOO-WFS-T:Service]>>Mapfile : %s\n",tmp->value);
mapObj *mymap = msLoadMap(tmp->value, NULL);
char *mname=strdup(tmp->value);
char *lname=NULL;
msApplyDefaultSubstitutions(mymap);
fprintf(stderr,"[ZOO-WFS-T:Service]>>Shape Path : %s\n",mymap->shapepath);
fprintf(stderr,"[ZOO-WFS-T:Service]>>Map Path : %s\n",mymap->mappath);
tmp=getMapFromMaps(inputs,"Request","value");
xmlInitParser();
xmlDocPtr resDoc = xmlNewDoc(BAD_CAST "1.0");
xmlNsPtr ns_wfs,ns_wfs1,ns_ogc,ns_xsi;
xmlNodePtr n;
ns_wfs=xmlNewNs(NULL,BAD_CAST "http://www.opengis.net/ows/1.1",BAD_CAST "wfs");
n = xmlNewNode(ns_wfs, BAD_CAST "TransactionResponse");
ns_wfs1=xmlNewNs(n,BAD_CAST "http://www.opengis.net/wfs",BAD_CAST "wfs");
ns_ogc=xmlNewNs(n,BAD_CAST "http://www.opengis.net/ogc",BAD_CAST "ogc");
ns_xsi=xmlNewNs(n,BAD_CAST "http://www.w3.org/2001/XMLSchema-instance",BAD_CAST "xsi");
xmlNewProp(n,BAD_CAST "xsi:schemaLocation",BAD_CAST "http://www.opengis.net/wfs http://www.opengis.net//wfs/1.0.0/WFS-transaction.xsd");
xmlNewProp(n,BAD_CAST "version",BAD_CAST "1.0.0");
fprintf(stderr,"DEBUG (%s)",tmp->value);
xmlDocPtr doc = xmlParseMemory(tmp->value,strlen(tmp->value));
xmlBufferPtr xmlbuff;
int buffersize;
xmlXPathContextPtr xpathCtx;
xmlXPathObjectPtr xpathObj;
//char * xpathExpr="/*/*[local-name()='Insert']/*";
char * xpathExpr="/*/*";
xpathCtx = xmlXPathNewContext(doc);
xpathObj = xmlXPathEvalExpression(BAD_CAST xpathExpr,xpathCtx);
if(!xpathObj->nodesetval){
fprintf( stderr,"[ZOO-WFS-T:Service]>>Request parsing failed.");
return SERVICE_FAILED;
}
xmlbuff=xmlBufferCreate();
int size = (xpathObj->nodesetval) ? xpathObj->nodesetval->nodeNr : 0;
OGRRegisterAll();
for(int k=0;k<size;k++){
xmlNodePtr tmpx=xpathObj->nodesetval->nodeTab[k];
if(tmpx->type==XML_ELEMENT_NODE && xmlStrcasecmp(BAD_CAST "Insert",tmpx->name)==0){
tmpx=tmpx->children;
layerObj *mylayer=NULL;
OGRDataSourceH hDS=NULL;
OGRLayerH olayer=NULL;
char *featureid;
xmlNodePtr n1=xmlNewNode(ns_wfs, BAD_CAST "InsertResult");
while(tmpx!=NULL){
while(tmpx->type!=XML_ELEMENT_NODE)
tmpx=tmpx->next;
if(mylayer==NULL){
fprintf(stderr,"[ZOO-WFS-T:Service]>>Mylayer Name %s\n",tmpx->name);
mylayer=mymap->layers[msGetLayerIndex(mymap,(char*)tmpx->name)];
fprintf(stderr,"[ZOO-WFS-T:Service]>>Layer Type %s + %s + %d + %d (\"%s\")\n",mylayer->plugin_library,mylayer->plugin_library_original,mylayer->connectiontype,mylayer->type,mylayer->connection);
//featureid=msLookupHashTable(&mylayer->metadata,"gml_featureid");
featureid=msLookupHashTable(&mylayer->metadata,"ows_featureid");
fprintf( stderr,"[ZOO-WFS-T:Service]>>FeatureId Field : %s.\n",featureid);
char tmpDS[1024];
sprintf(tmpDS,"%s%s%s",mymap->mappath,mymap->shapepath,mylayer->connection);
fprintf( stderr,"[ZOO-WFS-T:Service]>>Trying to open %s.",tmpDS);
hDS = OGROpen( tmpDS, TRUE, NULL );
if( hDS == NULL ){
/**
* Need to create an error message here rather than returning service_failed !
*/
fprintf( stderr,"[ZOO-WFS-T:Service]>>Open %s failed : %s.",tmpDS,CPLGetLastErrorMsg());
OGRReleaseDataSource( hDS );
return SERVICE_FAILED;
}else
fprintf( stderr,"[ZOO-WFS-T:Service]>>Open %s successfully.\n",tmpDS );
olayer=OGR_DS_GetLayer(hDS,0);
}
OGR_L_ResetReading(olayer);
OGRFeatureH hFeature;
xmlNodePtr cnode=tmpx->children;
xmlNodePtr gnode;
OGRGeometryH hGeometry;
hFeature = OGR_F_Create( OGR_L_GetLayerDefn( olayer ) );
while(cnode!=NULL){
if(cnode->type == XML_ELEMENT_NODE) {
if(xmlStrncmp(cnode->name,BAD_CAST "msGeometry",xmlStrlen(cnode->name))==0){
const xmlChar *content;
xmlBufferEmpty(xmlbuff);
xmlNodePtr inode=cnode->children;
while(inode->type==XML_TEXT_NODE)
inode=inode->next;
if(xmlNodeDump(xmlbuff,doc,inode,0,1)<=0){
fprintf(stderr,"[ZOO-WFS-T:Service]>>Error dumping the geometry node");
return SERVICE_FAILED;
}
content = xmlBufferContent(xmlbuff);
fprintf(stderr,"[ZOO-WFS-T:Service]>>Insert field value : %s=%s\n",cnode->name,content);
char *geomContent=(char*)malloc((xmlStrlen(content)+1)*sizeof(char));
sprintf(geomContent,"%s",content);
hGeometry = OGR_G_CreateFromGML(geomContent);
OGR_F_SetGeometry( hFeature, hGeometry );
OGR_G_DestroyGeometry(hGeometry);
}
else{
fprintf(stderr,"[ZOO-WFS-T:Service]>>Insert field value : %s=%s\n",cnode->name,cnode->children->content);
OGRFeatureDefnH hFDefn;
int iField;
OGRGeometryH hGeometry;
hFDefn = OGR_L_GetLayerDefn(olayer);
int fid=OGR_F_GetFieldIndex(hFeature,(char*)cnode->name);
xmlChar *cctmp=cnode->children->content;
char *ctmp=(char*)malloc((xmlStrlen(cctmp)+1)*sizeof(char));
sprintf(ctmp,"%s",cctmp);
ctmp[xmlStrlen(cctmp)]=0;
fprintf( stderr,"[ZOO-WFS-T:Service]>>Field %d : %s = %s\n", fid,cnode->name,ctmp );
if(fid>=0){
OGRFieldDefnH hFieldDefn = OGR_FD_GetFieldDefn( hFDefn,fid);
if( OGR_Fld_GetType(hFieldDefn) == OFTInteger ){
OGR_F_SetFieldInteger( hFeature, fid, atoi(ctmp));
fprintf( stderr,"[ZOO-WFS-T:Service]>>Integer : %s = %d\n", ctmp,atoi(ctmp) );
}
else if( OGR_Fld_GetType(hFieldDefn) == OFTReal ){
OGR_F_SetFieldDouble( hFeature, fid, atof(ctmp));
fprintf( stderr,"[ZOO-WFS-T:Service]>>Double : %s = %3f\n", ctmp,atof(ctmp) );
}
else if( OGR_Fld_GetType(hFieldDefn) == OFTString ){
OGR_F_SetFieldString( hFeature, fid, ctmp);
fprintf( stderr,"[ZOO-WFS-T:Service]>>String : %s = %s\n", ctmp,ctmp );
}
else
fprintf( stderr,"[ZOO-WFS-T:Service]>>Unsupported field type : %s = \"%s\"\n", OGR_Fld_GetNameRef(hFieldDefn),cctmp );
}
else{
OGR_F_SetFID( hFeature, atoi(ctmp));
fprintf( stderr,"[ZOO-WFS-T:Service]>>Unsupported field name : %s \n", cnode->name );
}
}
}
cnode=cnode->next;
}
if( OGR_L_CreateFeature( olayer, hFeature )!= OGRERR_NONE )
{
fprintf( stderr,"Failed to create feature in datasource.\n" );
return SERVICE_FAILED;
}
xmlNodePtr n2=xmlNewNode(ns_ogc, BAD_CAST "FeatureId");
char *sfid=(char*)malloc((strlen(mylayer->name)+strlen(OGR_F_GetFieldAsString( hFeature, OGR_F_GetFieldIndex(hFeature,featureid)))+2)*sizeof(char));
sprintf(sfid,"%s.%s",mylayer->name,OGR_F_GetFieldAsString( hFeature, OGR_F_GetFieldIndex(hFeature,featureid)));
xmlNewProp(n2,BAD_CAST "fid",BAD_CAST sfid);
xmlAddChild(n1,n2);
fprintf(stderr,"<ogc:FeatureId fid=\"%s.%s\"/>",mylayer->name,OGR_F_GetFieldAsString( hFeature, OGR_F_GetFieldIndex(hFeature,featureid)));
OGR_F_Destroy( hFeature );
//xmlFree(n2);
tmpx=tmpx->next;
}
//OGRReleaseDataSource( hDS );
OGR_DS_Destroy( hDS );
xmlAddChild(n,n1);
}
else if(tmpx->type==XML_ELEMENT_NODE && (xmlStrcasecmp(BAD_CAST "Delete",tmpx->name)==0 || xmlStrcasecmp(BAD_CAST "Update",tmpx->name)==0)){
layerObj *mylayer=NULL;
OGRDataSourceH hDS=NULL;
OGRLayerH olayer=NULL;
char *featureid;
int fid,lid;
char *rtype=(char*)tmpx->name;
map *properties=NULL;
lname=(char*)malloc((xmlStrlen(xmlGetProp(tmpx,BAD_CAST "typeName"))+1)*sizeof(char));
sprintf(lname,"%s",(char*)xmlGetProp(tmpx,BAD_CAST "typeName"));
fprintf(stderr,"[ZOO-WFS-T:Service]>>Layer Name %s\n",lname);
if(hasLock<0){
getLockOnMap4Layer(mname,lname);
hasLock=1;
}
lid=msGetLayerIndex(mymap,lname);
fprintf(stderr,"[ZOO-WFS-T:Service]>>Layer Name %s , id : %d\n",lname,lid);
mylayer=GET_LAYER(mymap,lid);
rectObj ext;
msOWSGetLayerExtent(mymap,mylayer,"MO",&ext);
mylayer->status=MS_ON;
fprintf(stderr,"[ZOO-WFS-T:Service]>>Layer (%d) Type %s + %s + %d + %d (\"%s\")\n",lid,mylayer->plugin_library,mylayer->plugin_library_original,mylayer->connectiontype,mylayer->type,mylayer->connection);
//featureid=msLookupHashTable(&mylayer->metadata,"gml_featureid");
featureid=msLookupHashTable(&mylayer->metadata,"ows_featureid");
fprintf( stderr,"[ZOO-WFS-T:Service]>>FeatureId Field : %s.\n",featureid);
//char tmpDS[1024];
/*char *tmpDS=(char*)malloc((strlen(mymap->mappath)+strlen(mymap->shapepath)+strlen(mylayer->connection)+1)*sizeof(char));
sprintf(tmpDS,"%s%s%s",mymap->mappath,mymap->shapepath,mylayer->connection);*/
/*char tmpDS[1024];
char *tmpDS=(char*)malloc((strlen(mylayer->connection)+strlen(mylayer->connection)+1)*/
fprintf( stderr,"[ZOO-WFS-T:Service]>>Trying to open %s.",mylayer->connection,mylayer->data);
hDS = OGROpen( mylayer->connection, TRUE, NULL );
if( hDS == NULL ) {
/**
* Need to create an error message here rather than returning service_failed !
*/
fprintf( stderr,"[ZOO-WFS-T:Service]>>Open %s failed : %s.",mylayer->connection,CPLGetLastErrorMsg());
return SERVICE_FAILED;
}else
fprintf( stderr,"[ZOO-WFS-T:Service]>>Open from %s %s successfully.\n",mylayer->connection , lname);
olayer=OGR_DS_GetLayerByName(hDS,lname);
if(olayer==NULL){
fprintf(stderr,"Layer not found !!");
}
OGR_L_ResetReading(olayer);
OGRFeatureH hFeature;
while( (hFeature = OGR_L_GetNextFeature(olayer)) != NULL ){
fid=OGR_F_GetFieldIndex(hFeature,featureid);
OGR_F_Destroy(hFeature);
break;
}
tmpx=tmpx->children;
char *fclause=NULL;
while(tmpx!=NULL){
fprintf(stderr,"Starting %d\n",tmpx==NULL);
if(tmpx->type==XML_ELEMENT_NODE)
fprintf(stderr,"%s\n",tmpx->name);
while(tmpx!=NULL && tmpx->type!=XML_ELEMENT_NODE)
tmpx=tmpx->next;
fprintf(stderr,"Starting %d\n",tmpx==NULL);
if(tmpx==NULL)
break;
if(tmpx->type==XML_ELEMENT_NODE)
fprintf(stderr,"%s\n",tmpx->name);
if(xmlStrcasecmp(tmpx->name,BAD_CAST "Filter")==0){
xmlBufferEmpty(xmlbuff);
if(xmlNodeDump(xmlbuff,doc,tmpx,0,0)<=0){
fprintf(stderr,"[ZOO-WFS-T:Service]>>Error dumping the filter node");
return SERVICE_FAILED;
}
const xmlChar *content = xmlBufferContent(xmlbuff);
//char *filter=(char*)malloc((xmlStrlen(content)+1)*sizeof(char));
char *realfilter=(char*)malloc((xmlStrlen(content)+1)*sizeof(char));
sprintf(realfilter,"%s",content);
FilterEncodingNode *fen=FLTParseFilterEncoding(realfilter);
mylayer->maxfeatures = -1;
//layer->startindex = -1;
fprintf(stderr,"[ZOO-WFS-T:Service]>>Filter on %s : %s (%d-%d)\n",mylayer->name,realfilter,lid,FLTValidFilterNode(fen));
if (!fen) {
// Need to output exception response
fprintf(stderr,"[ZOO-WFS-T:Service]>>FilterNode is null !\n",content);
return SERVICE_FAILED;
}
//lid=msGetLayerIndex(mymap,mylayer->name);
/* preparse the filter for gml aliases */
FLTPreParseFilterForAlias(fen, mymap, lid, "G");
/* run filter. If no results are found, do not throw exception */
/* this is a null result */
if( FLTApplyFilterToLayer(fen, mymap, lid) != MS_SUCCESS )
{
errorObj *ms_error = msGetErrorObj();
fprintf(stderr, "[ZOO-WFS-T:Service]>> FLTApplyFilterToLayer() result : %s\n",ms_error->message);
if(ms_error->code != MS_NOTFOUND)
{
fprintf(stderr, "[ZOO-WFS-T:Service]>> FLTApplyFilterToLayer() failed \n");
}
}
int j=0;
fprintf(stderr,"[ZOO-WFS-T:Service]>>Filter NumResult : %d\n",mylayer->resultcache->numresults);
for(j=0;j<mylayer->resultcache->numresults;j++){
shapeObj shape;
msInitShape(&shape);
//msLayerResultsGetShape(mylayer, &shape, -1, j);
//msLayerResultsGetShape(mylayer, &shape, -1, j);
msLayerGetShape(mylayer, &shape, &(mylayer->resultcache->results[j]));
if(fclause==NULL){
fclause=(char*)malloc((strlen(featureid)+strlen(shape.values[fid])+1)*sizeof(char));
sprintf(fclause,"%s=%s",featureid,shape.values[fid]);
}
else{
char *stmp=strdup(fclause);
fclause=(char*)realloc(fclause,(strlen(fclause)+strlen(featureid)+strlen(shape.values[fid])+6)*sizeof(char));
sprintf(fclause,"%s OR %s=%s",stmp,featureid,shape.values[fid]);
free(stmp);
}
fprintf(stderr,"[ZOO-WFS-T:Service]>>FCLAUSE %s\n",fclause);
fprintf(stderr,"[ZOO-WFS-T:Service]>>FeatureId (%s-%d) value : %s\n",featureid,fid,shape.values[fid]);
}
FLTFreeFilterEncodingNode(fen);
fen=NULL;
}
else if(xmlStrcasecmp(tmpx->name,BAD_CAST "Property")==0){
xmlNodePtr inode=tmpx->children;
char *name;
while(inode!=NULL){
fprintf(stderr,"[ZOO-WFS-T:Service]>> Type: %d (%d)\n",inode->type,XML_ELEMENT_NODE);
while(inode->type!=XML_ELEMENT_NODE)
inode=inode->next;
if(xmlStrcasecmp(inode->name,BAD_CAST "Name")==0){
name=strdup((char*)inode->children->content);
fprintf(stderr,"[ZOO-WFS-T:Service]>>Name: %s\n",inode->children->content);
}
if(xmlStrcasecmp(inode->name,BAD_CAST "Value")==0){
xmlNodePtr inode1=xmlFirstElementChild(inode);
fprintf(stderr,"[ZOO-WFS-T:Service]>>(%s) Value: %s %d==%d\n",name,inode->children->content,inode->children->type,XML_ELEMENT_NODE);
char *value;
if(inode->children->type!=XML_ELEMENT_NODE && strncmp("msGeometry",name,10)!=0)
value=strdup((char*)inode->children->content);
else{
fprintf(stderr,"DEBUG %d\n",xmlNodeDump(xmlbuff,doc,xmlFirstElementChild(inode),0,1));
if(xmlNodeDump(xmlbuff,doc,inode->children,0,1)<=0){
fprintf(stderr,"[ZOO-WFS-T:Service]>>Error dumping the geometry node");
return SERVICE_FAILED;
}
const xmlChar *content;
content = xmlBufferContent(xmlbuff);
fprintf(stderr,"[ZOO-WFS-T:Service]>>Updated Geometry value : %s=%s\n",inode->children->name,content);
value=(char*)malloc((xmlStrlen(content)+1)*sizeof(char));
sprintf(value,"%s",content);
}
if(properties==NULL){
properties=createMap(name,value);
}
else
addToMap(properties,name,value);
//dumpMap(properties);
free(name);
free(value);
inode=NULL;
continue;
}
inode=inode->next;
}
}
tmpx=tmpx->next;
}
fprintf(stderr,"[ZOO-WFS-T:Service]>>Starting (%s)!\n",fclause);
if(fclause!=NULL && OGR_L_SetAttributeFilter(olayer,fclause)==OGRERR_NONE){
fprintf(stderr,"[ZOO-WFS-T:Service]>>Starting!\n");
OGR_L_ResetReading(olayer);
if(strcasecmp("Delete",rtype)==0){
while( (hFeature = OGR_L_GetNextFeature(olayer)) != NULL ){
OGR_L_DeleteFeature(olayer,OGR_F_GetFID(hFeature));
OGR_F_Destroy(hFeature);
}
}else if(strcasecmp("Update",rtype)==0 && properties!=NULL){
while( (hFeature = OGR_L_GetNextFeature(olayer)) != NULL ) {
map *tmap=properties;
while(tmap!=NULL) {
if(strcasecmp("msGeometry",tmap->name)!=0){
int fid=OGR_F_GetFieldIndex(hFeature,tmap->name);
OGR_F_SetFieldString(hFeature,fid,tmap->value);
}else{
OGRGeometryH hGeometry = OGR_G_CreateFromGML(tmap->value);
OGR_F_SetGeometry( hFeature, hGeometry );
OGR_G_DestroyGeometry(hGeometry);
}
fprintf( stderr,"[ZOO-WFS-T:Service]>>Update : %s(%d) = %s\n", tmap->name,fid, tmap->value);
tmap=tmap->next;
}
OGR_L_SetFeature(olayer,hFeature);
}
OGR_F_Destroy(hFeature);
}
}
fprintf(stderr,"[ZOO-WFS-T:Service]>>Finishing!\n");
free(fclause);
fclause=NULL;
freeMap(&properties);
free(properties);
properties=NULL;
OGR_DS_Destroy( hDS );
}
}
xmlChar *xmlb;
int bsize;
xmlNodePtr n1=xmlNewNode(ns_wfs,BAD_CAST "TransactionResult");
xmlNewProp(n1,BAD_CAST "handle",BAD_CAST "Transaction 01");
xmlNodePtr n2=xmlNewNode(ns_wfs,BAD_CAST "Status");
xmlNodePtr n3=xmlNewNode(ns_wfs,BAD_CAST "SUCCESS");
xmlAddChild(n2,n3);
xmlAddChild(n1,n2);
xmlAddChild(n,n1);
xmlDocSetRootElement(resDoc, n);
xmlDocDumpFormatMemory(resDoc, &xmlb, &bsize, 1);
addToMap(outputs->content,"value",(char*)xmlb);
//outputs->next=NULL;
xmlXPathFreeObject(xpathObj);
xmlXPathFreeContext(xpathCtx);
xmlCleanupParser();
if(lname!=NULL){
releaseLockOnMap4Layer(mname,lname);
}
return SERVICE_SUCCEEDED;
}
}
<|start_filename|>mapmint-ui/templates/UsersManagement/MainWindow.html<|end_filename|>
#import zoo
<div>
<form>
<div>
<a href="#mm_users">Users</a>|<a href="#mm_groups">Groups</a>
</div>
<div id="um_users">
<table id="um_utable">
<thead>
<th width="100">$zoo._("Login")</th>
<th width="150">$zoo._("Last Name")</th>
<th width="150">$zoo._("First Name")</th>
<th width="150">$zoo._("Mail")</th>
<th width="50">$zoo._("Phone")</th>
</thead>
</table>
</div>
<div id="um_groups">
<table id="um_gtable">
</table>
</div>
</form>
</div>
<|start_filename|>mapmint-ui/templates/Manager/Styler_bs.html<|end_filename|>
#encoding UTF-8
#import zoo
#try
#set isBasic=$basic
#except
#set isBasic=False
#end try
#def printTabHeader(id,title,font,classe)
<li role="presentation" #if $classe is not None#class="$classe"#end if#>
<a id="$(id)_Toggler" href="#$id" aria-controls="home" role="tab" data-toggle="tab">
<i class="fa $font fa-fw"></i>
<span class="hidden-xs hidden-sm hidden-md">
$title
</span>
</a>
</li>
#end def
<ul class="nav nav-tabs" role="tablist">
$printTabHeader("mm_layer_property_style_display",$zoo._("Symbology"),"fa-paint-brush",None)
$printTabHeader("mm_layer_property_label_display",$zoo._("Labels"),"fa-file-text-o","no-raster")
#if not(isBasic)
$printTabHeader("mm_layer_property_grid_display",$zoo._("Grid"),"fa-th","require-grid")
#end if
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane active"
id="mm_layer_property_style_display">
<form class="form-horizontal mtpp" method="get" >
#if not(isBasic)
<div class="form-group require-raster">
<label class="col-sm-3 control-label">$zoo._(" Resampling method: ")</label>
<div class="col-sm-9 ">
<select type="text" name="resample" class="form-control">
<option value="-1">$zoo._("Choose")</option>
#set tmp=["NEAREST","AVERAGE","BILINEAR"]
#for a in tmp
<option value="$a">$a</option>
#end for
</select>
</div>
</div>
<script type="template/text" id="style_processing_line_template" >
<label class="col-sm-3 control-label">[label]</label>
<div class="col-sm-9 ">
<div class="input-group">
<input name="processing_[name]" class="form-control" value="[value]" data-toggle="tooltip" title="" data-original-title="Processing directive"/>
<span class="input-group-btn" id="basic-addon1"><button class="btn btn-default" type="button" onclick="console.log(\$(this).parent().parent().parent().prev());\$(this).parent().parent().parent().prev().remove(); \$(this).parent().parent().parent().remove();">$zoo._("Delete")</button></span>
</div>
</div>
</script>
<div class="form-group require-raster" id="style_processings">
</div>
<div class="form-group require-raster" id="style_processings_tools">
<label class="col-sm-3 control-label">Add a directive</label>
<div class="col-sm-9 ">
<div class="input-group">
<input name="new_processing_directive"
class="form-control" value="" data-toggle="tooltip" title=""
data-original-title="Processing directive name, sample:
COLOR_MATCH_THRESHOLD, DITHER, EXTENT_PRIORITY, LOAD_FULL_RES_IMAGE,
LOAD_WHOLE_IMAGE, LUT, OVERSAMPLE_RATIO"/>
<span class="input-group-btn" id="basic-addon1">
<button class="btn btn-default" type="button"
onclick="\$('#style_processings').append(\$('#style_processing_line_template').html() .replace(/\[name\]/g,\$(this).parent().prev().val()).replace(/\[label\]/g,\$(this).parent().prev().val()).replace(/\[value\]/g,''));\$(this).parent().prev().val('');">$zoo._("Add")
</button>
</span>
</div>
</div>
</div>
#end if
<div class="form-group">
<label class="col-sm-3 control-label">$zoo._("Opacity")</label>
<div class="col-sm-9 ">
<div class="range">
<input type="range" name="styleOpacity" min="1" max="100" value="100"
onchange="\$(this).next().html(\$(this).val() + '%')" oninput="\$(this).next().html(\$(this).val() + '%')"/>
<output>100%</output>
</div>
</div>
</div>
#def printSelect($classes,$title,$name,$choices)
<div class="form-group no-grid $classes">
<label class="col-sm-3 control-label">$title</label>
<div class="col-sm-9 ">
<select name="$name" class="form-control class-switcher">
#for a in $choices.keys()
<option value="$a" #if $choices[$a][1]#class="no-raster"#end if##if $choices[$a][2]#class="require-raster"#end if#>$choices[$a][0]</otion>
#end for
</select>
</div>
</div>
#end def
#from collections import OrderedDict
#if not(isBasic)
#set choices=OrderedDict([
("us", [$zoo._("Unique Symbol"),False,False]),
("gs", [$zoo._("Graduated Symbol"),False,False]),
("cc", [$zoo._("Continuous Color"),True,False]),
("uv", [$zoo._("Unique Value"),False,False]),
("tl", [$zoo._("Time line"),True,False]) ,
("tc", [$zoo._("Time line classes"),True,False])
])
#else
#set choices=OrderedDict([
("us", [$zoo._("Choose"),False,False]),
("gs", [$zoo._("Graduated Symbol"),False,False]),
("cc", [$zoo._("Continuous Color"),True,False]),
("uv", [$zoo._("Unique Value"),False,False]),
("tl", [$zoo._("Time line"),True,False]),
("tc", [$zoo._("Time line classes"),True,False])
])
#end if
$printSelect("",$zoo._("Legend Type: "),"classification",$choices)
<div class="form-group require-tc no-tl no-grid no-us no-gs no-cc no-uv col-sm-12">
<label class="col-sm-3 control-label">$zoo._("Field defining steps")</label>
<div class="col-sm-9">
<select name="step_field" class="form-control mmField" onchange="if(\$(this).val()=='-1') \$(this).parent().parent().next().show();else \$(this).parent().parent().next().hide();">
<option value="-2">$zoo._("Choose a field")</option>
</select>
</div>
</div>
<div class="form-group require-tl no-tc no-grid no-us no-gs no-cc no-uv col-sm-12">
<label class="col-sm-3 control-label">$zoo._("Steps")</label>
<div class="col-sm-5 ">
<select name="step" class="form-control mmstep-list" onchange="if(\$(this).val()=='-1') \$(this).parent().parent().next().show();else \$(this).parent().parent().next().hide();">
<option value="-2">$zoo._("Choose a step")</option>
<option value="-1">$zoo._("Add a step")</option>
</select>
</div>
<button class="btn btn-default disabled col-sm-4 mmstep-delete">
$zoo._("Delete")
</button>
</div>
<div class="form-group require-add-step no-tc no-us no-gs no-cc no-uv col-sm-12">
<label class="col-sm-3 control-label">$zoo._("Step name")</label>
<div class="col-sm-5">
<input type="text" class="form-control" name="stepName" placeholder="$zoo._("1789")" value="" />
<p class="help-block"></p>
</div>
<button class="btn btn-default col-sm-4 mmstep-add">
$zoo._("Add")
</button>
</div>
#if not(isBasic)
#set choices={
"us": [$zoo._("Unique Symbol"),False,False],
"gs": [$zoo._("Graduated Symbol"),False,False],
"cc": [$zoo._("Continuous Color"),True,False],
"uv": [$zoo._("Unique Value"),False,False]
}
#else
#set choices={
"gs": [$zoo._("Graduated Symbol"),False,False],
"cc": [$zoo._("Continuous Color"),True,False],
"uv": [$zoo._("Unique Value"),False,False],
}
#end if
$printSelect("require-tl require-tc no-us no-gs no-cc no-uv",$zoo._("Legend Type for this step"),"step_classification",$choices)
#if not(isBasic)
<div class="form-group require-raster no-us">
<label class="col-sm-3 control-label">$zoo._("Tiled version")</label>
<div class="col-sm-9">
<div class="input-group">
<span class="input-group-addon">
<input name="tileSizec" type="checkbox" onchange="\$(this).parent().next().attr('disabled',!\$(this).is(':checked'));" />
</span>
<input type="text" class="form-control" name="tileSize" disabled="disabled" value="" />
</div>
</div>
</div>
<div class="form-group require-raster no-us">
<label class="col-sm-3 control-label">$zoo._("Min / Max values")</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="minBandValue" value="" />
<p class="help-block"></p>
</div>
<div class="col-sm-4">
<input type="text" class="form-control" name="maxBandValue" value="" />
<p class="help-block"></p>
</div>
</div>
<div class="form-group require-raster no-gs no-uv">
<label class="col-sm-3 control-label">$zoo._("No-data value")</label>
<div class="col-sm-9 ">
<div class="input-group cpicker">
<span class="input-group-addon">
<input name="expressionc" type="checkbox" onchange="\$(this).parent().next().attr('disabled',!\$(this).is(':checked'));" />
</span>
<input type="text" class="form-control" name="nodataColorValue" value="#000000" onkeyup="if(\$(this).val().length==7)\$(this).parent().colorpicker('setValue', \$(this).val());"/>
<span class="input-group-addon"><i></i></span>
</div>
</div>
</div>
#end if
<div class="form-group no-us">
<label class="col-sm-3 control-label">$zoo._("Min / Max color")</label>
<div class="col-sm-9 ">
<div class="col-sm-6">
<div class="input-group cpicker">
<input type="text" class="form-control" name="minColorValue" value="#ffffff" />
<span class="input-group-addon"><i></i></span>
</div>
</div>
<div class="col-sm-6">
<div class="input-group cpicker">
<input type="text" class="form-control" name="maxColorValue" value="#ffffff" />
<span class="input-group-addon"><i></i></span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">$zoo._("Expression settings")</label>
<div class="col-sm-9 ">
<div class="input-group">
<span class="input-group-addon">
<input name="expressionc" type="checkbox" onchange="\$(this).parent().next().attr('disabled',!\$(this).is(':checked'));" />
</span>
<textarea class="form-control" disabled="disabled" name="expression0"></textarea>
</div>
</div>
</div>
<div class="form-group no-us">
<label class="col-sm-3 control-label">$zoo._("Classification field")</label>
<div class="col-sm-9 ">
<select name="classField" class="form-control mmField">
</select>
</div>
</div>
#if isBasic
<div class="form-group">
<label class="col-sm-3 control-label">$zoo._("Formula")</label>
<div class="col-sm-9 ">
<textarea class="form-control"name="formula"></textarea>
</div>
</div>
#end if
<div class="form-group no-us require-point">
<label class="col-sm-3 control-label">$zoo._("Size field")</label>
<div class="col-sm-9 ">
<div class="input-group">
<span class="input-group-addon">
<input name="classField1c" type="checkbox" onchange="\$(this).parent().next().attr('disabled',!\$(this).is(':checked'));" />
</span>
<input type="text" name="classField1" disabled="disabled" class="form-control"
data-toggle="tooltip" title="$zoo._("Use the formula you want (ie. MY_FIELD*10).")" />
</div>
</div>
</div>
<div class="form-group no-us no-uv require-gs">
<label class="col-sm-3 control-label">$zoo._("Classes number")</label>
<div class="col-sm-9 ">
<input type="text" name="nbclass" class="form-control"
data-toggle="tooltip" title="$zoo._("Define the number of classes you want to be generated.")" />
</div>
</div>
<div class="form-group no-us no-uv require-gs no-raster">
<label class="col-sm-3 control-label">$zoo._("Discretization")</label>
<div class="col-sm-9 ">
<select type="text" name="discretization" class="form-control">
<option value="-1">$zoo._("Choose")</option>
#set tmp=["equal","jenks","quantile","pretty","kmeans","fisher"]
#for a in tmp
<option value="$a">$a</option>
#end for
</select>
</div>
</div>
<div class="col-sm-12 no-grid">
<div class="col-sm-3">
<button href="#" class="btn btn-default mmClassifier no-tc">$zoo._("Classify")</button>
<button href="#" class="btn btn-default mmClassifier require-tc no-tl no-us no-uv no-gs no-raster">$zoo._("Generate")</button>
#if isBasic
<button href="#" class="btn btn-default mmPreviewer">$zoo._("Preview")</button>
#end if
</div>
<div class="col-sm-9" id="classify_progress" style="display:none">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0</div>
</div>
</div>
</div>
<div class="col-sm-12 classesTable">
<table id="classes"></table>
</div>
</form>
</div>
<div role="tabpanel" class="tab-pane" id="mm_layer_property_label_display">
#include $conf['main']['templatesPath']+"/Manager/Styler/Label_bs.html"
</div>
<div role="tabpanel" class="tab-pane" id="mm_layer_property_grid_display">
#include $conf['main']['templatesPath']+"/Manager/Styler/Grid_bs.html"
</div>
</div>
<|start_filename|>mapmint-ui/css/layout-default-latest2.css<|end_filename|>
/*
MapMint green Cascading Style Sheet
Copyright Cartoworks Inc. 2010
*/
body {
font: 12px Verdana, Arial, Helvetica, sans-serif;
background: url(../images/main-bg2.png);
padding: 0;
margin: 0;
}
h1{
margin:0;padding:5px;background: #d1d1d1; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#a1a1a1'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#a1a1a1)); /* for webkit browsers */
background: -moz-linear-gradient(top, #ebebeb, #a1a1a1); /* for firefox 3.6+ */
font-size:1.1em;font-weight:normal;text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
/*
* Panes & content divs
*/
.ui-layout-pane {
background: #E7E7E7;
border:1px solid #BBB;
padding:10px;
overflow:auto;
}
.ui-layout-content {
padding:0px;
position:relative;
overflow:auto;
}
.ui-layout-center{
padding:0px;
background:transparent;
border:0;
}
.inner-layout-container .ui-layout-pane {
overflow:auto;
}
.close {width:17px;height:16px;background:url(../images/close-sidebar.png);float:right;}
.close:hover {width:17px;height:16px;background:url(../images/close-sidebar-hover.png);float:right;}
/*** IMPORTANT - do not modify ***/
.inner-layout-container { height:100%;}
.ui-layout-center,.ui-layout-north,.ui-layout-south,.inner-center,.inner-west,.inner-east {display:none;}
.inner-center,.inner-west,.inner-east {padding:0px;}
.ui-layout-north{
overflow:hidden;
background:#565656 url(../images/mapmint-logo2.png) no-repeat;
border:0;
margin:0;
padding:0;
height:50px;
max-height:50px;
}
.ui-layout-south{
overflow:hidden;
background:#565656;
border:0;
margin:0;
padding:0;
height:50px;
max-height:50px;
}
/*
* Resizer bars
*/
.ui-layout-resizer{background:transparent;}
.ui-layout-resizer-drag {}
.ui-layout-resizer-hover{}
.ui-layout-resizer-open-hover{background:transparent;}
.ui-layout-resizer-dragging{background:transparent;}
.ui-layout-resizer-dragging {border-left:1px solid #BBB;border-right: 1px solid #BBB;}
.ui-layout-resizer-dragging-limit{background:transparent;}
.ui-layout-resizer-closed-hover{background:transparent;}
.ui-layout-resizer-sliding {opacity: .10;filter: alpha(opacity=10);}
.ui-layout-resizer-sliding-hover{opacity: 1.00;filter: alpha(opacity=100);}
.ui-layout-resizer-north-sliding-hover { border-bottom-width: 1px; }
.ui-layout-resizer-south-sliding-hover { border-top-width: 1px; }
.ui-layout-resizer-west-sliding-hover { border-right-width: 1px; }
.ui-layout-resizer-east-sliding-hover { border-left-width: 1px; }
/*
* Toggler buttons
*/
.ui-layout-toggler{border: 1px solid #BBB;background-color: #BBB;}
.ui-layout-resizer-hover .ui-layout-toggler{opacity: .60;filter: alpha(opacity=60);}
.ui-layout-resizer-hover .ui-layout-toggler-hover{ background-color: #44d0e5;opacity:1.00;filter:alpha(opacity=100);}
.ui-layout-toggler-north,.ui-layout-toggler-south{border-width: 0 1px;}
.ui-layout-toggler-west,.ui-layout-toggler-east{border-width: 1px 0;}
.ui-layout-resizer-sliding, .ui-layout-toggler{display: none;}
.tipsy { padding: 5px; font-size: 10px; position: absolute; z-index: 100000; }
.tipsy-inner { padding: 5px 8px 4px 8px; background-color:#565656; color: white; max-width: 200px; text-align: center; }
.tipsy-inner { border-radius: 3px; -moz-border-radius:3px; -webkit-border-radius:3px; }
.tipsy-arrow { position: absolute; background:transparent no-repeat top left; width: 9px; height: 5px; }
.tipsy-n .tipsy-arrow { top: 0; left: 50%; margin-left: -4px; }
.tipsy-nw .tipsy-arrow { top: 0; left: 10px; }
.tipsy-ne .tipsy-arrow { top: 0; right: 10px; }
.tipsy-s .tipsy-arrow { bottom: 0; left: 50%; margin-left: -4px; background-position: bottom left; }
.tipsy-sw .tipsy-arrow { bottom: 0; left: 10px; background-position: bottom left; }
.tipsy-se .tipsy-arrow { bottom: 0; right: 10px; background-position: bottom left; }
.tipsy-e .tipsy-arrow { top: 50%; margin-top: -4px; right: 0; width: 5px; height: 9px; background-position: top right; }
.tipsy-w .tipsy-arrow { top: 50%; margin-top: -4px; left: 0; width: 5px; height: 9px; }
.datawarehouse {width:100%;height:60px;margin:0;padding:0;border-bottom:1px solid #bababa;background: #E7E7E7 url(../images/datawarehouse-icon.png) no-repeat;background-position:3px 3px;}
.hover {background: #7dff26}
.layermanager {width:100%;height:60px;margin:0;padding:0;border-bottom:1px solid #bababa;background:#E7E7E7 url(../images/layermanager-icon.png) no-repeat;background-position:3px 3px;}
.printpublisher {width:100%;height:60px;margin:0;padding:0;border-bottom:1px solid #bababa;background:#E7E7E7 url(../images/printpublisher-icon.png) no-repeat;background-position:3px 3px;}
.webpublisher {width:100%;height:60px;margin:0;padding:0;border-bottom:1px solid #bababa;background:#E7E7E7 url(../images/webpublisher-icon.png) no-repeat;background-position:3px 3px;}
.documentation {width:100%;height:60px;margin:0;padding:0;border-bottom:1px solid #bababa;background:#E7E7E7 url(../images/documentation-icon.png) no-repeat;background-position:3px 3px;}
.datawarehouse h2, .layermanager h2, .printpublisher h2, .webpublisher h2, .documentation h2{
float:left;margin:0;padding:10px 0 0 70px;background:transparent;
;font-size:1.2em;font-weight:normal;text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
.datawarehouse h3, .layermanager h3, .printpublisher h3, .webpublisher h3, .documentation h3{
float:left;position:absolute;margin:0;padding:30px 0 0 70px;background:transparent;font-size:1.1em;font-weight:normal;color:#333333;
}
.start-stop{float:right;position:relative;top:15px;right:10px;}
.toolbar{background:#a1a1a1;width:100%;height:30px;}
.fg-button {outline:0;width:24px;height:24px;margin:0 4px;margin-bottom:0; padding: 4px 8px; text-decoration:none !important; cursor:pointer; position: relative; text-align: center; zoom: 1;}
.fg-button2 {outline:0;width:24px;height:16px;margin:0 4px;margin-bottom:0; padding: 4px 8px; text-decoration:none !important; cursor:normal; position: relative; text-align: center; zoom: 1;}
a.fg-button { float:left;}
button.fg-button { width:auto; overflow:visible; }
.fg-button-icon-left { padding-left: 0; }
.fg-button-icon-right { padding-right: 0; }
.fg-button-icon-left .ui-icon { right: auto; left: 0 margin-left: 0; }
.fg-button-icon-right .ui-icon { left: auto; right: 0; margin-left: 0; }
.fg-button-icon-solo { display:block; width:8px; text-indent: -9999px; } /* solo icon buttons must have block properties for the text-indent to work */
.fg-buttonset { float:left;margin-right: 1.5em; }
.fg-buttonset .fg-button { float: left; }
.fg-buttonset-single .fg-button,
.fg-buttonset-multi .fg-button { margin-right: -1px;}
.db {background-image:url(../images/add-layer-pg.png) !important;}
.dir {background-image:url(../images/dir.png) !important;}
.add-layer-vector {background-image:url(../images/add-layer-vector.png) !important;}
.add-layer-raster {background-image:url(../images/add-layer-raster.png) !important;}
.add-layer-wfs {background-image:url(../images/add-layer-wfs.png) !important;}
.add-layer-wms {background-image:url(../images/add-layer-wms.png) !important;}
.add-layer-wcs {background-image:url(../images/add-layer-wcs.png) !important;}
.get-layer-info {background-image:url(../images/get-layer-info.png) !important;}
.export-layer {background-image:url(../images/export-layer.png) !important;}
.delete-layer {background-image:url(../images/delete-layer.png) !important;}
.maincfg1 {background-image:url(../images/main-config-server-icon.png) !important;}
.maincfg2 {background-image:url(../images/maincfg-identification-icon-blue.png) !important;}
/*
* Themes bar
*/
.theme-bar{width:100%;height:40px;}
.green{
float:left;
width:24px;
height:24px;
margin:10px 5px 0 10px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.blue{
float:left;
width:24px;
height:24px;
margin:10px 5px;
background: #44d0e5; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#44d0e5', endColorstr='#398ee4'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#44d0e5), to(#398ee4)); /* for webkit browsers */
background: -moz-linear-gradient(top, #44d0e5, #398ee4 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.purple{
float:left;
width:24px;
height:24px;
margin:10px 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #c743f8, #8340f3 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.pink{
float:left;
width:24px;
height:24px;
margin:10px 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
#nav {
position:relative;
top:7px;
left:295px;
margin: 0;
padding: 5px 4px 0;
line-height: 100%;
background: transparent;
border:0;
height:50px;
font-size:1.1em;
}
#nav li {
margin: 0 5px;
padding: 0 0 8px;
float: left;
position: relative;
list-style: none;
}
/* main level link */
#nav a {
font-weight: normal;
color: #e7e5e5;
text-decoration: none;
display: block;
padding: 8px 20px;
margin: 0;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
text-shadow: 0 1px 1px rgba(0, 0, 0, .3);
}
/* main level link hover */
#nav .current a {
background: #d1d1d1; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#a1a1a1'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#a1a1a1)); /* for webkit browsers */
background: -moz-linear-gradient(top, #ebebeb, #a1a1a1); /* for firefox 3.6+ */
color: #333333;
border-top: solid 1px #f8f8f8;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
#nav .datawarehousenav a, #nav .dashboard a {
background: #44d0e5; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#44d0e5', endColorstr='#398ee4'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#44d0e5), to(#398ee4)); /* for webkit browsers */
background: -moz-linear-gradient(top, #44d0e5, #398ee4 ); /* for firefox 3.6+ */
color: #FFFFFF;
border-top: solid 1px #398ee4;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(0, 0, 0, .8);
}
#nav .datawarehousenav a:hover, #nav .dashboard a:hover {
color: #FFFFFF;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(0, 0, 0, .8);
}
#nav li.datawarehousenav:hover > a, #nav li.dashboard:hover > a {
background: #44d0e5; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#44d0e5', endColorstr='#398ee4'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#44d0e5), to(#398ee4)); /* for webkit browsers */
background: -moz-linear-gradient(top, #44d0e5, #398ee4 ); /* for firefox 3.6+ */
border-top: solid 1px #398ee4;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(0,0,0, .8);
}
#nav li:hover > a {
background: #44d0e5; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#44d0e5', endColorstr='#398ee4'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#44d0e5), to(#398ee4)); /* for webkit browsers */
background: -moz-linear-gradient(top, #44d0e5, #398ee4 ); /* for firefox 3.6+ */
border-top: solid 1px #398ee4;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
/* sub levels link hover */
#nav ul li:hover a, #nav li:hover li a {
background: none;
border: none;
color: #666;
-webkit-box-shadow: none;
-moz-box-shadow: none;
}
/* level 2 list */
#nav ul {
background: #ddd; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#cfcfcf'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#cfcfcf)); /* for webkit browsers */
background: -moz-linear-gradient(top, #ffffff, #cfcfcf); /* for firefox 3.6+ */
display: none;
margin: 0;
padding: 0;
width: 185px;
position: absolute;
top: 38px;
left: 0;
border: solid 1px #b4b4b4;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
}
/* dropdown */
#nav li:hover > ul {
display: block;
}
#nav ul li {
float: none;
margin: 0;
padding: 0;
}
#nav ul a {
font-weight: normal;
text-shadow: 0 1px 1px rgba(255, 255, 255, .9);
}
/* level 3+ list */
#nav ul ul {
left: 181px;
top: -3px;
}
/* rounded corners for first and last child */
#nav ul li:first-child > a, #nav ul.orange li:first-child > a, #nav ul.purple li:first-child > a {
-webkit-border-top-left-radius: 9px;
-moz-border-radius-topleft: 9px;
-webkit-border-top-right-radius: 9px;
-moz-border-radius-topright: 9px;
}
#nav ul li:last-child > a, #nav ul.orange li:last-child > a, #nav ul.purple li:last-child > a {
-webkit-border-bottom-left-radius: 9px;
-moz-border-radius-bottomleft: 9px;
-webkit-border-bottom-right-radius: 9px;
-moz-border-radius-bottomright: 9px;
}
/* clearfix */
#nav:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#nav {
display: inline-block;
}
html[xmlns] #nav {
display: block;
}
* html #nav {
height: 1%;
}
<|start_filename|>public_map/assets/js/importers-public.js<|end_filename|>
// Filename: login.js
define([
'module', 'jquery', 'zoo','notify', 'metisMenu', 'summernote', 'xml2json','typeahead', 'adminBasic',"datepicker","fileinput","fileinput_local","managerTools"
], function(module, $,Zoo,notify, metisMenu, summernote, X2JS,typeahead,adminBasic,datepicker,fileinput,fileinput_local,managerTools) {
(function(){
var methods = ['addClass', 'removeClass'];
$.each(methods, function (index, method) {
var originalMethod = $.fn[method];
$.fn[method] = function () {
var oldClass = this.className;
var result = originalMethod.apply(this, arguments);
var newClass = this.className;
this.trigger(method, [oldClass, newClass]);
return result;
};
});
})();
var embedded=[];
var _x2js = new X2JS({
arrayAccessFormPaths: [
'ProcessDescriptions.ProcessDescription.DataInputs.Input',
'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
'Capabilities.ServiceIdentification.Keywords'
],
});
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
language: module.config().language
});
var mainTableSelectedId=null;
var mainTableFilter=[];
var mainTableFiles={};
var embeddedTableFilter=[];
var embeddedTableFiles=[];
var embeddedTableSelectedId=[];
var tableDisplayed={};
function displayTable(lid,ltype,tfields,rfields,tfilters){
console.log("START DISPLAY TABLE");
var cnt=0;
var CRowSelected=[];
var CFeaturesSelected=[];
var CFeatures=[];
//var rfields=mainTableRFields.join(",");
console.log(lid);
var myRootElement=$('#'+lid).parent().find(".btn-group").first().parent();
tableDisplayed[lid]=$('#'+lid).DataTable( {
language: {
url: module.config().translationUrl
},
data: [],
"dom": 'Zlfrtip',
"colResize": true,
autoWidth: false,
"scrollY": ($(window).height()/2)+"px",
"scrollCollapse": true,
"scrollX": true,
//"sScrollX": "100%",
//"sScrollXInner": "100%",
"bAutoWidth": false,
"bProcessing": true,
"bServerSide": true,
fixedHeader: true,
responsive: true,
deferRender: true,
crollCollapse: true,
rowId: 'fid',
"sAjaxSource": "users",
select: false,
"lengthMenu": [[5, 10, 25, 50, 1000], [5, 10, 25, 50, "All"]],
aoColumns: tfields,
/*"aoColumns": [
{ "sWidth": "10%", "target": 0 }, // 1st column width
{ "sWidth": "90%", "target": 1 }
],*/
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
console.log("Starting datatable download");
console.log(aoData);
var llimit=[];
for(j in {"iDisplayStart":0,"iDisplayLength":0,"iSortCol_0":0,"sSortDir_0":0,"sSearch":0})
for(i in aoData)
if(aoData[i].name==j){
if(llimit.length==4 && aoData[i].value!="")
llimit.push(aoData[i].value);
if(llimit.length<4)
llimit.push(aoData[i].value);
}
console.log(llimit);
var closestproperties=rfields;
var page=llimit[0]+1;
console.log(page);
if(page!=1){
page=(llimit[0]/llimit[1])+1;
console.log(page);
}
console.log(page);
var opts=zoo.getRequest({
identifier: "np.clientViewTable",
dataInputs: [
{"identifier":"table","value":ltype,"dataType":"string"},
{"identifier":"offset","value":llimit[0],"dataType":"int"},
{"identifier":"limit","value":llimit[1],"dataType":"int"},
{"identifier":"page","value":page,"dataType":"int"},
{"identifier":"sortorder","value":llimit[3],"dataType":"string"},
{"identifier":"sortname","value":(closestproperties.split(",")[llimit[2]]),"dataType":"string"},
{"identifier":"filters","value":JSON.stringify(tfilters, null, ' '),"mimeType":"application/json"}
],
dataOutputs: [
{"identifier":"Result","mimeType":"application/json","type":"raw"}
],
type: 'POST',
storeExecuteResponse: false
});
console.log(opts);
opts["success"]=function(rdata) {
features=rdata;
featureCount=rdata["total"];
var data=[];
CFeatures=[];
console.log(features);
for(var i in features.rows){
console.log(features.rows[i]);
var lparams={
"fid": lid+"_"+features.rows[i].id
}
var tmp=rfields.split(',');
for(var kk=0;kk<tmp.length;kk++)
lparams[tmp[kk]]=features.rows[i].cell[kk];
data.push(lparams);
CFeatures.push(data[data.length-1]);
}
var opts={
"sEcho": cnt++,
"iDraw": cnt++,
"iTotalRecords": featureCount,
"iTotalDisplayRecords": featureCount,
"aaData": (featureCount>0?data:[])
};
console.log(opts);
fnCallback(opts);
for(d in data){
if ( $.inArray(data[d].fid+"", CRowSelected) !== -1 ) {
console.log(data[d].fid);
$('#'+lid).DataTable().row($("#"+data[d].fid)).select();
}else{
$('#'+lid).DataTable().row($("#"+data[d].fid)).deselect();
}
}
if(featureCount==0){
$('#'+lid+'Table').DataTable().clear();
console.log("clear table");
}
console.log('finish');
};
opts["error"]=function(){
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
};
oSettings.jqXHR = $.ajax( opts );
}
});
$('#'+lid+' tbody').off('click');
$('#'+lid+' tbody').on('click', 'tr', function () {
console.log($(this));
var prefix=lid.replace(/mainListing_display/g,"");
console.log(prefix);
console.log(lid);
var row = $('#'+lid).DataTable().row($(this));
console.log(row);
console.log("ID: "+$(this).find("input[name=id]").val());
var test=$(this).hasClass("selected");
$('#'+lid+' tbody tr').each(function(){
$(this).removeClass("selected");
$('#'+lid).DataTable().row($(this)).deselect();
CRowSelected.pop();
});
if(!test){
if(lid=="mainListing_display")
mainTableSelectedId=$(this).find("input[name=id]").val();
else{
embeddedTableSelectedId.push({name:lid,value:$(this).find("input[name=id]").val()});
}
CRowSelected.push( lid+"_"+$(this).find("input[name=id]").val() );
$(this).addClass("selected");
$('#'+lid).DataTable().row($(this)).select();
if(prefix.indexOf("input_")<0)
$(".toActivate").each(function(){
$(this).children().first().click();
console.log($(this));
});
var params=[
{"identifier":"tableId","value":$("input[name="+prefix+"mainTableId]").val(),"dataType": "integer"},
{"identifier":"id","value":$(this).find("input[name=id]").val(),"dataType": "integer"}
];
var cid=$(this).find("input[name=id]").val();
if(prefix.indexOf("input_")<0)
adminBasic.callService("np.clientView",params,function(data){
for(i in data){
console.log(i);
console.log(data[i]);
var myRoot=$("#"+prefix+"edit0_"+i);
myRoot.find("input[name=edit_tuple_id]").val(cid);
console.log(myRoot);
for(j in data[i]){
console.log(data[i][j]);
if(data[i][j]){
if(!data[i][j].type){
myRoot.find("input[name=edit_"+j+"],select[name=edit_"+j+"],textarea[name=edit_"+j+"]").val(data[i][j]).change();
myRoot.find("input[name=edit_"+j+"],select[name=edit_"+j+"],textarea[name=edit_"+j+"]").each(function(){
if($(this).hasClass("htmlEditor")){
$(this).code(data[i][j]);
}
});
}else{
myRoot.find("input[name=edit_"+j+"]").each(function(){
var closure=$(this);
$(this).fileinput('destroy');
var cname=data[i][j]["filename"].split('/');
var display=data[i][j]["fileurl"];
var regs=[RegExp("tif","g"),RegExp("gif","g"),RegExp("png","g"),RegExp("jpg","g"),RegExp("jpeg","g")];
var isImage=false;
for(var l=0;l<regs.length;l++){
if(data[i][j]["fileurl"]!=data[i][j]["fileurl"].replace(regs[l],"")){
isImage=true;
break;
}
}
isRecognizedFileType=false;
var recognizedFileTypes=[
[RegExp("pdf","g"),"fa-file-pdf-o"],
[RegExp("doc","g"),"fa-file-word-o"],
[RegExp("xls","g"),"fa-file-excel-o"],
[RegExp("ppt","g"),"fa-file-powerpoint-o"],
[RegExp("dbf","g"),"fa-table"],
[RegExp("csv","g"),"fa-table"],
[RegExp("zip","g"),"fa-file-zip-o"],
["default","fa-external-link"]
];
var iClass=recognizedFileTypes[recognizedFileTypes.length-1][1];
for(var l=0;l<recognizedFileTypes.length;l++){
if(data[i][j]["fileurl"]!=data[i][j]["fileurl"].replace(recognizedFileTypes[l][0],"")){
isRecognizedFileType=true;
iClass=recognizedFileTypes[l][1];
break;
}
}
$(this).fileinput({
initialPreview: [
'<a href="'+data[i][j]["fileurl"]+'" target="_blank">'+(isImage?'<img src="'+data[i][j]["fileurl"]+'" style="height:160px" />':'<i class="fa '+iClass+'" aria-hidden="true" style="font-size: 10em;"></i>')+'</a>'
],
initialPreviewAsData: true,
initialPreviewConfig: [
{caption: cname[cname.length-1], width: "120px"}
],
overwriteInitial: true,
language: module.config().lang,
uploadUrl: module.config().url+"?service=WPS&version=1.0.0&request=Execute&RawDataOutput=Result&Identifier=upload.saveOnServer0&dataInputs=filename="+closure.attr("name")+";"+closure.attr("name")+"=Reference@isFile=true;dest=none",
uploadAsync: true,
maxFileCount: 1,
});
$(this).on('fileuploaded', function(event, data, previewId, index) {
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
console.log('File uploaded triggered');
mainTableFiles[closure.attr("name")]=data.response.files[0].fileName;
console.log(data);
console.log(data.response.files[0].fileName);
});
});
}
}
}
}
try{
if(prefix==""){
console.log("____ loadEmbeddedTables ____");
loadEmbeddedTables(function(i){
console.log("____ EmbeddedTables load "+embeddeds[i].id);
//$("embedded_"+i+"_mainListing_display").dataTable().fnDraw();
//$.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
console.log("____ EmbeddedTables loaded"+i);
displayTable(embeddeds[i].id+"mainListing_display",$("input[name="+embeddeds[i].id+"mainTableViewId]").val(),embeddeds[i].mainTableFields,embeddeds[i].mainTableRFields.join(","),embeddedTableFilter[i]);
});
console.log("____ loadEmbeddedTables");
}
}catch(e){
console.log(e);
console.log("---- No embedded tables");
}
$(".notifications").notify({
message: { text: "Tuple loaded." },
type: 'success',
}).show();
},function(data){
myRoot.append(data["ExceptionReport"]["Exception"]["ExceptionText"].toString());
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
});
else{
console.log("**** TRAITEMENT DES INPUT TABLES"+"****");
$("input[name="+prefix+"link_val]").val($(this).find("input[name=id]").val());
}
$(".require-"+prefix+"select").show();
}else{
$(".require-"+prefix+"select").hide();
mainTableSelectedId=null;
}
console.log(row);
});
$(".mmFile").each(function(){
var closure=$(this);
$(this).fileinput({
language: module.config().lang,
uploadUrl: module.config().url+"?service=WPS&version=1.0.0&request=Execute&RawDataOutput=Result&Identifier=upload.saveOnServer0&dataInputs=filename="+closure.attr("name")+";"+closure.attr("name")+"=Reference@isFile=true;dest=none", // server upload action
uploadAsync: true,
maxFileCount: 1,
done: function (e, data) {
console.log(data);
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
}
});
$(this).on('fileuploaded', function(event, data, previewId, index) {
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
console.log('File uploaded triggered');
mainTableFiles[closure.attr("name")]=data.response.files[0].fileName;
console.log(data);
console.log(data.response.files[0].fileName);
});
});
}
function bindSave(){
$("[data-mmaction=runPrint]").click(function(){
var closure=$(this);
$(this).addClass("disabled");
console.log($(this).children().first().next());
$(this).children().first().next().show();
$(this).children().first().hide();
var tableId=null;
var tupleId=null;
if($(this).parent().parent().attr('id').indexOf('embedded')>=0){
var closure=$(this);
for(var i=0;i<2;i++)
closure=closure.parent();
tmp=closure.attr('id').split('report')
for(var i=0;i<embeddedTableSelectedId.length;i++){
if(embeddedTableSelectedId[i].name==tmp[0]+"mainListing_display"){
tupleId=embeddedTableSelectedId[i].value;
tableId=$("#"+tmp[0]+"listing").find('input[name='+tmp[0]+'mainTableId]').val();
break;
}
}
}else{
tableId=$('#listing').first().find('input[name=mainTableId]').val();
tupleId=mainTableSelectedId;
}
console.log($(this).parent().parent().attr('id'));
console.log(mainTableSelectedId);
console.log(embeddedTableSelectedId);
console.log($('#listing').first().find('input[name=mainTableId]').val());
params=[
{identifier: "tableId", value: tableId, dataType: "string"},
{identifier: "id", value: tupleId, dataType: "string"}
];
closure=$(this);
adminBasic.callService("np.clientPrint",params,function(data){
console.log(data)
closure.removeClass("disabled");
closure.children().first().show();
closure.children().first().next().hide();
closure.parent().parent().find(".report_display").html('');
var ul=$(managerTools.generateFromTemplate($("#"+closure.parent().parent().attr("id")+"_link_list").html(),[],[]));
for(i=0;i<data.length;i++){
var format="odt";
var classe="fa-file-text-o";
if(data[i].indexOf("pdf")>0){
format="pdf";
classe="fa-file-pdf-o";
}
if(data[i].indexOf("doc")>0){
format="doc";
classe="fa-file-word-o";
}
if(data[i].indexOf("html")>0){
format="html";
classe="fa-code";
}
ul.find(".list-group").append(
managerTools.generateFromTemplate($("#"+closure.parent().parent().attr("id")+"_link").html(),["link","format","class"],[data[i],format,classe])
);
}
closure.parent().parent().find(".report_display").html(ul);
});
});
$("[data-mmaction=save]").click(function(){
console.log('* Run save function');
var myRoot=$(this).parent();
console.log(myRoot);
var myRoot1=$(this).parent().parent();
console.log(myRoot1);
params=[];
var tupleReal={};
myRoot.find("script").each(function(){
if($(this).attr('id').indexOf('runFirst')>=0)
return;
console.log($(this));
try{
console.log("**********- "+(myRoot1.attr('id').indexOf('embedded')<0));
console.log("**********- "+(!$(this).parent().attr('id')));
console.log("**********- "+($(this).parent().attr('id').indexOf("mm_table_editor_form")<0));
}catch(e){
console.log(e);
}
console.log($(this).parent().parent().parent());
console.log($(this).parent().parent().parent().parent());
if((myRoot1.attr('id') && myRoot1.attr('id').indexOf('input')>=0) || (myRoot1.attr('id') && myRoot1.attr('id').indexOf('embedded')<0 && (!myRoot.attr('id') || myRoot.attr('id').indexOf("mm_table_editor_form")<0)))
return;
console.log($(this).attr("name"));
console.log($(this).attr("id"));
console.log($(this)[0].innerHTML);
tupleReal[$(this).attr("id").replace(/edition_/,"")]=$(this)[0].innerHTML;
});
var tuple={};
myRoot.find("input,textarea,select").each(function(){
try{
// ISSUE WITH upload
console.log($(this));
var noDisplay=false;
try{
console.log("**********- "+myRoot1.attr('id'))
noDisplay=(($(this).attr("id").replace(/edition_/,"")=="tuple_id") ||
($(this).attr("id").replace(/edition_/,"")=="table_id") ||
($(this).attr("id").replace(/edition_/,"")=="edition_id") );
console.log($(this).attr("id").replace(/edition_/,""));
console.log("**********- "+(myRoot1.attr('id').indexOf('embedded')<0));
console.log("**********- "+($(this).parent().parent().parent().parent().attr('id').indexOf("embedded_")>=0));
console.log("**********- "+($(this).parent().parent().parent().attr('id').indexOf("embedded_")>=0));
}catch(e){
console.log(e);
}
if(noDisplay || (myRoot1.attr('id').indexOf('embedded')<0 && (
($(this).parent().parent().parent().parent().attr('id') &&
$(this).parent().parent().parent().parent().attr('id').indexOf("embedded_")>=0)
||
($(this).parent().parent().parent().attr('id') && $(this).parent().parent().parent().attr('id').indexOf("embedded_")>=0)) ) )
return;
console.log($(this).parent().parent().parent());
console.log($(this).parent().parent().parent().parent());
if(!mainTableFiles[$(this).attr("name")]){
if($(this).attr("name").indexOf("link_col")<0)
tuple[$(this).attr("id").replace(/edition_/,"")]=$(this).val();
else{
tuple[$(this).val()]=$(this).next().val();
tupleReal={};
}
}
else{
tuple[$(this).attr("id").replace(/edition_/,"")]=mainTableFiles[$(this).attr("name")];
mainTableFiles[$(this).attr("name")]=null;
}
}catch(e){
console.log($(this));
}
});
var parts=myRoot1.attr('id').split("_");
if(parts[0]=="embedded"){
var ei=parseInt(parts[1]);
var obj=embeddedTableFilter[ei][0];
console.log(obj);
for(var key in obj)
if(key!="linkClause")
tuple[key]=obj[key];
}
myRoot1.find("#edition_table_id").last().each(function(){
params.push({identifier: "tableId", value: $(this).val(), dataType: "string"});
});
myRoot1.find("#edition_edition_id").last().each(function(){
params.push({identifier: "editId", value: $(this).val(), dataType: "string"});
});
myRoot1.find("#edition_tuple_id").last().each(function(){
params.push({identifier: "id", value: $(this).val(), dataType: "string"});
});
params.push({identifier: "tuple", value: JSON.stringify(tuple, null, ' '), mimeType: "application/json"});
params.push({identifier: "tupleReal", value: JSON.stringify(tupleReal, null, ' '), mimeType: "application/json"});
console.log(params);
adminBasic.callService("np.clientInsert",params,function(data){
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
console.log("RELOAD UPDATED LIST");
console.log(myRoot1.parent().parent().parent().prev());
var lRoot=myRoot1.parent().parent().parent().prev();
var tlRoot=lRoot.find('li').first().children().first();
try{
tlRoot.attr("href").indexOf("embedded")
}catch(e){
lRoot=myRoot1.parent().prev();
tlRoot=lRoot.find('li').first().children().first();
}
lRoot.find('li').first().children().first().click();
console.log(lRoot.find('li').first().children().first().attr("href"));
if(tlRoot.attr("href").indexOf("embedded")>=0){
var tid=tlRoot.attr("href").replace(/#/g,"").replace(/listing/g,"mainListing_display");
$(".require-"+tid.replace(/mainListing_display/g,"select")).hide();
tableDisplayed[tid].rows().every( function () {
tableDisplayed["mainListing_display"].row(this).deselect();
});
tableDisplayed[tid].columns.adjust().draw();
}
else if(tlRoot.attr("href")=="#listing"){
/*tableDisplayed["mainListing_display"].rows().each(function(){
$(this).deselect();
});*/
$(".require-select").hide();
//tableDisplayed["mainListing_display"].destroy();
//console.log("fnDraw");
//tableDisplayed["mainListing_display"].draw();
//alert('ok');
$("#mainListing_display").find('tr').each(function(){
console.log($(this));
if($(this).hasClass("selected"))
console.log($(this));
$(this).removeClass("selected");
//$(this).click();
});
tableDisplayed["mainListing_display"].rows().every( function () {
console.log(this);
console.log(tableDisplayed["mainListing_display"].row(this));
tableDisplayed["mainListing_display"].row(this).deselect();
});
tableDisplayed["mainListing_display"].columns.adjust().draw();
tableDisplayed["mainListing_display"].rows().every( function () {
console.log(this);
console.log(tableDisplayed["mainListing_display"].row(this));
tableDisplayed["mainListing_display"].row(this).deselect();
});
$("#mainListing_display").find('tr').each(function(){
console.log($(this));
$(this).removeClass("selected");
//$(this).click();
});
//displayTable("mainListing_display",$("input[name=mainTableViewId]").val(),mainTableFields,mainTableRFields.join(","),mainTableFilter);
}
//console.log(lRoot.next().find('.active').first().find('.dataTables_wrapper').first().attrd('id'));
},function(data){
myRoot.append('<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>'+data["ExceptionReport"]["Exception"]["ExceptionText"].toString()+'</div>');
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
});
console.log('* Save function end');
return false;
});
}
function bindDelete(){
$("[data-mmaction=delete]").click(function(){
console.log('* Run save function');
var myRoot=$(this).parent();
params=[];
var tuple={};
/*myRoot.find("input,textarea,select").each(function(){
console.log($(this).attr("name"));
console.log($(this).attr("id"));
console.log($(this).val());
if(!$(this).attr("id"))
return;
tuple[$(this).attr("id").replace(/edition_/,"")]=$(this).val();
});*/
var myRoot1=$(this).parent().parent();
myRoot1.find("#edition_table_id").each(function(){
params.push({identifier: "tableId", value: $(this).val(), dataType: "string"});
});
myRoot1.find("#edition_tuple_id").each(function(){
params.push({identifier: "tupleId", value: $(this).val(), dataType: "string"});
});
params.push({identifier: "tuple", value: JSON.stringify(tuple, null, ' '), mimeType: "application/json"});
console.log(params);
adminBasic.callService("np.clientDelete",params,function(data){
console.log(data);
var lRoot=myRoot1.parent().prev();
console.log(lRoot);
lRoot.find('li').first().children().first().click();
console.log(lRoot.find('li').first().children().first().attr("href"));
var tlRoot=lRoot.find('li').first().children().first();
if(tlRoot.attr("href").indexOf("embedded")>=0){
var tid=tlRoot.attr("href").replace(/#/g,"").replace(/listing/g,"mainListing_display");
$(".require-"+tid.replace(/mainListing_display/g,"select")).hide();
tableDisplayed[tid].rows().every( function () {
tableDisplayed["mainListing_display"].row(this).deselect();
});
tableDisplayed[tid].columns.adjust().draw();
}
else if(tlRoot.attr("href")=="#listing"){
$("#mainListing_display").find('tr').each(function(){
console.log($(this));
if($(this).hasClass("selected"))
console.log($(this));
$(this).removeClass("selected");
//$(this).click();
});
$(".require-select").hide();
tableDisplayed["mainListing_display"].rows().every( function () {
console.log(this);
console.log(tableDisplayed["mainListing_display"].row(this));
tableDisplayed["mainListing_display"].row(this).deselect();
});
tableDisplayed["mainListing_display"].columns.adjust().draw();
}
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
},function(data){
myRoot.append('<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>'+data["ExceptionReport"]["Exception"]["ExceptionText"].toString()+'</div>');
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
});
console.log('* Save function end');
return false;
});
}
function bindSearch(){
$("[data-mmaction=search]").click(function(){
console.log('* Run search function');
var myRoot=$(this).parent();
params=[];
var tuple={};
var lines="";
myRoot.find("input,textarea").each(function(){
if(!$(this).is(":disabled") && $(this).attr("id")!="edition_uid"){
try{
tuple[$(this).attr("id").replace(/edition_/,"")]=$(this).val();
lines+=managerTools.generateFromTemplate($("#filter_line_template")[0].innerHTML,["line"],[$(this).parent().parent().prev().html()+" - "+$(this).val()]);
}catch(e){
console.log($(this));
}
}
});
var clause="";
myRoot.find("select").each(function(){
if(!$(this).is(":disabled")){
try{
tuple[$(this).attr("id").replace(/edition_/,"")]=$(this).val();
if($(this).attr("id")!="edition_linkClause"){
lines+=managerTools.generateFromTemplate($("#filter_line_template")[0].innerHTML,["line"],[$(this).parent().parent().prev().html()+" - "+$(this).find("option:selected").text()]);
}else
clause=$(this).val();
}catch(e){
console.log($(this));
}
}
});
console.log('************** '+clause+' **********************');
$("#listing").prepend(managerTools.generateFromTemplate($("#filter_complete_template")[0].innerHTML,["type","id","cid","body"],[(clause!="OR"?"info":"primary"),mainTableFilter.length,mainTableFilter.length+1,lines]));
mainTableFilter.push(tuple);
$("#listing").find(".close").each(function(){
$(this).off('click');
$(this).on('click',function(e){
console.log($(this).parent().parent());
var cid=parseInt($(this).parent().attr('id').replace(/filter_/,""));
mainTableFilter.splice(cid,1);
var lRoot=$(this).parent().parent();
$(this).parent().remove();
console.log(cid);
lRoot.find(".alert").each(function(){
var lcid=parseInt($(this).attr('id').replace(/filter_/,""));
console.log(lcid);
if(lcid>cid){
$(this).attr('id',"filter_"+(lcid+(cid-lcid)));
var content=$(this).find("strong").html();
console.log(content);
var cReg=new RegExp(" "+(lcid+1),"g");
console.log(" "+((lcid+(cid-lcid))+1));
console.log(" "+(cid+1));
console.log(content.replace(cReg," "+((lcid+(cid-lcid))+1)));
$(this).find("strong").html(content.replace(cReg," "+((lcid+(cid-lcid))+1)));
}
});
$("#mainListing_display").dataTable().fnDraw();
$.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
});
});
$("#mainListing_display").dataTable().fnDraw();
$.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
console.log('* Search function end');
return false;
});
}
function loadEmbeddedTables(func){
embeddedTableFilter=[];
//var prefix="embedded_"+i;
for(var i=0;i<embeddeds.length;i++){
var prefix=embeddeds[i].id;
console.log(prefix);
if(tableDisplayed[prefix+"mainListing_display"])
tableDisplayed[prefix+"mainListing_display"].destroy();
embeddedTableFilter.push([]);
var oRoot=$("#"+prefix+"mainListing_display");
console.log(oRoot);
for(var j=0;j<6;j++){
oRoot=oRoot.parent();
console.log(oRoot);
}
console.log(oRoot);
var lRoot=oRoot.find("input").last();
console.log(lRoot);
if(lRoot.length==0){
console.log("************ "+oRoot.parent().parent().parent());
lRoot=oRoot.parent().parent().parent().find("input").last();
}
lRoot.each(function(){
console.log($(this));
var lid=oRoot.find("input[name="+prefix+"link_col]").val();
console.log(lid);
var obj={"linkClause":" AND "};
obj[lid]=$(this).val();
embeddedTableFilter[i].push(obj);
});
console.log(lRoot);
try{
func(i);
}catch(e){
console.log('!!!!! ERROR: '+e);
}
}
}
var changingFields=[];
var initialize=function(){
var closure=this;
$('#side-menu').metisMenu({ toggle: false });
$('#side-menu').css({"max-height": ($(window).height()-50)+"px","overflow":"scroll"});
adminBasic.initialize(zoo);
$(".mmdatastore").click(function(e){
document.location=$(this).attr("href");
return false;
});
displayTable("mainListing_display",$("input[name=mainTableViewId]").val(),mainTableFields,mainTableRFields.join(","),mainTableFilter);
$(".tab-pane").find("script").each(function(){
try{
changingFields.push(JSON.parse("{\""+$(this).attr('name')+"\":"+$(this).html()+"}"));
console.log(changingFields);
var lname=$(this).attr('name');
/*
* Create the options array containing initial values
*/
$(this).parent().find('select[name='+$(this).attr('name')+']').first().find('option').each(function(){
console.log(changingFields[changingFields.length-1][lname])
for(var i in changingFields[changingFields.length-1][lname]){
for(var j in changingFields[changingFields.length-1][lname][i]){
changingFields[changingFields.length-1][lname][i][j]["options"].push($(this).val());
}
}
});
/*
* Load all the corresponding values
*/
for(var i=0;i<changingFields[changingFields.length-1][lname].length;i++){
changingFields[changingFields.length-1][lname][i]["myEditId"]=$(this).parent().parent().attr('id').replace(/edit_/g,"").replace(/edit0_/g,"");
var closure=$(this);
for(var j in changingFields[changingFields.length-1][lname][i])
if(j!="myEditId"){
console.log(lname);
(function(closure,ref){
zoo.execute({
"identifier": "template.display",
"type": "POST",
dataInputs: [
{"identifier":"tmpl","value":"public/modules/tables/fetchDependencies_js","dataType":"string"},
{"identifier":"elements","value":JSON.stringify(changingFields[changingFields.length-1]),"mimeType":"applicaiton/json"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
closure.parent().find('select[name='+closure.attr('name')+']').first().off('change');
(function(data){
closure.parent().find('select[name='+closure.attr('name')+']').first().change(function(){
console.log(ref)
console.log($(this).val());
console.log(data)
console.log(data[$(this).val()])
console.log($(this).parent().parent().parent().parent().find("[name=edit_"+data[$(this).val()]['id']+"]"));
$(this).parent().parent().parent().parent().find("[name=edit_"+data[$(this).val()]['id']+"]").html("");
if(data[$(this).val()]['value'].length>0)
for(var j=0;j<data[$(this).val()]['value'].length;j++)
$(this).parent().parent().parent().parent().find("[name=edit_"+data[$(this).val()]['id']+"]").append('<option value="'+data[$(this).val()]['value'][j][0]+'">'+data[$(this).val()]['value'][j][1]+'</option>');
else
$(this).parent().parent().parent().parent().find("[name=edit_"+data[$(this).val()]['id']+"]").append('<option value="NULL">'+module.config().localizationStrings.tables.none+'</option>');
});
closure.parent().find('select[name='+closure.attr('name')+']').first().change();
})(data);
console.log("SUCCESS");
},
error: function(data){
console.log("ERROR");
console.log(data);
}
});
})(closure,j);
}
}
//console.log($(this).attr('name'));
}catch(e){
console.log(e);
}
});
console.log(embedded);
try{
for(var i=0;i<embeddeds.length;i++){
$(".require-embedded_"+i+"_select").hide();
}
}catch(e){
console.log("----- DEBUG :"+e);
}
try{
console.log("+++++++ "+iembeddeds);
for(var i=0;i<iembeddeds.length;i++){
$(".require-"+iembeddeds[i]["id"]+"select").hide();
console.log("+++++++ "+iembeddeds[i]["id"]+"mainListing_display");
displayTable(iembeddeds[i]["id"]+"mainListing_display",$("input[name="+iembeddeds[i]["id"]+"mainTableViewId]").val(),iembeddeds[i].mainTableFields,iembeddeds[i].mainTableRFields.join(","),[]);
}
}catch(e){
console.log("----- DEBUG :"+e);
}
/*try{
loadEmbeddedTables(function(i){
displayTable("embedded_"+i+"_mainListing_display",$("input[name=embedded_"+i+"_mainTableViewId]").val(),embeddeds[i].mainTableFields,embeddeds[i].mainTableRFields.join(","),embeddedTableFilter[i]);
});
}catch(e){
console.log("No embedded tables");
}*/
$(".require-select").hide();
$("#listing_Toggler").click();
bindSave();
bindSearch();
bindDelete();
$("textarea.htmlEditor").each(function(){
var closure=$(this);
window.setTimeout(function () {
closure.summernote();
},500);
});
$('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
$.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
} );
console.log("Start Table Public Module");
};
// Return public methods
return {
initialize: initialize,
datepicker: datepicker,
embedded: embedded
};
});
<|start_filename|>mapmint-ui/css/layout-default-latest.css<|end_filename|>
/*
MapMint default Cascading Style Sheet
Copyright Cartoworks Inc. 2010
*/
body {
font: 12px Verdana, Arial, Helvetica, sans-serif;
background: url(../images/main-bg2.png);
padding: 0;
margin: 0;
}
h1{
margin:0;padding:5px;background: #d1d1d1; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#a1a1a1'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#a1a1a1)); /* for webkit browsers */
background: -moz-linear-gradient(top, #ebebeb, #a1a1a1); /* for firefox 3.6+ */
font-size:1.1em;font-weight:normal;text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
h2{
color:#565656;
margin:0;padding:5px;background: transparent;
font-size:1.1em;font-weight:bold;
}
/*
* Panes & content divs
*/
.ui-layout-pane {
background: #d7d7d7;
border:1px solid #BBB;
padding:10px;
overflow:hidden;
}
.ui-layout-content {
padding:0px;
position:relative;
overflow:hidden;
}
.ui-layout-center{
padding:0px;
background:transparent;
border:0;
overflow:hidden;
}
.inner-layout-container .ui-layout-pane {
overflow:auto;
}
.close {width:17px;height:16px;background:url(../images/close-sidebar.png);float:right;}
.close:hover {width:17px;height:16px;background:url(../images/close-sidebar-hover.png);float:right;}
.close-toolbar, .close-toolbar2 {width:17px;height:16px;background:url(../images/close-toolbar.png);float:right;}
.close-toolbar:hover, close-toolbar2:hover {width:17px;height:16px;background:url(../images/close-toolbar-hover.png);float:right;}
/*** IMPORTANT - do not modify ***/
.inner-layout-container { height:100%;}
.ui-layout-center,.ui-layout-north,.ui-layout-south,.inner-center,.inner-west,.inner-east {display:none;}
.inner-center,.inner-west,.inner-east {padding:0px;}
.ui-layout-north{
overflow:hidden;
background:#565656 url(../images/mapmint-logo-in.png) no-repeat;
border:0;
margin:0;
padding:0;
height:50px;
max-height:50px;
}
.ui-layout-south{
overflow:hidden;
background:#565656;
border:0;
margin:0;
padding:0;
height:50px;
max-height:50px;
}
p.credits{float:left;margin:1em;color:#FFFFFF;}
p.credits a{text-decoration:none;color:#FFFFFF;}
p.credits a:hover{text-decoration:underline;color:chartreuse;}
/*
* Resizer bars
*/
.ui-layout-resizer{background:transparent;}
.ui-layout-resizer-drag {}
.ui-layout-resizer-hover{}
.ui-layout-resizer-open-hover{background:transparent;}
.ui-layout-resizer-dragging{background:transparent;}
.ui-layout-resizer-dragging {border-left:1px solid #BBB;border-right: 1px solid #BBB;}
.ui-layout-resizer-dragging-limit{background:transparent;}
.ui-layout-resizer-closed-hover{background:transparent;}
.ui-layout-resizer-sliding {opacity: .10;filter: alpha(opacity=10);}
.ui-layout-resizer-sliding-hover{opacity: 1.00;filter: alpha(opacity=100);}
.ui-layout-resizer-north-sliding-hover { border-bottom-width: 1px; }
.ui-layout-resizer-south-sliding-hover { border-top-width: 1px; }
.ui-layout-resizer-west-sliding-hover { border-right-width: 1px; }
.ui-layout-resizer-east-sliding-hover { border-left-width: 1px; }
/*
* Toggler buttons
*/
.ui-layout-toggler{border: 1px solid #BBB;background-color: #BBB;}
.ui-layout-resizer-hover .ui-layout-toggler{opacity: .60;filter: alpha(opacity=60);}
.ui-layout-resizer-hover .ui-layout-toggler-hover{ background-color: #6fd105;opacity:1.00;filter:alpha(opacity=100);}
.ui-layout-toggler-north,.ui-layout-toggler-south{border-width: 0 1px;}
.ui-layout-toggler-west,.ui-layout-toggler-east{border-width: 1px 0;}
.ui-layout-resizer-sliding, .ui-layout-toggler{display: none;}
/*
* Tooltips
*/
.tipsy { padding: 5px; font-size: 10px; position: absolute; z-index: 1000000000000; }
.tipsy-inner { padding: 5px 8px 4px 8px; background-color:#565656; color: white; max-width: 200px; text-align: center; }
.tipsy-inner { border-radius: 3px; -moz-border-radius:3px; -webkit-border-radius:3px; }
.tipsy-arrow { position: absolute; background:transparent no-repeat top left; width: 9px; height: 5px; }
.tipsy-n .tipsy-arrow { top: 0; left: 50%; margin-left: -4px; }
.tipsy-nw .tipsy-arrow { top: 0; left: 10px; }
.tipsy-ne .tipsy-arrow { top: 0; right: 10px; }
.tipsy-s .tipsy-arrow { bottom: 0; left: 50%; margin-left: -4px; background-position: bottom left; }
.tipsy-sw .tipsy-arrow { bottom: 0; left: 10px; background-position: bottom left; }
.tipsy-se .tipsy-arrow { bottom: 0; right: 10px; background-position: bottom left; }
.tipsy-e .tipsy-arrow { top: 50%; margin-top: -4px; right: 0; width: 5px; height: 9px; background-position: top right; }
.tipsy-w .tipsy-arrow { top: 50%; margin-top: -4px; left: 0; width: 5px; height: 9px; }
.tabs{ margin:0;
width:100%;
font-size:1em;
color:#565656;
background: #FFFFFF url(../images/wbg1.png) repeat-x}
/*
* Dashboard style
*/
.datawarehouse {width:100%;height:75px;margin:0;background: #333333 url(../images/wbg.gif) repeat-x;
}
.datawarehouse img {display:inline;float:left;margin:0;padding:0;position:relative;top:20px;left:20px;}
.datawarehouse p a{display:inline;float:left;position:relative;top:0;left:70px;padding:0;color:#43cb1f;font-size:1.1em;text-decoration:none;-moz-border-radius:3px;background:#FFFFFF;padding:3px 10px 3px 10px;margin:0 10px 0 0;}
.datawarehouse p a:hover{display:inline;float:left;position:relative;top:0;left:70px;padding:0;color:#FFFFFF;font-size:1.1em;text-decoration:none;-moz-border-radius:3px;background:#43cb1f;padding:3px 10px 3px 10px;margin:0 10px 0 0;}
.styler {width:100%;height:75px;background: #FFFFFF url(../images/wbg.gif) repeat-x;
}
.styler img {display:inline;float:left;margin:0;padding:0;position:relative;top:20px;left:20px;}
.styler p a{display:inline;float:left;position:relative;top:0;left:70px;padding:0;color:#43cb1f;font-size:1.1em;text-decoration:none;-moz-border-radius:3px;background:#FFFFFF;padding:3px 10px 3px 10px;margin:0 10px 0 0;}
.styler p a:hover{display:inline;float:left;position:relative;top:0;left:70px;padding:0;color:#FFFFFF;font-size:1.1em;text-decoration:none;-moz-border-radius:3px;background:#43cb1f;padding:3px 10px 3px 10px;margin:0 10px 0 0;}
.mapmanager {width:100%;height:75px;background: #FFFFFF url(../images/wbg.gif) repeat-x;
}
.mapmanager img {display:inline;float:left;margin:0;padding:0;position:relative;top:20px;left:20px;}
.mapmanager p a{display:inline;float:left;position:relative;top:0;left:70px;padding:0;color:#43cb1f;font-size:1.1em;text-decoration:none;-moz-border-radius:3px;background:#FFFFFF;padding:3px 10px 3px 10px;margin:0 10px 0 0;}
.mapmanager p a:hover{display:inline;float:left;position:relative;top:0;left:70px;padding:0;color:#FFFFFF;font-size:1.1em;text-decoration:none;-moz-border-radius:3px;background:#43cb1f;padding:3px 10px 3px 10px;margin:0 10px 0 0;}
.doceditor{width:100%;height:75px;background: #FFFFFF url(../images/wbg.gif) repeat-x;border-bottom:1px solid #E1E1E1;
}
.doceditor img {display:inline;float:left;margin:0;padding:0;position:relative;top:20px;left:20px;}
.doceditor p a{display:inline;float:left;position:relative;top:0;left:70px;padding:0;color:#43cb1f;font-size:1.1em;text-decoration:none;-moz-border-radius:3px;background:#FFFFFF;padding:3px 10px 3px 10px;margin:0 10px 0 0;}
.doceditor p a:hover{display:inline;float:left;position:relative;top:0;left:70px;padding:0;color:#FFFFFF;font-size:1.1em;text-decoration:none;-moz-border-radius:3px;background:#43cb1f;padding:3px 10px 3px 10px;margin:0 10px 0 0;}
.webpublisher{width:100%;height:75px;background: #FFFFFF url(../images/wbg.gif) repeat-x;
}
.webpublisher img {display:inline;float:left;margin:0;padding:0;position:relative;top:20px;left:20px;}
.webpublisher p a{display:inline;float:left;position:relative;top:0;left:70px;padding:0;color:#43cb1f;font-size:1.1em;text-decoration:none;-moz-border-radius:3px;background:#FFFFFF;padding:3px 10px 3px 10px;;margin:0 10px 0 0;}
.webpublisher p a:hover{display:inline;float:left;position:relative;top:0;left:70px;padding:0;color:#FFFFFF;font-size:1.1em;text-decoration:none;-moz-border-radius:3px;background:#43cb1f;padding:3px 10px 3px 10px;margin:0 10px 0 0;}
.documentation {width:100%;height:60px;margin:0;padding:0;background:#E7E7E7 url(../images/documentation-icon.png) no-repeat;background-position:3px 3px;}
.datawarehouse h2,.styler h2, .mapmanager h2, .doceditor h2, .webpublisher h2, .documentation h2{
margin:0;padding:7px 0 0 70px;background:transparent; display:block;
;font-size:1.2em;font-weight:normal;text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
.datawarehouse h3, .mapmanager h3, .doceditor h3, .webpublisher h3, .documentation h3{
float:left;position:absolute;margin:0;padding:30px 0 0 70px;background:transparent;font-size:1.1em;font-weight:normal;color:#333333;
}
.toolbar, .datasource-toolbar {background:#a1a1a1;width:100%;height:40px;}
.map-nav-toolbar{position:absolute;top:38px;left:10px;width:180px;height:33px;z-index:1000000;-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .4);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .4);
box-shadow: 0 1px 1px rgba(0, 0, 0, .4);}
.map-tools-toolbar{width:60%;margin:0 auto;z-index:1000000;}
#mposition{position:absolute;bottom:10px;left:10px;font-weight:normal;font-size:0.9em;text-align:center;line-height:28px;width:144px;height:28px;z-index:1000000;-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .4);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .4);
box-shadow: 0 1px 1px rgba(0, 0, 0, .4);}
.f{margin-top:6px;}
.fg-button {width:28px;height:28px;margin:1px 3px;padding:0; text-decoration:none !important; cursor:pointer; position: relative; text-align: center;}
.fg-button-big {outline:0;width:32px;height:32px;margin:10px 0;margin-bottom:0; padding:0; text-decoration:none !important; cursor:normal; position: relative; text-align: center; zoom: 1;}
a.fg-button { float:left;}
a.fg-button-big { float:left;}
button.fg-button, button.fg-button-big { width:auto; overflow:visible; }
.fg-button-icon-left { padding-left: 0; }
.fg-button-icon-right { padding-right: 0; }
.fg-button-icon-left .ui-icon { right: auto; left: 0 margin-left: 0; }
.fg-button-icon-right .ui-icon { left: auto; right: 0; margin-left: 0; }
.fg-button-icon-solo { display:block; width:8px; text-indent: -9999px; } /* solo icon buttons must have block properties for the text-indent to work */
.fg-buttonset { float:left;margin-right:0; }
.fg-buttonset .fg-button { float: left; }
.fg-buttonset-single .fg-button,
.fg-buttonset-multi .fg-button { margin-right: -1px;}
input.rounded{width:100%;height:20px;margin:1px;-moz-border-radius:5px;border:1px solid #9f9f9f;
}
input.name{width:65%;height:20px;margin:1px;-moz-border-radius:5px;border:1px solid #9f9f9f;margin-left:10px;
}
textarea.maincfg{width:100%;height:100px;margin:1px;-moz-border-radius:5px;border:1px solid #9f9f9f;font: .9em Verdana;
}
.dialogs{border:0;background:transparent;margin:0;width:100%;font-size:0.9em;}
.db {background-image:url(../images/add-layer-pg.png) !important;}
.dir {background-image:url(../images/dir.png) !important;}
.add-layer-vector {background-image:url(../images/add-layer-vector.png) !important;}
.add-layer-raster {background-image:url(../images/add-layer-raster.png) !important;}
.add-layer-wfs {background-image:url(../images/add-layer-wfs.png) !important;}
.add-layer-wms {background-image:url(../images/add-layer-wms.png) !important;}
.add-layer-wcs {background-image:url(../images/add-layer-wcs.png) !important;}
.get-layer-info {background-image:url(../images/get-layer-info.png) !important;}
.export-layer {background-image:url(../images/export-layer.png) !important;}
.delete-layer {background-image:url(../images/delete-layer.png) !important;}
.maincfg1 {background-image:url(../images/main-config-server-icon.png) !important;}
.maincfg2 {background-image:url(../images/main-config-identify-icon.png) !important;}
.maincfg3 {background-image:url(../images/main-config-people-icon.png) !important;}
.pan {background-image:url(../images/pan.png) !important;}
.zoommaxextent {background-image:url(../images/zoom-maxextent.png)!important;}
.zoombox {background-image:url(../images/zoom-extent.png)!important;}
.zoom-last {background-image:url(../images/zoom-last.png)!important;}
.zoom-next {background-image:url(../images/zoom-next.png)!important;}
.identify {background-image:url(../images/identify.png)!important;}
.measure-dist{background-image:url(../images/measure-dist.png)!important;}
.measure-area{background-image:url(../images/measure-area.png)!important;}
.point {background-image:url(../images/point.png) !important;}
.line {background-image:url(../images/line.png) !important;}
.polygon {background-image:url(../images/polygon.png) !important;}
.select-feature {background-image:url(../images/select-feature.png)!important;}
.add-point {background-image:url(../images/add-point.png)!important;}
.add-line {background-image:url(../images/add-line.png)!important;}
.add-polygon {background-image:url(../images/add-polygon.png)!important;}
.delete-feature {background-image:url(../images/delete-feature.png)!important;}
.buffer{background-image:url(../images/buffer.png)!important;}
.centroid{background-image:url(../images/centroid.png)!important;}
.convexhull{background-image:url(../images/convexhull.png)!important;}
.boundary{background-image:url(../images/boundary.png)!important;}
.simplify{background-image:url(../images/simplify.png)!important;}
.union{background-image:url(../images/union.png)!important;}
.intersection{background-image:url(../images/intersection.png)!important;}
.vector-styles{background-image:url(../images/vector-styles.png)!important;}
.raster-styles{background-image:url(../images/raster-styles.png)!important;}
ul.styles{list-style:none;width:100%;margin:1em 0;padding:0;}
ul.styles li{list-style:none;background: url(../images/wbg.gif) repeat-x top;
margin:0;padding:5px 0;text-indent:5px;}
ul.styles li img{vertical-align:bottom;margin-left:10px;margin-right:10px;}
.dropdown-toolbars {float:left;width:150px;max-width:150px;height:29px;margin:0;padding:4px;padding-top:2px;font-size:1em;font-weight:normal;c}
.dropdown-toolbars dd, .dropdown-toolbars dt, .dropdown-toolbars ul {margin:0px; padding:0px; font-size:1em;font-weight:normal;}
.dropdown-toolbars dd {position:absolute;}
.dropdown-toolbars a, .dropdown a:visited {color:#333333; text-decoration:none;outline:none;width:140px;max-width:140px;}
.dropdown-toolbars a:hover {color:#000000;width:140px;max-width:140px;}
.dropdown-toolbars dt a:hover {color:#000000;border:1px solid #7d7d7d;}
.dropdown-toolbars dt a {background:#E0E0E0 url(../images/arrow.png) no-repeat scroll right center; display:block; padding-right:10px;border:1px solid #7d7d7d; width:140px;}
.dropdown-toolbars dt a span {cursor:pointer; display:block;padding:5px;}
.dropdown-toolbars dd ul {z-index:10000000000; background:#E0E0E0 none repeat scroll 0 0; border:1px solid #9f9f9f; color:#333333; display:none;left:0px; padding:5px 0px; position:absolute; top:2px; width:130px; min-width:130px; list-style:none;}
.dropdown-toolbars span.value { display:none;}
.dropdown-toolbars dd ul li a { padding:5px; display:block;width:120px;max-width:120px;cursor:pointer;}
.dropdown-toolbars dd ul li a:hover { background-color:#9f9f9f;width:120px;max-width:120px;cursor:pointer;}
.dropdown-toolbars dd ul li a label{cursor:pointer;}
.map-tools{background-image:url(../images/map-tools.png)!important;}
.save-as-map{float:right;position:relative;top:0;right:1em;}
.editing-toolbar .ui-dialog-content .ui-widget-content {padding:0;margin:0;}
.spatial-toolbar .ui-dialog-content .ui-widget-content {padding:0;margin:0;}
.buttonset{padding:10px;display:block;}
.dialog-lenght{font-size:0.8em;}
.dialog-area{font-size:0.8em;}
.dialog-area sup{font-size:0.6em;}
.datasources-container{width:100%;height:89%;overflow:auto;}
.raster-tools{background-image:url(../images/raster-tools.png)!important;}
.raster-toolbar{display:none;
position:absolute;
right:10%;
top:140px;
width:200px;height:33px;border:1px solid red;z-index:1000000;border-top: solid 1px #f8f8f8;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .3);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .3);
box-shadow: 0 1px 1px rgba(0, 0, 0, .3);
cursor:pointer;
}
.vector-tools{background-image:url(../images/vector-tools.png)!important;}
.vector-toolbar{display:none;
position:absolute;
right:6%;
top:140px;
width:200px;height:28px;border:1px solid red;z-index:1000000;border-top: solid 1px #f8f8f8;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .3);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .3);
box-shadow: 0 1px 1px rgba(0, 0, 0, .3);
cursor:pointer;
}
.terrain-tools{background-image:url(../images/terrain-tools.png)!important;}
#mmslider{position:absolute;left:0;width:36px;height:150px;padding:0;margin-top:100px;z-index:1000000;}
h2.point-title, h2.line-title{background: url(../images/wbg.gif) repeat-x top;
border: 1px solid #ccc;
border-top: 0px;border-left:0;border-right:0;margin:0;margin-top:1em;
font-weight:normal;font-size:1em;padding:6px;}
.point-sub{width:100%;margin:0;}
.point-top{width:100%;
background: url(../images/bg.gif) repeat-x top;
margin:0;padding:0;height:37px;}
.line-top {width:100%;
background: url(../images/bg.gif) repeat-x top;
margin:0;padding:0;height:37px;}
.dropdown {float:left;width:150px;max-width:150px;height:29px;margin:0;padding:4px;font-size:1em;font-weight:normal;}
.dropdown dd, .dropdown dt, .dropdown ul {margin:0px; padding:0px; font-size:1em;font-weight:normal;}
.dropdown dd {position:absolute;}
.dropdown a, .dropdown a:visited {color:#333333; text-decoration:none;outline:none;width:140px;max-width:140px;}
.dropdown a:hover {color:#000000;width:140px;max-width:140px;}
.dropdown dt a:hover {color:#000000;border:1px solid #9f9f9f;}
.dropdown dt a {background:#FFFFFF url(../images/arrow.png) no-repeat scroll right center; display:block; padding-right:10px;border:1px solid #9f9f9f; width:130px;}
.dropdown dt a span {cursor:pointer; display:block;padding:5px;}
.dropdown dd ul {z-index:10000000; background:#FFFFFF none repeat scroll 0 0; border:1px solid #9f9f9f; color:#333333; display:none;left:0px; padding:5px 0px; position:relative; top:2px; width:130px; min-width:130px; list-style:none;}
.dropdown span.value { display:none;}
.dropdown dd ul li a { color:#333333;padding:5px; display:block;width:120px;max-width:120px;}
.dropdown dd ul li a:hover { color:#333333;background-color:#E0E0E0;width:120px;max-width:120px;}
.opacity-title{margin:10px 0 0 20px;padding:0;float:left;}
#slider-opacity{width:150px;margin:10px 0 0 20px;padding:0;float:left;}
.percent{width:50px;height:20px;margin:5px 5px 5px 20px ;border:0;background:transparent;}
.point-symbol{width:100%;background:#FFFFFF;height:30%;border-top: 1px solid #ccc;border-bottom: 1px solid #ccc; }
.point-symbol-container{width:100%;background:#FFFFFF;height:30%;margin:0;border:0;}
.point-symbol-container h3{padding:5px;color:#727272;margin:0;font-size:1em;font-weight:normal;}
.point-symbol-container p.size{padding:15px 5px 5px 5px;color:#727272;margin:0;font-size:1em;font-weight:normal;}
.point-symbol-container p.size span{font-weight:normal;}
input.size{width:50px;height:20px;margin:5px;-moz-border-radius:5px;border:1px solid #9f9f9f;}
.point-symbol-container img{margin:5px;margin-right:0;background:transparent;}
.point-symbol-container img.active{margin:5px;margin-right:0;background:#43cb1f;}
.point-symbol-container img:hover{margin:5px;margin-right:0;background:#FFFFFF;}
.point-symbol-container img{padding:0;border:0;}
.point-fill, .line-fill{width:100%;background:#FFFFFF;border-bottom: 1px solid #ccc;}
.point-fill-container, .line-fill-container{width:100%;background:#FFFFFF;margin-top:.5%;border:0;}
.line-fill-container h3{padding:5px;color:#727272;margin:0;font-size:1em;font-weight:normal;}
.dropdown-fill {width:150px;max-width:150px;height:29px;margin:0;padding:4px;font-size:1em;font-weight:normal;}
.dropdown-fill dd, .dropdown-fill dt, .dropdown-fill ul {margin:0px; padding:0px; font-size:1em;font-weight:normal;}
.dropdown-fill dd {position:relative;}
.dropdown-fill a, .dropdown-fill a:visited {color:#333333; text-decoration:none;outline:none;width:140px;max-width:140px;}
.dropdown-fill a:hover {color:#000000;width:140px;max-width:140px;}
.dropdown-fill dt a:hover {color:#000000;border:1px solid #9f9f9f;}
.dropdown-fill dt a {background:#E0E0E0 url(../images/arrow.png) no-repeat scroll right center; display:block; padding-right:10px;border:1px solid #9f9f9f; width:130px;}
.dropdown-fill dt a span {cursor:pointer; display:block;padding:5px;}
.dropdown-fill dd ul {z-index:10000000; background:#E0E0E0 none repeat scroll 0 0; border:1px solid #9f9f9f; color:#333333; display:none;left:0px; padding:5px 0px; position:relative; top:2px; width:130px; min-width:130px; list-style:none;}
.dropdown-fill span.value { display:none;}
.dropdown-fill dd ul li a { padding:5px; display:block;width:120px;max-width:120px;}
.dropdown-fill dd ul li a:hover { background-color:#9f9f9f;width:120px;max-width:120px;}
#colorSelector2 {
position: absolute;
top: 0;
left: 0;
width: 36px;
height: 36px;
background: url(../images/select2.png);
}
#colorSelector2 div {
position: absolute;
top: 4px;
left: 4px;
width: 28px;
height: 28px;
background: url(../images/select2.png) center;
}
#colorpickerHolder2 {
top: 32px;
left: 0;
width: 356px;
height: 0;
overflow: hidden;
position: absolute;
z-index:10000000;
}
#colorpickerHolder2 .colorpicker {
background-image: url(../images/custom_background.png);
position: absolute;
bottom: 0;
left: 0;
}
#colorpickerHolder2 .colorpicker_hue div {
background-image: url(../images/custom_indic.gif);
}
#colorpickerHolder2 .colorpicker_hex {
background-image: url(../images/custom_hex.png);
}
#colorpickerHolder2 .colorpicker_rgb_r {
background-image: url(../images/custom_rgb_r.png);
}
#colorpickerHolder2 .colorpicker_rgb_g {
background-image: url(../images/custom_rgb_g.png);
}
#colorpickerHolder2 .colorpicker_rgb_b {
background-image: url(../images/custom_rgb_b.png);
}
#colorpickerHolder2 .colorpicker_hsb_s {
background-image: url(../images/custom_hsb_s.png);
display: none;
}
#colorpickerHolder2 .colorpicker_hsb_h {
background-image: url(../images/custom_hsb_h.png);
display: none;
}
#colorpickerHolder2 .colorpicker_hsb_b {
background-image: url(../images/custom_hsb_b.png);
display: none;
}
#colorpickerHolder2 .colorpicker_submit {
background-image: url(../images/custom_submit.png);
}
#colorpickerHolder2 .colorpicker input {
color: #778398;
}
.point-stroke, .line-stroke{width:100%;background:#FFFFFF;border-bottom: 1px solid #ccc; }
.point-stroke-container, .line-stroke-container{width:100%;background:#FFFFFF;margin-top:.5%;border:0;}
.point-stroke-container h3, .line-stroke-container h3 {padding:5px;color:#727272;margin:0;font-size:1em;font-weight:normal;}
.dropdown-stroke {width:150px;max-width:150px;height:29px;margin:0;padding:4px;font-size:1em;font-weight:normal;}
.dropdown-stroke dd, .dropdown-fill dt, .dropdown-fill ul {margin:0px; padding:0px; font-size:1em;font-weight:normal;}
.dropdown-stroke dd {position:relative;}
.dropdown-stroke a, .dropdown-stroke a:visited {color:#333333; text-decoration:none;outline:none;width:140px;max-width:140px;}
.dropdown-stroke a:hover {color:#000000;width:140px;max-width:140px;}
.dropdown-stroke dt a:hover {color:#000000;border:1px solid #9f9f9f;}
.dropdown-stroke dt a {background:#E0E0E0 url(../images/arrow.png) no-repeat scroll right center; display:block; padding-right:10px;border:1px solid #9f9f9f; width:130px;}
.dropdown-stroke dt a span {cursor:pointer; display:block;padding:5px;}
.dropdown-stroke dd ul { z-index:10000000;background:#E0E0E0 none repeat scroll 0 0; border:1px solid #9f9f9f; color:#333333; display:none;left:0px; padding:5px 0px; position:relative; top:2px; width:130px; min-width:130px; list-style:none;}
.dropdown-strokel span.value { display:none;}
.dropdown-stroke dd ul li a { padding:5px; display:block;width:120px;max-width:120px;}
.dropdown-stroke dd ul li a:hover { background-color:#9f9f9f;width:120px;max-width:120px;}
#colorSelector3 {
position: absolute;
top: 0;
left: 0;
width: 36px;
height: 36px;
background: url(../images/select2.png);
}
#colorSelector3 div {
position: absolute;
top: 4px;
left: 4px;
width: 28px;
height: 28px;
background: url(../images/select2.png) center;
}
#colorpickerHolder3 {
top: 32px;
left: 0;
width: 356px;
height: 0;
overflow: hidden;
position: absolute;
z-index:10000000;
}
#colorpickerHolder3 .colorpicker {
background-image: url(../images/custom_background.png);
position: absolute;
bottom: 0;
left: 0;
}
#colorpickerHolder3 .colorpicker_hue div {
background-image: url(../images/custom_indic.gif);
}
#colorpickerHolder3 .colorpicker_hex {
background-image: url(../images/custom_hex.png);
}
#colorpickerHolder3 .colorpicker_rgb_r {
background-image: url(../images/custom_rgb_r.png);
}
#colorpickerHolder3 .colorpicker_rgb_g {
background-image: url(../images/custom_rgb_g.png);
}
#colorpickerHolder3 .colorpicker_rgb_b {
background-image: url(../images/custom_rgb_b.png);
}
#colorpickerHolder3 .colorpicker_hsb_s {
background-image: url(../images/custom_hsb_s.png);
display: none;
}
#colorpickerHolder3 .colorpicker_hsb_h {
background-image: url(../images/custom_hsb_h.png);
display: none;
}
#colorpickerHolder3 .colorpicker_hsb_b {
background-image: url(../images/custom_hsb_b.png);
display: none;
}
#colorpickerHolder3 .colorpicker_submit {
background-image: url(../images/custom_submit.png);
}
#colorpickerHolder3 .colorpicker input {
color: #778398;
}
#customWidget {
position:relative;
display:block;
height: 36px;
}
/*
* Themes bar
*/
.theme-bar{width:100%;height:50px;position:absolute;bottom:25px;left:0;}
.green{
float:left;
width:24px;
height:24px;
margin:10px 5px 0 10px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.blue{
float:left;
width:24px;
height:24px;
margin:10px 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #44d0e5, #398ee4 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.purple{
float:left;
width:24px;
height:24px;
margin:10px 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #c743f8, #8340f3 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
.pink{
float:left;
width:24px;
height:24px;
margin:10px 5px;
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #f869ec, #f630f8 ); /* for firefox 3.6+ */
border:1px solid #AAA;
}
#nav {
position:relative;
top:4px;
left:290px;
margin: 0;
padding: 5px 4px 0;
line-height: 100%;
background: transparent;
border:0;
height:50px;
font-size:1.1em;
}
#nav li {
margin: 0 5px;
padding: 0 0 8px;
float: left;
position: relative;
list-style: none;
}
/* main level link */
#nav a {
font-weight: normal;
color: #e7e5e5;
text-decoration: none;
display: block;
padding: 8px 20px;
margin: 0;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
text-shadow: 0 1px 1px rgba(0, 0, 0, .3);
}
/* main level link hover */
#nav .current a {
background: #d1d1d1; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#a1a1a1'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#a1a1a1)); /* for webkit browsers */
background: -moz-linear-gradient(top, #ebebeb, #a1a1a1); /* for firefox 3.6+ */
color: #333333;
border-top: solid 1px #f8f8f8;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
#nav .dashboard a {
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */
color: #FFFFFF;
border-top: solid 1px #4bbf30;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(0, 0, 0, .8);
}
#nav .datawarehousenav a:hover, #nav .dashboard a:hover {
color: #FFFFFF;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(0, 0, 0, .8);
}
#nav li.datawarehousenav:hover > a, #nav li.dashboard:hover > a {
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #8ad148); /* for firefox 3.6+ */
border-top: solid 1px #4bbf30;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(0,0,0, .8);
}
#nav li:hover > a {
background: #8ad148; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#8ad148', endColorstr='#4bbf30'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#8ad148), to(#4bbf30)); /* for webkit browsers */
background: -moz-linear-gradient(top, #8ad148, #4bbf30); /* for firefox 3.6+ */
border-top: solid 1px #4bbf30;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
text-shadow: 0 1px 0 rgba(255, 255, 255, .8);
}
/* sub levels link hover */
#nav ul li:hover a, #nav li:hover li a {
background: none;
border: none;
color: #666;
-webkit-box-shadow: none;
-moz-box-shadow: none;
}
/* level 2 list */
#nav ul {
background: #ddd; /* for non-css3 browsers */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#cfcfcf'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#cfcfcf)); /* for webkit browsers */
background: -moz-linear-gradient(top, #ffffff, #cfcfcf); /* for firefox 3.6+ */
display: none;
margin: 0;
padding: 0;
width: 185px;
position: absolute;
top: 38px;
left: 0;
border: solid 1px #b4b4b4;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
}
/* dropdown */
#nav li:hover > ul {
display: block;
}
#nav ul li {
float: none;
margin: 0;
padding: 0;
}
#nav ul a {
font-weight: normal;
text-shadow: 0 1px 1px rgba(255, 255, 255, .9);
}
/* level 3+ list */
#nav ul ul {
left: 181px;
top: -3px;
}
/* rounded corners for first and last child */
#nav ul li:first-child > a, #nav ul.orange li:first-child > a, #nav ul.purple li:first-child > a {
-webkit-border-top-left-radius: 9px;
-moz-border-radius-topleft: 9px;
-webkit-border-top-right-radius: 9px;
-moz-border-radius-topright: 9px;
}
#nav ul li:last-child > a, #nav ul.orange li:last-child > a, #nav ul.purple li:last-child > a {
-webkit-border-bottom-left-radius: 9px;
-moz-border-radius-bottomleft: 9px;
-webkit-border-bottom-right-radius: 9px;
-moz-border-radius-bottomright: 9px;
}
/* clearfix */
#nav:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#nav {
display: inline-block;
}
html[xmlns] #nav {
display: block;
}
* html #nav {
height: 1%;
}
@-webkit-keyframes animate-stripes {
from {
background-position: 0 0;
}
to {
background-position: 24px 0;
}
}
/* Bar which is placed behind the progress */
.ui-progress-bar {
/* Usual setup stuff */
position: relative;
top:10px;
right:40px;
float:right;
height: 15px;
width:100px;
/* Pad right so we don't cover the borders when fully progressed */
padding-right: 2px;
/* For browser that don't support gradients, we'll set a blanket background colour */
background-color: #abb2bc;
/* Rounds the ends, we specify an excessive amount to make sure they are completely rounded */
/* Adjust to your liking, and don't forget to adjust to the same amount in .ui-progress */
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
/* Webkit background gradient */
background: -webkit-gradient(linear, left bottom, left top, color-stop(0, #b6bcc6), color-stop(1, #9da5b0));
/* Mozilla background gradient */
background: -moz-linear-gradient(#9da5b0 0%, #b6bcc6 100%);
/* Give it the inset look by adding some shadows and highlights */
-webkit-box-shadow: inset 0px 1px 2px 0px rgba(, 0, 0, 0.5), 0px 1px 0px 0px #565656;
-moz-box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #565656;
box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #565656;
}
/* Progress part of the progress bar */
.ui-progress {
/* Usual setup stuff */
position: relative;
display: block;
overflow: hidden;
/* Height should be 2px less than .ui-progress-bar so as to not cover borders and give it a look of being inset */
height: 13px;
/* Rounds the ends, we specify an excessive amount to make sure they are completely rounded */
/* Adjust to your liking, and don't forget to adjust to the same amount in .ui-progress-bar */
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
/* Set the background size so the stripes work correctly */
-webkit-background-size: 24px 24px; /* Webkit */
/* For browser that don't support gradients, we'll set a blanket background colour */
background-color: #74d04c;
/* Webkit background stripes and gradient */
background: -webkit-gradient(linear, 0 0, 24 24,
color-stop(0.00, rgba(255,255,255,0.17)),
color-stop(0.25, rgba(255,255,255,0.17)),
color-stop(0.26, rgba(255,255,255,0)),
color-stop(0.50, rgba(255,255,255,0)),
color-stop(0.51, rgba(255,255,255,0.17)),
color-stop(0.75, rgba(255,255,255,0.17)),
color-stop(0.76, rgba(255,255,255,0)),
color-stop(1.00, rgba(255,255,255,0))
), -webkit-gradient(linear, left bottom, left top, color-stop(0, #8ad148), color-stop(1, #4bbf30));
/* Mozilla (Firefox etc) background stripes */
/* Note: Mozilla's support for gradients is more true to the original design, allowing gradients at 30 degrees, as apposed to 45 degress in webkit. */
background: -moz-repeating-linear-gradient(top left -30deg,
rgba(255,255,255,0.17),
rgba(255,255,255,0.17) 5px,
rgba(255,255,255,0) 5px,
rgba(255,255,255,0) 10px
), -moz-linear-gradient(#8ad148 0%, #4bbf30 100%);
/* Webkit embossing */
-webkit-box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
/* Mozilla embossing */
-moz-box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
/* IE9 and Opera embossing */
box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
/* Give it a higher contrast outline */
border: 1px solid #4c8932;
/* Webkit magic */
-webkit-animation: animate-stripes 2s linear infinite;
/* TODO: Wait for Mozilla to support animation, then implement */
}
/* Progress indicator text */
.ui-progress span.ui-label {
font-size: 0.9em;
position: absolute;
right: 0;
line-height: 13px;
padding-right: 3px;
color: rgba(0,0,0,0.6);
text-shadow: rgba(255,255,255, 0.45) 0 1px 0px;
white-space: nowrap;
}
.progress_box_call{float:right;height:15px;width:15px;position: relative;
top:10px;
right:20px;background:url(../images/progress_box-icon.png) no-repeat;}
.progress_box_call:hover{background:url(../images/progress_box-icon-hover.png) no-repeat;cursor:pointer;}
.map{width:100%;height:89%;margin:0;padding:0;}
<|start_filename|>mapmint-ui/templates/Distiller/dirs/display_bs.html<|end_filename|>
#import zoo
#import datastores.directories.service as ds
#import os
#import mm_access
#set tmpl=$conf['main']['templatesPath']+"/Distiller/form_line.html"
#include $tmpl
#set ftmpl=$self._CHEETAH__cheetahIncludes[$tmpl]
#from datastores.directories.service import *
#def listDir($conf,$dir,$level)
#if $mm_access.checkDataStorePriv($conf,$dir,"rx")
#set res=ds.mmListDir($dir)
<ul class="list-group level-$level">
#for i in $res
#if $os.path.isdir(os.path.join($dir,$i))
<li class="list-group-item">
<input type="radio" name="browse" value="$os.path.join($dir,$i)" />
#set res1=ds.mmListDir(os.path.join($dir,$i))
#set res2=[]
#for j in $res1
#if $os.path.isdir(os.path.join(os.path.join($dir,$i),$j))
#set res2+=[$j]
#end if
#end for
<i class="fa fa-folder#if len(res2)>0#-open#end if# fa-fw"> </i>
$i ($(getFormatedSize($getDirSize(os.path.join($dir,$i)))))
#if len(res2)>0
<a href="#">
<span class="fa arrow"></span>
</a>
#end if
$listDir($conf,os.path.join($dir,$i),$level+1)
</li>
#end if
#end for
</ul>
#end if
#end def
<div>
<h2>$zoo._("Add new directory")</h2>
<form class="form-horizontal mtpp" action="" method="#" >
$ftmpl.printLine({"id":"name","name":$zoo._("Name")})
<div class="form-group">
<label class="col-sm-3 control-label">$zoo._("Directory")</label>
<div class="col-sm-9 ">
<input type="radio" name="Distiller_form_type" id="Distiller_form_type" onclick="\$(this).parent().parent().next().hide();\$(this).parent().parent().next().next().show();" value="use" checked="checked"/>$zoo._("Browse")
<input type="radio" name="Distiller_form_type"
id="Distiller_form_type" value="new"
onclick="\$(this).parent().parent().next().show();\$(this).parent().parent().next().next().hide();"
/>$zoo._("New")
</div>
</div>
$ftmpl.printLine({"id":"path","name":$zoo._("Path"),"classe":"collapse"})
<div class="form-group">
<label class="col-sm-3 control-label">$zoo._("Path")</label>
<div class="col-sm-9 ">
#set dir=$conf["main"]["dataPath"]+"/ftp/"
$listDir($conf,$dir,0)
</div>
</div>
$ftmpl.printButton({"id":"add","name":$zoo._("Add")})
</form>
</div>
<|start_filename|>public_map/assets/js/publisher.js<|end_filename|>
// Filename: login.js
define([
'module', 'jquery', 'zoo','notify', 'metisMenu', 'summernote', 'xml2json','typeahead', 'adminBasic', 'ol','datasources','mmDataTables','colorpicker','slider'
], function(module, $,Zoo,notify, metisMenu, summernote, X2JS,typeahead,adminBasic,ol,datasources,MMDataTable,colorpicker,slider) {
var _x2js = new X2JS({
arrayAccessFormPaths: [
'ProcessDescriptions.ProcessDescription.DataInputs.Input',
'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
'Capabilities.ServiceIdentification.Keywords'
],
});
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
language: module.config().language
});
function publishMap(){
var lbindings={
"labelFormat": "mmLabelFormat",
};
var inputs=[];
var val=$("textarea[name=projectDescription]").summernote("code");
inputs.push({
"identifier": "mmDescription",
"value": (val.indexOf("<div>")==0?"":"<div>")+val+(val.indexOf("<div>")==0?"":"</div>"),
"mimeType": "text/plain"
});
inputs.push({
"identifier": "map",
"value": $("#save-map").val(),
"dataType": "string"
});
inputs.push({
"identifier": "mmProjectName",
"value": $("#save-map").val(),
"dataType": "string"
});
//mmDescription
var tmp=["Title","Keywords","Author","Copyright"];
for(var i=0;i<tmp.length;i++){
if($("#mm_property_display").find("input[name=project"+tmp[i]+"]").val()!="")
inputs.push({
"identifier": "mm"+tmp[i],
"value": $("#mm_property_display").find("input[name=project"+tmp[i]+"]").val(),
"dataType": "string"
});
}
inputs.push({
"identifier": "mmIPRestriction",
"value": $("input[name='projectIp']").val(),
"dataType": "string"
});
inputs.push({
"identifier": "layout_t",
"value": "leftcol_bs",
"dataType": "string"
});
inputs.push({
"identifier": "mmBAK",
"value": $("input[name=mmBAK]").val(),
"dataType": "string"
});
inputs.push({
"identifier": "mmLayoutColor",
"value": "green",
"dataType": "string"
});
var rasterLayers=[];
var vectorLayers=[];
var activatedLayers=[];
var popups=[];
var windows=[];
$("input[type=radio]:checked").each(function(){
if($(this).val()=="raster"){
rasterLayers.push($(this).attr("id").replace(/layer_type1_/g,""));
}else
vectorLayers.push($(this).attr("id").replace(/layer_type_/g,""));
});
$("input[name=activate]:checked").each(function(){
activatedLayers.push($(this).attr("id").replace(/is_activated_layer_/g,""));
});
$("input[name=popup]:checked").each(function(){
popups.push($(this).attr("id").replace(/layer_has_popup_/g,""));
});
$("input[name=windows]:checked").each(function(){
windows.push($(this).attr("id").replace(/layer_has_click_/g,""));
});
var minmaxArray=[[],[],[],[]];
$("#datasources_list").find("tr").each(function(){
var cnt=0;
$(this).find("input[type=text]").each(function(){
minmaxArray[cnt].push($(this).val());
cnt+=1;
});
});
var minmaxValues=["minScales","maxScales","lminScales","lmaxScales"];
for(var i=0;i<minmaxValues.length;i++){
inputs.push({
"identifier": minmaxValues[i],
"value": minmaxArray[i].join(','),
"dataType": "string"
});
}
inputs.push({
"identifier": "mmMBaseLayers",
"value": $("#mapquest").val().join(','),
"dataType": "string"
});
inputs.push({
"identifier": "mmLSPos",
"value": $('select[name="layerswitcherPosition"]').val(),
"dataType": "string"
});
inputs.push({
"identifier": "mmLSAct",
"value": $('select[name="layerswitcherOpen"]').val(),
"dataType": "string"
});
$(".um_groups_f").find("select").each(function(){
inputs.push({
"identifier": "mm_access_groups",
"value": $(this).val(),
"dataType": "string"
});
});
$(".tm_themes_f").find("select").each(function(){
inputs.push({
"identifier": "mm_themes_class",
"value": $(this).val(),
"dataType": "string"
});
});
var tools=["mmNav","mmOT","mmVT","mmRT"];
for(var i=0;i<tools.length;i++){
inputs.push({
"identifier": tools[i],
"value": $("#"+tools[i]).val().join(','),
"dataType": "string"
});
}
$("#mm_mapp_display").find("input[type=text]").each(function(){
console.log($(this));
if($(this).val()!="")
inputs.push({
"identifier": $(this).attr("id"),
"value": $(this).val(),
"dataType": "string"
});
});
inputs.push({
"identifier": "mmOSMBaseLayers",
"value": ""+$("#base_osm").is(":checked"),
"dataType": "string"
});
inputs.push({
"identifier": "base_osm",
"value": ""+$("#base_osm").is(":checked"),
"dataType": "string"
});
if($("#"+$("#mmBBDefault").val()).val())
inputs.push({
"identifier": "mmPBaseLayers",
"value": $("#"+$("#mmBBDefault").val()).val().join(','),
"dataType": "string"
});
else
inputs.push({
"identifier": "mmPBaseLayers",
"value": "",
"dataType": "string"
});
if($("#mmWMTSBL").is(":checked")){
$(".wmts_layers_list").each(function(){
inputs.push({
"identifier": "mmWMTSBLURL",
"value": $(this).prev().find('input[type="text"]').val(),
"dataType": "string"
});
var val=$(this).next().find("textarea[name=wmts_attribution]").summernote("code");
inputs.push({
"identifier": "mmWMTSAttribution",
"value": (val.indexOf("<div>")==0?"":"<div>")+val+(val.indexOf("<div>")==0?"":"</div>"),
"mimeType": "text/plain"
});
var value="";
$(this).find('input[type="checkbox"]').each(function(){
if(value!="")
value+=",";
value+=$(this).parent().next().attr("data-value")+"|"+$(this).parent().parent().parent().next().find('input[type="text"]').first().val();
});
inputs.push({
"identifier": "mmWMTSBaseLayers",
"value": value,
"dataType": "string"
});
});
/*inputs.push({
"identifier": "mmWMTSBLURL",
"value": $("#wmts_layers_list").prev().find('input[type="text"]').val(),
"dataType": "string"
});
var val=$("textarea[name=wmts_attribution]").summernote("code");
inputs.push({
"identifier": "mmWMTSAttribution",
"value": (val.indexOf("<div>")==0?"":"<div>")+val+(val.indexOf("<div>")==0?"":"</div>"),
"mimeType": "text/plain"
});
var value="";
$("#wmts_layers_list").find('input[type="checkbox"]').each(function(){
if(value!="")
value+=",";
value+=$(this).parent().next().attr("data-value")+"|"+$(this).parent().parent().parent().next().find('input[type="text"]').first().val();
});
inputs.push({
"identifier": "mmWMTSBaseLayers",
"value": value,
"dataType": "string"
});*/
}
inputs.push({
"identifier": "mmProprietaryBaseLayers",
"value": $("#mmBBDefault").val(),
"dataType": "string"
});
inputs.push({
"identifier": "mmBProject",
"value": ($("#mmBProject").val()!=-1?$("#mmBProject").val():""),
"dataType": "string"
});
inputs.push({
"identifier": "mmActivatedBaseLayers",
"value": $("#base_layer_active_sel").val(),
"dataType": "string"
});
inputs.push({
"identifier": "ffamily",
"value": $("#mm_mapp_display").find("select[name=layoutFont]").val(),
"dataType": "string"
});
inputs.push({
"identifier": "fsize",
"value": $("#mm_mapp_display").find("select[name=layoutFontSize]").val(),
"dataType": "string"
});
inputs.push({
"identifier": "fsize",
"value": $("#mm_mapp_display").find("select[name=layoutFontColor]").val(),
"dataType": "string"
});
inputs.push({
"identifier": "tprj",
"value": $("#tprj").val(),
"dataType": "string"
});
inputs.push({
"identifier": "mmWindowList",
"value": windows.join(','),
"dataType": "string"
});
inputs.push({
"identifier": "mmPopupList",
"value": popups.join(','),
"dataType": "string"
});
inputs.push({
"identifier": "mmActivatedLayers",
"value": activatedLayers.join(','),
"dataType": "string"
});
inputs.push({
"identifier": "vectorLayers",
"value": vectorLayers.join(','),
"dataType": "string"
});
inputs.push({
"identifier": "rasterLayers",
"value": rasterLayers.join(','),
"dataType": "string"
});
zoo.execute({
identifier: "mapfile.savePublishMap",
type: "POST",
dataInputs: inputs,
dataOutputs: [
{"identifier":"Result"},
],
storeExecuteResponse: true,
status: true,
success: function(data){
var cid=0;
for(var i in zoo.launched)
cid=i;
var progress=$("#manaMap").find(".progress-bar").first();
progress.parent().show();
progress.removeClass("progress-bar-success");
progress.attr("aria-valuenow",0);
progress.css('width', (0)+'%');
zoo.watch(cid, {
onPercentCompleted: function(data) {
progress.css('width', (eval(data.percentCompleted))+'%');
progress.attr("aria-valuenow",eval(data.percentCompleted));
progress.text(data.text+' : '+(data.percentCompleted)+'%');
},
onProcessSucceeded: function(data) {
progress.attr("aria-valuenow",100);
progress.css('width', (100)+'%');
progress.text(data.text+' : '+(100)+'%');
progress.addClass("progress-bar-success");
if (data.result.ExecuteResponse.ProcessOutputs) {
progress.text(data.result.ExecuteResponse.ProcessOutputs.Output.Data.LiteralData.__text );
$(".notifications").notify({
message: { text: data.result.ExecuteResponse.ProcessOutputs.Output.Data.LiteralData.__text },
type: 'success',
}).show();
}
},
onError: function(data) {
progress.attr("aria-valuenow",100);
progress.css('width', (100)+'%');
progress.text(data.text+' : '+(100)+'%');
try{
$(".notifications").notify({
message: { text: data["result"]["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}catch(e){
console.log(e);
}
},
});
},
error: function(data){
console.log("ERROR");
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
return false;
}
function publishPreview(){
$(".notifications").notify({
message: { text: "Start publication" },
type: 'success',
}).show();
zoo.execute({
identifier: "mapfile.savePublishPreview",
type: "POST",
dataInputs: [
{
"identifier": "map",
"value": module.config().pmapfile,
"dataType": "string"
}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log("SUCCESS");
console.log(data);
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
},
error: function(data){
console.log("ERROR");
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function removeProject(){
zoo.execute({
identifier: "mapfile.removeMap",
type: "POST",
dataInputs: [
{
"identifier": "map",
"value": module.config().pmapfile,
"dataType": "string"
}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
console.log("SUCCESS");
console.log(data);
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
document.location.reload(false);
},
error: function(data){
console.log("ERROR");
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function updateBaseLayers(){
$("#base_layer_active").html("");
loadBaseLayers();
}
function loadBaseLayers(){
var baselayers=[];
var proprietary=false;
$("#mm_baselayers_display").find('select').each(function(){
if($(this).attr("id")!="mmBBDefault"){
$(this).find("option:selected").each(function(){
if($(this).attr("value")!=-1)
$("#base_layer_active").append($(this)[0].outerHTML);
});
}
else{
proprietary=true;
}
});
var i=1;
if($("#base_osm").is(":checked")){
$("#base_layer_active").prepend('<option value="1">OpenStreetMap</option>');
}
$("#base_layer_active").find("option").each(function(){
$(this).attr("value",i);
$(this).prop("selected",false);
var lowLimit=($("#base_osm").is("checked")?1:0);
if(i-1>lowLimit && i-1 <= $("#mapquest").find("option:selected").length+lowLimit){
var origin=$(this).text();
$(this).text("MapQuest "+origin);
}else{
if(i-1>lowLimit){
var origin=$(this).text();
$(this).text($("#mmBBDefault").val()+" "+origin);
}
}
i+=1;
});
$("#base_layer_active").val($("#base_layer_active_sel").val());
console.log(baselayers);
}
function displayPermissionForm(obj,dataStore,layer){
console.log(obj);
var params=[
{
"identifier": "tmpl",
"value": "UsersManagement/LayerAccess_bs",
"dataType": "string"
},
{
"identifier": "layer",
"value": layer,
"dataType": "string"
},
{
"identifier": "hasIpRestriction",
"value": "True",
"dataType": "string"
}
];
zoo.execute({
identifier: "template.display",
type: "POST",
dataInputs: params,
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
var cindex=obj.parent().parent().index();
try{
$("#datasources_list").find("tbody > tr:eq("+(cindex+1)+")").find('#datasourcePrivileges').parent().remove();
}catch(e){}
$("#datasources_list").find("tbody > tr:eq("+cindex+")").after('<tr><td colspan="11">'+data+'</td></tr>');
var relement=$("#datasources_list").find("tbody > tr:eq("+cindex+")").next();
console.log(relement);
if(relement.find("select").length==1){
relement.find(".gselectDel").hide();
}
relement.find(".gselectAdd").click(function(){
try{
var newElement=$(this).parent().next().next().next().clone();
console.log($(this).parent().next().next().next());
console.log(newElement);
$(this).parent().parent().append($(newElement)[0].outerHTML);
if(relement.find("select").length>1){
relement.find(".gselectDel").show();
}
}catch(e){
alert(e);
}
return false;
});
relement.find(".gselectDel").click(function(){
try{
console.log($(this).parent().parent().find(".row").last());
$(this).parent().parent().find(".row").last().remove();
if(relement.find("select").length>1){
relement.find(".gselectDel").show();
}else
relement.find(".gselectDel").hide();
}catch(e){
alert(e);
}
return false;
});
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
var actions={
"publish": publishMap,
"publishPreview": publishPreview
};
var initialize=function(){
adminBasic.initialize(zoo);
loadBaseLayers();
$("#manaMap").find(".btn-group").first().find("button").click(function(e){
if($(this).attr("data-act"))
actions[$(this).attr("data-act")]();
});
$("#removeModal").find(".modal-footer").find("button").last().click(function(e){
removeProject();
});
$('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
$.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
} );
$("#mmBBDefault").on("change",function(){
console.log("BBDefault change!");
if($(this).val()=="Planet"){
$("#Planet").find("option").each(function(){
if($(this).val().indexOf("http")>=0){
var myElement=$(this);
$.ajax({
url: $(this).val(),
success: function(data){
//alert("ok");
console.log(data);
try{
for(var i=0;i<data.mosaics.length;i++){
console.log(data.mosaics[i]);
$("#Planet").append('<option>'+data.mosaics[i].name+'</option>');
}
}catch(e){
var tmp=$(data).find("Contents").find("Layer").each(function(){
console.log($(this).find("ows\\:Title").text());
console.log($(this).find("ows\\:Identifier").text());
console.log($(this).find("ResourceURL").attr("template"));
console.log($(this));
$("#Planet").append('<option value="'+$(this).find("ows\\:Identifier").text().replace(/ /g,"__")+'|'+$(this).find("ResourceURL").attr("template").replace(/TileMatrix/g,"z").replace(/TileCol/g,"x").replace(/TileRow/g,"y")+'|'+$(this).find("ows\\:Title").text()+'">'+$(this).find("ows\\:Title").text()+'</option>');
});
console.log(data);
}
myElement.remove();
if($("#mmBBDefault_ini").length && $("#mmBBDefault_ini").val()!=""){
var tmp=$("#mmBBDefault_ini").val().split(',');
$("#Planet").find("option").each(function(){
if(tmp.indexOf($(this).val())>=0)
$(this).prop("selected",true);
});
$("#mmBBDefault_ini").val("");
}
},
error: function(){
alert("NO OK");
}
});
}
});
}
});
$(".tab-pane").css({"max-height":($(window).height()-(4*$("nav").height()))+"px","overflow-x":"hidden","overflow-y":"auto"});
console.log("Start Publisher");
$('#datasources_list').DataTable( {
autoWidth: false,
"scrollY": ($(window).height()/2)+"px",
"scrollCollapse": true,
"scrollX": true,
"paging": false,
"ordering": false,
"info": false,
"responsive": false,
deferRender: true,
scrollCollapse: true,
bFilter: false
} );
$('table.gen').DataTable( {
"scrollCollapse": true,
"scrollX": true,
"paging": false,
"ordering": false,
"info": false,
"responsive": false,
deferRender: true,
scrollCollapse: true,
bFilter: false
} );
// DataTables with reponsive parameter requires the following for re-activating the input radio
$("#mm_olayers_display").find("input[type=radio]").each(function(){
if($(this).attr("checked"))
$(this).prop("checked",true);
});
$('.cpicker').colorpicker();
$(".gselectAdd").click(function(e){
var rootNode=$(this).parent().parent();
var toDuplicate=$(this).parent().next();
rootNode.append(toDuplicate[0].outerHTML);
rootNode.find(".gselect").last().attr("id","um_group_"+($(".gselect").length-1));
return false;
});
$(".gselectDel").click(function(e){
var rootNode=$(this).parent().parent();
var toRemove=rootNode.find(".gselect").last();
toRemove.remove();
return false;
});
window.setTimeout(function () {
adminBasic.typeaheadMap(module,zoo,[$("#save-map"),$("#save-map")]);
},100);
window.setTimeout(function () {
$(".mm-editor").summernote({height: 150});
}, 110);
$(".nav-tabs").each(function(){
$(this).find("a").first().each(function(){
$(this).click();
});
});
console.log($("#wmts_server_url").find("input").first());
$("#wmts_server_url").find("input").first().on('input', function(){
if($(this).val().indexOf("http://")>=0 || $(this).val().indexOf("https://")>=0){
$(this).prev().find("button").first().removeClass("disabled");
$(this).prev().find("button").first().off("click");
var myElement=$(this).val();
$(this).prev().find("button").first().on("click",function(){
console.log($(this));
$("#wmts_layers_list").html("");
$.ajax({
url: myElement,
success: function(data){
//alert("ok");
console.log(data);
var tmp=$(data).find("Contents").find("Layer").each(function(){
var template=$("#template_wmts_layers")[0].innerHTML;
template=template.replace(/VAL/g,$(this).find("ows\\:Identifier").text().replace(/ /g,"__")+'|'+$(this).find("ResourceURL").attr("template").replace(/TileMatrix/g,"z").replace(/TileCol/g,"x").replace(/TileRow/g,"y")+'|'+$(this).find("ows\\:Title").text());
template=template.replace(/NEWTITLE/g,$(this).find("ows\\:Title").text());
template=template.replace(/TITLE/g,$(this).find("ows\\:Title").text());
$("#wmts_layers_list").append(template);
});
console.log(data);
$("#wmts_layers_list").find('input[type="checkbox"]').each(function(){
$(this).off("change");
$(this).on("change",function(){
var closure=$(this);
if($(this).is(":checked")){
$("#base_layer_active").append("<option value='"+$("#base_layer_active").find("option").lengh+"'>"+closure.parent().parent().parent().next().find('input').first().val()+"</option>");
}else{
$("#base_layer_active").find("option").each(function(){
if($(this).text()==closure.parent().parent().parent().next().find('input').first().val())
$(this).remove();
});
}
});
});
if($("#mmBBDefault_ini").length && $("#mmBBDefault_ini").val()!=""){
var tmp=$("#mmBBDefault_ini").val().split(',');
$("#Planet").find("option").each(function(){
if(tmp.indexOf($(this).val())>=0)
$(this).prop("selected",true);
});
$("#mmBBDefault_ini").val("");
}
},
error: function(){
alert("NO OK");
}
});
});
}
});
if($("#wmts_layers_list").parent().find("input[type=text]").first().val()!=""){
$("#mmWMTSBL").prop("checked",true).change();
$("#wmts_server_url").find("input").first().focus();
}
if($(".wmts_server_url").first().find('input').first().val()==" ")
$("#mmWMTSBL").prop("checked",false).change();
$("#mmBBDefault").change();
};
function addWMTS(){
$(".wmts_server_url").last().find("input").last().on('input', function(){
console.log($(this));
if($(this).val().indexOf("http://")>=0 || $(this).val().indexOf("https://")>=0){
$(this).prev().find("button").first().removeClass("disabled");
$(this).prev().find("button").first().off("click");
var myElement=$(this).val();
$(this).prev().find("button").first().on("click",function(){
console.log($(this));
var myRootElement=$(this).parent().parent().next();
myRootElement.html("");
$.ajax({
url: myElement,
success: function(data){
//alert("ok");
console.log(data);
var tmp=$(data).find("Contents").find("Layer").each(function(){
var template=$("#template_wmts_layers")[0].innerHTML;
template=template.replace(/VAL/g,$(this).find("ows\\:Identifier").text().replace(/ /g,"__")+'|'+$(this).find("ResourceURL").attr("template").replace(/TileMatrix/g,"z").replace(/TileCol/g,"x").replace(/TileRow/g,"y")+'|'+$(this).find("ows\\:Title").text());
template=template.replace(/NEWTITLE/g,$(this).find("ows\\:Title").text());
template=template.replace(/TITLE/g,$(this).find("ows\\:Title").text());
myRootElement.append(template);
});
console.log(data);
myRootElement.find('input[type="checkbox"]').each(function(){
$(this).off("change");
$(this).on("change",function(){
var closure=$(this);
if($(this).is(":checked")){
$("#base_layer_active").append("<option value='"+$("#base_layer_active").find("option").lengh+"'>"+closure.parent().parent().parent().next().find('input').first().val()+"</option>");
}else{
$("#base_layer_active").find("option").each(function(){
if($(this).text()==closure.parent().parent().parent().next().find('input').first().val())
$(this).remove();
});
}
});
});
if($("#mmBBDefault_ini").length && $("#mmBBDefault_ini").val()!=""){
var tmp=$("#mmBBDefault_ini").val().split(',');
$("#Planet").find("option").each(function(){
if(tmp.indexOf($(this).val())>=0)
$(this).prop("selected",true);
});
$("#mmBBDefault_ini").val("");
}
},
error: function(){
alert("NO OK");
}
});
});
}
});
$(".wmts_server_url").last().next().next().next().find("a.btn").last().show();
if($("#wmts_layers_lis").parent().find("input[type=text]").first().val()!=""){
$("#mmWMTSBL").prop("checked",true).change();
$("#wmts_server_url").find("input").first().focus();
}
$("#mmBBDefault").change();
}
function deleteWMTS(){
$(".wmts_server_url").last().next().next().next().remove();
$(".wmts_server_url").last().next().next().remove();
$(".wmts_server_url").last().next().remove();
$(".wmts_server_url").last().remove();
}
var firstLoad=null;
// Return public methods
return {
initialize: initialize,
updateBaseLayers: updateBaseLayers,
displayPermissionForm: displayPermissionForm,
addWMTS: addWMTS,
deleteWMTS: deleteWMTS,
firstLoad: firstLoad,
};
});
<|start_filename|>mapmint-ui/new-themes/themes/default/misc.css<|end_filename|>
.distiller_vector_polygon{
background: url(../img/polygon.png) no-repeat;
display: block;
width: 16px;
height: 16px;
float: left;
}
.distiller_vector_point{
background: url(../img/point.png) no-repeat;
display: block;
width: 16px;
height: 16px;
float: left;
}
.distiller_vector_line{
background: url(../img/line.png) no-repeat;
display: block;
width: 16px;
height: 16px;
float: left;
}
.distiller_raster{
background: url(../img/raster-icon.png) no-repeat;
display: block;
width: 16px;
height: 16px;
float: left;
}
.tabs-left, .tabs-right, .maps-container {background:#FFFFFF; color: #565656;font-size:.85em;overflow:hidden;color:#707070}
.tabs-right p {padding:0 0 0 10px;}
.tabs-left table {font-size:1em;}
.tabs-project table{font-size:1em;}
.tabs-project table.gen, table.gen{font-size:.85em;width: 98%;padding:0px 0 0 8px;color:#707070;}
.tabs-project table.layouts{width: 97%;padding:0;}
.tabs-project p{padding:10px 0 0 10px;margin:0;font-size:0.95em;}
table.layouts {width:98%;margin:0;padding:0px 0 0 8px;font-size:0.95em;background:#EBEBEB;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
behavior: url(js/ie-css3.htc);
color:#565656;border:1px solid #9f9f9f;margin:3px 0 0 12px;
}
table.layouts tr td {width:15%;}
table.layouts img {border:1px solid #9f9f9f;margin-left:20px;}
table.themz {width:97%;font-size:0.95em;background:#EBEBEB;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
behavior: url(js/ie-css3.htc);color:#000000;border:1px solid #9f9f9f;margin:3px 0 0 12px;padding: 2px 0 25px 12px;}
table.themz th span {float:left;margin:0 0 5px 0;padding:0;font-weight:normal;text-align:left;padding:5px;background:#FFFFFF;-moz-border-radius:4px;}
table.themz tr td {width:10%;}
table.themz tr td a {text-decoration:none;cursor:default;color:#565656;}
table.themz tr td a:hover {cursor:default;}
table.themz tr td a span{position:relative;top:30px;left:0;}
table.font {margin:0 0 0 0;padding:0 0 0 8px;}
table.font th span {float:left;margin:0 0 5px 0;padding:0;font-weight:normal;text-align:left;padding:5px;background:#FFFFFF;-moz-border-radius:4px;}
table.font td span.fcolor {width:50%;display:block;margin:0 5px 0 0;padding:3px;
background:#EBEBEB;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));background:
-moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
behavior: url(js/ie-css3.htc);
color:#000000;border:1px solid #9f9f9f;valign:middle;}
table td span.fcolor2 {
width:100%;
line-height: 22px;
display:block;
margin:0;
padding:0 0 0 3px;
background:#EBEBEB;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
color:#000000;
border:1px solid #9f9f9f;
valign:middle;
behavior: url(js/ie-css3.htc);
}
table td span.fcolor2 .color_picker {float:right;}
table.font td .color_picker {
height: 13px;
width: 14px;
padding: 0 !important;
float:right;
cursor: pointer;
line-height: 16px;
display:inline-block;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius: 2px;
behavior: url(js/ie-css3.htc);
}
table.datasources {
width:98%;
margin:0;
padding:0px 0 5px 0;
font-size:0.95em;
background:#EBEBEB;
background: -webkit-gradient(linear, left top, left bottombottom, from(#ebebeb), to(#ffffff));
background: -moz-linear-gradient(top, #ebebeb, #ffffff);
background: -ms-linear-gradient(#ebebeb, #ffffff);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ebebeb', endColorstr='#ffffff');
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
color:#000000;
border:1px solid #9f9f9f;
margin:3px 0 0 12px;
behavior: url(js/ie-css3.htc);
}
table.datasources th {color:#333333;font-weight:normal;padding: 2px 0 6px 0 ;background:#FFFFFF;}
table.datasources th.name {text-align:left;text-indent:5px;}
table.datasources tr td {text-align:center;color:#565656;}
table.datasources tr td.layerName {width:50%;text-align:left;}
table.logo {margin:10px 0 0 0;padding:0 0 0 8px;}
table.logo th span {float:left;margin:0 0 5px 0;padding:0;font-weight:normal;text-align:left;padding:5px;background:#FFFFFF;-moz-border-radius:4px;}
table.layers-gen {margin:10px 0 0 0;padding:0 0 0 8px;width:60%;}
table.layers-gen th span {float:left;margin:0 0 5px 0;padding:0;font-weight:normal;text-align:left;padding:5px;background:#FFFFFF;-moz-border-radius:4px;}
.nicEdit-pane{moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;font-size:.8em;behavior: url(js/ie-css3.htc);}
.nicEdit-main{height:300px;background:#FFFFFF;}
.nicEdit-button-hover{moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;border:1px solid #919191;behavior: url(js/ie-css3.htc);}
.nb-container{float:right;margin:0;padding:0;height:90%;}
.tt-container{float:left;margin:0;padding:0;height:50px;}
span.inlinebar{margin:25%;}
.distiller {width:100%;height:78px;margin:0;background: #FFFFFF url(../img/wbg.png) repeat-x;}
.distiller img {display:inline;float:left;margin:0;padding:0;position:relative;top:20px;left:20px;}
.distiller p{margin:0;padding:0;}
.distiller p a{width:180px;text-align:center;display:block;font-size:.8em;text-decoration:none;padding:0;margin:7px 10px;}
.distiller p a:hover{width:180px;text-decoration:none;padding:0;margin:7px 10px;}
.manager, .publisher, .printer {width:100%;height:78px;background: #FFFFFF url(../img/wbg.png) repeat-x;}
.manager img, .publisher img, .printer img {display:inline;float:left;margin:0;padding:0;position:relative;top:20px;left:20px;}
.manager p a, .publisher p a, .printer p a{width:180px;text-align:center;display:block;font-size:.8em;text-decoration:none;margin:25px 10px 0 0;}
.manager p a:hover, .publisher p a:hover, .printer p a:hover {width:180px;padding:0;text-decoration:none;margin:25px 10px 0 0;}
.distiller h2,.styler h2, .manager h2, .printer h2, .publisher h2{color:#545454;
margin:0;padding:15px 0 0 40px;background:transparent; display:block;float:left;
;font-size:.8em;text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
}
.distiller h3, .styler h3, .manager h3, .printer h3, .publisher h3{
position:absolute;margin:0;padding:40px 0 0 72px;background:transparent;font-size:.8em;font-weight:normal;color:#7a7a7a;
}
.save-config{position:relative;top:5px;right:10px;font-size:.85em;float:right;}
.maps-container ul{margin:0;padding:0;list-style:none;}
.tabs-right ul{margin:10px 0;padding:0;list-style:none;}
.tabs-right ul li, .maps-container ul li{font-size:.95em;margin:0;padding:10px;text-indent:0;
background: -moz-linear-gradient(top, #FFFFFF, #eaeaea);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#eaeaea));
background: -ms-linear-gradient(#ffffff, #eaeaea);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eaeaea');
-ms-filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#eaeaea');
}
.maps-container ul li a.default-map {color:#7ABA54;background-image:url(../img/icon-active.png);
background-repeat:no-repeat;
background-position:right; }
.tabs-right ul li a, .maps-container ul li a{text-decoration:none;color:#565656;display:block;}
.tabs-right ul li a:hover, .maps-container ul li a:hover{text-decoration:none;color:#000000;}
.tabs-right ul li a span, .maps-container ul li a span{display:block;text-decoration:none;color:#777777;font-size:.9em;}
.tabs-right ul li:hover a span, .maps-container ul li:hover a span {color:#FFFFFF;}
<|start_filename|>mapmint-ui/new-themes/themes/default/tree.css<|end_filename|>
/*
* MapMint Tree CSS
*/
.tree{
font-size:.85em;
margin:0;
color:#565656;
padding:0;
list-style-type:none;
}
.tree li{
white-space:nowrap;
font-size:1em;
color:#333333;
font-weight:normal;
text-shadow: 0 1px 0 rgba(255, 255, 255, 1);
}
.tree li ul{
list-style-type:none;
margin:0;
padding:0;
}
.tree li ul li{
font-size:1em;
color:#565656;
font-weight:normal;
text-shadow: none;
}
.tree-node{
height:18px;
padding: 5px 0 3px 0;
white-space:nowrap;
cursor:pointer;
}
.tree-indent{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-hit{
cursor:pointer;
}
.tree-expanded{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
background:url('../img/tree_arrows.png') no-repeat -18px 0px;
}
.tree-expanded-hover{
background:url('../img/tree_arrows.png') no-repeat -50px 0px;
}
.tree-collapsed{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
background:url('../img/tree_arrows.png') no-repeat 0px 0px;
}
.tree-collapsed-hover{
background:url('../img/tree_arrows.png') no-repeat -32px 0px;
}
.tree-folder{
display:inline-block;
background:url('../img/tree_folder.png') no-repeat;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-folder-open{
background:url('../img/tree_folder_open.png') no-repeat;
}
.tree-file{
display:inline-block;
background:url('../img/tree_file.png') no-repeat;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-loading{
background:url('../img/tree_loading.gif') no-repeat;
}
.tree-title{
display:inline-block;
text-decoration:none;
vertical-align:middle;
padding:1px 2px 1px 2px;
white-space:nowrap;
}
.tree-node-hover{
background:#ffffff;
background: -moz-linear-gradient(top, #FFFFFF, #eaeaea);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#eaeaea));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#EAEAEA'); /* for IE */
}
.tree-checkbox{
display:inline-block;
width:16px;
height:18px;
vertical-align:middle;
}
.tree-checkbox0{
background:url('../img/tree_checkbox_0.png') no-repeat;
}
.tree-checkbox1{
background:url('../img/tree_checkbox_1.png') no-repeat;
}
.tree-checkbox2{
background:url('../img/tree_checkbox_2.png') no-repeat;
}
.tree-node-proxy{
font-size:12px;
padding:1px 2px 1px 18px;
background:#fafafa;
border:1px solid #ccc;
z-index:9900000;
}
.tree-dnd-yes{
background:url('../img/tree_dnd_yes.png') no-repeat 0 center;
}
.tree-dnd-no{
background:url('../img/tree_dnd_no.png') no-repeat 0 center;
}
.tree-node-top{
border-top:1px dotted red;
}
.tree-node-bottom{
border-bottom:1px dotted red;
}
.tree-node-append .tree-title{
border:1px dotted red;
}
.tree-editor{
border:1px solid #ccc;
font-size:12px;
line-height:16px;
width:80px;
position:absolute;
top:0;
}
.emenu,.menu{
position:absolute;
background:#f0f0f0 url('../img/menu.gif') repeat-y;
margin:0;
padding:2px;
border:1px solid #ccc;
overflow:hidden;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
}
.menu-item{
position:relative;
margin:0;
padding:0;
height:22px;
line-height:20px;
overflow:hidden;
font-size:.8em;
color:#565656;
cursor:pointer;
border:1px solid transparent;
_border:1px solid #f0f0f0;
}
.menu-text{
position:absolute;
left:28px;
top:0px;
}
.menu-icon{
position:absolute;
width:16px;
height:16px;
top:3px;
left:2px;
}
.menu-rightarrow{
position: absolute;
width:4px;
height:7px;
top:7px;
right:5px;
background:url('../img/menu_rightarrow.png') no-repeat;
}
.menu-sep{
margin:3px 0px 3px 24px;
line-height:2px;
font-size:2px;
background:url('../img/menu_sep.png') repeat-x;
}
.menu-shadow{
position:absolute;
background:#ddd;
border-radius:4px;
-moz-border-radius:4px;
-webkit-border-radius: 4px;
-moz-box-shadow:
0px 1px 3px rgba(000,000,000,0.3),
inset 0px 0px 2px rgba(255,255,255,1);
-webkit-box-shadow:
0px 1px 3px rgba(000,000,000,0.3),
inset 0px 0px 2px rgba(255,255,255,1);
box-shadow:
0px 1px 3px rgba(000,000,000,0.3),
inset 0px 0px 2px rgba(255,255,255,1);}
.scales{
background:url('../img/scales.png') no-repeat;
}
.min-scale{
background:url('../img/min-scale.png') no-repeat;
}
.max-scale{
background:url('../img/max-scale.png') no-repeat;
}
.icon-zoom{
background:url('../img/zoomtolayer.png') no-repeat;
}
.icon-db{
background:url('../img/db-icon.png') no-repeat;
}
.icon-wfs{
background:url('../img/server-icon.png') no-repeat;
}
.icon-blank{
background:url('../img/blank.gif') no-repeat;
}
.icon-add{
background:url('../img/edit_add.png') no-repeat;
}
.icon-add-dir{
background:url('../img/folder_add.png') no-repeat;
}
.icon-add-grid{
background:url('../img/toggle_grid.png') no-repeat;
}
.icon-edit{
background:url('../img/pencil.png') no-repeat;
}
.icon-add-layer-m {background:url(../img/add-layer-m.png) no-repeat;}
.icon-move{
background:url('../img/move.png') no-repeat;
}
.icon-remove{
background:url('../img/edit_remove.png') no-repeat;
}
.icon-table{
background:url('../img/table.png') no-repeat;
}
.icon-style{
background:url('../img/palette.png') no-repeat;
}
.icon-template{
background:url('../img/template.png') no-repeat;
}
.icon-template-header{
background:url('../img/template-header.png') no-repeat;
}
.icon-template-content{
background:url('../img/template-content.png') no-repeat;
}
.icon-template-footer{
background:url('../img/template-footer.png') no-repeat;
}
.icon-properties{
background:url('../img/properties.png') no-repeat;
}
.icon-save{
background:url('../img/filesave.png') no-repeat;
}
.icon-cut{
background:url('../img/cut.png') no-repeat;
}
.icon-ok{
background:url('../img/ok.png') no-repeat;
}
.icon-no{
background:url('../img/no.png') no-repeat;
}
.icon-cancel{
background:url('../img/cancel.png') no-repeat;
}
.icon-umanage{
background:url('../img/locker.png') no-repeat;
}
.icon-refresh{
background:url('../img/refresh.png') no-repeat;
}
.icon-reload{
background:url('../img/reload.png') no-repeat;
}
.icon-search{
background:url('../img/search.png') no-repeat;
}
.icon-print{
background:url('../img/print.png') no-repeat;
}
.icon-help{
background:url('../img/help.png') no-repeat;
}
.icon-undo{
background:url('../img/undo.png') no-repeat;
}
.icon-redo{
background:url('../img/redo.png') no-repeat;
}
.icon-back{
background:url('../img/back.png') no-repeat;
}
.icon-sum{
background:url('../img/sum.png') no-repeat;
}
<|start_filename|>mapmint-ui/templates/preview/modules/sharing/init.js<|end_filename|>
var popupWindow;
function loadSharingWindow(){
var hauteur=(arguments.length>2?arguments[2]:480);
var largeur=(arguments.length>3?arguments[3]:480);
var top=(screen.height-hauteur)/2;
var left=(screen.width-largeur)/2;
var options = "menubar=no,scrollbars=yes,statusbar=no,resizable=yes";
if(popupWindow)
popupWindow.close();
popupWindow=window.open(arguments[1],System.messages[arguments[0]+" sharing"],"top="+top+",left="+left+",width="+largeur+"px,height="+hauteur+"px,"+options);
popupWindow.focus();
}
function permalink(){
saveContext(_permalink);
}
function _permalink(url){
var purl=url;
System.curl=url;
var params=[{name: "Text",value:url,dataType: "string"}];
data=WPSGetHeader("QREncode")+WPSGetInputs(params)+WPSGetOutput({"form":"ResponseDocument","asReference":"true","name":"QR"})+WPSGetFooter();
\$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
var params1=[
{name: "img",value:WPSParseReference(xml),dataType: "string"},
{name: "url",value:System.curl,dataType: "string"},
{name: "tmpl",value:"public/modules/sharing/default",dataType: "string"}
];
data=WPSGetHeader("template.display")+WPSGetInputs(params1)+WPSGetOutput({"name":"Result"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
if(\$("#sharing-dialog").length>0){
\$("#sharing-dialog").window('close');
\$("#sharing-dialog").remove();
}
\$('body').append('<div id="sharing-window" title="'+System.messages["Permalink"]+'"></div>');
\$('#sharing-window').html(xml.responseText);
\$('#sharing-window').window({
collapsible:false,
minimizable:false,
maximizable:false,
draggable:true,
resizable: false,
width: 400,
top: 100,
left: 100
});
}
}); //urlContext = xml.responseText;
//urlContext = xml.responseText;
//func(xml.responseText);
}
});
}
function _shareOnTwitter(url){
var urlTwitter = "http://www.twitter.com/share?url="+url;
loadSharingWindow("Twitter",urlTwitter,480,520);
}
function shareOnTwitter(){
saveContext(_shareOnTwitter);
}
function _shareOnFB(url){
var params=[{name: "Text",value:url,dataType: "string"}];
data=WPSGetHeader("QREncode")+WPSGetInputs(params)+WPSGetOutput({"form": "ResponseDocument","asReference":"true","name":"QR"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: data,
complete: function(xml,status) {
var urlFB = "http://www.facebook.com/sharer.php?s=100&p[title]=MapMint Context&p[url]="+url+"&p[images][0]="+encodeURIComponent(WPSParseReference(xml));
loadSharingWindow("Facebook",urlFB,480,480);
//func(xml.responseText);
}
});
}
function shareOnFB(){
saveContext(_shareOnFB);
}
<|start_filename|>mapmint-services/vector-converter-src/gdal_src/cpl_spawn.h<|end_filename|>
/**********************************************************************
* $Id: cpl_spawn.h 25681 2013-02-24 18:22:20Z rouault $
*
* Project: CPL - Common Portability Library
* Purpose: Implement CPLSystem().
* Author: <NAME>, <even dot rouault at mines dash paris dot org>
*
**********************************************************************
* Copyright (c) 2013,<NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#ifndef CPL_SPAWN_H_INCLUDED
#define CPL_SPAWN_H_INCLUDED
#include "cpl_vsi.h"
CPL_C_START
/* -------------------------------------------------------------------- */
/* Spawn a process. */
/* -------------------------------------------------------------------- */
int CPL_DLL CPLSpawn( const char * const papszArgv[], VSILFILE* fin, VSILFILE* fout,
int bDisplayErr );
#ifdef WIN32
#include <windows.h>
typedef HANDLE CPL_FILE_HANDLE;
#define CPL_FILE_INVALID_HANDLE NULL
typedef DWORD CPL_PID;
#else
#include <sys/types.h>
typedef int CPL_FILE_HANDLE;
#define CPL_FILE_INVALID_HANDLE -1
typedef pid_t CPL_PID;
#endif
typedef struct _CPLSpawnedProcess CPLSpawnedProcess;
CPLSpawnedProcess CPL_DLL* CPLSpawnAsync( int (*pfnMain)(CPL_FILE_HANDLE, CPL_FILE_HANDLE),
const char * const papszArgv[],
int bCreateInputPipe,
int bCreateOutputPipe,
int bCreateErrorPipe,
char** papszOptions );
CPL_PID CPL_DLL CPLSpawnAsyncGetChildProcessId(CPLSpawnedProcess* p);
int CPL_DLL CPLSpawnAsyncFinish(CPLSpawnedProcess* p, int bWait, int bKill);
CPL_FILE_HANDLE CPL_DLL CPLSpawnAsyncGetInputFileHandle(CPLSpawnedProcess* p);
CPL_FILE_HANDLE CPL_DLL CPLSpawnAsyncGetOutputFileHandle(CPLSpawnedProcess* p);
CPL_FILE_HANDLE CPL_DLL CPLSpawnAsyncGetErrorFileHandle(CPLSpawnedProcess* p);
void CPL_DLL CPLSpawnAsyncCloseInputFileHandle(CPLSpawnedProcess* p);
void CPL_DLL CPLSpawnAsyncCloseOutputFileHandle(CPLSpawnedProcess* p);
void CPL_DLL CPLSpawnAsyncCloseErrorFileHandle(CPLSpawnedProcess* p);
int CPL_DLL CPLPipeRead(CPL_FILE_HANDLE fin, void* data, int length);
int CPL_DLL CPLPipeWrite(CPL_FILE_HANDLE fout, const void* data, int length);
CPL_C_END
#endif // CPL_SPAWN_H_INCLUDED
<|start_filename|>mapmint-ui/js/wfst.js<|end_filename|>
var efeature;
function getInsertRequest(){
query='<wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" xmlns:ogc="http://www.opengis.net/ogc" version="1.0.0" service="WFS"><wfs:Insert><'+System.mmNodeId+'>';
for(var i=0;i< System.layerFields.length;i++){
try{
if(document.getElementById("l_"+System.layerFields[i]).value!="")
query+='<'+System.layerFields[i]+'>'+document.getElementById("l_"+System.layerFields[i]).value+'</'+System.layerFields[i]+'>';
document.getElementById("l_"+System.layerFields[i]).value="";
}catch(e){/*alert(i+" "+e);*/}
}
try{
var toto=new OpenLayers.Format.GML();
var toto1=toto.buildGeometryNode(editable.features[0].geometry);
var str=(new XMLSerializer()).serializeToString(toto1);
query+='<msGeometry>'+str+'</msGeometry>';
}catch(e){alert(e);}
query+='</'+System.mmNodeId+'></wfs:Insert></wfs:Transaction>';
editMode='NONE';
mapControls.select=tselect;//new OpenLayers.Control.SelectFeature(wfsPolygon, {callbacks: {'click':feature_info}});
map.addControl(mapControls.select);
mapControls.select.activate();
return query;
}
function getUpdateRequest(){
query='<wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" xmlns:ogc="http://www.opengis.net/ogc" version="1.0.0" service="WFS"><wfs:Update typeName="'+System.mmNodeId+'">';
for(var i=0;i<System.layerFields.length;i++){
try{
query+='<wfs:Property><wfs:Name>'+System.layerFields[i]+'</wfs:Name><wfs:Value>'+$("#fe_"+System.layerFields[i])[0].value+'</wfs:Value></wfs:Property>';
}catch(e){/*alert(i+" "+e);*/}
}
try{
var toto=new OpenLayers.Format.GML();
var toto1=toto.buildGeometryNode(finalLayers[2].features[0].geometry);
var str=(new XMLSerializer()).serializeToString(toto1);
query+='<wfs:Property><wfs:Name>msGeometry</wfs:Name><wfs:Value>'+str+'</wfs:Value></wfs:Property>';
}catch(e){alert(e);}
query+='<ogc:Filter><ogc:FeatureId fid="'+System.mmNodeId+'.'+efeature.attributes[System.layerFields[0]]+'" /></ogc:Filter>';
query+='</wfs:Update></wfs:Transaction>';
return query;
}
function getDeleteRequest(){
query='<wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" xmlns:ogc="http://www.opengis.net/ogc" version="1.0.0" service="WFS"><wfs:Delete typeName="'+System.mmNodeId+'">';
query+='<ogc:Filter><ogc:FeatureId fid="'+System.mmNodeId+'.'+efeature.attributes[System.layerFields[0]]+'" /></ogc:Filter>';
query+='</wfs:Delete></wfs:Transaction>';
return query;
}
var editMode='Update';
function saveWFST(){
query=editMode=='Insert'?getInsertRequest():editMode=='Delete'?getDeleteRequest():getUpdateRequest();
pre_query='<wps:Execute service="WPS" version="1.0.0" xmlns:wfs="http://www.opengis.net/wfs" xmlns:ogc="http://www.opengis.net/ogc" xmlns:wps="http://www.opengis.net/wps/1.0.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wps/1.0.0 ../wpsExecute_request.xsd"><ows:Identifier>wfs-t.Transaction</ows:Identifier><wps:DataInputs><wps:Input><ows:Identifier>Request</ows:Identifier><ows:Title>Playground area</ows:Title><wps:Data><wps:ComplexData mimeType="text/xml">';
post_query='</wps:ComplexData></wps:Data></wps:Input><wps:Input><ows:Identifier>MapFile</ows:Identifier><ows:Title>Distance which people will walk to get to a playground.</ows:Title><wps:Data><wps:LiteralData>'+$("#mapName")[0].value+'</wps:LiteralData></wps:Data></wps:Input></wps:DataInputs><wps:ResponseForm><wps:RawDataOutput><wps:Output><ows:Identifier>Result</ows:Identifier></wps:Output></wps:RawDataOutput></wps:ResponseForm></wps:Execute>';
var request = new OpenLayers.Request.XMLHttpRequest();
request.open('POST',System.zooUrl,true);
request.setRequestHeader('Content-Type','text/xml');
/*request.onreadystatechange = function() {
if(request.readyState == OpenLayers.Request.XMLHttpRequest.DONE) {
wfsPolygon.refresh();
}
}*/
request.send(pre_query+query+post_query);
try{
$("#dialog").dialog("close");
for(var i in System.layerFields){
try{
$("#fe_"+i).value="";
}catch(e){/*alert(i+" "+e);*/}
}
}catch(e){}
}
<|start_filename|>mapmint-ui/js/datawarehouse-layout.js<|end_filename|>
var myLayout, middleLayout, innerLayout_Center, innerLayout_South;
$(document).ready(function () {
myLayout = $('body').layout({
west__showOverflowOnHover: true
, west__minSize: 300
, west__onresize: 'middleLayout.resizeAll'
, center__onresize: 'middleLayout.resizeAll'
, north__resizable: false
, closable: true // pane can open & close
, resizable: true // when open, pane can be resized
, slidable: true // when closed, pane can 'slide' open over other panes - closes on mouse-out
, north__slidable: false
, north__closable: false
, north__showOverflowOnHover: true
, north__togglerLength_closed: '100%' // toggle-button is full-width of resizer-bar
, north__spacing_closed: 0 // big resizer-bar when open (zero height)
, south__resizable: false // OVERRIDE the pane-default of 'resizable=true'
, south__spacing_open: 0 // no resizer-bar when open (zero height)
, south__spacing_closed: 20 // big resizer-bar when open (zero height)
});
middleLayout = $('.ui-layout-subcenter').layout({
center__paneSelector: ".middle-center"
, center__initClosed: false
, south__paneSelector: ".middle-south"
, south__size: '10%'
, south__initClosed: false
, spacing_open: 0 // ALL panes
, spacing_closed: 0 // ALL panes
});
});
<|start_filename|>mapmint-services/vector-converter-src/gdal_src/ogr_geometry.h<|end_filename|>
/******************************************************************************
* $Id: ogr_geometry.h 25450 2013-01-04 23:15:38Z rouault $
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: Classes for manipulating simple features that is not specific
* to a particular interface technology.
* Author: <NAME>, <EMAIL>
*
******************************************************************************
* Copyright (c) 1999, <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#ifndef _OGR_GEOMETRY_H_INCLUDED
#define _OGR_GEOMETRY_H_INCLUDED
#include "ogr_core.h"
#include "ogr_spatialref.h"
/**
* \file ogr_geometry.h
*
* Simple feature geometry classes.
*/
/**
* Simple container for a position.
*/
class OGRRawPoint
{
public:
OGRRawPoint()
{
x = y = 0.0;
}
double x;
double y;
};
typedef struct GEOSGeom_t *GEOSGeom;
/************************************************************************/
/* OGRGeometry */
/************************************************************************/
class OGRPoint;
/**
* Abstract base class for all geometry classes.
*
* Some spatial analysis methods require that OGR is built on the GEOS library
* to work properly. The precise meaning of methods that describe spatial relationships
* between geometries is described in the SFCOM, or other simple features interface
* specifications, like "OpenGIS® Implementation Specification for
* Geographic information - Simple feature access - Part 1: Common architecture"
* (<a href="http://www.opengeospatial.org/standards/sfa">OGC 06-103r3</a>)
*
*/
class CPL_DLL OGRGeometry
{
private:
OGRSpatialReference * poSRS; // may be NULL
protected:
int nCoordDimension;
public:
OGRGeometry();
virtual ~OGRGeometry();
// standard IGeometry
virtual int getDimension() const = 0;
virtual int getCoordinateDimension() const;
virtual OGRBoolean IsEmpty() const = 0;
virtual OGRBoolean IsValid() const;
virtual OGRBoolean IsSimple() const;
virtual OGRBoolean IsRing() const;
virtual void empty() = 0;
virtual OGRGeometry *clone() const = 0;
virtual void getEnvelope( OGREnvelope * psEnvelope ) const = 0;
virtual void getEnvelope( OGREnvelope3D * psEnvelope ) const = 0;
// IWks Interface
virtual int WkbSize() const = 0;
virtual OGRErr importFromWkb( unsigned char *, int=-1 )=0;
virtual OGRErr exportToWkb( OGRwkbByteOrder, unsigned char * ) const = 0;
virtual OGRErr importFromWkt( char ** ppszInput ) = 0;
virtual OGRErr exportToWkt( char ** ppszDstText ) const = 0;
// non-standard
virtual OGRwkbGeometryType getGeometryType() const = 0;
virtual const char *getGeometryName() const = 0;
virtual void dumpReadable( FILE *, const char * = NULL, char** papszOptions = NULL ) const;
virtual void flattenTo2D() = 0;
virtual char * exportToGML( const char* const * papszOptions = NULL ) const;
virtual char * exportToKML() const;
virtual char * exportToJson() const;
virtual GEOSGeom exportToGEOS() const;
virtual void closeRings();
virtual void setCoordinateDimension( int nDimension );
void assignSpatialReference( OGRSpatialReference * poSR );
OGRSpatialReference *getSpatialReference( void ) const { return poSRS; }
virtual OGRErr transform( OGRCoordinateTransformation *poCT ) = 0;
OGRErr transformTo( OGRSpatialReference *poSR );
virtual void segmentize(double dfMaxLength);
// ISpatialRelation
virtual OGRBoolean Intersects( OGRGeometry * ) const;
virtual OGRBoolean Equals( OGRGeometry * ) const = 0;
virtual OGRBoolean Disjoint( const OGRGeometry * ) const;
virtual OGRBoolean Touches( const OGRGeometry * ) const;
virtual OGRBoolean Crosses( const OGRGeometry * ) const;
virtual OGRBoolean Within( const OGRGeometry * ) const;
virtual OGRBoolean Contains( const OGRGeometry * ) const;
virtual OGRBoolean Overlaps( const OGRGeometry * ) const;
// virtual OGRBoolean Relate( const OGRGeometry *, const char * ) const;
virtual OGRGeometry *Boundary() const;
virtual double Distance( const OGRGeometry * ) const;
virtual OGRGeometry *ConvexHull() const;
virtual OGRGeometry *Buffer( double dfDist, int nQuadSegs = 30 ) const;
virtual OGRGeometry *Intersection( const OGRGeometry *) const;
virtual OGRGeometry *Union( const OGRGeometry * ) const;
virtual OGRGeometry *UnionCascaded() const;
virtual OGRGeometry *Difference( const OGRGeometry * ) const;
virtual OGRGeometry *SymDifference( const OGRGeometry * ) const;
virtual OGRErr Centroid( OGRPoint * poPoint ) const;
virtual OGRGeometry *Simplify(double dTolerance) const;
OGRGeometry *SimplifyPreserveTopology(double dTolerance) const;
virtual OGRGeometry *Polygonize() const;
// backward compatibility to non-standard method names.
OGRBoolean Intersect( OGRGeometry * ) const CPL_WARN_DEPRECATED("Non standard method. Use Intersects() instead");
OGRBoolean Equal( OGRGeometry * ) const CPL_WARN_DEPRECATED("Non standard method. Use Equals() instead");
virtual OGRGeometry *SymmetricDifference( const OGRGeometry * ) const CPL_WARN_DEPRECATED("Non standard method. Use SymDifference() instead");
virtual OGRGeometry *getBoundary() const CPL_WARN_DEPRECATED("Non standard method. Use Boundary() instead");
// Special HACK for DB2 7.2 support
static int bGenerate_DB2_V72_BYTE_ORDER;
virtual void swapXY();
};
/************************************************************************/
/* OGRPoint */
/************************************************************************/
/**
* Point class.
*
* Implements SFCOM IPoint methods.
*/
class CPL_DLL OGRPoint : public OGRGeometry
{
double x;
double y;
double z;
public:
OGRPoint();
OGRPoint( double x, double y );
OGRPoint( double x, double y, double z );
virtual ~OGRPoint();
// IWks Interface
virtual int WkbSize() const;
virtual OGRErr importFromWkb( unsigned char *, int=-1 );
virtual OGRErr exportToWkb( OGRwkbByteOrder, unsigned char * ) const;
virtual OGRErr importFromWkt( char ** );
virtual OGRErr exportToWkt( char ** ppszDstText ) const;
// IGeometry
virtual int getDimension() const;
virtual OGRGeometry *clone() const;
virtual void empty();
virtual void getEnvelope( OGREnvelope * psEnvelope ) const;
virtual void getEnvelope( OGREnvelope3D * psEnvelope ) const;
virtual OGRBoolean IsEmpty() const;
// IPoint
double getX() const { return x; }
double getY() const { return y; }
double getZ() const { return z; }
// Non standard
virtual void setCoordinateDimension( int nDimension );
void setX( double xIn ) { x = xIn; if (nCoordDimension == 0) nCoordDimension = 2; }
void setY( double yIn ) { y = yIn; if (nCoordDimension == 0) nCoordDimension = 2; }
void setZ( double zIn ) { z = zIn; nCoordDimension=3; }
// ISpatialRelation
virtual OGRBoolean Equals( OGRGeometry * ) const;
// Non standard from OGRGeometry
virtual const char *getGeometryName() const;
virtual OGRwkbGeometryType getGeometryType() const;
virtual OGRErr transform( OGRCoordinateTransformation *poCT );
virtual void flattenTo2D();
virtual void swapXY();
};
/************************************************************************/
/* OGRCurve */
/************************************************************************/
/**
* Abstract curve base class.
*/
class CPL_DLL OGRCurve : public OGRGeometry
{
public:
OGRCurve();
virtual ~OGRCurve();
// ICurve methods
virtual double get_Length() const = 0;
virtual void StartPoint(OGRPoint *) const = 0;
virtual void EndPoint(OGRPoint *) const = 0;
virtual int get_IsClosed() const;
virtual void Value( double, OGRPoint * ) const = 0;
};
/************************************************************************/
/* OGRLineString */
/************************************************************************/
/**
* Concrete representation of a multi-vertex line.
*/
class CPL_DLL OGRLineString : public OGRCurve
{
protected:
int nPointCount;
OGRRawPoint *paoPoints;
double *padfZ;
void Make3D();
void Make2D();
public:
OGRLineString();
virtual ~OGRLineString();
// IWks Interface
virtual int WkbSize() const;
virtual OGRErr importFromWkb( unsigned char *, int = -1 );
virtual OGRErr exportToWkb( OGRwkbByteOrder, unsigned char * ) const;
virtual OGRErr importFromWkt( char ** );
virtual OGRErr exportToWkt( char ** ppszDstText ) const;
// IGeometry interface
virtual int getDimension() const;
virtual OGRGeometry *clone() const;
virtual void empty();
virtual void getEnvelope( OGREnvelope * psEnvelope ) const;
virtual void getEnvelope( OGREnvelope3D * psEnvelope ) const;
virtual OGRBoolean IsEmpty() const;
// ICurve methods
virtual double get_Length() const;
virtual void StartPoint(OGRPoint *) const;
virtual void EndPoint(OGRPoint *) const;
virtual void Value( double, OGRPoint * ) const;
// ILineString methods
int getNumPoints() const { return nPointCount; }
void getPoint( int, OGRPoint * ) const;
double getX( int i ) const { return paoPoints[i].x; }
double getY( int i ) const { return paoPoints[i].y; }
double getZ( int i ) const;
// ISpatialRelation
virtual OGRBoolean Equals( OGRGeometry * ) const;
// non standard.
virtual void setCoordinateDimension( int nDimension );
void setNumPoints( int );
void setPoint( int, OGRPoint * );
void setPoint( int, double, double );
void setPoint( int, double, double, double );
void setPoints( int, OGRRawPoint *, double * = NULL );
void setPoints( int, double * padfX, double * padfY,
double *padfZ = NULL );
void addPoint( OGRPoint * );
void addPoint( double, double );
void addPoint( double, double, double );
void getPoints( OGRRawPoint *, double * = NULL ) const;
void getPoints( void* pabyX, int nXStride,
void* pabyY, int nYStride,
void* pabyZ = NULL, int nZStride = 0 ) const;
void addSubLineString( const OGRLineString *,
int nStartVertex = 0, int nEndVertex = -1 );
void reversePoints( void );
// non-standard from OGRGeometry
virtual OGRwkbGeometryType getGeometryType() const;
virtual const char *getGeometryName() const;
virtual OGRErr transform( OGRCoordinateTransformation *poCT );
virtual void flattenTo2D();
virtual void segmentize(double dfMaxLength);
virtual void swapXY();
};
/************************************************************************/
/* OGRLinearRing */
/************************************************************************/
/**
* Concrete representation of a closed ring.
*
* This class is functionally equivelent to an OGRLineString, but has a
* separate identity to maintain alignment with the OpenGIS simple feature
* data model. It exists to serve as a component of an OGRPolygon.
*
* The OGRLinearRing has no corresponding free standing well known binary
* representation, so importFromWkb() and exportToWkb() will not actually
* work. There is a non-standard GDAL WKT representation though.
*
* Because OGRLinearRing is not a "proper" free standing simple features
* object, it cannot be directly used on a feature via SetGeometry(), and
* cannot genearally be used with GEOS for operations like Intersects().
* Instead the polygon should be used, or the OGRLinearRing should be
* converted to an OGRLineString for such operations.
*/
class CPL_DLL OGRLinearRing : public OGRLineString
{
private:
friend class OGRPolygon;
// These are not IWks compatible ... just a convenience for OGRPolygon.
virtual int _WkbSize( int b3D ) const;
virtual OGRErr _importFromWkb( OGRwkbByteOrder, int b3D,
unsigned char *, int=-1 );
virtual OGRErr _exportToWkb( OGRwkbByteOrder, int b3D,
unsigned char * ) const;
public:
OGRLinearRing();
OGRLinearRing( OGRLinearRing * );
~OGRLinearRing();
// Non standard.
virtual const char *getGeometryName() const;
virtual OGRGeometry *clone() const;
virtual int isClockwise() const;
virtual void reverseWindingOrder();
virtual void closeRings();
virtual double get_Area() const;
OGRBoolean isPointInRing(const OGRPoint* pt, int bTestEnvelope = TRUE) const;
OGRBoolean isPointOnRingBoundary(const OGRPoint* pt, int bTestEnvelope = TRUE) const;
// IWks Interface - Note this isnt really a first class object
// for the purposes of WKB form. These methods always fail since this
// object cant be serialized on its own.
virtual int WkbSize() const;
virtual OGRErr importFromWkb( unsigned char *, int=-1 );
virtual OGRErr exportToWkb( OGRwkbByteOrder, unsigned char * ) const;
};
/************************************************************************/
/* OGRSurface */
/************************************************************************/
/**
* Abstract base class for 2 dimensional objects like polygons.
*/
class CPL_DLL OGRSurface : public OGRGeometry
{
public:
virtual double get_Area() const = 0;
virtual OGRErr PointOnSurface( OGRPoint * poPoint ) const = 0;
};
/************************************************************************/
/* OGRPolygon */
/************************************************************************/
/**
* Concrete class representing polygons.
*
* Note that the OpenGIS simple features polygons consist of one outer
* ring, and zero or more inner rings. A polygon cannot represent disconnected
* regions (such as multiple islands in a political body). The
* OGRMultiPolygon must be used for this.
*/
class CPL_DLL OGRPolygon : public OGRSurface
{
int nRingCount;
OGRLinearRing **papoRings;
public:
OGRPolygon();
virtual ~OGRPolygon();
// Non standard (OGRGeometry).
virtual const char *getGeometryName() const;
virtual OGRwkbGeometryType getGeometryType() const;
virtual OGRGeometry *clone() const;
virtual void empty();
virtual OGRErr transform( OGRCoordinateTransformation *poCT );
virtual void flattenTo2D();
virtual OGRBoolean IsEmpty() const;
virtual void segmentize(double dfMaxLength);
// ISurface Interface
virtual double get_Area() const;
virtual int PointOnSurface( OGRPoint * poPoint ) const;
// IWks Interface
virtual int WkbSize() const;
virtual OGRErr importFromWkb( unsigned char *, int = -1 );
virtual OGRErr exportToWkb( OGRwkbByteOrder, unsigned char * ) const;
virtual OGRErr importFromWkt( char ** );
virtual OGRErr exportToWkt( char ** ppszDstText ) const;
// IGeometry
virtual int getDimension() const;
virtual void getEnvelope( OGREnvelope * psEnvelope ) const;
virtual void getEnvelope( OGREnvelope3D * psEnvelope ) const;
// ISpatialRelation
virtual OGRBoolean Equals( OGRGeometry * ) const;
// Non standard
virtual void setCoordinateDimension( int nDimension );
void addRing( OGRLinearRing * );
void addRingDirectly( OGRLinearRing * );
OGRLinearRing *getExteriorRing();
const OGRLinearRing *getExteriorRing() const;
int getNumInteriorRings() const;
OGRLinearRing *getInteriorRing( int );
const OGRLinearRing *getInteriorRing( int ) const;
OGRBoolean IsPointOnSurface( const OGRPoint * ) const;
virtual void closeRings();
virtual void swapXY();
};
/************************************************************************/
/* OGRGeometryCollection */
/************************************************************************/
/**
* A collection of 1 or more geometry objects.
*
* All geometries must share a common spatial reference system, and
* Subclasses may impose additional restrictions on the contents.
*/
class CPL_DLL OGRGeometryCollection : public OGRGeometry
{
int nGeomCount;
OGRGeometry **papoGeoms;
OGRErr importFromWkbInternal( unsigned char * pabyData, int nSize, int nRecLevel );
OGRErr importFromWktInternal( char **ppszInput, int nRecLevel );
public:
OGRGeometryCollection();
virtual ~OGRGeometryCollection();
// Non standard (OGRGeometry).
virtual const char *getGeometryName() const;
virtual OGRwkbGeometryType getGeometryType() const;
virtual OGRGeometry *clone() const;
virtual void empty();
virtual OGRErr transform( OGRCoordinateTransformation *poCT );
virtual void flattenTo2D();
virtual OGRBoolean IsEmpty() const;
virtual void segmentize(double dfMaxLength);
// IWks Interface
virtual int WkbSize() const;
virtual OGRErr importFromWkb( unsigned char *, int = -1 );
virtual OGRErr exportToWkb( OGRwkbByteOrder, unsigned char * ) const;
virtual OGRErr importFromWkt( char ** );
virtual OGRErr exportToWkt( char ** ppszDstText ) const;
virtual double get_Length() const;
virtual double get_Area() const;
// IGeometry methods
virtual int getDimension() const;
virtual void getEnvelope( OGREnvelope * psEnvelope ) const;
virtual void getEnvelope( OGREnvelope3D * psEnvelope ) const;
// IGeometryCollection
int getNumGeometries() const;
OGRGeometry *getGeometryRef( int );
const OGRGeometry *getGeometryRef( int ) const;
// ISpatialRelation
virtual OGRBoolean Equals( OGRGeometry * ) const;
// Non standard
virtual void setCoordinateDimension( int nDimension );
virtual OGRErr addGeometry( const OGRGeometry * );
virtual OGRErr addGeometryDirectly( OGRGeometry * );
virtual OGRErr removeGeometry( int iIndex, int bDelete = TRUE );
void closeRings();
virtual void swapXY();
};
/************************************************************************/
/* OGRMultiPolygon */
/************************************************************************/
/**
* A collection of non-overlapping OGRPolygons.
*
* Note that the IMultiSurface class hasn't been modelled, nor have any
* of it's methods.
*/
class CPL_DLL OGRMultiPolygon : public OGRGeometryCollection
{
public:
OGRMultiPolygon();
// Non standard (OGRGeometry).
virtual const char *getGeometryName() const;
virtual OGRwkbGeometryType getGeometryType() const;
virtual OGRGeometry *clone() const;
virtual OGRErr importFromWkt( char ** );
virtual OGRErr exportToWkt( char ** ) const;
// IGeometry methods
virtual int getDimension() const;
// Non standard
virtual OGRErr addGeometryDirectly( OGRGeometry * );
virtual double get_Area() const;
};
/************************************************************************/
/* OGRMultiPoint */
/************************************************************************/
/**
* A collection of OGRPoints.
*/
class CPL_DLL OGRMultiPoint : public OGRGeometryCollection
{
private:
OGRErr importFromWkt_Bracketed( char **, int bHasM, int bHasZ );
public:
OGRMultiPoint();
// Non standard (OGRGeometry).
virtual const char *getGeometryName() const;
virtual OGRwkbGeometryType getGeometryType() const;
virtual OGRGeometry *clone() const;
virtual OGRErr importFromWkt( char ** );
virtual OGRErr exportToWkt( char ** ) const;
// IGeometry methods
virtual int getDimension() const;
// Non standard
virtual OGRErr addGeometryDirectly( OGRGeometry * );
};
/************************************************************************/
/* OGRMultiLineString */
/************************************************************************/
/**
* A collection of OGRLineStrings.
*/
class CPL_DLL OGRMultiLineString : public OGRGeometryCollection
{
public:
OGRMultiLineString();
~OGRMultiLineString();
// Non standard (OGRGeometry).
virtual const char *getGeometryName() const;
virtual OGRwkbGeometryType getGeometryType() const;
virtual OGRGeometry *clone() const;
virtual OGRErr importFromWkt( char ** );
virtual OGRErr exportToWkt( char ** ) const;
// IGeometry methods
virtual int getDimension() const;
// Non standard
virtual OGRErr addGeometryDirectly( OGRGeometry * );
};
/************************************************************************/
/* OGRGeometryFactory */
/************************************************************************/
/**
* Create geometry objects from well known text/binary.
*/
class CPL_DLL OGRGeometryFactory
{
static OGRErr createFromFgfInternal( unsigned char *pabyData,
OGRSpatialReference * poSR,
OGRGeometry **ppoReturn,
int nBytes,
int *pnBytesConsumed,
int nRecLevel );
public:
static OGRErr createFromWkb( unsigned char *, OGRSpatialReference *,
OGRGeometry **, int = -1 );
static OGRErr createFromWkt( char **, OGRSpatialReference *,
OGRGeometry ** );
static OGRErr createFromFgf( unsigned char *, OGRSpatialReference *,
OGRGeometry **, int = -1, int * = NULL );
static OGRGeometry *createFromGML( const char * );
static OGRGeometry *createFromGEOS( GEOSGeom );
static void destroyGeometry( OGRGeometry * );
static OGRGeometry *createGeometry( OGRwkbGeometryType );
static OGRGeometry * forceToPolygon( OGRGeometry * );
static OGRGeometry * forceToLineString( OGRGeometry *, bool bOnlyInOrder = true );
static OGRGeometry * forceToMultiPolygon( OGRGeometry * );
static OGRGeometry * forceToMultiPoint( OGRGeometry * );
static OGRGeometry * forceToMultiLineString( OGRGeometry * );
static OGRGeometry * organizePolygons( OGRGeometry **papoPolygons,
int nPolygonCount,
int *pbResultValidGeometry,
const char **papszOptions = NULL);
static void *getGEOSGeometryFactory();
static int haveGEOS();
static OGRGeometry* transformWithOptions( const OGRGeometry* poSrcGeom,
OGRCoordinateTransformation *poCT,
char** papszOptions );
static OGRGeometry*
approximateArcAngles( double dfX, double dfY, double dfZ,
double dfPrimaryRadius, double dfSecondaryAxis,
double dfRotation,
double dfStartAngle, double dfEndAngle,
double dfMaxAngleStepSizeDegrees );
};
OGRwkbGeometryType CPL_DLL OGRFromOGCGeomType( const char *pszGeomType );
const char CPL_DLL * OGRToOGCGeomType( OGRwkbGeometryType eGeomType );
/* Prepared geometry API (needs GEOS >= 3.1.0) */
typedef struct _OGRPreparedGeometry OGRPreparedGeometry;
int OGRHasPreparedGeometrySupport();
OGRPreparedGeometry* OGRCreatePreparedGeometry( const OGRGeometry* poGeom );
void OGRDestroyPreparedGeometry( OGRPreparedGeometry* poPreparedGeom );
int OGRPreparedGeometryIntersects( const OGRPreparedGeometry* poPreparedGeom,
const OGRGeometry* poOtherGeom );
#endif /* ndef _OGR_GEOMETRY_H_INCLUDED */
<|start_filename|>mapmint-ui/css/scalebar.css<|end_filename|>
/*ScaleBar*/
.scalebar-container{
position:absolute;
bottom:45px;
right:10px;
width:200px;
background:#FFFFFF;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
-moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
z-index:1000;
}
#scalebar{
z-index:1000;
margin: 0 15%;
}
.olControlScaleBar {
padding:0;
max-width:120px;
font-family: arial;
color: #FFFFFF;
right: 10px;
bottom: 37.5px;
z-index: 1002;
}
.olControlScaleBarBar {
height: 11px;
top: 12px;
background-color: #00008B;
background-image: url(../img/scalebar-bar.png);
background-position: 0 0;
background-repeat: repeat-x;
}
.olControlScaleBarBarAlt {
height: 11px;
top: 12px;
background-color: #00008B;
background-image: url(../img/scalebar-bar.png);
background-position: 0 0;
background-repeat: repeat-x;
}
.olControlScaleBarMarkerMajor {
height: 13px;
width: 13px;
top: 12px;
background-image: url(../img/scalebar-marker.png);
background-position: 0 0;
background-repeat: no-repeat;
z-index: 5000;
}
.olControlScaleBarMarkerMinor {
height: 13px;
width: 13px;
top: 12px;
background-image: url(../img/scalebar-marker.png);
background-position: 0 0;
background-repeat: no-repeat;
z-index: 5000;
}
.olControlScaleBarNumbersBox {
height: 13px;
width: 40px;
top: 24px;
font-size: .7em;
font-weight:normal;
color:#816c5b;
}
.olControlScaleBarLabelBox {
height: 15px;
top: -2px;
font-size: .8em;
font-weight:normal;
color:#816c5b;
}
.olControlScaleBarLabelBoxSingleLine {
height: 15px;
width: 35px;
top: 0px;
left: 10px;
font-size: 13px;
}
<|start_filename|>mapmint-ui/templates/preview/modules/indexes/init.js<|end_filename|>
function readIndexForGeo(featureGeoJSON,lbounds){
for(var i=0;i<queryLayersList.length;i++){
if(queryLayersList[i].real_name==\$('#it1 option:selected').text()){
var params=[{"name": "InputEntity1","value": featureGeoJSON,"mimeType": "application/json"},{"name": "InputEntity2", "xlink:href": msUrl+"?map="+mapPath+"/project_${conf["senv"]["last_map"]}.map&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=ms:"+queryLayersList[i].local_id+"&bbox="+lbounds.getBounds(),"mimeType": "text/xml"}];
if(System.inMap || System.outMap){
if(!System.allOverlays){
if((System.si=="in") && System.outMap)
params.push({"name": "InputEntity3","xlink:href": System.outMap+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
else
if(System.inMap)
params.push({"name": "InputEntity3","xlink:href": System.inMap+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
}else
params.push({"name": "InputEntity3","xlink:href": System.allOverlays+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result&bbox="+lbounds.getBounds()+"&__tt="+Date(),"mimeType": "text/xml"});
}
req=WPSGetHeader("vector-tools.Intersection0")+WPSGetInputs(params)+WPSGetOutput({"name": "Result","form":"ResponseDocument","mimeType": "image/png","asReference":"true"})+WPSGetFooter();
$.ajax({
type: "POST",
url: System.zooUrl,
contentType: 'text/xml',
data: req,
complete: function(xml,status) {
//urlContext = xml.responseText;
var params=[];
if(System.si=="in"){
if(System.inMap){
System.inMap0=System.inMap;
params.push({"name": "InputEntity1", "xlink:href": System.inMap0+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
}
System.inMap=WPSParseReference(xml);
//alert((params.length+1)+" "+System.inMap);
//alert(xml);
params.push({"name": "InputEntity"+(params.length+1), "xlink:href": System.inMap+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
}else{
if(System.outMap){
System.outMap0=System.outMap;
params.push({"name": "InputEntity2", "xlink:href": System.outMap0+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
}
System.outMap=WPSParseReference(xml);
params.push({"name": "InputEntity1", "xlink:href": System.outMap+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=Result"+"&__tt="+Date(),"mimeType": "text/xml"});
}
req0=WPSGetHeader("nullGeo")+WPSGetInputs([{"name": "InputEntity1", "xlink:href": ((System.si=="in")?System.inMap:System.outMap)+"&SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&typeName=ms:Result"+"&__tt="+Date(),"mimeType": "text/xml"}])+WPSGetOutput({"name": "Result","form":"RawDataOutput","mimeType": "application/json","asReference":"true"})+WPSGetFooter();
indexes_reaction(req0,params);
}
});
}
}
}
var myStyleMap=new OpenLayers.StyleMap({
"default": new OpenLayers.Style({
strokeColor: "#eeeeee",
pointRadius: 5,
strokeWidth: 1
}, {
rules: [
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LIKE,
property: "idx_type",
value: "in"
}),
symbolizer: {
fillColor: "#880000",
pointRadius: 5
}
}),
new OpenLayers.Rule({
filter: new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.LIKE,
property: "idx_type",
value: "out"
}),
symbolizer: {
fillColor: "#000088",
pointRadius: 5
}
}),
new OpenLayers.Rule({
elseFilter: true,
symbolizer: {
fillColor: "#aaaa00",
opacity: 0.3,
pointRadius: 5
}
})
]
})
});
TerritoriesSelected=new OpenLayers.Layer.Vector("TerritoriesSelected", {
styleMap: myStyleMap,
renderers: System.renderer
});
map.addLayer(TerritoriesSelected);
System.overlays={};
idxCirControl = new OpenLayers.Control();
OpenLayers.Util.extend(idxCirControl, {
draw: function () {
// this Handler.Box will intercept the shift-mousedown
// before Control.MouseDefault gets to see it
this.box = new OpenLayers.Handler.RegularPolygon( idxCirControl,
{"done": this.notice},
{sides: 40});
this.box.activate();
},
notice: function (bounds) {
\$('#output-gfi').html("");
var geojson = new OpenLayers.Format.GeoJSON;
featureGeoJSON=geojson.write(new OpenLayers.Feature.Vector(bounds.transform(mercator,wgs84)));
readIndexForGeo(featureGeoJSON,bounds);
}
});
idxStdControl = new OpenLayers.Control();
OpenLayers.Util.extend(idxStdControl, {
draw: function () {
// this Handler.Box will intercept the shift-mousedown
// before Control.MouseDefault gets to see it
this.box = new OpenLayers.Handler.Box( idxStdControl,
{"done": this.notice});
this.box.activate();
},
notice: function (bounds) {
var geojson = new OpenLayers.Format.GeoJSON;
var ll = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.left, bounds.bottom)).transform(map.getProjectionObject(),wgs84);
var ur = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.right, bounds.top)).transform(map.getProjectionObject(),wgs84);
bounds1 = new OpenLayers.Bounds();
bounds1.extend(ll);
bounds1.extend(ur);
bounds0=bounds1.toGeometry();
var attributes = {name: "<NAME>", bar: "foo"};
featureGeoJSON=geojson.write(new OpenLayers.Feature.Vector(bounds0,attributes));
readIndexForGeo(featureGeoJSON,bounds0);
}
});
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
defaultHandlerOptions: {
'single': true,
'double': false,
'pixelTolerance': 0,
'stopSingle': false,
'stopDouble': false
},
initialize: function(options) {
this.handlerOptions = OpenLayers.Util.extend(
{}, this.defaultHandlerOptions
);
OpenLayers.Control.prototype.initialize.apply(
this, arguments
);
this.handler = new OpenLayers.Handler.Click(
this, {
'click': this.notice
}, this.handlerOptions
);
},
notice: function(e) {
var lonlat = map.getLonLatFromViewPortPx(e.xy);
bounds3=lonlat;
var ll=new OpenLayers.LonLat(bounds3.lon-100, bounds3.lat-100);
var ur=new OpenLayers.LonLat(bounds3.lon+100, bounds3.lat+100);
bounds2 = new OpenLayers.Bounds();
bounds2.extend(ll);
bounds2.extend(ur);
bounds2.transform(map.getProjectionObject(),wgs84);
bounds4=bounds2.toGeometry();
var attributes = {name: "<NAME>", bar: "foo"};
var geojson = new OpenLayers.Format.GeoJSON;
featureGeoJSON=geojson.write(new OpenLayers.Feature.Vector(bounds4,attributes));
readIndexForGeo(featureGeoJSON,bounds4);
}
});
idxPoiControl = new OpenLayers.Control.Click();
toggleRepportSubmit(false);
idxCtrl={"infopoint": idxPoiControl, "info": idxStdControl,"infocircle": idxCirControl};
map.addControls([idxPoiControl,idxStdControl,idxCirControl]);
for(var i in idxCtrl)
mapControls[i]=idxCtrl[i];
for(i in mapControls){
toggleControl({"name":i});
break;
}
<|start_filename|>public_map/mapmint-nudemap.css<|end_filename|>
#loading{
position:absolute;
top: 10px;
left: 10px;
width:200px;
font-size:.8em;
color:#707070;
z-index:1000;
background:#FFFFFF;
border-radius:5px;
}
.tipsy{font-size:13px !important;}
#loading ul{list-style:none;}
.copy p {
padding: 6px 0 10px 0;
}
#coords{float:left;padding:0 5px 0 0;color:#FFFFFF;font-size:.8em;text-shadow:#000000 0 1px 0;display:inline;position:absolute;right:100px !important;bottom:16px;}
#base_layers{
position: absolute;
top: 10px;
right:10px;
}
<|start_filename|>mapmint-services/print/service.js<|end_filename|>
/******************************************************************************
* Author: <NAME>, <EMAIL>
* Copyright (c) 2011-2014, Cartoworks Inc.
******************************************************************************
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************/
function printMapImage(conf,inputs,outputs){
var myOutputs0= {"Result": { type: 'RawDataOutput', "mimeType": "application/json" }};
var myInputs0= {
tmpl: { "value":"preview/tobbox18_js" ,"dataType": "string" },
lat: { "value": inputs["lat"]["value"] ,"dataType": "string" },
lon: { "value":inputs["lon"]["value"] ,"dataType": "string" }
};
var myProcess0 = new ZOO.Process(conf["main"]["serverAddress"],'template.display');
alert(inputs);
var myExecuteResult0=myProcess0.Execute(myInputs0,myOutputs0);//,"Cookie: MMID="+conf["senv"]["MMID"]);
alert(myExecuteResult0);
var tmp=eval(myExecuteResult0);
var ext=tmp[0][0]+","+tmp[0][1]+","+tmp[1][0]+","+tmp[1][1];
var ext1=tmp[0][0]+","+tmp[1][1]+","+tmp[1][0]+","+tmp[0][1];
var bl="base_layers/default.xml";
try{
bl="base_layers/"+inputs["bl"]["value"]+".xml";
}catch(e){
}
var myInputs1= {
InputDSN: { "value": bl ,"dataType": "string" },
OutputDSN: { "value": "PRINTED_MAP_"+conf["lenv"]["usid"] ,"dataType": "string" },
Format: { "value": "png","dataType": "string" },
OutSize: { "value": "1024,768","dataType": "string" },
ProjWin: { "value": ext1,"dataType": "string" }
};
var myOutputs1= {Result: { type: 'RawDataOutput', "mimeType": "text/plain" }};
var myProcess1 = new ZOO.Process(conf["main"]["serverAddress"],'raster-tools.translate');
alert(inputs);
var myExecuteResult1=myProcess1.Execute(myInputs1,myOutputs1);//,"Cookie: MMID="+conf["senv"]["MMID"]);
alert(myExecuteResult1);
var myInputs2= {
layers: { "value": "0" ,"dataType": "string" },
ext: { "value": ext, "dataType": "string" },
iFormat: { "value": "A4l","dataType": "string" },
map: { "value": inputs["map"]["value"],"dataType": "string" },
bgMap: { "value": myExecuteResult1,"dataType": "string" },
zoom: { "value": "18","dataType": "string" },
tDoc: { "value": "MM-PrintedMap.pdf","dataType": "string" }
};
var myOutputs2= {Result: { type: 'RawDataOutput', "mimeType": "text/plain" }};
var myProcess2 = new ZOO.Process(conf["main"]["serverAddress"],'print.printOnlyMap');
alert(inputs);
var myExecuteResult2=myProcess2.Execute(myInputs2,myOutputs2);//,"Cookie: MMID="+conf["senv"]["MMID"]);
alert(myExecuteResult2);
outputs["Result"]["generated_file"]=myExecuteResult2;
//outputs["Result"]["value"]=myExecuteResult2;
return {result: ZOO.SERVICE_SUCCEEDED, outputs: outputs};
}
<|start_filename|>mapmint-ui/js/datawarehouse-controls.js<|end_filename|>
$(function() {
$('a.tool').tipsy({fade: true, offset:3, opacity: 1, gravity: 'nw'});
});
$(function() {
$(".error").click(function(){
$.notifyBar({ cls: "error", html: "error occured" });
});
$(".success").click(function(){
$.notifyBar({ cls: "success", html: "operation sucessful" });
});
$(".common").click(function(){
$.notifyBar({ cls: "common", html: "<p class='load'>Chargement <img src='img/loadingbar.gif' /></p>" });
});
});
$(function() {
$('.maincfg1').button({
text: false
});
$('.maincfg2').button({
text: false
});
$('.db').button({
text: false
}).click(function() {
$( ".dialog-postgis" ).dialog("open");
});
$('.pg-db').button({
text: false
}).click(function() {
$( ".dialog-postgis-new" ).dialog("open");
});
$('.dir').button({
text: false
});
$('.add-layer-vector').button({
text: false
});
$('.add-layer-raster').button({
text: false
}).click(function() {
$( "#dialog1" ).dialog('open');
});
$('.add-layer-wfs').button({
text: false
}).click(function() {
$( ".dialog-wfs" ).dialog("open");
});
$('.wfs-new').button({
text: false
}).click(function() {
$( ".dialog-wfs-new" ).dialog("open");
});
$('.add-layer-wms').button({
text: false
}).click(function() {
$( ".dialog-wms" ).dialog("open");
});
$('.wms-new').button({
text: false
}).click(function() {
$( ".dialog-wms-new" ).dialog("open");
});
$('.add-layer-wcs').button({
text: false
})
$('.get-layer-info').button({
text: false
})
$('.export-layer').button({
text: false
})
$('.delete-layer').button({
text: false
})
$( ".f" ).button();
$( ".start-stop" ).button();
$('#forward').button({
text: false,
icons: {
primary: 'ui-icon-seek-next'
}
});
$('#end').button({
text: false,
icons: {
primary: 'ui-icon-seek-end'
}
});
$("#shuffle").button();
$("#repeat").buttonset();
});
<|start_filename|>mapmint-ui/templates/preview/modules/geolocation/init.js<|end_filename|>
var pulsate = function(feature) {
var point = feature.geometry.getCentroid(),
bounds = feature.geometry.getBounds(),
radius = Math.abs((bounds.right - bounds.left)/2),
count = 0,
grow = 'up';
var resize = function(){
if (count>16) {
clearInterval(window.resizeInterval);
}
var interval = radius * 0.03;
var ratio = interval/radius;
switch(count) {
case 4:
case 12:
grow = 'down'; break;
case 8:
grow = 'up'; break;
}
if (grow!=='up') {
ratio = - Math.abs(ratio);
}
feature.geometry.resize(1+ratio, point);
geolocation.drawFeature(feature);
count++;
};
window.resizeInterval = window.setInterval(resize, 50, point, radius);
};
<|start_filename|>public_map/assets/js/documents.js<|end_filename|>
// Filename: login.js
define([
'module', 'jquery', 'zoo','notify', 'metisMenu', 'summernote', 'xml2json','typeahead', 'adminBasic', 'ol','datasources','mmDataTables','rowReorder','colorpicker','slider',"sortable"
], function(module, $,Zoo,notify, metisMenu, summernote, X2JS,typeahead,adminBasic,ol,datasources,MMDataTable,rowReorder,colorpicker,slider,sortable) {
(function(){
var methods = ['addClass', 'removeClass'];
$.each(methods, function (index, method) {
var originalMethod = $.fn[method];
$.fn[method] = function () {
var oldClass = this.className;
var result = originalMethod.apply(this, arguments);
var newClass = this.className;
this.trigger(method, [oldClass, newClass]);
return result;
};
});
})();
var _x2js = new X2JS({
arrayAccessFormPaths: [
'ProcessDescriptions.ProcessDescription.DataInputs.Input',
'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
'Capabilities.ServiceIdentification.Keywords'
],
});
var zoo = new Zoo({
url: module.config().url,
delay: module.config().delay,
language: module.config().language
});
var llevels=["first","second","third","forth"];
var llevelInit=false;
var reg0=new RegExp("documents_","");
var reloadElement=true;
function loadElements(table,init){
zoo.execute({
identifier: "np.list",
type: "POST",
dataInputs: [
{"identifier": "table","value": table,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
if(!reloadElement)
return;
if(init){
if($("#listElements").find("#document_"+localId).length){
console.log($("#listElements").find("#document_"+localId).hasClass("selected"));
if(!$("#listElements").find("#document_"+localId).hasClass("selected"))
$("#listElements").find("#document_"+localId).click();
else{
for(var i=0;i<2;i++)
$("#listElements").find("#document_"+localId).click();
}
}else{
loadAnElement(localId);
}
}
else
for(var i=0;i<data.length;i++){
if(data[i]["selected"]){
if($("#listElements").find("#document_"+data[i]["id"]).length){
$("#listElements").find("#document_"+data[i]["id"]).click();
}else{
loadAnElement(data[i]["id"]);
}
break;
}
}
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function fileUrlSelection(data){
$("input#file").val("");
if(data["url"]==null){
$("input[name=doct]").first().prop("checked",true);
$("input[name=doct]").first().click();
$("#documents_file_link").attr("href",module.config().publicationUrl+"/documents/"+data["file"]);
$("#documents_file_link").html(data["file"]);
}
else{
$("input[name=doct]").last().prop("checked",true);
$("input[name=doct]").last().click();
$("#documents_file_link").attr("href","");
$("#documents_file_link").html("");
}
}
function fillForm(data){
$(".project-title").html(data["name"]);
var myRootLocation=$(".theForm");
var reg=new RegExp("documents_","");
myRootLocation.find("textarea").each(function(){
if(!$(this).attr("id"))
return;
if($(this).attr("id").replace(reg,"")=="description"){
$(this).summernote("code",data[$(this).attr("id").replace(reg,"")]);
}
else
$(this).val(data[$(this).attr("id").replace(reg,"")]).change();
});
myRootLocation.find("input[type=text],select").each(function(){
if(!$(this).attr("id"))
return;
if($(this).attr("type")=="text"){
if($(this).attr("id").replace(/color/g,"")!=$(this).attr("id")){
if(data[$(this).attr("id").replace(reg,"")])
$(this).val("#"+data[$(this).attr("id").replace(reg,"")]).change();
else
$(this).val("#000").change();
}
else
$(this).val(data[$(this).attr("id").replace(reg,"")])
}else{
$(this).find('option').prop('selected', false);
if($.isArray(data[$(this).attr("id").replace(reg,"")])){
var obj=data[$(this).attr("id").replace(reg,"")];
var oid=$(this).attr("id").replace(reg,"");
if(obj.length==0)
$(this).find('option[value="-1"]').prop("selected",true);
for(var i=0;i<obj.length;i++){
$(this).find('option[value="'+obj[i]+'"]').prop("selected",true);
}
}else{
$(this).val((data[$(this).attr("id").replace(reg,"")]!=null?data[$(this).attr("id").replace(reg,"")]:-1));
}
}
});
}
function loadAnElement(id){
localId=id;
//console.log("loadATheme -> "+id);
$(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.details",
type: "POST",
dataInputs: [
{"identifier": "table","value": "documents","dataType":"string"},
{"identifier": "id","value": id,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
fileUrlSelection(data);
$(".fa-spin").addClass("hide");
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function createJsonFromForm(form){
var params={};
form.find('textarea').each(function(){
if(!$(this).attr("id"))
return;
var cid=$(this).attr('id').replace(reg0,"");
if(cid=="description")
params[cid]=$(this).summernote("code");
else
params[cid]=$(this).val();
});
form.find('input[type="text"]').each(function(){
if(!$(this).attr("id"))
return;
if($(this).attr("id").replace(/color/g,"")!=$(this).attr("id"))
params[$(this).attr('id').replace(reg0,"")]=$(this).val().replace(/#/,"");
else
params[$(this).attr('id').replace(reg0,"")]=$(this).val();
});
form.find('select').each(function(){
if(!$(this).attr("id"))
return;
if($(this).find("option:selected").length>1){
params[$(this).attr('id').replace(reg0,"")]=[];
var oid=$(this).attr('id').replace(reg0,"");
$(this).find("option:selected").each(function(){
params[oid].push($(this).val());
});
}else
params[$(this).attr('id').replace(reg0,"")]=$(this).val();
});
return params;
}
function bindSave(){
$(".theForm").find("button").click(function(){
$('#documents_filename').val($('#file').val());$('#fileUpload').submit();
});
}
var lid="listElements";
function saveAnElement(){
var id=localId;
$(".fa-spin").removeClass("hide");
var obj=createJsonFromForm($(".theForm"));
obj["id"]=id;
localId=id;
obj["filename"]=$('input#file').val();
localInit=true;
zoo.execute({
identifier: "np.updateElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": "documents","dataType":"string"},
{"identifier": "documents_groups_in", value: "d_id",dataType: "string"},
{"identifier": "documents_groups_out", value: "g_id",dataType: "string"},
{"identifier": "documents_themes_in", value: "d_id",dataType: "string"},
{"identifier": "documents_themes_out", value: "t_id",dataType: "string"},
{"identifier": "tuple","value": JSON.stringify(obj, null, ' '),"mimeType":"application/json"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
$(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
reloadElement=true;
$("#"+lid).dataTable().fnDraw();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function addAnElement(){
$(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.insertElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": "documents","dataType":"string"},
{"identifier": "name","value": $("#adder").find('input[name="dname"]').val(),"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
fillForm(data);
$(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
localInit=false;
reloadElement=true;
$("#"+lid).dataTable().fnDraw();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
function deleteAnElement(id){
$(".fa-spin").removeClass("hide");
zoo.execute({
identifier: "np.deleteElement",
type: "POST",
dataInputs: [
{"identifier": "table","value": "documents","dataType":"string"},
{"identifier": "atable","value": "documents_themes","dataType":"string"},
{"identifier": "akey","value": "d_id","dataType":"string"},
{"identifier": "atable","value": "documents_groups","dataType":"string"},
{"identifier": "akey","value": "d_id","dataType":"string"},
{"identifier": "id","value": id,"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","type":"raw"},
],
success: function(data){
$(".fa-spin").addClass("hide");
$(".notifications").notify({
message: { text: data },
type: 'success',
}).show();
localInit=false;
reloadElement=true;
$("#"+lid).dataTable().fnDraw();
},
error: function(data){
$(".notifications").notify({
message: { text: data["ExceptionReport"]["Exception"]["ExceptionText"].toString() },
type: 'danger',
}).show();
}
});
}
var localInit=false;
var localItem=-1;
function startDataTable(rfields,fields){
var cnt=0;
var CRowSelected=[];
var CFeaturesSelected=[];
var CFeatures=[];
var lid="listElements";
$('#listElements').DataTable( {
language: {
url: module.config().translationUrl
},
data: [],
"dom": 'Zlfrtip',
"colResize": true,
autoWidth: false,
"scrollY": ($(window).height()/2)+"px",
"scrollCollapse": true,
"scrollX": true,
//"sScrollX": "100%",
//"sScrollXInner": "100%",
"bAutoWidth": false,
"bProcessing": true,
"bServerSide": true,
fixedHeader: true,
//searching: true,
responsive: true,
deferRender: true,
crollCollapse: true,
ordering: "id",
rowId: 'fid',
"sAjaxSource": "users",
select: {
info: false,
},
"lengthMenu": [[5, 10, 25, 50, 1000], [5, 10, 25, 50, "All"]],
columns: fields,
"rowCallback": function( row, data ) {
$(row).removeClass('selected');
if ( $.inArray(data.DT_RowId, CRowSelected) !== -1 ) {
$('#'+lid).DataTable().row($(row)).select();
}else{
$('#'+lid).DataTable().row($(row)).deselect();
}
},
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
var llimit=[];
for(j in {"iDisplayStart":0,"iDisplayLength":0,"iSortCol_0":0,"sSortDir_0":0,"sSearch":0})
for(i in aoData)
if(aoData[i].name==j){
if(llimit.length==4 && aoData[i].value!="")
llimit.push(aoData[i].value);
if(llimit.length<4)
llimit.push(aoData[i].value);
}
var closestproperties=rfields;
var page=llimit[0]+1;
if(page!=1){
page=(llimit[0]/llimit[1])+1;
}
var opts=zoo.getRequest({
identifier: "datastores.postgis.getTableContent",
dataInputs: [
{"identifier":"dataStore","value":module.config().db,"dataType":"string"},
{"identifier":"table","value":"mm.documents","dataType":"string"},
{"identifier":"offset","value":llimit[0],"dataType":"int"},
{"identifier":"limit","value":llimit[1],"dataType":"int"},
{"identifier":"page","value":page,"dataType":"int"},
{"identifier":"sortorder","value":llimit[3],"dataType":"string"},
{"identifier":"search","value":llimit[llimit.length-1],"dataType":"string"},
{"identifier":"sortname","value":(closestproperties.split(",")[llimit[2]]),"dataType":"string"},
{"identifier":"fields","value":closestproperties.replace(/,msGeometry/g,""),"dataType":"string"}
],
dataOutputs: [
{"identifier":"Result","mimeType":"application/json","type":"raw"}
],
type: 'POST',
storeExecuteResponse: false
});
opts["success"]=function(rdata) {
features=rdata;
featureCount=rdata["total"];
var data=[];
CFeatures=[];
for(var i in features.rows){
var lparams={
"fid": "document_"+features.rows[i].id
}
var tmp=rfields.split(',');
for(var kk=0;kk<tmp.length;kk++)
lparams[tmp[kk]]=features.rows[i].cell[kk];
data.push(lparams);
CFeatures.push(data[data.length-1]);
}
var opts={
"sEcho": cnt++,
"iDraw": cnt++,
"iTotalRecords": featureCount,
"iTotalDisplayRecords": featureCount,
"aaData": (featureCount>0?data:[])
};
fnCallback(opts);
for(d in data){
if ( $.inArray(data[d].fid+"", CRowSelected) !== -1 ) {
$('#'+lid).DataTable().row($("#"+data[d].fid)).select();
}else{
$('#'+lid).DataTable().row($("#"+data[d].fid)).deselect();
}
}
if(featureCount==0){
$('#'+lid+'Table').DataTable().clear();
}
var existing=$('#'+lid+'_info').children('span.select-info');
if(existing.length)
existing.remove();
var lreg=new RegExp("\\[dd\\]","g");
$('#'+lid+'_info').append($('<span class="select-info"/>').append(
$('<span class="select-item"/>').append((CRowSelected.length>1?module.config().localizationStrings.dataTables.selection:module.config().localizationStrings.dataTables.selection0).replace(lreg,CRowSelected.length).replace(lreg,CRowSelected.length))
));
loadElements("documents",localInit);
};
opts["error"]=function(){
notify('Execute failed:' +data.ExceptionReport.Exception.ExceptionText, 'danger');
};
oSettings.jqXHR = $.ajax( opts );
}
});
var ltype="document";
//var myRootElement=$('#'+lid).parent().find(".btn-group").first().parent();
$('#'+lid+' tbody').on('click', 'tr', function () {
if(!this.id)
return;
var id = this.id+"";
var reg0=new RegExp(ltype+'s_',"g");
var index = $.inArray(id, CRowSelected);
if ( index == -1 ) {
if(CRowSelected.length>0){
$('#'+lid).DataTable().row($("#"+CRowSelected[0])).deselect();
CRowSelected.pop(CRowSelected[0]);
CFeaturesSelected.pop(CFeaturesSelected[0]);
}
/*if(CFeaturesSelected.length==0)
myRootElement.find(".require-select").removeClass("disabled");*/
CRowSelected.push( id );
$('#'+lid).DataTable().row("#"+id).select();
for(var i=0;i<CFeatures.length;i++){
if(CFeatures[i]["fid"]==id)
CFeaturesSelected.push( CFeatures[i] );
}
reg=new RegExp(ltype+"_","g");
localId=id.replace(reg,"");
reloadElement=false;
loadAnElement(localId);
} else {
$("."+lid+"BaseEditForm").removeClass("in");
CRowSelected.pop(index);
CFeaturesSelected.pop(index);
$('#'+lid).DataTable().row("#"+id).deselect();
}
var existing=$('#'+lid+'_info').children('span.select-info');
if(existing.length)
existing.remove();
var lreg=[
new RegExp("\\[dd\\]","g"),
new RegExp("\\[ee\\]","g")
];
var currentLoc=(CFeaturesSelected.length!=CRowSelected.length?(CRowSelected.length>1?module.config().localizationStrings.dataTables.selectionm:module.config().localizationStrings.dataTables.selectionm0):(CRowSelected.length>1?module.config().localizationStrings.dataTables.selection:module.config().localizationStrings.dataTables.selection0));
$('#'+lid+'_info').append($('<span class="select-info"/>').append(
$('<span class="select-item"/>').append(currentLoc.replace(lreg[0],CRowSelected.length).replace(lreg[1],CFeaturesSelected.length))
));
});
}
var initialize=function(){
adminBasic.initialize(zoo);
window.setTimeout(function () {
$("textarea#documents_description").summernote();
},10);
$('[data-toggle="tooltip"]').tooltip({container: 'body'});
startDataTable("id,name",[
{
"data": "id",
"name": "id",
"width": "10%"
},
{
"data": "name",
"name": "name",
"width": "80%"
},
]);
bindSave();
$("#adder").find("button").click(function(){
addAnElement();
$("#adder").removeClass("in");
});
$("#deleter").find("button").click(function(){
deleteAnElement(localId);
$("#deleter").removeClass("in");
});
console.log("Start Documents");
};
// Return public methods
return {
initialize: initialize,
saveAnElement: saveAnElement
};
});
<|start_filename|>public_map/mapmint-mobile.css<|end_filename|>
img.logo {
float: left;
position: relative;
top: 5px;
left: 5px;
}
#coords {
float: left;
padding: 0 2px 0 0;
color: white;
font-size: .8em;
text-shadow: #333 0 1px 0;
display: inline;
position: absolute;
right: 10px;
bottom: 50px;
}
.ui-footer {
height: 68px;
}
.ui-bar-f {
border-top: 1px solid #56A00E;
border-bottom: 1px solid #56A00E;
background: #74B042;
color: white;
font-weight: bold;
text-shadow: 0 -1px 1px #234403;
background-image: -webkit-gradient(linear, left top, left bottom, from(#74B042), to(#56A00E));
background-image: -webkit-linear-gradient(#74B042, #56A00E);
background-image: -moz-linear-gradient(#74B042, #56A00E);
background-image: -ms-linear-gradient(#74B042, #56A00E);
background-image: -o-linear-gradient(#74B042, #56A00E);
background-image: linear-gradient(#74B042, #56A00E);
}
.ui-content{
padding: 0px;
}
.ui-icon-layers{
background-image: url(img/layers-icon.png) !important;
}
.ui-icon-startPoint{
background-image: url(img/startMarker-small.png);
}
.ui-icon-endPoint{
background-image: url(img/endMarker-small.png);
}
.ui-icon-interPoint{
background-image: url(img/interMarker-small.png);
}
.scalebar-container {
bottom: 5px;
}
.page{
overflow: none;
}
.baselayer_icon{
display: block;
float: left;
height: 20px;
margin-right: 15px;
margin-top: -5px;
width: 20px;
}
.ui-icon-check {
opacity: 0.3;
}
.checked .ui-icon-check {
opacity: 1;
}
.layersPage .ui-content {
padding: 0px 15px 0px 15px;
}
.layersPage .hidden{
display: none;
}
.hidden{
display: none;
}
.mmCompassContainer{
background: url('../img/mmCompassBg0.png') no-repeat;
width: 42px;
height: 42px;
margin-left: 5px;
margin-top: -5px;
}
#mmCompassContainer{
cursor: move;
}
#imgLogo{
position: absolute;
left: 7px;
top: 7px;
}
/**
* Compass
*/
#compass {
background-image:-webkit-radial-gradient(30% 30%, #FFEE72, #666900);
margin-left: 5px;
border-radius:130px;
width:60px;
height:60px;
display:block;
}
@media (orientation:landscape) {
#compass {
margin-top:-2px;
}
}
@media (orientation:portrait) {
#compass {
margin-top:-2px;
}
}
#spinner {
background-image:-webkit-radial-gradient(30% 30%, #FFF6F4, #D1C790);
box-shadow:0 0 1px #444 inset;
position:relative;
top:5px;
left:5px;
border-radius:100px;
width:50px;
height:50px;
-webkit-transition: all 0.2s ease-in-out;
}
#pin {
background-image:-webkit-radial-gradient(30% 30%, #FFEE72, #666900);
box-shadow:0 0 1px #444;
position:relative;
top:22.5px;
left:22.5px;
border-radius:5px;
width:5px;
height:5px;
}
.degree, .point, .arrow {
position:absolute;
left:15px;
width:20px;
text-align:center;
top:2.5px;
-webkit-transform-origin:10px 47.5px;
}
.degree {
color:#222;
}
.point {
top:-1px;
-webkit-transform-origin:10px 27.5px;
font-size:10px;
}
.point.main {
font-weight:bold;
font-size: 16px;
}
.arrow {
left:23.75px;
top:-7.5px;
-webkit-transform-origin:2.5px 32.5px;
width: 0;
height: 0;
border-left: 2.5px solid transparent;
border-right: 2.5px solid transparent;
border-bottom: 2.5px solid #777;
}
.arrow.main {
border-bottom: 5px solid #444;
}
/**
* Slider
*/
#slider-0{
position: absolute;
top: 10px;
left: 70px;
width: 56px;
display: none;
}
div.ui-slider{
position: absolute;
top: 2px;
right: 55px;
width: 125px;
}
@media (orientation:portrait) {
#slider-0 {
margin-top:-2px;
width: 125px;
}
div.ui-slider{
position: absolute;
top: 2px;
right: 75px;
width: 125px;
}
}
.ui-controlgroup-horizontal .ui-controlgroup-last {
margin: 0;
top: 0px;
}
.ui-btn-active{background:#74B042;}
.ui-focus{-moz-box-shadow:0 0 12px #74B042;-webkit-box-shadow:0 0 12px #74B042;box-shadow:0 0 12px #74B042}
.olcontrolscalebarlabelbox {
height: 15px;
top: -2px;
font-size: .8em;
font-weight: normal;
color: white;
}
.olcontrolscalebarnumbersbox {
height: 13px;
width: 40px;
top: 24px;
font-size: .7em;
font-weight: normal;
color: white;
}
.scalebar-container {
background: transparent;
}
.ui-loader {
z-index: 10000;
} | aryanxk02/mapmint |
<|start_filename|>tests/samples/issue-284-build-ext-inplace/hello/_hello_sk.cxx<|end_filename|>
// Python includes
#include <Python.h>
// STD includes
#include <stdio.h>
//-----------------------------------------------------------------------------
static PyObject *hello_example(PyObject *self, PyObject *args)
{
// Unpack a string from the arguments
const char *strArg;
if (!PyArg_ParseTuple(args, "s", &strArg))
return NULL;
// Print message and return None
PySys_WriteStdout("Hello, %s! :)\n", strArg);
Py_RETURN_NONE;
}
//-----------------------------------------------------------------------------
static PyObject *elevation_example(PyObject *self, PyObject *args)
{
// Return an integer
return PyLong_FromLong(21463L);
}
//-----------------------------------------------------------------------------
static PyMethodDef hello_methods[] = {
{
"hello",
hello_example,
METH_VARARGS,
"Prints back 'Hello <param>', for example example: hello.hello('you')"
},
{
"size",
elevation_example,
METH_VARARGS,
"Returns elevation of Nevado Sajama."
},
{NULL, NULL, 0, NULL} /* Sentinel */
};
//-----------------------------------------------------------------------------
#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC init_hello_sk(void)
{
(void) Py_InitModule("_hello_sk", hello_methods);
}
#else /* PY_MAJOR_VERSION >= 3 */
static struct PyModuleDef hello_module_def = {
PyModuleDef_HEAD_INIT,
"_hello_sk",
"Internal \"_hello_sk\" module",
-1,
hello_methods
};
PyMODINIT_FUNC PyInit__hello_sk(void)
{
return PyModule_Create(&hello_module_def);
}
#endif /* PY_MAJOR_VERSION >= 3 */
<|start_filename|>skbuild/resources/cmake/UseF2PY.cmake<|end_filename|>
#.rst:
#
# The following functions are defined:
#
# .. cmake:command:: add_f2py_target
#
# Create a custom rule to generate the source code for a Python extension module
# using f2py.
#
# add_f2py_target(<Name> [<F2PYInput>]
# [OUTPUT_VAR <OutputVar>])
#
# ``<Name>`` is the name of the new target, and ``<F2PYInput>``
# is the path to a pyf source file. Note that, despite the name, no new
# targets are created by this function. Instead, see ``OUTPUT_VAR`` for
# retrieving the path to the generated source for subsequent targets.
#
# If only ``<Name>`` is provided, and it ends in the ".pyf" extension, then it
# is assumed to be the ``<F2PYInput>``. The name of the input without the
# extension is used as the target name. If only ``<Name>`` is provided, and it
# does not end in the ".pyf" extension, then the ``<F2PYInput>`` is assumed to
# be ``<Name>.pyf``.
#
#
# Options:
#
# ``OUTPUT_VAR <OutputVar>``
# Set the variable ``<OutputVar>`` in the parent scope to the path to the
# generated source file. By default, ``<Name>`` is used as the output
# variable name.
#
# ``DEPENDS [source [source2...]]``
# Sources that must be generated before the F2PY command is run.
#
# Defined variables:
#
# ``<OutputVar>``
# The path of the generated source file.
#
# Example usage
# ^^^^^^^^^^^^^
#
# .. code-block:: cmake
#
# find_package(F2PY)
#
# # Note: In this case, either one of these arguments may be omitted; their
# # value would have been inferred from that of the other.
# add_f2py_target(f2py_code f2py_code.pyf)
#
# add_library(f2py_code MODULE ${f2py_code})
# target_link_libraries(f2py_code ...)
#
#=============================================================================
# Copyright 2011 Kitware, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#=============================================================================
get_property(languages GLOBAL PROPERTY ENABLED_LANGUAGES)
function(add_f2py_target _name)
set(options )
set(oneValueArgs OUTPUT_VAR)
set(multiValueArgs DEPENDS)
cmake_parse_arguments(_args "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
list(GET _args_UNPARSED_ARGUMENTS 0 _arg0)
# if provided, use _arg0 as the input file path
if(_arg0)
set(_source_file ${_arg0})
# otherwise, must determine source file from name, or vice versa
else()
get_filename_component(_name_ext "${_name}" EXT)
# if extension provided, _name is the source file
if(_name_ext)
set(_source_file ${_name})
string(REGEX REPLACE "\\.[^.]*$" "" _name ${_source})
# otherwise, assume the source file is ${_name}.pyf
else()
set(_source_file ${_name}.pyf)
endif()
endif()
set(_embed_main FALSE)
if("C" IN_LIST languages)
set(_output_syntax "C")
else()
message(FATAL_ERROR "C must be enabled to use F2PY")
endif()
set(extension "c")
set(generated_file "${CMAKE_CURRENT_BINARY_DIR}/${_name}module.${extension}")
set(generated_wrapper "${CMAKE_CURRENT_BINARY_DIR}/${_name}-f2pywrappers.f")
get_filename_component(generated_file_dir ${generated_file} DIRECTORY)
set_source_files_properties(${generated_file} PROPERTIES GENERATED TRUE)
set_source_files_properties(${generated_wrapper} PROPERTIES GENERATED TRUE)
set(_output_var ${_name})
if(_args_OUTPUT_VAR)
set(_output_var ${_args_OUTPUT_VAR})
endif()
set(${_output_var} ${generated_file} ${generated_wrapper} PARENT_SCOPE)
file(RELATIVE_PATH generated_file_relative
${CMAKE_BINARY_DIR} ${generated_file})
set(comment "Generating ${_output_syntax} source ${generated_file_relative}")
# Get the include directories.
get_source_file_property(pyf_location ${_source_file} LOCATION)
get_filename_component(pyf_path ${pyf_location} PATH)
# Create the directory so that the command can cd to it
file(MAKE_DIRECTORY ${generated_file_dir})
# Add the command to run the compiler.
add_custom_command(OUTPUT ${generated_file} ${generated_wrapper}
COMMAND ${F2PY_EXECUTABLE} ${pyf_location}
COMMAND ${CMAKE_COMMAND} -E touch ${generated_wrapper}
DEPENDS ${_source_file}
${_args_DEPENDS}
WORKING_DIRECTORY ${generated_file_dir}
COMMENT ${source_comment})
endfunction()
| vyasr/scikit-build |
<|start_filename|>schemas/ecclesia/lib/generated/user/application.js<|end_filename|>
export {};
//# sourceMappingURL=application.js.map | votecube/votecube-ui |
<|start_filename|>common/eglstate/common.cpp<|end_filename|>
#include "common.hpp"
#include <map>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <GLES/gl.h>
#include <GLES/glext.h> // this has to come after glext2 due to khr_debug collision
#include <GLES3/gl3.h>
#include <GLES3/gl31.h>
#include <GLES3/gl32.h>
// KHR_debug says "GL only", but functionality also exists in GLES 3.1, whereas KHR_debug does not. hence it is missing from both headers.
#ifndef GL_PROGRAM_PIPELINE
#define GL_PROGRAM_PIPELINE 0x82E4
#endif
namespace
{
std::map<int, const char*> sEnumMap;
std::map<int, const char*> sDrawEnumMap;
std::map<int, const char*> sEglEnumMap;
bool sInitedEnumMap = false;
#define InsertEnumString(e) \
sEnumMap.insert(std::pair<int, const char*>((e), (#e)))
#define InsertDrawEnumString(e) \
sDrawEnumMap.insert(std::pair<int, const char*>((e), (#e)))
#define InsertEglEnumString(e) \
sEglEnumMap.insert(std::pair<int, const char*>((e), (#e)))
// TODO: this really should be autogenerated from gl.xml
void InitEnumMap()
{
// generated from gl3.h by:
// grep "#define" gl3.h | awk '{print $3" "$2}' | sort | awk '{print "InsertEnumString("$2");"}'
// egl map inserts generated with:
// 1. cat egl.h | grep "#define" > defines.txt
// 2. cat defines.txt | awk '{ print "sEnumMap.insert(pair<int,string>("$3 ",\"" $2 "\"));" }'
InsertEglEnumString(EGL_SUCCESS);
InsertEglEnumString(EGL_NOT_INITIALIZED);
InsertEglEnumString(EGL_BAD_ACCESS);
InsertEglEnumString(EGL_BAD_ALLOC);
InsertEglEnumString(EGL_BAD_ATTRIBUTE);
InsertEglEnumString(EGL_BAD_CONFIG);
InsertEglEnumString(EGL_BAD_CONTEXT);
InsertEglEnumString(EGL_BAD_CURRENT_SURFACE);
InsertEglEnumString(EGL_BAD_DISPLAY);
InsertEglEnumString(EGL_BAD_MATCH);
InsertEglEnumString(EGL_BAD_NATIVE_PIXMAP);
InsertEglEnumString(EGL_BAD_NATIVE_WINDOW);
InsertEglEnumString(EGL_BAD_PARAMETER);
InsertEglEnumString(EGL_BAD_SURFACE);
InsertEglEnumString(EGL_CONTEXT_LOST);
InsertEglEnumString(EGL_BUFFER_SIZE);
InsertEglEnumString(EGL_ALPHA_SIZE);
InsertEglEnumString(EGL_BLUE_SIZE);
InsertEglEnumString(EGL_GREEN_SIZE);
InsertEglEnumString(EGL_RED_SIZE);
InsertEglEnumString(EGL_DEPTH_SIZE);
InsertEglEnumString(EGL_STENCIL_SIZE);
InsertEglEnumString(EGL_CONFIG_CAVEAT);
InsertEglEnumString(EGL_CONFIG_ID);
InsertEglEnumString(EGL_LEVEL);
InsertEglEnumString(EGL_MAX_PBUFFER_HEIGHT);
InsertEglEnumString(EGL_MAX_PBUFFER_PIXELS);
InsertEglEnumString(EGL_MAX_PBUFFER_WIDTH);
InsertEglEnumString(EGL_NATIVE_RENDERABLE);
InsertEglEnumString(EGL_NATIVE_VISUAL_ID);
InsertEglEnumString(EGL_NATIVE_VISUAL_TYPE);
InsertEglEnumString(EGL_SAMPLES);
InsertEglEnumString(EGL_SAMPLE_BUFFERS);
InsertEglEnumString(EGL_SURFACE_TYPE);
InsertEglEnumString(EGL_TRANSPARENT_TYPE);
InsertEglEnumString(EGL_TRANSPARENT_BLUE_VALUE);
InsertEglEnumString(EGL_TRANSPARENT_GREEN_VALUE);
InsertEglEnumString(EGL_TRANSPARENT_RED_VALUE);
InsertEglEnumString(EGL_NONE);
InsertEglEnumString(EGL_BIND_TO_TEXTURE_RGB);
InsertEglEnumString(EGL_BIND_TO_TEXTURE_RGBA);
InsertEglEnumString(EGL_MIN_SWAP_INTERVAL);
InsertEglEnumString(EGL_MAX_SWAP_INTERVAL);
InsertEglEnumString(EGL_LUMINANCE_SIZE);
InsertEglEnumString(EGL_ALPHA_MASK_SIZE);
InsertEglEnumString(EGL_COLOR_BUFFER_TYPE);
InsertEglEnumString(EGL_COLOR_COMPONENT_TYPE_EXT);
InsertEglEnumString(EGL_RENDERABLE_TYPE);
InsertEglEnumString(EGL_MATCH_NATIVE_PIXMAP);
InsertEglEnumString(EGL_CONFORMANT);
InsertEglEnumString(EGL_SLOW_CONFIG);
InsertEglEnumString(EGL_NON_CONFORMANT_CONFIG);
InsertEglEnumString(EGL_TRANSPARENT_RGB);
InsertEglEnumString(EGL_RGB_BUFFER);
InsertEglEnumString(EGL_LUMINANCE_BUFFER);
InsertEglEnumString(EGL_NO_TEXTURE);
InsertEglEnumString(EGL_TEXTURE_RGB);
InsertEglEnumString(EGL_TEXTURE_RGBA);
InsertEglEnumString(EGL_TEXTURE_2D);
InsertEglEnumString(EGL_VENDOR);
InsertEglEnumString(EGL_VERSION);
InsertEglEnumString(EGL_EXTENSIONS);
InsertEglEnumString(EGL_CLIENT_APIS);
InsertEglEnumString(EGL_HEIGHT);
InsertEglEnumString(EGL_WIDTH);
InsertEglEnumString(EGL_BUFFER_AGE_KHR);
InsertEglEnumString(EGL_LARGEST_PBUFFER);
InsertEglEnumString(EGL_TEXTURE_FORMAT);
InsertEglEnumString(EGL_TEXTURE_TARGET);
InsertEglEnumString(EGL_MIPMAP_TEXTURE);
InsertEglEnumString(EGL_MIPMAP_LEVEL);
InsertEglEnumString(EGL_RENDER_BUFFER);
InsertEglEnumString(EGL_VG_COLORSPACE);
InsertEglEnumString(EGL_VG_ALPHA_FORMAT);
InsertEglEnumString(EGL_HORIZONTAL_RESOLUTION);
InsertEglEnumString(EGL_VERTICAL_RESOLUTION);
InsertEglEnumString(EGL_PIXEL_ASPECT_RATIO);
InsertEglEnumString(EGL_SWAP_BEHAVIOR);
InsertEglEnumString(EGL_MULTISAMPLE_RESOLVE);
InsertEglEnumString(EGL_BACK_BUFFER);
InsertEglEnumString(EGL_SINGLE_BUFFER);
InsertEglEnumString(EGL_VG_COLORSPACE_sRGB);
InsertEglEnumString(EGL_VG_COLORSPACE_LINEAR);
InsertEglEnumString(EGL_VG_ALPHA_FORMAT_NONPRE);
InsertEglEnumString(EGL_VG_ALPHA_FORMAT_PRE);
InsertEglEnumString(EGL_DISPLAY_SCALING);
InsertEglEnumString(EGL_BUFFER_PRESERVED);
InsertEglEnumString(EGL_BUFFER_DESTROYED);
InsertEglEnumString(EGL_OPENVG_IMAGE);
InsertEglEnumString(EGL_CONTEXT_CLIENT_TYPE);
InsertEglEnumString(EGL_CONTEXT_CLIENT_VERSION);
InsertEglEnumString(EGL_MULTISAMPLE_RESOLVE_DEFAULT);
InsertEglEnumString(EGL_MULTISAMPLE_RESOLVE_BOX);
InsertEglEnumString(EGL_OPENGL_ES_API);
InsertEglEnumString(EGL_OPENVG_API);
InsertEglEnumString(EGL_OPENGL_API);
InsertEglEnumString(EGL_DRAW);
InsertEglEnumString(EGL_READ);
InsertEglEnumString(EGL_CORE_NATIVE_ENGINE);
/* EGL_NV_coverage_sample */
InsertEglEnumString(EGL_COVERAGE_BUFFERS_NV);
InsertEglEnumString(EGL_COVERAGE_SAMPLES_NV);
/* EGL_NV_depth_nonlinear */
InsertEglEnumString(EGL_DEPTH_ENCODING_NV);
InsertEglEnumString(EGL_DEPTH_ENCODING_NONLINEAR_NV);
/* GLES 1 enums */
InsertEnumString(GL_ADD); // 0x0104
InsertEnumString(GL_NEVER); // 0x0200
InsertEnumString(GL_LESS); // 0x0201
InsertEnumString(GL_EQUAL); // 0x0202
InsertEnumString(GL_LEQUAL); // 0x0203
InsertEnumString(GL_GREATER); // 0x0204
InsertEnumString(GL_NOTEQUAL); // 0x0205
InsertEnumString(GL_GEQUAL); // 0x0206
InsertEnumString(GL_ALWAYS); // 0x0207
InsertEnumString(GL_SRC_COLOR); // 0x0300
InsertEnumString(GL_ONE_MINUS_SRC_COLOR); // 0x0301
InsertEnumString(GL_SRC_ALPHA); // 0x0302
InsertEnumString(GL_ONE_MINUS_SRC_ALPHA); // 0x0303
InsertEnumString(GL_DST_ALPHA); // 0x0304
InsertEnumString(GL_ONE_MINUS_DST_ALPHA); // 0x0305
InsertEnumString(GL_DST_COLOR); // 0x0306
InsertEnumString(GL_ONE_MINUS_DST_COLOR); // 0x0307
InsertEnumString(GL_SRC_ALPHA_SATURATE); // 0x0308
InsertEnumString(GL_FRONT); // 0x0404
InsertEnumString(GL_BACK); // 0x0405
InsertEnumString(GL_FRONT_AND_BACK); // 0x0408
InsertEnumString(GL_INVALID_ENUM); // 0x0500
InsertEnumString(GL_INVALID_VALUE); // 0x0501
InsertEnumString(GL_INVALID_OPERATION); // 0x0502
InsertEnumString(GL_STACK_OVERFLOW); // 0x0503
InsertEnumString(GL_STACK_UNDERFLOW); // 0x0504
InsertEnumString(GL_OUT_OF_MEMORY); // 0x0505
InsertEnumString(GL_EXP); // 0x0800
InsertEnumString(GL_EXP2); // 0x0801
InsertEnumString(GL_CW); // 0x0900
InsertEnumString(GL_CCW); // 0x0901
InsertEnumString(GL_CURRENT_COLOR); // 0x0B00
InsertEnumString(GL_CURRENT_NORMAL); // 0x0B02
InsertEnumString(GL_CURRENT_TEXTURE_COORDS); // 0x0B03
InsertEnumString(GL_POINT_SMOOTH); // 0x0B10
InsertEnumString(GL_POINT_SIZE); // 0x0B11
InsertEnumString(GL_SMOOTH_POINT_SIZE_RANGE); // 0x0B12
InsertEnumString(GL_LINE_SMOOTH); // 0x0B20
InsertEnumString(GL_LINE_WIDTH); // 0x0B21
InsertEnumString(GL_SMOOTH_LINE_WIDTH_RANGE); // 0x0B22
InsertEnumString(GL_CULL_FACE); // 0x0B44
InsertEnumString(GL_CULL_FACE_MODE); // 0x0B45
InsertEnumString(GL_FRONT_FACE); // 0x0B46
InsertEnumString(GL_LIGHTING); // 0x0B50
InsertEnumString(GL_LIGHT_MODEL_TWO_SIDE); // 0x0B52
InsertEnumString(GL_LIGHT_MODEL_AMBIENT); // 0x0B53
InsertEnumString(GL_SHADE_MODEL); // 0x0B54
InsertEnumString(GL_COLOR_MATERIAL); // 0x0B57
InsertEnumString(GL_FOG); // 0x0B60
InsertEnumString(GL_FOG_DENSITY); // 0x0B62
InsertEnumString(GL_FOG_START); // 0x0B63
InsertEnumString(GL_FOG_END); // 0x0B64
InsertEnumString(GL_FOG_MODE); // 0x0B65
InsertEnumString(GL_FOG_COLOR); // 0x0B66
InsertEnumString(GL_DEPTH_RANGE); // 0x0B70
InsertEnumString(GL_DEPTH_TEST); // 0x0B71
InsertEnumString(GL_DEPTH_WRITEMASK); // 0x0B72
InsertEnumString(GL_DEPTH_CLEAR_VALUE); // 0x0B73
InsertEnumString(GL_DEPTH_FUNC); // 0x0B74
InsertEnumString(GL_STENCIL_TEST); // 0x0B90
InsertEnumString(GL_STENCIL_CLEAR_VALUE); // 0x0B91
InsertEnumString(GL_STENCIL_FUNC); // 0x0B92
InsertEnumString(GL_STENCIL_VALUE_MASK); // 0x0B93
InsertEnumString(GL_STENCIL_FAIL); // 0x0B94
InsertEnumString(GL_STENCIL_PASS_DEPTH_FAIL); // 0x0B95
InsertEnumString(GL_STENCIL_PASS_DEPTH_PASS); // 0x0B96
InsertEnumString(GL_STENCIL_REF); // 0x0B97
InsertEnumString(GL_STENCIL_WRITEMASK); // 0x0B98
InsertEnumString(GL_MATRIX_MODE); // 0x0BA0
InsertEnumString(GL_NORMALIZE); // 0x0BA1
InsertEnumString(GL_VIEWPORT); // 0x0BA2
InsertEnumString(GL_MODELVIEW_STACK_DEPTH); // 0x0BA3
InsertEnumString(GL_PROJECTION_STACK_DEPTH); // 0x0BA4
InsertEnumString(GL_TEXTURE_STACK_DEPTH); // 0x0BA5
InsertEnumString(GL_MODELVIEW_MATRIX); // 0x0BA6
InsertEnumString(GL_PROJECTION_MATRIX); // 0x0BA7
InsertEnumString(GL_TEXTURE_MATRIX); // 0x0BA8
InsertEnumString(GL_ALPHA_TEST); // 0x0BC0
InsertEnumString(GL_ALPHA_TEST_FUNC); // 0x0BC1
InsertEnumString(GL_ALPHA_TEST_REF); // 0x0BC2
InsertEnumString(GL_DITHER); // 0x0BD0
InsertEnumString(GL_BLEND_DST); // 0x0BE0
InsertEnumString(GL_BLEND_SRC); // 0x0BE1
InsertEnumString(GL_BLEND); // 0x0BE2
InsertEnumString(GL_LOGIC_OP_MODE); // 0x0BF0
InsertEnumString(GL_COLOR_LOGIC_OP); // 0x0BF2
InsertEnumString(GL_SCISSOR_BOX); // 0x0C10
InsertEnumString(GL_SCISSOR_TEST); // 0x0C11
InsertEnumString(GL_COLOR_CLEAR_VALUE); // 0x0C22
InsertEnumString(GL_COLOR_WRITEMASK); // 0x0C23
InsertEnumString(GL_PERSPECTIVE_CORRECTION_HINT); // 0x0C50
InsertEnumString(GL_POINT_SMOOTH_HINT); // 0x0C51
InsertEnumString(GL_LINE_SMOOTH_HINT); // 0x0C52
InsertEnumString(GL_FOG_HINT); // 0x0C54
InsertEnumString(GL_UNPACK_ALIGNMENT); // 0x0CF5
InsertEnumString(GL_PACK_ALIGNMENT); // 0x0D05
InsertEnumString(GL_ALPHA_SCALE); // 0x0D1C
InsertEnumString(GL_MAX_LIGHTS); // 0x0D31
InsertEnumString(GL_MAX_CLIP_PLANES); // 0x0D32
InsertEnumString(GL_MAX_TEXTURE_SIZE); // 0x0D33
InsertEnumString(GL_MAX_MODELVIEW_STACK_DEPTH); // 0x0D36
InsertEnumString(GL_MAX_PROJECTION_STACK_DEPTH); // 0x0D38
InsertEnumString(GL_MAX_TEXTURE_STACK_DEPTH); // 0x0D39
InsertEnumString(GL_MAX_VIEWPORT_DIMS); // 0x0D3A
InsertEnumString(GL_SUBPIXEL_BITS); // 0x0D50
InsertEnumString(GL_RED_BITS); // 0x0D52
InsertEnumString(GL_GREEN_BITS); // 0x0D53
InsertEnumString(GL_BLUE_BITS); // 0x0D54
InsertEnumString(GL_ALPHA_BITS); // 0x0D55
InsertEnumString(GL_DEPTH_BITS); // 0x0D56
InsertEnumString(GL_STENCIL_BITS); // 0x0D57
InsertEnumString(GL_TEXTURE_2D); // 0x0DE1
InsertEnumString(GL_DONT_CARE); // 0x1100
InsertEnumString(GL_FASTEST); // 0x1101
InsertEnumString(GL_NICEST); // 0x1102
InsertEnumString(GL_AMBIENT); // 0x1200
InsertEnumString(GL_DIFFUSE); // 0x1201
InsertEnumString(GL_SPECULAR); // 0x1202
InsertEnumString(GL_POSITION); // 0x1203
InsertEnumString(GL_SPOT_DIRECTION); // 0x1204
InsertEnumString(GL_SPOT_EXPONENT); // 0x1205
InsertEnumString(GL_SPOT_CUTOFF); // 0x1206
InsertEnumString(GL_CONSTANT_ATTENUATION); // 0x1207
InsertEnumString(GL_LINEAR_ATTENUATION); // 0x1208
InsertEnumString(GL_QUADRATIC_ATTENUATION); // 0x1209
InsertEnumString(GL_BYTE); // 0x1400
InsertEnumString(GL_UNSIGNED_BYTE); // 0x1401
InsertEnumString(GL_SHORT); // 0x1402
InsertEnumString(GL_UNSIGNED_SHORT); // 0x1403
InsertEnumString(GL_INT); // 0x1404
InsertEnumString(GL_UNSIGNED_INT); // 0x1405
InsertEnumString(GL_FLOAT); // 0x1406
InsertEnumString(GL_FIXED); // 0x140C
InsertEnumString(GL_CLEAR); // 0x1500
InsertEnumString(GL_AND); // 0x1501
InsertEnumString(GL_AND_REVERSE); // 0x1502
InsertEnumString(GL_COPY); // 0x1503
InsertEnumString(GL_AND_INVERTED); // 0x1504
InsertEnumString(GL_NOOP); // 0x1505
InsertEnumString(GL_XOR); // 0x1506
InsertEnumString(GL_OR); // 0x1507
InsertEnumString(GL_NOR); // 0x1508
InsertEnumString(GL_EQUIV); // 0x1509
InsertEnumString(GL_INVERT); // 0x150A
InsertEnumString(GL_OR_REVERSE); // 0x150B
InsertEnumString(GL_COPY_INVERTED); // 0x150C
InsertEnumString(GL_OR_INVERTED); // 0x150D
InsertEnumString(GL_NAND); // 0x150E
InsertEnumString(GL_SET); // 0x150F
InsertEnumString(GL_EMISSION); // 0x1600
InsertEnumString(GL_SHININESS); // 0x1601
InsertEnumString(GL_AMBIENT_AND_DIFFUSE); // 0x1602
InsertEnumString(GL_MODELVIEW); // 0x1700
InsertEnumString(GL_PROJECTION); // 0x1701
InsertEnumString(GL_TEXTURE); // 0x1702
InsertEnumString(GL_ALPHA); // 0x1906
InsertEnumString(GL_RGB); // 0x1907
InsertEnumString(GL_RGBA); // 0x1908
InsertEnumString(GL_LUMINANCE); // 0x1909
InsertEnumString(GL_LUMINANCE_ALPHA); // 0x190A
InsertEnumString(GL_FLAT); // 0x1D00
InsertEnumString(GL_SMOOTH); // 0x1D01
InsertEnumString(GL_KEEP); // 0x1E00
InsertEnumString(GL_REPLACE); // 0x1E01
InsertEnumString(GL_INCR); // 0x1E02
InsertEnumString(GL_DECR); // 0x1E03
InsertEnumString(GL_VENDOR); // 0x1F00
InsertEnumString(GL_RENDERER); // 0x1F01
InsertEnumString(GL_VERSION); // 0x1F02
InsertEnumString(GL_EXTENSIONS); // 0x1F03
InsertEnumString(GL_MODULATE); // 0x2100
InsertEnumString(GL_DECAL); // 0x2101
InsertEnumString(GL_TEXTURE_ENV_MODE); // 0x2200
InsertEnumString(GL_TEXTURE_ENV_COLOR); // 0x2201
InsertEnumString(GL_TEXTURE_ENV); // 0x2300
InsertEnumString(GL_NEAREST); // 0x2600
InsertEnumString(GL_LINEAR); // 0x2601
InsertEnumString(GL_NEAREST_MIPMAP_NEAREST); // 0x2700
InsertEnumString(GL_LINEAR_MIPMAP_NEAREST); // 0x2701
InsertEnumString(GL_NEAREST_MIPMAP_LINEAR); // 0x2702
InsertEnumString(GL_LINEAR_MIPMAP_LINEAR); // 0x2703
InsertEnumString(GL_TEXTURE_MAG_FILTER); // 0x2800
InsertEnumString(GL_TEXTURE_MIN_FILTER); // 0x2801
InsertEnumString(GL_TEXTURE_WRAP_S); // 0x2802
InsertEnumString(GL_TEXTURE_WRAP_T); // 0x2803
InsertEnumString(GL_REPEAT); // 0x2901
InsertEnumString(GL_POLYGON_OFFSET_UNITS); // 0x2A00
InsertEnumString(GL_CLIP_PLANE0); // 0x3000
InsertEnumString(GL_CLIP_PLANE1); // 0x3001
InsertEnumString(GL_CLIP_PLANE2); // 0x3002
InsertEnumString(GL_CLIP_PLANE3); // 0x3003
InsertEnumString(GL_CLIP_PLANE4); // 0x3004
InsertEnumString(GL_CLIP_PLANE5); // 0x3005
InsertEnumString(GL_LIGHT0); // 0x4000
InsertEnumString(GL_LIGHT1); // 0x4001
InsertEnumString(GL_LIGHT2); // 0x4002
InsertEnumString(GL_LIGHT3); // 0x4003
InsertEnumString(GL_LIGHT4); // 0x4004
InsertEnumString(GL_LIGHT5); // 0x4005
InsertEnumString(GL_LIGHT6); // 0x4006
InsertEnumString(GL_LIGHT7); // 0x4007
InsertEnumString(GL_UNSIGNED_SHORT_4_4_4_4); // 0x8033
InsertEnumString(GL_UNSIGNED_SHORT_5_5_5_1); // 0x8034
InsertEnumString(GL_POLYGON_OFFSET_FILL); // 0x8037
InsertEnumString(GL_POLYGON_OFFSET_FACTOR); // 0x8038
InsertEnumString(GL_RESCALE_NORMAL); // 0x803A
InsertEnumString(GL_TEXTURE_BINDING_2D); // 0x8069
InsertEnumString(GL_VERTEX_ARRAY); // 0x8074
InsertEnumString(GL_NORMAL_ARRAY); // 0x8075
InsertEnumString(GL_COLOR_ARRAY); // 0x8076
InsertEnumString(GL_TEXTURE_COORD_ARRAY); // 0x8078
InsertEnumString(GL_VERTEX_ARRAY_SIZE); // 0x807A
InsertEnumString(GL_VERTEX_ARRAY_TYPE); // 0x807B
InsertEnumString(GL_VERTEX_ARRAY_STRIDE); // 0x807C
InsertEnumString(GL_NORMAL_ARRAY_TYPE); // 0x807E
InsertEnumString(GL_NORMAL_ARRAY_STRIDE); // 0x807F
InsertEnumString(GL_COLOR_ARRAY_SIZE); // 0x8081
InsertEnumString(GL_COLOR_ARRAY_TYPE); // 0x8082
InsertEnumString(GL_COLOR_ARRAY_STRIDE); // 0x8083
InsertEnumString(GL_TEXTURE_COORD_ARRAY_SIZE); // 0x8088
InsertEnumString(GL_TEXTURE_COORD_ARRAY_TYPE); // 0x8089
InsertEnumString(GL_TEXTURE_COORD_ARRAY_STRIDE); // 0x808A
InsertEnumString(GL_VERTEX_ARRAY_POINTER); // 0x808E
InsertEnumString(GL_NORMAL_ARRAY_POINTER); // 0x808F
InsertEnumString(GL_COLOR_ARRAY_POINTER); // 0x8090
InsertEnumString(GL_TEXTURE_COORD_ARRAY_POINTER); // 0x8092
InsertEnumString(GL_MULTISAMPLE); // 0x809D
InsertEnumString(GL_SAMPLE_ALPHA_TO_COVERAGE); // 0x809E
InsertEnumString(GL_SAMPLE_ALPHA_TO_ONE); // 0x809F
InsertEnumString(GL_SAMPLE_COVERAGE); // 0x80A0
InsertEnumString(GL_SAMPLE_BUFFERS); // 0x80A8
InsertEnumString(GL_SAMPLES); // 0x80A9
InsertEnumString(GL_SAMPLE_COVERAGE_VALUE); // 0x80AA
InsertEnumString(GL_SAMPLE_COVERAGE_INVERT); // 0x80AB
InsertEnumString(GL_POINT_SIZE_MIN); // 0x8126
InsertEnumString(GL_POINT_SIZE_MAX); // 0x8127
InsertEnumString(GL_POINT_FADE_THRESHOLD_SIZE); // 0x8128
InsertEnumString(GL_POINT_DISTANCE_ATTENUATION); // 0x8129
InsertEnumString(GL_CLAMP_TO_EDGE); // 0x812F
InsertEnumString(GL_GENERATE_MIPMAP); // 0x8191
InsertEnumString(GL_GENERATE_MIPMAP_HINT); // 0x8192
InsertEnumString(GL_UNSIGNED_SHORT_5_6_5); // 0x8363
InsertEnumString(GL_ALIASED_POINT_SIZE_RANGE); // 0x846D
InsertEnumString(GL_ALIASED_LINE_WIDTH_RANGE); // 0x846E
InsertEnumString(GL_TEXTURE0); // 0x84C0
InsertEnumString(GL_TEXTURE1); // 0x84C1
InsertEnumString(GL_TEXTURE2); // 0x84C2
InsertEnumString(GL_TEXTURE3); // 0x84C3
InsertEnumString(GL_TEXTURE4); // 0x84C4
InsertEnumString(GL_TEXTURE5); // 0x84C5
InsertEnumString(GL_TEXTURE6); // 0x84C6
InsertEnumString(GL_TEXTURE7); // 0x84C7
InsertEnumString(GL_TEXTURE8); // 0x84C8
InsertEnumString(GL_TEXTURE9); // 0x84C9
InsertEnumString(GL_TEXTURE10); // 0x84CA
InsertEnumString(GL_TEXTURE11); // 0x84CB
InsertEnumString(GL_TEXTURE12); // 0x84CC
InsertEnumString(GL_TEXTURE13); // 0x84CD
InsertEnumString(GL_TEXTURE14); // 0x84CE
InsertEnumString(GL_TEXTURE15); // 0x84CF
InsertEnumString(GL_TEXTURE16); // 0x84D0
InsertEnumString(GL_TEXTURE17); // 0x84D1
InsertEnumString(GL_TEXTURE18); // 0x84D2
InsertEnumString(GL_TEXTURE19); // 0x84D3
InsertEnumString(GL_TEXTURE20); // 0x84D4
InsertEnumString(GL_TEXTURE21); // 0x84D5
InsertEnumString(GL_TEXTURE22); // 0x84D6
InsertEnumString(GL_TEXTURE23); // 0x84D7
InsertEnumString(GL_TEXTURE24); // 0x84D8
InsertEnumString(GL_TEXTURE25); // 0x84D9
InsertEnumString(GL_TEXTURE26); // 0x84DA
InsertEnumString(GL_TEXTURE27); // 0x84DB
InsertEnumString(GL_TEXTURE28); // 0x84DC
InsertEnumString(GL_TEXTURE29); // 0x84DD
InsertEnumString(GL_TEXTURE30); // 0x84DE
InsertEnumString(GL_TEXTURE31); // 0x84DF
InsertEnumString(GL_ACTIVE_TEXTURE); // 0x84E0
InsertEnumString(GL_CLIENT_ACTIVE_TEXTURE); // 0x84E1
InsertEnumString(GL_MAX_TEXTURE_UNITS); // 0x84E2
InsertEnumString(GL_SUBTRACT); // 0x84E7
InsertEnumString(GL_COMBINE); // 0x8570
InsertEnumString(GL_COMBINE_RGB); // 0x8571
InsertEnumString(GL_COMBINE_ALPHA); // 0x8572
InsertEnumString(GL_RGB_SCALE); // 0x8573
InsertEnumString(GL_ADD_SIGNED); // 0x8574
InsertEnumString(GL_INTERPOLATE); // 0x8575
InsertEnumString(GL_CONSTANT); // 0x8576
InsertEnumString(GL_PRIMARY_COLOR); // 0x8577
InsertEnumString(GL_PREVIOUS); // 0x8578
InsertEnumString(GL_SRC0_RGB); // 0x8580
InsertEnumString(GL_SRC1_RGB); // 0x8581
InsertEnumString(GL_SRC2_RGB); // 0x8582
InsertEnumString(GL_SRC0_ALPHA); // 0x8588
InsertEnumString(GL_SRC1_ALPHA); // 0x8589
InsertEnumString(GL_SRC2_ALPHA); // 0x858A
InsertEnumString(GL_OPERAND0_RGB); // 0x8590
InsertEnumString(GL_OPERAND1_RGB); // 0x8591
InsertEnumString(GL_OPERAND2_RGB); // 0x8592
InsertEnumString(GL_OPERAND0_ALPHA); // 0x8598
InsertEnumString(GL_OPERAND1_ALPHA); // 0x8599
InsertEnumString(GL_OPERAND2_ALPHA); // 0x859A
InsertEnumString(GL_NUM_COMPRESSED_TEXTURE_FORMATS); // 0x86A2
InsertEnumString(GL_COMPRESSED_TEXTURE_FORMATS); // 0x86A3
InsertEnumString(GL_DOT3_RGB); // 0x86AE
InsertEnumString(GL_DOT3_RGBA); // 0x86AF
InsertEnumString(GL_BUFFER_SIZE); // 0x8764
InsertEnumString(GL_BUFFER_USAGE); // 0x8765
InsertEnumString(GL_POINT_SPRITE_OES); // 0x8861
InsertEnumString(GL_COORD_REPLACE_OES); // 0x8862
InsertEnumString(GL_ARRAY_BUFFER); // 0x8892
InsertEnumString(GL_ELEMENT_ARRAY_BUFFER); // 0x8893
InsertEnumString(GL_ARRAY_BUFFER_BINDING); // 0x8894
InsertEnumString(GL_ELEMENT_ARRAY_BUFFER_BINDING); // 0x8895
InsertEnumString(GL_VERTEX_ARRAY_BUFFER_BINDING); // 0x8896
InsertEnumString(GL_NORMAL_ARRAY_BUFFER_BINDING); // 0x8897
InsertEnumString(GL_COLOR_ARRAY_BUFFER_BINDING); // 0x8898
InsertEnumString(GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING); // 0x889A
InsertEnumString(GL_STATIC_DRAW); // 0x88E4
InsertEnumString(GL_DYNAMIC_DRAW); // 0x88E8
InsertEnumString(GL_POINT_SIZE_ARRAY_TYPE_OES); // 0x898A
InsertEnumString(GL_POINT_SIZE_ARRAY_STRIDE_OES); // 0x898B
InsertEnumString(GL_POINT_SIZE_ARRAY_POINTER_OES); // 0x898C
InsertEnumString(GL_PALETTE4_RGB8_OES); // 0x8B90
InsertEnumString(GL_PALETTE4_RGBA8_OES); // 0x8B91
InsertEnumString(GL_PALETTE4_R5_G6_B5_OES); // 0x8B92
InsertEnumString(GL_PALETTE4_RGBA4_OES); // 0x8B93
InsertEnumString(GL_PALETTE4_RGB5_A1_OES); // 0x8B94
InsertEnumString(GL_PALETTE8_RGB8_OES); // 0x8B95
InsertEnumString(GL_PALETTE8_RGBA8_OES); // 0x8B96
InsertEnumString(GL_PALETTE8_R5_G6_B5_OES); // 0x8B97
InsertEnumString(GL_PALETTE8_RGBA4_OES); // 0x8B98
InsertEnumString(GL_PALETTE8_RGB5_A1_OES); // 0x8B99
InsertEnumString(GL_POINT_SIZE_ARRAY_OES); // 0x8B9C
InsertEnumString(GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES); // 0x8B9F
/* GLES EXT enums */
InsertEnumString(GL_TEXTURE_GEN_MODE_OES); // 0x2500
InsertEnumString(GL_RGB10_EXT); // 0x8052
InsertEnumString(GL_BGRA_EXT); // 0x80E1
InsertEnumString(GL_DEPTH_COMPONENT32_OES); // 0x81A7
InsertEnumString(GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT); // 0x8365
InsertEnumString(GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT); // 0x8366
InsertEnumString(GL_COMPRESSED_RGB_S3TC_DXT1_EXT); // 0x83F0
InsertEnumString(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT); // 0x83F1
InsertEnumString(GL_ALL_COMPLETED_NV); // 0x84F2
InsertEnumString(GL_FENCE_STATUS_NV); // 0x84F3
InsertEnumString(GL_FENCE_CONDITION_NV); // 0x84F4
InsertEnumString(GL_TEXTURE_MAX_ANISOTROPY_EXT); // 0x84FE
InsertEnumString(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT); // 0x84FF
InsertEnumString(GL_TEXTURE_FILTER_CONTROL_EXT); // 0x8500
InsertEnumString(GL_TEXTURE_LOD_BIAS_EXT); // 0x8501
InsertEnumString(GL_NORMAL_MAP_OES); // 0x8511
InsertEnumString(GL_REFLECTION_MAP_OES); // 0x8512
InsertEnumString(GL_MAX_VERTEX_UNITS_OES); // 0x86A4
InsertEnumString(GL_WEIGHT_ARRAY_TYPE_OES); // 0x86A9
InsertEnumString(GL_WEIGHT_ARRAY_STRIDE_OES); // 0x86AA
InsertEnumString(GL_WEIGHT_ARRAY_SIZE_OES); // 0x86AB
InsertEnumString(GL_WEIGHT_ARRAY_POINTER_OES); // 0x86AC
InsertEnumString(GL_WEIGHT_ARRAY_OES); // 0x86AD
InsertEnumString(GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD); // 0x87EE
InsertEnumString(GL_3DC_X_AMD); // 0x87F9
InsertEnumString(GL_3DC_XY_AMD); // 0x87FA
InsertEnumString(GL_ALPHA32F_EXT); // 0x8816
InsertEnumString(GL_LUMINANCE32F_EXT); // 0x8818
InsertEnumString(GL_LUMINANCE_ALPHA32F_EXT); // 0x8819
InsertEnumString(GL_ALPHA16F_EXT); // 0x881C
InsertEnumString(GL_LUMINANCE16F_EXT); // 0x881E
InsertEnumString(GL_LUMINANCE_ALPHA16F_EXT); // 0x881F
InsertEnumString(GL_WRITEONLY_RENDERING_QCOM); // 0x8823
InsertEnumString(GL_MATRIX_PALETTE_OES); // 0x8840
InsertEnumString(GL_MAX_PALETTE_MATRICES_OES); // 0x8842
InsertEnumString(GL_CURRENT_PALETTE_MATRIX_OES); // 0x8843
InsertEnumString(GL_MATRIX_INDEX_ARRAY_OES); // 0x8844
InsertEnumString(GL_MATRIX_INDEX_ARRAY_SIZE_OES); // 0x8846
InsertEnumString(GL_MATRIX_INDEX_ARRAY_TYPE_OES); // 0x8847
InsertEnumString(GL_MATRIX_INDEX_ARRAY_STRIDE_OES); // 0x8848
InsertEnumString(GL_MATRIX_INDEX_ARRAY_POINTER_OES); // 0x8849
InsertEnumString(GL_WEIGHT_ARRAY_BUFFER_BINDING_OES); // 0x889E
InsertEnumString(GL_BUFFER_ACCESS_OES); // 0x88BB
InsertEnumString(GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES); // 0x898D
InsertEnumString(GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES); // 0x898E
InsertEnumString(GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES); // 0x898F
InsertEnumString(GL_SYNC_OBJECT_APPLE); // 0x8A53
InsertEnumString(GL_TEXTURE_CROP_RECT_OES); // 0x8B9D
InsertEnumString(GL_MATRIX_INDEX_ARRAY_BUFFER_BINDING_OES); // 0x8B9E
InsertEnumString(GL_TEXTURE_WIDTH_QCOM); // 0x8BD2
InsertEnumString(GL_TEXTURE_HEIGHT_QCOM); // 0x8BD3
InsertEnumString(GL_TEXTURE_DEPTH_QCOM); // 0x8BD4
InsertEnumString(GL_TEXTURE_INTERNAL_FORMAT_QCOM); // 0x8BD5
InsertEnumString(GL_TEXTURE_FORMAT_QCOM); // 0x8BD6
InsertEnumString(GL_TEXTURE_TYPE_QCOM); // 0x8BD7
InsertEnumString(GL_TEXTURE_IMAGE_VALID_QCOM); // 0x8BD8
InsertEnumString(GL_TEXTURE_NUM_LEVELS_QCOM); // 0x8BD9
InsertEnumString(GL_TEXTURE_TARGET_QCOM); // 0x8BDA
InsertEnumString(GL_TEXTURE_OBJECT_VALID_QCOM); // 0x8BDB
InsertEnumString(GL_STATE_RESTORE); // 0x8BDC
InsertEnumString(GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG); // 0x8C00
InsertEnumString(GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG); // 0x8C01
InsertEnumString(GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG); // 0x8C02
InsertEnumString(GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG); // 0x8C03
InsertEnumString(GL_MODULATE_COLOR_IMG); // 0x8C04
InsertEnumString(GL_RECIP_ADD_SIGNED_ALPHA_IMG); // 0x8C05
InsertEnumString(GL_TEXTURE_ALPHA_MODULATE_IMG); // 0x8C06
InsertEnumString(GL_FACTOR_ALPHA_MODULATE_IMG); // 0x8C07
InsertEnumString(GL_FRAGMENT_ALPHA_MODULATE_IMG); // 0x8C08
InsertEnumString(GL_ADD_BLEND_IMG); // 0x8C09
InsertEnumString(GL_SRGB_ALPHA_EXT); // 0x8C42
InsertEnumString(GL_ATC_RGB_AMD); // 0x8C92
InsertEnumString(GL_ATC_RGBA_EXPLICIT_ALPHA_AMD); // 0x8C93
InsertEnumString(GL_FRAMEBUFFER_INCOMPLETE_FORMATS_OES); // 0x8CDA
InsertEnumString(GL_STENCIL_INDEX1_OES); // 0x8D46
InsertEnumString(GL_STENCIL_INDEX4_OES); // 0x8D47
InsertEnumString(GL_TEXTURE_GEN_STR_OES); // 0x8D60
InsertEnumString(GL_ETC1_RGB8_OES); // 0x8D64
InsertEnumString(GL_TEXTURE_EXTERNAL_OES); // 0x8D65
InsertEnumString(GL_TEXTURE_BINDING_EXTERNAL_OES); // 0x8D67
InsertEnumString(GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES); // 0x8D68
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT); // 0x8D6C
InsertEnumString(GL_PERFMON_GLOBAL_MODE_QCOM); // 0x8FA0
InsertEnumString(GL_CONTEXT_ROBUST_ACCESS_EXT); // 0x90F3
InsertEnumString(GL_RENDERBUFFER_SAMPLES_IMG); // 0x9133
InsertEnumString(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG); // 0x9134
InsertEnumString(GL_MAX_SAMPLES_IMG); // 0x9135
InsertEnumString(GL_TEXTURE_SAMPLES_IMG); // 0x9136
InsertEnumString(GL_BGRA8_EXT); // 0x93A1
/* GLES 2 enums */
InsertEnumString(GL_INVALID_FRAMEBUFFER_OPERATION); // 0x0506
InsertEnumString(GL_DEPTH_COMPONENT); // 0x1902
InsertEnumString(GL_CONSTANT_COLOR); // 0x8001
InsertEnumString(GL_ONE_MINUS_CONSTANT_COLOR); // 0x8002
InsertEnumString(GL_CONSTANT_ALPHA); // 0x8003
InsertEnumString(GL_ONE_MINUS_CONSTANT_ALPHA); // 0x8004
InsertEnumString(GL_BLEND_COLOR); // 0x8005
InsertEnumString(GL_FUNC_ADD); // 0x8006
InsertEnumString(GL_BLEND_EQUATION); // 0x8009
InsertEnumString(GL_FUNC_SUBTRACT); // 0x800A
InsertEnumString(GL_FUNC_REVERSE_SUBTRACT); // 0x800B
InsertEnumString(GL_RGBA4); // 0x8056
InsertEnumString(GL_RGB5_A1); // 0x8057
InsertEnumString(GL_BLEND_DST_RGB); // 0x80C8
InsertEnumString(GL_BLEND_SRC_RGB); // 0x80C9
InsertEnumString(GL_BLEND_DST_ALPHA); // 0x80CA
InsertEnumString(GL_BLEND_SRC_ALPHA); // 0x80CB
InsertEnumString(GL_DEPTH_COMPONENT16); // 0x81A5
InsertEnumString(GL_MIRRORED_REPEAT); // 0x8370
InsertEnumString(GL_MAX_RENDERBUFFER_SIZE); // 0x84E8
InsertEnumString(GL_INCR_WRAP); // 0x8507
InsertEnumString(GL_DECR_WRAP); // 0x8508
InsertEnumString(GL_TEXTURE_CUBE_MAP); // 0x8513
InsertEnumString(GL_TEXTURE_BINDING_CUBE_MAP); // 0x8514
InsertEnumString(GL_TEXTURE_CUBE_MAP_POSITIVE_X); // 0x8515
InsertEnumString(GL_TEXTURE_CUBE_MAP_NEGATIVE_X); // 0x8516
InsertEnumString(GL_TEXTURE_CUBE_MAP_POSITIVE_Y); // 0x8517
InsertEnumString(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y); // 0x8518
InsertEnumString(GL_TEXTURE_CUBE_MAP_POSITIVE_Z); // 0x8519
InsertEnumString(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z); // 0x851A
InsertEnumString(GL_MAX_CUBE_MAP_TEXTURE_SIZE); // 0x851C
InsertEnumString(GL_VERTEX_ATTRIB_ARRAY_ENABLED); // 0x8622
InsertEnumString(GL_VERTEX_ATTRIB_ARRAY_SIZE); // 0x8623
InsertEnumString(GL_VERTEX_ATTRIB_ARRAY_STRIDE); // 0x8624
InsertEnumString(GL_VERTEX_ATTRIB_ARRAY_TYPE); // 0x8625
InsertEnumString(GL_CURRENT_VERTEX_ATTRIB); // 0x8626
InsertEnumString(GL_VERTEX_ATTRIB_ARRAY_POINTER); // 0x8645
InsertEnumString(GL_STENCIL_BACK_FUNC); // 0x8800
InsertEnumString(GL_STENCIL_BACK_FAIL); // 0x8801
InsertEnumString(GL_STENCIL_BACK_PASS_DEPTH_FAIL); // 0x8802
InsertEnumString(GL_STENCIL_BACK_PASS_DEPTH_PASS); // 0x8803
InsertEnumString(GL_BLEND_EQUATION_ALPHA); // 0x883D
InsertEnumString(GL_MAX_VERTEX_ATTRIBS); // 0x8869
InsertEnumString(GL_VERTEX_ATTRIB_ARRAY_NORMALIZED); // 0x886A
InsertEnumString(GL_MAX_TEXTURE_IMAGE_UNITS); // 0x8872
InsertEnumString(GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING); // 0x889F
InsertEnumString(GL_STREAM_DRAW); // 0x88E0
InsertEnumString(GL_FRAGMENT_SHADER); // 0x8B30
InsertEnumString(GL_VERTEX_SHADER); // 0x8B31
InsertEnumString(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS); // 0x8B4C
InsertEnumString(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS); // 0x8B4D
InsertEnumString(GL_SHADER_TYPE); // 0x8B4F
InsertEnumString(GL_FLOAT_VEC2); // 0x8B50
InsertEnumString(GL_FLOAT_VEC3); // 0x8B51
InsertEnumString(GL_FLOAT_VEC4); // 0x8B52
InsertEnumString(GL_INT_VEC2); // 0x8B53
InsertEnumString(GL_INT_VEC3); // 0x8B54
InsertEnumString(GL_INT_VEC4); // 0x8B55
InsertEnumString(GL_BOOL); // 0x8B56
InsertEnumString(GL_BOOL_VEC2); // 0x8B57
InsertEnumString(GL_BOOL_VEC3); // 0x8B58
InsertEnumString(GL_BOOL_VEC4); // 0x8B59
InsertEnumString(GL_FLOAT_MAT2); // 0x8B5A
InsertEnumString(GL_FLOAT_MAT3); // 0x8B5B
InsertEnumString(GL_FLOAT_MAT4); // 0x8B5C
InsertEnumString(GL_SAMPLER_2D); // 0x8B5E
InsertEnumString(GL_SAMPLER_CUBE); // 0x8B60
InsertEnumString(GL_DELETE_STATUS); // 0x8B80
InsertEnumString(GL_COMPILE_STATUS); // 0x8B81
InsertEnumString(GL_LINK_STATUS); // 0x8B82
InsertEnumString(GL_VALIDATE_STATUS); // 0x8B83
InsertEnumString(GL_INFO_LOG_LENGTH); // 0x8B84
InsertEnumString(GL_ATTACHED_SHADERS); // 0x8B85
InsertEnumString(GL_ACTIVE_UNIFORMS); // 0x8B86
InsertEnumString(GL_ACTIVE_UNIFORM_MAX_LENGTH); // 0x8B87
InsertEnumString(GL_SHADER_SOURCE_LENGTH); // 0x8B88
InsertEnumString(GL_ACTIVE_ATTRIBUTES); // 0x8B89
InsertEnumString(GL_ACTIVE_ATTRIBUTE_MAX_LENGTH); // 0x8B8A
InsertEnumString(GL_SHADING_LANGUAGE_VERSION); // 0x8B8C
InsertEnumString(GL_CURRENT_PROGRAM); // 0x8B8D
InsertEnumString(GL_IMPLEMENTATION_COLOR_READ_TYPE); // 0x8B9A
InsertEnumString(GL_IMPLEMENTATION_COLOR_READ_FORMAT); // 0x8B9B
InsertEnumString(GL_STENCIL_BACK_REF); // 0x8CA3
InsertEnumString(GL_STENCIL_BACK_VALUE_MASK); // 0x8CA4
InsertEnumString(GL_STENCIL_BACK_WRITEMASK); // 0x8CA5
InsertEnumString(GL_FRAMEBUFFER_BINDING); // 0x8CA6
InsertEnumString(GL_RENDERBUFFER_BINDING); // 0x8CA7
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE); // 0x8CD0
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME); // 0x8CD1
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL); // 0x8CD2
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE); // 0x8CD3
InsertEnumString(GL_FRAMEBUFFER_COMPLETE); // 0x8CD5
InsertEnumString(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT); // 0x8CD6
InsertEnumString(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT); // 0x8CD7
InsertEnumString(GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS); // 0x8CD9
InsertEnumString(GL_FRAMEBUFFER_UNSUPPORTED); // 0x8CDD
InsertEnumString(GL_COLOR_ATTACHMENT0); // 0x8CE0
InsertEnumString(GL_DEPTH_ATTACHMENT); // 0x8D00
InsertEnumString(GL_STENCIL_ATTACHMENT); // 0x8D20
InsertEnumString(GL_FRAMEBUFFER); // 0x8D40
InsertEnumString(GL_RENDERBUFFER); // 0x8D41
InsertEnumString(GL_RENDERBUFFER_WIDTH); // 0x8D42
InsertEnumString(GL_RENDERBUFFER_HEIGHT); // 0x8D43
InsertEnumString(GL_RENDERBUFFER_INTERNAL_FORMAT); // 0x8D44
InsertEnumString(GL_STENCIL_INDEX8); // 0x8D48
InsertEnumString(GL_RENDERBUFFER_RED_SIZE); // 0x8D50
InsertEnumString(GL_RENDERBUFFER_GREEN_SIZE); // 0x8D51
InsertEnumString(GL_RENDERBUFFER_BLUE_SIZE); // 0x8D52
InsertEnumString(GL_RENDERBUFFER_ALPHA_SIZE); // 0x8D53
InsertEnumString(GL_RENDERBUFFER_DEPTH_SIZE); // 0x8D54
InsertEnumString(GL_RENDERBUFFER_STENCIL_SIZE); // 0x8D55
InsertEnumString(GL_RGB565); // 0x8D62
InsertEnumString(GL_LOW_FLOAT); // 0x8DF0
InsertEnumString(GL_MEDIUM_FLOAT); // 0x8DF1
InsertEnumString(GL_HIGH_FLOAT); // 0x8DF2
InsertEnumString(GL_LOW_INT); // 0x8DF3
InsertEnumString(GL_MEDIUM_INT); // 0x8DF4
InsertEnumString(GL_HIGH_INT); // 0x8DF5
InsertEnumString(GL_SHADER_BINARY_FORMATS); // 0x8DF8
InsertEnumString(GL_NUM_SHADER_BINARY_FORMATS); // 0x8DF9
InsertEnumString(GL_SHADER_COMPILER); // 0x8DFA
InsertEnumString(GL_MAX_VERTEX_UNIFORM_VECTORS); // 0x8DFB
InsertEnumString(GL_MAX_VARYING_VECTORS); // 0x8DFC
InsertEnumString(GL_MAX_FRAGMENT_UNIFORM_VECTORS); // 0x8DFD
/* GLES 2 EXT enums */
InsertEnumString(GL_POLYGON_MODE_NV); // 0x0B40
InsertEnumString(GL_DRAW_BUFFER_EXT); // 0x0C01
InsertEnumString(GL_POINT_NV); // 0x1B00
InsertEnumString(GL_LINE_NV); // 0x1B01
InsertEnumString(GL_FILL_NV); // 0x1B02
InsertEnumString(GL_POLYGON_OFFSET_POINT_NV); // 0x2A01
InsertEnumString(GL_POLYGON_OFFSET_LINE_NV); // 0x2A02
InsertEnumString(GL_CLIP_DISTANCE6_APPLE); // 0x3006
InsertEnumString(GL_CLIP_DISTANCE7_APPLE); // 0x3007
InsertEnumString(GL_MIN); // 0x8007
InsertEnumString(GL_MAX); // 0x8008
//InsertEnumString(GL_ALPHA8_OES); // 0x803C
//InsertEnumString(GL_LUMINANCE8_OES); // 0x8040
//InsertEnumString(GL_LUMINANCE4_ALPHA4_OES); // 0x8043
//InsertEnumString(GL_LUMINANCE8_ALPHA8_OES); // 0x8045
InsertEnumString(GL_RGB16_EXT); // 0x8054
InsertEnumString(GL_RGBA16_EXT); // 0x805B
InsertEnumString(GL_TEXTURE_3D); // 0x806F
InsertEnumString(GL_BUFFER_IMMUTABLE_STORAGE_EXT); // 0x821F
InsertEnumString(GL_BUFFER_STORAGE_FLAGS_EXT); // 0x8220
InsertEnumString(GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED); // 0x8221
InsertEnumString(GL_R16_EXT); // 0x822A
InsertEnumString(GL_RG16_EXT); // 0x822C
InsertEnumString(GL_MAX_VIEWPORTS_NV); // 0x825B
InsertEnumString(GL_VIEWPORT_SUBPIXEL_BITS_NV); // 0x825C
InsertEnumString(GL_VIEWPORT_BOUNDS_RANGE_NV); // 0x825D
InsertEnumString(GL_VIEWPORT_INDEX_PROVOKING_VERTEX_NV); // 0x825F
InsertEnumString(GL_TEXTURE_VIEW_MIN_LEVEL_OES); // 0x82DB
InsertEnumString(GL_TEXTURE_VIEW_NUM_LEVELS_OES); // 0x82DC
InsertEnumString(GL_TEXTURE_VIEW_MIN_LAYER_OES); // 0x82DD
InsertEnumString(GL_TEXTURE_VIEW_NUM_LAYERS_OES); // 0x82DE
InsertEnumString(GL_TEXTURE_IMMUTABLE_LEVELS); // 0x82DF
InsertEnumString(GL_SAMPLER); // 0x82E6
InsertEnumString(GL_CONTEXT_RELEASE_BEHAVIOR_KHR); // 0x82FB
InsertEnumString(GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR); // 0x82FC
InsertEnumString(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT); // 0x83F2
InsertEnumString(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT); // 0x83F3
InsertEnumString(GL_PERFQUERY_DONOT_FLUSH_INTEL); // 0x83F9
InsertEnumString(GL_PERFQUERY_FLUSH_INTEL); // 0x83FA
InsertEnumString(GL_PERFQUERY_WAIT_INTEL); // 0x83FB
InsertEnumString(GL_PATH_TRANSPOSE_MODELVIEW_MATRIX_NV); // 0x84E3
InsertEnumString(GL_PATH_TRANSPOSE_PROJECTION_MATRIX_NV); // 0x84E4
InsertEnumString(GL_UNSIGNED_SHORT_8_8_APPLE); // 0x85BA
InsertEnumString(GL_UNSIGNED_SHORT_8_8_REV_APPLE); // 0x85BB
InsertEnumString(GL_Z400_BINARY_AMD); // 0x8740
InsertEnumString(GL_QUERY_COUNTER_BITS_EXT); // 0x8864
InsertEnumString(GL_TIME_ELAPSED_EXT); // 0x88BF
InsertEnumString(GL_ETC1_SRGB8_NV); // 0x88EE
InsertEnumString(GL_RGB_422_APPLE); // 0x8A1F
InsertEnumString(GL_TEXTURE_SRGB_DECODE_EXT); // 0x8A48
InsertEnumString(GL_DECODE_EXT); // 0x8A49
InsertEnumString(GL_SKIP_DECODE_EXT); // 0x8A4A
InsertEnumString(GL_PROGRAM_PIPELINE_OBJECT_EXT); // 0x8A4F
InsertEnumString(GL_RGB_RAW_422_APPLE); // 0x8A51
InsertEnumString(GL_FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT); // 0x8A52
InsertEnumString(GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT); // 0x8A54
InsertEnumString(GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT); // 0x8A55
InsertEnumString(GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT); // 0x8A56
InsertEnumString(GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT); // 0x8A57
InsertEnumString(GL_PROGRAM_OBJECT_EXT); // 0x8B40
InsertEnumString(GL_SHADER_OBJECT_EXT); // 0x8B48
InsertEnumString(GL_COUNTER_TYPE_AMD); // 0x8BC0
InsertEnumString(GL_COUNTER_RANGE_AMD); // 0x8BC1
InsertEnumString(GL_UNSIGNED_INT64_AMD); // 0x8BC2
InsertEnumString(GL_PERCENTAGE_AMD); // 0x8BC3
InsertEnumString(GL_PERFMON_RESULT_AVAILABLE_AMD); // 0x8BC4
InsertEnumString(GL_PERFMON_RESULT_SIZE_AMD); // 0x8BC5
InsertEnumString(GL_PERFMON_RESULT_AMD); // 0x8BC6
InsertEnumString(GL_SAMPLER_EXTERNAL_2D_Y2Y_EXT); // 0x8BE7
InsertEnumString(GL_SGX_BINARY_IMG); // 0x8C0A
InsertEnumString(GL_TEXTURE_2D_ARRAY); // 0x8C1A
InsertEnumString(GL_SLUMINANCE_ALPHA_NV); // 0x8C44
InsertEnumString(GL_SLUMINANCE8_ALPHA8_NV); // 0x8C45
InsertEnumString(GL_SLUMINANCE_NV); // 0x8C46
InsertEnumString(GL_SLUMINANCE8_NV); // 0x8C47
InsertEnumString(GL_COMPRESSED_SRGB_S3TC_DXT1_NV); // 0x8C4C
InsertEnumString(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV); // 0x8C4D
InsertEnumString(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV); // 0x8C4E
InsertEnumString(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV); // 0x8C4F
InsertEnumString(GL_HALF_FLOAT_OES); // 0x8D61
//InsertEnumString(GL_SAMPLER_EXTERNAL_OES); // 0x8D66
InsertEnumString(GL_FRAMEBUFFER_SRGB_EXT); // 0x8DB9
InsertEnumString(GL_UNSIGNED_INT_10_10_10_2_OES); // 0x8DF6
InsertEnumString(GL_INT_10_10_10_2_OES); // 0x8DF7
InsertEnumString(GL_QUERY_WAIT_NV); // 0x8E13
InsertEnumString(GL_QUERY_NO_WAIT_NV); // 0x8E14
InsertEnumString(GL_QUERY_BY_REGION_WAIT_NV); // 0x8E15
InsertEnumString(GL_QUERY_BY_REGION_NO_WAIT_NV); // 0x8E16
InsertEnumString(GL_COLOR_SAMPLES_NV); // 0x8E20
InsertEnumString(GL_TRANSFORM_FEEDBACK); // 0x8E22
InsertEnumString(GL_TIMESTAMP_EXT); // 0x8E28
InsertEnumString(GL_DEPTH_COMPONENT16_NONLINEAR_NV); // 0x8E2C
InsertEnumString(GL_COVERAGE_COMPONENT_NV); // 0x8ED0
InsertEnumString(GL_COVERAGE_COMPONENT4_NV); // 0x8ED1
InsertEnumString(GL_COVERAGE_ATTACHMENT_NV); // 0x8ED2
InsertEnumString(GL_COVERAGE_BUFFERS_NV); // 0x8ED3
InsertEnumString(GL_COVERAGE_SAMPLES_NV); // 0x8ED4
InsertEnumString(GL_COVERAGE_ALL_FRAGMENTS_NV); // 0x8ED5
InsertEnumString(GL_COVERAGE_EDGE_FRAGMENTS_NV); // 0x8ED6
InsertEnumString(GL_COVERAGE_AUTOMATIC_NV); // 0x8ED7
InsertEnumString(GL_MALI_SHADER_BINARY_ARM); // 0x8F60
InsertEnumString(GL_MALI_PROGRAM_BINARY_ARM); // 0x8F61
InsertEnumString(GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_FAST_SIZE_EXT); // 0x8F63
InsertEnumString(GL_SHADER_PIXEL_LOCAL_STORAGE_EXT); // 0x8F64
InsertEnumString(GL_FETCH_PER_SAMPLE_ARM); // 0x8F65
InsertEnumString(GL_FRAGMENT_SHADER_FRAMEBUFFER_FETCH_MRT_ARM); // 0x8F66
InsertEnumString(GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_SIZE_EXT); // 0x8F67
InsertEnumString(GL_R8_SNORM); // 0x8F94
InsertEnumString(GL_RG8_SNORM); // 0x8F95
InsertEnumString(GL_RGBA8_SNORM); // 0x8F97
InsertEnumString(GL_R16_SNORM_EXT); // 0x8F98
InsertEnumString(GL_RG16_SNORM_EXT); // 0x8F99
InsertEnumString(GL_RGB16_SNORM_EXT); // 0x8F9A
InsertEnumString(GL_RGBA16_SNORM_EXT); // 0x8F9B
InsertEnumString(GL_BINNING_CONTROL_HINT_QCOM); // 0x8FB0
InsertEnumString(GL_CPU_OPTIMIZED_QCOM); // 0x8FB1
InsertEnumString(GL_GPU_OPTIMIZED_QCOM); // 0x8FB2
InsertEnumString(GL_RENDER_DIRECT_TO_FRAMEBUFFER_QCOM); // 0x8FB3
InsertEnumString(GL_GPU_DISJOINT_EXT); // 0x8FBB
InsertEnumString(GL_SR8_EXT); // 0x8FBD
InsertEnumString(GL_SRG8_EXT); // 0x8FBE
InsertEnumString(GL_SHADER_BINARY_VIV); // 0x8FC4
InsertEnumString(GL_PATH_FORMAT_SVG_NV); // 0x9070
InsertEnumString(GL_PATH_FORMAT_PS_NV); // 0x9071
InsertEnumString(GL_STANDARD_FONT_NAME_NV); // 0x9072
InsertEnumString(GL_SYSTEM_FONT_NAME_NV); // 0x9073
InsertEnumString(GL_FILE_NAME_NV); // 0x9074
InsertEnumString(GL_PATH_STROKE_WIDTH_NV); // 0x9075
InsertEnumString(GL_PATH_END_CAPS_NV); // 0x9076
InsertEnumString(GL_PATH_INITIAL_END_CAP_NV); // 0x9077
InsertEnumString(GL_PATH_TERMINAL_END_CAP_NV); // 0x9078
InsertEnumString(GL_PATH_JOIN_STYLE_NV); // 0x9079
InsertEnumString(GL_PATH_MITER_LIMIT_NV); // 0x907A
InsertEnumString(GL_PATH_DASH_CAPS_NV); // 0x907B
InsertEnumString(GL_PATH_INITIAL_DASH_CAP_NV); // 0x907C
InsertEnumString(GL_PATH_TERMINAL_DASH_CAP_NV); // 0x907D
InsertEnumString(GL_PATH_DASH_OFFSET_NV); // 0x907E
InsertEnumString(GL_PATH_CLIENT_LENGTH_NV); // 0x907F
InsertEnumString(GL_PATH_FILL_MODE_NV); // 0x9080
InsertEnumString(GL_PATH_FILL_MASK_NV); // 0x9081
InsertEnumString(GL_PATH_FILL_COVER_MODE_NV); // 0x9082
InsertEnumString(GL_PATH_STROKE_COVER_MODE_NV); // 0x9083
InsertEnumString(GL_PATH_STROKE_MASK_NV); // 0x9084
InsertEnumString(GL_COUNT_UP_NV); // 0x9088
InsertEnumString(GL_COUNT_DOWN_NV); // 0x9089
InsertEnumString(GL_PATH_OBJECT_BOUNDING_BOX_NV); // 0x908A
InsertEnumString(GL_CONVEX_HULL_NV); // 0x908B
InsertEnumString(GL_BOUNDING_BOX_NV); // 0x908D
InsertEnumString(GL_TRANSLATE_X_NV); // 0x908E
InsertEnumString(GL_TRANSLATE_Y_NV); // 0x908F
InsertEnumString(GL_TRANSLATE_2D_NV); // 0x9090
InsertEnumString(GL_TRANSLATE_3D_NV); // 0x9091
InsertEnumString(GL_AFFINE_2D_NV); // 0x9092
InsertEnumString(GL_AFFINE_3D_NV); // 0x9094
InsertEnumString(GL_TRANSPOSE_AFFINE_2D_NV); // 0x9096
InsertEnumString(GL_TRANSPOSE_AFFINE_3D_NV); // 0x9098
InsertEnumString(GL_UTF8_NV); // 0x909A
InsertEnumString(GL_UTF16_NV); // 0x909B
InsertEnumString(GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV); // 0x909C
InsertEnumString(GL_PATH_COMMAND_COUNT_NV); // 0x909D
InsertEnumString(GL_PATH_COORD_COUNT_NV); // 0x909E
InsertEnumString(GL_PATH_DASH_ARRAY_COUNT_NV); // 0x909F
InsertEnumString(GL_PATH_COMPUTED_LENGTH_NV); // 0x90A0
InsertEnumString(GL_PATH_FILL_BOUNDING_BOX_NV); // 0x90A1
InsertEnumString(GL_PATH_STROKE_BOUNDING_BOX_NV); // 0x90A2
InsertEnumString(GL_SQUARE_NV); // 0x90A3
InsertEnumString(GL_ROUND_NV); // 0x90A4
InsertEnumString(GL_TRIANGULAR_NV); // 0x90A5
InsertEnumString(GL_BEVEL_NV); // 0x90A6
InsertEnumString(GL_MITER_REVERT_NV); // 0x90A7
InsertEnumString(GL_MITER_TRUNCATE_NV); // 0x90A8
InsertEnumString(GL_SKIP_MISSING_GLYPH_NV); // 0x90A9
InsertEnumString(GL_USE_MISSING_GLYPH_NV); // 0x90AA
InsertEnumString(GL_PATH_ERROR_POSITION_NV); // 0x90AB
InsertEnumString(GL_ACCUM_ADJACENT_PAIRS_NV); // 0x90AD
InsertEnumString(GL_ADJACENT_PAIRS_NV); // 0x90AE
InsertEnumString(GL_FIRST_TO_REST_NV); // 0x90AF
InsertEnumString(GL_PATH_GEN_MODE_NV); // 0x90B0
InsertEnumString(GL_PATH_GEN_COEFF_NV); // 0x90B1
InsertEnumString(GL_PATH_GEN_COMPONENTS_NV); // 0x90B3
InsertEnumString(GL_PATH_DASH_OFFSET_RESET_NV); // 0x90B4
InsertEnumString(GL_MOVE_TO_RESETS_NV); // 0x90B5
InsertEnumString(GL_MOVE_TO_CONTINUES_NV); // 0x90B6
InsertEnumString(GL_PATH_STENCIL_FUNC_NV); // 0x90B7
InsertEnumString(GL_PATH_STENCIL_REF_NV); // 0x90B8
InsertEnumString(GL_PATH_STENCIL_VALUE_MASK_NV); // 0x90B9
InsertEnumString(GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV); // 0x90BD
InsertEnumString(GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV); // 0x90BE
InsertEnumString(GL_PATH_COVER_DEPTH_FUNC_NV); // 0x90BF
InsertEnumString(GL_COLOR_ATTACHMENT_EXT); // 0x90F0
InsertEnumString(GL_MULTIVIEW_EXT); // 0x90F1
InsertEnumString(GL_MAX_MULTIVIEW_BUFFERS_EXT); // 0x90F2
InsertEnumString(GL_TEXTURE_2D_MULTISAMPLE); // 0x9100
InsertEnumString(GL_TEXTURE_2D_MULTISAMPLE_ARRAY); // 0x9102
InsertEnumString(GL_SGX_PROGRAM_BINARY_IMG); // 0x9130
InsertEnumString(GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG); // 0x9137
InsertEnumString(GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG); // 0x9138
InsertEnumString(GL_BUFFER_OBJECT_EXT); // 0x9151
InsertEnumString(GL_QUERY_OBJECT_EXT); // 0x9153
InsertEnumString(GL_VERTEX_ARRAY_OBJECT_EXT); // 0x9154
InsertEnumString(GL_VIRTUAL_PAGE_SIZE_X_EXT); // 0x9195
InsertEnumString(GL_VIRTUAL_PAGE_SIZE_Y_EXT); // 0x9196
InsertEnumString(GL_VIRTUAL_PAGE_SIZE_Z_EXT); // 0x9197
InsertEnumString(GL_MAX_SPARSE_TEXTURE_SIZE_EXT); // 0x9198
InsertEnumString(GL_MAX_SPARSE_3D_TEXTURE_SIZE_EXT); // 0x9199
InsertEnumString(GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_EXT); // 0x919A
InsertEnumString(GL_TEXTURE_SPARSE_EXT); // 0x91A6
InsertEnumString(GL_VIRTUAL_PAGE_SIZE_INDEX_EXT); // 0x91A7
InsertEnumString(GL_NUM_VIRTUAL_PAGE_SIZES_EXT); // 0x91A8
InsertEnumString(GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_EXT); // 0x91A9
InsertEnumString(GL_NUM_SPARSE_LEVELS_EXT); // 0x91AA
InsertEnumString(GL_SHADER_BINARY_DMP); // 0x9250
InsertEnumString(GL_SMAPHS30_PROGRAM_BINARY_DMP); // 0x9251
InsertEnumString(GL_SMAPHS_PROGRAM_BINARY_DMP); // 0x9252
InsertEnumString(GL_DMP_PROGRAM_BINARY_DMP); // 0x9253
InsertEnumString(GL_GCCSO_SHADER_BINARY_FJ); // 0x9260
InsertEnumString(GL_BLEND_PREMULTIPLIED_SRC_NV); // 0x9280
InsertEnumString(GL_BLEND_OVERLAP_NV); // 0x9281
InsertEnumString(GL_UNCORRELATED_NV); // 0x9282
InsertEnumString(GL_DISJOINT_NV); // 0x9283
InsertEnumString(GL_CONJOINT_NV); // 0x9284
InsertEnumString(GL_BLEND_ADVANCED_COHERENT_KHR); // 0x9285
InsertEnumString(GL_SRC_NV); // 0x9286
InsertEnumString(GL_DST_NV); // 0x9287
InsertEnumString(GL_SRC_OVER_NV); // 0x9288
InsertEnumString(GL_DST_OVER_NV); // 0x9289
InsertEnumString(GL_SRC_IN_NV); // 0x928A
InsertEnumString(GL_DST_IN_NV); // 0x928B
InsertEnumString(GL_SRC_OUT_NV); // 0x928C
InsertEnumString(GL_DST_OUT_NV); // 0x928D
InsertEnumString(GL_SRC_ATOP_NV); // 0x928E
InsertEnumString(GL_DST_ATOP_NV); // 0x928F
InsertEnumString(GL_PLUS_NV); // 0x9291
InsertEnumString(GL_PLUS_DARKER_NV); // 0x9292
InsertEnumString(GL_MINUS_NV); // 0x929F
InsertEnumString(GL_CONTRAST_NV); // 0x92A1
InsertEnumString(GL_INVERT_RGB_NV); // 0x92A3
InsertEnumString(GL_LINEARDODGE_NV); // 0x92A4
InsertEnumString(GL_LINEARBURN_NV); // 0x92A5
InsertEnumString(GL_VIVIDLIGHT_NV); // 0x92A6
InsertEnumString(GL_LINEARLIGHT_NV); // 0x92A7
InsertEnumString(GL_PINLIGHT_NV); // 0x92A8
InsertEnumString(GL_HARDMIX_NV); // 0x92A9
InsertEnumString(GL_PLUS_CLAMPED_NV); // 0x92B1
InsertEnumString(GL_PLUS_CLAMPED_ALPHA_NV); // 0x92B2
InsertEnumString(GL_MINUS_CLAMPED_NV); // 0x92B3
InsertEnumString(GL_INVERT_OVG_NV); // 0x92B4
InsertEnumString(GL_FRAGMENT_COVERAGE_TO_COLOR_NV); // 0x92DD
InsertEnumString(GL_FRAGMENT_COVERAGE_COLOR_NV); // 0x92DE
InsertEnumString(GL_RASTER_MULTISAMPLE_EXT); // 0x9327
InsertEnumString(GL_RASTER_SAMPLES_EXT); // 0x9328
InsertEnumString(GL_MAX_RASTER_SAMPLES_EXT); // 0x9329
InsertEnumString(GL_RASTER_FIXED_SAMPLE_LOCATIONS_EXT); // 0x932A
InsertEnumString(GL_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT); // 0x932B
InsertEnumString(GL_EFFECTIVE_RASTER_SAMPLES_EXT); // 0x932C
InsertEnumString(GL_DEPTH_SAMPLES_NV); // 0x932D
InsertEnumString(GL_STENCIL_SAMPLES_NV); // 0x932E
InsertEnumString(GL_MIXED_DEPTH_SAMPLES_SUPPORTED_NV); // 0x932F
InsertEnumString(GL_MIXED_STENCIL_SAMPLES_SUPPORTED_NV); // 0x9330
InsertEnumString(GL_COVERAGE_MODULATION_TABLE_NV); // 0x9331
InsertEnumString(GL_COVERAGE_MODULATION_NV); // 0x9332
InsertEnumString(GL_COVERAGE_MODULATION_TABLE_SIZE_NV); // 0x9333
InsertEnumString(GL_FILL_RECTANGLE_NV); // 0x933C
InsertEnumString(GL_SAMPLE_LOCATION_SUBPIXEL_BITS_NV); // 0x933D
InsertEnumString(GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_NV); // 0x933E
InsertEnumString(GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_NV); // 0x933F
InsertEnumString(GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_NV); // 0x9340
InsertEnumString(GL_PROGRAMMABLE_SAMPLE_LOCATION_NV); // 0x9341
InsertEnumString(GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_NV); // 0x9342
InsertEnumString(GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_NV); // 0x9343
InsertEnumString(GL_CONSERVATIVE_RASTERIZATION_NV); // 0x9346
InsertEnumString(GL_SUBPIXEL_PRECISION_BIAS_X_BITS_NV); // 0x9347
InsertEnumString(GL_SUBPIXEL_PRECISION_BIAS_Y_BITS_NV); // 0x9348
InsertEnumString(GL_MAX_SUBPIXEL_PRECISION_BIAS_BITS_NV); // 0x9349
InsertEnumString(GL_FONT_GLYPHS_AVAILABLE_NV); // 0x9368
InsertEnumString(GL_FONT_TARGET_UNAVAILABLE_NV); // 0x9369
InsertEnumString(GL_FONT_UNAVAILABLE_NV); // 0x936A
InsertEnumString(GL_FONT_UNINTELLIGIBLE_NV); // 0x936B
InsertEnumString(GL_STANDARD_FONT_FORMAT_NV); // 0x936C
InsertEnumString(GL_FRAGMENT_INPUT_NV); // 0x936D
InsertEnumString(GL_MULTISAMPLES_NV); // 0x9371
InsertEnumString(GL_SUPERSAMPLE_SCALE_X_NV); // 0x9372
InsertEnumString(GL_SUPERSAMPLE_SCALE_Y_NV); // 0x9373
InsertEnumString(GL_CONFORMANT_NV); // 0x9374
InsertEnumString(GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE); // 0x93A0
InsertEnumString(GL_TEXTURE_USAGE_ANGLE); // 0x93A2
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_ANGLE); // 0x93A3
InsertEnumString(GL_PACK_REVERSE_ROW_ORDER_ANGLE); // 0x93A4
InsertEnumString(GL_PROGRAM_BINARY_ANGLE); // 0x93A6
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_3x3x3_OES); // 0x93C0
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_4x3x3_OES); // 0x93C1
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_4x4x3_OES); // 0x93C2
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_4x4x4_OES); // 0x93C3
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_5x4x4_OES); // 0x93C4
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_5x5x4_OES); // 0x93C5
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_5x5x5_OES); // 0x93C6
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_6x5x5_OES); // 0x93C7
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_6x6x5_OES); // 0x93C8
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_6x6x6_OES); // 0x93C9
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_3x3x3_OES); // 0x93E0
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x3x3_OES); // 0x93E1
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x3_OES); // 0x93E2
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x4_OES); // 0x93E3
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4x4_OES); // 0x93E4
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x4_OES); // 0x93E5
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x5_OES); // 0x93E6
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5x5_OES); // 0x93E7
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x5_OES); // 0x93E8
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x6_OES); // 0x93E9
InsertEnumString(GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV2_IMG); // 0x93F0
InsertEnumString(GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV2_IMG); // 0x93F1
InsertEnumString(GL_PERFQUERY_COUNTER_EVENT_INTEL); // 0x94F0
InsertEnumString(GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL); // 0x94F1
InsertEnumString(GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL); // 0x94F2
InsertEnumString(GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL); // 0x94F3
InsertEnumString(GL_PERFQUERY_COUNTER_RAW_INTEL); // 0x94F4
InsertEnumString(GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL); // 0x94F5
InsertEnumString(GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL); // 0x94F8
InsertEnumString(GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL); // 0x94F9
InsertEnumString(GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL); // 0x94FA
InsertEnumString(GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL); // 0x94FB
InsertEnumString(GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL); // 0x94FC
InsertEnumString(GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL); // 0x94FD
InsertEnumString(GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL); // 0x94FE
InsertEnumString(GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL); // 0x94FF
InsertEnumString(GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL); // 0x9500
/* GLES 3 enums */
InsertEnumString(GL_READ_BUFFER); // 0x0C02
InsertEnumString(GL_UNPACK_ROW_LENGTH); // 0x0CF2
InsertEnumString(GL_UNPACK_SKIP_ROWS); // 0x0CF3
InsertEnumString(GL_UNPACK_SKIP_PIXELS); // 0x0CF4
InsertEnumString(GL_PACK_ROW_LENGTH); // 0x0D02
InsertEnumString(GL_PACK_SKIP_ROWS); // 0x0D03
InsertEnumString(GL_PACK_SKIP_PIXELS); // 0x0D04
InsertEnumString(GL_HALF_FLOAT); // 0x140B
InsertEnumString(GL_COLOR); // 0x1800
InsertEnumString(GL_DEPTH); // 0x1801
InsertEnumString(GL_STENCIL); // 0x1802
InsertEnumString(GL_RED); // 0x1903
InsertEnumString(GL_GREEN); // 0x1904
InsertEnumString(GL_BLUE); // 0x1905
InsertEnumString(GL_RGB8); // 0x8051
InsertEnumString(GL_RGBA8); // 0x8058
InsertEnumString(GL_RGB10_A2); // 0x8059
InsertEnumString(GL_TEXTURE_BINDING_3D); // 0x806A
InsertEnumString(GL_UNPACK_SKIP_IMAGES); // 0x806D
InsertEnumString(GL_UNPACK_IMAGE_HEIGHT); // 0x806E
InsertEnumString(GL_TEXTURE_WRAP_R); // 0x8072
InsertEnumString(GL_MAX_3D_TEXTURE_SIZE); // 0x8073
InsertEnumString(GL_MAX_ELEMENTS_VERTICES); // 0x80E8
InsertEnumString(GL_MAX_ELEMENTS_INDICES); // 0x80E9
InsertEnumString(GL_TEXTURE_MIN_LOD); // 0x813A
InsertEnumString(GL_TEXTURE_MAX_LOD); // 0x813B
InsertEnumString(GL_TEXTURE_BASE_LEVEL); // 0x813C
InsertEnumString(GL_TEXTURE_MAX_LEVEL); // 0x813D
InsertEnumString(GL_DEPTH_COMPONENT24); // 0x81A6
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING); // 0x8210
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE); // 0x8211
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE); // 0x8212
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE); // 0x8213
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE); // 0x8214
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE); // 0x8215
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE); // 0x8216
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE); // 0x8217
InsertEnumString(GL_FRAMEBUFFER_DEFAULT); // 0x8218
InsertEnumString(GL_FRAMEBUFFER_UNDEFINED); // 0x8219
InsertEnumString(GL_DEPTH_STENCIL_ATTACHMENT); // 0x821A
InsertEnumString(GL_MAJOR_VERSION); // 0x821B
InsertEnumString(GL_MINOR_VERSION); // 0x821C
InsertEnumString(GL_NUM_EXTENSIONS); // 0x821D
InsertEnumString(GL_RG); // 0x8227
InsertEnumString(GL_RG_INTEGER); // 0x8228
InsertEnumString(GL_R8); // 0x8229
InsertEnumString(GL_RG8); // 0x822B
InsertEnumString(GL_R16F); // 0x822D
InsertEnumString(GL_R32F); // 0x822E
InsertEnumString(GL_RG16F); // 0x822F
InsertEnumString(GL_RG32F); // 0x8230
InsertEnumString(GL_R8I); // 0x8231
InsertEnumString(GL_R8UI); // 0x8232
InsertEnumString(GL_R16I); // 0x8233
InsertEnumString(GL_R16UI); // 0x8234
InsertEnumString(GL_R32I); // 0x8235
InsertEnumString(GL_R32UI); // 0x8236
InsertEnumString(GL_RG8I); // 0x8237
InsertEnumString(GL_RG8UI); // 0x8238
InsertEnumString(GL_RG16I); // 0x8239
InsertEnumString(GL_RG16UI); // 0x823A
InsertEnumString(GL_RG32I); // 0x823B
InsertEnumString(GL_RG32UI); // 0x823C
InsertEnumString(GL_PROGRAM_BINARY_RETRIEVABLE_HINT); // 0x8257
InsertEnumString(GL_UNSIGNED_INT_2_10_10_10_REV); // 0x8368
InsertEnumString(GL_DEPTH_STENCIL); // 0x84F9
InsertEnumString(GL_UNSIGNED_INT_24_8); // 0x84FA
InsertEnumString(GL_MAX_TEXTURE_LOD_BIAS); // 0x84FD
InsertEnumString(GL_VERTEX_ARRAY_BINDING); // 0x85B5
InsertEnumString(GL_PROGRAM_BINARY_LENGTH); // 0x8741
InsertEnumString(GL_NUM_PROGRAM_BINARY_FORMATS); // 0x87FE
InsertEnumString(GL_PROGRAM_BINARY_FORMATS); // 0x87FF
InsertEnumString(GL_RGBA32F); // 0x8814
InsertEnumString(GL_RGB32F); // 0x8815
InsertEnumString(GL_RGBA16F); // 0x881A
InsertEnumString(GL_RGB16F); // 0x881B
InsertEnumString(GL_MAX_DRAW_BUFFERS); // 0x8824
InsertEnumString(GL_DRAW_BUFFER0); // 0x8825
InsertEnumString(GL_DRAW_BUFFER1); // 0x8826
InsertEnumString(GL_DRAW_BUFFER2); // 0x8827
InsertEnumString(GL_DRAW_BUFFER3); // 0x8828
InsertEnumString(GL_DRAW_BUFFER4); // 0x8829
InsertEnumString(GL_DRAW_BUFFER5); // 0x882A
InsertEnumString(GL_DRAW_BUFFER6); // 0x882B
InsertEnumString(GL_DRAW_BUFFER7); // 0x882C
InsertEnumString(GL_DRAW_BUFFER8); // 0x882D
InsertEnumString(GL_DRAW_BUFFER9); // 0x882E
InsertEnumString(GL_DRAW_BUFFER10); // 0x882F
InsertEnumString(GL_DRAW_BUFFER11); // 0x8830
InsertEnumString(GL_DRAW_BUFFER12); // 0x8831
InsertEnumString(GL_DRAW_BUFFER13); // 0x8832
InsertEnumString(GL_DRAW_BUFFER14); // 0x8833
InsertEnumString(GL_DRAW_BUFFER15); // 0x8834
InsertEnumString(GL_TEXTURE_COMPARE_MODE); // 0x884C
InsertEnumString(GL_TEXTURE_COMPARE_FUNC); // 0x884D
InsertEnumString(GL_COMPARE_REF_TO_TEXTURE); // 0x884E
InsertEnumString(GL_CURRENT_QUERY); // 0x8865
InsertEnumString(GL_QUERY_RESULT); // 0x8866
InsertEnumString(GL_QUERY_RESULT_AVAILABLE); // 0x8867
InsertEnumString(GL_BUFFER_MAPPED); // 0x88BC
InsertEnumString(GL_BUFFER_MAP_POINTER); // 0x88BD
InsertEnumString(GL_STREAM_READ); // 0x88E1
InsertEnumString(GL_STREAM_COPY); // 0x88E2
InsertEnumString(GL_STATIC_READ); // 0x88E5
InsertEnumString(GL_STATIC_COPY); // 0x88E6
InsertEnumString(GL_DYNAMIC_READ); // 0x88E9
InsertEnumString(GL_DYNAMIC_COPY); // 0x88EA
InsertEnumString(GL_PIXEL_PACK_BUFFER); // 0x88EB
InsertEnumString(GL_PIXEL_UNPACK_BUFFER); // 0x88EC
InsertEnumString(GL_PIXEL_PACK_BUFFER_BINDING); // 0x88ED
InsertEnumString(GL_PIXEL_UNPACK_BUFFER_BINDING); // 0x88EF
InsertEnumString(GL_DEPTH24_STENCIL8); // 0x88F0
InsertEnumString(GL_VERTEX_ATTRIB_ARRAY_INTEGER); // 0x88FD
InsertEnumString(GL_VERTEX_ATTRIB_ARRAY_DIVISOR); // 0x88FE
InsertEnumString(GL_MAX_ARRAY_TEXTURE_LAYERS); // 0x88FF
InsertEnumString(GL_MIN_PROGRAM_TEXEL_OFFSET); // 0x8904
InsertEnumString(GL_MAX_PROGRAM_TEXEL_OFFSET); // 0x8905
InsertEnumString(GL_SAMPLER_BINDING); // 0x8919
InsertEnumString(GL_UNIFORM_BUFFER); // 0x8A11
InsertEnumString(GL_UNIFORM_BUFFER_BINDING); // 0x8A28
InsertEnumString(GL_UNIFORM_BUFFER_START); // 0x8A29
InsertEnumString(GL_UNIFORM_BUFFER_SIZE); // 0x8A2A
InsertEnumString(GL_MAX_VERTEX_UNIFORM_BLOCKS); // 0x8A2B
InsertEnumString(GL_MAX_FRAGMENT_UNIFORM_BLOCKS); // 0x8A2D
InsertEnumString(GL_MAX_COMBINED_UNIFORM_BLOCKS); // 0x8A2E
InsertEnumString(GL_MAX_UNIFORM_BUFFER_BINDINGS); // 0x8A2F
InsertEnumString(GL_MAX_UNIFORM_BLOCK_SIZE); // 0x8A30
InsertEnumString(GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS); // 0x8A31
InsertEnumString(GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS); // 0x8A33
InsertEnumString(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT); // 0x8A34
InsertEnumString(GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH); // 0x8A35
InsertEnumString(GL_ACTIVE_UNIFORM_BLOCKS); // 0x8A36
InsertEnumString(GL_UNIFORM_TYPE); // 0x8A37
InsertEnumString(GL_UNIFORM_SIZE); // 0x8A38
InsertEnumString(GL_UNIFORM_NAME_LENGTH); // 0x8A39
InsertEnumString(GL_UNIFORM_BLOCK_INDEX); // 0x8A3A
InsertEnumString(GL_UNIFORM_OFFSET); // 0x8A3B
InsertEnumString(GL_UNIFORM_ARRAY_STRIDE); // 0x8A3C
InsertEnumString(GL_UNIFORM_MATRIX_STRIDE); // 0x8A3D
InsertEnumString(GL_UNIFORM_IS_ROW_MAJOR); // 0x8A3E
InsertEnumString(GL_UNIFORM_BLOCK_BINDING); // 0x8A3F
InsertEnumString(GL_UNIFORM_BLOCK_DATA_SIZE); // 0x8A40
InsertEnumString(GL_UNIFORM_BLOCK_NAME_LENGTH); // 0x8A41
InsertEnumString(GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS); // 0x8A42
InsertEnumString(GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES); // 0x8A43
InsertEnumString(GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER); // 0x8A44
InsertEnumString(GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER); // 0x8A46
InsertEnumString(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS); // 0x8B49
InsertEnumString(GL_MAX_VERTEX_UNIFORM_COMPONENTS); // 0x8B4A
InsertEnumString(GL_MAX_VARYING_COMPONENTS); // 0x8B4B
InsertEnumString(GL_SAMPLER_3D); // 0x8B5F
InsertEnumString(GL_SAMPLER_2D_SHADOW); // 0x8B62
InsertEnumString(GL_FLOAT_MAT2x3); // 0x8B65
InsertEnumString(GL_FLOAT_MAT2x4); // 0x8B66
InsertEnumString(GL_FLOAT_MAT3x2); // 0x8B67
InsertEnumString(GL_FLOAT_MAT3x4); // 0x8B68
InsertEnumString(GL_FLOAT_MAT4x2); // 0x8B69
InsertEnumString(GL_FLOAT_MAT4x3); // 0x8B6A
InsertEnumString(GL_FRAGMENT_SHADER_DERIVATIVE_HINT); // 0x8B8B
InsertEnumString(GL_UNSIGNED_NORMALIZED); // 0x8C17
InsertEnumString(GL_TEXTURE_BINDING_2D_ARRAY); // 0x8C1D
InsertEnumString(GL_ANY_SAMPLES_PASSED); // 0x8C2F
InsertEnumString(GL_R11F_G11F_B10F); // 0x8C3A
InsertEnumString(GL_UNSIGNED_INT_10F_11F_11F_REV); // 0x8C3B
InsertEnumString(GL_RGB9_E5); // 0x8C3D
InsertEnumString(GL_UNSIGNED_INT_5_9_9_9_REV); // 0x8C3E
InsertEnumString(GL_SRGB); // 0x8C40
InsertEnumString(GL_SRGB8); // 0x8C41
InsertEnumString(GL_SRGB8_ALPHA8); // 0x8C43
InsertEnumString(GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH); // 0x8C76
InsertEnumString(GL_TRANSFORM_FEEDBACK_BUFFER_MODE); // 0x8C7F
InsertEnumString(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS); // 0x8C80
InsertEnumString(GL_TRANSFORM_FEEDBACK_VARYINGS); // 0x8C83
InsertEnumString(GL_TRANSFORM_FEEDBACK_BUFFER_START); // 0x8C84
InsertEnumString(GL_TRANSFORM_FEEDBACK_BUFFER_SIZE); // 0x8C85
InsertEnumString(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN); // 0x8C88
InsertEnumString(GL_RASTERIZER_DISCARD); // 0x8C89
InsertEnumString(GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS); // 0x8C8A
InsertEnumString(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS); // 0x8C8B
InsertEnumString(GL_INTERLEAVED_ATTRIBS); // 0x8C8C
InsertEnumString(GL_SEPARATE_ATTRIBS); // 0x8C8D
InsertEnumString(GL_TRANSFORM_FEEDBACK_BUFFER); // 0x8C8E
InsertEnumString(GL_TRANSFORM_FEEDBACK_BUFFER_BINDING); // 0x8C8F
InsertEnumString(GL_READ_FRAMEBUFFER); // 0x8CA8
InsertEnumString(GL_DRAW_FRAMEBUFFER); // 0x8CA9
InsertEnumString(GL_READ_FRAMEBUFFER_BINDING); // 0x8CAA
InsertEnumString(GL_RENDERBUFFER_SAMPLES); // 0x8CAB
InsertEnumString(GL_DEPTH_COMPONENT32F); // 0x8CAC
InsertEnumString(GL_DEPTH32F_STENCIL8); // 0x8CAD
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER); // 0x8CD4
InsertEnumString(GL_MAX_COLOR_ATTACHMENTS); // 0x8CDF
InsertEnumString(GL_COLOR_ATTACHMENT1); // 0x8CE1
InsertEnumString(GL_COLOR_ATTACHMENT2); // 0x8CE2
InsertEnumString(GL_COLOR_ATTACHMENT3); // 0x8CE3
InsertEnumString(GL_COLOR_ATTACHMENT4); // 0x8CE4
InsertEnumString(GL_COLOR_ATTACHMENT5); // 0x8CE5
InsertEnumString(GL_COLOR_ATTACHMENT6); // 0x8CE6
InsertEnumString(GL_COLOR_ATTACHMENT7); // 0x8CE7
InsertEnumString(GL_COLOR_ATTACHMENT8); // 0x8CE8
InsertEnumString(GL_COLOR_ATTACHMENT9); // 0x8CE9
InsertEnumString(GL_COLOR_ATTACHMENT10); // 0x8CEA
InsertEnumString(GL_COLOR_ATTACHMENT11); // 0x8CEB
InsertEnumString(GL_COLOR_ATTACHMENT12); // 0x8CEC
InsertEnumString(GL_COLOR_ATTACHMENT13); // 0x8CED
InsertEnumString(GL_COLOR_ATTACHMENT14); // 0x8CEE
InsertEnumString(GL_COLOR_ATTACHMENT15); // 0x8CEF
InsertEnumString(GL_COLOR_ATTACHMENT16); // 0x8CF0
InsertEnumString(GL_COLOR_ATTACHMENT17); // 0x8CF1
InsertEnumString(GL_COLOR_ATTACHMENT18); // 0x8CF2
InsertEnumString(GL_COLOR_ATTACHMENT19); // 0x8CF3
InsertEnumString(GL_COLOR_ATTACHMENT20); // 0x8CF4
InsertEnumString(GL_COLOR_ATTACHMENT21); // 0x8CF5
InsertEnumString(GL_COLOR_ATTACHMENT22); // 0x8CF6
InsertEnumString(GL_COLOR_ATTACHMENT23); // 0x8CF7
InsertEnumString(GL_COLOR_ATTACHMENT24); // 0x8CF8
InsertEnumString(GL_COLOR_ATTACHMENT25); // 0x8CF9
InsertEnumString(GL_COLOR_ATTACHMENT26); // 0x8CFA
InsertEnumString(GL_COLOR_ATTACHMENT27); // 0x8CFB
InsertEnumString(GL_COLOR_ATTACHMENT28); // 0x8CFC
InsertEnumString(GL_COLOR_ATTACHMENT29); // 0x8CFD
InsertEnumString(GL_COLOR_ATTACHMENT30); // 0x8CFE
InsertEnumString(GL_COLOR_ATTACHMENT31); // 0x8CFF
InsertEnumString(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE); // 0x8D56
InsertEnumString(GL_MAX_SAMPLES); // 0x8D57
InsertEnumString(GL_PRIMITIVE_RESTART_FIXED_INDEX); // 0x8D69
InsertEnumString(GL_ANY_SAMPLES_PASSED_CONSERVATIVE); // 0x8D6A
InsertEnumString(GL_MAX_ELEMENT_INDEX); // 0x8D6B
InsertEnumString(GL_RGBA32UI); // 0x8D70
InsertEnumString(GL_RGB32UI); // 0x8D71
InsertEnumString(GL_RGBA16UI); // 0x8D76
InsertEnumString(GL_RGB16UI); // 0x8D77
InsertEnumString(GL_RGBA8UI); // 0x8D7C
InsertEnumString(GL_RGB8UI); // 0x8D7D
InsertEnumString(GL_RGBA32I); // 0x8D82
InsertEnumString(GL_RGB32I); // 0x8D83
InsertEnumString(GL_RGBA16I); // 0x8D88
InsertEnumString(GL_RGB16I); // 0x8D89
InsertEnumString(GL_RGBA8I); // 0x8D8E
InsertEnumString(GL_RGB8I); // 0x8D8F
InsertEnumString(GL_RED_INTEGER); // 0x8D94
InsertEnumString(GL_RGB_INTEGER); // 0x8D98
InsertEnumString(GL_RGBA_INTEGER); // 0x8D99
InsertEnumString(GL_INT_2_10_10_10_REV); // 0x8D9F
InsertEnumString(GL_FLOAT_32_UNSIGNED_INT_24_8_REV); // 0x8DAD
InsertEnumString(GL_SAMPLER_2D_ARRAY); // 0x8DC1
InsertEnumString(GL_SAMPLER_2D_ARRAY_SHADOW); // 0x8DC4
InsertEnumString(GL_SAMPLER_CUBE_SHADOW); // 0x8DC5
InsertEnumString(GL_UNSIGNED_INT_VEC2); // 0x8DC6
InsertEnumString(GL_UNSIGNED_INT_VEC3); // 0x8DC7
InsertEnumString(GL_UNSIGNED_INT_VEC4); // 0x8DC8
InsertEnumString(GL_INT_SAMPLER_2D); // 0x8DCA
InsertEnumString(GL_INT_SAMPLER_3D); // 0x8DCB
InsertEnumString(GL_INT_SAMPLER_CUBE); // 0x8DCC
InsertEnumString(GL_INT_SAMPLER_2D_ARRAY); // 0x8DCF
InsertEnumString(GL_UNSIGNED_INT_SAMPLER_2D); // 0x8DD2
InsertEnumString(GL_UNSIGNED_INT_SAMPLER_3D); // 0x8DD3
InsertEnumString(GL_UNSIGNED_INT_SAMPLER_CUBE); // 0x8DD4
InsertEnumString(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY); // 0x8DD7
InsertEnumString(GL_TRANSFORM_FEEDBACK_PAUSED); // 0x8E23
InsertEnumString(GL_TRANSFORM_FEEDBACK_ACTIVE); // 0x8E24
InsertEnumString(GL_TRANSFORM_FEEDBACK_BINDING); // 0x8E25
InsertEnumString(GL_TEXTURE_SWIZZLE_R); // 0x8E42
InsertEnumString(GL_TEXTURE_SWIZZLE_G); // 0x8E43
InsertEnumString(GL_TEXTURE_SWIZZLE_B); // 0x8E44
InsertEnumString(GL_TEXTURE_SWIZZLE_A); // 0x8E45
InsertEnumString(GL_COPY_READ_BUFFER); // 0x8F36
InsertEnumString(GL_COPY_WRITE_BUFFER); // 0x8F37
InsertEnumString(GL_RGB8_SNORM); // 0x8F96
InsertEnumString(GL_SIGNED_NORMALIZED); // 0x8F9C
InsertEnumString(GL_RGB10_A2UI); // 0x906F
InsertEnumString(GL_MAX_SERVER_WAIT_TIMEOUT); // 0x9111
InsertEnumString(GL_OBJECT_TYPE); // 0x9112
InsertEnumString(GL_SYNC_CONDITION); // 0x9113
InsertEnumString(GL_SYNC_STATUS); // 0x9114
InsertEnumString(GL_SYNC_FLAGS); // 0x9115
InsertEnumString(GL_SYNC_FENCE); // 0x9116
InsertEnumString(GL_SYNC_GPU_COMMANDS_COMPLETE); // 0x9117
InsertEnumString(GL_UNSIGNALED); // 0x9118
InsertEnumString(GL_SIGNALED); // 0x9119
InsertEnumString(GL_ALREADY_SIGNALED); // 0x911A
InsertEnumString(GL_TIMEOUT_EXPIRED); // 0x911B
InsertEnumString(GL_CONDITION_SATISFIED); // 0x911C
InsertEnumString(GL_WAIT_FAILED); // 0x911D
InsertEnumString(GL_BUFFER_ACCESS_FLAGS); // 0x911F
InsertEnumString(GL_BUFFER_MAP_LENGTH); // 0x9120
InsertEnumString(GL_BUFFER_MAP_OFFSET); // 0x9121
InsertEnumString(GL_MAX_VERTEX_OUTPUT_COMPONENTS); // 0x9122
InsertEnumString(GL_MAX_FRAGMENT_INPUT_COMPONENTS); // 0x9125
InsertEnumString(GL_TEXTURE_IMMUTABLE_FORMAT); // 0x912F
InsertEnumString(GL_COMPRESSED_R11_EAC); // 0x9270
InsertEnumString(GL_COMPRESSED_SIGNED_R11_EAC); // 0x9271
InsertEnumString(GL_COMPRESSED_RG11_EAC); // 0x9272
InsertEnumString(GL_COMPRESSED_SIGNED_RG11_EAC); // 0x9273
InsertEnumString(GL_COMPRESSED_RGB8_ETC2); // 0x9274
InsertEnumString(GL_COMPRESSED_SRGB8_ETC2); // 0x9275
InsertEnumString(GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2); // 0x9276
InsertEnumString(GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2); // 0x9277
InsertEnumString(GL_COMPRESSED_RGBA8_ETC2_EAC); // 0x9278
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC); // 0x9279
InsertEnumString(GL_NUM_SAMPLE_COUNTS); // 0x9380
/* GLES 3.1 enums */
InsertEnumString(GL_TEXTURE_WIDTH); // 0x1000
InsertEnumString(GL_TEXTURE_HEIGHT); // 0x1001
InsertEnumString(GL_TEXTURE_INTERNAL_FORMAT); // 0x1003
InsertEnumString(GL_STENCIL_INDEX); // 0x1901
InsertEnumString(GL_TEXTURE_RED_SIZE); // 0x805C
InsertEnumString(GL_TEXTURE_GREEN_SIZE); // 0x805D
InsertEnumString(GL_TEXTURE_BLUE_SIZE); // 0x805E
InsertEnumString(GL_TEXTURE_ALPHA_SIZE); // 0x805F
InsertEnumString(GL_TEXTURE_DEPTH); // 0x8071
InsertEnumString(GL_PROGRAM_SEPARABLE); // 0x8258
InsertEnumString(GL_ACTIVE_PROGRAM); // 0x8259
InsertEnumString(GL_PROGRAM_PIPELINE_BINDING); // 0x825A
InsertEnumString(GL_MAX_COMPUTE_SHARED_MEMORY_SIZE); // 0x8262
InsertEnumString(GL_MAX_COMPUTE_UNIFORM_COMPONENTS); // 0x8263
InsertEnumString(GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS); // 0x8264
InsertEnumString(GL_MAX_COMPUTE_ATOMIC_COUNTERS); // 0x8265
InsertEnumString(GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS); // 0x8266
InsertEnumString(GL_COMPUTE_WORK_GROUP_SIZE); // 0x8267
InsertEnumString(GL_MAX_UNIFORM_LOCATIONS); // 0x826E
InsertEnumString(GL_VERTEX_ATTRIB_BINDING); // 0x82D4
InsertEnumString(GL_VERTEX_ATTRIB_RELATIVE_OFFSET); // 0x82D5
InsertEnumString(GL_VERTEX_BINDING_DIVISOR); // 0x82D6
InsertEnumString(GL_VERTEX_BINDING_OFFSET); // 0x82D7
InsertEnumString(GL_VERTEX_BINDING_STRIDE); // 0x82D8
InsertEnumString(GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET); // 0x82D9
InsertEnumString(GL_MAX_VERTEX_ATTRIB_BINDINGS); // 0x82DA
InsertEnumString(GL_MAX_VERTEX_ATTRIB_STRIDE); // 0x82E5
InsertEnumString(GL_TEXTURE_COMPRESSED); // 0x86A1
InsertEnumString(GL_TEXTURE_DEPTH_SIZE); // 0x884A
InsertEnumString(GL_READ_ONLY); // 0x88B8
InsertEnumString(GL_WRITE_ONLY); // 0x88B9
InsertEnumString(GL_READ_WRITE); // 0x88BA
InsertEnumString(GL_TEXTURE_STENCIL_SIZE); // 0x88F1
InsertEnumString(GL_TEXTURE_RED_TYPE); // 0x8C10
InsertEnumString(GL_TEXTURE_GREEN_TYPE); // 0x8C11
InsertEnumString(GL_TEXTURE_BLUE_TYPE); // 0x8C12
InsertEnumString(GL_TEXTURE_ALPHA_TYPE); // 0x8C13
InsertEnumString(GL_TEXTURE_DEPTH_TYPE); // 0x8C16
InsertEnumString(GL_TEXTURE_SHARED_SIZE); // 0x8C3F
InsertEnumString(GL_SAMPLE_POSITION); // 0x8E50
InsertEnumString(GL_SAMPLE_MASK); // 0x8E51
InsertEnumString(GL_SAMPLE_MASK_VALUE); // 0x8E52
InsertEnumString(GL_MAX_SAMPLE_MASK_WORDS); // 0x8E59
InsertEnumString(GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET); // 0x8E5E
InsertEnumString(GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET); // 0x8E5F
InsertEnumString(GL_MAX_IMAGE_UNITS); // 0x8F38
InsertEnumString(GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES); // 0x8F39
InsertEnumString(GL_IMAGE_BINDING_NAME); // 0x8F3A
InsertEnumString(GL_IMAGE_BINDING_LEVEL); // 0x8F3B
InsertEnumString(GL_IMAGE_BINDING_LAYERED); // 0x8F3C
InsertEnumString(GL_IMAGE_BINDING_LAYER); // 0x8F3D
InsertEnumString(GL_IMAGE_BINDING_ACCESS); // 0x8F3E
InsertEnumString(GL_DRAW_INDIRECT_BUFFER); // 0x8F3F
InsertEnumString(GL_DRAW_INDIRECT_BUFFER_BINDING); // 0x8F43
InsertEnumString(GL_VERTEX_BINDING_BUFFER); // 0x8F4F
InsertEnumString(GL_IMAGE_2D); // 0x904D
InsertEnumString(GL_IMAGE_3D); // 0x904E
InsertEnumString(GL_IMAGE_CUBE); // 0x9050
InsertEnumString(GL_IMAGE_2D_ARRAY); // 0x9053
InsertEnumString(GL_INT_IMAGE_2D); // 0x9058
InsertEnumString(GL_INT_IMAGE_3D); // 0x9059
InsertEnumString(GL_INT_IMAGE_CUBE); // 0x905B
InsertEnumString(GL_INT_IMAGE_2D_ARRAY); // 0x905E
InsertEnumString(GL_UNSIGNED_INT_IMAGE_2D); // 0x9063
InsertEnumString(GL_UNSIGNED_INT_IMAGE_3D); // 0x9064
InsertEnumString(GL_UNSIGNED_INT_IMAGE_CUBE); // 0x9066
InsertEnumString(GL_UNSIGNED_INT_IMAGE_2D_ARRAY); // 0x9069
InsertEnumString(GL_IMAGE_BINDING_FORMAT); // 0x906E
InsertEnumString(GL_IMAGE_FORMAT_COMPATIBILITY_TYPE); // 0x90C7
InsertEnumString(GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE); // 0x90C8
InsertEnumString(GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS); // 0x90C9
InsertEnumString(GL_MAX_VERTEX_IMAGE_UNIFORMS); // 0x90CA
InsertEnumString(GL_MAX_FRAGMENT_IMAGE_UNIFORMS); // 0x90CE
InsertEnumString(GL_MAX_COMBINED_IMAGE_UNIFORMS); // 0x90CF
InsertEnumString(GL_SHADER_STORAGE_BUFFER); // 0x90D2
InsertEnumString(GL_SHADER_STORAGE_BUFFER_BINDING); // 0x90D3
InsertEnumString(GL_SHADER_STORAGE_BUFFER_START); // 0x90D4
InsertEnumString(GL_SHADER_STORAGE_BUFFER_SIZE); // 0x90D5
InsertEnumString(GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS); // 0x90D6
InsertEnumString(GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS); // 0x90DA
InsertEnumString(GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS); // 0x90DB
InsertEnumString(GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS); // 0x90DC
InsertEnumString(GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS); // 0x90DD
InsertEnumString(GL_MAX_SHADER_STORAGE_BLOCK_SIZE); // 0x90DE
InsertEnumString(GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT); // 0x90DF
InsertEnumString(GL_DEPTH_STENCIL_TEXTURE_MODE); // 0x90EA
InsertEnumString(GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS); // 0x90EB
InsertEnumString(GL_DISPATCH_INDIRECT_BUFFER); // 0x90EE
InsertEnumString(GL_DISPATCH_INDIRECT_BUFFER_BINDING); // 0x90EF
InsertEnumString(GL_TEXTURE_BINDING_2D_MULTISAMPLE); // 0x9104
InsertEnumString(GL_TEXTURE_SAMPLES); // 0x9106
InsertEnumString(GL_TEXTURE_FIXED_SAMPLE_LOCATIONS); // 0x9107
InsertEnumString(GL_SAMPLER_2D_MULTISAMPLE); // 0x9108
InsertEnumString(GL_INT_SAMPLER_2D_MULTISAMPLE); // 0x9109
InsertEnumString(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE); // 0x910A
InsertEnumString(GL_MAX_COLOR_TEXTURE_SAMPLES); // 0x910E
InsertEnumString(GL_MAX_DEPTH_TEXTURE_SAMPLES); // 0x910F
InsertEnumString(GL_MAX_INTEGER_SAMPLES); // 0x9110
InsertEnumString(GL_COMPUTE_SHADER); // 0x91B9
InsertEnumString(GL_MAX_COMPUTE_UNIFORM_BLOCKS); // 0x91BB
InsertEnumString(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS); // 0x91BC
InsertEnumString(GL_MAX_COMPUTE_IMAGE_UNIFORMS); // 0x91BD
InsertEnumString(GL_MAX_COMPUTE_WORK_GROUP_COUNT); // 0x91BE
InsertEnumString(GL_MAX_COMPUTE_WORK_GROUP_SIZE); // 0x91BF
InsertEnumString(GL_ATOMIC_COUNTER_BUFFER); // 0x92C0
InsertEnumString(GL_ATOMIC_COUNTER_BUFFER_BINDING); // 0x92C1
InsertEnumString(GL_ATOMIC_COUNTER_BUFFER_START); // 0x92C2
InsertEnumString(GL_ATOMIC_COUNTER_BUFFER_SIZE); // 0x92C3
InsertEnumString(GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS); // 0x92CC
InsertEnumString(GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS); // 0x92D0
InsertEnumString(GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS); // 0x92D1
InsertEnumString(GL_MAX_VERTEX_ATOMIC_COUNTERS); // 0x92D2
InsertEnumString(GL_MAX_FRAGMENT_ATOMIC_COUNTERS); // 0x92D6
InsertEnumString(GL_MAX_COMBINED_ATOMIC_COUNTERS); // 0x92D7
InsertEnumString(GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE); // 0x92D8
InsertEnumString(GL_ACTIVE_ATOMIC_COUNTER_BUFFERS); // 0x92D9
InsertEnumString(GL_UNSIGNED_INT_ATOMIC_COUNTER); // 0x92DB
InsertEnumString(GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS); // 0x92DC
InsertEnumString(GL_UNIFORM); // 0x92E1
InsertEnumString(GL_UNIFORM_BLOCK); // 0x92E2
InsertEnumString(GL_PROGRAM_INPUT); // 0x92E3
InsertEnumString(GL_PROGRAM_OUTPUT); // 0x92E4
InsertEnumString(GL_BUFFER_VARIABLE); // 0x92E5
InsertEnumString(GL_SHADER_STORAGE_BLOCK); // 0x92E6
InsertEnumString(GL_TRANSFORM_FEEDBACK_VARYING); // 0x92F4
InsertEnumString(GL_ACTIVE_RESOURCES); // 0x92F5
InsertEnumString(GL_MAX_NAME_LENGTH); // 0x92F6
InsertEnumString(GL_MAX_NUM_ACTIVE_VARIABLES); // 0x92F7
InsertEnumString(GL_NAME_LENGTH); // 0x92F9
InsertEnumString(GL_TYPE); // 0x92FA
InsertEnumString(GL_ARRAY_SIZE); // 0x92FB
InsertEnumString(GL_OFFSET); // 0x92FC
InsertEnumString(GL_BLOCK_INDEX); // 0x92FD
InsertEnumString(GL_ARRAY_STRIDE); // 0x92FE
InsertEnumString(GL_MATRIX_STRIDE); // 0x92FF
InsertEnumString(GL_IS_ROW_MAJOR); // 0x9300
InsertEnumString(GL_ATOMIC_COUNTER_BUFFER_INDEX); // 0x9301
InsertEnumString(GL_BUFFER_BINDING); // 0x9302
InsertEnumString(GL_BUFFER_DATA_SIZE); // 0x9303
InsertEnumString(GL_NUM_ACTIVE_VARIABLES); // 0x9304
InsertEnumString(GL_ACTIVE_VARIABLES); // 0x9305
InsertEnumString(GL_REFERENCED_BY_VERTEX_SHADER); // 0x9306
InsertEnumString(GL_REFERENCED_BY_FRAGMENT_SHADER); // 0x930A
InsertEnumString(GL_REFERENCED_BY_COMPUTE_SHADER); // 0x930B
InsertEnumString(GL_TOP_LEVEL_ARRAY_SIZE); // 0x930C
InsertEnumString(GL_TOP_LEVEL_ARRAY_STRIDE); // 0x930D
InsertEnumString(GL_LOCATION); // 0x930E
InsertEnumString(GL_FRAMEBUFFER_DEFAULT_WIDTH); // 0x9310
InsertEnumString(GL_FRAMEBUFFER_DEFAULT_HEIGHT); // 0x9311
InsertEnumString(GL_FRAMEBUFFER_DEFAULT_SAMPLES); // 0x9313
InsertEnumString(GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS); // 0x9314
InsertEnumString(GL_MAX_FRAMEBUFFER_WIDTH); // 0x9315
InsertEnumString(GL_MAX_FRAMEBUFFER_HEIGHT); // 0x9316
InsertEnumString(GL_MAX_FRAMEBUFFER_SAMPLES); // 0x9318
/* GLES 3.2 enums */
InsertEnumString(GL_CONTEXT_LOST); // 0x0507
InsertEnumString(GL_TEXTURE_BORDER_COLOR); // 0x1004
InsertEnumString(GL_CLAMP_TO_BORDER); // 0x812D
InsertEnumString(GL_CONTEXT_FLAGS); // 0x821E
InsertEnumString(GL_DEBUG_OUTPUT_SYNCHRONOUS); // 0x8242
InsertEnumString(GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH); // 0x8243
InsertEnumString(GL_DEBUG_CALLBACK_FUNCTION); // 0x8244
InsertEnumString(GL_DEBUG_CALLBACK_USER_PARAM); // 0x8245
InsertEnumString(GL_DEBUG_SOURCE_API); // 0x8246
InsertEnumString(GL_DEBUG_SOURCE_WINDOW_SYSTEM); // 0x8247
InsertEnumString(GL_DEBUG_SOURCE_SHADER_COMPILER); // 0x8248
InsertEnumString(GL_DEBUG_SOURCE_THIRD_PARTY); // 0x8249
InsertEnumString(GL_DEBUG_SOURCE_APPLICATION); // 0x824A
InsertEnumString(GL_DEBUG_SOURCE_OTHER); // 0x824B
InsertEnumString(GL_DEBUG_TYPE_ERROR); // 0x824C
InsertEnumString(GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR); // 0x824D
InsertEnumString(GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR); // 0x824E
InsertEnumString(GL_DEBUG_TYPE_PORTABILITY); // 0x824F
InsertEnumString(GL_DEBUG_TYPE_PERFORMANCE); // 0x8250
InsertEnumString(GL_DEBUG_TYPE_OTHER); // 0x8251
InsertEnumString(GL_LOSE_CONTEXT_ON_RESET); // 0x8252
InsertEnumString(GL_GUILTY_CONTEXT_RESET); // 0x8253
InsertEnumString(GL_INNOCENT_CONTEXT_RESET); // 0x8254
InsertEnumString(GL_UNKNOWN_CONTEXT_RESET); // 0x8255
InsertEnumString(GL_RESET_NOTIFICATION_STRATEGY); // 0x8256
InsertEnumString(GL_LAYER_PROVOKING_VERTEX); // 0x825E
InsertEnumString(GL_UNDEFINED_VERTEX); // 0x8260
InsertEnumString(GL_NO_RESET_NOTIFICATION); // 0x8261
InsertEnumString(GL_DEBUG_TYPE_MARKER); // 0x8268
InsertEnumString(GL_DEBUG_TYPE_PUSH_GROUP); // 0x8269
InsertEnumString(GL_DEBUG_TYPE_POP_GROUP); // 0x826A
InsertEnumString(GL_DEBUG_SEVERITY_NOTIFICATION); // 0x826B
InsertEnumString(GL_MAX_DEBUG_GROUP_STACK_DEPTH); // 0x826C
InsertEnumString(GL_DEBUG_GROUP_STACK_DEPTH); // 0x826D
InsertEnumString(GL_BUFFER); // 0x82E0
InsertEnumString(GL_SHADER); // 0x82E1
InsertEnumString(GL_PROGRAM); // 0x82E2
InsertEnumString(GL_QUERY); // 0x82E3
InsertEnumString(GL_PROGRAM_PIPELINE); // 0x82E4
InsertEnumString(GL_MAX_LABEL_LENGTH); // 0x82E8
InsertEnumString(GL_MAX_TESS_CONTROL_INPUT_COMPONENTS); // 0x886C
InsertEnumString(GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS); // 0x886D
InsertEnumString(GL_GEOMETRY_SHADER_INVOCATIONS); // 0x887F
InsertEnumString(GL_GEOMETRY_VERTICES_OUT); // 0x8916
InsertEnumString(GL_GEOMETRY_INPUT_TYPE); // 0x8917
InsertEnumString(GL_GEOMETRY_OUTPUT_TYPE); // 0x8918
InsertEnumString(GL_MAX_GEOMETRY_UNIFORM_BLOCKS); // 0x8A2C
InsertEnumString(GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS); // 0x8A32
InsertEnumString(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS); // 0x8C29
InsertEnumString(GL_TEXTURE_BUFFER); // 0x8C2A
InsertEnumString(GL_MAX_TEXTURE_BUFFER_SIZE); // 0x8C2B
InsertEnumString(GL_TEXTURE_BINDING_BUFFER); // 0x8C2C
InsertEnumString(GL_TEXTURE_BUFFER_DATA_STORE_BINDING); // 0x8C2D
InsertEnumString(GL_SAMPLE_SHADING); // 0x8C36
InsertEnumString(GL_MIN_SAMPLE_SHADING_VALUE); // 0x8C37
InsertEnumString(GL_PRIMITIVES_GENERATED); // 0x8C87
InsertEnumString(GL_FRAMEBUFFER_ATTACHMENT_LAYERED); // 0x8DA7
InsertEnumString(GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS); // 0x8DA8
InsertEnumString(GL_SAMPLER_BUFFER); // 0x8DC2
InsertEnumString(GL_INT_SAMPLER_BUFFER); // 0x8DD0
InsertEnumString(GL_UNSIGNED_INT_SAMPLER_BUFFER); // 0x8DD8
InsertEnumString(GL_GEOMETRY_SHADER); // 0x8DD9
InsertEnumString(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS); // 0x8DDF
InsertEnumString(GL_MAX_GEOMETRY_OUTPUT_VERTICES); // 0x8DE0
InsertEnumString(GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS); // 0x8DE1
InsertEnumString(GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS); // 0x8E1E
InsertEnumString(GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS); // 0x8E1F
InsertEnumString(GL_FIRST_VERTEX_CONVENTION); // 0x8E4D
InsertEnumString(GL_LAST_VERTEX_CONVENTION); // 0x8E4E
InsertEnumString(GL_MAX_GEOMETRY_SHADER_INVOCATIONS); // 0x8E5A
InsertEnumString(GL_MIN_FRAGMENT_INTERPOLATION_OFFSET); // 0x8E5B
InsertEnumString(GL_MAX_FRAGMENT_INTERPOLATION_OFFSET); // 0x8E5C
InsertEnumString(GL_FRAGMENT_INTERPOLATION_OFFSET_BITS); // 0x8E5D
InsertEnumString(GL_PATCH_VERTICES); // 0x8E72
InsertEnumString(GL_TESS_CONTROL_OUTPUT_VERTICES); // 0x8E75
InsertEnumString(GL_TESS_GEN_MODE); // 0x8E76
InsertEnumString(GL_TESS_GEN_SPACING); // 0x8E77
InsertEnumString(GL_TESS_GEN_VERTEX_ORDER); // 0x8E78
InsertEnumString(GL_TESS_GEN_POINT_MODE); // 0x8E79
InsertEnumString(GL_FRACTIONAL_ODD); // 0x8E7B
InsertEnumString(GL_FRACTIONAL_EVEN); // 0x8E7C
InsertEnumString(GL_MAX_PATCH_VERTICES); // 0x8E7D
InsertEnumString(GL_MAX_TESS_GEN_LEVEL); // 0x8E7E
InsertEnumString(GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS); // 0x8E7F
InsertEnumString(GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS); // 0x8E80
InsertEnumString(GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS); // 0x8E81
InsertEnumString(GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS); // 0x8E82
InsertEnumString(GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS); // 0x8E83
InsertEnumString(GL_MAX_TESS_PATCH_COMPONENTS); // 0x8E84
InsertEnumString(GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS); // 0x8E85
InsertEnumString(GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS); // 0x8E86
InsertEnumString(GL_TESS_EVALUATION_SHADER); // 0x8E87
InsertEnumString(GL_TESS_CONTROL_SHADER); // 0x8E88
InsertEnumString(GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS); // 0x8E89
InsertEnumString(GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS); // 0x8E8A
InsertEnumString(GL_TEXTURE_CUBE_MAP_ARRAY); // 0x9009
InsertEnumString(GL_TEXTURE_BINDING_CUBE_MAP_ARRAY); // 0x900A
InsertEnumString(GL_SAMPLER_CUBE_MAP_ARRAY); // 0x900C
InsertEnumString(GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW); // 0x900D
InsertEnumString(GL_INT_SAMPLER_CUBE_MAP_ARRAY); // 0x900E
InsertEnumString(GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY); // 0x900F
InsertEnumString(GL_IMAGE_BUFFER); // 0x9051
InsertEnumString(GL_IMAGE_CUBE_MAP_ARRAY); // 0x9054
InsertEnumString(GL_INT_IMAGE_BUFFER); // 0x905C
InsertEnumString(GL_INT_IMAGE_CUBE_MAP_ARRAY); // 0x905F
InsertEnumString(GL_UNSIGNED_INT_IMAGE_BUFFER); // 0x9067
InsertEnumString(GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY); // 0x906A
InsertEnumString(GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS); // 0x90CB
InsertEnumString(GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS); // 0x90CC
InsertEnumString(GL_MAX_GEOMETRY_IMAGE_UNIFORMS); // 0x90CD
InsertEnumString(GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS); // 0x90D7
InsertEnumString(GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS); // 0x90D8
InsertEnumString(GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS); // 0x90D9
InsertEnumString(GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY); // 0x9105
InsertEnumString(GL_SAMPLER_2D_MULTISAMPLE_ARRAY); // 0x910B
InsertEnumString(GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY); // 0x910C
InsertEnumString(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY); // 0x910D
InsertEnumString(GL_MAX_GEOMETRY_INPUT_COMPONENTS); // 0x9123
InsertEnumString(GL_MAX_GEOMETRY_OUTPUT_COMPONENTS); // 0x9124
InsertEnumString(GL_MAX_DEBUG_MESSAGE_LENGTH); // 0x9143
InsertEnumString(GL_MAX_DEBUG_LOGGED_MESSAGES); // 0x9144
InsertEnumString(GL_DEBUG_LOGGED_MESSAGES); // 0x9145
InsertEnumString(GL_DEBUG_SEVERITY_HIGH); // 0x9146
InsertEnumString(GL_DEBUG_SEVERITY_MEDIUM); // 0x9147
InsertEnumString(GL_DEBUG_SEVERITY_LOW); // 0x9148
InsertEnumString(GL_TEXTURE_BUFFER_OFFSET); // 0x919D
InsertEnumString(GL_TEXTURE_BUFFER_SIZE); // 0x919E
InsertEnumString(GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT); // 0x919F
InsertEnumString(GL_MULTIPLY); // 0x9294
InsertEnumString(GL_SCREEN); // 0x9295
InsertEnumString(GL_OVERLAY); // 0x9296
InsertEnumString(GL_DARKEN); // 0x9297
InsertEnumString(GL_LIGHTEN); // 0x9298
InsertEnumString(GL_COLORDODGE); // 0x9299
InsertEnumString(GL_COLORBURN); // 0x929A
InsertEnumString(GL_HARDLIGHT); // 0x929B
InsertEnumString(GL_SOFTLIGHT); // 0x929C
InsertEnumString(GL_DIFFERENCE); // 0x929E
InsertEnumString(GL_EXCLUSION); // 0x92A0
InsertEnumString(GL_HSL_HUE); // 0x92AD
InsertEnumString(GL_HSL_SATURATION); // 0x92AE
InsertEnumString(GL_HSL_COLOR); // 0x92AF
InsertEnumString(GL_HSL_LUMINOSITY); // 0x92B0
InsertEnumString(GL_PRIMITIVE_BOUNDING_BOX); // 0x92BE
InsertEnumString(GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS); // 0x92CD
InsertEnumString(GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS); // 0x92CE
InsertEnumString(GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS); // 0x92CF
InsertEnumString(GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS); // 0x92D3
InsertEnumString(GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS); // 0x92D4
InsertEnumString(GL_MAX_GEOMETRY_ATOMIC_COUNTERS); // 0x92D5
InsertEnumString(GL_DEBUG_OUTPUT); // 0x92E0
InsertEnumString(GL_IS_PER_PATCH); // 0x92E7
InsertEnumString(GL_REFERENCED_BY_TESS_CONTROL_SHADER); // 0x9307
InsertEnumString(GL_REFERENCED_BY_TESS_EVALUATION_SHADER); // 0x9308
InsertEnumString(GL_REFERENCED_BY_GEOMETRY_SHADER); // 0x9309
InsertEnumString(GL_FRAMEBUFFER_DEFAULT_LAYERS); // 0x9312
InsertEnumString(GL_MAX_FRAMEBUFFER_LAYERS); // 0x9317
InsertEnumString(GL_MULTISAMPLE_LINE_WIDTH_RANGE); // 0x9381
InsertEnumString(GL_MULTISAMPLE_LINE_WIDTH_GRANULARITY); // 0x9382
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_4x4); // 0x93B0
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_5x4); // 0x93B1
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_5x5); // 0x93B2
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_6x5); // 0x93B3
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_6x6); // 0x93B4
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_8x5); // 0x93B5
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_8x6); // 0x93B6
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_8x8); // 0x93B7
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_10x5); // 0x93B8
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_10x6); // 0x93B9
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_10x8); // 0x93BA
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_10x10); // 0x93BB
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_12x10); // 0x93BC
InsertEnumString(GL_COMPRESSED_RGBA_ASTC_12x12); // 0x93BD
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4); // 0x93D0
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4); // 0x93D1
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5); // 0x93D2
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5); // 0x93D3
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6); // 0x93D4
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5); // 0x93D5
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6); // 0x93D6
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8); // 0x93D7
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5); // 0x93D8
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6); // 0x93D9
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8); // 0x93DA
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10); // 0x93DB
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10); // 0x93DC
InsertEnumString(GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12); // 0x93DD
/* GL_OES_packed_depth_stencil */
// For glTex[Sub]Image2D
InsertEnumString(GL_DEPTH_STENCIL_OES);
InsertEnumString(GL_UNSIGNED_INT_24_8_OES);
// For renderbuffer storage
InsertEnumString(GL_DEPTH24_STENCIL8_OES);
/* GL_EXT_multisampled_render_to_texture */
InsertEnumString(GL_RENDERBUFFER_SAMPLES_EXT);
InsertEnumString(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT);
InsertEnumString(GL_MAX_SAMPLES_EXT);
/* GL_EXT_texture_format_BGRA8888 */
InsertEnumString(GL_BGRA_EXT);
InsertDrawEnumString(GL_LINES_ADJACENCY);
InsertDrawEnumString(GL_LINE_STRIP_ADJACENCY);
InsertDrawEnumString(GL_TRIANGLES_ADJACENCY);
InsertDrawEnumString(GL_TRIANGLE_STRIP_ADJACENCY);
InsertDrawEnumString(GL_ISOLINES);
//InsertDrawEnumString(GL_QUADS);
InsertDrawEnumString(GL_PATCHES);
InsertDrawEnumString(GL_POINTS);
InsertDrawEnumString(GL_LINES);
InsertDrawEnumString(GL_LINE_LOOP);
InsertDrawEnumString(GL_LINE_STRIP);
InsertDrawEnumString(GL_TRIANGLES);
InsertDrawEnumString(GL_TRIANGLE_STRIP);
InsertDrawEnumString(GL_TRIANGLE_FAN);
InsertDrawEnumString(GL_QUADS); //0x0007
InsertDrawEnumString(GL_BYTE);
InsertDrawEnumString(GL_UNSIGNED_BYTE);
InsertDrawEnumString(GL_SHORT);
InsertDrawEnumString(GL_UNSIGNED_SHORT);
InsertDrawEnumString(GL_INT);
InsertDrawEnumString(GL_UNSIGNED_INT);
// KHR_debug
InsertEnumString(GL_DEBUG_OUTPUT_KHR);
InsertEnumString(GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR);
InsertEnumString(GL_MAX_DEBUG_MESSAGE_LENGTH_KHR);
InsertEnumString(GL_MAX_DEBUG_LOGGED_MESSAGES_KHR);
InsertEnumString(GL_DEBUG_LOGGED_MESSAGES_KHR);
InsertEnumString(GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_KHR);
InsertEnumString(GL_MAX_DEBUG_GROUP_STACK_DEPTH_KHR);
InsertEnumString(GL_DEBUG_GROUP_STACK_DEPTH_KHR);
InsertEnumString(GL_MAX_LABEL_LENGTH_KHR);
InsertEnumString(GL_DEBUG_CALLBACK_FUNCTION_KHR);
InsertEnumString(GL_DEBUG_CALLBACK_USER_PARAM_KHR);
InsertEnumString(GL_DEBUG_SOURCE_API_KHR);
InsertEnumString(GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR);
InsertEnumString(GL_DEBUG_SOURCE_SHADER_COMPILER_KHR);
InsertEnumString(GL_DEBUG_SOURCE_THIRD_PARTY_KHR);
InsertEnumString(GL_DEBUG_SOURCE_APPLICATION_KHR);
InsertEnumString(GL_DEBUG_SOURCE_OTHER_KHR);
InsertEnumString(GL_DEBUG_TYPE_ERROR_KHR);
InsertEnumString(GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR);
InsertEnumString(GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR);
InsertEnumString(GL_DEBUG_TYPE_PORTABILITY_KHR);
InsertEnumString(GL_DEBUG_TYPE_PERFORMANCE_KHR);
InsertEnumString(GL_DEBUG_TYPE_OTHER_KHR);
InsertEnumString(GL_DEBUG_TYPE_MARKER_KHR);
InsertEnumString(GL_DEBUG_TYPE_PUSH_GROUP_KHR);
InsertEnumString(GL_DEBUG_TYPE_POP_GROUP_KHR);
InsertEnumString(GL_DEBUG_SEVERITY_HIGH_KHR);
InsertEnumString(GL_DEBUG_SEVERITY_MEDIUM_KHR);
InsertEnumString(GL_DEBUG_SEVERITY_LOW_KHR);
InsertEnumString(GL_DEBUG_SEVERITY_NOTIFICATION_KHR);
InsertEnumString(GL_STACK_UNDERFLOW);
InsertEnumString(GL_STACK_OVERFLOW);
InsertEnumString(GL_BUFFER_KHR);
InsertEnumString(GL_SHADER_KHR);
InsertEnumString(GL_PROGRAM_KHR);
InsertEnumString(GL_QUERY_KHR);
InsertEnumString(GL_PROGRAM_PIPELINE);
InsertEnumString(GL_SAMPLER);
sInitedEnumMap = true;
}
}
const char * EnumString(unsigned int enumToFind, const std::string &funName)
{
if ( !sInitedEnumMap ) InitEnumMap();
if (funName.compare(0, 3, "egl") == 0)
{
const auto& citer = sEglEnumMap.find(enumToFind);
if (citer != sEglEnumMap.end())
{
return citer->second;
}
}
if (funName.find("glBlend") != std::string::npos) // needs special handling
{
if (enumToFind == GL_ZERO)
{
return "GL_ZERO";
}
else if (enumToFind == GL_ONE)
{
return "GL_ONE";
}
}
if (funName.find("glTexParameter") != std::string::npos) // texturing, needs special handling
{
if (enumToFind == GL_NONE)
{
return "GL_NONE";
}
}
if (funName.find("glDraw") != std::string::npos)
{
const auto& citer = sDrawEnumMap.find(enumToFind);
if (citer != sDrawEnumMap.end())
{
return citer->second;
}
}
if (funName == "glGetError")
{
return "GL_NO_ERROR";
}
const auto& citer = sEnumMap.find(enumToFind);
if (citer != sEnumMap.end())
{
return citer->second;
}
return NULL;
}
const std::string Cube2D::asString() const
{
char buffer[128];
sprintf(buffer, "x:%d y:%d width:%d height:%d", x, y, width, height);
return buffer;
}
<|start_filename|>patrace/src/helper/depth_dumper.hpp<|end_filename|>
#include "../../thirdparty/opengl-registry/api/GLES3/gl31.h"
namespace image {
class Image;
}
class DepthDumper
{
public:
enum TexType
{
Tex2D = 0,
Tex2DArray,
TexCubemap,
TexCubemapArray,
TexEnd
};
~DepthDumper();
static const GLchar *depthCopyVSCode;
static const GLchar *depthCopyFSCode;
static const GLchar *depthArrayCopyFSCode;
static const GLchar *depthCopyCubeVSCode;
static const GLchar *depthCopyCubeFSCode;
static const GLchar *DS_dFSCode;
static const GLchar *DS_sFSCode;
GLint depthCopyVS, depthCopyCubeVS, depthCopyFS, depthCopyCubeFS, depthCopyCubeProgram, depthCopyProgram;
GLint DSCopy_dFS, DSCopy_sFS, depthDSCopyProgram, stencilDSCopyProgram;
GLint depthArrayCopyFS, depthArrayCopyProgram;
GLuint depthFBO, depthTexture;
GLuint depthVertexBuf, depthIndexBuf;
GLint cubemapIdLocation;
GLint layerIdxLocation;
void initializeDepthCopyer();
void get_depth_texture_image(GLuint sourceTexture, int width, int height, GLvoid *pixels, GLint internalFormat, TexType texType, int id);
};
| shihchinw/patrace |
<|start_filename|>Makefile<|end_filename|>
REPO=threathuntproj
IMAGE_NAME=hunting
# Point this to the full path of a directory you want to mount as your "work"
# volume inside the container. This will become "/home/jovyan/work" (Jupyter
# default value)
DATAVOL=$(HOME)
# change this to the local port on which you'd like to connect to the
# container. Usually you can just leave this as-is.
LOCALPORT=8888
build: Dockerfile refresh
docker build --build-arg JUPYTER_NB_PASS=$$JUPYTER_NB_PASS -t $(REPO)/$(IMAGE_NAME):dev .
refresh:
docker pull jupyter/pyspark-notebook
test:
@echo "\n************************"
@echo "Testing basic functionality with Python 3..."
docker run -v `pwd`:/home/jovyan/work $(REPO)/$(IMAGE_NAME):dev jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=60 --output /tmp/testoutput-py3.ipynb /home/jovyan/work/Test.ipynb
@echo "Testing Apache Spark support with Python 3..."
docker run -v `pwd`:/home/jovyan/work $(REPO)/$(IMAGE_NAME):dev jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=60 --output /tmp/testoutput-spark-py3.ipynb /home/jovyan/work/Test-spark.ipynb
run:
docker run -it -p $(LOCALPORT):8888 --user root -e GRANT_SUDO=yes -e GEN_CERT=yes -v $(DATAVOL):/home/jovyan/work $(REPO)/$(IMAGE_NAME):dev
run-lab:
docker run -it -p $(LOCALPORT):8888 --user root -e GRANT_SUDO=yes -e GEN_CERT=yes -e JUPYTER_ENABLE_LAB=yes -v $(DATAVOL):/home/jovyan/work $(REPO)/$(IMAGE_NAME):dev
| padfoot999/hunter |
<|start_filename|>additive_synthesis/additive_synthesis.js<|end_filename|>
var context = new AudioContext;
var Partial = function(context) {
this.context = context;
this.attackTime = 0.01;
this.decayTime = 0.01;
this.osc = context.createOscillator();
this.gain = context.createGain();
this.osc.connect(this.gain);
this.gain.connect(context.destination);
};
Partial.prototype.start = function() {
var now = this.context.currentTime
this.gain.gain.setValueAtTime(0, now);
this.osc.frequency.setValueAtTime(this.frequency, now);
this.gain.gain.linearRampToValueAtTime(this.amplitude, now + this.attackTime);
this.osc.start(now);
};
Partial.prototype.stop = function() {
var now = this.context.currentTime
this.gain.gain.setValueAtTime(this.gain.gain.value, now);
this.gain.gain.linearRampToValueAtTime(0, now + this.decayTime);
this.osc.stop(now + this.decayTime);
};
var Note = function(context, frequency, parameters) {
this.context = context;
this.frequency = frequency;
this.parameters = parameters;
this.partials = _.times(this.parameters.number_of_partials, function() {
return new Partial(this.context);
});
this.frequencies = _.map(this.parameters.partial_frequencies, function(f) {
return f * this.frequency
}, this);
this.amplitudes = this.parameters.partial_amplitudes;
_.each(this.partials, function(partial, index) {
partial.frequency = this.frequencies[index];
partial.amplitude = this.amplitudes[index];
}, this);
};
Note.prototype.start = function() {
_.map(this.partials, function(partial) { partial.start() });
};
Note.prototype.stop = function() {
_.map(this.partials, function(partial) { partial.stop() });
};
var AdditiveSynth = function(context, parameters) {
this.context = context;
this.notes = {};
this.parameters = parameters;
};
AdditiveSynth.prototype.noteOn = function(midi_note_number) {
var frequency = this.midiNoteNumberToFrequency(midi_note_number);
this.notes[midi_note_number] = new Note(this.context, frequency, this.parameters)
this.notes[midi_note_number].start();
};
AdditiveSynth.prototype.midiNoteNumberToFrequency = function(midi_note_number) {
var f_ref = 440;
var n_ref = 57;
var a = Math.pow(2, 1/12);
var n = midi_note_number - n_ref;
var f = f_ref * Math.pow(a, n);
return f;
};
AdditiveSynth.prototype.noteOff = function(midi_note_number) {
this.notes[midi_note_number].stop();
};
var SquareWave = {
number_of_partials: 6,
partial_frequencies: [1, 3, 5, 7, 9, 11],
partial_amplitudes: [1, 1/3, 1/5, 1/7, 1/9, 1/11]
}
var Bell = {
number_of_partials: 9,
partial_frequencies: [4.07, 3.76, 3, 2.74, 2, 1.71, 1.19, .92, .56],
partial_amplitudes: [1, 1, 1, 1, 1, 1, 1, 1, 1]
}
var SawTooth = {
number_of_partials: 6,
partial_frequencies: [1, 2, 3, 4, 5, 6],
partial_amplitudes: [1, 1/2, 1/3, 1/4, 1/5, 1/6]
}
window.onload = function() {
var saw = new AdditiveSynth(context, SawTooth);
var square = new AdditiveSynth(context, SquareWave);
var bell = new AdditiveSynth(context, Bell);
var synth = saw;
var keyboard = new Keyboard(document);
keyboard.onKeyDown = function(e) {
if (e.program) {
switch(e.program) {
case 1:
synth = saw;
break;
case 2:
synth = square;
break;
case 3:
synth = bell;
break;
}
} else {
synth.noteOn(e.midi);
}
}
keyboard.onKeyUp = function(e) {
synth.noteOff(e.midi);
}
};
<|start_filename|>keyboard/keyboard.js<|end_filename|>
var Keyboard = function(element) {
element.addEventListener("keydown", this.keydown.bind(this), false);
element.addEventListener("keyup", this.keyup.bind(this), false);
this.octave = 4;
};
Keyboard.prototype.keydown = function(e) {
if (e.repeat == false) {
if (e.keyCode == 188) {
this.octave -= 1;
};
if (e.keyCode == 190) {
this.octave += 1;
};
var note = this.keycodeToNote(e.keyCode);
if(note) { this.onKeyDown(note); };
};
};
Keyboard.prototype.keyup = function(e) {
if (e.repeat == false) {
var note = this.keycodeToNote(e.keyCode);
if (note) { this.onKeyUp(note); };
};
};
Keyboard.prototype.keycodeToNote = function(keycode) {
var map = {
49: {program: 1},
50: {program: 2},
51: {program: 3},
65: {pitch: 'C', octave: 0, step: 0},
87: {pitch: 'C#', octave: 0, step: 1},
83: {pitch: 'D', octave: 0, step: 2},
69: {pitch: 'D#', octave: 0, step: 3},
68: {pitch: 'E', octave: 0, step: 4},
70: {pitch: 'F', octave: 0, step: 5},
84: {pitch: 'F#', octave: 0, step: 6},
71: {pitch: 'G', octave: 0, step: 7},
89: {pitch: 'G#', octave: 0, step: 8},
72: {pitch: 'A', octave: 0, step: 9},
85: {pitch: 'A#', octave: 0, step: 10},
74: {pitch: 'B', octave: 0, step: 11},
75: {pitch: 'C', octave: 1, step: 0},
79: {pitch: 'C#', octave: 1, step: 1},
76: {pitch: 'D', octave: 1, step: 2},
80: {pitch: 'D#', octave: 1, step: 3},
186: {pitch: 'E', octave: 1, step: 4},
222: {pitch: 'F', octave: 1, step: 5},
221: {pitch: 'F#', octave: 1, step: 6},
220: {pitch: 'G', octave: 1, step: 7}
};
var note = map[keycode];
if (note && note.pitch) {
note.octave = note.octave + this.octave;
note.midi = note.step + (note.octave * 12);
return {pitch: note.pitch + note.octave, midi: note.midi};
} else if (note && note.program) {
return note;
} else {
return false;
};
};
<|start_filename|>subtractive_synthesis/subtractive_synthesis.js<|end_filename|>
var context = new AudioContext;
var SubtractiveSynth = function(context, parameters) {
this.context = context;
this.parameters = parameters;
this.setup();
};
SubtractiveSynth.prototype.setup = function() {
var ctx = this.context;
osc1 = ctx.createOscillator();
osc1.type = this.parameters.osc1type;
osc1.detune.value = this.parameters.osc1detune;
osc1.start();
osc2 = ctx.createOscillator();
osc2.type = this.parameters.osc2type;
osc2.detune.value = this.parameters.osc2detune;
osc2.start();
env = ctx.createGain();
env.gain.value = 0;
filter = ctx.createBiquadFilter();
filter.frequency.value = this.parameters.filterCutoff;
filter.type = 'lowpass';
osc1.connect(env);
osc2.connect(env);
env.connect(filter);
filter.connect(ctx.destination);
this.oscillators = [osc1, osc2];
this.envelope = env;
this.filter = filter;
};
SubtractiveSynth.prototype.noteOn = function(midi_note_number) {
this.setOscillatorFrequencies(midi_note_number);
this.triggerEnvelopeAttack();
this.triggerFilterAttack();
};
SubtractiveSynth.prototype.triggerEnvelopeAttack = function() {
var param = this.envelope.gain;
var now = this.context.currentTime;
param.cancelScheduledValues(now);
param.setValueAtTime(0, now);
param.linearRampToValueAtTime(1, now + this.parameters.attack);
};
SubtractiveSynth.prototype.triggerFilterAttack = function() {
var param = this.filter.frequency;
var now = this.context.currentTime;
if (this.parameters.filterAttack > 0) {
param.cancelScheduledValues(now);
param.setValueAtTime(param.value, now);
param.linearRampToValueAtTime(this.parameters.filterCutoff, now + this.parameters.filterAttack);
};
};
SubtractiveSynth.prototype.setOscillatorFrequencies = function(midi_note_number) {
var osc1freq = this.midiNoteNumberToFrequency(midi_note_number + this.parameters.osc1tune);
var osc2freq = this.midiNoteNumberToFrequency(midi_note_number + this.parameters.osc2tune);
var now = this.context.currentTime;
var osc1param = this.oscillators[0].frequency;
osc1param.cancelScheduledValues(now);
osc1param.setValueAtTime(osc1param.value, now);
osc1param.linearRampToValueAtTime(osc1freq, now + this.parameters.glideTime);
var osc2param = this.oscillators[1].frequency;
osc2param.cancelScheduledValues(now);
osc2param.setValueAtTime(osc2param.value, now);
osc2param.linearRampToValueAtTime(osc2freq, now + this.parameters.glideTime);
};
SubtractiveSynth.prototype.midiNoteNumberToFrequency = function(midi_note_number) {
var f_ref = 440;
var n_ref = 57;
var a = Math.pow(2, 1/12);
var n = midi_note_number - n_ref;
var f = f_ref * Math.pow(a, n);
return f;
};
SubtractiveSynth.prototype.noteOff = function(midi_note_number) {
var now = this.context.currentTime;
this.triggerEnvelopeRelease();
this.triggerFilterRelease();
};
SubtractiveSynth.prototype.triggerEnvelopeRelease = function() {
var param = this.envelope.gain;
var now = this.context.currentTime;
param.cancelScheduledValues(now);
param.setValueAtTime(param.value, now);
param.linearRampToValueAtTime(0, now + this.parameters.release);
};
SubtractiveSynth.prototype.triggerFilterRelease = function() {
var param = this.filter.frequency;
var now = this.context.currentTime;
if (this.parameters.filterDecay > 0) {
param.cancelScheduledValues(now);
param.setValueAtTime(param.value, now);
param.linearRampToValueAtTime(0, now + this.parameters.filterDecay);
};
};
var MellowLead = {
osc1type: 'square',
osc2type: 'sine',
osc1detune: -10,
osc2detune: +10,
glideTime: 0.02,
release: 0.35
}
var GrowlingBass = {
osc1type: 'square',
osc2type: 'sawtooth',
osc1tune: -24,
osc2tune: -9,
filterCutoff: 125,
filterDecay: 0.6,
release: 0.60
}
var Defaults = {
osc1type: 'square',
osc2type: 'square',
osc1tune: 0,
osc2tune: 0,
osc1detune: 0,
osc2detune: 0,
filterCutoff: context.sampleRate,
filterAttack: 0,
filterDecay: 0,
glideTime: 0,
attack: 0,
release: 0
}
window.onload = function() {
var synth = new SubtractiveSynth(context, _.defaults(MellowLead, Defaults));
var keyboard = new Keyboard(document);
keyboard.onKeyDown = function(e) {
synth.noteOn(e.midi);
}
keyboard.onKeyUp = function(e) {
synth.noteOff(e.midi);
}
};
<|start_filename|>theremin/theremin.js<|end_filename|>
var context = new AudioContext;
var Theremin = function(context) {
this.context = context;
};
Theremin.prototype.playNote = function(note) {
var now = this.context.currentTime;
var param = this.oscillator.frequency;
param.cancelScheduledValues(now);
param.setValueAtTime(param.value, now);
param.linearRampToValueAtTime(note, now + 0.01);
};
Theremin.prototype.start = function() {
this.setup();
this.oscillator.start();
};
Theremin.prototype.stop = function() {
this.oscillator.stop();
};
Theremin.prototype.setup = function() {
this.oscillator = this.context.createOscillator();
this.oscillator.type = 'sine';
this.gain = this.context.createGain();
this.oscillator.connect(this.gain);
this.gain.connect(this.context.destination);
};
Theremin.prototype.setVolume = function(volume) {
var now = this.context.currentTime;
var param = this.gain.gain;
param.cancelScheduledValues(now);
param.setValueAtTime(param.value, now);
param.linearRampToValueAtTime(volume, now + 0.01);
};
var relativePosition = function(event) {
var x = event.clientX;
var y = event.clientY;
var maxX = document.documentElement.clientWidth;
var maxY = document.documentElement.clientHeight;
return { x: x/maxX, y: y/maxY }
};
var controlTheremin = function(theremin, event) {
var parameters = relativePosition(event);
var frequency = parameters.x * 1000;
var volume = parameters.y;
theremin.playNote(frequency);
theremin.setVolume(volume);
};
window.onload = function() {
var theremin = new Theremin(context);
var keyboard = new Keyboard(document);
var body = document.getElementsByTagName("body")[0];
body.addEventListener("mousemove", function(event) {
controlTheremin(theremin, event);
});
var playing = false;
keyboard.onKeyDown = function(e) {
if(playing == true) {
theremin.stop();
playing = false;
} else {
theremin.start();
playing = true;
}
};
};
<|start_filename|>granular/granular.js<|end_filename|>
var context = new AudioContext;
var Grain = function(context, data, output) {
this.context = context;
this.data = data;
this.output = output;
this.setup();
};
Grain.prototype.setup = function() {
var N = this.data.length;
this.buffer = this.context.createBuffer(1, N, this.context.sampleRate);
var buffer_data = this.buffer.getChannelData(0);
for (var i = 0; i < N; i++) {
// Hann window
window_fn = 0.5 * (1 - Math.cos(2 * Math.PI * i / (N - 1)));
buffer_data[i] = this.data[i] * window_fn;
}
};
Grain.prototype.trigger = function(time) {
var source = this.context.createBufferSource();
source.buffer = this.buffer;
source.connect(this.output);
source.start(time);
};
var GranularSynth = function(context, url, params) {
this.context = context;
this.loadSample(url);
this.output = context.createDynamicsCompressor();
this.output.connect(context.destination);
this.grainsPerSecond = params.grainsPerSecond;
this.grainLength = params.grainLength;
this.walkProbability = params.walkProbability;
};
GranularSynth.prototype.loadSample = function(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function() {
this.context.decodeAudioData(request.response, function(buffer) {
this.buffer = buffer;
this.createGrains();
}.bind(this));
}.bind(this);
request.send();
};
GranularSynth.prototype.createGrains = function() {
var rawData = this.buffer.getChannelData(0);
var chunks = _.chunk(rawData, this.grainLength);
this.grains = chunks.map(function(data) {
return new Grain(this.context, data, this.output)
}.bind(this) );
this.ready();
};
GranularSynth.prototype.stop = function() {
clearInterval(this.scheduler);
};
GranularSynth.prototype.play = function() {
var scheduleAheadTime = 1;
var nextGrainTime = this.context.currentTime;
var grainIndex = 25;
this.scheduler = setInterval(function() {
while (nextGrainTime < this.context.currentTime + scheduleAheadTime ) {
if (Math.random() < this.walkProbability) {
if (Math.random() > 0.5) {
grainIndex = Math.min(this.grains.length - 1, grainIndex + 1);
} else {
grainIndex = Math.max(0, grainIndex - 1);
}
}
nextGrainTime += 1 / this.grainsPerSecond;
this.grains[grainIndex].trigger(nextGrainTime);
}
}.bind(this), 250);
};
window.onload = function() {
var fastSynth = new GranularSynth(context, '/short.wav', {grainsPerSecond: 10, grainLength: 4000, walkProbability: 0.5});
var slowSynth = new GranularSynth(context, '/short.wav', {grainsPerSecond: 40, grainLength: 40000, walkProbability: 1});
var keyboard = new Keyboard(document);
var playing = false;
var synth = fastSynth;
synth.ready = function() {
keyboard.onKeyDown = function(e) {
if (e.program) {
switch(e.program) {
case 1:
synth = fastSynth;
break;
case 2:
synth = slowSynth;
break;
}
} else {
if(playing == true) {
synth.stop();
playing = false;
} else {
synth.play();
playing = true;
}
}
}
}
};
<|start_filename|>sampler/sampler.js<|end_filename|>
var context = new AudioContext;
var Voice = function(context, buffer, offset) {
this.context = context;
this.buffer = buffer;
this.offset = offset;
};
Voice.prototype.start = function() {
this.source = this.context.createBufferSource();
this.source.loop = true;
this.source.buffer = this.buffer;
this.source.connect(this.context.destination);
this.source.start(0, this.offset);
};
Voice.prototype.stop = function() {
this.source.stop();
};
var SamplingSynth = function(context, parameters) {
this.context = context;
this.notes = {};
this.parameters = parameters;
this.loadSample(parameters.url);
};
SamplingSynth.prototype.loadSample = function(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function() {
this.context.decodeAudioData(request.response, function(buffer) {
this.buffer = buffer;
this.ready();
}.bind(this));
}.bind(this);
request.send();
};
SamplingSynth.prototype.noteOn = function(midi_note_number) {
var offset = this.parameters.offsets[midi_note_number];
this.notes[midi_note_number] = new Voice(this.context, this.buffer, offset);
this.notes[midi_note_number].start();
};
SamplingSynth.prototype.noteOff = function(midi_note_number) {
this.notes[midi_note_number].stop();
};
var Amen = {
url: '/amen.wav',
offsets: {
48: 0,
50: 0.431,
52: 1.091,
53: 1.536,
55: 2.175,
57: 2.643,
59: 4.587,
60: 5.671,
62: 6.317
}
}
window.onload = function() {
var synth = new SamplingSynth(context, Amen);
var keyboard = new Keyboard(document);
synth.ready = function() {
console.log('ready');
keyboard.onKeyDown = function(e) {
synth.noteOn(e.midi);
}
keyboard.onKeyUp = function(e) {
synth.noteOff(e.midi);
}
};
};
<|start_filename|>fm_synthesis/fm_synthesis.js<|end_filename|>
var context = new AudioContext;
var Voice = function(context, frequency, parameters) {
this.context = context;
this.modulatingOsc = context.createOscillator()
this.modulatingOscGain = context.createGain();
this.carrierOsc = context.createOscillator();
this.carrierOscGain = context.createGain();
this.modulatingOsc.connect(this.modulatingOscGain);
this.modulatingOscGain.connect(this.carrierOsc.frequency);
this.carrierOsc.connect(this.carrierOscGain);
this.carrierOscGain.connect(context.destination);
this.modulationIndex = parameters.modulationIndex;
this.modulationFrequency = frequency / parameters.carrierModulationRatio;
this.modulatingOsc.frequency.value = this.modulationFrequency;
this.carrierOsc.frequency.value = frequency;
};
Voice.prototype.on = function() {
this.modulatingOsc.start();
this.carrierOsc.start();
this.triggerCarrierEnvelope();
this.triggerSpectralEnvelope();
};
Voice.prototype.triggerCarrierEnvelope = function() {
var param = this.carrierOscGain.gain;
var now = this.context.currentTime;
param.cancelScheduledValues(now);
param.setValueAtTime(0, now);
param.linearRampToValueAtTime(1, now + 0.2);
param.linearRampToValueAtTime(0.7, now + 0.3);
param.setValueAtTime(0.7, now + 0.5);
param.linearRampToValueAtTime(0, now + 0.6);
};
Voice.prototype.triggerSpectralEnvelope = function() {
var param = this.modulatingOscGain.gain;
var now = this.context.currentTime;
var A = this.modulationIndex * this.modulationFrequency;
param.cancelScheduledValues(now);
param.setValueAtTime(0, now);
param.linearRampToValueAtTime(A, now + 0.2);
param.linearRampToValueAtTime(A * 0.8, now + 0.3);
param.setValueAtTime(A * 0.8, now + 0.5);
param.linearRampToValueAtTime(0, now + 0.6);
};
Voice.prototype.off = function() {
this.modulatingOsc.stop();
this.carrierOsc.stop();
};
var FmSynth = function(context, parameters) {
this.context = context;
this.voices = {};
this.parameters = parameters;
};
FmSynth.prototype.noteOn = function(midi_note_number) {
var frequency = this.midiNoteNumberToFrequency(midi_note_number);
this.voices[midi_note_number] = new Voice(this.context, frequency, this.parameters)
this.voices[midi_note_number].on();
};
FmSynth.prototype.midiNoteNumberToFrequency = function(midi_note_number) {
var f_ref = 440;
var n_ref = 57;
var a = Math.pow(2, 1/12);
var n = midi_note_number - n_ref;
var f = f_ref * Math.pow(a, n);
return f;
};
FmSynth.prototype.noteOff = function(midi_note_number) {
this.voices[midi_note_number].off();
};
var params = {
carrierModulationRatio: 1,
modulationIndex: 10
};
window.onload = function() {
var synth = new FmSynth(context, params);
var keyboard = new Keyboard(document);
keyboard.onKeyDown = function(e) {
synth.noteOn(e.midi);
}
keyboard.onKeyUp = function(e) {
synth.noteOff(e.midi);
}
};
| purplecabbage/synth_history |
<|start_filename|>docs/index.html<|end_filename|>
<!doctype html>
<html lang="en">
<!-- === Header Starts === -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Efficient Learning of Safe Driving Policy via Human-AI Copilot Optimization</title>
<link href="./assets/bootstrap.min.css" rel="stylesheet">
<link href="./assets/font.css" rel="stylesheet" type="text/css">
<link href="./assets/style.css" rel="stylesheet" type="text/css">
<script src="./assets/jquery.min.js"></script>
<script type="text/javascript" src="assets/corpus.js"></script>
</head>
<!-- === Header Ends === -->
<script>
var lang_flag = 1;
</script>
<body>
<!-- === Home Section Starts === -->
<div class="section">
<!-- === Title Starts === -->
<div class="header">
<!-- <div class="logo">-->
<!-- <a href="https://decisionforce.github.io/" target="_blank">-->
<!-- <img src="images/deciforce.png">-->
<!-- </a>-->
<!-- </div>-->
<!-- <div style="padding-top: 30pt; margin: 0 50pt;" class="title" id="lang">-->
<!-- Safe Driving via Expert Guided Policy Optimization-->
<!-- </div>-->
<table>
<tr>
<td>
<!--
<div class="logo"
style="
width: 100pt;
vertical-align: text-top;
text-align: center;
">
<a href="https://decisionforce.github.io/" target="_blank">
<img src="images/deciforce.png">
</a>
</div>-->
</td>
<td>
<div style="padding-top: 10pt;" class="title" id="lang">
Efficient Learning of Safe Driving Policy via Human-AI Copilot Optimization
</div>
</td>
<td>
<!--
<div class="logo"
style="
width: 100pt;
padding-top: 10pt;
vertical-align: center;
text-align: center;
">
<a href="https://github.com/decisionforce/metadrive" target="_blank">
<img style=" width: 120pt;" src="images/metadrive.png">
</a>
</div>
-->
</td>
</tr>
</table>
</div>
<!-- === Title Ends === -->
<div class="author">
<p style="text-align:center">International Conference on Learning Representations (ICLR) 2022</p>
<a href="https://Quanyili.github.io"><NAME></a><sup>1</sup>*,
<a href="https://pengzhenghao.github.io" target="_blank"><NAME></a><sup>2</sup>*,
<a href="http://bzhou.ie.cuhk.edu.hk" target="_blank"><NAME></a><sup>3</sup>
</div>
<div class="institution" style="font-size: 11pt;">
<div>
<sup>2</sup>The Chinese University of Hong Kong,
<!-- <sup>2</sup>SenseTime Research <br>-->
<sup>1</sup>Centre for Perceptual and Interactive Intelligence<br>
<sup>3</sup>University of California, Los Angeles<br>
</div>
</div>
<table border="0" align="center">
<tr>
<td align="center" style="padding: 0pt 0 15pt 0">
<a class="bar" href="https://decisionforce.github.io/HACO"><b>Webpage</b></a> |
<a class="bar" href="https://github.com/decisionforce/HACO"><b>Code</b></a> |
<!-- <a class="bar" href="images/egpo_poster.png"><b>Poster</b></a> |-->
<a class="bar" href="#video"><b>Video</b></a> |
<a class="bar" href="#talk"><b>Talk</b></a> |
<a class="bar" href="https://openreview.net/pdf?id=0cgU-BZp2ky"><b>Paper</b></a> |
<a class="bar" href="https://github.com/decisionforce/HACO/blob/main/docs/iclr_poster.pdf"><b>Poster</b></a>
</td>
</tr>
</table>
</div>
<!-- === Home Section Ends === -->
<!--<div class="section">-->
<!-- <!– <div class="title" id="lang">Demonstrative Videos</div>–>-->
<!-- <div align="center">-->
<!-- <table width="90%" style="margin: -20pt -5pt; text-align: center;">-->
<!-- <tr>-->
<!-- <td>-->
<!-- <video style="display:block; width:98%; height:auto; "-->
<!-- autoplay="autoplay" muted loop="loop" playsinline>-->
<!-- <source src="https://raw.githubusercontent.com/decisionforce/archive/master/EGPO/egpo_vs_ppo.mp4"-->
<!-- type="video/mp4"/>-->
<!-- </video>-->
<!-- <div style="top: -10%;">EGPO-trained agent exhibits safer driving behaviors than the PPO agent and obtains much lower cost.</div><br>-->
<!-- </td>-->
<!-- </tr>-->
<!-- <!– </table>–>-->
<!-- <!– <br>–>-->
<!-- <!– <br>–>-->
<!-- <!– <table width="95%" style="margin: 0 0; text-align: center;">–>-->
<!-- <!– <tr>–>-->
<!-- <!– <td>–>-->
<!-- <!– <video style="display:block; width:98%; height:auto;"–>-->
<!-- <!– autoplay="autoplay" controls muted loop="loop">–>-->
<!-- <!– <source src="https://raw.githubusercontent.com/decisionforce/archive/master/EGPO/egpo_showtime.mp4"–>-->
<!-- <!– type="video/mp4"/>–>-->
<!-- <!– </video>–>-->
<!-- <!– </td>–>-->
<!-- <!– </tr>–>-->
<!-- <!– <tr>–>-->
<!-- <!– <td>–>-->
<!-- <!– The behaviors of EGPO-trained agents.–>-->
<!-- <!– </td>–>-->
<!-- <!– </tr>–>-->
<!-- </table>-->
<!-- </div>-->
<!--</div>-->
<!-- === Overview Section Starts === -->
<div class="section">
<div class="title" id="lang">Human-AI Copilot Optimization (HACO)</div>
<div class="body">
<div class="teaser">
<img src="images/framework.jpg">
<div class="text">
<br>
Fig. 1 Framework </div>
</div>
<div class="text">
<p>
We develop an efficient <b>Human-AI Copilot Optimization method (HACO)</b>, which incorporate human into
the Reinforcement Learning (RL) training loop to boost the learning efficiency and ensure the safety.
Sidestepping the requirement of complex reward engineering, HACO injects the human knowledge extracted
from partial demonstration into the proxy value function by Offline RL technique. On the other hand,
entropy regularization and intervention minimization are used for encouraging exploration and saving
human budget respectively.
The comprehensive experiments show the superior sample efficiency and safety guarantee of the proposed
method.
</p>
</div>
</div>
</div>
<!-- === Result Section Starts === -->
<div class="section">
<div class="title" id="lang">Experiment Result</div>
<div class="body">
<div class="teaser"><img
src="images/haco_exp.jpg">
<div class="text">
<br>
Fig. 2 Learning Dynamics </div>
</div>
<div class="text">
The experiments conducted on <a href="https://github.com/decisionforce/metadrive">MetaDrive Simulator</a>
show the efficient training as well as the low safety violation, when compared with RL, Offline RL,
Imitation Learning and human-in-the-loop baselines. Results are reported in the Table 1.
Compared to other data-hungry baselines, HACO utilizes less transitions and achieve highest success rate.
Also, with the human protection, HACO yields only 30.14 total safety violations in the whole
training process, two orders of magnitude less than other RL baselines, even though HACO access neither
the cost or reward signal.
In the human-in-the-loop paradigm, another concern is the expensive human budget consuming.
As shown in Fig. 2 <b>B</b>., expensive human budget decreases along with the training.
</div>
<div class="teaser">
<div class="text">
Table. 1 Comparison results
<br>
</div>
<img
src="images/exp_table.png">
</div>
</div>
</div>
</div>
<!-- === Result Section Ends === -->
<div class="section">
<div class="title" id="talk">Talk</div>
<div class="text">
<br>
<p>
We summarize our core technical comtribution in this talk.
</p>
</div>
<div class="body">
<div class="vedio" style="position: relative; padding-top: 2%; margin: 0pt auto; text-align: center;">
<iframe width="900" height="506" src="https://www.youtube.com/embed/PiJv4wtp8T8"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</div>
</div>
</div>
<div class="section">
<div class="title" id="video">Demo Video</div>
<div class="text">
<br>
<p>
HACO is tested on <a href="https://github.com/decisionforce/metadrive">MetaDrive Simulator</a>, which is
efficient and allows generating various scenarios. Here, we provide the full training process of HACO and
compare it with RL, IL and Offline RL baselines. As a result, HACO achieves superior sample efficiency
with safety guarantee and outperform all baselines.
</p>
</div>
<div class="body">
<div class="vedio" style="position: relative; padding-top: 2%; margin: 0pt auto; text-align: center;">
<iframe width="900" height="506" src="https://www.youtube.com/embed/Mp37zErSXwk"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</div>
</div>
</div>
<div class="section">
<div class="title" id="video_carla">Benchmark HACO on CARLA</div>
<div class="text">
<br>
<p>
Furthermore, we benchmark HACO on <a href=https://github.com/carla-simulator/carla>CARLA Simulator</a>,
where agent takes semantic top-down view as observation. Equipped with 3-layer convolution neural network,
HACO agent learns not only the feature extractor but the driving policy with human involvement in 10 minutes.
</p>
</div>
<div class="body">
<div class="vedio" style="position: relative; padding-top: 2%; margin: 0pt auto; text-align: center;">
<iframe width="900" height="506" src="https://www.youtube.com/embed/vm-Cog-9feY"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</div>
</div>
</div>
<!-- === Reference Section Starts === -->
<div class="section">
<div class="bibtex">
<div class="text">Reference</div>
</div>
<!-- If you find this work useful in your project, please consider to cite it through:-->
<pre>
@inproceedings{
li2022efficient,
title={Efficient Learning of Safe Driving Policy via Human-AI Copilot Optimization},
author={<NAME> and <NAME> and <NAME>},
booktitle={International Conference on Learning Representations},
year={2022},
url={https://openreview.net/forum?id=0cgU-BZp2ky}
}
</pre>
<!-- Adjust the frame size based on the demo (Every project differs). -->
</div>
</body>
</html>
| decisionforce/HACO |
<|start_filename|>GRStarsView/Classes/GRStarView.h<|end_filename|>
//
// GRStarView.h
// GroooSource
//
// Created by Assuner on 2017/5/10.
// Copyright © 2017年 Assuner. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface GRStarView : UIView
@property (nonatomic, assign) CGFloat lightPercent;
@end
<|start_filename|>Example/Pods/Target Support Files/GRStarsView/GRStarsView-umbrella.h<|end_filename|>
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "GRStarsView.h"
#import "GRStarView.h"
FOUNDATION_EXPORT double GRStarsViewVersionNumber;
FOUNDATION_EXPORT const unsigned char GRStarsViewVersionString[];
<|start_filename|>Example/GRStarsView/GRAppDelegate.h<|end_filename|>
//
// GRAppDelegate.h
// GRStarsView
//
// Created by Assuner-Lee on 05/11/2017.
// Copyright (c) 2017 Assuner-Lee. All rights reserved.
//
@import UIKit;
@interface GRAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
<|start_filename|>GRStarsView/Classes/GRStarsView.h<|end_filename|>
//
// GRStarsView.h
// GroooSource
//
// Created by Assuner on 2017/5/10.
// Copyright © 2017年 Assuner. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef void (^GRTouchedActionBlock)(CGFloat score);
@interface GRStarsView : UIView
@property (nonatomic, assign) BOOL allowSelect;
@property (nonatomic, assign) CGFloat score;
@property (nonatomic, assign) BOOL allowDecimal;
@property (nonatomic, assign) BOOL allowDragSelect;
@property (nonatomic, copy) GRTouchedActionBlock touchedActionBlock;
- (instancetype)initWithStarSize:(CGSize)size margin:(CGFloat)margin numberOfStars:(NSInteger)number;
@end
<|start_filename|>Example/GRStarsView/GRViewController.h<|end_filename|>
//
// GRViewController.h
// GRStarsView
//
// Created by Assuner-Lee on 05/11/2017.
// Copyright (c) 2017 Assuner-Lee. All rights reserved.
//
@import UIKit;
@interface GRViewController : UIViewController
@end
| zgbilltalent/GRStarsView |
<|start_filename|>fixScript.js<|end_filename|>
var p = fetch('https://starwarsopening.firebaseio.com/openings.json');
p.then(function(data){
return data.json();
}).then(function(data){
var keys = Object.keys(data);
var c = 0;
for(var i=0;i<keys.length;i++){
var k = keys[i];
var obj = data[k];
if(obj.text == "321321321"){
c++;
var fb = new Firebase('https://starwarsopening.firebaseio.com/openings/'+k);
//fb.on("value", function(snapshot) {
// var o = snapshot.val();
// console.log(o);
//});
fb.remove();
}
}
console.log(c);
});
// count script
var p = fetch('https://starwarsopening.firebaseio.com/openings.json');
p.then(function(data){
return data.json();
}).then(function(data){
var keys = Object.keys(data);
console.log(keys.length);
});
<|start_filename|>public/bb8.css<|end_filename|>
.bb8 {
width: 20em;
height: 28em;
margin-top: -14em;
top: 50%;
left: 50%;
margin-left: -10em;
position: absolute;
-moz-animation: bump 0.1s infinite linear alternate;
-webkit-animation: bump 0.1s infinite linear alternate;
animation: bump 0.1s infinite linear alternate;
}
.bb8-top {
height: 8em;
width: 12em;
margin: 0 auto;
position: relative;
}
.bb8-head {
background: #f3f2f2;
height: 8em;
width: 12em;
z-index: 99;
position: absolute;
top: 1.6em;
-moz-border-radius: 15em 15em 85% 85%;
-webkit-border-radius: 15em;
border-radius: 15em 15em 85% 85%;
overflow: hidden;
border-bottom: 0.5em solid #dbd7d7;
}
.bb8-head:after {
background: transparent;
border: 0.5em #959fa3 solid;
width: 20em;
height: 10em;
left: 50%;
position: absolute;
bottom: .2em;
margin-left: -10.25em;
display: block;
content: "";
-moz-border-radius: 85%;
-webkit-border-radius: 85%;
border-radius: 85%;
}
.orange-stripe {
background: transparent;
border: 0.5em #db7c2e solid;
width: 20em;
height: 10em;
left: 50%;
position: absolute;
bottom: .6em;
margin-left: -10.25em;
-moz-border-radius: 85%;
-webkit-border-radius: 85%;
border-radius: 85%;
}
.orange-stripe:before {
display: block;
content: "";
background: #f3f2f2;
position: absolute;
width: 7em;
height: 2em;
bottom: -1em;
left: 50%;
margin-left: -2.5em;
}
.hat {
background: #959fa3;
height: 4em;
width: 8em;
position: absolute;
top: -2em;
right: 50%;
margin-right: -4em;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
}
.hat:before {
background: #f3f2f2;
height: 2em;
width: 4em;
content: '';
display: block;
position: absolute;
top: 1em;
left: 50%;
margin-left: -2em;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
}
.hat:after {
background: transparent;
border: 0.5em #db7c2e solid;
content: '';
display: block;
position: absolute;
z-index: 1;
height: 4.5em;
width: 9em;
left: 50%;
margin-left: -5em;
top: 50%;
margin-top: -2.75em;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
}
.eye {
height: 2.5em;
width: 2.5em;
background: #323c48;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
position: absolute;
top: 50%;
right: 12%;
-moz-transform: scale(0.65);
-ms-transform: scale(0.65);
-webkit-transform: scale(0.65);
transform: scale(0.65);
}
.eye:before {
border: 0.2em #f3f2f2 solid;
background: #08060d;
height: 2em;
width: 2em;
position: absolute;
content: '';
display: block;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
left: 50%;
top: 50%;
margin-left: -1em;
margin-top: -1em;
}
.eye:after {
background: white;
height: .25em;
width: .25em;
left: 1em;
bottom: .55em;
content: '';
display: block;
position: absolute;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
-webkit-filter: blur(0.15em);
filter: blur(0.15em);
}
.eye-large {
height: 3.5em;
width: 3.5em;
background: #323c48;
border: 0.25em solid #f3f2f2;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
position: absolute;
top: 25%;
left: 50%;
margin-left: -2em;
z-index: 100;
}
.eye-large:before {
background: #08060d;
height: 2.75em;
width: 2.75em;
position: absolute;
content: '';
display: block;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
left: 50%;
top: 50%;
margin-left: -1.375em;
margin-top: -1.375em;
}
.eye-large:after {
background: #ee2f22;
height: 1em;
width: 1em;
left: 1em;
bottom: 1em;
content: '';
display: block;
position: absolute;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
-webkit-filter: blur(0.15em);
filter: blur(0.15em);
opacity: 0.5;
}
.bb8-antena {
background: #f3f2f2;
width: .25em;
height: 2em;
-moz-border-radius: 100%;
-webkit-border-radius: 100%;
border-radius: 100%;
position: absolute;
top: 0;
left: 50%;
margin-left: -.5em;
}
.bb8-antena-2 {
background: #f3f2f2;
width: .25em;
height: 5em;
-moz-border-radius: 100%;
-webkit-border-radius: 100%;
border-radius: 100%;
position: absolute;
top: -2em;
left: 50%;
margin-left: .75em;
overflow: hidden;
}
.bb8-antena-2:before {
display: block;
content: '';
width: 1em;
background: #181e2c;
height: 1em;
}
.bb8-antena-2:after {
display: block;
content: '';
width: 1em;
background: #181e2c;
height: .8em;
position: absolute;
bottom: .75em;
}
.bb8-body {
background: #f3f2f2;
width: 20em;
height: 20em;
overflow: hidden;
position: relative;
-moz-border-radius: 20em;
-webkit-border-radius: 20em;
border-radius: 20em;
-moz-animation: spin 1s infinite linear;
-webkit-animation: spin 1s infinite linear;
animation: spin 1s infinite linear;
}
div[class^=panel-] {
width: 11em;
height: 11em;
background: #db7c2e;
-moz-border-radius: 11em;
-webkit-border-radius: 11em;
border-radius: 11em;
position: absolute;
}
div[class^=panel-]:before {
height: 8em;
width: 8em;
-moz-border-radius: 11em;
-webkit-border-radius: 11em;
border-radius: 11em;
background: #f3f2f2;
display: block;
content: '';
left: 50%;
top: 50%;
margin-top: -4em;
margin-left: -4em;
position: absolute;
}
.panel-1 {
top: -8em;
left: -3em;
}
.panel-2 {
bottom: -2em;
left: -8em;
}
.panel-3 {
right: 1em;
bottom: -8em;
-moz-transform: rotate(-20deg);
-ms-transform: rotate(-20deg);
-webkit-transform: rotate(-20deg);
transform: rotate(-20deg);
}
.panel-4 {
right: -7em;
top: -1em;
-moz-transform: rotate(20deg);
-ms-transform: rotate(20deg);
-webkit-transform: rotate(20deg);
transform: rotate(20deg);
}
.panel-5 {
top: 4em;
left: 4em;
-moz-transform: rotate(20deg);
-ms-transform: rotate(20deg);
-webkit-transform: rotate(20deg);
transform: rotate(20deg);
}
div[class^=inset-] {
width: 2em;
height: 8em;
position: absolute;
left: 50%;
top: 50%;
margin-top: -4em;
margin-left: -1em;
}
div[class^=inset-]:before {
position: absolute;
top: 0;
display: block;
content: '';
border-top: 2em solid #db7c2e;
border-left: .5em solid transparent;
border-right: .5em solid transparent;
height: 0;
width: 1em;
}
div[class^=inset-]:after {
position: absolute;
bottom: 0;
display: block;
content: '';
border-bottom: 2em solid #db7c2e;
border-left: .5em solid transparent;
border-right: .5em solid transparent;
height: 0;
width: 1em;
}
.plating {
background: #959fa3;
height: 3.5em;
width: 3.5em;
position: absolute;
left: 50%;
top: 50%;
margin-left: -1.75em;
margin-top: -1.75em;
overflow: hidden;
-moz-border-radius: 2em;
-webkit-border-radius: 2em;
border-radius: 2em;
}
.plating:before {
height: 6em;
width: 2.7em;
content: '';
display: block;
position: absolute;
top: -1em;
right: -1.3em;
background: #f3f2f2;
}
.inset-1 {
-moz-transform: rotate(90deg);
-ms-transform: rotate(90deg);
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
}
@-moz-keyframes spin {
100% {
-moz-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-webkit-keyframes spin {
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes spin {
100% {
-moz-transform: rotate(360deg);
-ms-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-moz-keyframes bump {
100% {
margin-top: -13.8em;
}
}
@-webkit-keyframes bump {
100% {
margin-top: -13.8em;
}
}
@keyframes bump {
100% {
margin-top: -13.8em;
}
}
<|start_filename|>public/StarWars.js<|end_filename|>
/*
http://codepen.io/TimPietrusky/pen/eHGfj
* Star Wars opening crawl from 1977
*
* I freaking love Star Wars, but could not find
* a web version of the original opening crawl from 1977.
* So I created this one.
*
* I wrote an article where I explain how this works:
* http://timpietrusky.com/star-wars-opening-crawl-from-1977
*
* Watch the Start Wars opening crawl on YouTube.
* http://www.youtube.com/watch?v=7jK-jZo6xjY
*
* Stuff I used:
* - CSS (animation, transform)
* - HTML audio (the opening theme)
* - SVG (the Star Wars logo from wikimedia.org)
* http://commons.wikimedia.org/wiki/File:Star_Wars_Logo.svg
* - JavaScript (to sync the animation/audio)
*
* Thanks to <NAME> for his amazing article
* which helped me to create this remake of the Star Wars opening crawl.
* http://www.sitepoint.com/css3-starwars-scrolling-text/
*
* Sound copyright by The Walt Disney Company.
*
*
* 2013 by <NAME>
* timpietrusky.com
*
*/
StarWarsOpening = (function() {
/*
* Constructor
*/
function StarWarsOpening(args) {
// Context wrapper
this.el = $(args.el);
// Audio to play the opening crawl
this.audio = this.el.find('audio').get(0);
this.audioDefer = $.Deferred();
var that = this;
this.audio.oncanplaythrough = function() {
that.audioDefer.resolve();
};
// Start the animation
this.start = this.el.find('.start');
// The animation wrapper
this.animation = this.el.find('.animation');
// Remove animation and shows the start screen
this.reset();
// Reset the animation and shows the start screen
$(this.audio).bind('ended', $.proxy(function() {
this.audio.currentTime = 0;
this.reset();
var o = this.opening;
// set data on form
$("#f-intro").val(o.intro);
$("#f-logo").val(o.logo || "Star\nwars");
$("#f-episode").val(o.episode);
$("#f-title").val(o.title);
$("#f-text").val(o.text);
$("#f-center").prop('checked',o.center || false);
$('#f-text').css('text-align', o.center? 'center' : 'initial');
setTimeout(function(){
if($('.start').css('display') === 'block')
$('body').removeClass('running');
},10000);
}, this));
}
/*
* Resets the animation and shows the start screen.
*/
StarWarsOpening.prototype.reset = function() {
this.start.show(); // show config form
$('.pageHide').show(); // show footer and social buttons
// reset the animation
this.cloned = this.animation.clone(true);
this.animation.remove();
this.animation = this.cloned;
$(window).trigger('resize'); // trigger resize to allow scrol in the config form
};
StarWarsOpening.prototype.resetAudio = function() {
this.audio.pause();
this.audio.currentTime = 0;
};
StarWarsOpening.prototype.play = function(){
this.start.hide();
$('.pageHide').hide();
unsetLoading(); // grants the loader to hide. Sometimes doesn't hide, maybe due to history navigation in browser.
$('body').removeClass('running');
$('body').addClass('running');
$('body').scrollTop(0);
this.audio.play();
this.el.append(this.animation);
// adjust animation speed
var titles = $('.titles > div',this.animation)[0];
if(titles.offsetHeight > 1977) // 1997 is year of the first Star Wars movie.
{
var exceedSize = titles.offsetHeight - 1977;
var animConstant = 0.04041570438799076;
var animDist = 20 - exceedSize*animConstant;
var cssRule;
var ss = document.styleSheets;
for (var i = 0; i < ss.length; ++i) {
// loop through all the rules!
for (var x = 0; x < ss[i].cssRules.length; ++x) {
var rule = ss[i].cssRules[x];
if (rule.name == "titles" && rule.type == CSSRule.KEYFRAMES_RULE) {
cssRule = rule;
}
}
}
if(cssRule)
cssRule.appendRule("100% { top: "+ animDist +"% }");
}
}
return StarWarsOpening;
})();
var StarWars = new StarWarsOpening({
el : '.starwars'
});
<|start_filename|>public/termsOfService.html<|end_filename|>
<!DOCTYPE html><html><head><meta charset="utf-8">
<style>
body{
color: #ffd54e;
background-color: black;
font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
text-align: justify;
padding: 1%;
}
a{
color: inherit;
font-weight: bold;
}
#pageTitle{
text-align: center;
}
</style>
</head>
<body>
<a id="themeButton" href="#">Black and White</a>
<h2 id="pageTitle">Star Wars Intro Creator<br />Terms of Service</h2>
<p>Last updated: Febrary 25, 2017.</p>
<p>These Terms of Service (“Terms”, “Terms of Service”) refers to the Star Wars Intro Creator website (<a href="http://brorlandi.github.io/StarWarsIntroCreator">brorlandi.github.io/StarWarsIntroCreator</a>) (the “Service”) operated by <NAME> and <NAME> (“us”, “we”, or “our”).
Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all visitors, users and others who access or use the Service.</p>
<h4><a id="About_the_Service_5"></a>About the Service</h4>
<p>This website is not related or to Lucasfilm Ltd., Walt Disney, or Twentieth Century Fox. The music and the Star Wars logo are copyrights of Lucasfilm Ltd. This website is developed by fans only.</p>
<p>We are not responsible for the content inserted in our service. This service should not be used to publish content to suggest violence, discrimination, illegal acts, transgression and hatred.
You must not defame, stalk, bully, abuse, harass, threaten, impersonate or intimidate people or entities via the Service.<br>
The content published in the service is registered by a unique key available in the URL. The content of this service is publicly available to anyone who knows the URL. You can not prevent others from accessing your content if it was published to the service. If you want your content removed from the site, please contact us via email. We don't share users' personal information with anyone.</p>
<h4><a id="About_Download_Videos_12"></a>About Download Videos</h4>
<p>The videos are rendered on a 1280 x 720 pixel resolution, thus, we do not guarantee that the rendered videos are identical to the creations in this service. The quality may differ depending on the device on which the content is displayed. You can see a sample of a video rendered here: <a href="https://www.youtube.com/watch?v=IQf8AN07T_E">https://www.youtube.com/watch?v=IQf8AN07T_E</a></p>
<p>The videos are rendered in our servers and takes 50 minutes on average to be rendered. To deliver this feature for free we have a queue of videos to be rendered. You will be prompted to put your email in. Your email will be only used to send a link to download the video when it’s ready. We don’t send spam and we don’t share your email address with third parties.</p>
<p>We are not responsible for any errors (typos, misspellings) made when rendering the video, the rendered video is reproduced exactly how it was received. Any fix(es) requested in a rendered text will be subject to our current availability.</p>
<p>We cannot ensure the video will be properly delivered when it was caused by any issues that are beyond the domains of Star Wars Intro Creator (misspelled email, user inbox is full, inactive user account, the email service sent the video notification e-mail to spam).</p>
<p>The videos have rendered content, logo and music, copyrighted to Lucasfilm Ltd and its reproduction may depend on the terms of service of third party applications. We are not responsible for the reproduction of videos on third party services. The reproduction of the videos for commercial use is subject to the copyrights of Lucasfilm Ltd.</p>
<p>Sharing the rendered video on services like Facebook and YouTube may violate copyright, which is not allowed by such services. In those cases it may be better to use the shareable link to Star Wars Intro Creator’s Web Intro.</p>
<h4><a id="About_Donations_26"></a>About Donations</h4>
<p>Donations are used to maintain the video rendering servers up.</p>
<p>As a reward for donors who donate at least 5 US Dollars we will provide the video before the entire queue. The donation must be in the exact value or greater than 5 US Dollars. Multiple donations that add up to the value of 5 US Dollars will not be accepted to get the video earlier. For 10 US Dollars or more the video will be rendered in Full HD resolution (1920x1080).</p>
<p>You must use the same email you have used in your PayPal account used to donate to ask for the video rendering. We are not responsible for misspelled emails, user inbox is full, inactivate user account and spam filters.</p>
<p>Donators will generally get their video within 2-4 hours, but the time it takes for a given video to be ready may vary on how many video requests were made recently. You should receive a confirmation email about your donation and your video being processed, if not, contact us.</p>
<p>Only donations made via the website buttons will be processed. If you make a donation directly to our PayPal account it will not be processed automatically, please contact us if it’s the case.</p>
<p>If you want to donate a greater value to get more videos, you can, contact us for further details.</p>
<p>We use PayPal to receive donations and it’s only way we accept donations at the time.</p>
<h4><a id="About_third_parties_42"></a>About third parties</h4>
<p>Our Service may contain links to third-party web sites or services that are not owned or controlled by Star Wars Intro Creator. Star Wars Intro Creator has no control over, and assumes no responsibility for: the content, privacy policies, or practices of any third party web sites or services. You further acknowledge and agree that Star Wars Intro Creator shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods or services available on or through any such web sites or services.</p>
<p>We reserve the right, at our sole discretion, to modify or replace these Terms at any time.</p>
<p>If you have any questions about these Terms, please contact us via <a href="mailto:<EMAIL>"><EMAIL></a> and <a href="mailto:<EMAIL>"><EMAIL></a> .</p>
<script>
var currentThemeIndex = 0;
var themes = [
{
background: 'black',
color: '#ffd54e',
text: 'Black and White',
},
{
background: 'white',
color: 'black',
text: 'Star Wars',
},
];
document.querySelector('#themeButton').addEventListener('click',function(e){
e.preventDefault();
currentThemeIndex = (currentThemeIndex + 1) % themes.length;
var currentTheme = themes[currentThemeIndex];
var body = document.querySelector('body');
body.style.backgroundColor = currentTheme.background;
body.style.color = currentTheme.color;
e.currentTarget.innerHTML = currentTheme.text;
});
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-71659114-1', 'auto');
ga('send', 'pageview', {
'page': "/termsOfService.html"
});
</script>
<!-- Hotjar Tracking Code for http://brorlandi.github.io/ -->
<script>
(function(h,o,t,j,a,r){
h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
h._hjSettings={hjid:537847,hjsv:5};
a=o.getElementsByTagName('head')[0];
r=o.createElement('script');r.async=1;
r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
a.appendChild(r);
})(window,document,'//static.hotjar.com/c/hotjar-','.js?sv=');
</script>
</body>
</html>
<|start_filename|>public/errorFunction.js<|end_filename|>
function ajaxErrorFunction(bodyMessage){
var body = encodeURI("Hi, the website didn't work as expected. \n\n"+bodyMessage);
return function (){
swal({
html: true,
title: '<h2 style="font-family: StarWars;">an error has occured</h2>',
text: '<p style="text-align: left">Something went wrong! Sorry about that! Please try again, if this error repeats please contact us: : '+
'<br><a style="color: #ffd54e;" href="mailto:<EMAIL>,<EMAIL>?Subject=SWIC%20Problem&Body='+body+'" target="_blank"><EMAIL><br> <EMAIL></a></p>',
type: "error",
confirmButtonText: "Ok"
});
}
}
<|start_filename|>gulpfile.js<|end_filename|>
var gulp = require('gulp');
var connect = require('gulp-connect');
var sass = require('gulp-sass');
var del = require('del');
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var minifyCss = require('gulp-minify-css');
gulp.task('connect', function() {
connect.server({
root: 'public',
livereload: true
});
});
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./public'))
.pipe(connect.reload());
});
gulp.task('reload', function () {
gulp.src(['./public/**/*','!./public/**/*.scss'])
.pipe(connect.reload());
});
gulp.task('watch', function () {
gulp.watch(['./public/**/*','!./public/**/*.scss'],['reload']);
gulp.watch('./sass/**/*.scss', ['sass']);
});
gulp.task('clean-build',function(){
del.sync('./dist/*');
});
gulp.task('build',['sass','clean-build'],function(){
gulp.src('public/index.html')
.pipe(useref())
.pipe(gulpif('*.js', uglify()))
.pipe(gulpif('styles.css', minifyCss()))
.pipe(gulp.dest('dist'));
gulp.src(['./public/*.*','./public/.nojekyll','!public/index.html','!public/styles.css','!public/bb8.css','!public/*.js'])
.pipe(gulp.dest('./dist'));
});
gulp.task('default', ['sass','connect','watch']);
<|start_filename|>public/main.js<|end_filename|>
// sweet alerts config
swal.setDefaults({
customClass: 'star-wars-alert',
});
var OpeningKey = null;
var defaultOpening = null; // to check if user not edited the default opening
// make audio load on mobile devices
var audio = document.getElementsByTagName('audio')[0];
var audioIsLoaded = false;
var loadData = function () {
if(!audioIsLoaded){
audio.load();
audioIsLoaded = true;
}
};
document.body.addEventListener('touchstart', loadData);
// prevent arrow scrolling in firefox
window.addEventListener("keydown", function(e) {
// space and arrow keys
var type = document.activeElement.type || '';
if(!type.startsWith('text')){
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}
}, false);
var notPlayed = true;
var showFooter = true;
window.setLoading = function (){
$('#loader').show();
$('#form-starwars').hide();
}
window.unsetLoading = function (){
$('#loader').hide();
$('#form-starwars').show();
}
setLoading();
$('#form-starwars').submit(function(event) {
event.preventDefault();
var opening = getOpeningFormValues();
var before = StarWars.opening;
if(!isOpeningsDifferents(opening, before)){ // User replay the same intro without modification, doesn't need to create a new one
var hashbefore = location.hash;
var hashnow = '!/'+OpeningKey;
location.hash = hashnow;
if(hashbefore !== hashnow){ // if user is in edit form but not in /edit url, force hashchange because the hash will be the same.
window.dispatchEvent(new Event('hashchange'));
}
return;
}
if(!isOpeningsDifferents(opening,defaultOpening)){
setLoading();
location.hash = '!/Episode8';
return;
}
var aLogo = opening.logo.split('\n');
if(aLogo.length > 2){
sweetAlert("Oops...", "Logo can't have more than 2 lines.", "warning");
return;
}
var aIntro = opening.intro.split('\n');
if(aIntro.length > 2){
sweetAlert("Oops...", "Intro text can't have more than 2 lines.", "warning");
return;
}
for(var key in opening){
if(opening[key] == "string" && opening[key].indexOf("??") > -1){
sweetAlert("Oops...", "Your text can't contain the sequence \"??\", please fix it and submit again.", "error");
return;
}
}
setLoading();
$.ajax({
url: "https://starwarsopeninga.firebaseio.com/openings.json",
method: "POST",
data: JSON.stringify(opening),
dataType: "json",
success: function(data){
var key = 'A'+data.name.substring(1);
CreatedIntros.save(key,opening);
location.hash = '!/'+key;
},
error: ajaxErrorFunction('Error when creating the intro.\n\n'+JSON.stringify(opening))
});
});
$(window).on('hashchange', function() {
var urlByKey = function(key){
var code = key.charAt(0);
if(code === "A"){
key = key.substr(1);
return 'https://starwarsopeninga.firebaseio.com/openings/-'+key+'.json';
}else{
return 'https://starwarsopening.firebaseio.com/openings/-'+key+'.json';
}
};
$("#playBut").remove();
var params = location.hash.replace('#!/', '').split('/');
var key = params[0];
var edit = false;
try{
edit = params[1] === "edit";
}catch(e){}
$('body').removeClass('running');
if(key != ""){
$('[name=custom]').val(key);
try{
key = parseSpecialKeys(key);
var url = urlByKey(key);
$.ajax({
url: url,
success: function(opening) {
if(opening == null){
sweetAlert("Oops...", "Introduction not found!", "error");
return;
}
StarWars.opening = opening;
OpeningKey = key;
$("#videoButton").show();
var intro = opening.intro.replace(/</g,"<");
intro = intro.replace(/>/g,">");
intro = intro.replace(/\n/g,"<br>");
StarWars.animation.find("#intro").html(intro);
StarWars.animation.find("#episode").text(opening.episode);
var title = StarWars.animation.find("#title")
if(checkCompatibleSWFont(opening.title)){
title.addClass('SWFont');
}
title.text(opening.title);
var ps = opening.text.split('\n');
var div = StarWars.animation.find("#text");
div.text('');
for(var i in ps){
div.append($('<p>').text(ps[i]));
}
div.css('text-align',opening.center ? 'center':'');
$('#logosvg',StarWars.animation).css('width',$(window).width()+'px'); // set width of the logo
$('#logoimg',StarWars.animation).css('width',$(window).width()+'px');
var logoText = opening.logo ? opening.logo : "star\nwars";
var aLogo = logoText.split('\n'); // breaks logo text in 2 lines
var logo1 = aLogo[0];
var logo2 = aLogo[1] || "";
if(logoText.toLowerCase() != "star\nwars"){
var texts = $('#logosvg text',StarWars.animation);
texts[0].textContent = logo1;
texts[1].textContent = logo2;
// calculate the svg viewBox using the number of characters of the longest world in the logo.
var logosize = logo1.length > logo2.length ? logo1 : logo2;
var vbox = '0 0 '+logosize.length*200+' 500';
$('#logosvg',StarWars.animation).each(function () {$(this)[0].setAttribute('viewBox', vbox) });
$('#logosvg',StarWars.animation).show();
$('#logoimg',StarWars.animation).hide();
}else{ // if the logo text is "Star Wars" set to the logo SVG.
$('#logosvg',StarWars.animation).hide();
$('#logoimg',StarWars.animation).show();
}
var play = function(){
$.when(StarWars.audioDefer).then(function(){
var buffered = StarWars.audio.buffered.end(StarWars.audio.buffered.length-1);
if(buffered == 0 && !audioIsLoaded){
unsetLoading();
playbutton = $('<div class="verticalWrapper"><div class="playAudio"><button id="playBut" class="playButton" style="font-size: 80px">Play</button></div></div>');
$('body').append(playbutton);
$('#playBut',playbutton).click(function(){
setLoading();
playbutton.remove();
});
StarWars.audio.oncanplaythrough = function () {
notPlayed = false;
StarWars.play();
};
}else{
notPlayed = false;
StarWars.play();
}
if(edit){
StarWars.audio.currentTime = 97;
$('#form-starwars').show();
}
});
};
if(document.hasFocus()){ // play if has focus
play();
}else{
$(window).focus(function(){ // play when got focus
if(notPlayed){
play();
}
});
}
},
error: ajaxErrorFunction('Error when try to load the intro '+key)
});
}catch(error){
location.hash = "";
setLoading();
}
}else{
if(!notPlayed){
StarWars.reset();
StarWars.resetAudio();
}else{
unsetLoading();
}
}
ga('send', 'pageview', {
'page': location.pathname + location.search + location.hash
});
});
function getInternetExplorerVersion()
{
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
else if (navigator.appName == 'Netscape')
{
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
$(document).ready(function() {
if(getInternetExplorerVersion() !== -1){
sweetAlert("Internet Explorer Detected", "This website is not compatible with Internet Explorer, please use Chrome. Sorry for the inconvenience.", "error");
unsetLoading();
return;
}
defaultOpening = getOpeningFormValues(); // get the default opening from the default form values
window.dispatchEvent(new Event('hashchange'));
$('#f-center').change(function(){
var center = $(this).is(':checked');
$('#f-text').css('text-align', center == true ? 'center' : 'initial');
});
});
var calcTime = function(queue){
var minutes = (queue+1)*30;
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);
var time = "";
if(days > 0){
time += days + " days";
}
if(days < 3){
hours = hours%24;
minutes = minutes%60;
if(hours > 0){
time += " " +hours + " hours";
}
if(minutes > 0){
time += " " +minutes + " minutes";
}
}
return time;
};
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
var termsOfServiceText = 'By using this website you are agreeing to our <a style="color: #ffd54e;font-weight:bold;" href="termsOfService.html" target="_blank">Terms of Service</a>.';
var requestVideo = function(donate, email){
if(email === false) return false;
if (!validateEmail(email)) {
swal.showInputError("You need to type an e-mail!");
return false;
}
var url = "https://endor.nihey.org/request?code="+ OpeningKey +"&email=" + email;
$.ajax({
url: url,
type: 'GET',
crossDomain: true,
success: function(data){
var queue = data.queue;
swal({
html: true,
title: '<h2 style="font-family: StarWars;">video request sent</h2>',
text:'<p style="text-align: justify">'+
'Your video has been queued. Your current position on the queue is <b>'+
(queue+1) + '</b>, which will take up to <b>'+ calcTime(queue) +'</b>.<br>'+
'The link to download the video will be sent to the e-mail:<br>'+
'</p><span style="text-align: center; font-weight: bold">'+email+'</span>'+
(
donate ?
(
'<p style="margin-top: 15px;text-align: justify">But as you donated, we will bump you up on the queue.'+
' Thank you so much for supporting us! You should receive the confirmation email within a few minutes.'+
'</p>'
) :
''
) +
'<p style="text-align: justify;margin-top: 15px;">'+termsOfServiceText+'</p>'
});
},
error: ajaxErrorFunction('Error when request video download.')
});
};
$("#videoButton").click(function(){
var now = getOpeningFormValues();
var before = StarWars.opening;
if(isOpeningsDifferents(now, before)){ // prevent user to request download without save the edited intro
swal({
html: true,
title: '<h2 style="font-family: StarWars;">Text modified</h2>',
text: '<p style="text-align: justify">'+
'You have changed some of the text inputs. You need to play the new intro to save and request a download.',
showCancelButton: true,
confirmButtonText: "Ok, play it!",
confirmButtonColor: "#807300",
animation: "slide-from-top"
},function(ok){
if(ok){
$('#form-starwars').submit();
}
});
return;
}
// swal({
// html: true,
// title: '<h2 style="font-family: StarWars;">loading</h2>',
// text: '<iframe src="./atat.html" height="200px"></iframe>',
// animation: "slide-from-top",
// showConfirmButton: false
// });
$.ajax({
url: "https://endor.nihey.org/status?code="+OpeningKey,
crossDomain: true,
success: function(data){
var queue = data.queue;
if(data.url){
swal({
html: true,
title: '<h2 style="font-family: StarWars;">Download</h2>',
text: '<p style="text-align: left">'+
'This video has already been generated, click the link below to download.<br><br>'+
'<a style="color: #ffd54e;" href="'+data.url+'">'+data.url+'</a></p>',
});
}else{
swal({
html: true,
title: '<h2 style="font-family: StarWars;">Donate and Download</h2>',
text: '<p style="text-align: left">'+
'We want to provide videos for free, but we have to use a server to render it, which costs money.<br>'+
'There are <b>'+(queue+1)+' videos</b> in front of you and it will take <b>'+calcTime(queue)+'</b> to be processed.<br><br>'+
'Can\'t wait for it? Donate at least <b>5 US Dollars</b>, you will jump the queue and your video will be ready in few hours.<br>'+
'The video will be rendered in HD quality and MP4 file. To see a sample video click '+
'<a style="color: #ffd54e;font-weight:bold;" href="https://www.youtube.com/watch?v=IQf8AN07T_E" target="_blank">here</a>.'+
'Donate at least <b>10 US Dollars</b> and you will get the video in <b>Full HD resolution (1920x1080)</b><br><br>'+
'<b>Attention!</b> Make sure there are no typos in your text, there will be no correction after the video rendering.<br>'+
termsOfServiceText+
'</p>'+
'<iframe src="./atat.html" height="200px"></iframe>',
showCancelButton: true,
confirmButtonText: "Yes, donate!",
confirmButtonColor: "#807300",
cancelButtonText: "No, I'll get in the queue!",
closeOnConfirm: false,
closeOnCancel: false,
animation: false
},function(donate){
var generateAlert = {
html: true,
title: '<h2 style="font-family: StarWars;">Generate video</h2>',
text: '<p style="text-align: justify">'+
'Type your email below and you will receive a message with the URL to download your video when it\'s ready. We promise not to send spam!'+
'</p>' + (donate ? [
'<br><p style="text-align: justify">',
' Please, use the same email from you PayPal account.',
" If you want to receive in another e-mail too, click on download button again and add more e-mails. You don't need to donate again.",
' <br><br>',
' Attention! Make sure there are no typos in your text, you will need to request a new video download and donate again.<br><br>',
' '+termsOfServiceText,
'</p>',
].join('') : ''),
type: 'input',
showCancelButton: true,
inputPlaceholder: "Your e-mail...",
closeOnConfirm: false,
showLoaderOnConfirm: true,
};
if(donate){
generateAlert.title = '<h2 style="font-family: StarWars;">Donate</h2>';
generateAlert.text = 'Click on the button below:'
+'<br><iframe src="./donateButtons.html#!/' + OpeningKey + '" height="100"></iframe>'+generateAlert.text;
}
swal(generateAlert, requestVideo.bind(window, donate));
});
}
},
error: ajaxErrorFunction('Error when request video information to download.')
});
});
function getOpeningFormValues(){ // read the opening from form and create the object
return {
intro: $("#f-intro").val(),
logo: $("#f-logo").val(),
episode: $("#f-episode").val(),
title: $("#f-title").val(),
text: $("#f-text").val(),
center: $("#f-center").prop('checked')
};
};
function isOpeningsDifferents(a,b){ // compare two openings texts to see if they are different
var changes =[];
if(a === null || b == null ){
return true;
}
changes.push(a.intro !== b.intro);
changes.push(a.logo !== b.logo);
changes.push(a.episode !== b.episode);
changes.push(a.title !== b.title);
changes.push(a.text !== b.text);
changes.push(a.center !== b.center && b.center !== undefined);
return changes.reduce(function(c,e){
return c || e;
},false);
};
function parseSpecialKeys(key){
switch (key) {
case "Episode7": // Episode7 is a special key for URL, it plays the Episode 7 opening
return "AKcKeYMPogupSU_r1I_g";
case "Episode8":
return "AL6yNfOxCGkHKBUi54xp";
// TODO other eps
default:
return key;
}
}
function checkCompatibleSWFont(title){
var supportedChars = " qwertyuiopasdfghjklzxcvbnm0123456789!$".split(''); // all supported supported chars
var unique = title.toLowerCase().split('').filter(function(item, i, ar){ return ar.indexOf(item) === i; }); // get unique characters from the input string
for(var i=0;i<unique.length;i++){
if(supportedChars.indexOf(unique[i]) == -1){
return false;
}
}
return true;
}
<|start_filename|>public/createdIntros.js<|end_filename|>
function createdIntros(){
var source = '{{#if intros.length}}' +
'<div id="box">'+
'{{#each intros}}'+
'<div>'+
'<div class="circCont">'+
'<button data-id="{{@index}}" class="removeButton circle fromMiddle">'+
'<span></span>'+
'</button>'+
'</div>'+
'<a href="#!/{{this.key}}" class="link">{{this.title}}</a>'+
'</div>'+
'{{/each}}'+
'</div>'+
'{{/if}}';
this.template = Handlebars.compile(source);
this.element = $('#createdIntros');
this.remove = function(index){
var that = this;
swal({
html: true,
title: '<h2 style="font-family: StarWars;">remove intro</h2>',
text: '<p style="text-align: justify">'+
'This will not remove the intro from the database. Are you sure you want to remove the intro from this browser?<br>'+
'</p>',
showCancelButton: true,
confirmButtonText: "Yes",
cancelButtonText: "No",
animation: "slide-from-top"
},function(confirm){
if(confirm){
var intros = JSON.parse(localStorage.StarWarsIntros);
intros.splice(index,1);
localStorage.StarWarsIntros = JSON.stringify(intros);
that.load();
}
});
}
this.load = function(){
var intros = localStorage.StarWarsIntros ? JSON.parse(localStorage.StarWarsIntros) : [];
var html = $(this.template({intros:intros}));
var that = this;
html.find('.removeButton').click(function(e){
that.remove(e.target.dataset.id);
});
this.element.html(html);
};
var getTitle = function(intro){
var see = ['title','episode','logo','text'];
for(var i=0;i<see.length;i++){
var property = intro[see[i]];
if(property.trim() !== ''){
return property.slice(0,50);
}
}
}
this.save = function(key,intro){
var intros = localStorage.StarWarsIntros ? JSON.parse(localStorage.StarWarsIntros) : [];
var title = getTitle(intro);
intros.push({title: title, key: key});
localStorage.StarWarsIntros = JSON.stringify(intros);
}
};
CreatedIntros = new createdIntros();
CreatedIntros.load();
<|start_filename|>public/textDisplay.css<|end_filename|>
#logoimg {
display: none;
display: block; }
#logosvg {
display: block; }
#showIntroDiv {
position: absolute;
top: 20px;
left: 50px;
z-index: 20; }
#showLogo {
position: absolute;
top: 80px;
left: -60px;
width: 200px;
z-index: 20; }
#logoConfig {
position: absolute;
top: 200px;
left: -50px;
width: 200px;
-webkit-transform: rotate(90deg);
z-index: 20; }
#textHeightConfig {
position: absolute;
top: 500px;
left: -50px;
width: 200px;
-webkit-transform: rotate(90deg);
z-index: 20; }
.configRanges {
position: absolute;
top: 80px;
left: 50px; }
.configRanges.second {
top: 380px; }
.starwars .intro {
display: none;
opacity: 1;
animation: 0 !important; }
.starwars .titles > div {
top: 80%;
opacity: 1; }
.starwars .logo {
display: none;
opacity: 1; }
@keyframes titles {}@keyframes logo {}
<|start_filename|>public/styles.css<|end_filename|>
@import url(https://fonts.googleapis.com/css?family=News+Cycle:400,700);
@font-face {
font-family: StarWars;
src: url("Starjedi.ttf"); }
@font-face {
font-family: StarWarsTitle;
src: url("SWCrawlTitle2.ttf"); }
html,
body {
width: 100%;
height: 100%;
font: 700 1em "News Cycle", sans-serif;
letter-spacing: .15em;
color: #ffd54e;
margin: 0;
background-color: black; }
/* Remove dotted border on Firefox (http://stackoverflow.com/a/199319) */
button::-moz-focus-inner {
border: 0; }
.starwars section {
position: absolute;
top: 45%;
left: 50%;
z-index: 1; }
.starwars .start {
font-size: 200%;
width: 100%;
margin: 0 0 0 -50%;
text-align: center;
top: 0; }
.starwars .start #config {
margin: 0 auto;
width: 500px; }
.starwars .introBg {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background-color: black;
animation: introBg 9s;
opacity: 0; }
.starwars .intro {
margin: 0 auto;
padding: 0 100px;
position: static;
top: 0px;
left: 0px;
font-size: 500%;
font-weight: 400;
color: #4bd5ee;
opacity: 0;
animation: intro 6s ease-out 1s; }
@media (max-height: 720px) {
.starwars .intro {
font-size: 350%; } }
.starwars .logo {
font-family: StarWars;
text-align: center;
position: static;
margin: 0 auto;
opacity: 0;
animation: logo 11s cubic-bezier(0.11, 0.51, 0.48, 0.88) 9s; }
.starwars .logo img {
width: 300px; }
.starwars .titles {
width: 14.65em;
margin: 0 0 0 -7.325em;
top: auto;
bottom: 0;
height: 50em;
font-size: 350%;
text-align: justify;
overflow: hidden;
word-wrap: break-word;
transform-origin: 50% 100%;
-moz-transform: perspective(300px) rotateX(25deg);
-o-transform: perspective(300px) rotateX(25deg);
-ms-transform: perspective(300px) rotateX(25deg);
-webkit-transform: perspective(300px) rotateX(25deg);
transform: perspective(300px) rotateX(25deg); }
@media screen and (min-width: 1920px) and (max-width: 1920px) {
.starwars .titles {
zoom: 1.9;
-moz-transform: perspective(266px) rotateX(29deg) scaleX(1.2);
-o-transform: perspective(266px) rotateX(29deg) scaleX(1.2);
-ms-transform: perspective(266px) rotateX(29deg) scaleX(1.2);
-webkit-transform: perspective(266px) rotateX(29deg) scaleX(1.2);
transform: perspective(266px) rotateX(29deg) scaleX(1.2); } }
@media screen and (min-width: 1366px) and (max-width: 1366px) {
.starwars .titles {
zoom: 1.5;
-moz-transform: perspective(216px) rotateX(26deg);
-o-transform: perspective(216px) rotateX(26deg);
-ms-transform: perspective(216px) rotateX(26deg);
-webkit-transform: perspective(216px) rotateX(26deg);
transform: perspective(216px) rotateX(26deg); } }
@media screen and (min-width: 1280px) and (max-width: 1280px) {
.starwars .titles {
zoom: 1.5;
-moz-transform: perspective(216px) rotateX(26deg);
-o-transform: perspective(216px) rotateX(26deg);
-ms-transform: perspective(216px) rotateX(26deg);
-webkit-transform: perspective(216px) rotateX(26deg);
transform: perspective(216px) rotateX(26deg); } }
.starwars .titles > div {
position: absolute;
top: 100%;
animation: titles 73s linear 13s; }
.starwars .titles > div > p {
margin: 1.35em 0 1.85em 0;
line-height: 1.35em;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
-o-backface-visibility: hidden;
backface-visibility: hidden; }
.starwars .titles > div .tcenter {
margin: 1.35em 0 -1em 0;
text-align: center; }
.verticalWrapper {
display: flex;
align-items: center;
height: 100%;
width: 100%;
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px; }
@keyframes intro {
0% {
opacity: 0; }
20% {
opacity: 1; }
90% {
opacity: 1; }
100% {
opacity: 0; } }
@keyframes introBg {
0% {
opacity: 1; }
100% {
opacity: 1; } }
@keyframes logo {
0% {
-moz-transform: scale(1.3);
-o-transform: scale(1.3);
-ms-transform: scale(1.3);
-webkit-transform: scale(1.3);
transform: scale(1.3);
opacity: 1; }
95% {
opacity: 1; }
100% {
-moz-transform: scale(0.01);
-o-transform: scale(0.01);
-ms-transform: scale(0.01);
-webkit-transform: scale(0.01);
transform: scale(0.01);
opacity: 0; } }
@keyframes titles {
0% {
top: 100%;
opacity: 1; }
95% {
opacity: 1; }
100% {
top: 20%;
opacity: 0; } }
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none; }
.playButton, .downloadButton {
font-family: StarWars;
cursor: pointer;
font-size: 50px;
border: 0;
background: transparent;
color: #ffd54e;
text-shadow: none;
transition: text-shadow 0.5s ease-out;
outline: none; }
.playButton:focus, .downloadButton:focus, .playButton:hover, .downloadButton:hover {
text-shadow: -1px 1px 8px #45f500, 1px -1px 8px #45f500; }
#form-starwars {
width: 500px; }
#form-starwars input, #form-starwars textarea {
width: 97%;
margin-bottom: 0px;
padding: 0.3em;
border: 3px solid rgba(255, 213, 78, 0.2);
border-radius: 3px;
background: black;
color: #ffd54e;
transition: border-color 0.7s ease-out;
overflow-x: hidden; }
#form-starwars input:active, #form-starwars input:focus, #form-starwars textarea:active, #form-starwars textarea:focus {
border-color: #ffd54e; }
#form-starwars textarea {
resize: none; }
#form-starwars textarea#f-logo {
color: black;
border: 0.0666em solid rgba(255, 213, 78, 0.2);
border-radius: 0.0533em;
font-family: StarWars;
font-size: 50px;
font-weight: normal;
height: 92px;
line-height: 86%;
width: 93%;
text-shadow: -2px -2px 0 #ffd54e, -2px -1px 0 #ffd54e, -2px 0px 0 #ffd54e, -2px 1px 0 #ffd54e, -2px 2px 0 #ffd54e, -1px -2px 0 #ffd54e, -1px -1px 0 #ffd54e, -1px 0px 0 #ffd54e, -1px 1px 0 #ffd54e, -1px 2px 0 #ffd54e, 0px -2px 0 #ffd54e, 0px -1px 0 #ffd54e, 0px 0px 0 #ffd54e, 0px 1px 0 #ffd54e, 0px 2px 0 #ffd54e, 1px -2px 0 #ffd54e, 1px -1px 0 #ffd54e, 1px 0px 0 #ffd54e, 1px 1px 0 #ffd54e, 1px 2px 0 #ffd54e, 2px -2px 0 #ffd54e, 2px -1px 0 #ffd54e, 2px 0px 0 #ffd54e, 2px 1px 0 #ffd54e, 2px 2px 0 #ffd54e; }
#form-starwars textarea#f-text {
margin-top: 10px; }
#f-intro {
color: #4bd5ee !important; }
#f-text {
height: 200px; }
#f-logo, #f-title, #f-episode {
text-align: center; }
#loader .inner {
width: 100%;
text-align: center; }
#pageTitle {
line-height: 100%;
font-family: StarWars; }
.star-wars-alert {
background-color: black !important;
border: 2px solid #ffd54e; }
.star-wars-alert h2, .star-wars-alert p {
color: #ffd54e !important; }
.star-wars-alert button {
border: 2px solid #ffd54e !important;
color: #ffd54e !important;
background-color: black !important; }
#footer {
position: fixed;
width: 100%;
bottom: 1em;
text-align: center;
font-size: 0.7em;
color: #9e9e42; }
#footer a {
color: #ffd54e;
text-decoration: none; }
#footer a:hover {
color: #fff;
text-decoration: none; }
.socialButtons {
position: fixed;
bottom: 1em;
left: 1em;
z-index: 10; }
.socialButtons form {
margin-bottom: 5px; }
.socialButtons div {
margin-bottom: 0.33em; }
.socialButtons div:last-of-type {
margin-bottom: 0; }
.bg {
width: 100%;
height: 4100px;
position: absolute;
top: 0;
left: 0;
background-color: black;
background: url("bg-stars.png") repeat; }
.running {
overflow: hidden; }
.running .bg {
animation: scrolldown 7s 86s forwards; }
@keyframes scrolldown {
0% {
transform: translateY(0); }
100% {
transform: translateY(-2200px); } }
.deathstar {
background: black url(deathstar.png) no-repeat;
width: 655px;
height: 663px;
position: absolute;
bottom: 1150px;
right: 100px; }
#logosvg {
width: 900px;
display: none;
font-size: 210px; }
.playAudio {
width: 100%;
text-align: center;
font-size: 50px; }
#videoButton {
display: none;
margin-bottom: 30px;
font-size: 60px; }
.sweet-alert fieldset input {
width: 100%;
margin-bottom: 10px;
padding: 0.25em;
border: 0.25em solid rgba(255, 213, 78, 0.2);
border-radius: 0.2em;
background: black;
color: #ffd54e;
transition: border-color 0.7s ease-out; }
.sweet-alert fieldset input:active, .sweet-alert fieldset input:focus {
outline: none;
box-shadow: none;
border: 0.25em solid #ffd54e; }
.sweet-alert .icon, .sweet-alert .sa-input-error::before, .sweet-alert .sa-input-error::after {
background-color: #C31D00 !important; }
.sa-error-container {
background-color: #3c3808 !important; }
iframe {
border: none; }
.termsOfService {
text-align: center;
position: fixed;
bottom: 1em;
right: 1em;
z-index: 10; }
.termsOfService a {
color: #ffd54e;
text-decoration: none; }
.termsOfService a:hover {
text-decoration: underline; }
@keyframes pulseDownload {
0% {
text-shadow: none; }
40% {
text-shadow: -1px 1px 93px #45f500, 1px -1px 23px #45f500; }
60% {
text-shadow: -1px 1px 93px #45f500, 1px -1px 23px #45f500; }
100% {
text-shadow: none; } }
.downloadButton {
animation: pulseDownload 3s ease 0s infinite; }
.downloadButton:hover {
text-shadow: -1px 1px 93px #45f500, 1px -1px 23px #45f500;
animation: none; }
#createdIntros #box {
position: fixed;
top: 1em;
left: 1em;
z-index: 10;
border: #ffd54e 3px solid;
border-radius: 7px;
padding: 10px;
color: #ffd54e;
max-width: 20%; }
#createdIntros #box div {
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis; }
#createdIntros #box div a {
color: #ffd54e;
text-decoration: none; }
#createdIntros #box div a.link {
width: 250px; }
#createdIntros #box div a.link:hover {
text-decoration: underline; }
#createdIntros #box div .circCont {
display: inline-block;
float: right;
margin-top: 4px;
margin-left: 5px; }
#createdIntros #box div .circCont .circle {
width: 20px;
height: 20px;
background: transparent;
border: 2px solid #ffd54e;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
position: relative;
cursor: pointer;
display: inline-block; }
#createdIntros #box div .circCont .circle:after {
width: 12px;
height: 2px;
background-color: #ffd54e;
content: "";
left: 50%;
top: 50%;
margin-left: -6px;
margin-top: -1px;
position: absolute;
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-webkit-transform: rotate(-45deg);
transform: rotate(-45deg);
/*@include transform-origin(100%,100%);*/ }
#createdIntros #box div .circCont .circle:before {
left: 50%;
top: 50%;
margin-left: -6px;
margin-top: -1px;
width: 12px;
height: 2px;
background-color: #ffd54e;
content: "";
position: absolute;
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
/*@include transform-origin(0%,0%);*/ }
#createdIntros #box div .circCont .fromMiddle:before, #createdIntros #box div .circCont .fromMiddle:after {
z-index: 9999;
-moz-transition-delay: 150ms;
-o-transition-delay: 150ms;
-webkit-transition-delay: 150ms;
transition-delay: 150ms;
-moz-transition: ease-in-out 400ms;
-o-transition: ease-in-out 400ms;
-webkit-transition: ease-in-out 400ms;
transition: ease-in-out 400ms; }
#createdIntros #box div .circCont .fromMiddle span {
width: 18px;
height: 18px;
background-color: #ffd54e;
display: inline-block;
position: absolute;
-moz-border-radius: 100%;
-webkit-border-radius: 100%;
border-radius: 100%;
left: -1px;
top: -1px;
z-index: -9999;
-moz-transform: scale(0.3);
-ms-transform: scale(0.3);
-webkit-transform: scale(0.3);
transform: scale(0.3);
opacity: 0;
-moz-transition: ease-in-out 300ms;
-o-transition: ease-in-out 300ms;
-webkit-transition: ease-in-out 300ms;
transition: ease-in-out 300ms; }
#createdIntros #box div .circCont .fromMiddle:hover:before, #createdIntros #box div .circCont .fromMiddle:hover:after {
position: absolute;
background-color: black; }
#createdIntros #box div .circCont .fromMiddle:hover span {
-moz-transform: scale(1);
-ms-transform: scale(1);
-webkit-transform: scale(1);
transform: scale(1);
opacity: 1; }
#videoRequestAdvise {
font-size: 50%; }
#flabel {
font-size: 13px;
font-family: Arial;
font-weight: normal;
display: inline;
vertical-align: middle; }
.regular-checkbox {
display: none; }
.regular-checkbox + label {
background-color: black;
border: 3px solid rgba(255, 213, 78, 0.2);
padding: 9px;
border-radius: 3px;
display: inline-block;
position: relative;
top: 3px; }
.regular-checkbox:checked + label {
color: #99a1a7; }
.regular-checkbox:checked + label:after {
content: '\2714';
font-size: 14px;
position: absolute;
bottom: -2px;
left: 3px;
color: #ffd54e; }
#text {
line-height: 1.5em; }
#episode {
margin-bottom: -2em; }
#title.SWFont {
font-family: StarWarsTitle;
font-weight: normal;
font-size: 210%;
transform: scaleY(1);
margin-bottom: -0.1em;
margin-top: 1.35em;
text-transform: lowercase; }
#title {
transform: scaleY(2);
margin-bottom: 1.6em;
margin-top: 3.5em;
text-transform: uppercase; }
#playBut {
z-index: 1000; }
.sweet-alert {
box-sizing: border-box;
max-height: 100% !important;
overflow-y: auto !important;
padding: 0 17px 17px !important;
width: 512px !important; }
.sweet-alert:before {
content: "";
display: block;
height: 17px;
width: 0; }
#btcether {
font-weight: bold;
display: flex;
line-height: 25px; }
#btcether:hover {
text-decoration: underline;
cursor: pointer; }
#btcether span {
margin-left: 5px; }
<|start_filename|>public/bitcoinEther.js<|end_filename|>
document.querySelector('#btcether').addEventListener("click", function(e) {
e.preventDefault();
swal({
title: '<h2 style="font-family: StarWars;">Donate Bitcoin and Ether</h2>',
html: true,
text:'<p style="text-align: center">You can donate Bitcoins and Ether to the following Wallets. Please send us an email to tell us about your donation.</p>'+
'<br><p>Bitcoin: 1KAYmrrYYobx2k6p5zxkziGeggbXqPdYJ6</p>' +
'<br><p>Ether: <span style="font-size: 0.9em">0xe5c26Be15597B3b03519f2517592AE2dBdFf4E63</span> </p>',
allowOutsideClick: false,
});
}); | Graystripe17/StarWarsIntroCreator |
<|start_filename|>demo.js<|end_filename|>
function showTips1() {
layer.tips('展开所有节点', '#expand', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips2() {
layer.tips('收起所有节点', '#collapse', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips3() {
layer.tips('获取checkbox选中的节点信息', '#selected', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips4() {
layer.tips('添加根节点-父节点4,父节点4中带有子节点', '#addNode2', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips5() {
layer.tips('在父节点2下添加子节点22,子节点22中带有子节点', '#addNode', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips6() {
layer.tips('修改父节点3的名字', '#editNode', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips7() {
layer.tips('删除父节点2,所有子节点一起删除', '#removeNode', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips8() {
layer.tips('获取所有节点的信息', '#all', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips9() {
layer.tips('获取父节点2的信息', '#getNode', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips10() {
layer.tips('销毁treetable', '#destory', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips11() {
layer.tips('展开指定节点:父节点2', '#expandNode', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips12() {
layer.tips('折叠指定节点:父节点2', '#collapseNode', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips13() {
layer.tips('勾选 单个节点:父节点1。', '#checkNode', {
tips: [1, '#3595CC'],
time: 3000
})
}
function showTips14() {
layer.tips('取消勾选 单个节点:父节点1。', '#uncheckNode', {
tips: [2, '#3595CC'],
time: 3000
})
}
function showTips15() {
layer.tips('禁用父节点1的checkbox', '#disableNode', {
tips: [2, '#3595CC'],
time: 3000
})
}
function showTips16() {
layer.tips('解禁父节点1的checkbox', '#ableNode', {
tips: [2, '#3595CC'],
time: 3000
})
}
function showTips17() {
layer.tips('获取所有未选中节点的信息', '#unSelected', {
tips: [2, '#3595CC'],
time: 3000
})
}
function showTips18() {
layer.tips('勾选全部节点', '#checkAllNode', {
tips: [2, '#3595CC'],
time: 3000
})
}
function showTips19() {
layer.tips('取消勾选全部节点', '#unCheckAllNode', {
tips: [2, '#3595CC'],
time: 3000
})
}
function showTips20() {
layer.tips('根据节点数据的属性搜索,获取条件完全匹配的节点数据 JSON 对象,查找name=父节点1的节点', '#getNodeByParam', {
tips: [2, '#3595CC'],
time: 4000
})
} | shaojiepeng/layui-treetable |
<|start_filename|>webpack.config.js<|end_filename|>
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
let externals;
let optimization;
let mode = 'development';
let entry = {
docs: [
'webpack-dev-server/client?http://0.0.0.0:8080',
'webpack/hot/only-dev-server',
'./docs/js/main',
],
};
const output = {
path: path.join(__dirname, '/dist/'),
filename: '[name].js',
publicPath: '/',
};
let plugins = [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
chunks: ['app'],
template: 'docs/index.html',
filename: 'index.html',
}),
new BundleAnalyzerPlugin({
analyzerMode: process.env.ANALYZE_BUNDLE ? 'server' : 'disabled',
analyzerHost: '127.0.0.1',
analyzerPort: 8888,
openAnalyzer: true,
}),
];
const rules = [
{
test: /\.(otf|woff(2)?)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
},
},
],
},
{
test: /\.(ttf|eot|svg|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
],
},
{
test: /\.jsx?$/,
exclude: /node_modules|vendor/,
use: ['babel-loader', 'stylelint-custom-processor-loader'],
},
];
if (process.env.RELEASE) {
mode = 'production';
entry = {
docs: './docs/js/main',
};
// Compile sass into css
rules.push({
test: /\.(scss|css)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'sass-loader',
options: {
includePaths: [
path.resolve(__dirname, './node_modules/bourbon-neat'),
],
},
},
],
}),
});
plugins = [
new ExtractTextPlugin('docs.css'),
new HtmlWebpackPlugin({
chunks: ['docs'],
template: 'docs/index.html',
filename: 'index.html',
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
];
optimization = {
minimizer: [new TerserPlugin()],
};
} else {
// Normal sass loader. This complains if it runs in the RELEASE job, so only apply it if RELEASE
// is falsey.
rules.push({
test: /\.(scss|css)$/,
use: [
'style-loader',
'css-loader',
{
loader: 'sass-loader',
options: {
includePaths: [
path.resolve(__dirname, './node_modules/bourbon-neat'),
],
},
},
],
});
}
module.exports = {
mode,
externals,
devtool: process.env.NODE_ENV !== 'production' ? 'eval-source-map' : false,
resolveLoader: {
alias: {
'react-docs': path.join(__dirname, 'src/loaders/react-docs.js'),
},
},
resolve: {
extensions: ['.js', '.jsx'],
},
entry,
output,
plugins,
optimization,
module: {
rules,
},
};
| weaveworks/ui-components |
<|start_filename|>CognitiveBot/CognitiveBot/Helpers/Constants.cs<|end_filename|>
using System;
namespace CognitiveBot.Helpers
{
public static class Constants
{
public const string LoginIntent = "Login";
public const string ProductInfoIntent = "ProductInfo";
public const string AddToCartIntent = "AddToCart";
public const string PlaceOrderIntent = "PlaceOrder";
public const string ProductLabel = "Product";
public const string ProductNameLabel = "ProductName";
public const string EmailLabel = "builtin.email";
public const string NumberLabel = "builtin.number";
}
}
<|start_filename|>CognitiveBot/OfflineDirectLine/Dockerfile<|end_filename|>
FROM node:10.15.3
ARG UseDirectLinePort
ENV UseDirectLinePort=${UseDirectLinePort}
ARG BotEndPoint
ENV BotEndPoint=${BotEndPoint}
ARG BotPath
ENV BotPath=${BotPath}
ARG UseDirectLineHost
ENV UseDirectLineHost=${UseDirectLineHost}
WORKDIR /usr/src/app
COPY OfflineDirectLine/package*.json ./
RUN npm install
COPY OfflineDirectLine/. .
RUN ls -la .
EXPOSE 3010
EXPOSE 9222
CMD [ "npm", "start", "debug" ]
<|start_filename|>CognitiveBot/CognitiveBot/Helpers/TextAnalysisHelper.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using CognitiveBot.Model;
using Newtonsoft.Json;
namespace CognitiveBot.Helpers
{
public class TextAnalysisHelper
{
public static async Task<ResultDocument> MakeKeywordAnalysisAsync(IEnumerable<RequestMessage> messages, string endpoint)
{
ResultDocument messageAnalysis = null;
HttpClient httpClient = new HttpClient();
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(new RequestDocument() { Messages = messages }));
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var url = $"http://{endpoint}/text/analytics/v2.0/keyPhrases";
Console.WriteLine(url);
Console.WriteLine(JsonConvert.SerializeObject(new RequestDocument() { Messages = messages }));
using (HttpResponseMessage responseMessage = await httpClient.PostAsync(url, httpContent))
{
responseMessage.EnsureSuccessStatusCode();
if (responseMessage.IsSuccessStatusCode)
{
string stringResponse = await responseMessage.Content.ReadAsStringAsync();
messageAnalysis =
JsonConvert.DeserializeObject<ResultDocument>(
stringResponse);
}
}
return messageAnalysis;
}
public static async Task<LuisResult> MakeLUISAnalysisAsync(string message, string endpoint, string appId)
{
LuisResult messageAnalysis = null;
HttpClient httpClient = new HttpClient();
string url = $"http://{endpoint}/luis/v2.0/apps/{appId}?q={message}&staging=false&timezoneOffset=0&verbose=false&log=true";
Console.WriteLine(url);
using (HttpResponseMessage responseMessage = await httpClient.GetAsync(url))
{
responseMessage.EnsureSuccessStatusCode();
if (responseMessage.IsSuccessStatusCode)
{
string stringResponse = await responseMessage.Content.ReadAsStringAsync();
messageAnalysis =
JsonConvert.DeserializeObject<LuisResult>(
stringResponse);
}
}
return messageAnalysis;
}
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Model/RequestMessage.cs<|end_filename|>
using System;
using Newtonsoft.Json;
namespace CognitiveBot.Model
{
public class RequestMessage
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("text")]
public string MessageText { get; set; }
[JsonProperty("language")]
public string Language => "es";
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Helpers/DbHelper.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
using CognitiveBot.Model;
namespace CognitiveBot.Helpers
{
public class DbHelper
{
public static List<Product_Model> GetProducts(string product, string dataSource, string user, string password)
{
List<Product_Model> products = new List<Product_Model>();
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = dataSource;
builder.UserID = user;
builder.Password = password;
builder.InitialCatalog = "AdventureWorks";
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
connection.Open();
StringBuilder sb = new StringBuilder();
if (string.IsNullOrWhiteSpace(product))
{
sb.Append("select distinct(p.ProductID), p.Name, isnull(Color, ''), ListPrice, ThumbNailPhoto as Photo, c.Name as Category, m.Name as Model from SalesLT.Product p join SalesLT.ProductCategory c on p.ProductCategoryID = c.ProductCategoryID join SalesLT.ProductModel m on p.ProductModelID = m.ProductModelID join SalesLT.SalesOrderDetail s on s.ProductID = p.ProductID ");
sb.Append(" where p.ProductID in (select top 5 p.ProductID from SalesLT.Product p join SalesLT.SalesOrderDetail s on s.ProductID = p.ProductID group by p.ProductID order by sum(s.OrderQty) desc)");
}
else
{
sb.Append("select ProductID, p.Name, isnull(Color, ''), ListPrice, ThumbNailPhoto as Photo, c.Name as Category, m.Name as Model ");
sb.Append(" FROM [AdventureWorks].[SalesLT].[Product] p ");
sb.Append(" JOIN [AdventureWorks].[SalesLT].[ProductCategory] c on p.ProductCategoryID = c.ProductCategoryID ");
sb.Append(" JOIN [AdventureWorks].[SalesLT].[ProductModel] m on p.ProductModelID = m.ProductModelID");
sb.Append($" WHERE p.Name LIKE '%{product}%'");
}
String sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
products.Add(
new Product_Model
{
ProductID = reader.GetInt32(0),
Name = reader.GetString(1),
Color = reader.GetString(2),
ListPrice = reader.GetDecimal(3),
PhotoBytes = (byte[])reader["Photo"],
Category = reader.GetString(5),
Model = reader.GetString(6)
});
}
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
return products;
}
public static Product_Model GetProduct(int product, string dataSource, string user, string password)
{
Product_Model products = new Product_Model();
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = dataSource;
builder.UserID = user;
builder.Password = password;
builder.InitialCatalog = "AdventureWorks";
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
connection.Open();
StringBuilder sb = new StringBuilder();
sb.Append("select ProductID, p.Name, isnull(Color, ''), ListPrice, ThumbNailPhoto as Photo, c.Name as Category, m.Name as Model ");
sb.Append(" FROM [AdventureWorks].[SalesLT].[Product] p ");
sb.Append(" JOIN [AdventureWorks].[SalesLT].[ProductCategory] c on p.ProductCategoryID = c.ProductCategoryID ");
sb.Append(" JOIN [AdventureWorks].[SalesLT].[ProductModel] m on p.ProductModelID = m.ProductModelID");
sb.Append($" WHERE p.[ProductID] = {product}");
String sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
products =
new Product_Model
{
ProductID = reader.GetInt32(0),
Name = reader.GetString(1),
Color = reader.GetString(2),
ListPrice = reader.GetDecimal(3),
PhotoBytes = (byte[])reader["Photo"],
Category = reader.GetString(5),
Model = reader.GetString(6)
};
}
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
return products;
}
public static CustomerShort GetCustomer(string email, string dataSource, string user, string password)
{
var customer = new CustomerShort();
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = dataSource;
builder.UserID = user;
builder.Password = password;
builder.InitialCatalog = "AdventureWorks";
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
connection.Open();
StringBuilder sb = new StringBuilder();
sb.Append("select CustomerID, CompanyName, EmailAddress, CONCAT(Title, FirstName, LastName, Suffix) AS CustomerName ");
sb.Append(" FROM [AdventureWorks].[SalesLT].[Customer] ");
sb.Append($" WHERE EmailAddress = '{email}'");
String sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
customer = new CustomerShort()
{
CustomerID = reader.GetInt32(0),
CompanyName = reader.GetString(1),
EmailAddress = reader.GetString(2),
CustomerName = reader.GetString(3)
};
}
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
return customer;
}
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Config/EnvironmentConfig.cs<|end_filename|>
using System;
namespace CognitiveBot.Config
{
public class EnvironmentConfig
{
public String DataSource { get; set; }
public String DbUser { get; set; }
public String Password { get; set; }
public String LanguageEndPoint { get; set; }
public String TextEndPoint { get; set; }
public String LuisEndPoint { get; set; }
public String LuisAppId { get; set; }
public String DirectLine { get; set; }
}
}
<|start_filename|>CognitiveBot/OfflineDirectLine/DirectLineCore/bridge.js<|end_filename|>
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
exports.__esModule = true;
var bodyParser = require("body-parser");
var express = require("express");
var fetch = require("isomorphic-fetch");
var moment = require("moment");
var uuidv4 = require("uuid/v4");
var expiresIn = 1800;
var conversationsCleanupInterval = 10000;
var conversations = {};
var botDataStore = {};
exports.getRouter = function (serviceUrl, botUrl, conversationInitRequired) {
if (conversationInitRequired === void 0) { conversationInitRequired = true; }
var router = express.Router();
router.use(bodyParser.json()); // for parsing application/json
router.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
router.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, PATCH, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, x-ms-bot-agent');
next();
});
// CLIENT ENDPOINT
router.options('/directline', function (req, res) {
res.status(200).end();
});
// Creates a conversation
router.post('/directline/conversations', function (req, res) {
var conversationId = uuidv4().toString();
conversations[conversationId] = {
conversationId: conversationId,
history: []
};
console.log('Created conversation with conversationId: ' + conversationId);
var activity = createConversationUpdateActivity(serviceUrl, conversationId);
fetch(botUrl, {
method: 'POST',
body: JSON.stringify(activity),
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
res.status(response.status).send({
conversationId: conversationId,
expiresIn: expiresIn
});
});
});
// Reconnect API
router.get('/v3/directline/conversations/:conversationId', function (req, res) { console.warn('/v3/directline/conversations/:conversationId not implemented'); });
// Gets activities from store (local history array for now)
router.get('/directline/conversations/:conversationId/activities', function (req, res) {
var watermark = req.query.watermark && req.query.watermark !== 'null' ? Number(req.query.watermark) : 0;
var conversation = getConversation(req.params.conversationId, conversationInitRequired);
if (conversation) {
// If the bot has pushed anything into the history array
if (conversation.history.length > watermark) {
var activities = conversation.history.slice(watermark);
res.status(200).json({
activities: activities,
watermark: watermark + activities.length
});
}
else {
res.status(200).send({
activities: [],
watermark: watermark
});
}
}
else {
// Conversation was never initialized
res.status(400).send();
}
});
// Sends message to bot. Assumes message activities
router.post('/directline/conversations/:conversationId/activities', function (req, res) {
var incomingActivity = req.body;
// Make copy of activity. Add required fields
var activity = createMessageActivity(incomingActivity, serviceUrl, req.params.conversationId);
var conversation = getConversation(req.params.conversationId, conversationInitRequired);
if (conversation) {
conversation.history.push(activity);
fetch(botUrl, {
method: 'POST',
body: JSON.stringify(activity),
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
res.status(response.status).json({ id: activity.id });
});
}
else {
// Conversation was never initialized
res.status(400).send();
}
});
router.post('/v3/directline/conversations/:conversationId/upload', function (req, res) { console.warn('/v3/directline/conversations/:conversationId/upload not implemented'); });
router.get('/v3/directline/conversations/:conversationId/stream', function (req, res) { console.warn('/v3/directline/conversations/:conversationId/stream not implemented'); });
// BOT CONVERSATION ENDPOINT
router.post('/v3/conversations', function (req, res) { console.warn('/v3/conversations not implemented'); });
router.post('/v3/conversations/:conversationId/activities', function (req, res) {
var activity;
activity = req.body;
activity.id = uuidv4();
activity.from = { id: 'id', name: 'Bot' };
var conversation = getConversation(req.params.conversationId, conversationInitRequired);
if (conversation) {
conversation.history.push(activity);
res.status(200).send();
}
else {
// Conversation was never initialized
res.status(400).send();
}
});
router.post('/v3/conversations/:conversationId/activities/:activityId', function (req, res) {
var activity;
activity = req.body;
activity.id = uuidv4();
activity.from = { id: 'id', name: 'Bot' };
var conversation = getConversation(req.params.conversationId, conversationInitRequired);
if (conversation) {
conversation.history.push(activity);
res.status(200).send();
}
else {
// Conversation was never initialized
res.status(400).send();
}
});
router.get('/v3/conversations/:conversationId/members', function (req, res) { console.warn('/v3/conversations/:conversationId/members not implemented'); });
router.get('/v3/conversations/:conversationId/activities/:activityId/members', function (req, res) { console.warn('/v3/conversations/:conversationId/activities/:activityId/members'); });
// BOTSTATE ENDPOINT
router.get('/v3/botstate/:channelId/users/:userId', function (req, res) {
console.log('Called GET user data');
getBotData(req, res);
});
router.get('/v3/botstate/:channelId/conversations/:conversationId', function (req, res) {
console.log(('Called GET conversation data'));
getBotData(req, res);
});
router.get('/v3/botstate/:channelId/conversations/:conversationId/users/:userId', function (req, res) {
console.log('Called GET private conversation data');
getBotData(req, res);
});
router.post('/v3/botstate/:channelId/users/:userId', function (req, res) {
console.log('Called POST setUserData');
setUserData(req, res);
});
router.post('/v3/botstate/:channelId/conversations/:conversationId', function (req, res) {
console.log('Called POST setConversationData');
setConversationData(req, res);
});
router.post('/v3/botstate/:channelId/conversations/:conversationId/users/:userId', function (req, res) {
setPrivateConversationData(req, res);
});
router["delete"]('/v3/botstate/:channelId/users/:userId', function (req, res) {
console.log('Called DELETE deleteStateForUser');
deleteStateForUser(req, res);
});
return router;
};
/**
* @param app The express app where your offline-directline endpoint will live
* @param port The port where your offline-directline will be hosted
* @param botUrl The url of the bot (e.g. http://127.0.0.1:3978/api/messages)
* @param conversationInitRequired Requires that a conversation is initialized before it is accessed, returning a 400
* when not the case. If set to false, a new conversation reference is created on the fly. This is true by default.
*/
exports.initializeRoutes = function (app, host, port, botUrl, conversationInitRequired) {
if (port === void 0) { port = 3000; }
if (conversationInitRequired === void 0) { conversationInitRequired = true; }
conversationsCleanup();
var directLineEndpoint = host + ":" + port;
var router = exports.getRouter(directLineEndpoint, botUrl, conversationInitRequired);
app.use(router);
app.listen(port, function () {
console.log("Listening for messages from client on " + directLineEndpoint);
console.log("Routing messages to bot on " + botUrl);
});
};
var getConversation = function (conversationId, conversationInitRequired) {
// Create conversation on the fly when needed and init not required
if (!conversations[conversationId] && !conversationInitRequired) {
conversations[conversationId] = {
conversationId: conversationId,
history: []
};
}
return conversations[conversationId];
};
var getBotDataKey = function (channelId, conversationId, userId) {
return "$" + (channelId || '*') + "!" + (conversationId || '*') + "!" + (userId || '*');
};
var setBotData = function (channelId, conversationId, userId, incomingData) {
var key = getBotDataKey(channelId, conversationId, userId);
var newData = {
eTag: new Date().getTime().toString(),
data: incomingData.data
};
if (incomingData) {
botDataStore[key] = newData;
}
else {
delete botDataStore[key];
newData.eTag = '*';
}
return newData;
};
var getBotData = function (req, res) {
var key = getBotDataKey(req.params.channelId, req.params.conversationId, req.params.userId);
console.log('Data key: ' + key);
res.status(200).send(botDataStore[key] || { data: null, eTag: '*' });
};
var setUserData = function (req, res) {
res.status(200).send(setBotData(req.params.channelId, req.params.conversationId, req.params.userId, req.body));
};
var setConversationData = function (req, res) {
res.status(200).send(setBotData(req.params.channelId, req.params.conversationId, req.params.userId, req.body));
};
var setPrivateConversationData = function (req, res) {
res.status(200).send(setBotData(req.params.channelId, req.params.conversationId, req.params.userId, req.body));
};
var deleteStateForUser = function (req, res) {
Object.keys(botDataStore)
.forEach(function (key) {
if (key.endsWith("!{req.query.userId}")) {
delete botDataStore[key];
}
});
res.status(200).send();
};
// CLIENT ENDPOINT HELPERS
var createMessageActivity = function (incomingActivity, serviceUrl, conversationId) {
return __assign({}, incomingActivity, { channelId: 'emulator', serviceUrl: serviceUrl, conversation: { id: conversationId }, id: uuidv4() });
};
var createConversationUpdateActivity = function (serviceUrl, conversationId) {
var activity = {
type: 'conversationUpdate',
channelId: 'emulator',
serviceUrl: serviceUrl,
conversation: { id: conversationId },
id: uuidv4(),
membersAdded: [],
membersRemoved: [],
from: { id: 'offline-directline', name: 'Offline Directline Server' }
};
return activity;
};
var conversationsCleanup = function () {
setInterval(function () {
var expiresTime = moment().subtract(expiresIn, 'seconds');
Object.keys(conversations).forEach(function (conversationId) {
if (conversations[conversationId].history.length > 0) {
var lastTime = moment(conversations[conversationId].history[conversations[conversationId].history.length - 1].localTimestamp);
if (lastTime < expiresTime) {
delete conversations[conversationId];
console.log('deleted cId: ' + conversationId);
}
}
});
}, conversationsCleanupInterval);
};
<|start_filename|>CognitiveBot/CognitiveBot/Model/ResultMessage.cs<|end_filename|>
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace CognitiveBot.Model
{
public class ResultMessage
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("score")]
public double Score { get; set; }
[JsonProperty("keyPhrases")]
public List<string> KeyPhrases { get; set; }
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Model/CustomerShort.cs<|end_filename|>
using System;
namespace CognitiveBot.Model
{
public class CustomerShort
{
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public string CompanyName { get; set; }
public string EmailAddress { get; set; }
}
}
<|start_filename|>CognitiveBot/libraries/Microsoft.Bot.Builder.Dialogs/Prompts/ChoicePrompt.cs<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs.Choices;
using Microsoft.Bot.Schema;
using static Microsoft.Recognizers.Text.Culture;
namespace Microsoft.Bot.Builder.Dialogs
{
public class ChoicePrompt : Prompt<FoundChoice>
{
private static readonly Dictionary<string, ChoiceFactoryOptions> DefaultChoiceOptions = new Dictionary<string, ChoiceFactoryOptions>()
{
{ Spanish, new ChoiceFactoryOptions { InlineSeparator = ", ", InlineOr = " o ", InlineOrMore = ", o ", IncludeNumbers = true } },
{ Dutch, new ChoiceFactoryOptions { InlineSeparator = ", ", InlineOr = " of ", InlineOrMore = ", of ", IncludeNumbers = true } },
{ English, new ChoiceFactoryOptions { InlineSeparator = ", ", InlineOr = " or ", InlineOrMore = ", or ", IncludeNumbers = true } },
{ French, new ChoiceFactoryOptions { InlineSeparator = ", ", InlineOr = " ou ", InlineOrMore = ", ou ", IncludeNumbers = true } },
{ German, new ChoiceFactoryOptions { InlineSeparator = ", ", InlineOr = " oder ", InlineOrMore = ", oder ", IncludeNumbers = true } },
{ Japanese, new ChoiceFactoryOptions { InlineSeparator = "、 ", InlineOr = " または ", InlineOrMore = "、 または ", IncludeNumbers = true } },
{ Portuguese, new ChoiceFactoryOptions { InlineSeparator = ", ", InlineOr = " ou ", InlineOrMore = ", ou ", IncludeNumbers = true } },
{ Chinese, new ChoiceFactoryOptions { InlineSeparator = ", ", InlineOr = " 要么 ", InlineOrMore = ", 要么 ", IncludeNumbers = true } },
};
public ChoicePrompt(string dialogId, PromptValidator<FoundChoice> validator = null, string defaultLocale = null)
: base(dialogId, validator)
{
Style = ListStyle.Auto;
DefaultLocale = defaultLocale;
}
public ListStyle Style { get; set; }
public string DefaultLocale { get; set; }
public ChoiceFactoryOptions ChoiceOptions { get; set; }
public FindChoicesOptions RecognizerOptions { get; set; }
protected override async Task OnPromptAsync(ITurnContext turnContext, IDictionary<string, object> state, PromptOptions options, bool isRetry, CancellationToken cancellationToken = default(CancellationToken))
{
if (turnContext == null)
{
throw new ArgumentNullException(nameof(turnContext));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
// Determine culture
var culture = turnContext.Activity.Locale ?? DefaultLocale;
if (string.IsNullOrEmpty(culture) || !DefaultChoiceOptions.ContainsKey(culture))
{
culture = English;
}
// Format prompt to send
IMessageActivity prompt;
var choices = options.Choices ?? new List<Choice>();
var channelId = turnContext.Activity.ChannelId;
var choiceOptions = ChoiceOptions ?? DefaultChoiceOptions[culture];
var choiceStyle = options.Style ?? Style;
if (isRetry && options.RetryPrompt != null)
{
prompt = AppendChoices(options.RetryPrompt, channelId, choices, choiceStyle, choiceOptions);
}
else
{
prompt = AppendChoices(options.Prompt, channelId, choices, choiceStyle, choiceOptions);
}
// Send prompt
await turnContext.SendActivityAsync(prompt, cancellationToken).ConfigureAwait(false);
}
protected override Task<PromptRecognizerResult<FoundChoice>> OnRecognizeAsync(ITurnContext turnContext, IDictionary<string, object> state, PromptOptions options, CancellationToken cancellationToken = default(CancellationToken))
{
if (turnContext == null)
{
throw new ArgumentNullException(nameof(turnContext));
}
var choices = options.Choices ?? new List<Choice>();
var result = new PromptRecognizerResult<FoundChoice>();
if (turnContext.Activity.Type == ActivityTypes.Message)
{
var activity = turnContext.Activity;
var utterance = activity.Text;
var opt = RecognizerOptions ?? new FindChoicesOptions();
opt.Locale = activity.Locale ?? opt.Locale ?? DefaultLocale ?? English;
var results = ChoiceRecognizers.RecognizeChoices(utterance, choices, opt);
if (results != null && results.Count > 0)
{
result.Succeeded = true;
result.Value = results[0].Resolution;
}
}
return Task.FromResult(result);
}
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Helpers/ConversationnData.cs<|end_filename|>
using System;
namespace CognitiveBot.Helpers
{
public class ConversationData
{
public string Timestamp { get; set; }
public string ChannelId { get; set; }
public bool PromptedUserForName { get; set; } = false;
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Model/Product_Model.cs<|end_filename|>
using System;
namespace CognitiveBot.Model
{
public class Product_Model
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public decimal ListPrice { get; set; }
//public string Photo { get; set; }
public byte[] PhotoBytes { get; set; }
public string Category { get; set; }
public string Model { get; set; }
//public byte[] PhotoBytes => Convert.FromBase64String(Photo);
public string Photo => Convert.ToBase64String(PhotoBytes);
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Model/RequestDocument.cs<|end_filename|>
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace CognitiveBot.Model
{
public class RequestDocument
{
[JsonProperty("documents")]
public IEnumerable<RequestMessage> Messages { get; set; }
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Helpers/LuisParser.cs<|end_filename|>
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Bot.Builder;
namespace CognitiveBot.Helpers
{
public static class LuisParser
{
public static string GetEntityValue(RecognizerResult result, string intent = "")
{
foreach (var entity in result.Entities)
{
var product = JObject.Parse(entity.Value.ToString())[Constants.ProductLabel];
var productName = JObject.Parse(entity.Value.ToString())[Constants.ProductNameLabel];
var email = JObject.Parse(entity.Value.ToString())[Constants.EmailLabel];
var number = JObject.Parse(entity.Value.ToString())[Constants.NumberLabel];
if (number != null && intent == Constants.NumberLabel)
{
dynamic value = JsonConvert.DeserializeObject<dynamic>(entity.Value.ToString());
return $"{Constants.NumberLabel}_{value.number[0].text}";
}
if (product != null)
return $"{Constants.ProductLabel}_";
if (productName != null)
{
dynamic value = JsonConvert.DeserializeObject<dynamic>(entity.Value.ToString());
return $"{Constants.ProductNameLabel}_{value.ProductName[0].text}";
}
if (email != null)
{
dynamic value = JsonConvert.DeserializeObject<dynamic>(entity.Value.ToString());
return $"{Constants.EmailLabel}_{value.email[0].text}";
}
}
return "_";
}
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Model/LuisResult.cs<|end_filename|>
using System;
using System.Collections.Generic;
namespace CognitiveBot.Model
{
public class TopScoringIntent
{
public string Intent { get; set; }
public double Score { get; set; }
}
public class Entity
{
public string entity { get; set; }
public string Type { get; set; }
public int StartIndex { get; set; }
public int EndIndex { get; set; }
public double Score { get; set; }
}
public class LuisResult
{
public string Query { get; set; }
public TopScoringIntent TopScoringIntent { get; set; }
public List<Entity> Entities { get; set; }
}
}
<|start_filename|>CognitiveBot/sql_server/Dockerfile<|end_filename|>
FROM mcr.microsoft.com/mssql/server:2017-latest
ARG SA_PASSWORD
ENV SA_PASSWORD=${<PASSWORD>}
ARG ACCEPT_EULA
ENV ACCEPT_EULA=${ACCEPT_EULA}
COPY sql_server/import-data.sh /usr/src/app/
COPY sql_server/setup.sql /usr/src/app/
# Grant permissions for the import-data script to be executable
RUN ( /opt/mssql/bin/sqlservr --accept-eula & ) | grep -q "Service Broker manager has started" \
&& /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P $SA_PASSWORD -i /usr/src/app/setup.sql \
&& pkill sqlservr
<|start_filename|>CognitiveBot/CognitiveBot/Model/ResultDocument.cs<|end_filename|>
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace CognitiveBot.Model
{
public class ResultDocument
{
[JsonProperty("documents")]
public IEnumerable<ResultMessage> ResultMessages { get; set; }
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Dockerfile<|end_filename|>
FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 3978
EXPOSE 3010
ARG DataSource
ENV DataSource=${DataSource}
ARG DbUser
ENV DbUser=${DbUser}
ARG Password
ENV Password=${Password}
ARG LanguageEndPoint
ENV LanguageEndPoint=${LanguageEndPoint}
ARG TextEndPoint
ENV TextEndPoint=${TextEndPoint}
ARG LuisEndPoint
ENV LuisEndPoint=${LuisEndPoint}
ARG LuisAppId
ENV LuisAppId=${LuisAppId}
ARG DirectLine
ENV DirectLine=${DirectLine}
FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /src
COPY libraries .
COPY CognitiveBot/CognitiveBot.csproj ./
RUN dotnet restore ./CognitiveBot.csproj
COPY . .
RUN dotnet build CognitiveBot/CognitiveBot.csproj -c Release -o /app
FROM build AS publish
RUN dotnet publish CognitiveBot/CognitiveBot.csproj -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "CognitiveBot.dll"]
<|start_filename|>CognitiveBot/CognitiveBot/CognitiveBotBot.cs<|end_filename|>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using CognitiveBot.Config;
using CognitiveBot.Helpers;
using CognitiveBot.Model;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Configuration;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace CognitiveBot
{
/// <summary>
/// Represents a bot that processes incoming activities.
/// For each user interaction, an instance of this class is created and the OnTurnAsync method is called.
/// This is a Transient lifetime service. Transient lifetime services are created
/// each time they're requested. For each Activity received, a new instance of this
/// class is created. Objects that are expensive to construct, or have a lifetime
/// beyond the single turn, should be carefully managed.
/// For example, the <see cref="MemoryStorage"/> object and associated
/// <see cref="IStatePropertyAccessor{T}"/> object are created with a singleton lifetime.
/// </summary>
/// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1"/>
public class CognitiveBotBot: ActivityHandler, IBot
{
private const string WelcomeMessage = "Welcome to Adventure Works";
private const string InfoMessage = "How can we help you? You can talk to our assistant. Try saying 'I want to access' or 'show me the products list'. If you want to know about a specific product, you can use 'please tell me about mountain bike' or similar messages. Our smart digital assistant will do its best to help you!";
private const string PatternMessage = @"You can also say help to display some options";
//private readonly BotService _services;
//public static readonly string LuisKey = "AdventureWorksBotBot";
private BotState _conversationState;
private BotState _userState;
private readonly CognitiveBotAccessors _accessors;
private readonly ILogger _logger;
private readonly EnvironmentConfig _configuration;
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="conversationState">The managed conversation state.</param>
/// <param name="loggerFactory">A <see cref="ILoggerFactory"/> that is hooked to the Azure App Service provider.</param>
/// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1#windows-eventlog-provider"/>
public CognitiveBotBot(ConversationState cs, ILoggerFactory loggerFactory, IOptions<EnvironmentConfig> configuration,
//BotService botService,
ConversationState conversationState, UserState userState)
{
//_services = services ?? throw new System.ArgumentNullException(nameof(services));
this._conversationState = cs;
_userState = userState;
_configuration = configuration.Value;
if (conversationState == null)
{
throw new System.ArgumentNullException(nameof(conversationState));
}
if (loggerFactory == null)
{
throw new System.ArgumentNullException(nameof(loggerFactory));
}
_accessors = new CognitiveBotAccessors(conversationState)
{
CounterState = conversationState.CreateProperty<CounterState>(CognitiveBotAccessors.CounterStateName),
};
_logger = loggerFactory.CreateLogger<CognitiveBotBot>();
_logger.LogTrace("Turn start.");
}
static bool welcome = false;
public async override Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
// aqui se procesan las cards
if (turnContext.Activity.Type == ActivityTypes.Message)
{
var luisAnalysis = await CognitiveBot.Helpers.TextAnalysisHelper.MakeLUISAnalysisAsync(WebUtility.UrlEncode(turnContext.Activity.Text), _configuration.LuisEndPoint, _configuration.LuisAppId);
if (luisAnalysis.TopScoringIntent.Score > .4)
{
switch (luisAnalysis.TopScoringIntent.Intent)
{
case Constants.LoginIntent:
var ent = luisAnalysis.Entities.FirstOrDefault();
switch (ent.Type)
{
case Constants.EmailLabel:
var email = ent.entity;
var customer = DbHelper.GetCustomer(email, _configuration.DataSource, _configuration.DbUser, _configuration.Password);
var userName = "";
if (customer != null)
{
userName = customer.CustomerName;
var hero = new HeroCard();
hero.Title = "Welcome";
hero.Text = customer.CustomerName;
hero.Subtitle = customer.CompanyName;
var us = _userState.CreateProperty<CustomerShort>(nameof(CustomerShort));
var c = await us.GetAsync(turnContext, () => new CustomerShort());
c.CompanyName = customer.CompanyName;
c.CustomerName = customer.CustomerName;
c.CustomerID = customer.CustomerID;
c.EmailAddress = customer.EmailAddress;
var response = turnContext.Activity.CreateReply();
response.Attachments = new List<Attachment>() { hero.ToAttachment() };
await turnContext.SendActivityAsync(response, cancellationToken);
//await turnContext.SendActivityAsync($"Welcome {userName}");
}
else
await turnContext.SendActivityAsync($"User not found. Pleae try again");
break;
default:
await turnContext.SendActivityAsync("Please add your email to your login message");
break;
}
break;
case Constants.ProductInfoIntent:
var entity = luisAnalysis.Entities.FirstOrDefault(x => x.Type == Constants.ProductLabel || x.Type == Constants.ProductNameLabel);
switch (entity.Type)
{
case Constants.ProductLabel:
case Constants.ProductNameLabel:
var product = "";
var message = "Our Top 5 Products are:";
var productName = entity.entity;
if (entity.Type == Constants.ProductNameLabel)
{
product = productName;
message = "Your query returned the following products: ";
}
var products = DbHelper.GetProducts(product, _configuration.DataSource, _configuration.DbUser, _configuration.Password);
var data = "No results";
var typing = Activity.CreateTypingActivity();
var delay = new Activity { Type = "delay", Value = 5000 };
if (products != null)
{
var responseProducts = turnContext.Activity.CreateReply();
responseProducts.AttachmentLayout = AttachmentLayoutTypes.Carousel;
responseProducts.Attachments = new List<Attachment>();
foreach (var item in products)
{
var card = new HeroCard();
card.Subtitle = item.ListPrice.ToString("N2");
card.Title = item.Name;
card.Text = $"{item.Category} - {item.Model} - {item.Color}";
card.Buttons = new List<CardAction>()
{
new CardAction()
{
Value = $"Add product {item.ProductID} to the cart",
Type = ActionTypes.ImBack,
Title = " Add To Cart "
}
};
card.Images = new List<CardImage>()
{
new CardImage()
{
Url = $"data:image/gif;base64,{item.Photo}"
}
};
var plAttachment = card.ToAttachment();
responseProducts.Attachments.Add(plAttachment);
}
var activities = new IActivity[]
{
typing,
delay,
MessageFactory.Text($"{message}: "),
responseProducts,
MessageFactory.Text("What else can I do for you?")
};
await turnContext.SendActivitiesAsync(activities);
}
else
{
var activities = new IActivity[]
{ typing,
delay,
MessageFactory.Text($"{message}: {data}"),
MessageFactory.Text("What else can I do for you?")
};
await turnContext.SendActivitiesAsync(activities);
}
break;
default:
break;
}
break;
case Constants.AddToCartIntent:
var entProd = luisAnalysis.Entities.FirstOrDefault();
var number = 0;
if (entProd.Type == Constants.NumberLabel)
{
number = int.Parse(entProd.entity);
var product = DbHelper.GetProduct(number, _configuration.DataSource, _configuration.DbUser, _configuration.Password);
var userStateAccessors = _userState.CreateProperty<CustomerShort>(nameof(CustomerShort));
var shoppingCartAccessors = _userState.CreateProperty<List<ShoppingCart>>(nameof(List<ShoppingCart>));
var customer = await userStateAccessors.GetAsync(turnContext, () => new CustomerShort());
var cart = await shoppingCartAccessors.GetAsync(turnContext, () => new List<ShoppingCart>());
var item = new ShoppingCart()
{
CustomerID = customer.CustomerID,
ProductID = product.ProductID,
ProductName = product.Name,
ListPrice = product.ListPrice,
Photo = product.Photo
};
cart.Add(item);
var act = new IActivity[]
{
Activity.CreateTypingActivity(),
new Activity { Type = "delay", Value = 5000 },
MessageFactory.Text($"Product {product.Name} was added to the cart."),
MessageFactory.Text("What else can I do for you?")
};
await turnContext.SendActivitiesAsync(act);
}
break;
case Constants.PlaceOrderIntent:
//////////////////////77
var usAccessors = _userState.CreateProperty<CustomerShort>(nameof(CustomerShort));
var scAccessors = _userState.CreateProperty<List<ShoppingCart>>(nameof(List<ShoppingCart>));
var cust = await usAccessors.GetAsync(turnContext, () => new CustomerShort());
var shoppingCart = await scAccessors.GetAsync(turnContext, () => new List<ShoppingCart>());
if (shoppingCart.Count() > 0)
{
var receipt = turnContext.Activity.CreateReply();
receipt.Attachments = new List<Attachment>();
var card = new ReceiptCard();
card.Title = "Adventure Works";
card.Facts = new List<Fact>
{
new Fact("Name:", cust.CustomerName),
new Fact("E-mail:", cust.EmailAddress),
new Fact("Company:", cust.CompanyName),
};
decimal subtotal = 0;
decimal p = 16M / 100;
card.Items = new List<ReceiptItem>();
foreach (var product in shoppingCart)
{
var item = new ReceiptItem();
item.Price = product.ListPrice.ToString("N2");
item.Quantity = "1";
item.Text = product.ProductName;
item.Subtitle = product.ProductName;
item.Image = new CardImage()
{
Url = $"data:image/gif;base64, {product.Photo}"
};
subtotal += product.ListPrice;
card.Items.Add(item);
//var plAttachment = card.ToAttachment();
//receipt.Attachments.Add(plAttachment);
}
receipt.Attachments.Add(card.ToAttachment());
var tax = subtotal * p;
card.Tax = tax.ToString("N2");
var total = subtotal + tax;
card.Total = total.ToString("N2");
var activities = new IActivity[]
{
Activity.CreateTypingActivity(),
new Activity { Type = "delay", Value = 5000 },
MessageFactory.Text("Here is your receipt: "),
receipt,
MessageFactory.Text("What else can I do for you?")
};
await turnContext.SendActivitiesAsync(activities);
}
break;
default:
break;
}
}
else
{
var text = turnContext.Activity.Text.ToLowerInvariant();
switch (text)
{
case "help":
await SendIntroCardAsync(turnContext, cancellationToken);
break;
default:
await turnContext.SendActivityAsync("I did not understand you, sorry. Try again with a different sentence, please", cancellationToken: cancellationToken);
break;
}
}
}
else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
{
if (!welcome)
{
welcome = true;
await turnContext.SendActivityAsync($"Hi there. {WelcomeMessage}", cancellationToken: cancellationToken);
await turnContext.SendActivityAsync(InfoMessage, cancellationToken: cancellationToken);
await turnContext.SendActivityAsync(PatternMessage, cancellationToken: cancellationToken);
}
}
else
{
await turnContext.SendActivityAsync($"{turnContext.Activity.Type} activity detected");
}
// Save any state changes that might have occured during the turn.
await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken);
await _userState.SaveChangesAsync(turnContext, false, cancellationToken);
}
private static async Task SendIntroCardAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
var response = turnContext.Activity.CreateReply();
var card = new HeroCard();
card.Title = WelcomeMessage;
card.Text = InfoMessage;
card.Images = new List<CardImage>() { new CardImage("https://drive.google.com/uc?id=1eE_WlkW8G9cSI_w9heIWeo53ZkMtQu4x") };
card.Buttons = new List<CardAction>()
{
new CardAction(ActionTypes.OpenUrl, "Enter my credentials", null, "Enter my credentials", "Enter my credentials", "Login"),
new CardAction(ActionTypes.OpenUrl, "Show me the product list", null, "Show me the product list", "Show me the product list", "ProductInfo"),
};
response.Attachments = new List<Attachment>() { card.ToAttachment() };
await turnContext.SendActivityAsync(response, cancellationToken);
}
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
// Get the state properties from the turn context.
var conversationStateAccessors = _conversationState.CreateProperty<ConversationData>(nameof(ConversationData));
var conversationData = await conversationStateAccessors.GetAsync(turnContext, () => new ConversationData());
var userStateAccessors = _userState.CreateProperty<CustomerShort>(nameof(CustomerShort));
var shoppingCartAccessors = _userState.CreateProperty<List<ShoppingCart>>(nameof(List<ShoppingCart>));
var customer = await userStateAccessors.GetAsync(turnContext, () => new CustomerShort());
var cart = await shoppingCartAccessors.GetAsync(turnContext, () => new List<ShoppingCart>());
if (string.IsNullOrEmpty(customer.CustomerName))
{
if (conversationData.PromptedUserForName)
{
customer.CustomerName = turnContext.Activity.Text?.Trim();
await turnContext.SendActivityAsync($"Thanks {customer.CustomerName}.");
conversationData.PromptedUserForName = false;
}
else
{
await turnContext.SendActivityAsync($"What is your name?");
conversationData.PromptedUserForName = true;
}
}
else
{
var messageTimeOffset = (DateTimeOffset)turnContext.Activity.Timestamp;
var localMessageTime = messageTimeOffset.ToLocalTime();
conversationData.Timestamp = localMessageTime.ToString();
conversationData.ChannelId = turnContext.Activity.ChannelId.ToString();
// Display state data.
//await turnContext.SendActivityAsync($"{customer.CustomerName} sent: {turnContext.Activity.Text}");
//await turnContext.SendActivityAsync($"Message received at: {conversationData.Timestamp}");
//await turnContext.SendActivityAsync($"Message received from: {conversationData.ChannelId}");
}
}
/*
/// <summary>
/// Every conversation turn for our Echo Bot will call this method.
/// There are no dialogs used, since it's "single turn" processing, meaning a single
/// request and response.
/// </summary>
/// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed
/// for processing this conversation turn. </param>
/// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects
/// or threads to receive notice of cancellation.</param>
/// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
/// <seealso cref="BotStateSet"/>
/// <seealso cref="ConversationState"/>
/// <seealso cref="IMiddleware"/>
public async Task OnTurnAsync2(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
// Handle Message activity type, which is the main activity type for shown within a conversational interface
// Message activities may contain text, speech, interactive cards, and binary or unknown attachments.
// see https://aka.ms/about-bot-activity-message to learn more about the message and other activity types
//var activity = turnContext.Activity;
//activity.ServiceUrl = _configuration.DirectLine;
//turnContext.Activity.ServiceUrl = _configuration.DirectLine;
//Console.WriteLine($"Service Url {_configuration.DirectLine}");
if (turnContext.Activity.Type == ActivityTypes.Message)
{
// Get the conversation state from the turn context.
var state = await _accessors.CounterState.GetAsync(turnContext, () => new CounterState());
// Bump the turn count for this conversation.
state.TurnCount++;
// Set the property using the accessor.
await _accessors.CounterState.SetAsync(turnContext, state);
// Save the new turn count into the conversation state.
await _accessors.ConversationState.SaveChangesAsync(turnContext);
// Echo back to the user whatever they typed.
string responseMessage = "Disculpa, no entendí :(";
var luisAnalysis = await CognitiveBot.Helpers.TextAnalysisHelper.MakeLUISAnalysisAsync(WebUtility.UrlEncode(turnContext.Activity.Text), _configuration.LuisEndPoint, _configuration.LuisAppId);
if (luisAnalysis.TopScoringIntent.Score > .5)
switch (luisAnalysis.TopScoringIntent.Intent)
{
case "Analizar":
IList<RequestMessage> messagesResult = new List<RequestMessage>();
foreach (var entity in luisAnalysis.Entities)
{
RequestMessage requestMessage = new RequestMessage()
{
Id = entity.StartIndex.ToString(),
MessageText = entity.entity
};
messagesResult.Add(requestMessage);
Console.WriteLine($"Entity {entity.entity}");
}
var textAnalysis = await Helpers.TextAnalysisHelper.MakeKeywordAnalysisAsync(messagesResult, _configuration.TextEndPoint);
var res = string.Join(" | ", textAnalysis.ResultMessages?.First()?.KeyPhrases?.Take(5));
responseMessage = res;
break;
case "ObtenerProductos":
List<Product> products = new List<Product>();
try
{
products = Helpers.DbHelper.GetProducts(_configuration.DataSource, _configuration.DbUser, _configuration.Password);
}
catch
{
}
StringBuilder builder = new StringBuilder();
builder.AppendLine($"Hay {products.Count}");
foreach (var product in products)
{
builder.AppendLine($"{product.Name} - {product.Quantity}");
}
responseMessage = builder.ToString();
break;
default:
responseMessage = $"Turn {state.TurnCount}: You sent '{turnContext.Activity.Text}'\n";
break;
}
await turnContext.SendActivityAsync(responseMessage);
}
else
{
await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected");
}
}
*/
}
}
<|start_filename|>CognitiveBot/OfflineDirectLine/index.js<|end_filename|>
const directline = require("offline-directline/bridge");
const express = require("express");
const app = express();
directline.initializeRoutes(app, process.env.UseDirectLineHost, process.env.UseDirectLinePort, "http://" + process.env.BotEndPoint + process.env.BotPath);
//directline.initializeRoutes(app, "http://directline",3000, "http://127.0.0.1:3978/api/messages");
<|start_filename|>CognitiveBot/OfflineDirectLine/package.json<|end_filename|>
{
"name": "offline_directline",
"version": "1.0.0",
"description": "Offline DirectLine on Docker",
"author": "<NAME>, <NAME>",
"main": "index.js",
"scripts": {
"start": "node --inspect=0.0.0.0 index.js"
},
"dependencies": {
"offline-directline": "file:DirectLineCore"
}
}
<|start_filename|>CognitiveBot/CognitiveBot/Model/ShoppingCart.cs<|end_filename|>
using System;
namespace CognitiveBot.Model
{
public class ShoppingCart
{
public int ProductID { get; set; }
public int CustomerID { get; set; }
public string ProductName { get; set; }
public string Photo { get; set; }
public decimal ListPrice { get; set; }
}
}
| humbertojaimes/microsoft-build-bot |
<|start_filename|>dist/jsx-pragmatic-demo.js<|end_filename|>
!function(root, factory) {
"object" == typeof exports && "object" == typeof module ? module.exports = factory() : "function" == typeof define && define.amd ? define("pragmatic", [], factory) : "object" == typeof exports ? exports.pragmatic = factory() : root.pragmatic = factory();
}("undefined" != typeof self ? self : this, (function() {
return function(modules) {
var installedModules = {};
function __webpack_require__(moduleId) {
if (installedModules[moduleId]) return installedModules[moduleId].exports;
var module = installedModules[moduleId] = {
i: moduleId,
l: !1,
exports: {}
};
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
module.l = !0;
return module.exports;
}
__webpack_require__.m = modules;
__webpack_require__.c = installedModules;
__webpack_require__.d = function(exports, name, getter) {
__webpack_require__.o(exports, name) || Object.defineProperty(exports, name, {
enumerable: !0,
get: getter
});
};
__webpack_require__.r = function(exports) {
"undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(exports, Symbol.toStringTag, {
value: "Module"
});
Object.defineProperty(exports, "__esModule", {
value: !0
});
};
__webpack_require__.t = function(value, mode) {
1 & mode && (value = __webpack_require__(value));
if (8 & mode) return value;
if (4 & mode && "object" == typeof value && value && value.__esModule) return value;
var ns = Object.create(null);
__webpack_require__.r(ns);
Object.defineProperty(ns, "default", {
enumerable: !0,
value: value
});
if (2 & mode && "string" != typeof value) for (var key in value) __webpack_require__.d(ns, key, function(key) {
return value[key];
}.bind(null, key));
return ns;
};
__webpack_require__.n = function(module) {
var getter = module && module.__esModule ? function() {
return module.default;
} : function() {
return module;
};
__webpack_require__.d(getter, "a", getter);
return getter;
};
__webpack_require__.o = function(object, property) {
return {}.hasOwnProperty.call(object, property);
};
__webpack_require__.p = "";
return __webpack_require__(__webpack_require__.s = 0);
}([ function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function _renderChildren(children, renderer) {
var result = [];
for (var _i2 = 0; _i2 < children.length; _i2++) {
var renderedChild = children[_i2].render(renderer);
if (renderedChild) if (Array.isArray(renderedChild)) for (var _i4 = 0; _i4 < renderedChild.length; _i4++) {
var subchild = renderedChild[_i4];
subchild && result.push(subchild);
} else result.push(renderedChild);
}
return result;
}
var node_ElementNode = function() {
function ElementNode(name, props, children) {
this.type = "element";
this.name = void 0;
this.props = void 0;
this.children = void 0;
this.onRender = void 0;
this.name = name;
this.props = props || {};
this.children = children;
var onRender = this.props.onRender;
if ("function" == typeof onRender) {
this.onRender = onRender;
delete props.onRender;
}
}
var _proto = ElementNode.prototype;
_proto.render = function(renderer) {
var el = renderer(this);
this.onRender && this.onRender(el);
return el;
};
_proto.renderChildren = function(renderer) {
return _renderChildren(this.children, renderer);
};
return ElementNode;
}();
var node_FragmentNode = function() {
function FragmentNode(children) {
this.type = "fragment";
this.children = void 0;
this.children = children;
}
FragmentNode.prototype.render = function(renderer) {
return _renderChildren(this.children, renderer);
};
return FragmentNode;
}();
var node_TextNode = function() {
function TextNode(text) {
this.type = "text";
this.text = void 0;
this.text = text;
}
TextNode.prototype.render = function(renderer) {
return renderer(this);
};
return TextNode;
}();
var node_ComponentNode = function() {
function ComponentNode(component, props, children) {
this.type = "component";
this.component = void 0;
this.props = void 0;
this.children = void 0;
this.component = component;
this.props = props || {};
this.children = children;
this.props.children = children;
}
var _proto4 = ComponentNode.prototype;
_proto4.renderComponent = function(renderer) {
var child = function(child) {
var children = normalizeChildren(Array.isArray(child) ? child : [ child ]);
return 1 === children.length ? children[0] : children.length > 1 ? new node_FragmentNode(children) : void 0;
}(this.component(this.props, this.children));
if (child) return child.render(renderer);
};
_proto4.render = function(renderer) {
return renderer(this);
};
_proto4.renderChildren = function(renderer) {
return _renderChildren(this.children, renderer);
};
return ComponentNode;
}();
function normalizeChildren(children) {
var result = [];
for (var _i6 = 0; _i6 < children.length; _i6++) {
var child = children[_i6];
if (child) if ("string" == typeof child || "number" == typeof child) result.push(new node_TextNode(child.toString())); else {
if ("boolean" == typeof child) continue;
if (Array.isArray(child)) for (var _i8 = 0, _normalizeChildren2 = normalizeChildren(child); _i8 < _normalizeChildren2.length; _i8++) result.push(_normalizeChildren2[_i8]); else {
if (!child || "element" !== child.type && "text" !== child.type && "component" !== child.type) throw new TypeError("Unrecognized node type: " + typeof child);
result.push(child);
}
}
}
return result;
}
var node_node = function(element, props) {
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) children[_key - 2] = arguments[_key];
children = normalizeChildren(children);
if ("string" == typeof element) return new node_ElementNode(element, props, children);
if ("function" == typeof element) return new node_ComponentNode(element, props, children);
throw new TypeError("Expected jsx element to be a string or a function");
};
function isDefined(val) {
return null != val;
}
var _ELEMENT_DEFAULT_XML_, _ATTRIBUTE_DEFAULT_XM, _ADD_CHILDREN;
var ELEMENT_DEFAULT_XML_NAMESPACE = ((_ELEMENT_DEFAULT_XML_ = {}).svg = "http://www.w3.org/2000/svg",
_ELEMENT_DEFAULT_XML_);
var ATTRIBUTE_DEFAULT_XML_NAMESPACE = ((_ATTRIBUTE_DEFAULT_XM = {})["xlink:href"] = "http://www.w3.org/1999/xlink",
_ATTRIBUTE_DEFAULT_XM);
function createTextElement(doc, node) {
return doc.createTextNode(node.text);
}
function addProps(el, node) {
var props = node.props;
for (var _i4 = 0, _Object$keys2 = Object.keys(props); _i4 < _Object$keys2.length; _i4++) {
var prop = _Object$keys2[_i4];
var val = props[prop];
if (null != val && "el" !== prop && "innerHTML" !== prop) if (prop.match(/^on[A-Z][a-z]/) && "function" == typeof val) el.addEventListener(prop.slice(2).toLowerCase(), val); else if ("string" == typeof val || "number" == typeof val) {
var xmlNamespace = ATTRIBUTE_DEFAULT_XML_NAMESPACE[prop];
xmlNamespace ? el.setAttributeNS(xmlNamespace, prop, val.toString()) : el.setAttribute(prop, val.toString());
} else "boolean" == typeof val && !0 === val && el.setAttribute(prop, "");
}
"iframe" !== el.tagName.toLowerCase() || props.id || el.setAttribute("id", "jsx-iframe-" + "xxxxxxxxxx".replace(/./g, (function() {
return "0123456789abcdef".charAt(Math.floor(Math.random() * "0123456789abcdef".length));
})));
}
var ADD_CHILDREN = ((_ADD_CHILDREN = {}).iframe = function(el, node) {
var firstChild = node.children[0];
if (1 !== node.children.length || !firstChild || "element" !== firstChild.type || "html" !== firstChild.name) throw new Error("Expected only single html element node as child of iframe element");
el.addEventListener("load", (function() {
var win = el.contentWindow;
if (!win) throw new Error("Expected frame to have contentWindow");
var doc = win.document;
var docElement = doc.documentElement;
for (;docElement.children && docElement.children.length; ) docElement.removeChild(docElement.children[0]);
var child = firstChild.render(function(opts) {
void 0 === opts && (opts = {});
var _opts$doc = opts.doc, doc = void 0 === _opts$doc ? document : _opts$doc;
return function domRenderer(node) {
if ("component" === node.type) return node.renderComponent(domRenderer);
if ("text" === node.type) return createTextElement(doc, node);
if ("element" === node.type) {
var xmlNamespace = ELEMENT_DEFAULT_XML_NAMESPACE[node.name.toLowerCase()];
if (xmlNamespace) return function xmlNamespaceDomRenderer(node, xmlNamespace) {
if ("component" === node.type) return node.renderComponent((function(childNode) {
return xmlNamespaceDomRenderer(childNode, xmlNamespace);
}));
if ("text" === node.type) return createTextElement(doc, node);
if ("element" === node.type) {
var el = function(doc, node, xmlNamespace) {
return doc.createElementNS(xmlNamespace, node.name);
}(doc, node, xmlNamespace);
addProps(el, node);
addChildren(el, node, doc, (function(childNode) {
return xmlNamespaceDomRenderer(childNode, xmlNamespace);
}));
return el;
}
throw new TypeError("Unhandleable node");
}(node, xmlNamespace);
var el = function(doc, node) {
return node.props.el ? node.props.el : doc.createElement(node.name);
}(doc, node);
addProps(el, node);
addChildren(el, node, doc, domRenderer);
return el;
}
throw new TypeError("Unhandleable node");
};
}({
doc: doc
}));
for (;child.children.length; ) docElement.appendChild(child.children[0]);
}));
}, _ADD_CHILDREN.script = function(el, node) {
var firstChild = node.children[0];
if (1 !== node.children.length || !firstChild || "text" !== firstChild.type) throw new Error("Expected only single text node as child of script element");
el.text = firstChild.text;
}, _ADD_CHILDREN.default = function(el, node, renderer) {
for (var _i6 = 0, _node$renderChildren2 = node.renderChildren(renderer); _i6 < _node$renderChildren2.length; _i6++) el.appendChild(_node$renderChildren2[_i6]);
}, _ADD_CHILDREN);
function addChildren(el, node, doc, renderer) {
if (node.props.hasOwnProperty("innerHTML")) {
if (node.children.length) throw new Error("Expected no children to be passed when innerHTML prop is set");
var html = node.props.innerHTML;
if ("string" != typeof html) throw new TypeError("innerHTML prop must be string");
if ("script" === node.name) el.text = html; else {
el.innerHTML = html;
!function(el, doc) {
void 0 === doc && (doc = window.document);
for (var _i2 = 0, _el$querySelectorAll2 = el.querySelectorAll("script"); _i2 < _el$querySelectorAll2.length; _i2++) {
var script = _el$querySelectorAll2[_i2];
var parentNode = script.parentNode;
if (parentNode) {
var newScript = doc.createElement("script");
newScript.text = script.textContent;
parentNode.replaceChild(newScript, script);
}
}
}(el, doc);
}
} else (ADD_CHILDREN[node.name] || ADD_CHILDREN.default)(el, node, renderer);
}
function regex() {
return function(nodeInstance) {
return new RegExp(function textRenderer(node) {
if ("component" === node.type) return [].concat(node.renderComponent(textRenderer)).join("");
if ("element" === node.type) throw new Error("Text renderer does not support basic elements");
if ("text" === node.type) return node.text;
throw new TypeError("Unhandleable node: " + node.type);
}(nodeInstance));
};
}
regex.node = function(el, props) {
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) children[_key - 2] = arguments[_key];
var nodeInstance = node_node.apply(void 0, [ el, props ].concat(children));
return el.renderer ? nodeInstance.render(el.renderer()) : nodeInstance;
};
var escapeRegex = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&");
};
var regex_validateAndEscapeChildren = function(name, children) {
return (children = function(name, children) {
if (!children) throw new Error("Must pass children to " + name);
return children;
}(name, children)).map((function(child) {
return "text" === child.type ? new node_TextNode(escapeRegex(child.text)) : child;
}));
};
function Regex(_ref, children) {
var _ref$exact = _ref.exact, exact = void 0 === _ref$exact || _ref$exact;
children = regex_validateAndEscapeChildren("RegexGroup", children);
return exact ? [ "^" ].concat(children, [ "$" ]) : children;
}
Regex.renderer = regex;
function RegexText(props, children) {
return regex_validateAndEscapeChildren("RegexText", children);
}
function RegexWord(props, children) {
!function(name, children) {
if (children && children.length) throw new Error("Must not pass children to RegexWord");
}(0, children);
return "\\w+";
}
function RegexGroup(_ref2, children) {
var repeat = _ref2.repeat, repeatMin = _ref2.repeatMin, repeatMax = _ref2.repeatMax, name = _ref2.name, _ref2$optional = _ref2.optional, optional = void 0 !== _ref2$optional && _ref2$optional, _ref2$capture = _ref2.capture, capture = void 0 === _ref2$capture || _ref2$capture, _ref2$union = _ref2.union, union = void 0 !== _ref2$union && _ref2$union;
children = regex_validateAndEscapeChildren("RegexGroup", children);
if (isDefined(repeat) && (isDefined(repeatMin) || isDefined(repeatMax))) throw new Error("repeat can not be used with repeatMin or repeatMax");
if (name && !capture) throw new Error("Named groups must be captured");
if (union) {
var _result = [];
for (var _i2 = 0, _children2 = children; _i2 < _children2.length; _i2++) {
_result.push(_children2[_i2]);
_result.push(new node_TextNode("|"));
}
_result.pop();
children = _result;
}
var result = [];
result.push(capture ? "(" : "(?:");
name && result.push("?<" + escapeRegex(name) + ">");
result.push.apply(result, children);
result.push(")");
isDefined(repeat) && ("number" == typeof repeat ? result.push("{" + repeat + "}") : !0 === repeat && result.push("+"));
(isDefined(repeatMin) || isDefined(repeatMax)) && result.push("{" + (repeatMin || "") + "," + (repeatMax || "") + "}");
optional && result.push("?");
return result;
}
var email = "<EMAIL>";
var match = email.match(regex.node(Regex, null, regex.node(RegexWord, null), regex.node(RegexGroup, {
optional: !0
}, regex.node(RegexText, null, "."), regex.node(RegexWord, null)), regex.node(RegexText, null, "@"), regex.node(RegexGroup, {
union: !0,
name: "provider"
}, regex.node(RegexText, null, "paypal"), regex.node(RegexText, null, "google"), regex.node(RegexText, null, "$mail")), regex.node(RegexText, null, "."), regex.node(RegexGroup, {
union: !0,
name: "tld"
}, regex.node(RegexText, null, "com"), regex.node(RegexText, null, "org"), regex.node(RegexText, null, "net"))));
console.info(email, match);
} ]);
}));
<|start_filename|>dist/module/renderers/react.js<|end_filename|>
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
var _excluded = ["innerHTML", "class"];
// eslint-disable-next-line import/no-unresolved
import { ComponentNode, TextNode, ElementNode } from '../node';
import { NODE_TYPE } from '../constants';
function mapReactProps(props) {
var innerHTML = props.innerHTML,
className = props.class,
remainingProps = _objectWithoutPropertiesLoose(props, _excluded);
var dangerouslySetInnerHTML = innerHTML ? {
__html: innerHTML
} : null; // $FlowFixMe
return _extends({
dangerouslySetInnerHTML: dangerouslySetInnerHTML,
className: className
}, remainingProps);
}
export function react(_temp) {
var _ref = _temp === void 0 ? {} : _temp,
React = _ref.React;
if (!React) {
throw new Error("Must pass React library to react renderer");
}
var reactRenderer = function reactRenderer(node) {
if (node.type === NODE_TYPE.COMPONENT) {
return React.createElement.apply(React, [function () {
return node.renderComponent(reactRenderer) || null;
}, node.props].concat(node.renderChildren(reactRenderer)));
}
if (node.type === NODE_TYPE.ELEMENT) {
return React.createElement.apply(React, [node.name, mapReactProps(node.props)].concat(node.renderChildren(reactRenderer)));
}
if (node.type === NODE_TYPE.TEXT) {
return node.text;
}
throw new TypeError("Unhandleable node");
};
return reactRenderer;
}
<|start_filename|>src/renderers/react.js<|end_filename|>
/* @flow */
// eslint-disable-next-line import/no-unresolved
import type { Node } from 'react';
import { ComponentNode, TextNode, ElementNode, type NodeRenderer, type NodePropsType } from '../node';
import { NODE_TYPE } from '../constants';
type ReactType = {|
createElement : Function
|};
type ReactRenderer = NodeRenderer<ElementNode | TextNode | ComponentNode<*>, Node | string | null>;
function mapReactProps(props : NodePropsType) : NodePropsType {
const { innerHTML, class: className, ...remainingProps } = props;
const dangerouslySetInnerHTML = innerHTML
? { __html: innerHTML }
: null;
// $FlowFixMe
return {
dangerouslySetInnerHTML,
className,
...remainingProps
};
}
export function react({ React } : {| React : ReactType |} = {}) : ReactRenderer {
if (!React) {
throw new Error(`Must pass React library to react renderer`);
}
const reactRenderer = (node) => {
if (node.type === NODE_TYPE.COMPONENT) {
return React.createElement(() => (node.renderComponent(reactRenderer) || null), node.props, ...node.renderChildren(reactRenderer));
}
if (node.type === NODE_TYPE.ELEMENT) {
return React.createElement(node.name, mapReactProps(node.props), ...node.renderChildren(reactRenderer));
}
if (node.type === NODE_TYPE.TEXT) {
return node.text;
}
throw new TypeError(`Unhandleable node`);
};
return reactRenderer;
}
| krakenjs/jsx-pragmatic |
<|start_filename|>index.js<|end_filename|>
import HocForm from './src/HocForm';
import Field from './src/Field';
export { Field };
export default HocForm;
<|start_filename|>tests/HocForm.test.js<|end_filename|>
import React from 'react';
import Enzyme, { mount, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import hocForm, { Field } from '../index';
import {
Form,
validate,
} from './helpers';
Enzyme.configure({ adapter: new Adapter() });
const LoginForm = hocForm({
initialValues: {
login: 'hulk',
},
validate,
})(Form);
const LoginFormWithoutValidation = hocForm({})(Form);
describe('HocForm()()', () => {
const event = {
preventDefault: value => value,
};
let spy;
const onSubmit = jest.fn(values => values);
function submitWithNewLogin(wrapper, form, event, login, times) {
wrapper.setState({
values: {
login,
},
}, () => {
Promise.resolve(form.simulate('submit', event))
.then(() => expect(spy).toHaveBeenCalledTimes(times))
.catch(() => ({}));
});
}
afterEach(() => {
spy.mockRestore();
});
it('shallows HocForm with validation', () => {
const formWrapper = shallow(
<LoginForm
onSubmit={onSubmit}
/>,
);
spy = jest.spyOn(formWrapper.instance().props, 'onSubmit');
formWrapper.instance().setError('login', 'Please enter a login');
formWrapper.instance().unsetError('login');
formWrapper.instance().setValue('login', '');
const form = formWrapper.find(Form).first().dive();
submitWithNewLogin(formWrapper, form, event, '', 1);
submitWithNewLogin(formWrapper, form, event, 'starman', 2);
expect(formWrapper.render()).toMatchSnapshot();
});
it('shallows HocForm without sync or async validation', () => {
const onSubmit = jest.fn(values => values)
const formWrapper = shallow(
<LoginFormWithoutValidation
onSubmit={onSubmit}
/>,
);
const spy = jest.spyOn(formWrapper.instance().props, 'onSubmit');
const form = formWrapper.find(Form).first().dive();
formWrapper.instance().setValue('login', 'hulk');
submitWithNewLogin(formWrapper, form, event, 'starman', 1);
});
});
<|start_filename|>src/Field.js<|end_filename|>
import React from 'react';
import { FormContext } from './HocForm';
import ContextedField from './ContextedField';
function Field({ name, props, component }) {
return (
<FormContext.Consumer>
{({ state, setError, setValue, unsetError }) => (
<ContextedField
{...props}
component={component}
input={{
name,
onChange: value => setValue(name, value),
value: state.values[name] || undefined,
...(props.onBlur
? { onBlur: value => props.onBlur(value, state.values)
.then(() => unsetError(name))
.catch(error => setError(name, error))
}
: {}),
}}
meta={{ error: state.errors[name] || undefined }}
/>
)}
</FormContext.Consumer>
);
}
export default Field;
<|start_filename|>demo/src/App.js<|end_filename|>
import React, { Component } from 'react';
import Form from './Form';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<Form
onSubmit={values => alert(`The form is valid! 🎉\nThere are the values:\n${JSON.stringify(values)}`)}
/>
</div>
);
}
}
export default App;
<|start_filename|>webpack.config.js<|end_filename|>
const path = require('path');
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
mode: 'none',
entry: ['./index.js'],
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
plugins: [
new UglifyJsPlugin({
test: /\.js/
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.NoEmitOnErrorsPlugin()
],
resolve: {
extensions: ['*', '.js']
},
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'commonjs2'
}
};
<|start_filename|>demo/src/Form.js<|end_filename|>
import React from 'react';
import hocForm, { Field } from './lib/hoc-form';
import Input from './Input';
const style = {
field: {
display: 'flex',
flexDirection: 'column',
},
form: {
margin: 'auto',
width: '18em',
},
submitButton: {
background: 'mediumseagreen',
color: 'white',
border: '0',
borderRadius: '.3em',
cursor: 'pointer',
fontSize: '.9em',
fontWeight: '300',
height: '3.5em',
width: '100%',
},
};
const unavailableUsernames = [
'elonmusk',
'ironman',
'lukeskywalker',
];
function validateLogin(value = '') {
if (value.trim() === '') {
return Promise.reject('Please enter an username');
}
return unavailableUsernames.includes(value)
? Promise.reject('This username is unavailable')
: Promise.resolve()
}
function validatePassword(value = '') {
if (value.trim() === '') {
return Promise.reject('Please enter a password');
} else if (value.trim().length < 6) {
return Promise.reject('Password must contain 6 characters or more');
} else {
return Promise.resolve();
}
}
function validatePasswordConfirmation(value = '', password = '') {
if (value.trim() === '') {
return Promise.reject('Please enter a password');
} else if (value !== password) {
return Promise.reject('Please enter the same password as below');
} else {
return Promise.resolve();
}
}
export function Form({
onSubmit,
}) {
return (
<form onSubmit={onSubmit} noValidate style={style.form}>
<Field
name="login"
component={Input}
props={{
label: 'Login *',
onBlur: value => validateLogin(value),
placeholder: 'elonmusk',
type: 'string',
}}
/>
<Field
name="pwd"
component={Input}
props={{
label: 'Password *',
onBlur: value => validatePassword(value),
type: 'password',
}}
/>
<Field
name="confirmPwd"
component={Input}
props={{
label: 'Password confirmation *',
onBlur: (value, { pwd }) => validatePasswordConfirmation(value, pwd),
type: 'password',
}}
/>
<Field
name="referrer"
component={Input}
props={{
label: 'How did you find us? *',
placeholder: 'Google Search, Facebook or else',
type: 'string',
}}
/>
<button style={style.submitButton} type="submit">
Sign up
</button>
</form>
);
}
export default hocForm({
validate(values, props) {
let errors = {};
const errorCatcher = (key, callback, ...args) => (
callback(values[key], args)
.catch(error => ({ [key]: error }))
);
return Promise.all([
errorCatcher('login', validateLogin),
errorCatcher('pwd', validatePassword),
errorCatcher('confirmPwd', validatePasswordConfirmation, values.pwd),
]).then((errors) => {
if (!values.referrer) {
errors = errors.concat({ referrer: 'Please give us something! 😇🙏' });
}
const results = errors.reduce((acc, item) => ({ ...acc, ...item }), {});
return Object.keys(results).length ? Promise.reject(results) : Promise.resolve();
});
}
})(Form);
<|start_filename|>src/HocForm.js<|end_filename|>
import React, { Component } from 'react';
export const FormContext = React.createContext({});
const HOC = hocProps => WrappedComponent => {
return class Form extends Component {
static removeObjectEntry = function(name, values) {
return Object
.entries(values)
.reduce((acc, [key, value]) => ({
...acc,
...(key !== name ? { [key]: value } : {}),
}), {});
}
constructor(props) {
super(props);
const initialValues = hocProps.initialValues || props.initialValues;
this.state = {
errors: {},
isValid: false,
values: {
...(initialValues ? { ...initialValues } : {})
},
};
this.onSubmit = this.onSubmit.bind(this);
this.setError = this.setError.bind(this);
this.setValue = this.setValue.bind(this);
this.unsetError = this.unsetError.bind(this);
this.validate = hocProps.validate || this.props.validate;
}
onSubmit(e) {
e && e.preventDefault();
const { errors, values } = this.state;
if (!this.validate) {
this.props.onSubmit(values);
return;
}
this.validate(values)
.then(() => {
this.setState({ errors: {}, isValid: true });
this.props.onSubmit(values);
})
.catch(errors => this.setState({ errors, isValid: false }));
}
setError(key, error) {
this.setState({
errors: {
...this.state.errors,
[key]: error,
},
});
}
setValue(key, value) {
this.setState({
values: {
...this.state.values,
[key]: value,
},
});
}
unsetError(key) {
const errors = Form.removeObjectEntry(key, this.state.errors);
this.setState({ errors });
}
render() {
return (
<FormContext.Provider
value={{
setError: this.setError,
setValue: this.setValue,
state: { ...this.state },
unsetError: this.unsetError,
}}
>
<WrappedComponent
{...this.props}
hocFormState={{ ...this.state }}
onSubmit={this.onSubmit}
/>
</FormContext.Provider>
);
}
}
}
export default HOC;
<|start_filename|>demo/src/Input.js<|end_filename|>
import React from 'react';
const style = {
container: {
display: 'flex',
flexDirection: 'column',
position: 'relative',
},
error: {
bottom: '1em',
color: 'crimson',
fontSize: '.8em',
position: 'absolute',
},
field: {
border: '1px solid lightgrey',
borderColor: 'lightgrey',
borderRadius: '.3em',
fontSize: '1em',
fontWeight: 300,
height: '2em',
marginBottom: '2em',
padding: '.5em 1em',
},
invalidField: {
borderColor: 'crimson',
},
label: {
fontWeight: 300,
marginBottom: '.5em',
},
};
function Input({
input = {},
label = '',
meta = {},
placeholder = '',
type = 'text',
}) {
return (
<div style={style.container}>
<label style={style.label}>
{label}
</label>
<input
placeholder={placeholder}
type={type}
{...input}
onBlur={e => input.onBlur && input.onBlur(e.target.value)}
onChange={e => input.onChange(e.target.value)}
style={{
...style.field,
...(meta.error ? style.invalidField : {}),
}}
/>
{meta.error && <span style={style.error}>
{meta.error}
</span>}
</div>
);
}
export default Input;
<|start_filename|>src/ContextedField.js<|end_filename|>
import React from 'react';
function ContextedField({ component: CustomComponent, ...props }) {
return <CustomComponent {...props} />;
}
export default ContextedField;
<|start_filename|>tests/helpers.js<|end_filename|>
import React from 'react';
import { Field } from '../index';
import Input from '../demo/src/Input';
function singleField() {
return (
<Field
name="login"
component={Input}
props={{
label: 'Login',
placeholder: 'elonmusk',
type: 'string',
}}
/>
);
}
export function Form({ onSubmit }) {
return (
<form onSubmit={onSubmit} noValidate>
{singleField()}
<button type="submit">
Sign in
</button>
</form>
);
}
export function validate(values, props) {
let errors = {};
if (!values.login) {
errors = {
...errors,
login: 'Please enter a login',
};
}
return Object.keys(errors).length
? Promise.reject(errors)
: Promise.resolve();
} | pacdiv/hoc-form |
<|start_filename|>fileserver.go<|end_filename|>
package gzipped
import (
"fmt"
"net/http"
"os"
"path"
"strconv"
"strings"
"github.com/kevinpollet/nego"
)
// List of encodings we would prefer to use, in order of preference, best first.
var preferredEncodings = []string{"br", "gzip", "identity"}
// File extension to use for different encodings.
func extensionForEncoding(encname string) string {
switch encname {
case "gzip":
return ".gz"
case "br":
return ".br"
case "identity":
return ""
}
return ""
}
// Function to negotiate the best content encoding
// Pulled out here so we have the option of overriding nego's behavior and so we can test
func negotiate(r *http.Request, available []string) string {
return nego.NegotiateContentEncoding(r, available...)
}
type fileHandler struct {
root FileSystem
}
// FileServer is a drop-in replacement for Go's standard http.FileServer
// which adds support for static resources precompressed with gzip, at
// the cost of removing the support for directory browsing.
//
// If file filename.ext has a compressed version filename.ext.gz alongside
// it, if the client indicates that it accepts gzip-compressed data, and
// if the .gz file can be opened, then the compressed version of the file
// will be sent to the client. Otherwise the request is passed on to
// http.ServeContent, and the raw (uncompressed) version is used.
//
// It is up to you to ensure that the compressed and uncompressed versions
// of files match and have sensible timestamps.
//
// Compressed or not, requests are fulfilled using http.ServeContent, and
// details like accept ranges and content-type sniffing are handled by that
// method.
func FileServer(root FileSystem) http.Handler {
return &fileHandler{root}
}
func (f *fileHandler) openAndStat(path string) (http.File, os.FileInfo, error) {
file, err := f.root.Open(path)
var info os.FileInfo
// This slightly weird variable reuse is so we can get 100% test coverage
// without having to come up with a test file that can be opened, yet
// fails to stat.
if err == nil {
info, err = file.Stat()
}
if err != nil {
return file, nil, err
}
if info.IsDir() {
return file, nil, fmt.Errorf("%s is directory", path)
}
return file, info, nil
}
const (
acceptEncodingHeader = "Accept-Encoding"
contentEncodingHeader = "Content-Encoding"
contentLengthHeader = "Content-Length"
rangeHeader = "Range"
varyHeader = "Vary"
)
// Find the best file to serve based on the client's Accept-Encoding, and which
// files actually exist on the filesystem. If no file was found that can satisfy
// the request, the error field will be non-nil.
func (f *fileHandler) findBestFile(w http.ResponseWriter, r *http.Request, fpath string) (http.File, os.FileInfo, error) {
ae := r.Header.Get(acceptEncodingHeader)
if ae == "" {
return f.openAndStat(fpath)
}
// Got an accept header? See what possible encodings we can send by looking for files
var available []string
for _, posenc := range preferredEncodings {
ext := extensionForEncoding(posenc)
fname := fpath + ext
if f.root.Exists(fname) {
available = append(available, posenc)
}
}
if len(available) == 0 {
return f.openAndStat(fpath)
}
// Carry out standard HTTP negotiation
negenc := negotiate(r, available)
if negenc == "" || negenc == "identity" {
// If we fail to negotiate anything or if we negotiated the identity encoding, again try the base file
return f.openAndStat(fpath)
}
ext := extensionForEncoding(negenc)
if file, info, err := f.openAndStat(fpath + ext); err == nil {
wHeader := w.Header()
wHeader[contentEncodingHeader] = []string{negenc}
wHeader.Add(varyHeader, acceptEncodingHeader)
if len(r.Header[rangeHeader]) == 0 {
// If not a range request then we can easily set the content length which the
// Go standard library does not do if "Content-Encoding" is set.
wHeader[contentLengthHeader] = []string{strconv.FormatInt(info.Size(), 10)}
}
return file, info, nil
}
// If all else failed, fall back to base file once again
return f.openAndStat(fpath)
}
func (f *fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
upath := r.URL.Path
if !strings.HasPrefix(upath, "/") {
upath = "/" + upath
r.URL.Path = upath
}
fpath := path.Clean(upath)
if strings.HasSuffix(fpath, "/") {
// If you wanted to put back directory browsing support, this is
// where you'd do it.
http.NotFound(w, r)
return
}
// Find the best acceptable file, including trying uncompressed
if file, info, err := f.findBestFile(w, r, fpath); err == nil {
http.ServeContent(w, r, fpath, info.ModTime(), file)
file.Close()
return
}
// Doesn't exist, compressed or uncompressed
http.NotFound(w, r)
}
<|start_filename|>fileserver_test.go<|end_filename|>
package gzipped
import (
"bytes"
"compress/gzip"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/textproto"
"strconv"
"testing"
"github.com/kevinpollet/nego"
)
// Test that the server respects client preferences
func TestPreference(t *testing.T) {
req := http.Request{Header: http.Header{}}
// the client doesn't set any preferences, so we should pick br
for _, info := range []struct {
hdr string // the Accept-Encoding string
expect string // the expected encoding chosen by the server
}{
{"*", "br"},
{"gzip, deflate, br", "br"},
{"gzip, deflate, br;q=0.5", "gzip"},
} {
req.Header.Set("Accept-Encoding", info.hdr)
negenc := nego.NegotiateContentEncoding(&req, preferredEncodings...)
if negenc != info.expect {
t.Errorf("server chose %s but we expected %s for header %s", negenc, info.expect, info.hdr)
}
}
}
func testGet(t *testing.T, acceptGzip bool, urlPath string, expectedBody string) {
fs := FileServer(Dir("./testdata/"))
rr := httptest.NewRecorder()
req, _ := http.NewRequest("GET", urlPath, nil)
if acceptGzip {
req.Header.Set("Accept-Encoding", "gzip,*")
}
fs.ServeHTTP(rr, req)
h := rr.Header()
// Check the content-length is correct.
clh := h["Content-Length"]
if len(clh) > 0 {
byts, err := strconv.Atoi(clh[0])
if err != nil {
t.Errorf("Invalid Content-Length on response: '%s'", clh[0])
}
n := rr.Body.Len()
if n != byts {
t.Errorf("GET expected %d byts, got %d", byts, n)
}
}
// Check the body content is correct.
ce := h["Content-Encoding"]
var body string
if len(ce) > 0 {
if ce[0] == "gzip" {
rdr, err := gzip.NewReader(bytes.NewReader(rr.Body.Bytes()))
if err != nil {
t.Errorf("Gunzip failed: %s", err)
} else {
bbody, err := ioutil.ReadAll(rdr)
if err != nil {
t.Errorf("Gunzip read failed: %s", err)
} else {
body = string(bbody)
}
}
} else {
t.Errorf("Invalid Content-Encoding in response: '%s'", ce[0])
}
} else {
body = rr.Body.String()
}
if len(body) != len(expectedBody) {
t.Errorf("GET (acceptGzip=%v) returned wrong decoded body length %d, expected %d",
acceptGzip, len(body), len(expectedBody))
}
if body != expectedBody {
t.Errorf("GET (acceptGzip=%v) returned wrong body '%s'", acceptGzip, body)
}
}
func TestOpenStat(t *testing.T) {
fh := &fileHandler{Dir(".")}
_, _, err := fh.openAndStat(".")
if err == nil {
t.Errorf("openAndStat directory succeeded, should have failed")
}
_, _, err = fh.openAndStat("updog")
if err == nil {
t.Errorf("openAndStat nonexistent file succeeded, should have failed")
}
}
func TestNoBrowse(t *testing.T) {
fs := FileServer(Dir("./testdata/"))
rr := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
fs.ServeHTTP(rr, req)
if rr.Code != 404 {
t.Errorf("Directory browse succeeded")
}
}
func TestLeadingSlash(t *testing.T) {
fs := FileServer(Dir("./testdata/"))
rr := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "file.txt", nil)
fs.ServeHTTP(rr, req)
if rr.Code != 200 {
t.Errorf("Missing leading / on HTTP path caused error")
}
}
func Test404(t *testing.T) {
fs := FileServer(Dir("./testdata/"))
rr := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/nonexistent.txt", nil)
fs.ServeHTTP(rr, req)
if rr.Code != 404 {
t.Errorf("Directory browse succeeded")
}
}
func TestGet(t *testing.T) {
testGet(t, false, "/file.txt", "zyxwvutsrqponmlkjihgfedcba\n")
}
func TestGzipGet(t *testing.T) {
testGet(t, true, "/file.txt", "abcdefghijklmnopqrstuvwxyz\n")
}
func TestGetIdentity(t *testing.T) {
testGet(t, false, "/file2.txt", "1234567890987654321\n")
}
func TestGzipGetIdentity(t *testing.T) {
testGet(t, true, "/file2.txt", "1234567890987654321\n")
}
func TestConstHeaders(t *testing.T) {
for _, header := range []string{
acceptEncodingHeader,
contentEncodingHeader,
contentLengthHeader,
rangeHeader,
varyHeader,
} {
canonical := textproto.CanonicalMIMEHeaderKey(header)
if header != canonical {
t.Errorf("%s != %s", header, canonical)
}
}
}
| lpar/gzipped |
<|start_filename|>driver-mpr121/src/main/java/com/nilhcem/androidthings/driver/mpr121/Mpr121InputDriver.java<|end_filename|>
package com.nilhcem.androidthings.driver.mpr121;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import com.google.android.things.userdriver.UserDriverManager;
import com.google.android.things.userdriver.input.InputDriver;
import com.google.android.things.userdriver.input.InputDriverEvent;
import java.io.IOException;
public class Mpr121InputDriver implements AutoCloseable {
private static final String TAG = Mpr121InputDriver.class.getSimpleName();
private static final int SOFTWAREPOLL_DELAY_MS = 100;
// Driver parameters
private static final String DRIVER_NAME = "Mpr121";
private Mpr121 peripheralDevice;
private InputDriver inputDriver;
private InputDriverEvent inputEvent = new InputDriverEvent();
// Key codes mapped to input channels
private int[] keycodes;
private Handler inputHandler;
private boolean[] inputStatus;
/**
* Callback invoked to poll the state of the controller
*/
private final Runnable pollingCallback = new Runnable() {
@Override
public void run() {
try {
int data = peripheralDevice.getTouched();
for (int i = 0; i < Mpr121.NB_ELECTRODES; i++) {
if ((data & (1 << i)) != 0) {
if (!inputStatus[i]) {
Log.d(TAG, "#" + i + " touched");
inputStatus[i] = true;
emitInputEvents(keycodes[i], true);
}
} else {
if (inputStatus[i]) {
Log.d(TAG, "#" + i + " released");
inputStatus[i] = false;
emitInputEvents(keycodes[i], false);
}
}
}
} catch (IOException e) {
Log.e(TAG, "Error getting data from peripheral device", e);
} finally {
inputHandler.postDelayed(this, SOFTWAREPOLL_DELAY_MS);
}
}
};
/**
* Create a new Mpr121InputDriver to forward capacitive touch events
* to the Android input framework.
*
* @param i2cName I2C port name where the controller is attached. Cannot be null.
* @param handler optional {@link Handler} for software polling and callback events.
* @param keyCodes {@link KeyEvent} codes to be emitted for each input channel.
* Length must match the input channel count of the
* touch controller.
*/
public Mpr121InputDriver(String i2cName, Handler handler, int[] keyCodes) throws IOException {
// Verify inputs
if (keyCodes == null) {
throw new IllegalArgumentException("Must provide a valid set of key codes.");
}
this.keycodes = keyCodes;
this.peripheralDevice = new Mpr121(i2cName);
this.inputHandler = new Handler(handler == null ? Looper.myLooper() : handler.getLooper());
this.inputStatus = new boolean[Mpr121.NB_ELECTRODES];
inputHandler.post(pollingCallback);
}
@Override
public void close() throws IOException {
unregister();
inputHandler.removeCallbacks(pollingCallback);
if (peripheralDevice != null) {
try {
peripheralDevice.close();
} finally {
peripheralDevice = null;
}
}
}
/**
* Register this driver with the Android input framework.
*/
public void register() {
if (inputDriver == null) {
UserDriverManager manager = UserDriverManager.getInstance();
inputDriver = new InputDriver.Builder()
.setName(DRIVER_NAME)
.setSupportedKeys(keycodes)
.build();
manager.registerInputDriver(inputDriver);
}
}
/**
* Unregister this driver with the Android input framework.
*/
public void unregister() {
if (inputDriver != null) {
UserDriverManager manager = UserDriverManager.getInstance();
manager.unregisterInputDriver(inputDriver);
inputDriver = null;
}
}
/**
* Emit input events through the registered driver to the
* Android input framework using the defined set of key codes.
*/
private void emitInputEvents(int keyCode, boolean pressed) {
if (inputDriver == null) {
Log.w(TAG, "Driver not yet registered");
return;
}
inputEvent.clear();
inputEvent.setKeyPressed(keyCode, pressed);
inputDriver.emit(inputEvent);
}
}
<|start_filename|>driver-mpr121/src/main/java/com/nilhcem/androidthings/driver/mpr121/Mpr121.java<|end_filename|>
package com.nilhcem.androidthings.driver.mpr121;
import com.google.android.things.pio.I2cDevice;
import com.google.android.things.pio.PeripheralManager;
import java.io.IOException;
/**
* Android Things port of Adafruit MPR121
*
* @see "https://github.com/adafruit/Adafruit_MPR121"
*/
public class Mpr121 implements AutoCloseable {
public static final int NB_ELECTRODES = 12;
private static final int I2C_ADDRESS = 0x5A;
private static final int TOUCHSTATUS_L = 0x00;
private static final int MHDR = 0x2B;
private static final int NHDR = 0x2C;
private static final int NCLR = 0x2D;
private static final int FDLR = 0x2E;
private static final int MHDF = 0x2F;
private static final int NHDF = 0x30;
private static final int NCLF = 0x31;
private static final int FDLF = 0x32;
private static final int NHDT = 0x33;
private static final int NCLT = 0x34;
private static final int FDLT = 0x35;
private static final int TOUCHTH_0 = 0x41;
private static final int RELEASETH_0 = 0x42;
private static final int DEBOUNCE = 0x5B;
private static final int CONFIG1 = 0x5C;
private static final int CONFIG2 = 0x5D;
private static final int ECR = 0x5E;
private static final int SOFTRESET = 0x80;
private I2cDevice device;
public Mpr121(String i2cName) throws IOException {
PeripheralManager manager = PeripheralManager.getInstance();
device = manager.openI2cDevice(i2cName, I2C_ADDRESS);
init();
}
public int getTouched() throws IOException {
return device.readRegWord(TOUCHSTATUS_L) & 0x0FFF;
}
private void init() throws IOException {
// Soft reset
device.writeRegByte(SOFTRESET, (byte) 0x63);
device.writeRegByte(ECR, (byte) 0x00);
setThresholds((byte) 12, (byte) 6);
device.writeRegByte(MHDR, (byte) 0x01);
device.writeRegByte(NHDR, (byte) 0x01);
device.writeRegByte(NCLR, (byte) 0x0E);
device.writeRegByte(FDLR, (byte) 0x00);
device.writeRegByte(MHDF, (byte) 0x01);
device.writeRegByte(NHDF, (byte) 0x05);
device.writeRegByte(NCLF, (byte) 0x01);
device.writeRegByte(FDLF, (byte) 0x00);
device.writeRegByte(NHDT, (byte) 0x00);
device.writeRegByte(NCLT, (byte) 0x00);
device.writeRegByte(FDLT, (byte) 0x00);
device.writeRegByte(DEBOUNCE, (byte) 0x00);
device.writeRegByte(CONFIG1, (byte) 0x10); // default, 16uA charge current
device.writeRegByte(CONFIG2, (byte) 0x20); // 0.5uS encoding, 1ms period
// enable all electrodes
device.writeRegByte(ECR, (byte) 0x8F); // start with first 5 bits of baseline tracking
}
private void setThresholds(byte touch, byte release) throws IOException {
for (int i = 0; i < NB_ELECTRODES; i++) {
device.writeRegByte(TOUCHTH_0 + 2 * i, touch);
device.writeRegByte(RELEASETH_0 + 2 * i, release);
}
}
@Override
public void close() throws IOException {
if (device != null) {
try {
device.close();
} finally {
device = null;
}
}
}
}
<|start_filename|>.android-things-driver.json<|end_filename|>
{
"title": "MPR121",
"category": "Capacitive Touch Sensor",
"samples": [
"https://github.com/Nilhcem/mpr121-androidthings/tree/master/sample"
],
"published-maven": {
"maven-url": "https://jcenter.bintray.com",
"groupid": "com.nilhcem.androidthings",
"artifactid": "driver-mpr121"
},
"compatible-with": [
{
"title": "Adafruit 12-Key Capacitive Touch Sensor Breakout - MPR121",
"photo": "https://cdn-shop.adafruit.com/970x728/1982-00.jpg",
"url": "https://www.adafruit.com/product/1982"
}
]
}
<|start_filename|>sample/src/main/java/com/nilhcem/androidthings/driver/mpr121/sample/SampleActivity.java<|end_filename|>
package com.nilhcem.androidthings.driver.mpr121.sample;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import java.io.IOException;
public class SampleActivity extends Activity {
private static final String TAG = SampleActivity.class.getSimpleName();
private static final String MPR121_I2C = "I2C1";
private static final String BUZZER_GPIO = "PWM1";
private final Mpr121Helper mpr121 = new Mpr121Helper();
private final PassiveBuzzerHelper buzzer = new PassiveBuzzerHelper();
//Place resources in res/raw directory if you want to use the SoundPoolHelper instead
//private final SoundPoolHelper soundPool = new SoundPoolHelper();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
buzzer.init(BUZZER_GPIO);
//soundPool.init(this);
mpr121.init(MPR121_I2C, new Mpr121Helper.OnTouchListener() {
@Override
public void onSensorTouched(int id) {
buzzer.play(id);
//soundPool.play(id);
}
@Override
public void onSensorReleased(int id) {
}
});
} catch (IOException e) {
Log.e(TAG, "Error initializing project", e);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean result = mpr121.onKeyDown(keyCode);
if (!result) {
result = super.onKeyDown(keyCode, event);
}
return result;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
boolean result = mpr121.onKeyUp(keyCode);
if (!result) {
result = super.onKeyUp(keyCode, event);
}
return result;
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
buzzer.close();
//soundPool.close();
mpr121.close();
} catch (IOException e) {
Log.e(TAG, "Error closing I/Os");
}
}
}
<|start_filename|>sample/src/main/java/com/nilhcem/androidthings/driver/mpr121/sample/SoundPoolHelper.java<|end_filename|>
package com.nilhcem.androidthings.driver.mpr121.sample;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.SoundPool;
public class SoundPoolHelper {
private SoundPool soundPool;
private boolean loaded;
private int[] sounds = new int[12];
public void init(Context context) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build();
soundPool = new SoundPool.Builder()
.setMaxStreams(10)
.setAudioAttributes(audioAttributes)
.build();
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
loaded = true;
}
});
// load R.raw.sound[0->11]
for (int i = 0; i < 12; i++) {
sounds[i] = soundPool.load(context, context.getResources().getIdentifier("sound" + i, "raw", context.getPackageName()), 1);
}
}
public void play(int id) {
if (loaded) {
soundPool.play(sounds[id], 0.5f, 0.5f, 1, 0, 1f);
}
}
public void close() {
soundPool.release();
soundPool = null;
}
}
<|start_filename|>sample/src/main/java/com/nilhcem/androidthings/driver/mpr121/sample/Mpr121Helper.java<|end_filename|>
package com.nilhcem.androidthings.driver.mpr121.sample;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.view.KeyEvent;
import com.nilhcem.androidthings.driver.mpr121.Mpr121InputDriver;
import java.io.IOException;
public class Mpr121Helper {
public interface OnTouchListener {
void onSensorTouched(int id);
void onSensorReleased(int id);
}
private static final String TAG = Mpr121Helper.class.getSimpleName();
private static final int[] KEY_CODES = {
KeyEvent.KEYCODE_0, KeyEvent.KEYCODE_1, KeyEvent.KEYCODE_2, KeyEvent.KEYCODE_3,
KeyEvent.KEYCODE_4, KeyEvent.KEYCODE_5, KeyEvent.KEYCODE_6, KeyEvent.KEYCODE_7,
KeyEvent.KEYCODE_8, KeyEvent.KEYCODE_9, KeyEvent.KEYCODE_A, KeyEvent.KEYCODE_B
};
private final HandlerThread handlerThread = new HandlerThread("Mpr121Thread");
private Handler handler;
private Mpr121InputDriver inputDriver;
private OnTouchListener listener;
public void init(String i2cPin, final OnTouchListener listener) {
this.listener = listener;
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
try {
inputDriver = new Mpr121InputDriver(i2cPin, handler, KEY_CODES);
inputDriver.register();
} catch (IOException e) {
Log.e(TAG, "Unable to initialize Mpr121 driver", e);
}
}
public boolean onKeyDown(int keyCode) {
int id = getIdForKeyCode(keyCode);
if (id != -1) {
Log.d(TAG, "onSensorTouched: " + id);
listener.onSensorTouched(id);
return true;
}
return false;
}
public boolean onKeyUp(int keyCode) {
int id = getIdForKeyCode(keyCode);
if (id != -1) {
Log.d(TAG, "onSensorReleased: " + id);
listener.onSensorReleased(id);
return true;
}
return false;
}
public void close() {
try {
handlerThread.quitSafely();
if (inputDriver != null) {
inputDriver.unregister();
inputDriver.close();
}
} catch (IOException e) {
Log.w(TAG, "Unable to close Mpr121 driver", e);
} finally {
handler = null;
}
}
private int getIdForKeyCode(int keyCode) {
for (int i = 0; i < KEY_CODES.length; i++) {
if (keyCode == KEY_CODES[i]) {
return i;
}
}
return -1;
}
}
<|start_filename|>sample/src/main/java/com/nilhcem/androidthings/driver/mpr121/sample/PassiveBuzzerHelper.java<|end_filename|>
package com.nilhcem.androidthings.driver.mpr121.sample;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import com.google.android.things.contrib.driver.pwmspeaker.Speaker;
import java.io.IOException;
public class PassiveBuzzerHelper {
private static final String TAG = PassiveBuzzerHelper.class.getSimpleName();
private static final int HANDLER_MSG_STOP = 0;
private static final int HANDLER_MSG_PLAY = 1;
private final HandlerThread handlerThread = new HandlerThread("BuzzerThread");
private Handler handler;
private Speaker buzzer;
public void init(String gpioPin) throws IOException {
buzzer = new Speaker(gpioPin);
buzzer.stop(); // in case the PWM pin was enabled already
handlerThread.start();
handler = new Handler(handlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
try {
buzzer.stop();
if (msg.what == HANDLER_MSG_PLAY) {
buzzer.play(msg.arg1);
handler.sendEmptyMessageDelayed(HANDLER_MSG_STOP, 800);
}
} catch (IOException e) {
Log.e(TAG, "Buzzer error", e);
}
}
};
}
public void play(int id) {
switch (id) {
case 0:
playNote(880);
break;
case 1:
playNote(988);
break;
case 2:
playNote(1047);
break;
case 3:
playNote(1175);
break;
case 4:
playNote(1319);
break;
case 5:
playNote(1397);
break;
case 6:
playNote(1568);
break;
case 7:
playNote(1760);
break;
case 8:
playNote(1976);
break;
case 9:
playNote(2093);
break;
case 10:
playNote(2349);
break;
case 11:
playNote(2637);
break;
default:
playNote(0);
break;
}
}
public void close() throws IOException {
try {
handler.removeMessages(HANDLER_MSG_STOP);
handler.removeMessages(HANDLER_MSG_PLAY);
handlerThread.quitSafely();
buzzer.stop();
buzzer.close();
} finally {
buzzer = null;
handler = null;
}
}
private void playNote(int frequency) {
handler.removeMessages(HANDLER_MSG_STOP);
Message msg = new Message();
msg.what = frequency == 0 ? HANDLER_MSG_STOP : HANDLER_MSG_PLAY;
msg.arg1 = frequency;
handler.sendMessage(msg);
}
}
| Nilhcem/mpr121-androidthings |
<|start_filename|>cmake/Toolchain-QNX-8.0.0.cmake<|end_filename|>
#
# (C) Copyright 2009 Johns Hopkins University (JHU), All Rights
# Reserved.
# (C) Copyright 2013 <NAME> <<EMAIL>>
#
# --- begin cisst license - do not edit ---
#
# This software is provided "as is" under an open source license, with
# no warranty. The complete license can be found in license.txt and
# http://www.cisst.org/cisst/license.txt.
#
# --- end cisst license ---
SET(CMAKE_SYSTEM_NAME QNX)
SET(CMAKE_SYSTEM_VERSION 8.0.0)
# for device
#SET(CMAKE_SYSTEM_PROCESSOR armv7)
# for simulator
SET(CMAKE_SYSTEM_PROCESSOR x86)
SET(TOOLCHAIN QNX)
#SET(CMAKE_IMPORT_LIBRARY_SUFFIX ".a")
SET(CMAKE_SHARED_LIBRARY_PREFIX "lib")
SET(CMAKE_SHARED_LIBRARY_SUFFIX ".so")
SET(CMAKE_STATIC_LIBRARY_PREFIX "lib")
SET(CMAKE_STATIC_LIBRARY_SUFFIX ".a")
IF(CMAKE_HOST_WIN32)
SET(HOST_EXECUTABLE_SUFFIX ".exe")
ENDIF(CMAKE_HOST_WIN32)
FIND_PATH(QNX_HOST
NAME usr/bin/qcc${HOST_EXECUTABLE_SUFFIX}
PATHS $ENV{QNX_HOST} C:/QNX641/host/win32/x86
NO_CMAKE_PATH
NO_CMAKE_ENVIRONMENT_PATH
)
FIND_PATH(QNX_TARGET
NAME usr/include/qnx_errno.h
PATHS $ENV{QNX_TARGET} C:/QNX641/target/qnx6
NO_CMAKE_PATH
NO_CMAKE_ENVIRONMENT_PATH
)
IF(CMAKE_HOST_WIN32)
FIND_PATH(QNX_CONFIGURATION
NAME bin/qnxactivate.exe
PATHS $ENV{QNX_CONFIGURATION}
"C:/Program Files/QNX Software Systems/qconfig"
NO_CMAKE_PATH
NO_CMAKE_ENVIRONMENT_PATH
)
ENDIF(CMAKE_HOST_WIN32)
SET(ENV{QNX_HOST} ${QNX_HOST})
SET(ENV{QNX_TARGET} ${QNX_TARGET})
IF(CMAKE_HOST_WIN32)
SET(ENV{QNX_CONFIGURATION} ${QNX_CONFIGURATION})
SET(ENV{PATH} "$ENV{PATH};${QNX_HOST}/usr/bin")
ENDIF(CMAKE_HOST_WIN32)
SET(CMAKE_MAKE_PROGRAM "${QNX_HOST}/usr/bin/make${HOST_EXECUTABLE_SUFFIX}" CACHE PATH "QNX Make Program")
SET(CMAKE_SH "${QNX_HOST}/usr/bin/sh${HOST_EXECUTABLE_SUFFIX}" CACHE PATH "QNX shell Program")
SET(CMAKE_AR "${QNX_HOST}/usr/bin/nto${CMAKE_SYSTEM_PROCESSOR}-ar${HOST_EXECUTABLE_SUFFIX}" CACHE PATH "QNX ar Program")
SET(CMAKE_RANLIB "${QNX_HOST}/usr/bin/nto${CMAKE_SYSTEM_PROCESSOR}-ranlib${HOST_EXECUTABLE_SUFFIX}" CACHE PATH "QNX ranlib Program")
SET(CMAKE_NM "${QNX_HOST}/usr/bin/nto${CMAKE_SYSTEM_PROCESSOR}-nm${HOST_EXECUTABLE_SUFFIX}" CACHE PATH "QNX nm Program")
SET(CMAKE_OBJCOPY "${QNX_HOST}/usr/bin/nto${CMAKE_SYSTEM_PROCESSOR}-objcopy${HOST_EXECUTABLE_SUFFIX}" CACHE PATH "QNX objcopy Program")
SET(CMAKE_OBJDUMP "${QNX_HOST}/usr/bin/nto${CMAKE_SYSTEM_PROCESSOR}-objdump${HOST_EXECUTABLE_SUFFIX}" CACHE PATH "QNX objdump Program")
SET(CMAKE_LINKER "${QNX_HOST}/usr/bin/nto${CMAKE_SYSTEM_PROCESSOR}-ld" CACHE PATH "QNX Linker Program")
SET(CMAKE_STRIP "${QNX_HOST}/usr/bin/nto${CMAKE_SYSTEM_PROCESSOR}-strip${HOST_EXECUTABLE_SUFFIX}" CACHE PATH "QNX Strip Program")
# I think this is qcc's bug but we need -fPIC for libtomcrypt
SET(DEFAULT_COMPILER_FLAGS "-fPIC")
# well only x86 or armv7
SET(QCC_TARET_ARG1 ${CMAKE_SYSTEM_PROCESSOR})
IF (CMAKE_SYSTEM_PROCESSOR STREQUAL "armv7")
SET(QCC_TARET_ARG1 "${QCC_TARET_ARG1}le")
ENDIF()
SET(CMAKE_C_COMPILER ${QNX_HOST}/usr/bin/qcc${HOST_EXECUTABLE_SUFFIX})
SET(CMAKE_C_COMPILER_ARG1 " -Vgcc_nto${QCC_TARET_ARG1} -lang-c")
#SET(CMAKE_C_FLAGS "${DEFAULT_COMPILER_FLAGS}")
SET(CMAKE_C_FLAGS_DEBUG "-g")
SET(CMAKE_C_FLAGS_MINSIZEREL "-Os -DNDEBUG")
SET(CMAKE_C_FLAGS_RELEASE "-O3 -DNDEBUG")
SET(CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g")
SET(CMAKE_CXX_COMPILER ${QNX_HOST}/usr/bin/qcc${HOST_EXECUTABLE_SUFFIX})
SET(CMAKE_CXX_COMPILER_ARG1 "-Vgcc_nto${QCC_TARET_ARG1} -lang-c++")
#SET(CMAKE_CXX_FLAGS "${DEFAULT_COMPILER_FLAGS}")
SET(CMAKE_CXX_FLAGS_DEBUG "-g")
SET(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG")
SET(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG")
SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
SET(CMAKE_ASM_COMPILER ${QNX_HOST}/usr/bin/qcc${HOST_EXECUTABLE_SUFFIX})
SET(CMAKE_ASM_COMPILER_ARG1 "-Vgcc_nto${QCC_TARET_ARG1} -lang-c")
#SET(CMAKE_ASM_FLAGS "${DEFAULT_COMPILER_FLAGS}")
SET(CMAKE_ASM_FLAGS_DEBUG "-g")
SET(CMAKE_ASM_FLAGS_MINSIZEREL "-Os -DNDEBUG")
SET(CMAKE_ASM_FLAGS_RELEASE "-O3 -DNDEBUG")
SET(CMAKE_ASM_FLAGS_RELWITHDEBINFO "-O2 -g")
SET(CMAKE_FIND_ROOT_PATH ${QNX_TARGET})
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
# for Zlib and so
SET(CMAKE_APPBUNDLE_PATH "${QNX_TARGET}/lib:${QNX_TARGET}/usr/lib:${QNX_TARGET}/usr/include")
# for some reason FIND_PACKAGE doesn't find zlib properly so add this
SET(ZLIB_LIBRARY "{QNX_TARGET}/usr/lib/zlib.a")
# pthread is supported on QNX
SET(CMAKE_USE_PTHREADS_INIT TRUE)
<|start_filename|>package/template.c<|end_filename|>
#include <sagittarius.h>
#define LIBSAGITTARIUS_EXT_BODY
#include <sagittarius/extend.h>
#include "$header$"
extern void Sg__Init_$flat-name$lib(SgLibrary *lib);
SG_EXTENSION_ENTRY void CDECL Sg_Init_$flat-name$()
{
SgLibrary *lib;
/* Initialize the package DSO */
SG_INIT_EXTENSION($package-name$);
lib = SG_LIBRARY(Sg_FindLibrary(SG_INTERN("$library-name$"),
FALSE));
/* Call stub initialiser, the stub library will be automatically created. */
Sg__Init_$flat-name$lib(lib);
/* Do your initialisation here. */
}
| david135/sagittarius-scheme |
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/BlurBlock.cs<|end_filename|>
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Blur",
GUID = "eb7430c8-baf7-4268-912d-33c29c652242",
Description = "Uses a Gaussian kernel to blur the current image.",
GroupName = Global.GroupName,
Order = 5)]
[Icon]
public class BlurBlock : ImageProcessorMethodBaseBlock
{
public virtual int Kernelsize { get; set; }
public virtual double Sigma { get; set; }
public virtual int Threshold { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Blur(Kernelsize, Sigma, Threshold);
}
public override void SetDefaultValues(ContentType contentType)
{
base.SetDefaultValues(contentType);
Sigma = 1.4;
Threshold = 0;
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/ResizeBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Imaging;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Resize",
GUID = "a51f38ca-eb17-4acd-a3d6-c688ca7f98a3",
Description = "Resizes the current image to the given dimensions.",
GroupName = Global.GroupName,
Order = 23)]
[Icon]
public class ResizeBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Resize mode")]
[EnumAttribute(typeof(ResizeMode))]
public virtual ResizeMode Mode { get; set; }
[Display(Name = "Anchor position")]
[EnumAttribute(typeof(AnchorPosition))]
public virtual AnchorPosition Anchor { get; set; }
public virtual int Width { get; set; }
public virtual int Height { get; set; }
[Display(Name = "Width ratio")]
public virtual double WidthRatio { get; set; }
[Display(Name = "Height ratio")]
public virtual double HeightRatio { get; set; }
[Display(Name = "Center X")]
public virtual double CenterX { get; set; }
[Display(Name = "Center Y")]
public virtual double CenterY { get; set; }
[Display(Name = "Upscale")]
public virtual bool Upscale { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Resize(Width, Height, (float) WidthRatio, (float) HeightRatio, (float) CenterX, (float) CenterY, Mode, Anchor, Upscale);
}
public override void SetDefaultValues(ContentType contentType)
{
base.SetDefaultValues(contentType);
Upscale = true;
Anchor = AnchorPosition.Center;
WidthRatio = 0;
HeightRatio = 0;
CenterX = 0;
CenterY = 0;
Mode = ResizeMode.Pad;
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/FilterBlock.cs<|end_filename|>
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Filter",
GUID = "f6d77f0f-07b0-4495-9c56-57dadcbbc157",
Description = "Applies a filter to the current image.",
GroupName = Global.GroupName,
Order = 11)]
[Icon]
public class FilterBlock : ImageProcessorMethodBaseBlock
{
[EnumAttribute(typeof(Filter))]
public virtual Filter Filter { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Filter(Filter);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/WatermarkBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Watermark",
GUID = "6f0efc40-7e9a-4d07-ade2-292630a59dbf",
Description = "Adds a text based watermark to the current image with a wide range of options.",
GroupName = Global.GroupName,
Order = 31)]
[Icon]
public class WatermarkBlock : ImageProcessorMethodBaseBlock
{
private Point? position;
[Display(Name = "Text")]
public virtual string Text { get; set; }
public virtual int X { get; set; }
public virtual int Y { get; set; }
[UIHint("ColorPicker")]
public virtual string Color {
get
{
var color = this.GetPropertyValue(b => b.Color);
if (color == null)
return string.Empty;
color = color.TrimStart('#');
return color;
}
set
{
this.SetPropertyValue(b => b.Color, value.TrimStart('#'));
}
}
[Display(Name = "Font family")]
public virtual string FontFamily { get; set; }
public virtual int Size { get; set; }
[EnumAttribute(typeof(FontStyle))]
public virtual FontStyle Style { get; set; }
public virtual int Opacity { get; set; }
public virtual bool Dropshadow { get; set; }
public virtual bool Vertical { get; set; }
public virtual bool Rtl { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
position = new Point(X, Y);
return url.Watermark(Text, position, Color, FontFamily, Size, Style, Opacity, Dropshadow, Vertical, Rtl);
}
/// <summary>
/// Sets the default property values on the content data.
/// </summary>
/// <param name="contentType">Type of the content.</param>
public override void SetDefaultValues(ContentType contentType)
{
base.SetDefaultValues(contentType);
Text = string.Empty;
Color = "#ffffff";
position = new Point(X, Y);
FontFamily = null;
Size = 48;
Style = FontStyle.Bold;
Opacity = 100;
Dropshadow = false;
Vertical = false;
Rtl = false;
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Controllers/ProcessImageBlockController.cs<|end_filename|>
using System.Web.Mvc;
using EPiServer.Web.Mvc;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Controllers
{
public class ProcessImageBlockController : BlockController<Models.Blocks.ProcessImageBlock>
{
public override ActionResult Index(Models.Blocks.ProcessImageBlock currentContent)
{
return PartialView("~/modules/_protected/ImageProcessor.Web.Episerver.UI.Blocks/Views/ProcessImageBlock.cshtml", currentContent);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver/Extensions/Picture/PictureHelper.cs<|end_filename|>
using System;
using System.Web;
using System.Web.Mvc;
using EPiServer;
using EPiServer.Core;
using EPiServer.ServiceLocation;
using EPiServer.Web.Routing;
using ImageProcessor.Web.Episerver.Extensions.Picture;
using ImageProcessor.Web.Episerver.Picture;
namespace ImageProcessor.Web.Episerver
{
public static class PictureHelper
{
public static IHtmlString Picture(this HtmlHelper helper, ContentReference imageReference, ImageType imageType, LazyLoadType lazyLoadType, string altText = "")
{
return Picture(helper, imageReference, imageType, string.Empty, lazyLoadType, altText);
}
public static IHtmlString Picture(this HtmlHelper helper, ContentReference imageReference, ImageType imageType, string cssClass = "", LazyLoadType lazyLoadType = LazyLoadType.None, string altText = "")
{
if (imageReference == null)
{
return new MvcHtmlString(string.Empty);
}
var pictureData = PictureUtils.GetPictureData(imageReference, imageType, lazyLoadType == LazyLoadType.CustomProgressive, altText);
var pictureElement = BuildPictureElement(pictureData, cssClass, lazyLoadType);
return new MvcHtmlString(HttpUtility.HtmlDecode(pictureElement));
}
public static IHtmlString Picture(this HtmlHelper helper, string imageUrl, ImageType imageType, LazyLoadType lazyLoadType, string altText = "")
{
return Picture(helper, imageUrl, imageType, string.Empty, lazyLoadType, altText);
}
public static IHtmlString Picture(this HtmlHelper helper, string imageUrl, ImageType imageType, string cssClass = "", LazyLoadType lazyLoadType = LazyLoadType.None, string altText = "")
{
if (imageUrl == null)
{
return new MvcHtmlString(string.Empty);
}
var urlBuilder = new UrlBuilder(imageUrl);
return Picture(helper, urlBuilder, imageType, cssClass, lazyLoadType, altText);
}
public static IHtmlString Picture(this HtmlHelper helper, UrlBuilder imageUrl, ImageType imageType, string cssClass = "", LazyLoadType lazyLoadType = LazyLoadType.None, string altText = "")
{
if (imageUrl == null)
{
return new MvcHtmlString(string.Empty);
}
var pictureData = PictureUtils.GetPictureData(imageUrl, imageType, lazyLoadType == LazyLoadType.CustomProgressive, altText);
var pictureElement = BuildPictureElement(pictureData, cssClass, lazyLoadType);
return new MvcHtmlString(HttpUtility.HtmlDecode(pictureElement));
}
private static string BuildPictureElement(PictureData pictureData, string cssClass, LazyLoadType lazyLoadType)
{
//Create picture element
var pictureElement = new TagBuilder("picture");
if (pictureData.SrcSet != null)
{
if (pictureData.SrcSetWebp != null)
{
//Add source element with webp versions. Needs to be rendered before jpg version, browser selects the first version it supports.
pictureElement.InnerHtml += BuildSourceElement(pictureData, lazyLoadType, "webp");
}
//Add source element to picture element
pictureElement.InnerHtml += BuildSourceElement(pictureData, lazyLoadType);
}
//Add img element to picture element
pictureElement.InnerHtml += BuildImgElement(pictureData, lazyLoadType, cssClass);
return pictureElement.ToString();
}
private static string BuildImgElement(PictureData pictureData, LazyLoadType lazyLoadType, string cssClass)
{
var imgElement = new TagBuilder("img");
imgElement.Attributes.Add("alt", HttpUtility.HtmlEncode(pictureData.AltText));
//Add src and/or data-src attribute
switch (lazyLoadType)
{
case LazyLoadType.Custom:
case LazyLoadType.Hybrid:
imgElement.Attributes.Add("data-src", pictureData.ImgSrc);
break;
case LazyLoadType.CustomProgressive:
imgElement.Attributes.Add("src", pictureData.ImgSrcLowQuality);
imgElement.Attributes.Add("data-src", pictureData.ImgSrc);
break;
default:
imgElement.Attributes.Add("src", pictureData.ImgSrc);
break;
}
if (lazyLoadType == LazyLoadType.Native || lazyLoadType == LazyLoadType.Hybrid)
{
//Add loading attribute
imgElement.Attributes.Add("loading", "lazy");
}
//Add class attribute
if (!string.IsNullOrEmpty(cssClass))
{
imgElement.Attributes.Add("class", cssClass);
}
return imgElement.ToString(TagRenderMode.SelfClosing);
}
private static string BuildSourceElement(PictureData pictureData, LazyLoadType lazyLoadType, string format = "")
{
var sourceElement = new TagBuilder("source");
var srcset = pictureData.SrcSet;
if (format == "webp")
{
srcset = pictureData.SrcSetWebp;
sourceElement.Attributes.Add("type", "image/" + format);
}
switch (lazyLoadType)
{
case LazyLoadType.Custom:
case LazyLoadType.Hybrid:
sourceElement.Attributes.Add("data-srcset", srcset);
break;
case LazyLoadType.CustomProgressive:
sourceElement.Attributes.Add("srcset", format == "webp" ? pictureData.SrcSetLowQualityWebp : pictureData.SrcSetLowQuality);
sourceElement.Attributes.Add("data-srcset", srcset);
break;
default:
sourceElement.Attributes.Add("srcset", srcset);
break;
}
//Add sizes attribute
sourceElement.Attributes.Add("sizes", pictureData.SizesAttribute);
return sourceElement.ToString(TagRenderMode.SelfClosing);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Business/IForceAllPropertiesMode.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Business
{
public interface IForceAllPropertiesMode
{
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/EditorDescriptors/ImageReferenceBaseEditorDescriptor.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.Linq;
using EPiServer.Core;
using EPiServer.Shell;
using EPiServer.Shell.ObjectEditing;
using EPiServer.Shell.ObjectEditing.EditorDescriptors;
using ImageProcessor.Web.Episerver.UI.Crop.Core;
namespace ImageProcessor.Web.Episerver.UI.Crop.EditorDescriptors
{
public class ImageReferenceBaseEditorDescriptor : EditorDescriptor
{
public override void ModifyMetadata(ExtendedMetadata metadata, IEnumerable<Attribute> attributes)
{
base.ModifyMetadata(metadata, attributes);
var mediaReferenceAttribute = attributes.OfType<ImageReferenceAttribute>().FirstOrDefault();
if (mediaReferenceAttribute != null)
{
metadata.EditorConfiguration["cropRatio"] = mediaReferenceAttribute.CropRatio;
var allowedTypes = mediaReferenceAttribute.AllowedTypes;
if (allowedTypes == null || !allowedTypes.Any())
{
var imageDataType = typeof(ImageData);
allowedTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
.Where(t => imageDataType.IsAssignableFrom(t)).ToArray();
}
metadata.EditorConfiguration["allowedDndTypes"] =
allowedTypes.Select(x => x.FullName.ToLower()).ToArray();
}
metadata.CustomEditorSettings["uiWrapperType"] = UiWrapperType.Floating;
}
//public override void ModifyBaseMetadata(ExtendedMetadata metadata, IEnumerable<Attribute> attributes)
//{
//}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/BrightnessBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Brightness",
GUID = "290c6a81-2148-4716-bd68-024a3515bac8",
Description = "Adjusts the brightness of images.",
GroupName = Global.GroupName,
Order = 6)]
[Icon]
public class BrightnessBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Percentage", Description = "The desired adjustment percentage" )]
[Range(-99, 99)]
public virtual int Percentage { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Brightness(Percentage);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/EditorDescriptors/ImageReferenceListEditorDescriptor.cs<|end_filename|>
using EPiServer.Shell.ObjectEditing.EditorDescriptors;
using ImageProcessor.Web.Episerver.UI.Crop.Core.Collections;
namespace ImageProcessor.Web.Episerver.UI.Crop.EditorDescriptors
{
[EditorDescriptorRegistration(TargetType = typeof(ImageReferenceList), UIHint = "ImageReferenceList")]
public class ImageReferenceListEditorDescriptor : ImageReferenceBaseEditorDescriptor
{
public ImageReferenceListEditorDescriptor()
{
ClientEditingClass = "ipepiuicrop/Editors/ImageReferenceListSelector";
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/MetaBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Meta",
GUID = "e8270b25-2d7e-4abc-871d-35baf5a64016",
Description = "Toggles preservation of EXIF defined metadata within the image.",
GroupName = Global.GroupName,
Order = 18)]
[Icon]
public class MetaBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Preserve metadata")]
public virtual bool Preserve { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Meta(Preserve);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Serialization/LowercaseContractResolver.cs<|end_filename|>
using System;
using Newtonsoft.Json.Serialization;
namespace ImageProcessor.Web.Episerver.UI.Crop.Serialization
{
public class LowercaseContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return Char.ToLowerInvariant(propertyName[0]) + propertyName.Substring(1);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Core/MediaReference.cs<|end_filename|>
using System;
using EPiServer;
using EPiServer.Logging;
using EPiServer.ServiceLocation;
using EPiServer.Web.Routing;
using Newtonsoft.Json;
namespace ImageProcessor.Web.Episerver.UI.Crop.Core
{
[Serializable]
public abstract class MediaReference
{
//protected Injected<IUrlResolver> UrlResolver;
//protected Injected<ILogger> Logger;
//protected Injected<IContentRepository> ContentRepository;
public long Id { get; set; }
public abstract MediaReferenceType MediaType { get; }
public string PreviewUrl { get; set; }
[JsonIgnore]
public virtual string Url { get; }
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Core/CropDetails.cs<|end_filename|>
namespace ImageProcessor.Web.Episerver.UI.Crop.Core
{
public class CropDetails
{
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/RotateBoundedBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Rotate Bounded Block",
GUID = "0d536270-8fee-4413-86e9-42d7de84930f",
Description = "Rotate the image without expanding the canvas.",
GroupName = Global.GroupName,
Order = 25)]
[Icon]
public class RotateBoundedBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Rotate angle")]
[Range(-360,360)]
public virtual int Angle { get; set; }
[Display(Name = "Keep size")]
public virtual bool KeepSize { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.RotateBounded(Angle, KeepSize);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/FormatBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Format",
GUID = "80b7d027-49c3-4d41-8b97-2e253eec30ce",
Description = "Sets the output format of the current image to the given value.",
GroupName = Global.GroupName,
Order = 13)]
[Icon]
public class FormatBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Image format")]
[EnumAttribute(typeof(ImageFormat))]
public virtual ImageFormat Format { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Format(Format);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Core/Collections/MediaReferenceList.cs<|end_filename|>
using System.Collections.Generic;
namespace ImageProcessor.Web.Episerver.UI.Crop.Core.Collections
{
public class MediaReferenceList<T> : List<T> where T : MediaReference
{
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/CropProcessImageBlock.cs<|end_filename|>
using System;
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using EPiServer.Web.Routing;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
using ImageProcessor.Web.Episerver.UI.Crop.Core;
using ImageProcessor.Web.Episerver.UI.Crop.ExtensionMethods;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(
DisplayName = "Crop and process image",
GUID = "4a4c93fd-4215-43a4-88aa-18b70cfa69f5",
Description = "Crop and manipulate image stored in Episerver with ImageProcessor")]
[Icon]
public class CropProcessImageBlock : ProcessImageBaseBlock
{
/// <summary>
/// Gets the image to process
/// </summary>
/// <remarks></remarks>
[ImageReference]
[Display(Name = "Image", Order = 1)]
[Required(AllowEmptyStrings = false)]
public virtual ImageReference Image { get; set; }
public UrlBuilder GetMethods()
{
var url = new UrlBuilder(Image.GetCropUrl());
return MethodBuilder(url);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Core/Collections/ImageReferenceList.cs<|end_filename|>
namespace ImageProcessor.Web.Episerver.UI.Crop.Core.Collections
{
public class ImageReferenceList : MediaReferenceList<ImageReference>
{
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver/Extensions/Picture/PictureData.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImageProcessor.Web.Episerver.Extensions.Picture
{
public class PictureData
{
public string SrcSet { get; set; }
public string SrcSetWebp { get; set; }
public string SrcSetLowQuality { get; set; }
public string SrcSetLowQualityWebp { get; set; }
public string SizesAttribute { get; set; }
public string ImgSrc { get; set; }
public string ImgSrcLowQuality { get; set; }
public string AltText { get; set; }
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/EditorDescriptors/ImageReferenceEditorDescriptor.cs<|end_filename|>
using EPiServer.Shell.ObjectEditing.EditorDescriptors;
using ImageProcessor.Web.Episerver.UI.Crop.Core;
namespace ImageProcessor.Web.Episerver.UI.Crop.EditorDescriptors
{
[EditorDescriptorRegistration(TargetType = typeof(ImageReference), UIHint = "ImageReference")]
public class ImageReferenceEditorDescriptor : ImageReferenceBaseEditorDescriptor
{
public ImageReferenceEditorDescriptor()
{
ClientEditingClass = "ipepiuicrop/Editors/ImageReferenceSelector";
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/ExtensionMethods/ImageReferenceExtensions.cs<|end_filename|>
using System;
using EPiServer;
using EPiServer.Logging;
using EPiServer.Web.Routing;
using ImageProcessor.Web.Episerver;
using ImageProcessor.Web.Episerver.UI.Crop.Core;
namespace ImageProcessor.Web.Episerver.UI.Crop.ExtensionMethods
{
public static class ImageReferenceExtensions
{
private static readonly ILogger _logger;
static ImageReferenceExtensions()
{
_logger = LogManager.GetLogger(typeof(ImageReferenceExtensions));
}
public static UrlBuilder GetCropUrl(this ImageReference imageReference, int? width = null, int? height = null,
string fallback = null)
{
if (imageReference == null)
return GetFallback(fallback);
try
{
var url = UrlResolver.Current.GetUrl(new EPiServer.Core.ContentReference(imageReference.ContentLink));
if (string.IsNullOrEmpty(url))
throw new Exception("Could not retrieve image's url");
var urlBuilder = new UrlBuilder(url);
if (imageReference.CropDetails != null)
urlBuilder.QueryCollection.Add("crop",
$"{imageReference.CropDetails.X},{imageReference.CropDetails.Y},{imageReference.CropDetails.Width},{imageReference.CropDetails.Height}");
if (width.HasValue && width > 0)
urlBuilder.Width(width.Value);
if (height.HasValue && height > 0)
urlBuilder.Height(height.Value);
return urlBuilder;
}
catch (Exception ex)
{
_logger.Error("GetCroupUrl failed", ex);
return GetFallback(fallback);
}
}
private static UrlBuilder GetFallback(string fallback)
{
if (string.IsNullOrEmpty(fallback))
throw new ArgumentNullException("imageReference", "Image reference is null.");
return new UrlBuilder(fallback);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Core/PropertyImageReferenceList.cs<|end_filename|>
using System;
using EPiServer.Framework.DataAnnotations;
using EPiServer.PlugIn;
using ImageProcessor.Web.Episerver.UI.Crop.Core.Collections;
namespace ImageProcessor.Web.Episerver.UI.Crop.Core
{
[Serializable]
[EditorHint("ImageReferenceList")]
[PropertyDefinitionTypePlugIn(DisplayName = "ImageReferenceList")]
public class PropertyImageReferenceList : PropertyMediaReferenceBase<ImageReferenceList>
{
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Core/PropertyMediaReferenceBase.cs<|end_filename|>
using System;
using System.Collections.Generic;
using EPiServer.Core;
using EPiServer.Logging;
using ImageProcessor.Web.Episerver.UI.Crop.Serialization;
using Newtonsoft.Json;
namespace ImageProcessor.Web.Episerver.UI.Crop.Core
{
public abstract class PropertyMediaReferenceBase<T> : PropertyLongString
where T : class
{
protected readonly ILogger _logger = LogManager.GetLogger();
protected readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
Converters = new List<JsonConverter> {new MediaConverter()},
ContractResolver = new LowercaseContractResolver(),
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
public override Type PropertyValueType => typeof(T);
public override object Value
{
get
{
var value = base.Value as string;
if (value == null)
return null;
return JsonConvert.DeserializeObject<T>(value, _serializerSettings);
}
set
{
if (value != null)
base.Value = JsonConvert.SerializeObject(value, _serializerSettings);
}
}
public override object SaveData(PropertyDataCollection properties)
{
return JsonConvert.SerializeObject(Value, _serializerSettings);
}
public override void LoadData(object value)
{
try
{
Value = JsonConvert.DeserializeObject((string) value, _serializerSettings);
}
catch (Exception ex)
{
_logger.Error(ex.Message, ex);
Value = null;
}
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver/Extensions/Picture/Enums.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//TODO: namespace should be ImageProcessor.Web.Episerver.Picture, but wait for other breaking changes(?)
namespace ImageProcessor.Web.Episerver
{
public enum LazyLoadType
{
None,
Custom,
CustomProgressive,
[Obsolete("Use \"Custom\" instead.")]
Regular = Custom,
[Obsolete("Use \"CustomProgressive\" instead.")]
Progressive = CustomProgressive,
Native,
Hybrid
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/ProcessImageBaseBlock.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAnnotations;
using EPiServer.Web.Routing;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
public class ProcessImageBaseBlock : BlockData
{
[Display(Name = "Methods",
Description = "Select the methods to process the image with",
Order = 2)]
[AllowedTypes(typeof(ImageProcessorMethodBaseBlock))]
public virtual ContentArea Methods { get; set; }
[Display(Order = 3)]
public virtual int? Width { get; set; }
[Display(Order = 4)]
public virtual int? Height { get; set; }
public UrlBuilder MethodBuilder(UrlBuilder url)
{
if (Width > 0)
{
url.Width((int)Width);
}
if (Height > 0)
{
url.Height((int)Height);
}
if (Methods != null)
{
foreach (var item in Methods.FilteredItems)
{
if (item.GetContent() is ImageProcessorMethodBaseBlock method)
{
method.GetMethod(url);
}
}
}
return url;
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Core/PropertyImageReference.cs<|end_filename|>
using System;
using EPiServer.Framework.DataAnnotations;
using EPiServer.PlugIn;
namespace ImageProcessor.Web.Episerver.UI.Crop.Core
{
[Serializable]
[EditorHint("ImageReference")]
[PropertyDefinitionTypePlugIn(DisplayName = "ImageReference")]
public class PropertyImageReference : PropertyMediaReferenceBase<ImageReference>
{
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/ProcessImageBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using EPiServer.Shell.ObjectEditing;
using EPiServer.Web;
using EPiServer.Web.Routing;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(
DisplayName = "Process image",
GUID = "c493e717-5bee-4de7-8d8b-3ba40e012304",
Description = "Manipulate image stored in Episerver with ImageProcessor")]
[Icon]
public class ProcessImageBlock : ProcessImageBaseBlock
{
/// <summary>
/// Gets the image to process
/// </summary>
/// <remarks></remarks>
[DefaultDragAndDropTarget]
[Display(Name = "Image", Order = 1)]
[Required(AllowEmptyStrings = false)]
[UIHint(UIHint.Image)]
public virtual ContentReference Image
{
get; set;
}
public UrlBuilder GetMethods()
{
var url = new UrlBuilder(UrlResolver.Current.GetUrl(Image));
return MethodBuilder(url);
}
}
}
<|start_filename|>samples/AlloySampleLocal/modules/_protected/ImageProcessor.Web.Episerver.UI.Blocks/Views/CropProcessImageBlock.cshtml<|end_filename|>
@using System.Drawing
@using EPiServer.Web.Mvc.Html
@using ImageProcessor.Web.Episerver
@model ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks.CropProcessImageBlock
<img src="@Model.GetMethods()" />
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Controllers/CropProcessImageBlockController.cs<|end_filename|>
using System.Web.Mvc;
using EPiServer.Web.Mvc;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Controllers
{
public class CropProcessImageBlockController : BlockController<Models.Blocks.CropProcessImageBlock>
{
public override ActionResult Index(Models.Blocks.CropProcessImageBlock currentContent)
{
return PartialView("~/modules/_protected/ImageProcessor.Web.Episerver.UI.Blocks/Views/CropProcessImageBlock.cshtml", currentContent);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/SaturationBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Saturation",
GUID = "2266f607-1fb9-4356-ba5b-d7a6a781311a",
Description = "Adjusts the saturation of images.",
GroupName = Global.GroupName,
Order = 27)]
[Icon]
public class SaturationBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Percentage", Description = "The desired adjustment percentage")]
[Range(-99, 99)]
public virtual int Percentage { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Saturation(Percentage);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Business/ForceAllPropertiesModeUiDescriptor.cs<|end_filename|>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EPiServer.Shell;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Business
{
[UIDescriptorRegistration]
public class ForceAllPropertiesModeUiDescriptor : UIDescriptor<IForceAllPropertiesMode>
{
public ForceAllPropertiesModeUiDescriptor()
{
DefaultView = CmsViewNames.AllPropertiesView;
EnableStickyView = false;
DisabledViews = new List<string> { CmsViewNames.OnPageEditView, CmsViewNames.PreviewView };
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver/Extensions/Picture/PictureUtils.cs<|end_filename|>
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using EPiServer;
using EPiServer.Core;
using EPiServer.ServiceLocation;
using EPiServer.Web.Routing;
using ImageProcessor.Web.Episerver.Extensions.Picture;
namespace ImageProcessor.Web.Episerver.Picture
{
public static class PictureUtils
{
/// <summary>
/// Get the data necessary for rendering a Picture element.
/// </summary>
public static PictureData GetPictureData(ContentReference imageReference, ImageType imageType, bool includeLowQuality = false, string altText = "")
{
var imageUrl = new UrlBuilder(ServiceLocator.Current.GetInstance<UrlResolver>().GetUrl(imageReference));
//get focal point and/or alt-text from the image data
bool getFocalPoint, getAltText;
bool.TryParse(ConfigurationManager.AppSettings["IPE_FocalPointFromImage"], out getFocalPoint);
bool.TryParse(ConfigurationManager.AppSettings["IPE_AltTextFromImage"], out getAltText);
if (getFocalPoint || getAltText)
{
var image = ServiceLocator.Current.GetInstance<IContentLoader>().Get<IContent>(imageReference);
if (getFocalPoint)
{
imageUrl.MergeQueryCollection(BuildFocalPointCollection(image));
}
if (getAltText)
{
if (image?.Property["ImageAltText"]?.Value != null)
{
altText = HttpUtility.HtmlEncode(image.Property["ImageAltText"].ToString());
}
}
}
return GetPictureData(imageUrl, imageType, includeLowQuality, altText);
}
/// <summary>
/// Get the data necessary for rendering a Picture element.
/// </summary>
public static PictureData GetPictureData(string imageUrl, ImageType imageType, bool includeLowQuality = false, string altText = "")
{
var urlBuilder = new UrlBuilder(imageUrl);
return GetPictureData(urlBuilder, imageType, includeLowQuality, altText);
}
/// <summary>
/// Get the data necessary for rendering a Picture element.
/// </summary>
public static PictureData GetPictureData(UrlBuilder imageUrl, ImageType imageType, bool includeLowQuality = false, string altText = "")
{
var pData = new PictureData
{
AltText = altText
};
var currentFormat = GetFormatFromExtension(imageUrl.Path);
if (imageType.SrcSetWidths != null)
{
pData.SrcSet = BuildSrcSet(imageUrl, imageType, currentFormat);
pData.ImgSrc = BuildQueryString(imageUrl, imageType, imageType.DefaultImgWidth, currentFormat);
pData.SizesAttribute = string.Join(", ", imageType.SrcSetSizes);
if (includeLowQuality)
{
pData.SrcSetLowQuality = BuildSrcSet(imageUrl, imageType, currentFormat, true);
pData.ImgSrcLowQuality = BuildQueryString(imageUrl, imageType, imageType.DefaultImgWidth, currentFormat, 10);
}
//if jpg, also add webp versions
if (currentFormat == "jpg")
{
pData.SrcSetWebp = BuildSrcSet(imageUrl, imageType, "webp");
if (includeLowQuality)
{
pData.SrcSetLowQualityWebp = BuildSrcSet(imageUrl, imageType, "webp", true);
}
}
}
return pData;
}
private static string BuildSrcSet(UrlBuilder imageUrl, ImageType imageType, string format, bool lowQuality = false)
{
var lowQualityValue = format == "webp" ? 1 : 10; //webp can have lower quality value
var lowQualityFormat = format == "png" ? "png8" : format; //low quality png will be 8-bit
var srcset = string.Empty;
foreach (var width in imageType.SrcSetWidths)
{
if (lowQuality)
{
srcset += BuildQueryString(imageUrl, imageType, width, lowQualityFormat, lowQualityValue) + " " + width + "w, ";
}
else
{
srcset += BuildQueryString(imageUrl, imageType, width, format) + " " + width + "w, ";
}
}
srcset = srcset.TrimEnd(',', ' ');
return srcset;
}
private static string GetFormatFromExtension(string filePath)
{
var extension = Path.GetExtension(filePath);
var format = extension?.TrimStart('.');
if (format == "jpeg")
format = "jpg";
return format ?? string.Empty;
}
private static string BuildQueryString(UrlBuilder imageUrl, ImageType imageType, int? imageWidth, string format, int? overrideQuality = null)
{
var currentQueryKeys = imageUrl.QueryCollection.AllKeys;
var qc = new NameValueCollection();
if (format == "webp" || format == "png8")
{
qc.Add("format", format);
}
if (format != "png" && format != "png8") //quality is ignored for png anyway
{
if (overrideQuality.HasValue)
{
qc.Add("quality", overrideQuality.ToString());
}
else
{
if (!currentQueryKeys.Contains("quality")) //don't change quality value if it already exists
{
qc.Add("quality", imageType.Quality.ToString());
}
}
}
qc.Add("width", imageWidth.ToString());
if (imageType.HeightRatio > 0)
{
if (!currentQueryKeys.Contains("mode")) //don't change mode value if it already exists
{
qc.Add("mode", "crop");
}
qc.Add("heightratio", imageType.HeightRatio.ToString(CultureInfo.InvariantCulture));
}
bool.TryParse(ConfigurationManager.AppSettings["IPE_ShowInfo"], out var showDebugInfo);
if (showDebugInfo)
{
qc.Add(BuildInfoCollection(imageType, imageWidth, format));
}
//clone imageUrl and merge querystring values to the clone
var newTarget = new UrlBuilder(imageUrl.ToString());
newTarget.MergeQueryCollection(qc);
//make sure "quality" is last in querystring. It has to be after "format".
var quality = newTarget.QueryCollection.Get("quality");
if (!string.IsNullOrEmpty(quality))
{
newTarget.QueryCollection.Remove("quality");
newTarget.QueryCollection.Add("quality", quality);
}
return (string)newTarget;
}
private static NameValueCollection BuildFocalPointCollection(IContentData image)
{
var queryCollection = new NameValueCollection();
if (image?.Property["ImageFocalPoint"]?.Value != null)
{
var propertyValue = image.Property["ImageFocalPoint"].ToString();
var focalValues = propertyValue.Split('|');
if (focalValues.Length == 2)
{
var x = focalValues[0];
var y = focalValues[1];
queryCollection.Add("center", y + "," + x);
}
}
return queryCollection;
}
private static NameValueCollection BuildInfoCollection(ImageType imageType, int? imageWidth, string format)
{
var queryCollection = new NameValueCollection();
if (string.IsNullOrEmpty(format))
{
format = "original";
}
var height = Convert.ToInt32(imageWidth * imageType.HeightRatio);
var watermark = $"format:%20{format};%20width:%20{imageWidth};" + (height > 0 ? $"%20height:%20{height}" : "");
var fontsize = imageWidth > 700 ? 35 : 17;
var textX = imageWidth / 2 - 150;
textX = textX < 0 ? 10 : textX;
queryCollection.Add("watermark", watermark);
queryCollection.Add("color", "000000");
queryCollection.Add("fontsize", fontsize.ToString());
queryCollection.Add("textposition", string.Join(",", textX.ToString(), Convert.ToInt32(height / 2).ToString()));
return queryCollection;
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Serialization/AbstractJsonConverter.cs<|end_filename|>
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ImageProcessor.Web.Episerver.UI.Crop.Serialization
{
/// <summary>
/// Source: http://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class AbstractJsonConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override bool CanWrite => false;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
if (target == null)
return null;
//Create a new reader for this jObject, and set all properties to match the original reader.
JsonReader jObjectReader = jObject.CreateReader();
jObjectReader.Culture = reader.Culture;
jObjectReader.DateParseHandling = reader.DateParseHandling;
jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
jObjectReader.FloatParseHandling = reader.FloatParseHandling;
// Populate the object properties
serializer.Populate(jObjectReader, target);
return target;
}
/// <summary>Serializes to the specified type</summary>
/// <param name="writer">Newtonsoft.Json.JsonWriter</param>
/// <param name="value">Object to serialize.</param>
/// <param name="serializer">Newtonsoft.Json.JsonSerializer to use.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
protected static bool FieldExists(
JObject jObject,
string name,
JTokenType type)
{
JToken token;
return jObject.TryGetValue(name, out token) && token.Type == type;
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Core/ImageReferenceAttribute.cs<|end_filename|>
using System;
namespace ImageProcessor.Web.Episerver.UI.Crop.Core
{
[AttributeUsage(AttributeTargets.Property)]
public sealed class ImageReferenceAttribute : Attribute
{
//public ImageReferenceAttribute(Type[] allowedTypes)
//{
// AllowedTypes = allowedTypes;
//}
public double CropRatio { get; set; }
public Type[] AllowedTypes { get; set; }
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/RoundedCornersBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Rounded Corners",
GUID = "60b84172-12a5-4987-88c4-c285381d9ceb",
Description = "Adds rounded corners to the current image.",
GroupName = Global.GroupName,
Order = 26)]
[Icon]
public class RoundedCornersBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Radius")]
public virtual int Radius { get; set; }
[Display(Name = "Top left")]
public virtual bool Tl { get; set; }
[Display(Name = "Top right")]
public virtual bool Tr { get; set; }
[Display(Name = "Bottom left")]
public virtual bool Bl { get; set; }
[Display(Name = "Bottom right")]
public virtual bool Br { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.RoundedCorners(Radius, Tl, Tr, Bl, Br);
}
public override void SetDefaultValues(ContentType contentType)
{
base.SetDefaultValues(contentType);
Tl = true;
Tr = true;
Bl = true;
Br = true;
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Crop/Core/MediaReferenceType.cs<|end_filename|>
namespace ImageProcessor.Web.Episerver.UI.Crop.Core
{
public enum MediaReferenceType
{
Image = 0,
Other = 100
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/RotateBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Rotate",
GUID = "bfb53865-6e3b-4f8a-ae1b-109d6990bcad",
Description = "Rotates the current image by the given angle without clipping.",
GroupName = Global.GroupName,
Order = 24)]
[Icon]
public class RotateBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Angle")]
[Range(-360,360)]
public virtual int Angle { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Rotate(Angle);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/FlipBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Flip",
GUID = "3e364fb8-b530-413b-818b-bd2a83b42616",
Description = "Flips the current image either horizontally, vertically, or both.",
GroupName = Global.GroupName,
Order = 12)]
[Icon]
public class FlipBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Flip direction")]
[EnumAttribute(typeof(FlipDirection))]
public virtual FlipDirection FlipDirection { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Flip(FlipDirection);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/MaskBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Mask",
GUID = "fdc324b5-b3b6-4ad7-b19e-b8b70712dc06",
Description = "Applies the given image mask to the current image.",
GroupName = Global.GroupName,
Order = 17)]
[Icon]
public class MaskBlock : ImageProcessorMethodBaseBlock
{
public virtual int X { get; set; }
public virtual int Y { get; set; }
[Display(Name = "Mask Image")]
public virtual string MaskImage { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Mask(MaskImage, X, Y);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/PixelateBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Pixelate",
GUID = "9f61b2b0-0e12-46c5-95f8-4058adcb45b5",
Description = "Pixelates an image with the given size.",
GroupName = Global.GroupName,
Order = 20)]
[Icon]
public class PixelateBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Pixelblock size")]
public virtual int PixelBlockSize { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Pixelate(PixelBlockSize);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.Azure/AzureBlobCache.cs<|end_filename|>
using EPiServer;
using EPiServer.Core;
using EPiServer.Framework.Configuration;
using EPiServer.Logging;
using EPiServer.Web.Routing;
using ImageProcessor.Web.Caching;
//using ImageProcessor.Web.HttpModules;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
namespace ImageProcessor.Web.Episerver.Azure
{
/// <summary>
/// Provides an <see cref="IImageCache"/> implementation that uses the Episerver configured Azure blob storage.
/// The cache is self healing and cleaning.
/// </summary>
public class AzureBlobCache : ImageCacheBase
{
/// <summary>
/// The assembly version.
/// </summary>
private static readonly string AssemblyVersion = typeof(EpiserverImageProcessingModule).Assembly.GetName().Version.ToString();
/// <summary>
/// Use the configured logging mechanism
/// </summary>
private static readonly ILogger logger = LogManager.GetLogger();
/// <summary>
/// The cloud cached root blob container.
/// </summary>
private static CloudBlobContainer rootContainer;
/// <summary>
/// Determines if the CDN request is redirected or rewritten
/// </summary>
private readonly bool streamCachedImage;
/// <summary>
/// The timeout length for requesting the url.
/// </summary>
private readonly int timeout = 1000;
public string blobPath;
private const string prefix = "3p!_";
/// <summary>
/// Initializes a new instance of the <see cref="AzureBlobCache"/> class.
/// </summary>
/// <param name="requestPath">
/// The request path for the image.
/// </param>
/// <param name="fullPath">
/// The full path for the image.
/// </param>
/// <param name="querystring">
/// The query string containing instructions.
/// </param>
public AzureBlobCache(string requestPath, string fullPath, string querystring)
: base(requestPath, fullPath, querystring)
{
// Get the name of the configured blob provider
string providerName = EPiServerFrameworkSection.Instance.Blob.DefaultProvider;
if (rootContainer == null)
{
// Get the name of the connection string from there
string connectionStringName = EPiServerFrameworkSection.Instance.Blob.Providers[providerName].Parameters["connectionStringName"];
// Retrieve storage account from connection string.
CloudStorageAccount cloudCachedStorageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString);
// Create the blob client.
CloudBlobClient cloudBlobClient = cloudCachedStorageAccount.CreateCloudBlobClient();
// Retrieve reference to the container. Container is already created as part of the initialization process for the BlobProvider
rootContainer = cloudBlobClient.GetContainerReference(EPiServerFrameworkSection.Instance.Blob.Providers[providerName].Parameters["container"]);
}
//cachedCdnRoot = Settings.ContainsKey("CachedCDNRoot")
// ? Settings["CachedCDNRoot"]
// : rootContainer.Uri.ToString().TrimEnd(rootContainer.Name.ToCharArray());
if (Settings.ContainsKey("CDNTimeout"))
{
int.TryParse(Settings["CDNTimeout"], out int t);
timeout = t;
}
// This setting was added to facilitate streaming of the blob resource directly instead of a redirect. This is beneficial for CDN purposes
// but caution should be taken if not used with a CDN as it will add quite a bit of overhead to the site.
// See: https://github.com/JimBobSquarePants/ImageProcessor/issues/161
streamCachedImage = Settings.ContainsKey("StreamCachedImage") && Settings["StreamCachedImage"].ToLower() == "true";
}
/// <summary>
/// Gets a value indicating whether the image is new or updated in an asynchronous manner.
/// </summary>
/// <returns>
/// The asynchronous <see cref="Task"/> returning the value.
/// </returns>
public override async Task<bool> IsNewOrUpdatedAsync()
{
string cachedFilename = prefix + await CreateCachedFileNameAsync();
var media = UrlResolver.Current.Route(new UrlBuilder(FullPath)) as MediaData;
string containerName = media?.BinaryDataContainer?.Segments[1];
if (containerName == null)
{
// We're working with a static file here
containerName = $"_{prefix}static";
}
blobPath = $"{containerName}/{cachedFilename}";
CachedPath = $"{rootContainer.Uri.ToString()}/{containerName}/{cachedFilename}";
bool isUpdated = false;
CachedImage cachedImage = CacheIndexer.Get(CachedPath);
if (cachedImage == null)
{
CloudBlockBlob blockBlob = rootContainer.GetBlockBlobReference(blobPath);
//string t = GetSaSForBlob(blockBlob, SharedAccessBlobPermissions.Read);
if (await blockBlob.ExistsAsync())
{
// Pull the latest info.
await blockBlob.FetchAttributesAsync();
if (blockBlob.Properties.LastModified.HasValue)
{
cachedImage = new CachedImage
{
Key = Path.GetFileNameWithoutExtension(CachedPath),
Path = CachedPath,
CreationTimeUtc = blockBlob.Properties.LastModified.Value.UtcDateTime
};
CacheIndexer.Add(cachedImage, ImageCacheMaxMinutes);
}
}
}
if (cachedImage == null)
{
// Nothing in the cache so we should return true.
isUpdated = true;
}
else
{
// Check to see if the cached image is set to expire
// or a new file with the same name has replaced our current image
if (IsExpired(cachedImage.CreationTimeUtc) || await IsUpdatedAsync(cachedImage.CreationTimeUtc))
{
CacheIndexer.Remove(CachedPath);
isUpdated = true;
}
}
return isUpdated;
}
/// <summary>
/// Adds the image to the cache in an asynchronous manner.
/// </summary>
/// <param name="stream">
/// The stream containing the image data.
/// </param>
/// <param name="contentType">
/// The content type of the image.
/// </param>
/// <returns>
/// The <see cref="Task"/> representing an asynchronous operation.
/// </returns>
public override async Task AddImageToCacheAsync(Stream stream, string contentType)
{
CloudBlockBlob blockBlob = rootContainer.GetBlockBlobReference(blobPath);
await blockBlob.UploadFromStreamAsync(stream);
blockBlob.Properties.ContentType = contentType;
blockBlob.Properties.CacheControl = $"public, max-age={BrowserMaxDays * 86400}";
await blockBlob.SetPropertiesAsync();
blockBlob.Metadata.Add("ImageProcessedBy", "ImageProcessor.Web.Episerver.Azure" + AssemblyVersion);
await blockBlob.SetMetadataAsync();
return;
}
/// <summary>
/// Trims the cache of any expired items in an asynchronous manner.
/// </summary>
/// <returns>
/// The asynchronous <see cref="Task"/> representing an asynchronous operation.
/// </returns>
public override Task TrimCacheAsync()
{
if (!TrimCache)
{
return Task.FromResult(0);
}
ScheduleCacheTrimmer(async token =>
{
BlobContinuationToken continuationToken = null;
List<IListBlobItem> results = new List<IListBlobItem>();
// Loop through the all the files in a non blocking fashion.
do
{
BlobResultSegment response = await rootContainer.ListBlobsSegmentedAsync(string.Empty, true, BlobListingDetails.Metadata, 5000, continuationToken, null, null, token);
continuationToken = response.ContinuationToken;
results.AddRange(response.Results);
}
while (token.IsCancellationRequested == false && continuationToken != null);
// Now leap through and delete.
foreach (
CloudBlockBlob blob in
results.Where((blobItem, type) => blobItem is CloudBlockBlob)
.Cast<CloudBlockBlob>()
.OrderBy(b => b.Properties.LastModified?.UtcDateTime ?? new DateTime()))
{
if (token.IsCancellationRequested)
{
break;
}
if (blob.IsDeleted)
{
continue;
}
if (blob.Properties.LastModified.HasValue && !IsExpired(blob.Properties.LastModified.Value.UtcDateTime))
{
continue;
}
if (!blob.Name.Contains(prefix))
{
continue;
}
// Remove from the cache and delete each CachedImage.
CacheIndexer.Remove(blob.Name);
await blob.DeleteAsync(token);
}
});
return Task.FromResult(0);
}
/// <summary>
/// Returns a value indicating whether the requested image has been updated.
/// </summary>
/// <param name="creationDate">The creation date.</param>
/// <returns>The <see cref="bool"/></returns>
private async Task<bool> IsUpdatedAsync(DateTime creationDate)
{
bool isUpdated = false;
try
{
CloudBlockBlob blockBlob = rootContainer.GetBlockBlobReference(blobPath);
if (await blockBlob.ExistsAsync())
{
// Pull the latest info.
await blockBlob.FetchAttributesAsync();
if (blockBlob.Properties.LastModified.HasValue)
{
isUpdated = blockBlob.Properties.LastModified.Value.UtcDateTime > creationDate;
}
}
else
{
// Try and get the headers for the file, this should allow cache busting for remote files.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(RequestPath);
request.Method = "HEAD";
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
isUpdated = response.LastModified.ToUniversalTime() > creationDate;
}
}
}
catch
{
isUpdated = false;
}
return isUpdated;
}
/// <summary>
/// Rewrites the path to point to the cached image.
/// </summary>
/// <param name="context">
/// The <see cref="HttpContext"/> encapsulating all information about the request.
/// </param>
public override void RewritePath(HttpContext context)
{
CloudBlockBlob blockBlob = rootContainer.GetBlockBlobReference(blobPath);
string blobWithSAS = GetSaSForBlob(blockBlob, SharedAccessBlobPermissions.Read);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(blobWithSAS);
if (streamCachedImage)
{
// Map headers to enable 304s to pass through
if (context.Request.Headers["If-Modified-Since"] != null)
{
TrySetIfModifiedSinceDate(context, request);
}
string[] mapRequestHeaders = { "Cache-Control", "If-None-Match" };
foreach (string h in mapRequestHeaders)
{
if (context.Request.Headers[h] != null)
{
request.Headers.Add(h, context.Request.Headers[h]);
}
}
// Write the blob storage directly to the stream
request.Method = "GET";
request.Timeout = timeout;
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// A 304 is not an error
// It appears that some CDN's on Azure (Akamai) do not work properly when making head requests.
// They will return a response url and other headers but a 500 status code.
if (ex.Response != null && (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotModified
|| ex.Response.ResponseUri.AbsoluteUri.Equals(CachedPath, StringComparison.OrdinalIgnoreCase)))
{
response = (HttpWebResponse)ex.Response;
}
else
{
response?.Dispose();
logger.Error("Unable to stream cached path: " + CachedPath);
return;
}
}
Stream cachedStream = response.GetResponseStream();
if (cachedStream != null)
{
HttpResponse contextResponse = context.Response;
contextResponse.ClearHeaders();
// If streaming but not using a CDN the headers will be null.
// See https://github.com/JimBobSquarePants/ImageProcessor/pull/466
string etagHeader = response.Headers["ETag"];
if (!string.IsNullOrWhiteSpace(etagHeader))
{
contextResponse.Headers.Add("ETag", etagHeader);
}
string lastModifiedHeader = response.Headers["Last-Modified"];
if (!string.IsNullOrWhiteSpace(lastModifiedHeader))
{
contextResponse.Headers.Add("Last-Modified", lastModifiedHeader);
}
cachedStream.CopyTo(contextResponse.OutputStream); // Will be empty on 304s
EpiserverImageProcessingModule.SetHeaders(
context,
response.StatusCode == HttpStatusCode.NotModified ? null : response.ContentType,
null,
BrowserMaxDays,
response.StatusCode);
}
cachedStream?.Dispose();
response.Dispose();
}
else
{
// Prevent redundant metadata request if paths match.
//if (this.CachedPath == this.cachedRewritePath)
//{
// ImageProcessingModule.AddCorsRequestHeaders(context);
// context.Response.Redirect(this.CachedPath, false);
// return;
//}
// Redirect the request to the blob URL
request.Method = "HEAD";
request.Timeout = timeout;
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
response.Dispose();
EpiserverImageProcessingModule.AddCorsRequestHeaders(context);
context.Response.Redirect(blobWithSAS, false);
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
if (response != null)
{
HttpStatusCode responseCode = response.StatusCode;
// A 304 (NotModified) is not an error
// It appears that some CDN's on Azure (Akamai) do not work properly when making head requests.
// They will return a response url and other headers but a 500 status code.
if (responseCode == HttpStatusCode.NotModified || response.ResponseUri.AbsoluteUri.Equals(CachedPath, StringComparison.OrdinalIgnoreCase))
{
response.Dispose();
EpiserverImageProcessingModule.AddCorsRequestHeaders(context);
context.Response.Redirect(CachedPath, false);
}
else
{
response.Dispose();
logger.Error("Unable to rewrite cached path to: " + CachedPath);
}
}
else
{
// It's a 404, we should redirect to the cached path we have just saved to.
EpiserverImageProcessingModule.AddCorsRequestHeaders(context);
context.Response.Redirect(CachedPath, false);
}
}
}
}
/// <summary>
/// Tries to set IfModifiedSince header however this crashes when context.Request.Headers["If-Modified-Since"] exists,
/// but cannot be parsed. It cannot be parsed when it comes from Google Bot as UTC <example>Sun, 27 Nov 2016 20:01:45 UTC</example>
/// so DateTime.TryParse. If it returns false, then log the error.
/// </summary>
/// <param name="context">The current context</param>
/// <param name="request">The current request</param>
private static void TrySetIfModifiedSinceDate(HttpContext context, HttpWebRequest request)
{
string ifModifiedFromRequest = context.Request.Headers["If-Modified-Since"];
if (DateTime.TryParse(ifModifiedFromRequest, out DateTime ifModifiedDate))
{
request.IfModifiedSince = ifModifiedDate;
}
else
{
if (ifModifiedFromRequest.ToLower().Contains("utc"))
{
ifModifiedFromRequest = ifModifiedFromRequest.ToLower().Replace("utc", string.Empty);
if (DateTime.TryParse(ifModifiedFromRequest, out ifModifiedDate))
{
request.IfModifiedSince = ifModifiedDate;
}
}
else
{
logger.Error($"Unable to parse date {context.Request.Headers["If-Modified-Since"]} for {context.Request.Url}");
}
}
}
/// <summary>
/// Creates a SAS URI for the blob container.
/// </summary>
/// <param name="blobContainer"></param>
/// <param name="permission"></param>
/// <returns></returns>
static string GetSaSForBlobContainer(CloudBlobContainer blobContainer, SharedAccessBlobPermissions permission)
{
var sas = blobContainer.GetSharedAccessSignature(new SharedAccessBlobPolicy()
{
Permissions = permission,
SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),//SAS Start time is back by 5 minutes to take clock skewness into consideration
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15),
});
return string.Format(CultureInfo.InvariantCulture, "{0}{1}", blobContainer.Uri, sas);
}
/// <summary>
/// Creates a SAS URI for the blob.
/// </summary>
/// <param name="blob"></param>
/// <param name="permission"></param>
/// <returns></returns>
static string GetSaSForBlob(CloudBlockBlob blob, SharedAccessBlobPermissions permission)
{
var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
{
Permissions = permission,
SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5),
SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15),
});
return string.Format(CultureInfo.InvariantCulture, "{0}{1}", blob.Uri, sas);
}
}
}
<|start_filename|>src/ImageProcessor.Web.Episerver.UI.Blocks/Models/Blocks/TintBlock.cs<|end_filename|>
using System.ComponentModel.DataAnnotations;
using EPiServer;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using ImageProcessor.Web.Episerver.UI.Blocks.Business;
namespace ImageProcessor.Web.Episerver.UI.Blocks.Models.Blocks
{
[ContentType(DisplayName = "Tint",
GUID = "6150367c-3f59-4e4d-b96b-68b0c6fc3a2d",
Description = "Tints the current image with the given color.",
GroupName = Global.GroupName,
Order = 29)]
[Icon]
public class TintBlock : ImageProcessorMethodBaseBlock
{
[Display(Name = "Color")]
[UIHint("ColorPicker")]
public virtual string Color { get; set; }
public override UrlBuilder GetMethod(UrlBuilder url)
{
return url.Tint(Color);
}
}
} | ErikHen/ImageProcessor.Web.Episerver |
<|start_filename|>specs/armv5te-mustang-linux-gnueabi.json<|end_filename|>
{
"abi": "eabi",
"arch": "arm",
"crt-static-respected": true,
"data-layout": "e-m:e-p:32:32-Fi8-i64:64-v128:64:128-a:0:32-n32-S64",
"dynamic-linking": false,
"env": "gnu",
"executables": true,
"features": "+soft-float,+strict-align",
"has-elf-tls": true,
"has-thread-local": true,
"has-rpath": true,
"has-thumb-interworking": true,
"is-builtin": false,
"llvm-target": "armv5te-unknown-linux-gnueabi",
"max-atomic-width": 32,
"os": "linux",
"position-independent-executables": true,
"relro-level": "full",
"target-family": [
"unix"
],
"target-mcount": "\u0001__gnu_mcount_nc",
"target-pointer-width": "32",
"pre-link-args": {
"gcc": [
"-nostartfiles",
"-Wl,--undefined=memset"
]
},
"vendor": "mustang"
}
| carbotaniuman/mustang |
<|start_filename|>Assets/Scripts/CombatItem.cs<|end_filename|>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CombatItem : AItem {
private int damage;
}
<|start_filename|>Assets/Scripts/AItem.cs<|end_filename|>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class AItem : ScriptableObject {
public string ItemName;
public Sprite Sprite;
}
<|start_filename|>Assets/Scripts/Player/BoundsUtils.cs<|end_filename|>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class BoundsUtils {
public static void GetTopLeft(this Bounds bounds, ref Vector2 point) {
point.x = -bounds.extents.x;
point.y = bounds.extents.y;
point += (Vector2) bounds.center;
}
public static void GetTopRight( this Bounds bounds, ref Vector2 point ) {
point.x = bounds.extents.x;
point.y = bounds.extents.y;
point += (Vector2)bounds.center;
}
public static void GetBottomLeft( this Bounds bounds, ref Vector2 point ) {
point.x = -bounds.extents.x;
point.y = -bounds.extents.y;
point += (Vector2)bounds.center;
}
public static void GetBottomRight( this Bounds bounds, ref Vector2 point ) {
point.x = bounds.extents.x;
point.y = -bounds.extents.y;
point += (Vector2)bounds.center;
}
}
<|start_filename|>Assets/Scripts/KeyItem.cs<|end_filename|>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName ="Items/Key Item")]
public class KeyItem : AItem {
}
<|start_filename|>Assets/Scripts/Dialogue/ClickHandler.cs<|end_filename|>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ClickHandler : MonoBehaviour, IPointerClickHandler {
public UnityEvent Click;
public void OnPointerClick( PointerEventData eventData ) {
Click.Invoke();
}
}
<|start_filename|>Assets/Scripts/DialogueDef.cs<|end_filename|>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Dialogue Def")]
public class DialogueDef : ScriptableObject {
[TextArea(2,5)]
public string Text;
}
<|start_filename|>Assets/Scripts/Dialogue/Dialogue.cs<|end_filename|>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class Dialogue : MonoBehaviour {
public int MaxCharacters= 120;
public UnityEvent OnComplete;
private Text DialogText;
private string entireDialog = "";
private int indexInString = 0;
private void Start() {
DialogText = GetComponent<Text>();
}
public void SetDialog(string dialog) {
entireDialog = dialog;
indexInString = 0;
SetText();
}
public void ContinueText() {
if(indexInString >= entireDialog.Length) {
OnComplete.Invoke();
return;
}
indexInString += MaxCharacters;
SetText();
}
private void SetText() {
DialogText.text = entireDialog.Substring(indexInString, Mathf.Min(MaxCharacters, entireDialog.Length - indexInString));
}
}
<|start_filename|>Assets/Scripts/Dialogue/DialogueTester.cs<|end_filename|>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class DialogueTester : MonoBehaviour {
public Dialogue Dialogue;
public DialogueDef Text;
public void SetText() {
Dialogue.SetDialog(Text.Text);
}
#if UNITY_EDITOR
private void OnEnable() {
Dialogue = Object.FindObjectOfType<Dialogue>();
}
#endif
}
<|start_filename|>Assets/Scripts/PrintTester.cs<|end_filename|>
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrintTester : MonoBehaviour {
public void Print (string s) {
print(s);
}
}
| MichaelDemone/CyberpunkGame |
<|start_filename|>include/gltf2/Exceptions.hpp<|end_filename|>
#pragma once
#include <string>
#include <exception>
namespace gltf2 {
class MisformattedException: public std::exception {
public:
explicit MisformattedException(const char* key, const char* what) {
_what = std::string("Misformated file: '") + key + "' " + what;
}
explicit MisformattedException(const std::string& key, const std::string& what) {
_what = "Misformated file: '" + key + "' " + what;
}
virtual ~MisformattedException() throw() {}
virtual const char* what() const throw() {
return _what.c_str();
}
protected:
std::string _what;
};
class MisformattedExceptionNotNumber: public MisformattedException {
public:
explicit MisformattedExceptionNotNumber(const char* key) : MisformattedException(key, "is not a number") {}
explicit MisformattedExceptionNotNumber(const std::string& key) : MisformattedException(key, "is not a number") {}
virtual ~MisformattedExceptionNotNumber() throw() {}
};
class MisformattedExceptionNotBoolean: public MisformattedException {
public:
explicit MisformattedExceptionNotBoolean(const char* key) : MisformattedException(key, "is not a boolean") {}
explicit MisformattedExceptionNotBoolean(const std::string& key) : MisformattedException(key, "is not a boolean") {}
virtual ~MisformattedExceptionNotBoolean() throw() {}
};
class MisformattedExceptionNotString: public MisformattedException {
public:
explicit MisformattedExceptionNotString(const char* key) : MisformattedException(key, "is not a string") {}
explicit MisformattedExceptionNotString(const std::string& key) : MisformattedException(key, "is not a string") {}
virtual ~MisformattedExceptionNotString() throw() {}
};
class MisformattedExceptionNotArray: public MisformattedException {
public:
explicit MisformattedExceptionNotArray(const char* key) : MisformattedException(key, "is not an array") {}
explicit MisformattedExceptionNotArray(const std::string& key) : MisformattedException(key, "is not an array") {}
virtual ~MisformattedExceptionNotArray() throw() {}
};
class MisformattedExceptionNotGoodSizeArray: public MisformattedException {
public:
explicit MisformattedExceptionNotGoodSizeArray(const char* key) : MisformattedException(key, "is not the good size") {}
explicit MisformattedExceptionNotGoodSizeArray(const std::string& key) : MisformattedException(key, "is not the good size") {}
virtual ~MisformattedExceptionNotGoodSizeArray() throw() {}
};
class MisformattedExceptionNotObject: public MisformattedException {
public:
explicit MisformattedExceptionNotObject(const char* key) : MisformattedException(key, "is not an array") {}
explicit MisformattedExceptionNotObject(const std::string& key) : MisformattedException(key, "is not an array") {}
virtual ~MisformattedExceptionNotObject() throw() {}
};
class MisformattedExceptionIsRequired: public MisformattedException {
public:
explicit MisformattedExceptionIsRequired(const char* key) : MisformattedException(key, "is required") {}
explicit MisformattedExceptionIsRequired(const std::string& key) : MisformattedException(key, "is required") {}
virtual ~MisformattedExceptionIsRequired() throw() {}
};
}
<|start_filename|>test/basic.cpp<|end_filename|>
#include <gltf2/glTF2.hpp>
#include <gtest/gtest.h>
using namespace ::testing;
TEST(Main, Test0) {
gltf2::Asset asset = gltf2::load("./models/TriangleWithoutIndices.gltf");
// Asset
ASSERT_EQ(asset.metadata.version, "2.0");
ASSERT_EQ(asset.metadata.generator, "Manually converted to 2.0");
// Scenes
ASSERT_EQ(asset.scene, 0);
ASSERT_EQ(asset.scenes.size(), 1);
// Scene 0
ASSERT_EQ(asset.scenes[0].name, "scene0");
ASSERT_EQ(asset.scenes[0].nodes.size(), 1);
ASSERT_EQ(asset.scenes[0].nodes[0], 0);
// Nodes
ASSERT_EQ(asset.nodes.size(), 1);
// Node 0
ASSERT_EQ(asset.nodes[0].name, "node0");
ASSERT_EQ(asset.nodes[0].camera, -1);
ASSERT_EQ(asset.nodes[0].children.size(), 0);
ASSERT_EQ(asset.nodes[0].mesh, 0);
ASSERT_EQ(asset.nodes[0].skin, -1);
// Meshes
ASSERT_EQ(asset.meshes.size(), 1);
// Mesh 0
ASSERT_EQ(asset.meshes[0].name, "mesh0");
ASSERT_EQ(asset.meshes[0].primitives.size(), 1);
// Primitive 0
ASSERT_EQ(asset.meshes[0].primitives[0].mode, gltf2::Primitive::Mode::Triangles);
ASSERT_EQ(asset.meshes[0].primitives[0].indices, -1);
ASSERT_EQ(asset.meshes[0].primitives[0].material, -1);
// Primitive 0 attributes
ASSERT_EQ(asset.meshes[0].primitives[0].attributes.size(), 1);
ASSERT_EQ(asset.meshes[0].primitives[0].attributes.count("POSITION"), 1);
ASSERT_EQ(asset.meshes[0].primitives[0].attributes["POSITION"], 0);
// Accessors
ASSERT_EQ(asset.accessors.size(), 1);
// Accessor 0
ASSERT_EQ(asset.accessors[0].name, "");
ASSERT_EQ(asset.accessors[0].bufferView, 0);
ASSERT_EQ(asset.accessors[0].byteOffset, 0);
ASSERT_EQ(asset.accessors[0].componentType, gltf2::Accessor::ComponentType::Float);
ASSERT_EQ(asset.accessors[0].count, 3);
ASSERT_EQ(asset.accessors[0].type, gltf2::Accessor::Type::Vec3);
// BufferViews
ASSERT_EQ(asset.bufferViews.size(), 1);
// BufferView 0
ASSERT_EQ(asset.bufferViews[0].name, "");
ASSERT_EQ(asset.bufferViews[0].buffer, 0);
ASSERT_EQ(asset.bufferViews[0].byteOffset, 0);
ASSERT_EQ(asset.bufferViews[0].byteLength, 36);
ASSERT_EQ(asset.bufferViews[0].target, gltf2::BufferView::TargetType::ArrayBuffer);
// Buffer
ASSERT_EQ(asset.buffers.size(), 1);
// Buffer 0
ASSERT_EQ(asset.buffers[0].byteLength, 36);
ASSERT_EQ(asset.buffers[0].uri, "triangleWithoutIndices.bin");
ASSERT_NE(asset.buffers[0].data, nullptr);
uint8_t data[36] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f,
0x00, 0x00, 0x00, 0x00
};
for (uint32_t i = 0; i < asset.buffers[0].byteLength; ++i) {
ASSERT_EQ(asset.buffers[0].data[i], static_cast<char>(data[i]));
}
}
<|start_filename|>include/gltf2/glTF2.hpp<|end_filename|>
#pragma once
#include <string>
#include <unordered_map>
#include <vector>
#if defined(__ANDROID__)
#include <android/asset_manager.h>
#endif
namespace gltf2 {
#if defined(__ANDROID__)
extern AAssetManager* _assetManager;
#endif
using Attributes = std::unordered_map<std::string, uint32_t>;
struct Scene {
std::string name;
std::vector<uint32_t> nodes;
// extensions / extras
};
struct Primitive {
int32_t indices = -1; // Index to accessor containing the indices
int32_t material = -1; // Index to the material
enum class Mode : uint8_t {
Points = 0,
Lines = 1,
LineLoop = 2,
LineStrip = 3,
Triangles = 4,
TriangleStrip = 5,
TriangleFan = 6
} mode = Mode::Triangles; // primitive type
Attributes attributes; // Each attribute is mapped with his name and accessor index to the data
std::vector<Attributes> targets;
// extensions / extras
};
struct Mesh {
std::string name;
std::vector<float> weights;
std::vector<Primitive> primitives;
// extensions / extras
};
struct Buffer {
std::string name;
std::string uri;
uint32_t byteLength = 0;
char* data = nullptr;
// content
// extensions / extras
};
struct BufferView {
std::string name;
uint32_t buffer; // Index to the buffer
uint32_t byteOffset = 0;
uint32_t byteLength = 0;
uint32_t byteStride = 0; // The stride, in bytes
enum class TargetType : uint16_t {
None = 0,
ArrayBuffer = 34962,
ElementArrayBuffer = 34963
} target; // The target that the GPU buffer should be bound to.
// extensions / extras
};
struct Texture {
std::string name;
int32_t sampler{-1};
int32_t source{-1};
};
struct Sampler {
std::string name;
enum class MagFilter : uint16_t {
None,
Nearest = 9728,
Linear = 9729
} magFilter{MagFilter::None};
enum class MinFilter : uint16_t {
None,
Nearest = 9728,
Linear = 9729,
NearestMipMapNearest = 9984,
LinearMipMapNearest = 9985,
NearestMipMapLinear = 9986,
LinearMipMapLinear = 9987
} minFilter{MinFilter::None};
enum class WrappingMode : uint16_t {
ClampToEdge = 33071,
MirroredRepeat = 33648,
Repeat = 10497
};
WrappingMode wrapS{WrappingMode::Repeat};
WrappingMode wrapT{WrappingMode::Repeat};
};
struct Image {
std::string name;
std::string uri;
std::string mimeType;
int32_t bufferView{-1};
};
struct Material {
std::string name;
struct Texture {
int32_t index{-1};
uint32_t texCoord{0};
};
struct Pbr {
float baseColorFactor[4] = {1.0f, 1.0f, 1.0f, 1.0f};
Texture baseColorTexture;
float metallicFactor{1.0f};
float roughnessFactor{1.0f};
Texture metallicRoughnessTexture;
} pbr;
struct NormalTexture : Texture {
float scale{1.0f};
} normalTexture;
struct OcclusionTexture : Texture {
float strength{1.0f};
} occlusionTexture;
Texture emissiveTexture;
float emissiveFactor[3] = {0.0f, 0.0f, 0.0f};
enum class AlphaMode : uint8_t {
Opaque,
Mask,
Blend
} alphaMode{AlphaMode::Opaque};
float alphaCutoff{0.5f};
bool doubleSided{false};
};
struct Node {
std::string name;
int32_t camera = -1;
int32_t mesh = -1;
int32_t skin = -1;
std::vector<int> children;
float matrix[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
float rotation[4] = {0, 0, 0, 1};
float scale[3] = {1, 1, 1};
float translation[3] = { 0, 0, 0 };
std::vector<float> weights;
// extensions / extras
};
struct Accessor {
std::string name;
int32_t bufferView = -1;
uint32_t byteOffset = 0;
enum class ComponentType : uint16_t {
Byte = 5120,
UnsignedByte = 5121,
Short = 5122,
UnsignedShort = 5123,
UnsignedInt = 5125,
Float = 5126
} componentType;
bool normalized = false;
uint32_t count;
enum class Type : uint8_t {
Scalar,
Vec2,
Vec3,
Vec4,
Mat2,
Mat3,
Mat4
} type;
// max / min / sparse
// extensions / extras
};
struct Asset {
struct Metadata {
std::string copyright;
std::string generator;
std::string version;
std::string minVersion;
// extensions / extras
} metadata;
std::vector<std::string> extensionsUsed;
std::vector<std::string> extensionRequired;
std::vector<Accessor> accessors;
// std::vector<Animation> animations;
std::vector<Buffer> buffers;
std::vector<BufferView> bufferViews;
// std::vector<Camera> cameras;
std::vector<Image> images;
std::vector<Material> materials;
std::vector<Mesh> meshes;
std::vector<Node> nodes;
std::vector<Sampler> samplers;
int32_t scene = -1; // Index to the default scene
std::vector<Scene> scenes;
// std::vector<Skin> skins;
std::vector<Texture> textures;
// extensions / extras
std::string dirName;
Scene* getDefaultScene() const;
};
#if defined(__ANDROID__)
Asset load(std::string fileName, AAssetManager* assetManager);
#else
/**
* @brief Load a glTF v2.0 asset from a file
*
* @param[in] fileName The file name
*
* @return The asset
*/
Asset load(std::string fileName);
#endif
} // gltf2
<|start_filename|>src/gltf2/glTF2.cpp<|end_filename|>
#include <iostream>
#include <fstream>
#include <string>
#include <ext/json.hpp>
#include <gltf2/glTF2.hpp>
#include <gltf2/Exceptions.hpp>
#include <fstream>
namespace gltf2 {
#if defined(__ANDROID__)
AAssetManager* _assetManager = nullptr;
#endif
static void loadAsset(Asset& asset, nlohmann::json& json);
static void loadScenes(Asset& asset, nlohmann::json& json);
static void loadMeshes(Asset& asset, nlohmann::json& json);
static void loadNodes(Asset& asset, nlohmann::json& json);
static void loadBuffers(Asset& asset, nlohmann::json& json);
static void loadAccessors(Asset& asset, nlohmann::json& json);
static void loadBufferViews(Asset& asset, nlohmann::json& json);
static void loadBufferData(Asset& asset, Buffer& buffer);
static std::string pathAppend(const std::string& p1, const std::string& p2);
static void loadMaterials(Asset& asset, nlohmann::json& json);
static void loadTextureInfo(Material::Texture& texture, nlohmann::json& json);
static void loadImages(Asset& asset, nlohmann::json& json);
static void loadSamplers(Asset& asset, nlohmann::json& json);
static void loadTextures(Asset& asset, nlohmann::json& json);
static void loadAsset(Asset& asset, nlohmann::json& json) {
if (json.find("asset") == json.end()) {
throw MisformattedExceptionIsRequired("asset");
}
// version
if (json["asset"].find("version") == json["asset"].end()) {
throw MisformattedExceptionIsRequired("asset[version]");
}
if (!json["asset"]["version"].is_string()) {
throw MisformattedExceptionNotString("version");
}
asset.metadata.version = json["asset"]["version"].get<std::string>();
// copyright
if (json["asset"].find("copyright") != json["asset"].end()) {
if (!json["asset"]["copyright"].is_string()) {
throw MisformattedExceptionNotString("copyright");
}
asset.metadata.copyright = json["asset"]["copyright"].get<std::string>();
}
// generator
if (json["asset"].find("generator") != json["asset"].end()) {
if (!json["asset"]["generator"].is_string()) {
throw MisformattedExceptionNotString("generator");
}
asset.metadata.generator = json["asset"]["generator"].get<std::string>();
}
// minVersion
if (json["asset"].find("minVersion") != json["asset"].end()) {
if (!json["asset"]["minVersion"].is_string()) {
throw MisformattedExceptionNotString("minVersion");
}
asset.metadata.minVersion = json["asset"]["minVersion"].get<std::string>();
}
}
static void loadScenes(Asset& asset, nlohmann::json& json) {
if (json.find("scene") != json.end()) {
if (!json["scene"].is_number()) {
throw MisformattedExceptionNotNumber("scene");
}
asset.scene = json["scene"].get<int32_t>();
}
if (json.find("scenes") == json.end()) {
return;
}
auto& scenes = json["scenes"];
if (!scenes.is_array()) {
throw MisformattedExceptionNotArray("scenes");
}
if (asset.scene == -1) {
asset.scene = 0;
}
asset.scenes.resize(scenes.size());
for (uint32_t i = 0; i < scenes.size(); ++i) {
// name
if (scenes[i].find("name") != scenes[i].end()) {
if (!scenes[i]["name"].is_string()) {
throw MisformattedExceptionNotString("scenes[i][name]");
}
asset.scenes[i].name = scenes[i]["name"];
}
// nodes
if (scenes[i].find("nodes") != scenes[i].end()) {
auto& nodes = scenes[i]["nodes"];
if (!nodes.is_array()) {
throw MisformattedExceptionNotArray("scenes[i][nodes]");
}
asset.scenes[i].nodes.resize(nodes.size());
for (uint32_t j = 0; j < nodes.size(); ++j) {
asset.scenes[i].nodes[j] = nodes[j].get<uint32_t>();
}
}
}
}
static void loadMeshes(Asset& asset, nlohmann::json& json) {
if (json.find("meshes") == json.end()) {
return;
}
auto& meshes = json["meshes"];
if (!meshes.is_array()) {
throw MisformattedExceptionNotArray("meshes");
}
asset.meshes.resize(meshes.size());
for (uint32_t i = 0; i < meshes.size(); ++i) {
// name
if (meshes[i].find("name") != meshes[i].end()) {
if (!meshes[i]["name"].is_string()) {
throw MisformattedExceptionNotString("meshes[i][name]");
}
asset.meshes[i].name = meshes[i]["name"];
}
if (meshes[i].find("primitives") == meshes[i].end()) {
throw MisformattedExceptionIsRequired("meshes[i][primitives]");
}
auto& primitives = meshes[i]["primitives"];
if (!primitives.is_array()) {
throw MisformattedExceptionNotArray("meshes[i][primitives]");
}
asset.meshes[i].primitives.resize(primitives.size());
for (uint32_t j = 0; j < primitives.size(); ++j) {
// indices
if (primitives[j].find("indices") != primitives[j].end()) {
if (!primitives[j]["indices"].is_number()) {
throw MisformattedExceptionNotNumber("meshes[i][primitives][j][indices]");
}
asset.meshes[i].primitives[j].indices = primitives[j]["indices"].get<int32_t>();
}
// material
if (primitives[j].find("material") != primitives[j].end()) {
if (!primitives[j]["material"].is_number()) {
throw MisformattedExceptionNotNumber("meshes[i][primitives][j][material]");
}
asset.meshes[i].primitives[j].material = primitives[j]["material"].get<int32_t>();
}
// mode
if (primitives[j].find("mode") != primitives[j].end()) {
if (!primitives[j]["mode"].is_number()) {
throw MisformattedExceptionNotNumber("meshes[i][primitives][j][mode]");
}
asset.meshes[i].primitives[j].mode = static_cast<Primitive::Mode>(primitives[j]["mode"].get<uint8_t>());
}
if (primitives[j].find("attributes") == primitives[j].end()) {
throw MisformattedExceptionIsRequired("meshes[i][primitives][j][attributes]");
}
auto& attributes = primitives[j]["attributes"];
if (!attributes.is_object()) {
throw MisformattedExceptionNotObject("meshes[i][primitives][j][attributes]");
}
for (nlohmann::json::iterator it = attributes.begin(); it != attributes.end(); ++it) {
asset.meshes[i].primitives[j].attributes[it.key()] = it.value();
}
// TODO: primitives[j]["targets"]
}
// TODO: meshes[i]["weights"]
// TODO: meshes[i]["extensions"]
}
}
static void loadNodes(Asset& asset, nlohmann::json& json) {
if (json.find("nodes") == json.end()) {
return;
}
auto& nodes = json["nodes"];
if (!nodes.is_array()) {
throw MisformattedExceptionNotArray("nodes");
}
asset.nodes.resize(nodes.size());
for (uint32_t i = 0; i < nodes.size(); ++i) {
// name
if (nodes[i].find("name") != nodes[i].end()) {
if (!nodes[i]["name"].is_string()) {
throw MisformattedExceptionNotString("nodes[i][name]");
}
asset.nodes[i].name = nodes[i]["name"];
}
// camera
if (nodes[i].find("camera") != nodes[i].end()) {
if (!nodes[i]["camera"].is_number()) {
throw MisformattedExceptionNotNumber("nodes[i][camera]");
}
asset.nodes[i].camera = nodes[i]["camera"].get<int32_t>();
}
// children
if (nodes[i].find("children") != nodes[i].end()) {
auto& children = nodes[i]["children"];
if (!children.is_array()) {
throw MisformattedExceptionNotArray("nodes[i][chidren]");
}
asset.nodes[i].children.resize(children.size());
for (uint32_t j = 0; j < children.size(); ++j) {
asset.nodes[i].children[j] = children[j].get<uint32_t>();
}
}
// skin
if (nodes[i].find("skin") != nodes[i].end()) {
if (!nodes[i]["skin"].is_number()) {
throw MisformattedExceptionNotNumber("nodes[i][skin]");
}
asset.nodes[i].skin = nodes[i]["skin"].get<int32_t>();
}
// TODO: nodes[i]["matrix"]
// mesh
if (nodes[i].find("mesh") != nodes[i].end()) {
if (!nodes[i]["mesh"].is_number()) {
throw MisformattedExceptionNotNumber("nodes[i][mesh]");
}
asset.nodes[i].mesh = nodes[i]["mesh"].get<int32_t>();
}
// translation
if (nodes[i].find("translation") != nodes[i].end()) {
if (!nodes[i]["translation"].is_array()) {
throw MisformattedExceptionNotArray("nodes[i][translation]");
}
if (nodes[i]["translation"].size() != 3) {
throw MisformattedExceptionNotGoodSizeArray("nodes[i][translation]");
}
for (uint32_t j = 0; j < 3; ++j) {
if (!nodes[i]["translation"][j].is_number()) {
throw MisformattedExceptionNotNumber("nodes[i][translation][j]");
}
asset.nodes[i].translation[j] = nodes[i]["translation"][j].get<float>();
}
}
// rotation
if (nodes[i].find("rotation") != nodes[i].end()) {
if (!nodes[i]["rotation"].is_array()) {
throw MisformattedExceptionNotArray("nodes[i][rotation]");
}
if (nodes[i]["rotation"].size() != 4) {
throw MisformattedExceptionNotGoodSizeArray("nodes[i][rotation]");
}
for (uint32_t j = 0; j < 4; ++j) {
if (!nodes[i]["rotation"][j].is_number()) {
throw MisformattedExceptionNotNumber("nodes[i][rotation][j]");
}
asset.nodes[i].rotation[j] = nodes[i]["rotation"][j].get<float>();
}
}
// scale
if (nodes[i].find("scale") != nodes[i].end()) {
if (!nodes[i]["scale"].is_array()) {
throw MisformattedExceptionNotArray("nodes[i][scale]");
}
if (nodes[i]["scale"].size() != 3) {
throw MisformattedExceptionNotGoodSizeArray("nodes[i][scale]");
}
for (uint32_t j = 0; j < 3; ++j) {
if (!nodes[i]["scale"][j].is_number()) {
throw MisformattedExceptionNotNumber("nodes[i][scale][j]");
}
asset.nodes[i].scale[j] = nodes[i]["scale"][j].get<float>();
}
}
// TODO: nodes[i]["weights"]
}
}
static void loadBuffers(Asset& asset, nlohmann::json& json) {
if (json.find("buffers") == json.end()) {
return;
}
auto& buffers = json["buffers"];
if (!buffers.is_array()) {
throw MisformattedExceptionNotArray("buffers");
}
asset.buffers.resize(buffers.size());
for (uint32_t i = 0; i < buffers.size(); ++i) {
// name
if (buffers[i].find("name") != buffers[i].end()) {
if (!buffers[i]["name"].is_string()) {
throw MisformattedExceptionNotString("buffers[i][name]");
}
asset.buffers[i].name = buffers[i]["name"];
}
// byteLength
if (buffers[i].find("byteLength") == buffers[i].end()) {
throw MisformattedExceptionIsRequired("buffers[i][byteLength]");
} else if (!buffers[i]["byteLength"].is_number()) {
throw MisformattedExceptionNotNumber("buffers[i][byteLength]");
}
asset.buffers[i].byteLength = buffers[i]["byteLength"].get<int32_t>();
// uri
if (buffers[i].find("uri") != buffers[i].end()) {
if (!buffers[i]["uri"].is_string()) {
throw MisformattedExceptionNotString("buffers[i][uri]");
}
asset.buffers[i].uri = buffers[i]["uri"];
}
loadBufferData(asset, asset.buffers[i]);
}
}
static void loadAccessors(Asset& asset, nlohmann::json& json) {
if (json.find("accessors") == json.end()) {
return;
}
auto& accessors = json["accessors"];
if (!accessors.is_array()) {
throw MisformattedExceptionNotArray("accessors");
}
asset.accessors.resize(accessors.size());
for (uint32_t i = 0; i < accessors.size(); ++i) {
// bufferView
if (accessors[i].find("bufferView") != accessors[i].end()) {
if (!accessors[i]["bufferView"].is_number()) {
throw MisformattedExceptionNotNumber("accessors[i][bufferView]");
}
asset.accessors[i].bufferView = accessors[i]["bufferView"].get<int32_t>();
}
// bufferView
if (accessors[i].find("bufferView") != accessors[i].end()) {
if (!accessors[i]["bufferView"].is_number()) {
throw MisformattedExceptionNotNumber("accessors[i][bufferView]");
}
asset.accessors[i].bufferView = accessors[i]["bufferView"].get<int32_t>();
}
// byteOffset
if (accessors[i].find("byteOffset") != accessors[i].end()) {
if (!accessors[i]["byteOffset"].is_number()) {
throw MisformattedExceptionNotNumber("accessors[i][byteOffset]");
}
asset.accessors[i].byteOffset = accessors[i]["byteOffset"].get<uint32_t>();
}
// componentType
if (accessors[i].find("componentType") == accessors[i].end()) {
throw MisformattedExceptionIsRequired("accessors[i][componentType]");
} else if (!accessors[i]["componentType"].is_number()) {
throw MisformattedExceptionNotNumber("accessors[i][componentType]");
}
asset.accessors[i].componentType = static_cast<Accessor::ComponentType>(accessors[i]["componentType"].get<uint16_t>());
// normalized
if (accessors[i].find("normalized") != accessors[i].end()) {
if (!accessors[i]["normalized"].is_boolean()) {
throw MisformattedExceptionNotBoolean("accessors[i][normalized]");
}
asset.accessors[i].normalized = accessors[i]["normalized"].get<bool>();
}
// count
if (accessors[i].find("count") == accessors[i].end()) {
throw MisformattedExceptionIsRequired("accessors[i][count]");
} else if (!accessors[i]["count"].is_number()) {
throw MisformattedExceptionNotNumber("accessors[i][count]");
}
asset.accessors[i].count = accessors[i]["count"].get<uint32_t>();
// type
if (accessors[i].find("type") == accessors[i].end()) {
throw MisformattedExceptionIsRequired("accessors[i][type]");
} else if (!accessors[i]["type"].is_string()) {
throw MisformattedExceptionNotString("accessors[i][type]");
}
std::string type = accessors[i]["type"].get<std::string>();
if (type == "SCALAR") {
asset.accessors[i].type = Accessor::Type::Scalar;
} else if (type == "VEC2") {
asset.accessors[i].type = Accessor::Type::Vec2;
} else if (type == "VEC3") {
asset.accessors[i].type = Accessor::Type::Vec3;
} else if (type == "VEC4") {
asset.accessors[i].type = Accessor::Type::Vec4;
} else if (type == "MAT2") {
asset.accessors[i].type = Accessor::Type::Mat2;
} else if (type == "MAT3") {
asset.accessors[i].type = Accessor::Type::Mat3;
} else if (type == "MAT4") {
asset.accessors[i].type = Accessor::Type::Mat4;
} else {
throw MisformattedException("accessors[i][type]", "is not a valid type");
}
// TODO: accessors[i]["sparse"]
// TODO: accessors[i]["extensions"]
// TODO: accessors[i]["min"]
// TODO: accessors[i]["max"]
}
}
static void loadBufferViews(Asset& asset, nlohmann::json& json) {
if (json.find("bufferViews") == json.end()) {
return;
}
auto& bufferViews = json["bufferViews"];
if (!bufferViews.is_array()) {
throw MisformattedExceptionNotArray("bufferViews");
}
asset.bufferViews.resize(bufferViews.size());
for (uint32_t i = 0; i < bufferViews.size(); ++i) {
// name
if (bufferViews[i].find("name") != bufferViews[i].end()) {
if (!bufferViews[i]["name"].is_string()) {
throw MisformattedExceptionNotString("bufferViews[i][name]");
}
asset.bufferViews[i].name = bufferViews[i]["name"];
}
// buffer
if (bufferViews[i].find("buffer") == bufferViews[i].end()) {
throw MisformattedExceptionIsRequired("bufferViews[i][buffer]");
}
if (!bufferViews[i]["buffer"].is_number()) {
throw MisformattedExceptionNotNumber("bufferViews[i][buffer]");
}
asset.bufferViews[i].buffer = bufferViews[i]["buffer"].get<int32_t>();
// byteOffset
if (bufferViews[i].find("byteOffset") == bufferViews[i].end()) {
throw MisformattedExceptionIsRequired("bufferViews[i][byteOffset]");
}
if (!bufferViews[i]["byteOffset"].is_number()) {
throw MisformattedExceptionNotNumber("bufferViews[i][byteOffset]");
}
asset.bufferViews[i].byteOffset = bufferViews[i]["byteOffset"].get<int32_t>();
// byteLength
if (bufferViews[i].find("byteLength") == bufferViews[i].end()) {
throw MisformattedExceptionIsRequired("bufferViews[i][byteLength]");
}
if (!bufferViews[i]["byteLength"].is_number()) {
throw MisformattedExceptionNotNumber("bufferViews[i][byteLength]");
}
asset.bufferViews[i].byteLength = bufferViews[i]["byteLength"].get<int32_t>();
// byteStride
if (bufferViews[i].find("byteStride") != bufferViews[i].end()) {
if (!bufferViews[i]["byteStride"].is_number()) {
throw MisformattedExceptionNotNumber("bufferViews[i][byteStride]");
}
asset.bufferViews[i].byteStride = bufferViews[i]["byteStride"].get<int32_t>();
}
// target
if (bufferViews[i].find("target") != bufferViews[i].end()) {
if (!bufferViews[i]["target"].is_number()) {
throw MisformattedExceptionNotNumber("bufferViews[i][target]");
}
asset.bufferViews[i].target = static_cast<BufferView::TargetType>(bufferViews[i]["target"].get<uint16_t>());
}
// TODO: bufferViews[i]["extensions"]
// TODO: bufferViews[i]["extras"]
}
}
static void loadBufferData(Asset& asset, Buffer& buffer) {
if (!buffer.uri.size() && buffer.byteLength > 0) {
throw MisformattedException("buffers[i]", "is not empty but has no uri");
}
buffer.data = new char[buffer.byteLength];
#if defined(__ANDROID__)
AAsset* assetAndroid = AAssetManager_open(_assetManager, pathAppend(asset.dirName, buffer.uri).c_str(), AASSET_MODE_STREAMING);
if (!assetAndroid) {
throw std::runtime_error("Can't open Android asset");
}
AAsset_read(assetAndroid, reinterpret_cast<char*>(buffer.data), buffer.byteLength);
AAsset_close(assetAndroid);
#else
// TODO: load base64 uri
std::ifstream fileData(pathAppend(asset.dirName, buffer.uri), std::ios::binary);
if (!fileData.good()) {
throw MisformattedException("buffers[i].uri", "has not a valid uri (failed to open file)");
}
fileData.read(buffer.data, buffer.byteLength);
fileData.close();
#endif
}
static std::string pathAppend(const std::string& p1, const std::string& p2) {
char sep = '/';
std::string tmp = p1;
if (p1[p1.length()] != sep) { // Need to add a
tmp += sep; // path separator
return tmp + p2;
} else {
return p1 + p2;
}
}
static std::string getDirectoryName(const std::string& path) {
std::size_t found;
found = path.find_last_of("/");
if (found == std::string::npos) {
return "";
}
return path.substr(0, found);
}
static void loadMaterials(Asset& asset, nlohmann::json& json) {
if (json.find("materials") == json.end()) {
return;
}
auto& materials = json["materials"];
if (!materials.is_array()) {
throw MisformattedExceptionNotArray("materials");
}
asset.materials.resize(materials.size());
for (uint32_t i = 0; i < materials.size(); ++i) {
// name
if (materials[i].find("name") != materials[i].end()) {
if (!materials[i]["name"].is_string()) {
throw MisformattedExceptionNotString("materials[i][name]");
}
asset.materials[i].name = materials[i]["name"];
}
// pbrMetallicRoughness
if (materials[i].find("pbrMetallicRoughness") != materials[i].end()) {
if (!materials[i]["pbrMetallicRoughness"].is_object()) {
throw MisformattedExceptionNotObject("materials[i][pbrMetallicRoughness]");
}
// pbrMetallicRoughness.baseColorFactor
if (materials[i]["pbrMetallicRoughness"].find("baseColorFactor") != materials[i]["pbrMetallicRoughness"].end()) {
if (!materials[i]["pbrMetallicRoughness"]["baseColorFactor"].is_array()) {
throw MisformattedExceptionNotArray("materials[i][pbrMetallicRoughness][baseColorFactor]");
}
if (materials[i]["pbrMetallicRoughness"]["baseColorFactor"].size() != 4) {
throw MisformattedExceptionNotGoodSizeArray("materials[i][pbrMetallicRoughness][baseColorFactor]");
}
for (uint32_t j = 0; j < 4; ++j) {
if (!materials[i]["pbrMetallicRoughness"]["baseColorFactor"][j].is_number()) {
throw MisformattedExceptionNotNumber("materials[i][pbrMetallicRoughness][baseColorFactor][j]");
}
asset.materials[i].pbr.baseColorFactor[j] = materials[i]["pbrMetallicRoughness"]["baseColorFactor"][j].get<float>();
}
}
// pbrMetallicRoughness.baseColorTexture
if (materials[i]["pbrMetallicRoughness"].find("baseColorTexture") != materials[i]["pbrMetallicRoughness"].end()) {
loadTextureInfo(asset.materials[i].pbr.baseColorTexture, materials[i]["pbrMetallicRoughness"]["baseColorTexture"]);
}
// pbrMetallicRoughness.metallicFactor
if (materials[i]["pbrMetallicRoughness"].find("metallicFactor") != materials[i]["pbrMetallicRoughness"].end()) {
if (!materials[i]["pbrMetallicRoughness"]["metallicFactor"].is_number()) {
throw MisformattedExceptionNotNumber("materials[i][pbrMetallicRoughness][metallicFactor]");
}
asset.materials[i].pbr.metallicFactor = materials[i]["pbrMetallicRoughness"]["metallicFactor"].get<float>();
}
// pbrMetallicRoughness.roughnessFactor
if (materials[i]["pbrMetallicRoughness"].find("roughnessFactor") != materials[i]["pbrMetallicRoughness"].end()) {
if (!materials[i]["pbrMetallicRoughness"]["roughnessFactor"].is_number()) {
throw MisformattedExceptionNotNumber("materials[i][pbrMetallicRoughness][roughnessFactor]");
}
asset.materials[i].pbr.roughnessFactor = materials[i]["pbrMetallicRoughness"]["roughnessFactor"].get<float>();
}
// pbrMetallicRoughness.metallicRoughnessTexture
if (materials[i]["pbrMetallicRoughness"].find("metallicRoughnessTexture") != materials[i]["pbrMetallicRoughness"].end()) {
loadTextureInfo(asset.materials[i].pbr.metallicRoughnessTexture, materials[i]["pbrMetallicRoughness"]["metallicRoughnessTexture"]);
}
}
// normalTexture
if (materials[i].find("normalTexture") != materials[i].end()) {
loadTextureInfo(asset.materials[i].normalTexture, materials[i]["normalTexture"]);
// scale
if (materials[i]["normalTexture"].find("scale") != materials[i]["normalTexture"].end()) {
if (!materials[i]["normalTexture"]["scale"].is_number()) {
throw MisformattedExceptionNotNumber("materials[i][normalTexture][scale]");
}
}
}
// occlusionTexture
if (materials[i].find("occlusionTexture") != materials[i].end()) {
loadTextureInfo(asset.materials[i].occlusionTexture, materials[i]["occlusionTexture"]);
// scale
if (materials[i]["occlusionTexture"].find("strength") != materials[i]["occlusionTexture"].end()) {
if (!materials[i]["occlusionTexture"]["strength"].is_number()) {
throw MisformattedExceptionNotNumber("materials[i][occlusionTexture][strength]");
}
}
}
// emissiveTexture
if (materials[i].find("emissiveTexture") != materials[i].end()) {
loadTextureInfo(asset.materials[i].emissiveTexture, materials[i]["emissiveTexture"]);
}
// emissiveFactor
if (materials[i].find("emissiveFactor") != materials[i].end()) {
if (!materials[i]["emissiveFactor"].is_array()) {
throw MisformattedExceptionNotArray("materials[i][emissiveFactor]");
}
if (materials[i]["emissiveFactor"].size() != 3) {
throw MisformattedExceptionNotGoodSizeArray("materials[i][emissiveFactor]");
}
for (uint32_t j = 0; j < 3; ++j) {
if (!materials[i]["emissiveFactor"][j].is_number()) {
throw MisformattedExceptionNotNumber("materials[i][emissiveFactor][j]");
}
asset.materials[i].emissiveFactor[j] = materials[i]["emissiveFactor"][j].get<float>();
}
}
// alphaMode
if (materials[i].find("alphaMode") != materials[i].end()) {
if (!materials[i]["alphaMode"].is_string()) {
throw MisformattedExceptionNotString("materials[i][alphaMode]");
}
std::string type = materials[i]["alphaMode"].get<std::string>();
if (type == "OPAQUE") {
asset.materials[i].alphaMode = Material::AlphaMode::Opaque;
} else if (type == "MASK") {
asset.materials[i].alphaMode = Material::AlphaMode::Mask;
} else if (type == "BLEND") {
asset.materials[i].alphaMode = Material::AlphaMode::Blend;
} else {
throw MisformattedException("materials[i][alphaMode]", "is not a valid string");
}
}
// alphaCutoff
if (materials[i].find("alphaCutoff") != materials[i].end()) {
if (!materials[i]["alphaCutoff"].is_number()) {
throw MisformattedExceptionNotNumber("materials[i][alphaCutoff]");
}
asset.materials[i].alphaCutoff = materials[i]["alphaCutoff"].get<float>();
}
// doubleSided
if (materials[i].find("doubleSided") != materials[i].end()) {
if (!materials[i]["doubleSided"].is_boolean()) {
throw MisformattedExceptionNotBoolean("materials[i][doubleSided]");
}
asset.materials[i].doubleSided = materials[i]["doubleSided"].get<bool>();
}
// TODO: materials[i]["extensions"]
// TODO: materials[i]["extras"]
}
}
static void loadTextureInfo(Material::Texture& texture, nlohmann::json& json) {
if (!json.is_object()) {
throw MisformattedExceptionNotNumber("textureInfo");
}
// index
if (json.find("index") == json.end()) {
throw MisformattedExceptionIsRequired("textureInfo[index]");
}
if (!json["index"].is_number()) {
throw MisformattedExceptionNotNumber("textureInfo[index]");
}
texture.index = json["index"].get<int32_t>();
// texCoord
if (json.find("texCoord") != json.end()) {
if (!json["texCoord"].is_number()) {
throw MisformattedExceptionNotNumber("textureInfo[texCoord]");
}
texture.texCoord = json["texCoord"].get<int32_t>();
}
// TODO: json["extensions"]
// TODO: json["extras"]
}
static void loadImages(Asset& asset, nlohmann::json& json) {
if (json.find("images") == json.end()) {
return;
}
auto& images = json["images"];
if (!images.is_array()) {
throw MisformattedExceptionNotArray("images");
}
asset.images.resize(images.size());
for (uint32_t i = 0; i < images.size(); ++i) {
// name
if (images[i].find("name") != images[i].end()) {
if (!images[i]["name"].is_string()) {
throw MisformattedExceptionNotString("images[i][name]");
}
asset.images[i].name = images[i]["name"];
}
// uri
// TODO: load base64 uri
if (images[i].find("uri") != images[i].end()) {
if (!images[i]["uri"].is_string()) {
throw MisformattedExceptionNotString("images[i][uri]");
}
asset.images[i].uri = pathAppend(asset.dirName, images[i]["uri"]);
}
// mimeType
if (images[i].find("mimeType") != images[i].end()) {
if (!images[i]["mimeType"].is_string()) {
throw MisformattedExceptionNotString("images[i][mimeType]");
}
asset.images[i].mimeType = images[i]["mimeType"];
}
// bufferView
if (images[i].find("bufferView") != images[i].end()) {
if (!images[i]["bufferView"].is_number()) {
throw MisformattedExceptionNotNumber("images[i][bufferView]");
}
asset.images[i].bufferView = images[i]["bufferView"].get<int32_t>();
}
// TODO: Handle dependencies between mimeType and bufferView
// TODO: Handle the fact that we want an uri OR a bufferView
// TODO: images[i]["extensions"]
// TODO: images[i]["extras"]
}
}
static void loadSamplers(Asset& asset, nlohmann::json& json) {
if (json.find("samplers") == json.end()) {
return;
}
auto& samplers = json["samplers"];
if (!samplers.is_array()) {
throw MisformattedExceptionNotArray("samplers");
}
asset.samplers.resize(samplers.size());
for (uint32_t i = 0; i < samplers.size(); ++i) {
// name
if (samplers[i].find("name") != samplers[i].end()) {
if (!samplers[i]["name"].is_string()) {
throw MisformattedExceptionNotString("samplers[i][name]");
}
asset.samplers[i].name = samplers[i]["name"];
}
// magFilter
if (samplers[i].find("magFilter") != samplers[i].end()) {
if (!samplers[i]["magFilter"].is_number()) {
throw MisformattedExceptionNotNumber("samplers[i][magFilter]");
}
asset.samplers[i].magFilter = static_cast<Sampler::MagFilter>(samplers[i]["magFilter"].get<uint16_t>());
}
// minFilter
if (samplers[i].find("minFilter") != samplers[i].end()) {
if (!samplers[i]["minFilter"].is_number()) {
throw MisformattedExceptionNotNumber("samplers[i][minFilter]");
}
asset.samplers[i].minFilter = static_cast<Sampler::MinFilter>(samplers[i]["minFilter"].get<uint16_t>());
}
// wrapS
if (samplers[i].find("wrapS") != samplers[i].end()) {
if (!samplers[i]["wrapS"].is_number()) {
throw MisformattedExceptionNotNumber("samplers[i][wrapS]");
}
asset.samplers[i].wrapS = static_cast<Sampler::WrappingMode>(samplers[i]["wrapS"].get<uint16_t>());
}
// wrapT
if (samplers[i].find("wrapT") != samplers[i].end()) {
if (!samplers[i]["wrapT"].is_number()) {
throw MisformattedExceptionNotNumber("samplers[i][wrapT]");
}
asset.samplers[i].wrapT = static_cast<Sampler::WrappingMode>(samplers[i]["wrapT"].get<uint16_t>());
}
// TODO: samplers[i]["extensions"]
// TODO: samplers[i]["extras"]
}
}
static void loadTextures(Asset& asset, nlohmann::json& json) {
if (json.find("textures") == json.end()) {
return;
}
auto& textures = json["textures"];
if (!textures.is_array()) {
throw MisformattedExceptionNotArray("textures");
}
asset.textures.resize(textures.size());
for (uint32_t i = 0; i < textures.size(); ++i) {
// name
if (textures[i].find("name") != textures[i].end()) {
if (!textures[i]["name"].is_string()) {
throw MisformattedExceptionNotString("textures[i][name]");
}
asset.textures[i].name = textures[i]["name"];
}
// sampler
if (textures[i].find("sampler") != textures[i].end()) {
if (!textures[i]["sampler"].is_number()) {
throw MisformattedExceptionNotNumber("textures[i][sampler]");
}
asset.textures[i].sampler = textures[i]["sampler"].get<int32_t>();
}
// source
if (textures[i].find("source") != textures[i].end()) {
if (!textures[i]["source"].is_number()) {
throw MisformattedExceptionNotNumber("textures[i][source]");
}
asset.textures[i].source = textures[i]["source"].get<int32_t>();
}
// TODO: textures[i]["extensions"]
// TODO: textures[i]["extras"]
}
}
#if defined(__ANDROID__)
Asset load(std::string fileName, AAssetManager* assetManager) {
_assetManager = assetManager;
nlohmann::json json;
{
AAsset* asset = AAssetManager_open(assetManager, fileName.c_str(), AASSET_MODE_STREAMING);
if (!asset) {
throw std::runtime_error("Can't open Android asset");
}
uint32_t size = AAsset_getLength(asset);
if (size <= 0) {
throw std::runtime_error("Android asset is empty");
}
std::string content;
content.resize(size);
AAsset_read(asset, reinterpret_cast<char*>(&content[0]), size);
AAsset_close(asset);
json = nlohmann::json::parse(content);
}
#else
Asset load(std::string fileName) {
// TODO: Check the extension (.gltf / .glb)
nlohmann::json json;
{
std::ifstream file(fileName);
if (!file.is_open()) {
throw std::runtime_error("Can't load file");
}
file >> json;
}
#endif
Asset asset{};
asset.dirName = getDirectoryName(fileName);
loadAsset(asset, json);
loadScenes(asset, json);
loadMeshes(asset, json);
loadNodes(asset, json);
loadBuffers(asset, json);
loadBufferViews(asset, json);
loadAccessors(asset, json);
loadMaterials(asset, json);
loadImages(asset, json);
loadSamplers(asset, json);
loadTextures(asset, json);
return asset;
}
} // gltf2
| Lugdunum3D/glTF2-loader |
<|start_filename|>walter/katana/WalterIn/walterUSDOpEngine.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERUSDOPENGINE_H_
#define __WALTERUSDOPENGINE_H_
#include "walterUSDOpIndex.h"
#include "walterUSDCommonUtils.h"
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/stage.h>
PXR_NAMESPACE_USING_DIRECTIVE
namespace OpUtils
{
class PrivateData;
}
/** @brief The top-level entry point for rendering USD stage. We only have one
* object per stage. And it should contain everything ralated to the stage. */
class OpEngine
{
public:
/**
* @brief Public constructor
*
* @param iArchives the list of archives.
*
* @return The engine.
*/
static OpEngine& getInstance(const std::vector<std::string>& iArchives);
/** @brief Remove all the cached OpEngine objects */
static void clearCaches();
/**
* @brief Generate a scene graph node for the specified path.
*
* @param iPrivateData The object that is generated by us for each node we
* are going to produce.
* @param ioClientData The data came from the client (Katana) that should be
* passed to the caboose. For Katana it's GeolibCookInterface.
*/
void cook(const OpUtils::PrivateData* iPrivateData, void* ioClientData);
/**
* @brief Generate Masters location of a scene graph node if instances are
* present. This function should be called once at the begining of a cook
* process for a given "root" location.
*
* @param iPrivateData The object that is generated by us for each node we
* are going to produce.
* @param ioClientData The data came from the client (Katana) that should be
* passed to the caboose. For Katana it's GeolibCookInterface.
*/
void cookMasters(
const OpUtils::PrivateData* iPrivateData,
void* ioClientData);
/**
* @brief Sets scenes parameters before cooking.
*
* @param iPrivateData The object that is generated by us for each node we
* are going to produce.
* @param ioClientData The data came from the client (Katana) that should be
* passed to the caboose. For Katana it's GeolibCookInterface.
*/
void dress(void* ioClientData);
OpIndex& index() { return mIndex; }
/**
* @brief Get the 'real' master name for the given primitive.
*
* @param iPrim The primitive for which to check an eventual related
* master primitive and it's real name before it became instanciated.
* @return The original master primitive name.
*/
std::string getMasterName(const UsdPrim& iPrim);
/**
* @brief Get the 'real' master name for the given primitive.
*
* @param iPrim The primitive for which to check an eventual related
* master primitive and it's real name before it became instanciated.
* @return The original master primitive name.
*/
std::string getKatMasterName(const UsdPrim& iMasterPrim);
/**
* @brief Returns the string enough to recreate the same engine in the
* procedural.
*/
const std::string& getIdentifier() const { return mIdentifier; }
/**
* @brief Returns the USD stage
*/
UsdStageRefPtr getUsdStage() const { return mStage; }
private:
friend class std::pair<const size_t, OpEngine>;
// We need to be sure that this object can be created only by the registry.
OpEngine(const std::vector<std::string>& iArchives);
WalterUSDCommonUtils::MasterPrimInfo getMasterPrimInfo(
const UsdPrim& iPrim);
// Material assignments and the index data to fast access.
OpIndex mIndex;
// We keep the USD stage here, so once engine is destructed, the stage will
// be automatically closed.
UsdStageRefPtr mStage;
// The string that can be used in the procedural.
std::string mIdentifier;
// Map master primitive name with the primitive name they refer.
// This is used to handle assignement on instances.
WalterUSDCommonUtils::MastersInfoMap mMastersInfoMap;
};
#endif
<|start_filename|>walter/maya/walterStandin/walterUsdUtils.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "mayaUtils.h"
#include "walterUsdUtils.h"
#include "walterUsdConversion.h"
#include "schemas/walterHdStream/lookAPI.h"
#include "schemas/walterHdStream/primvar.h"
#include "schemas/walterHdStream/shader.h"
#include "schemas/walterHdStream/uvTexture.h"
#ifdef MFB_ALT_PACKAGE_NAME
#include <maya/MAnimControl.h>
#include <maya/MFnAttribute.h>
#include <maya/MFnDagNode.h>
#include <maya/MFnMatrixData.h>
#include <maya/MGlobal.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>
#include <maya/MSelectionList.h>
#include <pxr/base/gf/matrix4d.h>
#include <pxr/base/gf/vec3f.h>
#include <pxr/base/plug/registry.h>
#include <pxr/imaging/hdx/rendererPluginRegistry.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usdGeom/mesh.h>
#include <pxr/usd/usdGeom/xformCommonAPI.h>
#include <pxr/usd/usdShade/material.h>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/regex.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/variant.hpp>
#include <chrono>
#include <unordered_set>
#include <limits>
#include "PathUtil.h"
#include "walterShapeNode.h"
#include "rdoCustomResource.h"
#include "rdoProfiling.h"
#include "schemas/expression.h"
#include "walterAssignment.h"
#include "walterShaderUtils.h"
#include "walterUSDCommonUtils.h"
PXR_NAMESPACE_USING_DIRECTIVE
using namespace WalterMaya;
typedef boost::variant<MObject, SdfPath> ShaderBoostVariant;
const static TfToken xformToken("xformOp:transform");
// Changes given character if it's not allowed in USD name.
struct ExpressionFixName
{
char operator()(char x) const { return isalnum(x) ? x : '_'; }
};
inline std::string getBoostVariantName(const ShaderBoostVariant& var)
{
switch (var.which())
{
case 0:
// Hypershade shading network
return MFnDependencyNode(boost::get<MObject>(var)).name().asChar();
case 1:
// USD shading network
return boost::get<SdfPath>(var).GetElementString();
default:
// Should never happen
return "";
}
}
std::size_t hash_value(ShaderBoostVariant const& var)
{
size_t hash = 0;
boost::hash_combine(hash, boost::hash<int>{}(var.which()));
boost::hash_combine(
hash, boost::hash<std::string>{}(getBoostVariantName(var)));
return hash;
}
UsdStageRefPtr getStage(const ShapeNode* node)
{
// Get UsdStage from the data.
return node->getStage();
}
void stdStringArrayToMStringArray(
std::vector<std::string> const& stdArray,
MStringArray& mArray)
{
for (unsigned i = 0; i < stdArray.size(); ++i)
mArray.append(stdArray[i].c_str());
}
/**
* @brief Create USD Attribute out of MPlug.
*
* @param prim UsdPrim where it's necessary to create an attribute.
* @param attrPlug The source MPlug to get the type and the data.
* @param name Name of the attribute.
* @param custom If it's necessary to put custom meta to the attribute.
*
* @return New attribute
*/
UsdAttribute createAttribute(
UsdPrim& prim,
const MPlug& attrPlug,
const TfToken& name,
bool custom)
{
const MDataHandle data = attrPlug.asMDataHandle();
UsdAttribute attr;
// Convert Maya type to USD type.
switch (data.numericType())
{
case MFnNumericData::kInvalid:
{
int v;
if (data.type() == MFnData::kString)
{
// It's a string.
attr = prim.CreateAttribute(
name, SdfValueTypeNames->String, custom);
std::string str = data.asString().asChar();
attr.Set(str);
}
else if (attrPlug.getValue(v) == MS::kSuccess)
{
// This plug doesn't have data. But we can try to get an int.
attr =
prim.CreateAttribute(name, SdfValueTypeNames->Int, custom);
attr.Set(v);
}
break;
}
case MFnNumericData::kBoolean:
{
// This plug doesn't have data. But we can try to get an int.
attr = prim.CreateAttribute(name, SdfValueTypeNames->Bool, custom);
attr.Set(data.asBool());
break;
}
case MFnNumericData::kShort:
case MFnNumericData::kLong:
{
attr = prim.CreateAttribute(name, SdfValueTypeNames->Int, custom);
attr.Set(data.asInt());
break;
}
case MFnNumericData::kFloat:
{
attr = prim.CreateAttribute(name, SdfValueTypeNames->Float, custom);
attr.Set(data.asFloat());
break;
}
case MFnNumericData::kDouble:
{
// Float anyway
attr = prim.CreateAttribute(name, SdfValueTypeNames->Float, custom);
attr.Set(static_cast<float>(data.asDouble()));
break;
}
case MFnNumericData::k3Float:
{
// TODO: Point, Vector etc...
attr =
prim.CreateAttribute(name, SdfValueTypeNames->Color3f, custom);
const float3& color = data.asFloat3();
const GfVec3f vec(color[0], color[1], color[2]);
attr.Set(vec);
break;
}
}
return attr;
}
/**
* @brief Convert Maya object to USD object. ATM only walterOverride is
* supported.
*
* @param stage UsdStage where it's necessary to create the shader.
* @param obj Maya object to convert.
* @param parentPath Path of the parent object.
*
* @return Path of created objects.
*/
SdfPath saveConnectedShader(
UsdStageRefPtr stage,
MObject obj,
const SdfPath& parentPath)
{
const MFnDependencyNode depNode(obj);
std::string shaderName = depNode.name().asChar();
if (depNode.typeName() == "walterOverride")
{
// TODO: Skip if already created.
SdfPath attributesPath = parentPath.AppendChild(TfToken(shaderName));
UsdShadeMaterial attributesSchema =
UsdShadeMaterial::Define(stage, attributesPath);
UsdPrim attributesPrim = attributesSchema.GetPrim();
// Iterate the attribures of the walterOverride node.
unsigned int nAttributes = depNode.attributeCount();
for (unsigned int a = 0; a < nAttributes; a++)
{
MObject object = depNode.attribute(a);
MFnAttribute attr(object);
// Set good name. Remove the prefix and convert it.
// "walterSubdivType" -> "subdiv_type"
bool isUserData = false;
std::string name =
attributeNameDemangle(attr.name().asChar(), &isUserData);
if (name.empty())
{
continue;
}
// "arnold:attribute:" is hardcoded now because we don't have
// another options.
MPlug attrPlug = depNode.findPlug(object);
createAttribute(
attributesPrim,
attrPlug,
TfToken("arnold:attribute:" + name),
isUserData);
}
return attributesPath;
}
return SdfPath(shaderName);
}
/**
* @brief Save one single connection to the stage.
*
* @param stage UsdStage where it's necessary to create the shaders and
* expressions.
*
* @param expression "/*"
* @param renderLayer "defaultRenderLayer"
* @param renderTarget "attribute", "displacement", "shader"
* @param shaderPlug Maya connection
*/
void saveConnection(
UsdStageRefPtr stage,
const std::string& expression,
const std::string& renderLayer,
const std::string& renderTarget,
const MPlug& shaderPlug)
{
MPlugArray connections;
if (!shaderPlug.connectedTo(connections, true, false) ||
!connections.length())
{
return;
}
const MObject connectedNode(connections[0].node());
// TODO: MTOA outputs displacement nodes like this:
// MayaNormalDisplacement
// {
// name displacementShader1.message
// }
//
// We need to investigate why. But now we have a spacial case.
// USD doesn't allow to use special characters as names. We need to mangle
// them.
// TODO: consider the name intersections.
std::string nodeName = expression;
if (!SdfPath::IsValidIdentifier(nodeName))
{
std::transform(
nodeName.begin(),
nodeName.end(),
nodeName.begin(),
ExpressionFixName());
}
// We need to put everything to the materials node.
SdfPath materialsPath = SdfPath("/materials");
// Current object path.
SdfPath expressionPath =
materialsPath.AppendChild(TfToken(nodeName));
// Create the expression node.
auto expressionPrim =
stage->DefinePrim(expressionPath, TfToken("Expression"));
// TODO: Some check or assert.
WalterExpression expressionSchema(expressionPrim);
// Set expression
// RND-555: Demangle the expression to convert special regex characters
// We have to do this because USD converts by it-self backslash to slash
// and breaks regex expressions...
expressionSchema.SetExpression(
WalterCommon::convertRegex(expression));
// Set connection with the Material.
SdfPath connectedToPath =
saveConnectedShader(stage, connectedNode, materialsPath);
expressionSchema.SetConnection(renderLayer, renderTarget, connectedToPath);
}
// The description is in the header.
std::string constructUSDSessionLayer(MObject obj)
{
// Maya node
MFnDagNode dagNode(obj);
UsdStageRefPtr sceneStage =
getStage(dynamic_cast<ShapeNode*>(dagNode.userNode()));
if (!sceneStage)
{
return {};
}
// If we don't need assignments, we are done. Return what we have.
std::string session;
sceneStage->GetSessionLayer()->ExportToString(&session);
return session;
}
std::string getVariantsLayerAsText(MObject obj)
{
// Maya node
MFnDagNode dagNode(obj);
UsdStageRefPtr sceneStage =
getStage(dynamic_cast<ShapeNode*>(dagNode.userNode()));
if (!sceneStage)
{
return {};
}
return WalterUSDCommonUtils::getVariantsLayerAsText(sceneStage);
}
std::string getPurposeLayerAsText(MObject obj)
{
// Maya node
MFnDagNode dagNode(obj);
UsdStageRefPtr sceneStage =
getStage(dynamic_cast<ShapeNode*>(dagNode.userNode()));
if (!sceneStage)
{
return {};
}
return WalterUSDCommonUtils::getPurposeLayerAsText(sceneStage);
}
std::string getVisibilityLayerAsText(MObject obj)
{
// Maya node
MFnDagNode dagNode(obj);
UsdStageRefPtr sceneStage =
getStage(dynamic_cast<ShapeNode*>(dagNode.userNode()));
if (!sceneStage)
{
return {};
}
return WalterUSDCommonUtils::getVisibilityLayerAsText(sceneStage);
}
void setUSDVisibilityLayer(MObject obj, const std::string& visibility)
{
// Maya node
MFnDagNode dagNode(obj);
// Get USD stuff from the node.
UsdStageRefPtr sceneStage =
getStage(dynamic_cast<ShapeNode*>(dagNode.userNode()));
if (!sceneStage)
{
return;
}
if(!WalterUSDCommonUtils::setUSDVisibilityLayer(
sceneStage, visibility.c_str()))
{
MGlobal::displayError(
"[Walter USD] Cant't set the visibility layer to the object " +
dagNode.name());
}
}
// The description is in the header.
void setUSDSessionLayer(MObject obj, const std::string& session)
{
// Maya node
MFnDagNode dagNode(obj);
// Get USD stuff from the node.
UsdStageRefPtr sceneStage =
getStage(dynamic_cast<ShapeNode*>(dagNode.userNode()));
if (!sceneStage)
{
// It happens when opening a Maya scene. CachedGeometry is not created
// yet. But it's OK because we will use this layer when creating
// CacheFileEntry.
return;
}
if (session.empty())
{
sceneStage->GetSessionLayer()->Clear();
}
else if (!sceneStage->GetSessionLayer()->ImportFromString(session))
{
MGlobal::displayError(
"[Walter USD] Cant't set the session layer to the object " +
dagNode.name());
sceneStage->GetSessionLayer()->Clear();
}
}
void setUSDVariantsLayer(MObject obj, const std::string& variants)
{
// Maya node
MFnDagNode dagNode(obj);
// Get USD stuff from the node.
UsdStageRefPtr sceneStage =
getStage(dynamic_cast<ShapeNode*>(dagNode.userNode()));
if (!sceneStage)
{
// It happens when opening a Maya scene. CachedGeometry is not created
// yet. But it's OK because we will use this layer when creating
// CacheFileEntry.
return;
}
if(!WalterUSDCommonUtils::setUSDVariantsLayer(
sceneStage, variants.c_str()))
{
MGlobal::displayError(
"[Walter USD] Cant't set the variants layer to the object " +
dagNode.name());
}
}
void setUSDPurposeLayer(MObject obj, const std::string& variants)
{
// Maya node
MFnDagNode dagNode(obj);
// Get USD stuff from the node.
UsdStageRefPtr sceneStage =
getStage(dynamic_cast<ShapeNode*>(dagNode.userNode()));
if (!sceneStage)
{
// It happens when opening a Maya scene. CachedGeometry is not created
// yet. But it's OK because we will use this layer when creating
// CacheFileEntry.
return;
}
if(!WalterUSDCommonUtils::setUSDPurposeLayer(
sceneStage, variants.c_str()))
{
MGlobal::displayError(
"[Walter USD] Cant't set the variants layer to the object " +
dagNode.name());
}
}
bool getUSDTransform(
MObject obj,
const std::string& object,
double time,
double matrix[4][4])
{
// Maya node
MFnDagNode dagNode(obj);
// Get USD stuff from the node.
UsdStageRefPtr stage =
getStage(dynamic_cast<ShapeNode*>(dagNode.userNode()));
if (!stage)
{
return false;
}
UsdPrim prim = stage->GetPrimAtPath(SdfPath(object));
if (!prim)
{
std::string message("[Walter USD] Cant't get the tranform of prim ");
message += object;
MGlobal::displayError(message.c_str());
return false;
}
GfMatrix4d gfMatrix;
bool resetsXformStack;
UsdGeomXformable(prim).GetLocalTransformation(
&gfMatrix, &resetsXformStack, time);
gfMatrix.Get(matrix);
return true;
}
bool dirUSD(
const ShapeNode* node,
const MString& subNodeName,
MStringArray& result)
{
// Get USD stuff from the node.
UsdStageRefPtr stage = getStage(node);
if (!stage)
{
return false;
}
std::vector<std::string> result_ = WalterUSDCommonUtils::dirUSD(
stage, subNodeName.asChar());
stdStringArrayToMStringArray(result_, result);
return true;
}
bool propertiesUSD(
const ShapeNode* node,
const MString& subNodeName,
MStringArray& result,
bool attributeOnly)
{
// Get USD stuff from the node.
UsdStageRefPtr stage = getStage(node);
if (!stage)
{
return false;
}
std::vector<std::string> result_ = WalterUSDCommonUtils::propertiesUSD(
stage, subNodeName.asChar(), node->time, attributeOnly);
stdStringArrayToMStringArray(result_, result);
return true;
}
bool getVariantsUSD(
const ShapeNode* node,
const MString& subNodeName,
bool recursively,
MStringArray& result)
{
// Get USD stuff from the node.
UsdStageRefPtr stage = getStage(node);
if (!stage)
{
return false;
}
std::vector<std::string> result_ =
WalterUSDCommonUtils::getVariantsUSD(
stage,
subNodeName.asChar(),
recursively);
stdStringArrayToMStringArray(result_, result);
return true;
}
bool setVariantUSD(
ShapeNode* node,
const MString& subNodeName,
const MString& variantName,
const MString& variantSetName)
{
// Get USD stuff from the node.
UsdStageRefPtr stage = getStage(node);
if (!stage)
{
return false;
}
SdfLayerRefPtr variantLayer =
WalterUSDCommonUtils::getAnonymousLayer(stage, "variantLayer");
stage->SetEditTarget(variantLayer);
WalterUSDCommonUtils::setVariantUSD(stage, subNodeName.asChar(),
variantName.asChar(), variantSetName.asChar());
node->refresh();
return true;
}
bool assignedOverridesUSD(
const ShapeNode* node,
const MString& subNodeName,
MStringArray& result)
{
// Get USD stuff from the node.
UsdStageRefPtr stage = getStage(node);
if (!stage)
{
return false;
}
UsdTimeCode tc(node->time);
const SdfPath* primitivePath = WalterCommon::resolveAssignment<SdfPath>(
subNodeName.asChar(), node->getAssignedOverrides());
if (!primitivePath)
{
return {};
}
UsdPrim walterOverride = stage->GetPrimAtPath(*primitivePath);
std::vector<std::string> overrideDescription;
for (const auto& attr : walterOverride.GetAttributes())
{
int arraySize = -1;
std::string type, value;
WalterUsdConversion::getAttributeValueAsString(
attr, tc, type, value, arraySize);
std::string description =
WalterUsdConversion::constuctStringRepresentation(
attr.GetBaseName().GetText(),
"Override",
type,
value,
arraySize);
result.append(description.c_str());
}
return true;
}
bool primVarUSD(
const ShapeNode* node,
const MString& subNodeName,
MStringArray& result)
{
// Get USD stuff from the node.
UsdStageRefPtr stage = getStage(node);
if (!stage)
{
return false;
}
std::vector<std::string> result_ = WalterUSDCommonUtils::primVarUSD(
stage, subNodeName.asChar(), node->time);
stdStringArrayToMStringArray(result_, result);
return true;
}
inline UsdTimeCode getUSDTimeFromMayaTime(
const WalterMaya::ShapeNode* shapeNode) {
const MPlug timePlug =
MFnDependencyNode(shapeNode->thisMObject()).findPlug(ShapeNode::aTime);
double time;
if (!timePlug.isConnected())
{
time = MAnimControl::currentTime().value();
shapeNode->time = time / getCurrentFPS();
}
else
{
time = shapeNode->time * getCurrentFPS();
}
return UsdTimeCode(time);
}
void resetUSDTransforms(
const WalterMaya::ShapeNode* shapeNode,
const MString& subNodeName) {
// Get USD stuff from the node.
UsdStageRefPtr stage = getStage(shapeNode);
if (!stage)
return;
UsdPrim prim = shapeNode->getStage()->GetPrimAtPath(
SdfPath(subNodeName.asChar()));
UsdTimeCode currentFrame = getUSDTimeFromMayaTime(
shapeNode);
UsdAttribute xform = prim.GetAttribute(xformToken);
GfMatrix4d current;
xform.Get(¤t, currentFrame);
xform.Clear();
xform.Set(current, currentFrame);
}
bool updateUSDTransforms(
const ShapeNode* shapeNode,
const std::unordered_map<std::string, MMatrix>& matrices)
{
RDOPROFILE("");
#ifdef PERFORM_PROFILING
using namespace std;
using ChronoClock = chrono::high_resolution_clock;
using ChronoMS = chrono::microseconds;
unsigned int objectDuration = 0;
unsigned int attributeDuration = 0;
ChronoClock::time_point startTime = ChronoClock::now();
#endif
// Get USD stuff from the node.
UsdStageRefPtr stage = getStage(shapeNode);
if (!stage)
{
return false;
}
UsdTimeCode currentFrame = getUSDTimeFromMayaTime(
shapeNode);
// Put all the edits to the session layer.
stage->SetEditTarget(stage->GetSessionLayer());
for (const auto& object : matrices)
{
#ifdef PERFORM_PROFILING
ChronoClock::time_point objectTime = ChronoClock::now();
#endif
const std::string subObjectName = object.first;
const MMatrix& subObjectTransform = object.second;
UsdPrim prim = stage->GetPrimAtPath(SdfPath(subObjectName));
if (!prim)
{
continue;
}
// Don't set the transform of a prim pseudo-root.
// It's not supported by USD and leads to a SEGFAULT
if(prim.IsPseudoRoot())
{
MString msg = "[walter] Cannot set the transform of the USD pseudo-root: '";
msg += prim.GetPath().GetText();
msg += "'";
MGlobal::displayWarning(msg);
continue;
}
// The actual matrix.
double buffer[4][4];
subObjectTransform.get(buffer);
GfMatrix4d matrix(buffer);
// It's a bottleneck. MakeMatrixXform is extremely slow because it
// removes all the transformation attributes and creates a new one. We
// can check if the new one is created and use it directly.
UsdAttribute xform = prim.GetAttribute(xformToken);
if (xform.HasValue())
{
#ifdef PERFORM_PROFILING
ChronoClock::time_point attributeTime = ChronoClock::now();
#endif
GfMatrix4d old;
xform.Get(&old, currentFrame);
if (old != matrix)
{
// TODO: try to set attributes in multiple threads because Set
// is also a bottleneck.
xform.Set(matrix, currentFrame);
}
#ifdef PERFORM_PROFILING
ChronoClock::time_point finishTime = ChronoClock::now();
attributeDuration +=
chrono::duration_cast<ChronoMS>(finishTime - attributeTime)
.count();
#endif
}
else
{
UsdGeomXformable xf(prim);
UsdGeomXformOp xfOp = xf.MakeMatrixXform();
xfOp.Set(matrix, currentFrame);
}
#ifdef PERFORM_PROFILING
ChronoClock::time_point finishTime = ChronoClock::now();
objectDuration +=
chrono::duration_cast<ChronoMS>(finishTime - objectTime).count();
#endif
}
#ifdef PERFORM_PROFILING
ChronoClock::time_point finishTime = ChronoClock::now();
unsigned int totalDuration =
chrono::duration_cast<ChronoMS>(finishTime - startTime).count();
printf(
"[WALTER]: profiling of updateUSDTransforms: total:%ims "
"UsdPrim:%.02f%% "
"UsdAttribute::Set:%.02f%%\n",
totalDuration / 1000,
float(objectDuration - attributeDuration) * 100 / totalDuration,
float(attributeDuration) * 100 / totalDuration);
#endif
return true;
}
bool saveUSDTransforms(
const MString& objectName,
const MString& fileName,
const MTime& start,
const MTime& end,
const MTime& step,
bool resetSessionLayer)
{
RDOPROFILE("");
if (step.value() == 0.0)
{
MString msg;
msg.format(
"[walter] Step time for ^1s is 0. Seems it's an infinite loop.",
objectName);
MGlobal::displayError(msg);
return false;
}
// Looking for MFnDependencyNode object in the scene.
MSelectionList selectionList;
selectionList.add(objectName);
MObject obj;
selectionList.getDependNode(0, obj);
MFnDependencyNode depNode(obj);
ShapeNode* shapeNode = dynamic_cast<ShapeNode*>(depNode.userNode());
if(resetSessionLayer)
{
setUSDSessionLayer(obj, "");
shapeNode->setCachedFramesDirty();
}
const MPlug time = depNode.findPlug(ShapeNode::aTime);
// Evaluate the requested frames.
for (MTime t = start; t <= end; t += step)
{
MAnimControl::setCurrentTime(t);
// Evaluate the time graph. It should execute
// ShapeNode::setInternalValueInContext and save the dirty transforms.
time.asMTime();
// RND-647: Unfortunately if the node is not connected to time
// we need to force onTimeChanged.
MFnDependencyNode depNode(shapeNode->thisMObject());
const MPlug timePlug = depNode.findPlug(ShapeNode::aTime);
if(!timePlug.isConnected())
{
shapeNode->onTimeChanged(std::numeric_limits<float>::min());
}
// Save the transforms to the USD stage.
shapeNode->updateUSDStage();
}
UsdStageRefPtr stage = getStage(shapeNode);
if (!stage->GetSessionLayer()->Export(fileName.asChar()))
{
MString msg;
msg.format(
"[walter] Can't write USD ^1s. See the terminal for the details.",
fileName);
MGlobal::displayError(msg);
return false;
}
return true;
}
/**
* @brief Gets Perform value resolution to fetch the value of this attribute at
* the default time or at first available sample if the attribute is sampled.
*
* @param attr Attribute to resolve.
* @param value Value to write.
* @param time The default time.
*
* @return true if there was a value to be read.
*/
template <typename T>
bool usdAttributeGet(
const UsdAttribute attr,
T* value,
UsdTimeCode time = UsdTimeCode::Default())
{
std::vector<double> times;
if (attr.GetTimeSamples(×) && !times.empty())
{
time = times[0];
}
return attr.Get(value, time);
}
void mergeUSDObject(
UsdStageRefPtr sceneStage,
const UsdPrim& parent,
const std::vector<UsdPrim>& prims)
{
if (prims.empty())
{
return;
}
std::vector<UsdPrimRange> allPrims;
allPrims.reserve(prims.size());
for (const UsdPrim& prim : prims)
{
allPrims.push_back(UsdPrimRange::AllPrims(prim));
}
// Get total number of prims.
int numPrims = 0;
for (const auto& range : allPrims)
{
for (const auto& prim : range)
{
numPrims++;
}
}
if (numPrims <= 1)
{
return;
}
// Read the mesh data for all the prims
std::vector<VtArray<int>> faceVertexCounts(numPrims);
std::vector<VtArray<int>> faceVertexIndices(numPrims);
std::vector<VtArray<GfVec3f>> points(numPrims);
std::vector<GfMatrix4d> transforms(numPrims);
int counter = 0;
// TODO: Multithreaded
for (const auto& range : allPrims)
{
for (const auto& prim : range)
{
if (prim.IsA<UsdGeomMesh>())
{
UsdGeomMesh mesh(prim);
UsdAttribute countsAttr = mesh.GetFaceVertexCountsAttr();
UsdAttribute indicesAttr = mesh.GetFaceVertexIndicesAttr();
UsdAttribute pointsAttr = mesh.GetPointsAttr();
if (countsAttr && indicesAttr && indicesAttr)
{
usdAttributeGet(countsAttr, &(faceVertexCounts[counter]));
usdAttributeGet(indicesAttr, &(faceVertexIndices[counter]));
usdAttributeGet(pointsAttr, &(points[counter]));
// TODO: Time
transforms[counter] =
mesh.ComputeLocalToWorldTransform(1.0);
}
}
counter++;
}
}
// Get the inverse transformation of the parent.
GfMatrix4d parentInvTransform;
// Set the purpose of this object.
if (parent.IsA<UsdGeomImageable>())
{
UsdGeomImageable imageable(parent);
// TODO: Time
parentInvTransform = imageable.ComputeLocalToWorldTransform(1.0);
parentInvTransform = parentInvTransform.GetInverse();
}
else
{
parentInvTransform.SetIdentity();
}
// Compute the total amount of data
int faceVertexCountsSize = 0;
int faceVertexIndicesSize = 0;
int pointsSize = 0;
for (const auto& a : faceVertexCounts)
{
faceVertexCountsSize += a.size();
}
for (const auto& a : faceVertexIndices)
{
faceVertexIndicesSize += a.size();
}
for (const auto& a : points)
{
pointsSize += a.size();
}
// Initialize arrays.
VtArray<int> newObjectCounts(faceVertexCountsSize);
VtArray<int> newObjectIndices(faceVertexIndicesSize);
VtArray<GfVec3f> newObjectPoints(pointsSize);
// Merge everything together.
int countsOffset = 0;
int indicesOffset = 0;
int pointsOffset = 0;
// TODO: Multithreaded
for (int i = 0; i < numPrims; i++)
{
// Nothing to do with vertex counts, so we can batch copy them.
std::copy(
faceVertexCounts[i].begin(),
faceVertexCounts[i].end(),
newObjectCounts.begin() + countsOffset);
countsOffset += faceVertexCounts[i].size();
// We need to increase the point offset to each index.
int faceVertexIndicesCurrentSize = faceVertexIndices[i].size();
for (int j = 0; j < faceVertexIndicesCurrentSize; j++)
{
newObjectIndices[indicesOffset + j] =
faceVertexIndices[i][j] + pointsOffset;
}
indicesOffset += faceVertexIndicesCurrentSize;
// Relative transformation of the current object.
const GfMatrix4d& currentTransform = transforms[i] * parentInvTransform;
// We need to transform each point.
int pointsCurrentSize = points[i].size();
for (int j = 0; j < pointsCurrentSize; j++)
{
const GfVec3f& p3f = points[i][j];
// To multiply point (not vector) by matrix we need 4 component
// vector and the latest component should be 1.0.
GfVec4f p4f(p3f[0], p3f[1], p3f[2], 1.0f);
p4f = p4f * currentTransform;
// Back to 3 components.
newObjectPoints[pointsOffset + j] = GfVec3f(p4f[0], p4f[1], p4f[2]);
}
pointsOffset += pointsCurrentSize;
}
// Set render purpose to all the children.
for (const UsdPrim& prim : prims)
{
#if 1
// Set this object as inactive. It's MUCH faster, it's revercable, but
// the object becames not iterable.
prim.SetActive(false);
#else
// Set the render purpose for this object.
if (!prim.IsA<UsdGeomImageable>())
{
continue;
}
UsdGeomImageable imageable(prim);
UsdAttribute purposeAttr = imageable.CreatePurposeAttr();
purposeAttr.Set(UsdGeomTokens->render);
#endif
}
// Generate the name of the new mesh.
SdfPath path = parent.GetPath();
path = path.AppendChild(TfToken(path.GetName() + "ProxyShape"));
// Create the new mesh.
UsdGeomMesh mesh = UsdGeomMesh::Define(sceneStage, path);
UsdAttribute faceVertexCountsAttr = mesh.CreateFaceVertexCountsAttr();
UsdAttribute faceVertexIndicesAttr = mesh.CreateFaceVertexIndicesAttr();
UsdAttribute pointsAttr = mesh.CreatePointsAttr();
UsdAttribute purposeAttr = mesh.CreatePurposeAttr();
UsdAttribute doubleSidedAttr = mesh.CreateDoubleSidedAttr();
faceVertexCountsAttr.Set(newObjectCounts);
faceVertexIndicesAttr.Set(newObjectIndices);
pointsAttr.Set(newObjectPoints);
purposeAttr.Set(UsdGeomTokens->proxy);
doubleSidedAttr.Set(true);
}
bool freezeUSDTransforms(const WalterMaya::ShapeNode* userNode)
{
RDOPROFILE("");
UsdStageRefPtr sceneStage = getStage(userNode);
if (!sceneStage)
{
// It happens when opening a Maya scene. CachedGeometry is not created
// yet. But it's OK because we will use this layer when creating
// CacheFileEntry.
return false;
}
MObject node = userNode->thisMObject();
// Get all the objects with connected transforms and their parents.
SdfPathSet allPaths;
const MPlug transformsPlug(node, ShapeNode::aTransforms);
assert(!transformsPlug.isNull());
for (int i = 0, n = transformsPlug.numElements(); i < n; i++)
{
const MPlug element = transformsPlug.elementByPhysicalIndex(i);
const MPlug objectPlug = element.child(ShapeNode::aTransformsObject);
const MPlug matrixPlug = element.child(ShapeNode::aTransformsMatrix);
// Skip if there is no connection and if there is no name.
const MString currentSubObjectName = objectPlug.asString();
if (currentSubObjectName.length() == 0 || !matrixPlug.isConnected())
{
continue;
}
// Get and save all the parents.
SdfPath path(currentSubObjectName.asChar());
while (path != SdfPath::AbsoluteRootPath() &&
allPaths.find(path) == allPaths.end())
{
allPaths.insert(path);
path = path.GetParentPath();
}
}
// Looking for the proxy layer.
SdfLayerRefPtr renderProxyLayer =
WalterUSDCommonUtils::getAnonymousLayer(sceneStage, "renderProxyLayer");
renderProxyLayer->Clear();
// Put all the edits to this layer.
sceneStage->SetEditTarget(renderProxyLayer);
// Merge the children of saved objects.
for (const SdfPath& path : allPaths)
{
UsdPrim prim = sceneStage->GetPrimAtPath(path);
if (!prim)
{
// We are here because the stage doesn't have the requested object.
continue;
}
std::vector<UsdPrim> children;
for (const UsdPrim& c : prim.GetChildren())
{
if (allPaths.find(c.GetPath()) != allPaths.end())
{
// We don't need to merge the object if it's in the list because
// we need to keep ability to set the transform of this object.
continue;
}
children.push_back(c);
}
mergeUSDObject(sceneStage, prim, children);
}
return true;
}
bool unfreezeUSDTransforms(const WalterMaya::ShapeNode* userNode)
{
RDOPROFILE("");
UsdStageRefPtr sceneStage = getStage(userNode);
if (!sceneStage)
{
// It happens when opening a Maya scene. CachedGeometry is not created
// yet. But it's OK because we will use this layer when creating
// CacheFileEntry.
return false;
}
// When we get it we clear it.
SdfLayerRefPtr renderProxyLayer =
WalterUSDCommonUtils::getAnonymousLayer(sceneStage, "renderProxyLayer");
renderProxyLayer->Clear();
return true;
}
/**
* @brief Generate the glsl shader and register it in rdoCustomResource. For now
* it's just a simple template that depends on the shader name only.
*
* @param name The name of the shader
* @param UDIMs All the UDIM textures
*/
void publishGLSLShader(
std::string name,
const std::map<int, std::string>& UDIMs)
{
// We need this structure to keep the shaders because rdoCustomResource
// keeps only pointers.
static std::unordered_map<std::string, std::string> sGLSLShaders;
std::string shader =
"-- glslfx version 0.1\n"
"#import $TOOLS/glf/shaders/simpleLighting.glslfx\n"
"-- configuration\n"
"{\n"
" \"techniques\": {\n"
" \"default\": {\n"
" \"surfaceShader\": {\n";
shader += " \"source\": [ \"" + name + ".Surface\" ]\n";
shader +=
" }\n"
" }\n"
" }\n"
"}\n";
shader += "-- glsl " + name + ".Surface\n";
shader +=
"// This shader is also used for selection. There are no lights in\n"
"// selection mode, and the shader fails to compile if there is\n"
"// lighting code.\n"
"#ifndef NUM_LIGHTS\n"
"#define NUM_LIGHTS 0\n"
"#endif\n"
"vec4 surfaceShader(vec4 Peye, vec3 Neye, vec4 color, vec4 "
"patchCoord)\n"
"{\n"
"#if NUM_LIGHTS == 0\n"
" return color;\n"
"#else\n"
// TODO: For some unknown reason GLSL can have HD_HAS_uv but not
// HdGet_uv. Investigate this.
"#if defined(HD_HAS_uv)\n"
" vec2 uv = HdGet_uv();\n"
"#else\n"
" vec2 uv = vec2(0.0, 0.0);\n"
"#endif\n";
if (UDIMs.empty())
{
// Pre-initialize
shader += " vec3 texture = HdGet_diffuse();\n";
}
else
{
// Pre-initialization is not necessary
shader += " vec3 texture;\n";
}
bool first = true;
for (const auto& it : UDIMs)
{
std::string udimID;
int udim = it.first - 1;
if (udim > 0)
{
int u = udim % 10;
int v = udim / 10 % 10;
std::string conditionUV;
conditionUV += "uv[0] >= " + std::to_string(u) + ".0 && ";
conditionUV += "uv[0] < " + std::to_string(u + 1) + ".0 && ";
conditionUV += "uv[1] >= " + std::to_string(v) + ".0 && ";
conditionUV += "uv[1] < " + std::to_string(v + 1) + ".0";
udimID = std::to_string(it.first);
const std::string condition = first ? "if" : "else if";
shader += " " + condition + " (" + conditionUV + ")\n";
first = false;
}
shader += " {\n";
shader += " texture = HdGet_diffuse" + udimID + "();\n";
shader += " }\n";
}
shader +=
" return simpleLighting(color, Peye, Neye, vec4(texture, 1.0));\n"
"#endif\n"
"}\n";
setResource(std::string(name + ".glslfx").c_str(), shader.c_str());
sGLSLShaders[name] = shader;
}
/**
* @brief Returns value of specified attribute of the Maya object.
*
* @param iSceneStage The USD stage. We don't use it, it's for overloading.
* @param iShaderNode Thw walterOverride object.
* @param iAttribute The name of the custom attribute.
*/
std::string getStringValue(
const UsdStageRefPtr,
const MObject& iShaderNode,
const std::string& iAttribute)
{
const MFnDependencyNode depNode(iShaderNode);
MString attributeName = MString("walter_") + iAttribute.c_str();
const MPlug plug = depNode.findPlug(attributeName);
return plug.asString().asChar();
}
/**
* @brief Returns value of specified attribute of the prim.
*
* @param iSceneStage The USD stage.
* @param iPath The USD path to the walter override object in the stage.
* @param iAttribute The name of the attribute.
*/
std::string getStringValue(
const UsdStageRefPtr iSceneStage,
const SdfPath iPath,
const std::string& iAttribute)
{
const UsdPrim prim = iSceneStage->GetPrimAtPath(iPath);
if (prim.IsA<UsdShadeMaterial>())
{
for (const UsdAttribute attr : prim.GetAttributes())
{
const SdfValueTypeName attrTypeName = attr.GetTypeName();
if (attrTypeName != SdfValueTypeNames->String)
{
continue;
}
const std::string attrName = attr.GetName();
std::vector<std::string> splittedName;
boost::split(splittedName, attrName, boost::is_any_of(":"));
if (splittedName.back() != iAttribute)
{
continue;
}
std::string value;
attr.Get(&value);
return value;
}
}
return {};
}
/**
* @brief Returns value of specified attribute of the ShaderBoostVariant.
*
* @param iSceneStage The USD stage.
* @param iAttributeBoostVariant The object to get value from.
* @param iAttribute The name of the attribute.
*/
std::string getStringValue(
const UsdStageRefPtr iSceneStage,
const ShaderBoostVariant* iAttributeBoostVariant,
const std::string& iAttribute)
{
if (!iAttributeBoostVariant)
{
return {};
}
if (iAttributeBoostVariant->which() == 0)
{
// It's a Maya shader.
const MObject& shaderNode =
boost::get<MObject>(*iAttributeBoostVariant);
return getStringValue(iSceneStage, shaderNode, iAttribute);
}
else if (iAttributeBoostVariant->which() == 1)
{
// It's a shader in the USD stage.
const SdfPath& attributesPath =
boost::get<SdfPath>(*iAttributeBoostVariant);
return getStringValue(iSceneStage, attributesPath, iAttribute);
}
}
/**
* @brief Parse the given file path and resolve some tokens. It returns list of
* udim files or one sinle file.
*
* @param filePath The given path.
* @param iSceneStage The USD stage.
* @param iAttributeBoostVariant The walterOverride that applied to the current
* object.
* @param ioTokens The list of the attribute tokens used in the sahder. If this
* kind of the shader is being processed the first time, the list is empty and
* it's necessary to fill it. If this kind of the shader is being processed
* second time, the list is pre-filled with correct values.
* @param oUDIMs UDIM id to filenmae map. If the given file is not UDIM, then
* the map will have only one file with index 0.
*/
void parseTextureFilePath(
std::string filePath,
const UsdStageRefPtr iSceneStage,
const ShaderBoostVariant* iAttributeBoostVariant,
std::map<std::string, std::string>& ioTokens,
std::map<int, std::string>& oUDIMs,
bool logErrorIfTokenNotFound)
{
// Preloaded constants
static const std::string udim("udim");
static const std::string attr("attr:");
bool needToRecomputeTokens = ioTokens.empty();
// Get all the tokens. It's a set because the token can be specified twice.
std::unordered_set<std::string> tokens;
size_t foundOpen = 0;
while (true)
{
foundOpen = filePath.find('<', foundOpen);
if (foundOpen == std::string::npos)
{
break;
}
size_t foundClose = filePath.find('>', foundOpen);
if (foundClose == std::string::npos)
{
break;
}
tokens.insert(
filePath.substr(foundOpen + 1, foundClose - foundOpen - 1));
foundOpen = foundClose;
}
// This will be true if the given file has UDIMs.
bool needUDIMs = false;
// Resolve the tokens.
std::unordered_map<std::string, const std::string> values;
for (const std::string& token : tokens)
{
if (boost::starts_with(token, attr))
{
std::string attributeName = token.substr(attr.length());
if (needToRecomputeTokens)
{
std::string value = getStringValue(
iSceneStage, iAttributeBoostVariant, attributeName);
// Save it for future.
ioTokens.emplace(attributeName, value);
if (!value.empty())
{
values.emplace("<" + token + ">", value);
}
else if( logErrorIfTokenNotFound )
{
TF_CODING_ERROR(
"Can't get attr token '%s' in the texture '%s'.",
token.c_str(),
filePath.c_str());
}
}
else
{
auto it = ioTokens.find(attributeName);
if (it != ioTokens.end())
{
values.emplace("<" + token + ">", it->second);
}
else
{
TF_CODING_ERROR(
"Can't find attr token '%s' in the texture '%s'.",
token.c_str(),
filePath.c_str());
}
}
}
else if (boost::algorithm::to_lower_copy(token) == udim)
{
// We have UDIMs
needUDIMs = true;
}
else
{
TF_CODING_ERROR(
"Can't resolve token '%s' in the texture.", token.c_str());
}
}
for (const auto& it : values)
{
boost::replace_all(filePath, it.first, it.second);
}
if (!needUDIMs)
{
// We are done. No UDIMs.
oUDIMs[0] = filePath;
return;
}
// Get all the UDIMs with scanning the filesystem. It can be slow.
// Regex file filter. test<udim>.exr -> test[0-9][0-9][0-9][0-9].exr
const boost::regex filter(boost::ireplace_all_copy(
filePath, "<" + udim + ">", "[0-9][0-9][0-9][0-9]"));
// Get the position of the <udim> token to generate the UDIM ID from the
// filename.
foundOpen =
boost::algorithm::ifind_first(filePath, "<" + udim + ">").begin() -
filePath.begin();
// Directory to look
const boost::filesystem::path directory =
boost::filesystem::path(filePath).parent_path();
if (!boost::filesystem::exists(directory))
{
// No directory. No need to scan it.
return;
}
// TODO: limit number of textures, or add a warning message if the number of
// textures is more than glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max)
// Default ctor yields past-the-end
const boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator i(directory); i != end_itr; ++i)
{
// Skip if not a file
if (!boost::filesystem::is_regular_file(i->status()))
{
continue;
}
const std::string fileName = i->path().native();
// Skip if it's not UDIM
if (!boost::regex_match(fileName, filter))
{
continue;
}
oUDIMs[std::stoi(fileName.substr(foundOpen, 4))] = fileName;
}
}
/**
* @brief Create the USD shading network for the viewport and GLSL shader, so it
* can be rendered with Hydra.
*
* @param iShaderObj MObject that reproduces the maya shader or UsdShadeShader
* that reproduces USD shader.
* @param iAttributeBoostVariant The walterOverride that applied to the current
* object.
* @param iSceneStage The stage where the shader should be saved.
* @param iDagNode The current walterStandin node.
* @param ioTokens The list of the attribute tokens used in the sahder. If this
* kind of the shader is being processed the first time, the list is empty and
* it's necessary to fill it. If this kind of the shader is being processed
* second time, the list is pre-filled with correct values.
*
* @return The created material.
*/
template <class T>
UsdShadeMaterial produceGLSLShader(
const T& iShaderObj,
const ShaderBoostVariant* iAttributeBoostVariant,
const std::string& iShaderName,
UsdStageRefPtr iSceneStage,
const MFnDagNode& iDagNode,
std::map<std::string, std::string>& ioTokens,
bool logErrorIfTokenNotFound)
{
RDOPROFILE("");
// UUID will be added to the name of the shader. Hydra caches everything by
// name, and at this point, we would like to be sure that Hydra really
// recompiled this shader. Adding UUID to the end of the name is not the
// best way. It's better to find a way to force the Hydra refresh shader.
// But it works well at the moment.
static boost::uuids::random_generator generator;
std::string uuid = boost::uuids::to_string(generator());
std::replace(uuid.begin(), uuid.end(), '-', '_');
// Root path for all the materials.
static const SdfPath viewportPath("/materials/viewport");
// Path to the viewport material
const std::string shaderName = iShaderName + "_" + uuid;
const SdfPath viewportMaterialPath =
viewportPath.AppendChild(TfToken(shaderName));
// Get the shader info.
std::string textureFilePath;
GfVec3f color(1.0f, 1.0f, 1.0f);
walterShaderUtils::getTextureAndColor(iShaderObj, textureFilePath, color);
std::map<int, std::string> UDIMs;
if (!textureFilePath.empty())
{
parseTextureFilePath(
textureFilePath,
iSceneStage,
iAttributeBoostVariant,
ioTokens,
UDIMs,
logErrorIfTokenNotFound);
}
publishGLSLShader(shaderName, UDIMs);
// Hydra stuff. We need to create a shading network like this:
// def Material "siSurface" {
// rel displayLook:bxdf = </siSurface/Shader>
// }
UsdShadeMaterial material =
UsdShadeMaterial::Define(iSceneStage, viewportMaterialPath);
WalterHdStreamLookAPI look(material);
// def Shader "TestShader" {
// uniform asset info:filename = @shader.glslfx@
//
// float3 diffuse = (1.0, 1.0, 1.0)
// rel connectedSourceFor:diffuse = </Test/Texture.outputs:color>
//
// float2 uv = (0.0, 0.0)
// rel connectedSourceFor:uv = </Test/Primvar.outputs:result>
// }
SdfPath shaderPath = viewportMaterialPath.AppendChild(TfToken("Shader"));
WalterHdStreamShader shader(
UsdShadeShader::Define(iSceneStage, shaderPath).GetPrim());
shader.CreateFilenameAttr().Set(SdfAssetPath(shaderName + ".glslfx"));
UsdAttribute uv = shader.GetPrim().CreateAttribute(
TfToken("uv"), SdfValueTypeNames->Float2, false, SdfVariabilityVarying);
uv.Set(GfVec2f(0.0f, 0.0f));
if (UDIMs.empty())
{
// Just a diffuse parameter
UsdAttribute diffuse = shader.GetPrim().CreateAttribute(
TfToken("diffuse"),
SdfValueTypeNames->Float3,
false,
SdfVariabilityVarying);
diffuse.Set(color);
}
else
{
// Create a node with primvar.
// def Shader "Primvar" {
// uniform token info:id = "HwPrimvar_1"
// uniform token info:varname = "uv"
// float2 outputs:result
// }
SdfPath primvarPath =
viewportMaterialPath.AppendChild(TfToken("Primvar"));
WalterHdStreamPrimvar primvar(
UsdShadeShader::Define(iSceneStage, primvarPath).GetPrim());
primvar.CreateIdAttr().Set(UsdHydraTokens->HwPrimvar_1);
primvar.CreateVarnameAttr().Set(TfToken("uv"));
UsdShadeOutput primvarOutput(primvar.GetPrim().CreateAttribute(
TfToken(UsdShadeTokens->outputs.GetString() + "result"),
SdfValueTypeNames->Float2,
false,
SdfVariabilityVarying));
// Connect Primvar.outputs:result -> Shader.uv
UsdShadeInput(uv).ConnectToSource(primvarOutput);
// Textures
for (const auto& it : UDIMs)
{
std::string udimID;
if (it.first > 0)
{
udimID = std::to_string(it.first);
}
// Convert file.
// TODO: multithreaded.
const std::string textureFilePath =
walterShaderUtils::cacheTexture(it.second);
UsdAttribute diffuse = shader.GetPrim().CreateAttribute(
TfToken("diffuse" + udimID),
SdfValueTypeNames->Float3,
false,
SdfVariabilityVarying);
diffuse.Set(color);
// Create a node with texture.
// def Shader "Texture1001" {
// float2 uv
// rel connectedSourceFor:uv = </Test/UvPrimvar.outputs:result>
// uniform asset info:filename = @lenna.png@
// uniform token info:id = "HwUvTexture_1"
// color3f outputs:color
// uniform float textureMemory = 10000000
// }
SdfPath texturePath =
viewportMaterialPath.AppendChild(TfToken("Texture" + udimID));
WalterHdStreamUvTexture texture(
UsdShadeShader::Define(iSceneStage, texturePath).GetPrim());
texture.CreateIdAttr().Set(UsdHydraTokens->HwUvTexture_1);
texture.CreateTextureMemoryAttr().Set(0.01f);
texture.CreateFilenameAttr().Set(SdfAssetPath(textureFilePath));
UsdShadeOutput textureOutput(texture.GetPrim().CreateAttribute(
TfToken(UsdShadeTokens->outputs.GetString() + "color"),
SdfValueTypeNames->Float3,
false,
SdfVariabilityVarying));
// Connect Texture.outputs:color -> Shader.diffuse
UsdShadeInput(diffuse).ConnectToSource(textureOutput);
// Connect Primvar.outputs:result -> Texture.uv
UsdShadeInput(texture.CreateUvAttr())
.ConnectToSource(primvarOutput);
}
}
// rel displayLook:bxdf = </siSurface/Shader>
look.CreateBxdfRel().SetTargets({shaderPath});
return material;
}
/**
* @brief Fills oAssignments with all the recognized assignments of the stage.
*
* @param sceneStage The USD stage to read the material assignments.
* @param type "shader", "displacement" or "attribute".
* @param oAssignments Sub-node name (or expression) to surface shader path map.
*/
void getUSDAssignments(
UsdStageRefPtr sceneStage,
const std::string& type,
std::map<WalterCommon::Expression, ShaderBoostVariant>& oAssignments)
{
for (const UsdPrim& prim : sceneStage->Traverse())
{
if (!prim.IsA<WalterExpression>())
{
// WalterExpression is the only way to connect materials at the
// moment.
continue;
}
// Get expressions.
WalterExpression expression(prim);
std::string expressionText = expression.GetExpression();
// {"defaultRenderLayer": {"shader": materialPath}}
WalterExpression::AssignmentLayers layers = expression.GetLayers();
auto layerIt = layers.find("defaultRenderLayer");
if (layerIt == layers.end())
{
continue;
}
auto targetIt = layerIt->second.find(type);
if (targetIt == layerIt->second.end())
{
continue;
}
// The expression in USD is mangled.
// TODO: see RendererIndex::insertExpression to make it correctly.
expressionText= WalterCommon::demangleString(
WalterCommon::convertRegex(expressionText));
const SdfPath& materialPath = targetIt->second;
if (type == "attribute")
{
// If we are looking for an attribute, we are done. Otherwise we
// need to get a shader from the material.
oAssignments.emplace(
std::piecewise_construct,
std::forward_as_tuple(expressionText),
std::forward_as_tuple(materialPath));
continue;
}
UsdPrim materialPrim = sceneStage->GetPrimAtPath(materialPath);
if (!materialPrim || !materialPrim.IsA<UsdShadeMaterial>())
{
continue;
}
// Iterate the connections.
for (const UsdAttribute& attr : materialPrim.GetAttributes())
{
// The name is "arnold:surface"
const std::string name = attr.GetName();
std::vector<std::string> splitted;
boost::split(splitted, name, boost::is_any_of(":"));
if (splitted.size() < 2)
{
continue;
}
// Extract the render and the target.
std::string render = splitted[0];
std::string target = splitted[1];
// TODO: other renders?
if (render != "arnold" || target != "surface")
{
continue;
}
// Get the connection.
UsdShadeShader connectedShader =
walterShaderUtils::getConnectedScheme<UsdShadeShader>(attr);
if (!connectedShader)
{
// No connection.
continue;
}
oAssignments.emplace(
std::piecewise_construct,
std::forward_as_tuple(expressionText),
std::forward_as_tuple(connectedShader.GetPrim().GetPath()));
break;
}
}
}
/**
* @brief Fills oAssignments with all the recognized assignments of both
* walterStandin Maya node and USD Stage.
*
* @param iObject The walterStandin object to read the assignments.
* @param iSceneStage The USD stage to read the assignments.
* @param iType "attribute", "displacement", "shader"
* @param oAssignments Sub-node name (or expression) to ShaderBoostVariant map.
* ShaderBoostVariant can have eather SdfPath or MObject.
*/
void getAssignments(
const MObject& iObject,
UsdStageRefPtr iSceneStage,
const std::string& iType,
std::map<WalterCommon::Expression, ShaderBoostVariant>& oAssignments)
{
// Sub object (expression) to shader map. Contains all the expressions from
// both Maya and USD stage.
assert(oAssignments.empty());
// Sub object to Maya shader map. All the shader connections from Maya.
// Strong should be first because we use emplace everywhere.
getShaderAssignments(iObject, iType, oAssignments);
// Sub object (expression) to surface shader path map. All the expressions
// from the USD stage.
getUSDAssignments(iSceneStage, iType, oAssignments);
}
/**
* @brief Queries ShaderBoostVariant (which is eather SdfPath or MObject) and
* returns a map with requested attrTokens and values.
*
* @param iSceneStage The USD stage to read the assignments.
* @param iAttrTokens The list of attr tokens to query.
* @param iAttributeBoostVariant The object to get values from.
*
* @return The map with requested attrTokens and values.
*/
std::map<std::string, std::string> queryAttrTokens(
const UsdStageRefPtr iSceneStage,
const std::unordered_set<std::string>& iAttrTokens,
const ShaderBoostVariant* iAttributeBoostVariant)
{
std::map<std::string, std::string> map;
for (const std::string& attrToken : iAttrTokens)
{
map[attrToken] =
getStringValue(iSceneStage, iAttributeBoostVariant, attrToken);
}
return map;
}
// The description is in the header.
void processGLSLShaders(
const ShapeNode* userNode,
bool logErrorIfTokenNotFound)
{
RDOPROFILE("");
UsdStageRefPtr sceneStage = getStage(userNode);
if (!sceneStage)
{
// It happens when opening a Maya scene.
return;
}
// Maya node
MObject obj = userNode->thisMObject();
MFnDagNode dagNode(obj);
// Looking for the proxy layer.
SdfLayerRefPtr viewportShaderLayer =
WalterUSDCommonUtils::getAnonymousLayer(
sceneStage, "viewportShaderLayer");
// We need to recreate it to upate Hydra.
// TODO: it's super ugly, we need another way to update Hydra.
viewportShaderLayer->Clear();
// Put all the edits to this layer.
sceneStage->SetEditTarget(viewportShaderLayer);
// Sub object (expression) to shader map. Contains all the expressions from
// both Maya and USD stage.
std::map<WalterCommon::Expression, ShaderBoostVariant> shaderAssignments;
getAssignments(obj, sceneStage, "shader", shaderAssignments);
std::map<WalterCommon::Expression, ShaderBoostVariant> attributeAssignments;
getAssignments(obj, sceneStage, "attribute", attributeAssignments);
// Sub oblect to shader hash map. All the shader connections of USD. We use
// it as a cache to determine if the shader is already applied to the
// object.
std::unordered_map<std::string, size_t> assignmentsCache;
// Shader name to the list of the attribute tokens used in the sahder. We
// fill it when we output the shader the first time.
std::unordered_map<std::string, std::unordered_set<std::string>> tokenCache;
// Shader hash to material map.
std::map<size_t, UsdShadeMaterial> materialCache;
// We keep saved queries of walterOverride to avoid query the same requests.
// size_t is a hash of the walterOverride name and the shader name. We need
// ordered map in a second template to have the same hash.
std::map<size_t, std::map<std::string, std::string>> queriedTokensCache;
for (const UsdPrim& prim : sceneStage->Traverse())
{
if (!prim.IsA<UsdGeomImageable>())
{
continue;
}
SdfPath path = prim.GetPath();
std::string pathStr = path.GetString();
// Resolve the expression and get the current material. Reversed because
// the procedural historically sorts and reverses all the expressions.
// Since assignments is std::map, it's already sorted.
// boost::adaptors::reverse wraps an existing range to provide a new
// range whose iterators behave as if they were wrapped in
// reverse_iterator.
const ShaderBoostVariant* shaderBoostVariant =
WalterCommon::resolveAssignment<ShaderBoostVariant>(
pathStr, shaderAssignments);
if (!shaderBoostVariant)
{
// If there is no shader, nothing to do.
continue;
}
const ShaderBoostVariant* attributeBoostVariant =
WalterCommon::resolveAssignment<ShaderBoostVariant>(
pathStr, attributeAssignments);
std::string shaderName = getBoostVariantName(*shaderBoostVariant);
if (shaderName.empty())
{
continue;
}
// Trying to find the list of attribute tokens for the shader name.
auto attrTokenIt = tokenCache.find(shaderName);
// True if the list with attribute tokens existed. It means we already
// output the shader at least once. And we can compute the full hash
// without outputting it again.
bool attrTokenExisted = attrTokenIt != tokenCache.end();
// Get existed attribute tokens or create a new one.
std::unordered_set<std::string>& attrTokens =
attrTokenExisted ? attrTokenIt->second : tokenCache[shaderName];
// Get hash from name.
size_t shaderHash = std::hash<std::string>{}(shaderName);
// Hash of name and all the resolved tokens. It's not complete here.
// It's necessary to combine it with tokens before using.
size_t shaderAndAttrTokensHash = shaderHash;
// Hash from walterOverride object name.
size_t walterOverrideObjectHash;
if (attributeBoostVariant)
{
walterOverrideObjectHash =
boost::hash<const ShaderBoostVariant*>{}(attributeBoostVariant);
}
else
{
walterOverrideObjectHash = 0;
}
// We need to combine it with shader because we need to keep unique
// requests and different shaders need different tokens.
boost::hash_combine(walterOverrideObjectHash, shaderHash);
// We don't query walterOverride if we did it before.
auto queriedTokensIt =
queriedTokensCache.find(walterOverrideObjectHash);
if (queriedTokensIt == queriedTokensCache.end())
{
// If there are no tokens, queryAttrTokens will return an empty map.
auto result = queriedTokensCache.emplace(
walterOverrideObjectHash,
queryAttrTokens(sceneStage, attrTokens, attributeBoostVariant));
queriedTokensIt = result.first;
}
// We need ordered map to have the same hash.
std::map<std::string, std::string>& tokens = queriedTokensIt->second;
// Compute hash of the requested attribute tokens for current material
// and walterOverride. If there are no tokens, the hash should be 0.
size_t tokenHash = boost::hash_range(tokens.begin(), tokens.end());
UsdShadeMaterial material;
if (attrTokenExisted)
{
// We are here because we already produced this shader. So we need
// to decide if we need another one. We would need another one if
// the tokens of the shader is now different.
boost::hash_combine(shaderAndAttrTokensHash, tokenHash);
// Save that the current object has this shader. We will skip the
// children material if she shader will be the same.
assignmentsCache[pathStr] = shaderAndAttrTokensHash;
// Check if the parent has the same shader with the same tokens.
auto it = assignmentsCache.find(path.GetParentPath().GetString());
if (it != assignmentsCache.end() &&
it->second == shaderAndAttrTokensHash)
{
// Skip if the parent has the same shader assigned.
continue;
}
// Check if we already have the same shader with the same tokens.
auto matIt = materialCache.find(shaderAndAttrTokensHash);
if (matIt != materialCache.end())
{
material = matIt->second;
}
}
if (!material)
{
// We are here because we never produce this shder or if we produced
// it with different tokens.
// It's not switch/case because of break and continue in a loop.
if (shaderBoostVariant->which() == 0)
{
// It's a Maya shader.
const MObject& shaderNode =
boost::get<MObject>(*shaderBoostVariant);
if (shaderNode.isNull())
{
continue;
}
material = produceGLSLShader(
shaderNode,
attributeBoostVariant,
shaderName,
sceneStage,
dagNode,
tokens,
logErrorIfTokenNotFound);
}
else if (shaderBoostVariant->which() == 1)
{
// It's a shader in the USD stage.
const SdfPath shaderPath =
boost::get<SdfPath>(*shaderBoostVariant);
if (shaderPath.IsEmpty())
{
continue;
}
UsdShadeShader shader =
UsdShadeShader::Get(sceneStage, shaderPath);
// We checked it before
assert(shader);
material = produceGLSLShader(
shader,
attributeBoostVariant,
shaderName,
sceneStage,
dagNode,
tokens,
logErrorIfTokenNotFound);
}
if (!material)
{
// No material. There is nothing to bind.
continue;
}
if (!attrTokenExisted)
{
// We are here because we never produced this shader before. But
// we just did it right now and we have all the data to cache
// it.
// Save attrTokens for future.
for (const auto& a : tokens)
{
attrTokens.insert(a.first);
}
// Re-compute hash of the requested attribute tokens.
tokenHash = boost::hash_range(tokens.begin(), tokens.end());
// Combine it with the name. So we now have the full shader
// hash.
boost::hash_combine(shaderAndAttrTokensHash, tokenHash);
// Save that the current object has this shader. We will skip
// the children material if she shader will be the same.
assignmentsCache[pathStr] = shaderAndAttrTokensHash;
}
}
// Save material for future.
materialCache[shaderAndAttrTokensHash] = material;
// Connect the newly created material to the current object.
material.Bind(const_cast<UsdPrim&>(prim));
}
}
// The description is in the header.
void muteGLSLShaders(const ShapeNode* userNode, bool iSetVisible)
{
RDOPROFILE("");
UsdStageRefPtr sceneStage = getStage(userNode);
if (!sceneStage)
{
// It happens when opening a Maya scene.
return;
}
// Maya node
MObject obj = userNode->thisMObject();
MFnDagNode dagNode(obj);
// Looking for the proxy layer.
SdfLayerRefPtr viewportShaderLayer =
WalterUSDCommonUtils::getAnonymousLayer(
sceneStage, "viewportShaderLayer");
// USD destroys anonymous layer when calling UsdStage::MuteLayer. To avoid
// it, it's necessary to keep it somethere. We use vector because if we mute
// the layer twice and unmute once, we still need to protect this layer from
// destroying.
static std::vector<SdfLayerRefPtr> sMutedLayersCache;
if (iSetVisible)
{
sceneStage->UnmuteLayer(viewportShaderLayer->GetIdentifier());
auto it = std::find(
sMutedLayersCache.begin(),
sMutedLayersCache.end(),
viewportShaderLayer);
if (it != sMutedLayersCache.end())
{
sMutedLayersCache.erase(it);
}
}
else
{
sceneStage->MuteLayer(viewportShaderLayer->GetIdentifier());
sMutedLayersCache.push_back(viewportShaderLayer);
}
}
MString getLayerAsString(
const WalterMaya::ShapeNode* userNode,
const MString& layerName)
{
UsdStageRefPtr sceneStage = getStage(userNode);
if (!sceneStage)
{
// It happens when opening a Maya scene.
return {};
}
std::string layerStr;
if (layerName.length() == 0)
{
sceneStage->Flatten()->ExportToString(&layerStr);
}
else if (layerName == "session")
{
sceneStage->GetSessionLayer()->ExportToString(&layerStr);
}
else
{
SdfLayerRefPtr requestedLayer = WalterUSDCommonUtils::getAnonymousLayer(
sceneStage, layerName.asChar());
requestedLayer->ExportToString(&layerStr);
}
return layerStr.c_str();
}
// The description is in the header.
std::string getMayaStateAsUSDLayer(MObject obj)
{
// Regular expression looks like this:
// def Expression "_pSphere1_pSphereShape1"
// {
// rel assign:defaultRenderLayer:shader = </materials/aiStandard1>
// string expression = "\\pSphere1\\pSphereShape1"
// }
// Trying to get the USD stage from the Maya object.
UsdStageRefPtr stage;
// Maya node
MFnDagNode dagNode(obj);
// If the stage is not available, just create a new one.
stage = UsdStage::CreateInMemory();
const MPlug layersAssignation = dagNode.findPlug("layersAssignation");
if (layersAssignation.isNull())
{
MGlobal::displayWarning(
"[Walter USD Utils] Can't find " + dagNode.name() +
".layersAssignation.");
return {};
}
for (unsigned int i = 0, n = layersAssignation.numElements(); i < n; i++)
{
// Get walterStandin.layersAssignation[i]
const MPlug currentLayerCompound =
layersAssignation.elementByPhysicalIndex(i);
// Get walterStandin.layersAssignation[i].layer
MPlug layerPlug;
if (!GetChildMPlug(currentLayerCompound, "layer", layerPlug))
{
continue;
}
MPlugArray connections;
if (!layerPlug.connectedTo(connections, true, false) ||
!connections.length())
{
continue;
}
// The layer is the first connected node. We consider we have only one
// connection.
const MFnDependencyNode layer(connections[0].node());
const std::string layerName = layer.name().asChar();
// Get walterStandin.layersAssignation[i].shaderConnections
MPlug shadersPlug;
if (!GetChildMPlug(
currentLayerCompound, "shaderConnections", shadersPlug))
{
continue;
}
for (unsigned j = 0, m = shadersPlug.numElements(); j < m; j++)
{
// Get walterStandin.layersAssignation[i].shaderConnections[j]
const MPlug shadersCompound = shadersPlug.elementByPhysicalIndex(j);
// Get walterStandin.layersAssignation[].shaderConnections[].abcnode
MPlug abcnodePlug;
if (!GetChildMPlug(shadersCompound, "abcnode", abcnodePlug))
{
continue;
}
// It's an expression. "/pSphere1/pTorus1/pTorusShape1" or "/*".
const MString abcnode = abcnodePlug.asString().asChar();
if (!abcnode.length())
{
continue;
}
// Get walterStandin.layersAssignation[].shaderConnections[].shader
MPlug shaderPlug;
if (GetChildMPlug(shadersCompound, "shader", shaderPlug))
{
// Put it to USD.
saveConnection(
stage, abcnode.asChar(), layerName, "shader", shaderPlug);
}
// The same for displacement
MPlug dispPlug;
if (GetChildMPlug(shadersCompound, "displacement", dispPlug))
{
// Put it to USD.
saveConnection(
stage,
abcnode.asChar(),
layerName,
"displacement",
dispPlug);
}
// The same for attributes
MPlug attrPlug;
if (GetChildMPlug(shadersCompound, "attribute", attrPlug))
{
// Put it to USD.
saveConnection(
stage, abcnode.asChar(), layerName, "attribute", attrPlug);
}
}
}
// Compose everything together and get the string.
std::string session;
stage->Flatten()->ExportToString(&session);
return session;
}
bool extractAssignments(ShapeNode* iUserNode)
{
assert(iUserNode);
ShapeNode::ExpMap& assignments = iUserNode->getAssignments();
ShapeNode::ExpGroup& groups = iUserNode->getGroups();
MStringArray& embeddedShaders = iUserNode->getEmbeddedShaders();
ShapeNode::AssignedOverrides& assignedOverrides =
iUserNode->getAssignedOverrides();
assignments.clear();
groups.clear();
embeddedShaders.clear();
assignedOverrides.clear();
UsdStageRefPtr sceneStage = getStage(iUserNode);
if (!sceneStage)
{
// It happens when opening a Maya scene.
return false;
}
// Get all the expressions.
for (const UsdPrim& prim : sceneStage->Traverse())
{
if (prim.IsA<WalterExpression>())
{
// Get expressions.
WalterExpression expression(prim);
// USD uses \ as a separator. We use /. We need convert it.
std::string expressionText = WalterCommon::demangleString(
WalterCommon::convertRegex(expression.GetExpression()));
WalterExpression::AssignmentLayers layers = expression.GetLayers();
// Convert AssignmentLayers to CacheFileEntry::ExpMapPtr.
// AssignmentLayers is data of this format:
// {string "layer": {string "target": SdfPath "shader"}}
for (auto layer : layers)
{
for (auto target : layer.second)
{
ShapeNode::LayerKey layerkey(layer.first, target.first);
assignments[expressionText][layerkey] =
target.second.GetText();
}
}
auto foundLayer = layers.find("defaultRenderLayer");
if (foundLayer != layers.end())
{
SdfPath walterOverridePath = foundLayer->second["attribute"];
if (!walterOverridePath.IsEmpty())
{
assignedOverrides.emplace(
std::piecewise_construct,
std::forward_as_tuple(expressionText),
std::forward_as_tuple(walterOverridePath));
}
}
std::string group;
UsdAttribute groupAttr = expression.GetGroupAttr();
if (groupAttr)
{
groupAttr.Get(&group);
}
// We need to set it even if the expression doesn't have a group so
// we can get the list of expressions very fast.
groups[expressionText] = group;
}
else if (prim.IsA<UsdShadeMaterial>())
{
// Material.
embeddedShaders.append(prim.GetPath().GetText());
}
}
return true;
}
void getHydraPlugins(MStringArray& result)
{
HfPluginDescVector pluginDescriptors;
HdxRendererPluginRegistry::GetInstance().GetPluginDescs(&pluginDescriptors);
const PlugRegistry& registry = PlugRegistry::GetInstance();
for (const HfPluginDesc& pluginDescriptor : pluginDescriptors)
{
result.append(pluginDescriptor.id.GetText());
result.append(pluginDescriptor.displayName.c_str());
}
}
bool isPseudoRoot(
const ShapeNode* node,
const MString& subNodeName)
{
UsdStageRefPtr stage = getStage(node);
if (!stage)
return false;
return WalterUSDCommonUtils::isPseudoRoot(
stage, subNodeName.asChar());
}
bool isVisible(
const ShapeNode* node,
const MString& subNodeName)
{
UsdStageRefPtr stage = getStage(node);
if (!stage)
return false;
return WalterUSDCommonUtils::isVisible(
stage, subNodeName.asChar());
}
bool toggleVisibility(
const ShapeNode* node,
const MString& subNodeName)
{
UsdStageRefPtr stage = getStage(node);
if (!stage)
return false;
SdfLayerRefPtr visibilityLayer =
WalterUSDCommonUtils::getAnonymousLayer(stage, "visibilityLayer");
stage->SetEditTarget(visibilityLayer);
return WalterUSDCommonUtils::toggleVisibility(
stage, subNodeName.asChar());
}
bool setVisibility(
const ShapeNode* node,
const MString& subNodeName,
bool visible)
{
UsdStageRefPtr stage = getStage(node);
if (!stage)
return false;
SdfLayerRefPtr visibilityLayer =
WalterUSDCommonUtils::getAnonymousLayer(stage, "visibilityLayer");
stage->SetEditTarget(visibilityLayer);
return WalterUSDCommonUtils::setVisibility(
stage, subNodeName.asChar(), visible);
}
bool hideAllExceptedThis(
const ShapeNode* node,
const MString& subNodeName)
{
UsdStageRefPtr stage = getStage(node);
if (!stage)
return false;
SdfLayerRefPtr visibilityLayer =
WalterUSDCommonUtils::getAnonymousLayer(stage, "visibilityLayer");
stage->SetEditTarget(visibilityLayer);
return WalterUSDCommonUtils::hideAllExceptedThis(
stage, subNodeName.asChar());
}
MStringArray primPathsMatchingExpression(
const ShapeNode* node,
const MString& expression)
{
MStringArray res;
UsdStageRefPtr stage = getStage(node);
if (!stage)
return res;
std::vector<std::string> primPaths =
WalterUSDCommonUtils::primPathsMatchingExpression(
stage, expression.asChar());
for(auto path: primPaths)
res.append(path.c_str());
return res;
}
MString setPurpose(
ShapeNode* node,
const MString& subNodeName,
const MString& purpose)
{
UsdStageRefPtr stage = getStage(node);
if (!stage)
return "default";
SdfLayerRefPtr purposeLayer =
WalterUSDCommonUtils::getAnonymousLayer(stage, "purposeLayer");
stage->SetEditTarget(purposeLayer);
MString purposeName = WalterUSDCommonUtils::setPurpose(
stage, subNodeName.asChar(), purpose.asChar()).c_str();
// Re-construct the render-engine, Pixar Hydra bug
node->refresh();
return purposeName;
}
MString getPurpose(
const ShapeNode* node,
const MString& subNodeName)
{
UsdStageRefPtr stage = getStage(node);
if (!stage)
return "default";
return WalterUSDCommonUtils::purpose(
stage, subNodeName.asChar()).c_str();
}
void setRenderPurpose(
ShapeNode* node,
const MStringArray& purposeArray)
{
node->mParams.showRender = false;
node->mParams.showProxy = false;
node->mParams.showGuides = false;
for(uint32_t i=0; i<purposeArray.length(); i++) {
if(purposeArray[i].asChar() == std::string("render"))
node->mParams.showRender = true;
if(purposeArray[i].asChar() == std::string("proxy"))
node->mParams.showProxy = true;
if(purposeArray[i].asChar() == std::string("guide"))
node->mParams.showGuides = true;
}
// Re-construct the render-engine, Pixar Hydra bug
node->refresh();
}
MStringArray getRenderPurpose(
const ShapeNode* node)
{
MStringArray purposeArray;
if(node->mParams.showRender)
purposeArray.append("render");
if(node->mParams.showProxy)
purposeArray.append("proxy");
if(node->mParams.showGuides)
purposeArray.append("guide");
return purposeArray;
}
bool savePurposes(
const MString& objectName,
const MString& fileName) {
// Looking for MFnDependencyNode object in the scene.
MSelectionList selectionList;
selectionList.add(objectName);
MObject obj;
selectionList.getDependNode(0, obj);
MFnDependencyNode depNode(obj);
ShapeNode* shapeNode = dynamic_cast<ShapeNode*>(depNode.userNode());
UsdStageRefPtr stage = getStage(shapeNode);
SdfLayerRefPtr purposeLayer =
WalterUSDCommonUtils::getAnonymousLayer(stage, "purposeLayer");
if (!purposeLayer->Export(fileName.asChar()))
{
MString msg;
msg.format(
"[walter] Can't write USD ^1s. See the terminal for the details.",
fileName);
MGlobal::displayError(msg);
return false;
}
return true;
}
bool saveVariantsLayer(
const MString& objectName,
const MString& fileName) {
// Looking for MFnDependencyNode object in the scene.
MSelectionList selectionList;
selectionList.add(objectName);
MObject obj;
selectionList.getDependNode(0, obj);
MFnDependencyNode depNode(obj);
ShapeNode* shapeNode = dynamic_cast<ShapeNode*>(depNode.userNode());
UsdStageRefPtr stage = getStage(shapeNode);
SdfLayerRefPtr variantLayer =
WalterUSDCommonUtils::getAnonymousLayer(stage, "variantLayer");
if (!variantLayer->Export(fileName.asChar()))
{
MString msg;
msg.format(
"[walter] Can't write USD ^1s. See the terminal for the details.",
fileName);
MGlobal::displayError(msg);
return false;
}
return true;
}
#endif // MFB_ALT_PACKAGE_NAME
<|start_filename|>walter/arnold/procedural/engine.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __ENGINE_H__
#define __ENGINE_H__
#include <pxr/usd/sdf/path.h>
#include <string>
#include "delegate.h"
#include "index.h"
#include "plugin.h"
PXR_NAMESPACE_USING_DIRECTIVE
// The top-level entry point for rendering USD stage. We have one object per
// stage.
class RendererEngine
{
public:
// Public constructor.
static RendererEngine* getInstance(
const std::string& fileName,
const std::vector<std::string>& layers);
// Remove all the cached RendererEngine objects.
static void clearCaches();
// Number of nodes that is generated by the specified path.
int getNumNodes(const SdfPath& path, const std::vector<float>& times);
// Generate a render node for the specified path.
void* render(
const SdfPath& path,
int id,
const std::vector<float>& times,
const void* userData);
private:
friend class std::pair<const std::string, RendererEngine>;
// We need to be sure that this object can be created only by registry.
RendererEngine(
const std::string& fileName,
const std::vector<std::string>& layers);
// Prepare index.
void prepare(const UsdPrim& root);
RendererPlugin mPlugin;
RendererIndex mIndex;
RendererDelegate mDelegate;
UsdStageRefPtr mStage;
};
#endif
<|start_filename|>walter/maya/walterStandin/walterShapeNode.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef _walterShapeNode_h_
#define _walterShapeNode_h_
#include <maya/MMessage.h>
#include <maya/MPxSurfaceShape.h>
#include <maya/MPxSurfaceShapeUI.h>
#include <maya/MStringArray.h>
#include <pxr/usdImaging/usdImagingGL/gl.h>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/unordered_map.hpp>
#include <set>
#include <vector>
#include <maya/MNodeMessage.h>
#include "PathUtil.h"
// Bool is defined in /usr/include/X11/Intrinsic.h, it conflicts with USD.
#ifdef Bool
#undef Bool
#endif
#include <pxr/usd/usd/stage.h>
PXR_NAMESPACE_USING_DIRECTIVE
namespace WalterMaya {
/** @brief Keeps track of animated shapes held in a memory cache. */
class ShapeNode : public MPxSurfaceShape
{
public:
// Building following structure:
// {"object", {("layer", "target"): "shader"}}
typedef std::pair<std::string, std::string> LayerKey;
typedef std::map<LayerKey, std::string> LayerMap;
typedef std::map<std::string, LayerMap> ExpMap;
// First is the expression, second is the group.
typedef std::map<std::string, std::string> ExpGroup;
typedef std::map<WalterCommon::Expression, SdfPath> AssignedOverrides;
static void* creator();
static MStatus initialize();
static MStatus uninitialize();
static const MTypeId id;
static const MString drawDbClassificationGeometry;
static const MString drawRegistrantId;
static MObject aCacheFileName;
static MObject aTime;
static MObject aTimeOffset;
static MObject aBBmode;
// layersAssignation compound
static MObject aLayersAssignation;
static MObject aLayersAssignationLayer;
static MObject aLayersAssignationSC;
static MObject aLayersAssignationSCNode;
static MObject aLayersAssignationSCShader;
static MObject aLayersAssignationSCDisplacement;
static MObject aLayersAssignationSCAttribute;
// expressions compound
static MObject aExpressions;
static MObject aExpressionsName;
static MObject aExpressionsGroupName;
static MObject aExpressionsWeight;
static MObject aVisibilities;
static MObject aRenderables;
static MObject aAlembicShaders;
static MObject aEmbeddedShaders;
// The name of the procedural to render with Arnold.
static MObject aArnoldProcedural;
// Read-only attribute with USD session layer as a text.
static MObject aUSDSessionLayer;
// Read-only attribute with USD variants layer as a text.
static MObject aUSDVariantLayer;
// Read-only attribute with USD purposes layer as a text.
static MObject aUSDPurposeLayer;
// Read-only attribute with USD session layer as a text.
static MObject aUSDMayaStateLayer;
// Read-only attribute with USD visibility layer as a text.
static MObject aUSDVisibilityLayer;
// Transform compound
static MObject aTransforms;
static MObject aTransformsObject;
static MObject aTransformsMatrix;
static MObject aHydraPlugin;
static MObject aFrozen;
static const char* nodeTypeName;
static const char* selectionMaskName;
mutable double time;
mutable bool fReadScene;
mutable bool fReadMaterials;
mutable bool fLoadGeo;
mutable bool fBBmode;
mutable bool bTriggerGeoReload;
mutable bool fSceneLoaded;
mutable bool fFrozen;
enum CacheReadingState {
kCacheReadingFile,
kCacheReadingDone
};
ShapeNode();
~ShapeNode();
virtual void postConstructor();
virtual bool isBounded() const;
virtual MBoundingBox boundingBox() const;
// When internal attribute values are queried via getAttr or MPlug::getValue
// this method is called.
virtual bool getInternalValueInContext(const MPlug& plug,
MDataHandle& dataHandle, MDGContext& ctx);
// This method is used by Maya to determine the count of array elements.
virtual int internalArrayCount(
const MPlug& plug, const MDGContext& ctx) const;
virtual bool setInternalValueInContext(const MPlug& plug,
const MDataHandle& dataHandle, MDGContext& ctx);
virtual void copyInternalData(MPxNode* source);
virtual MStringArray getFilesToArchive( bool shortName = false,
bool unresolvedName = false,
bool markCouldBeImageSequence = false ) const;
virtual bool match( const MSelectionMask & mask,
const MObjectArray& componentList ) const;
virtual MSelectionMask getShapeSelectionMask() const;
virtual bool excludeAsPluginShape() const;
// Callback when the walter node is added to the model (create / undo-delete)
void addedToModelCB();
// Callback when the walter node is removed from model (delete)
void removedFromModelCB();
/* A string that contains all the sub-selected objects separated with a
* semicolon. */
void setSubSelectedObjects(const MString& obj);
const MString& getSubSelectedObjects() const { return fSubSelectedObjects; }
/**
* @brief Checks that a regex represents a valid walter expression.
*
* @param expression The regex expression to validate.
*
* @return True is the expression is valid, false otherwise.
*/
bool expressionIsMatching(const MString& expression);
// Originally it's for specifying which plugs should be set dirty based upon
// an input plug plugBeingDirtied which Maya is marking dirty. We use it to
// catch dirty event and save dirty plugs to the internal cache.
virtual MStatus setDependentsDirty(
const MPlug& plug,
MPlugArray& plugArray);
// Reads the internal dirty cache and update the USD stage.
void updateUSDStage() const;
/**
* @brief Regenerate the textures if it's necessary.
*
* @param iTexturesEnabled True if the testures should be enabled.
*/
void updateTextures(bool iTexturesEnabled) const;
// Clear the USD playback cache.
void setCachedFramesDirty();
// This method gets called when connections are made to attributes of this
// node.
virtual MStatus connectionMade(
const MPlug& plug,
const MPlug& otherPlug,
bool asSrc);
virtual MStatus connectionBroken(
const MPlug& plug,
const MPlug& otherPlug,
bool asSrc);
/**
* @brief The current visible file names merged in a single string.
*
* @return
*/
const MString resolvedCacheFileName() const;
/**
* @brief Saves the stage to the node.
*
* @param iStage USD stage.
*/
void setStage(UsdStageRefPtr iStage);
/**
* @brief The current stage.
*
* @return The current stage.
*/
UsdStageRefPtr getStage() const;
/**
* @brief Current renderer.
*
* @return Current Hydra renderer.
*/
UsdImagingGLSharedPtr getRenderer();
/** @brief Called when the loading of the USD file is finished. It's a bit
* ugly because we call it from SubNode::getCachedGeometry(), but it's done
* for a reason because getCachedGeometry is the first thing that is called
* from VP2 when the loading is finished. It should only be called from the
* main thread. */
void onLoaded();
/** @brief Set flag that allows to call onLoaded. We can't call it from a
* different thread because USD doesn't like it. */
void setJustLoaded();
/** @brief Refreshes the render. */
void refresh();
/**
* @brief All the assignments of the current stage.
*/
ExpMap& getAssignments() { return mAssignments; }
const ExpMap& getAssignments() const { return mAssignments; }
/**
* @brief All the expression groups of the current stage.
*/
ExpGroup& getGroups() { return mGroups; }
const ExpGroup& getGroups() const { return mGroups; }
/**
* @brief All the assigned overrides of the current stage.
*/
AssignedOverrides& getAssignedOverrides() { return mOverrides; }
const AssignedOverrides& getAssignedOverrides() const { return mOverrides; }
/**
* @brief All the materials of the current stage.
*/
MStringArray& getEmbeddedShaders() { return mEmbeddedShaders; }
const MStringArray& getEmbeddedShaders() const { return mEmbeddedShaders; }
/**
* @brief Buffer with session layer. Please note it's not a session layer.
* It contains a buffer that is created when reading the file. We need to
* put it to the newly created stage.
*/
const MString& getSessionLayerBuffer() const { return fSessionLayerBuffer; }
/**
* @brief Buffer with variants layer. Please note it's not a variants layer.
* It contains a buffer that is created when reading the file. We need to
* put it to the newly created stage.
*/
const MString& getVariantsLayerBuffer() const { return fVariantsLayerBuffer; }
/**
* @brief Buffer with variantspurpose layer. Please note it's not a purpose layer.
* It contains a buffer that is created when reading the file. We need to
* put it to the newly created stage.
*/
const MString& getPurposeLayerBuffer() const { return fPurposeLayerBuffer; }
/**
* @brief Buffer with variants layer. Please note it's not a variants layer.
* It contains a buffer that is created when reading the file. We need to
* put it to the newly created stage.
*/
const MString& getVisibilityLayerBuffer() const { return fVisibilityLayerBuffer; }
/**
* @brief Called by setInternalValueInContext when the time is changed.
* If the time is not connect, it is called on scene loading and when saving transforms.
*/
void onTimeChanged(double previous);
UsdImagingGL::RenderParams mParams;
private:
// Prohibited and not implemented.
ShapeNode(const ShapeNode& obj);
const ShapeNode& operator=(const ShapeNode& obj);
bool setInternalFileName();
virtual void getExternalContent(MExternalContentInfoTable& table) const;
virtual void setExternalContent(const MExternalContentLocationTable& table);
MCallbackId mNameChangedCallbackId;
MCallbackId mAttributeChangedCallbackId;
static void nameChangedCallback(MObject &obj, const MString &prevName, void *clientData);
static void addAttributeAddedOrRemovedCallback(
MNodeMessage::AttributeMessage msg,
MPlug& plug,
void* clientDat);
MString fCacheFileName;
MString fResolvedCacheFileName;
MIntArray fVisibilities;
MIntArray fRenderables;
// See internalArrayCount
mutable std::vector<std::string> mAssignmentShadersBuffer;
/* This is the list of the objects selected by user separted by a semicolon.
* SubSceneOverride::fSubSelectedObjects is the object that is highlighted
* in the viewport. */
MString fSubSelectedObjects;
// We keep the latest loaded session/variants layer on the case the CacheFileEntry is
// not yet loaded.
MString fSessionLayerBuffer;
MString fVariantsLayerBuffer;
MString fVisibilityLayerBuffer;
MString fPurposeLayerBuffer;
// mutable because it's a dirty cache.
mutable std::set<unsigned int> fDirtyTransforms;
mutable std::set<unsigned int> fPreviousDirtyTransforms;
// The list of the frames per object that was already sent to the USD stage.
std::map<unsigned int, std::set<double>> fCachedFrames;
UsdStageRefPtr mStage;
bool mRendererNeedsUpdate;
UsdImagingGLSharedPtr mRenderer;
ExpMap mAssignments;
ExpGroup mGroups;
AssignedOverrides mOverrides;
MStringArray mEmbeddedShaders;
bool mJustLoaded;
// They are mutable because they just reflect the state of the USD stage.
// A flag that it's necessary to regenerate the textures.
mutable bool mDirtyTextures;
// A lag that is true if layer "viewportShaderLayer" is not muted in the USD
// stage.
mutable bool mTexturesEnabled;
};
// Return root ShapeNode from the Maya object name
ShapeNode* getShapeNode(
const MString& objectName,
MStatus* returnStatus=NULL);
float getCurrentFPS();
///////////////////////////////////////////////////////////////////////////////
//
// DisplayPref
//
// Keeps track of the display preference.
//
////////////////////////////////////////////////////////////////////////////////
class DisplayPref
{
public:
enum WireframeOnShadedMode {
kWireframeOnShadedFull,
kWireframeOnShadedReduced,
kWireframeOnShadedNone
};
static WireframeOnShadedMode wireframeOnShadedMode();
static MStatus initCallback();
static MStatus removeCallback();
private:
static void displayPrefChanged(void*);
static WireframeOnShadedMode fsWireframeOnShadedMode;
static MCallbackId fsDisplayPrefChangedCallbackId;
};
///////////////////////////////////////////////////////////////////////////////
//
// ShapeUI
//
// Displays animated shapes held in a memory cache.
//
////////////////////////////////////////////////////////////////////////////////
class ShapeUI : public MPxSurfaceShapeUI
{
public:
static void* creator();
ShapeUI();
~ShapeUI();
virtual void getDrawRequests(const MDrawInfo & info,
bool objectAndActiveOnly,
MDrawRequestQueue & queue);
// Viewport 1.0 draw
virtual void draw(const MDrawRequest & request, M3dView & view) const;
virtual bool select(MSelectInfo &selectInfo, MSelectionList &selectionList,
MPointArray &worldSpaceSelectPts ) const;
private:
// Prohibited and not implemented.
ShapeUI(const ShapeUI& obj);
const ShapeUI& operator=(const ShapeUI& obj);
static MPoint getPointAtDepth( MSelectInfo &selectInfo,double depth);
// Helper functions for the viewport 1.0 drawing purposes.
void drawBoundingBox(const MDrawRequest & request, M3dView & view ) const;
void drawWireframe(const MDrawRequest & request, M3dView & view ) const;
void drawShaded(const MDrawRequest & request, M3dView & view, bool depthOffset ) const;
void drawUSD(
const MDrawRequest& request,
const M3dView& view,
bool wireframe) const;
// Draw Tokens
enum DrawToken {
kBoundingBox,
kDrawWireframe,
kDrawWireframeOnShaded,
kDrawSmoothShaded,
kDrawSmoothShadedDepthOffset
};
};
}
#endif
<|start_filename|>walter/katana/WalterIn/walterCompatibility.cpp<|end_filename|>
// Copyright 2018 <NAME>. All rights reserved.
#include "walterCompatibility.h"
#if KATANA_VERSION_MAJOR == 3
Foundry::Katana::FnLogging::FnLog::FnLog(std::string const& module)
{}
Foundry::Katana::FnLogging::FnLog::~FnLog()
{}
void Foundry::Katana::FnLogging::FnLog::log(
std::string const& message,
unsigned int severity) const
{}
#endif
<|start_filename|>walter/maya/walterStandin/walterPlugin.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterShapeNode.h"
#include "walterDrawOverride.h"
#include "walterCmd.h"
#include "walterOverrideNode.h"
#include <maya/MFnPlugin.h>
#include <maya/MPlugArray.h>
#include <maya/MDrawRegistry.h>
#include <maya/MGlobal.h>
#include <maya/MSelectionMask.h>
#include <maya/MSceneMessage.h>
#include <maya/MDGMessage.h>
#include <maya/MFnStringData.h>
#include <maya/MFnTypedAttribute.h>
using namespace WalterMaya;
MStatus createMenu()
{
MString cmd;
// File Open dialog
cmd += "proc int _walterCacheFileNameCB(";
cmd += "\tstring $plug,";
cmd += "\tstring $fileName,";
cmd += "\tstring $fileType)";
cmd += "{";
cmd += "\tsetAttr $plug -type \"string\" $fileName;";
cmd += "\treturn true;";
cmd += "}";
cmd += "proc _walterCacheFileNameBrowser(string $cmd)";
cmd += "{";
cmd += "\tfileBrowser($cmd, \"USD or ABC File\", \"\", 0);";
cmd += "}";
cmd += "global string $gMainCreateMenu;";
cmd += "ModCreateMenu($gMainCreateMenu);";
cmd += "string $walterCreateNodeCmd = \""
"string $node = `createNode walterStandin`;"
"setAttr ($node + \\\".overrideTexturing\\\") 0;"
"setAttr ($node + \\\".overrideEnabled\\\") 1;"
"string $plug = $node + \\\".cacheFileName\\\";"
"connectAttr -f time1.outTime ($node + \\\".time\\\");"
"_walterCacheFileNameBrowser(\\\"_walterCacheFileNameCB $plug\\\");\";";
cmd += "string $walterCreateNodeLabel = \"Walter Standin\";";
cmd += "string $walterStandinMenuItem = \"walterStandinMenuItem\";";
cmd += "if( !stringArrayContains("
"$walterStandinMenuItem, `menu -q -ia $gMainCreateMenu`) )";
cmd += "{";
cmd += "\tsetParent -menu $gMainCreateMenu;";
cmd += "\tmenuItem "
"-divider true "
"-dividerLabel \"Rodeo Walter\" "
"($walterStandinMenuItem+\"Divider\");";
cmd += "\tmenuItem "
"-label $walterCreateNodeLabel "
"-command $walterCreateNodeCmd $walterStandinMenuItem;";
cmd += "}";
cmd += "else";
cmd += "{";
cmd += "\tmenuItem -e "
"-label $walterCreateNodeLabel "
"-command $walterCreateNodeCmd "
"$walterStandinMenuItem;";
cmd += "}";
return MGlobal::executeCommandOnIdle(cmd);
}
MStatus loadAETemplates()
{
// AETemplate for walterOverride
MString cmd =
"import AEwalterOverrideTemplate\n"
"import AEwalterStandinTemplate\n";
return MGlobal::executePythonCommand(cmd);
}
MStatus deleteMenu()
{
MString cmd;
cmd += "global string $gMainCreateMenu;";
cmd += "string $walterStandinMenuItem = \"walterStandinMenuItem\";";
cmd += "if( stringArrayContains("
"$walterStandinMenuItem, `menu -q -ia $gMainCreateMenu`) )";
cmd += "{";
cmd += "\tdeleteUI -menuItem ($walterStandinMenuItem+\"Divider\");";
cmd += "\tdeleteUI -menuItem $walterStandinMenuItem;";
cmd += "}";
return MGlobal::executeCommand(cmd);
}
MCallbackId beforeNewSceneID;
MCallbackId beforeOpenSceneID;
MCallbackId afterOpenSceneID;
void onBeforeNewScene(void* userData)
{
// Only execute this callback in interactive state.
// Otherwise it will crash when rendered in the farm.
if (MGlobal::kInteractive == MGlobal::mayaState())
{
// Hide the panel (qt widget)
MString cmd =
"import walterPanel\n"
"walterPanel.hidePanel()\n";
MGlobal::executePythonCommand(cmd);
}
}
void onBeforeOpenScene(void* userData)
{
// Only execute this callback in interactive state.
// Otherwise it will crash when rendered in the farm.
if (MGlobal::kInteractive == MGlobal::mayaState())
{
// Refreshs the panel (qt widget) to remove
// the tree items associated with walter
// standins of the previous scene.
MString cmd =
"import walterPanel\n"
"walterPanel.refreshPanel()\n";
MGlobal::executePythonCommand(cmd);
}
}
void onAfterOpenScene(void* userData)
{
// Only execute this callback in interactive state.
// Otherwise it will crash when rendered in the farm.
if (MGlobal::kInteractive == MGlobal::mayaState())
{
// Refreshs the panel (qt widget) to update
// the tree items associated with walter
// standinsof the current scene.
MString cmd =
"import walterPanel\n"
"walterPanel.refreshPanel()\n";
MGlobal::executePythonCommand(cmd);
}
}
// Add callback when a dag is added/removed to support undo/redo
MCallbackId addNodeID;
MCallbackId removeNodeID;
MCallbackId connectNodeID;
void onAddCB(MObject& node, void* clientData)
{
if (MGlobal::kInteractive == MGlobal::mayaState()) {
MFnDependencyNode nodeFn(node);
if(MFn::kPluginShape == node.apiType()) {
MString cmd =
"callbacks -executeCallbacks -hook \"WALTER_SCENE_CHANGED\" \"ADD_ROOT_ITEM\" \"" + nodeFn.name() + "\"";
MGlobal::executeCommandOnIdle(cmd);
}
}
}
void onRemoveCB(MObject& node, void* clientData)
{
if (MGlobal::kInteractive == MGlobal::mayaState()) {
MFnDependencyNode nodeFn(node);
if(MFn::kPluginShape == node.apiType()) {
MString cmd =
"callbacks -executeCallbacks -hook \"WALTER_SCENE_CHANGED\" \"REMOVE_ROOT_ITEM\" \"" + nodeFn.name() + "\"";
MGlobal::executeCommandOnIdle(cmd);
}
}
}
void onConnectCB(MPlug& srcPlug, MPlug& destPlug, bool made, void* clientData)
{
if (MGlobal::kInteractive == MGlobal::mayaState()) {
MFnDependencyNode srcNodeFn(srcPlug.node());
MFnDependencyNode destNodeFn(destPlug.node());
MString primPath = "";
MString action = made ? "ATTACH_TRANSFORM" : "DETACH_TRANSFORM";
for(int i=0; i<srcNodeFn.attributeCount(); ++i) {
MObject attrObject = srcNodeFn.attribute(i);
if(attrObject.apiType() == MFn::kTypedAttribute) {
MFnTypedAttribute attribute(attrObject);
MObject defaultCustomData;
attribute.getDefault(defaultCustomData);
if(attribute.name() == Command::LOCATOR_ATTR_PRIM_PATH) {
MFnStringData data(defaultCustomData);
primPath = data.string();
if(primPath.length() > 0) {
MString cmd =
"callbacks -executeCallbacks -hook \"WALTER_TRANFORM_LOCATOR_DELETED\" \"" + action + "\" \"" + destNodeFn.name() + "\" \"" + primPath + "\"";
MGlobal::executeCommandOnIdle(cmd);
}
}
}
}
}
}
MStatus initializePlugin( MObject obj )
{
MStatus status;
beforeNewSceneID = MSceneMessage::addCallback(
MSceneMessage::kBeforeNew, onBeforeNewScene );
beforeOpenSceneID = MSceneMessage::addCallback(
MSceneMessage::kBeforeOpen, onBeforeOpenScene );
afterOpenSceneID = MSceneMessage::addCallback(
MSceneMessage::kAfterOpen, onAfterOpenScene );
addNodeID = MDGMessage::addNodeAddedCallback (
onAddCB, "dependNode", NULL, &status);
removeNodeID = MDGMessage::addNodeRemovedCallback (
onRemoveCB, "dependNode", NULL, &status);
connectNodeID = MDGMessage::addPreConnectionCallback (
onConnectCB, NULL, &status);
MFnPlugin plugin( obj, "RodeoFX", "1.0", "Any");
status = plugin.registerShape(
ShapeNode::nodeTypeName,
ShapeNode::id,
ShapeNode::creator,
ShapeNode::initialize,
ShapeUI::creator,
&ShapeNode::drawDbClassificationGeometry );
if (!status) {
status.perror("registerNode");
return status;
}
if (MGlobal::kInteractive == MGlobal::mayaState()) {
status = MHWRender::MDrawRegistry::registerDrawOverrideCreator(
ShapeNode::drawDbClassificationGeometry,
ShapeNode::drawRegistrantId,
DrawOverride::creator);
if (!status) {
status.perror("registerGeometryDrawCreator");
return status;
}
}
status = plugin.registerCommand(
"walterStandin", Command::creator, Command::cmdSyntax );
if (!status) {
status.perror("registerCommand");
return status;
}
MGlobal::executeCommand("setNodeTypeFlag -threadSafe true walterStandin");
status = plugin.registerNode(
"walterOverride",
WalterOverride::mId,
WalterOverride::creator,
WalterOverride::initialize);
if (MGlobal::kInteractive == MGlobal::mayaState()) {
status = createMenu();
if (!status) {
status.perror("Can't create the Walter menu.");
return status;
}
status = loadAETemplates();
if (!status) {
status.perror("Can't load AE Templates.");
return status;
}
}
std::cout << "[RodeoFX] walterStandin " <<
MAJOR_VERSION << "." << MINOR_VERSION << "." << PATCH_VERSION <<
", built on " << __DATE__ << " at " << __TIME__ << std::endl;
return MS::kSuccess;
}
MStatus uninitializePlugin( MObject obj )
{
MStatus status;
MSceneMessage::removeCallback(beforeNewSceneID);
MSceneMessage::removeCallback(beforeOpenSceneID);
MSceneMessage::removeCallback(afterOpenSceneID);
MDGMessage::removeCallback(addNodeID);
MDGMessage::removeCallback(removeNodeID);
MDGMessage::removeCallback(connectNodeID);
MFnPlugin plugin( obj );
if (MGlobal::kInteractive == MGlobal::mayaState()) {
// Deregister the one we registered in initializePlugin().
status = MHWRender::MDrawRegistry::deregisterDrawOverrideCreator(
ShapeNode::drawDbClassificationGeometry,
ShapeNode::drawRegistrantId);
if (!status) {
status.perror("deregisterDrawOverrideCreator");
return status;
}
}
status = ShapeNode::uninitialize();
if (!status) {
status.perror("ShapeNode::uninitialize()");
return status;
}
status = plugin.deregisterNode( ShapeNode::id );
if (!status) {
status.perror("deregisterNode");
return status;
}
status = plugin.deregisterCommand( "walterStandin" );
if (!status) {
status.perror("deregisterCommand");
return status;
}
if (MGlobal::kInteractive == MGlobal::mayaState()) {
status = deleteMenu();
if (!status) {
status.perror("Can't delete Walter menu.");
return status;
}
}
return MS::kSuccess;
}
<|start_filename|>walter/maya/walterStandin/walterShapeNode.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
// Important to include it before gl.h
#include <pxr/imaging/glf/glew.h>
#include "walterShapeNode.h"
#include "mayaUtils.h"
#include "PathUtil.h"
#include "rdoProfiling.h"
#include "walterThreadingUtils.h"
#include "walterUsdUtils.h"
#include <GL/gl.h>
#include <maya/M3dView.h>
#include <maya/MDagPath.h>
#include <maya/MDrawData.h>
#include <maya/MEventMessage.h>
#include <maya/MExternalContentInfoTable.h>
#include <maya/MExternalContentLocationTable.h>
#include <maya/MFileIO.h>
#include <maya/MFileObject.h>
#include <maya/MFnCamera.h>
#include <maya/MFnCompoundAttribute.h>
#include <maya/MFnDagNode.h>
#include <maya/MFnEnumAttribute.h>
#include <maya/MFnMatrixData.h>
#include <maya/MFnMessageAttribute.h>
#include <maya/MFnNumericAttribute.h>
#include <maya/MFnStringData.h>
#include <maya/MFnTypedAttribute.h>
#include <maya/MFnUnitAttribute.h>
#include <maya/MGlobal.h>
#include <maya/MHWGeometryUtilities.h>
#include <maya/MMaterial.h>
#include <maya/MMatrix.h>
#include <maya/MObjectArray.h>
#include <maya/MPointArray.h>
#include <maya/MSelectionList.h>
#include <maya/MSelectionMask.h>
#include <maya/MViewport2Renderer.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usdGeom/imageable.h>
#include <tbb/blocked_range.h>
#include <tbb/parallel_reduce.h>
#include <boost/algorithm/string.hpp>
#include <cassert>
#include <climits>
#include "walterUSDCommonUtils.h"
#include <maya/MNodeMessage.h>
//==============================================================================
// Error checking
//==============================================================================
#define MCHECKERROR(STAT,MSG) \
if (!STAT) { \
perror(MSG); \
return MS::kFailure; \
}
#define MREPORTERROR(STAT,MSG) \
if (!STAT) { \
perror(MSG); \
}
namespace WalterMaya {
const MTypeId ShapeNode::id(WALTER_MAYA_SHAPE_ID);
const MString ShapeNode::drawDbClassificationGeometry(
"drawdb/geometry/walterStandin" );
const MString ShapeNode::drawRegistrantId("walterStandin" );
MObject ShapeNode::aCacheFileName;
MObject ShapeNode::aTime;
MObject ShapeNode::aTimeOffset;
MObject ShapeNode::aBBmode;
MObject ShapeNode::aLayersAssignation;
MObject ShapeNode::aLayersAssignationLayer;
MObject ShapeNode::aLayersAssignationSC;
MObject ShapeNode::aLayersAssignationSCNode;
MObject ShapeNode::aLayersAssignationSCShader;
MObject ShapeNode::aLayersAssignationSCDisplacement;
MObject ShapeNode::aLayersAssignationSCAttribute;
MObject ShapeNode::aExpressions;
MObject ShapeNode::aExpressionsName;
MObject ShapeNode::aExpressionsGroupName;
MObject ShapeNode::aExpressionsWeight;
MObject ShapeNode::aVisibilities;
MObject ShapeNode::aRenderables;
MObject ShapeNode::aAlembicShaders;
MObject ShapeNode::aEmbeddedShaders;
MObject ShapeNode::aArnoldProcedural;
MObject ShapeNode::aUSDSessionLayer;
MObject ShapeNode::aUSDVariantLayer;
MObject ShapeNode::aUSDMayaStateLayer;
MObject ShapeNode::aTransforms;
MObject ShapeNode::aUSDPurposeLayer;
MObject ShapeNode::aTransformsObject;
MObject ShapeNode::aTransformsMatrix;
MObject ShapeNode::aFrozen;
MObject ShapeNode::aUSDVisibilityLayer;
MObject ShapeNode::aHydraPlugin;
const char* ShapeNode::nodeTypeName = "walterStandin";
const char* ShapeNode::selectionMaskName = "walterStandin";
void* ShapeNode::creator()
{
return new ShapeNode;
}
MStatus ShapeNode::initialize()
{
MStatus stat;
MFnTypedAttribute typedAttrFn;
MFnEnumAttribute eAttr;
MFnUnitAttribute uAttr;
MFnNumericAttribute nAttr;
MFnCompoundAttribute cAttr;
MFnMessageAttribute mAttr;
// It's here to be loaded by maya before everything else. We need to know
// the session layer before we open Alembic cache.
aUSDSessionLayer = typedAttrFn.create(
"USDSessionLayer",
"usdsl",
MFnData::kString,
MObject::kNullObj,
&stat);
typedAttrFn.setHidden(true);
typedAttrFn.setInternal(true);
typedAttrFn.setStorable(true);
stat = MPxNode::addAttribute(aUSDSessionLayer);
MCHECKERROR(stat, "MPxNode::addAttribute(USDSessionLayer)");
aUSDVariantLayer = typedAttrFn.create(
"USDVariantsLayer",
"usdvl",
MFnData::kString,
MObject::kNullObj,
&stat);
typedAttrFn.setHidden(true);
typedAttrFn.setInternal(true);
typedAttrFn.setStorable(true);
stat = MPxNode::addAttribute(aUSDVariantLayer);
MCHECKERROR(stat, "MPxNode::addAttribute(USDVariantLayer)");
aUSDPurposeLayer = typedAttrFn.create(
"USDPurposeLayer",
"usdpl",
MFnData::kString,
MObject::kNullObj,
&stat);
typedAttrFn.setHidden(true);
typedAttrFn.setInternal(true);
typedAttrFn.setStorable(true);
stat = MPxNode::addAttribute(aUSDPurposeLayer);
MCHECKERROR(stat, "MPxNode::addAttribute(USDPurposeLayer)");
aUSDMayaStateLayer = typedAttrFn.create(
"USDMayaStateLayer",
"usdmsl",
MFnData::kString,
MObject::kNullObj,
&stat);
typedAttrFn.setHidden(true);
typedAttrFn.setInternal(true);
typedAttrFn.setStorable(false);
stat = MPxNode::addAttribute(aUSDMayaStateLayer);
MCHECKERROR(stat, "MPxNode::addAttribute(aUSDMayaStateLayer)");
aUSDVisibilityLayer = typedAttrFn.create(
"USDVisibilityLayer",
"usdvisl",
MFnData::kString,
MObject::kNullObj,
&stat);
typedAttrFn.setHidden(true);
typedAttrFn.setInternal(true);
typedAttrFn.setStorable(true);
stat = MPxNode::addAttribute(aUSDVisibilityLayer);
MCHECKERROR(stat, "MPxNode::addAttribute(USDVisibilityLayer)");
aBBmode = nAttr.create("useBBox", "ubb",
MFnNumericData::kBoolean, false, &stat);
nAttr.setInternal(true);
stat = MPxNode::addAttribute(aBBmode);
MCHECKERROR(stat, "MPxNode::addAttribute(aBBmode)");
// time
aTime = uAttr.create("time", "t", MFnUnitAttribute::kTime);
uAttr.setStorable(false);
uAttr.setKeyable(true);
uAttr.setReadable(true);
uAttr.setWritable(true);
uAttr.setInternal(true);
stat = MPxNode::addAttribute(aTime);
MCHECKERROR(stat, "MPxNode::addAttribute(aTime)");
// timeOffset
aTimeOffset = uAttr.create("timeOffset", "to",MFnUnitAttribute::kTime);
uAttr.setStorable(true);
uAttr.setKeyable(true);
uAttr.setInternal(true);
stat = MPxNode::addAttribute(aTimeOffset);
MCHECKERROR(stat, "MPxNode::addAttribute(aTimeOffset)");
// Generating following compound attribute
// layersAssignation[]
// |-layer (message)
// +-shaderConnections[]
// |-abcnode (string)
// |-shader (message)
// |-displacement (message)
// +-attribute (message)
aLayersAssignationSCShader = mAttr.create("shader", "shader");
mAttr.setHidden(false);
mAttr.setReadable(true);
mAttr.setStorable(true);
mAttr.setWritable(true);
aLayersAssignationSCDisplacement = mAttr.create(
"displacement", "displacement");
mAttr.setHidden(false);
mAttr.setReadable(true);
mAttr.setStorable(true);
mAttr.setWritable(true);
aLayersAssignationSCAttribute = mAttr.create(
"attribute", "attribute");
mAttr.setHidden(false);
mAttr.setReadable(true);
mAttr.setStorable(true);
mAttr.setWritable(true);
aLayersAssignationSCNode = typedAttrFn.create(
"abcnode",
"abcnode",
MFnStringData::kString,
MObject::kNullObj);
typedAttrFn.setHidden(false);
typedAttrFn.setReadable(true);
typedAttrFn.setStorable(true);
typedAttrFn.setWritable(true);
aLayersAssignationSC = cAttr.create(
"shaderConnections", "shaderConnections");
cAttr.setArray(true);
cAttr.setReadable(true);
cAttr.setUsesArrayDataBuilder(true);
cAttr.addChild(aLayersAssignationSCNode);
cAttr.addChild(aLayersAssignationSCShader);
cAttr.addChild(aLayersAssignationSCDisplacement);
cAttr.addChild(aLayersAssignationSCAttribute);
aLayersAssignationLayer = mAttr.create("layer", "layer");
typedAttrFn.setHidden(false);
typedAttrFn.setReadable(true);
typedAttrFn.setStorable(true);
typedAttrFn.setWritable(true);
aLayersAssignation = cAttr.create("layersAssignation", "la");
cAttr.setArray(true);
cAttr.setReadable(true);
cAttr.setUsesArrayDataBuilder(true);
cAttr.addChild(aLayersAssignationLayer);
cAttr.addChild(aLayersAssignationSC);
stat = MPxNode::addAttribute(aLayersAssignation);
MCHECKERROR(stat, "MPxNode::addAttribute(layersAssignation)");
// Generating following compound attribute
// expressions[]
// |-expressionname (string)
// +-expressiongroupname (string)
// +-expressionweight (int)
aExpressionsName = typedAttrFn.create(
"expressionname",
"en",
MFnStringData::kString,
MObject::kNullObj);
typedAttrFn.setHidden(false);
typedAttrFn.setReadable(true);
typedAttrFn.setStorable(true);
typedAttrFn.setWritable(true);
aExpressionsGroupName = typedAttrFn.create(
"expressiongroupname",
"egn",
MFnStringData::kString,
MObject::kNullObj);
typedAttrFn.setHidden(false);
typedAttrFn.setReadable(true);
typedAttrFn.setStorable(true);
typedAttrFn.setWritable(true);
aExpressionsWeight = nAttr.create(
"expressionweight", "ew",
MFnNumericData::kInt, 0, &stat);
nAttr.setHidden(true);
nAttr.setReadable(true);
nAttr.setStorable(true);
nAttr.setWritable(true);
stat = MPxNode::addAttribute(aExpressionsWeight);
MCHECKERROR(stat, "MPxNode::addAttribute(expressionweight)");
aExpressions = cAttr.create("expressions", "exp");
cAttr.setArray(true);
cAttr.setReadable(true);
cAttr.setUsesArrayDataBuilder(true);
cAttr.addChild(aExpressionsName);
cAttr.addChild(aExpressionsGroupName);
cAttr.addChild(aExpressionsWeight);
stat = MPxNode::addAttribute(aExpressions);
MCHECKERROR(stat, "MPxNode::addAttribute(expressions)");
aVisibilities = nAttr.create(
"visibilities",
"vs",
MFnNumericData::kBoolean,
true,
&stat);
nAttr.setArray(true);
nAttr.setInternal(true);
stat = MPxNode::addAttribute(aVisibilities);
MCHECKERROR(stat, "MPxNode::addAttribute(visibilities)");
aRenderables = nAttr.create(
"renderables",
"rs",
MFnNumericData::kBoolean,
true,
&stat);
nAttr.setArray(true);
nAttr.setInternal(true);
stat = MPxNode::addAttribute(aRenderables);
MCHECKERROR(stat, "MPxNode::addAttribute(renderables)");
aAlembicShaders = typedAttrFn.create(
"alembicShaders",
"as",
MFnData::kString,
MObject::kNullObj,
&stat);
typedAttrFn.setArray(true);
typedAttrFn.setInternal(true);
typedAttrFn.setStorable(false);
stat = MPxNode::addAttribute(aAlembicShaders);
MCHECKERROR(stat, "MPxNode::addAttribute(aAlembicShaders)");
aEmbeddedShaders = typedAttrFn.create(
"embeddedShaders",
"es",
MFnData::kString,
MObject::kNullObj,
&stat);
typedAttrFn.setArray(true);
typedAttrFn.setInternal(true);
typedAttrFn.setStorable(false);
stat = MPxNode::addAttribute(aEmbeddedShaders);
MCHECKERROR(stat, "MPxNode::addAttribute(aEmbeddedShaders)");
aArnoldProcedural = typedAttrFn.create(
"arnoldProcedural",
"ap",
MFnData::kString,
MObject::kNullObj,
&stat);
typedAttrFn.setHidden(false);
typedAttrFn.setReadable(true);
typedAttrFn.setStorable(true);
typedAttrFn.setWritable(true);
stat = MPxNode::addAttribute(aArnoldProcedural);
MCHECKERROR(stat, "MPxNode::addAttribute(arnoldProcedural)");
// Generating following compound attribute
// transforms[]
// |-transformobject (string)
// +-transformmatrix (matrix)
aTransformsObject = typedAttrFn.create(
"transformobject",
"tro",
MFnStringData::kString,
MObject::kNullObj);
typedAttrFn.setConnectable(false);
typedAttrFn.setHidden(false);
typedAttrFn.setKeyable(false);
typedAttrFn.setReadable(true);
typedAttrFn.setStorable(true);
typedAttrFn.setWritable(true);
aTransformsMatrix = typedAttrFn.create(
"transformmatrix",
"trm",
MFnStringData::kMatrix,
MObject::kNullObj);
typedAttrFn.setConnectable(true);
typedAttrFn.setInternal(true);
typedAttrFn.setKeyable(true);
typedAttrFn.setReadable(true);
typedAttrFn.setStorable(false);
typedAttrFn.setWritable(true);
aTransforms = cAttr.create("transforms", "tr");
cAttr.setArray(true);
cAttr.setReadable(true);
cAttr.addChild(aTransformsObject);
cAttr.addChild(aTransformsMatrix);
stat = MPxNode::addAttribute(aTransforms);
MCHECKERROR(stat, "MPxNode::addAttribute(transforms)");
aFrozen = nAttr.create(
"frozenTransforms", "ft",
MFnNumericData::kBoolean,
false,
&stat);
nAttr.setInternal(true);
nAttr.setStorable(false);
stat = MPxNode::addAttribute(aFrozen);
MCHECKERROR(stat, "MPxNode::addAttribute(aFrozen)");
aHydraPlugin = typedAttrFn.create(
"hydraPlugin",
"hp",
MFnData::kString,
MObject::kNullObj,
&stat);
typedAttrFn.setInternal(true);
stat = MPxNode::addAttribute(aHydraPlugin);
MCHECKERROR(stat, "MPxNode::addAttribute(hydraPlugin)");
// File name. On the bottom to be sure that everything else is already
// loaded from the file.
aCacheFileName = typedAttrFn.create("cacheFileName", "cfn",
MFnData::kString, MObject::kNullObj, &stat);
typedAttrFn.setInternal(true);
stat = MPxNode::addAttribute(aCacheFileName);
MCHECKERROR(stat, "MPxNode::addAttribute(aCacheFileName)");
stat = DisplayPref::initCallback();
MCHECKERROR(stat, "DisplayPref::initCallbacks()");
return stat;
}
MStatus ShapeNode::uninitialize()
{
DisplayPref::removeCallback();
return MStatus::kSuccess;
}
ShapeNode::ShapeNode() :
bTriggerGeoReload(false),
fBBmode(false),
fLoadGeo(false),
fReadMaterials(false),
fSceneLoaded(false),
fFrozen(false),
fSubSelectedObjects(),
mRendererNeedsUpdate(false),
mJustLoaded(false),
mDirtyTextures(true),
mTexturesEnabled(false)
{
mParams.showGuides = true;
mParams.showProxy = true;
mParams.showRender = false;
}
ShapeNode::~ShapeNode()
{
MMessage::removeCallback(
mNameChangedCallbackId);
}
void ShapeNode::postConstructor()
{
MObject mobj = thisMObject();
MFnDependencyNode nodeFn(mobj);
nodeFn.setName("walterStandinShape#");
setRenderable(true);
// Explicitly initialize config when the first walter node is created.
// When initializing Config, it will access video adapters via WMI and
// Windows will sometimes send OnPaint message to Maya and thus cause a
// refresh. The wired OnPaint message will crash VP2 and walter.
// Config::initialize();
mNameChangedCallbackId = MNodeMessage::addNameChangedCallback(mobj, nameChangedCallback, nullptr);
}
void ShapeNode::nameChangedCallback(MObject &obj, const MString &prevName, void *clientData)
{
MFnDependencyNode node(obj);
// If the standin is name "walterStandinShape#", it has just been created.
// Otherwise it's renamed
MString cmd = prevName == MString("walterStandinShape#")
? "callbacks -executeCallbacks -hook \"WALTER_SCENE_CHANGED\" \"ADD_ROOT_ITEM\" \"" + node.name() + "\""
: "callbacks -executeCallbacks -hook \"WALTER_SCENE_CHANGED\" \"RENAME_ROOT_ITEM\" \"" + node.name() + "\" \"" + prevName + "\"";
MGlobal::executeCommandOnIdle(cmd);
}
bool ShapeNode::isBounded() const
{
return true;
}
MBoundingBox ShapeNode::boundingBox() const
{
static const double minBox = 1.0;
static const MBoundingBox minBBox(
MPoint(-minBox, -minBox, -minBox), MPoint(minBox, minBox, minBox));
// Get USD stuff from the node.
UsdStageRefPtr stage = getStage();
if (!stage)
{
return minBBox;
}
// Frame number.
// TODO: get FPS from Maya.
UsdTimeCode timeCode(1.0);
// UsdTimeCode timeCode(time * 24.0);
UsdGeomImageable imageable =
UsdGeomImageable::Get(stage, SdfPath::AbsoluteRootPath());
GfBBox3d bbox = imageable.ComputeWorldBound(
timeCode, UsdGeomTokens->default_, UsdGeomTokens->render);
// Push the bbox to Maya.
const GfRange3d& range = bbox.GetBox();
const GfVec3d& min = range.GetMin();
const GfVec3d& max = range.GetMax();
return MBoundingBox(
MPoint(min[0], min[1], min[2]), MPoint(max[0], max[1], max[2]));
return minBBox;
}
bool ShapeNode::getInternalValueInContext(const MPlug& plug,
MDataHandle& dataHandle, MDGContext& ctx)
{
if (plug == aCacheFileName) {
dataHandle.setString(fCacheFileName);
return true;
}
else if (plug == aTime) {
return false;
}
else if (plug == aTimeOffset) {
return false;
}
else if (plug == aBBmode) {
dataHandle.setBool(fBBmode);
return true;
}
else if (plug == aAlembicShaders)
{
unsigned int index = plug.logicalIndex();
if (index < mAssignmentShadersBuffer.size())
{
dataHandle.setString(mAssignmentShadersBuffer[index].c_str());
return true;
}
}
else if (plug == aUSDSessionLayer)
{
std::string session = constructUSDSessionLayer(thisMObject());
dataHandle.setString(session.c_str());
return true;
}
else if (plug == aUSDVariantLayer)
{
std::string layer = getVariantsLayerAsText(thisMObject());
dataHandle.setString(layer.c_str());
return true;
}
else if (plug == aUSDPurposeLayer)
{
std::string layer = getPurposeLayerAsText(thisMObject());
dataHandle.setString(layer.c_str());
return true;
}
else if (plug == aUSDVisibilityLayer)
{
std::string layer = getVisibilityLayerAsText(thisMObject());
dataHandle.setString(layer.c_str());
return true;
}
else if (plug == aUSDMayaStateLayer)
{
std::string layer = getMayaStateAsUSDLayer(thisMObject());
dataHandle.setString(layer.c_str());
return true;
}
else if (plug == aEmbeddedShaders)
{
unsigned int index = plug.logicalIndex();
if (index < getEmbeddedShaders().length())
{
dataHandle.setString(getEmbeddedShaders()[index]);
return true;
}
}
else if (plug == aFrozen)
{
dataHandle.setBool(fFrozen);
return true;
}
return MPxNode::getInternalValueInContext(plug, dataHandle, ctx);
}
int ShapeNode::internalArrayCount(const MPlug& plug, const MDGContext& ctx)
const
{
if (plug == aAlembicShaders)
{
// Rebuild list of the shaders. The idea that when we ask the number of
// items in aAlembicShaders, we prepare all the items and when we ask
// the item, we don't need to rebuild the complex map to the vector.
mAssignmentShadersBuffer.clear();
// Get all the objects
for (const auto& exp : getAssignments())
{
// Get all the layers
for (const auto& layer : exp.second)
{
// The current shader name
const std::string& currentShader = layer.second;
// Check if we already have it in the vector
auto found = std::find(
mAssignmentShadersBuffer.begin(),
mAssignmentShadersBuffer.end(),
currentShader);
if (found == mAssignmentShadersBuffer.end())
{
mAssignmentShadersBuffer.push_back(currentShader);
}
}
}
return mAssignmentShadersBuffer.size();
}
else if (plug == aEmbeddedShaders)
{
return getEmbeddedShaders().length();
}
return MPxNode::internalArrayCount(plug, ctx);
}
bool ShapeNode::setInternalFileName()
{
MString newResolvedFileName = resolvedCacheFileName();
if (newResolvedFileName != fResolvedCacheFileName)
{
fResolvedCacheFileName = newResolvedFileName;
// Remove the stage. It should remove the object from the viewport.
setStage(UsdStageRefPtr(nullptr));
// This should clear the caches.
onLoaded();
// Start the loading is a different thread.
WalterThreadingUtils::loadStage(thisMObject());
}
return true;
}
bool ShapeNode::setInternalValueInContext(const MPlug& plug,
const MDataHandle& dataHandle, MDGContext& ctx)
{
if (plug == aCacheFileName) {
fCacheFileName = dataHandle.asString();
return setInternalFileName();
}
else if (plug == aTime) {
MFnDagNode fn(thisMObject());
MTime time, timeOffset;
time = dataHandle.asTime();
MPlug plug = fn.findPlug(aTimeOffset);
plug.getValue(timeOffset);
double dtime;
dtime = time.as(MTime::kSeconds) + timeOffset.as(MTime::kSeconds);
double previous = this->time;
this->time = dtime;
// We want to update the cached shape
onTimeChanged(previous);
return false;
}
else if (plug == aTimeOffset) {
MFnDagNode fn(thisMObject());
MTime time, timeOffset;
timeOffset = dataHandle.asTime();
MPlug plug = fn.findPlug(aTime);
plug.getValue(time);
double dtime;
dtime = time.as(MTime::kSeconds) + timeOffset.as(MTime::kSeconds);
double previous = this->time;
this->time = dtime;
// We want to update the cached shape
onTimeChanged(previous);
return false;
}
else if (plug == aBBmode) {
this->fBBmode = dataHandle.asBool();
bTriggerGeoReload = true;
return true;
}
else if (plug == aVisibilities) {
unsigned index = plug.logicalIndex();
unsigned length = fVisibilities.length();
// Extend the size
if (length <= index) {
fVisibilities.setLength(index+1);
}
// Fill with default values
while (length < index) {
fVisibilities[length] = 1;
length++;
}
fVisibilities[index] = dataHandle.asBool();
if (!MFileIO::isReadingFile())
{
// TODO: it's a fast workaround. When we change one visibility from
// the UI, Maya calls this method for all the visibilities of the
// layers. We don't need to reload the stage a lot of times at once,
// so we reload it only if the last visibility is changed.
std::string fileName = fCacheFileName.asChar();
if (std::count(fileName.begin(), fileName.end(), ':') == index)
{
// This will update internal file name and reload the stage if
// necessary.
setInternalFileName();
}
}
// Return false to indicate that Maya can store the attribute's value in
// the data block. Otherwise the size of array aFiles will not be
// changed and this attribute will not be saved in Maya file.
return false;
}
else if (plug == aRenderables) {
unsigned index = plug.logicalIndex();
unsigned length = fRenderables.length();
// Extend the size
if (length <= index) {
fRenderables.setLength(index+1);
}
// Fill with default values
while (length < index) {
fRenderables[length] = 1;
length++;
}
fRenderables[index] = dataHandle.asBool();
// Return false to indicate that Maya can store the attribute's value in
// the data block. Otherwise the size of array aFiles will not be
// changed and this attribute will not be saved in Maya file.
return false;
}
else if (plug == aUSDSessionLayer) {
// Save the session layer in the buffer. If CacheFileEntry is not loaded
// yet (it happeng on Maya scene opening), setUSDSessionLayer will skip
// execution and CacheFileEntry will use this buffer.
fSessionLayerBuffer = dataHandle.asString();
setUSDSessionLayer(thisMObject(), fSessionLayerBuffer.asChar());
return false;
}
else if (plug == aUSDVisibilityLayer) {
// Save the Visibilitys layer in the buffer. If CacheFileEntry is not loaded
// yet (it happeng on Maya scene opening), setUSDVisibilityLayer will skip
// execution and CacheFileEntry will use this buffer.
fVisibilityLayerBuffer = dataHandle.asString();
setUSDVisibilityLayer(thisMObject(), fVisibilityLayerBuffer.asChar());
return true;
}
else if (plug == aUSDVariantLayer) {
// Save the variants layer in the buffer. If CacheFileEntry is not loaded
// yet (it happeng on Maya scene opening), setUSDVariantsLayer will skip
// execution and CacheFileEntry will use this buffer.
fVariantsLayerBuffer = dataHandle.asString();
setUSDVariantsLayer(thisMObject(), fVariantsLayerBuffer.asChar());
return true;
}
else if (plug == aUSDPurposeLayer) {
// Save the Purposes layer in the buffer. If CacheFileEntry is not loaded
// yet (it happeng on Maya scene opening), setUSDPurposeLayer will skip
// execution and CacheFileEntry will use this buffer.
fPurposeLayerBuffer = dataHandle.asString();
setUSDPurposeLayer(thisMObject(), fPurposeLayerBuffer.asChar());
return true;
}
else if (plug == aFrozen) {
this->fFrozen = dataHandle.asBool();
// Reset caches and re-merge everything.
setCachedFramesDirty();
return true;
}
else if (plug == aHydraPlugin) {
// The user changed the Hydra plugin. We need to re-create the renderer.
mRendererNeedsUpdate = true;
}
return MPxNode::setInternalValueInContext(plug, dataHandle, ctx);
}
MStringArray ShapeNode::getFilesToArchive(
bool shortName, bool unresolvedName, bool markCouldBeImageSequence ) const
{
MStringArray files;
if(unresolvedName)
{
files.append(fCacheFileName);
}
else
{
//unresolvedName is false, resolve the path via MFileObject.
MFileObject fileObject;
fileObject.setRawFullName(fCacheFileName);
files.append(fileObject.resolvedFullName());
}
return files;
}
void ShapeNode::copyInternalData(MPxNode* source)
{
if (source && source->typeId() == id)
{
ShapeNode* node = dynamic_cast<ShapeNode*>(source);
// We can't copy mStage because we need to have a copy of the stage.
fCacheFileName = node->fCacheFileName;
// This should reload the stage and all the additional stuff.
setInternalFileName();
}
}
bool ShapeNode::match( const MSelectionMask & mask,
const MObjectArray& componentList ) const
{
MSelectionMask walterMask(ShapeNode::selectionMaskName);
return mask.intersects(walterMask) && componentList.length()==0;
}
MSelectionMask ShapeNode::getShapeSelectionMask() const
{
return MSelectionMask(ShapeNode::selectionMaskName);
}
bool ShapeNode::excludeAsPluginShape() const
{
// Walter node has its own display filter in Show menu.
// We don't want "Plugin Shapes" to filter out walter nodes.
return false;
}
void ShapeNode::setSubSelectedObjects(const MString& obj)
{
fSubSelectedObjects = obj;
std::string expression = obj.asChar();
// Get USD stuff from the node.
if (!mRenderer || !mStage)
{
return;
}
SdfPathVector selection;
if (!expression.empty())
{
// Generate a regexp object.
void* regexp = WalterCommon::createRegex(expression);
UsdPrimRange range(mStage->GetPrimAtPath(SdfPath::AbsoluteRootPath()));
for (const UsdPrim& prim: range)
{
const SdfPath& path = prim.GetPath();
std::string current = path.GetString();
// TODO: What if we have '/cube' and '/cubeBig/shape' objects? If we
// try to select the first one, both of them will be selected.
if (boost::starts_with(current, expression) ||
WalterCommon::searchRegex(regexp, current)) {
selection.push_back(path);
}
}
// Delete a regexp object.
WalterCommon::clearRegex(regexp);
}
mRenderer->SetSelected(selection);
}
bool ShapeNode::expressionIsMatching(const MString& expression)
{
return WalterUSDCommonUtils::expressionIsMatching(
mStage, expression.asChar());
}
ShapeNode* getShapeNode(
const MString& objectName, MStatus* returnStatus)
{
/* Get ShapeNode from the string. First, create the section. */
MSelectionList selection;
MStatus status = selection.add(objectName);
if (status != MS::kSuccess) {
if (returnStatus) {
*returnStatus = status;
}
return NULL;
}
/* Get the MObject of the dependency node. */
MObject object;
status = selection.getDependNode(0, object);
if (status != MS::kSuccess) {
if (returnStatus) {
*returnStatus = status;
}
return NULL;
}
/* MFnDependencyNode allows the manipulation of dependency graph nodes. */
MFnDependencyNode depNode(object, &status);
if (status != MS::kSuccess) {
if (returnStatus) {
*returnStatus = status;
}
return NULL;
}
/* Get the ShapeNode. */
ShapeNode* userNode = dynamic_cast<ShapeNode*>(depNode.userNode());
if (returnStatus) {
if (userNode) {
*returnStatus = MS::kSuccess;
} else {
*returnStatus = MS::kFailure;
}
}
return userNode;
}
float getCurrentFPS()
{
// Cache it, so no necessary to querry MTime each frame.
static float currentFPS = -1.0;
if (currentFPS < 0.0f)
{
MTime::Unit unit = MTime::uiUnit();
switch (unit)
{
case MTime::kGames:
currentFPS = 15.0f;
break;
case MTime::kFilm:
currentFPS = 24.0f;
break;
case MTime::kPALFrame:
currentFPS = 25.0f;
break;
case MTime::kNTSCFrame:
currentFPS = 30.0f;
break;
case MTime::kShowScan:
currentFPS = 48.0f;
break;
case MTime::kPALField:
currentFPS = 50.0f;
break;
case MTime::kNTSCField:
currentFPS = 60.0f;
break;
case MTime::k2FPS:
currentFPS = 2.0f;
break;
case MTime::k3FPS:
currentFPS = 3.0f;
break;
case MTime::k4FPS:
currentFPS = 4.0f;
break;
case MTime::k5FPS:
currentFPS = 5.0f;
break;
case MTime::k6FPS:
currentFPS = 6.0f;
break;
case MTime::k8FPS:
currentFPS = 8.0f;
break;
case MTime::k10FPS:
currentFPS = 10.0f;
break;
case MTime::k12FPS:
currentFPS = 12.0f;
break;
case MTime::k16FPS:
currentFPS = 16.0f;
break;
case MTime::k20FPS:
currentFPS = 20.0f;
break;
case MTime::k40FPS:
currentFPS = 40.0f;
break;
case MTime::k75FPS:
currentFPS = 75.0f;
break;
case MTime::k80FPS:
currentFPS = 80.0f;
break;
case MTime::k100FPS:
currentFPS = 100.0f;
break;
case MTime::k120FPS:
currentFPS = 120.0f;
break;
case MTime::k125FPS:
currentFPS = 125.0f;
break;
case MTime::k150FPS:
currentFPS = 150.0f;
break;
case MTime::k200FPS:
currentFPS = 200.0f;
break;
case MTime::k240FPS:
currentFPS = 240.0f;
break;
case MTime::k250FPS:
currentFPS = 250.0f;
break;
case MTime::k300FPS:
currentFPS = 300.0f;
break;
case MTime::k375FPS:
currentFPS = 375.0f;
break;
case MTime::k400FPS:
currentFPS = 400.0f;
break;
case MTime::k500FPS:
currentFPS = 500.0f;
break;
case MTime::k600FPS:
currentFPS = 600.0f;
break;
case MTime::k750FPS:
currentFPS = 750.0f;
break;
case MTime::k1200FPS:
currentFPS = 1200.0f;
break;
case MTime::k1500FPS:
currentFPS = 1500.0f;
break;
case MTime::k2000FPS:
currentFPS = 2000.0f;
break;
case MTime::k3000FPS:
currentFPS = 3000.0f;
break;
case MTime::k6000FPS:
currentFPS = 6000.0f;
break;
default:
currentFPS = 0.0f;
break;
}
}
return currentFPS;
}
//==============================================================================
// CLASS DisplayPref
//==============================================================================
DisplayPref::WireframeOnShadedMode DisplayPref::fsWireframeOnShadedMode;
MCallbackId DisplayPref::fsDisplayPrefChangedCallbackId;
MStatus DisplayPref::initCallback()
{
MStatus stat;
// Register DisplayPreferenceChanged callback
fsDisplayPrefChangedCallbackId = MEventMessage::addEventCallback(
"DisplayPreferenceChanged", DisplayPref::displayPrefChanged, NULL, &stat);
MCHECKERROR(stat, "MEventMessage::addEventCallback(DisplayPreferenceChanged");
// Trigger the callback manually to init class members
displayPrefChanged(NULL);
return MS::kSuccess;
}
MStatus DisplayPref::removeCallback()
{
MStatus stat;
// Remove DisplayPreferenceChanged callback
MEventMessage::removeCallback(fsDisplayPrefChangedCallbackId);
MCHECKERROR(stat, "MEventMessage::removeCallback(DisplayPreferenceChanged)");
return MS::kSuccess;
}
void DisplayPref::displayPrefChanged(void*)
{
MStatus stat;
// Wireframe on shaded mode: Full/Reduced/None
MString wireframeOnShadedActive = MGlobal::executeCommandStringResult(
"displayPref -q -wireframeOnShadedActive", false, false, &stat);
if (stat) {
if (wireframeOnShadedActive == "full") {
fsWireframeOnShadedMode = kWireframeOnShadedFull;
}
else if (wireframeOnShadedActive == "reduced") {
fsWireframeOnShadedMode = kWireframeOnShadedReduced;
}
else if (wireframeOnShadedActive == "none") {
fsWireframeOnShadedMode = kWireframeOnShadedNone;
}
else {
assert(0);
}
}
}
DisplayPref::WireframeOnShadedMode DisplayPref::wireframeOnShadedMode()
{
return fsWireframeOnShadedMode;
}
//==============================================================================
// CLASS ShapeUI
//==============================================================================
void* ShapeUI::creator()
{
return new ShapeUI;
}
ShapeUI::ShapeUI()
{}
ShapeUI::~ShapeUI()
{}
void ShapeUI::getDrawRequests(const MDrawInfo & info,
bool objectAndActiveOnly,
MDrawRequestQueue & queue)
{
// Get the data necessary to draw the shape
MDrawData data;
getDrawData( 0, data );
// Decode the draw info and determine what needs to be drawn
M3dView::DisplayStyle appearance = info.displayStyle();
M3dView::DisplayStatus displayStatus = info.displayStatus();
MDagPath path = info.multiPath();
switch ( appearance )
{
case M3dView::kBoundingBox :
{
MDrawRequest request = info.getPrototype( *this );
request.setDrawData( data );
request.setToken( kBoundingBox );
MColor wireframeColor = MHWRender::MGeometryUtilities::wireframeColor(path);
request.setColor(wireframeColor);
queue.add( request );
}break;
case M3dView::kWireFrame :
{
MDrawRequest request = info.getPrototype( *this );
request.setDrawData( data );
request.setToken( kDrawWireframe );
MColor wireframeColor = MHWRender::MGeometryUtilities::wireframeColor(path);
request.setColor(wireframeColor);
queue.add( request );
} break;
// All of these modes are interpreted as meaning smooth shaded
// just as it is done in the viewport 2.0.
case M3dView::kFlatShaded :
case M3dView::kGouraudShaded :
default:
{
ShapeNode* node = (ShapeNode*)surfaceShape();
if (!node) break;
// Get the view to draw to
M3dView view = info.view();
const bool needWireframe = ((displayStatus == M3dView::kActive) ||
(displayStatus == M3dView::kLead) ||
(displayStatus == M3dView::kHilite) ||
(view.wireframeOnShaded()));
// When we need to draw both the shaded geometry and the
// wireframe mesh, we need to offset the shaded geometry
// in depth to avoid Z-fighting against the wireframe
// mesh.
//
// On the hand, we don't want to use depth offset when
// drawing only the shaded geometry because it leads to
// some drawing artifacts. The reason is a litle bit
// subtle. At silouhette edges, both front-facing and
// back-facing faces are meeting. These faces can have a
// different slope in Z and this can lead to a different
// Z-offset being applied. When unlucky, the back-facing
// face can be drawn in front of the front-facing face. If
// two-sided lighting is enabled, the back-facing fragment
// can have a different resultant color. This can lead to
// a rim of either dark or bright pixels around silouhette
// edges.
//
// When the wireframe mesh is drawn on top (even a dotted
// one), it masks this effect sufficiently that it is no
// longer distracting for the user, so it is OK to use
// depth offset when the wireframe mesh is drawn on top.
const DrawToken shadedDrawToken = needWireframe ?
kDrawSmoothShadedDepthOffset : kDrawSmoothShaded;
// Get the default material.
//
// Note that we will only use the material if the viewport
// option "Use default material" has been selected. But,
// we still need to set a material (even an unevaluated
// one), so that the draw request is indentified as
// drawing geometry instead of drawing the wireframe mesh.
MMaterial material = MMaterial::defaultMaterial();
if (view.usingDefaultMaterial()) {
// Evaluate the material.
if ( !material.evaluateMaterial(view, path) ) {
MStatus stat;
// MString msg = MStringResource::getString(kEvaluateMaterialErrorMsg, stat);
// perror(msg.asChar());
}
// Create the smooth shaded draw request
MDrawRequest request = info.getPrototype( *this );
request.setDrawData( data );
// This draw request will draw all sub nodes using an
// opaque default material.
request.setToken( shadedDrawToken );
request.setIsTransparent( false );
request.setMaterial( material );
queue.add( request );
}
else if (view.xray()) {
// Create the smooth shaded draw request
MDrawRequest request = info.getPrototype( *this );
request.setDrawData( data );
// This draw request will draw all sub nodes using in X-Ray mode
request.setToken( shadedDrawToken );
request.setIsTransparent( true );
request.setMaterial( material );
queue.add( request );
}
else {
// Opaque draw request
if (1) {
// Create the smooth shaded draw request
MDrawRequest request = info.getPrototype( *this );
request.setDrawData( data );
// This draw request will draw opaque sub nodes
request.setToken( shadedDrawToken );
// USD draw modification: USD needs to render everything in
// one pass. So it's necessary to provide the wireframe
// color even if it's a regular shading pass.
auto wireOnModel = DisplayPref::wireframeOnShadedMode();
if (needWireframe &&
wireOnModel != DisplayPref::kWireframeOnShadedNone) {
MColor wireframeColor =
MHWRender::MGeometryUtilities::wireframeColor(path);
request.setColor(wireframeColor);
}
request.setMaterial( material );
queue.add( request );
}
// Transparent draw request
if (0) {
// Create the smooth shaded draw request
MDrawRequest request = info.getPrototype( *this );
request.setDrawData( data );
// This draw request will draw transparent sub nodes
request.setToken( shadedDrawToken );
request.setIsTransparent( true );
request.setMaterial( material );
queue.add( request );
}
}
// create a draw request for wireframe on shaded if
// necessary.
if (needWireframe &&
DisplayPref::wireframeOnShadedMode() != DisplayPref::kWireframeOnShadedNone)
{
MDrawRequest wireRequest = info.getPrototype( *this );
wireRequest.setDrawData( data );
wireRequest.setToken( kDrawWireframeOnShaded );
wireRequest.setDisplayStyle( M3dView::kWireFrame );
MColor wireframeColor = MHWRender::MGeometryUtilities::wireframeColor(path);
wireRequest.setColor(wireframeColor);
queue.add( wireRequest );
}
} break;
}
}
void ShapeUI::draw(const MDrawRequest & request, M3dView & view) const
{
// Initialize GL Function Table.
// InitializeGLFT();
// Get the token from the draw request.
// The token specifies what needs to be drawn.
DrawToken token = DrawToken(request.token());
switch( token )
{
case kBoundingBox :
drawBoundingBox( request, view );
break;
case kDrawWireframe :
case kDrawWireframeOnShaded :
drawWireframe( request, view );
break;
case kDrawSmoothShaded :
drawShaded( request, view, false );
break;
case kDrawSmoothShadedDepthOffset :
drawShaded( request, view, true );
break;
}
}
void ShapeUI::drawBoundingBox(const MDrawRequest & request, M3dView & view) const
{
// Get the surface shape
ShapeNode* node = (ShapeNode*)surfaceShape();
if (!node) return;
// Get the bounding box
MBoundingBox box = node->boundingBox();
view.beginGL();
{
// TODO: Draw BBox.
}
view.endGL();
}
void ShapeUI::drawWireframe(const MDrawRequest & request, M3dView & view) const
{
// Get the surface shape
ShapeNode* node = (ShapeNode*)surfaceShape();
if ( !node ) return;
MMatrix projMatrix;
view.projectionMatrix(projMatrix);
MMatrix modelViewMatrix;
view.modelViewMatrix(modelViewMatrix);
MMatrix localToPort = modelViewMatrix * projMatrix;
view.beginGL();
{
// USD render.
drawUSD(request, view, true);
}
view.endGL();
}
void ShapeUI::drawShaded(
const MDrawRequest & request, M3dView & view, bool depthOffset) const
{
// Get the surface shape
ShapeNode* node = (ShapeNode*)surfaceShape();
if ( !node ) return;
MMatrix projMatrix;
view.projectionMatrix(projMatrix);
MMatrix modelViewMatrix;
view.modelViewMatrix(modelViewMatrix);
MMatrix localToNDC = modelViewMatrix * projMatrix;
M3dView::LightingMode lightingMode;
view.getLightingMode(lightingMode);
unsigned int lightCount;
view.getLightCount(lightCount);
view.beginGL();
// USD render.
drawUSD(request, view, false);
view.endGL();
}
void ShapeUI::drawUSD(
const MDrawRequest& request,
const M3dView& view,
bool wireframe) const
{
// Get the surface shape
ShapeNode* node = (ShapeNode*)surfaceShape();
assert(node);
// Get USD stuff from the node.
UsdStageRefPtr stage = node->getStage();
UsdImagingGLSharedPtr renderer = node->getRenderer();
if (!renderer || !stage)
{
return;
}
GfMatrix4d viewMatrix;
GfMatrix4d projectionMatrix;
glGetDoublev(GL_MODELVIEW_MATRIX, viewMatrix.GetArray());
glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix.GetArray());
// Get the Maya viewport.
unsigned int originX;
unsigned int originY;
unsigned int width;
unsigned int height;
view.viewport(originX, originY, width, height);
// Put the camera and the viewport to the engine.
renderer->SetCameraState(
viewMatrix,
projectionMatrix,
GfVec4d(originX, originY, width, height));
const MColor wireframeColor = request.color();
// USD render.
UsdImagingGL::RenderParams params;
params.frame = UsdTimeCode(node->time * getCurrentFPS());
params.highlight = false;
if (wireframeColor.r > 1e-6f ||
wireframeColor.g > 1e-6f ||
wireframeColor.b > 1e-6f) {
// Wireframe color is not 0, so we need to draw the wireframe.
if (wireframe) {
// It's a wireframe-only mode.
params.drawMode = UsdImagingGLEngine::DRAW_WIREFRAME;
}
else {
// It's a wireframe with shading mode.
params.highlight = true;
params.drawMode = UsdImagingGLEngine::DRAW_WIREFRAME_ON_SURFACE;
}
params.wireframeColor =
GfVec4f(
wireframeColor.r,
wireframeColor.g,
wireframeColor.b,
1.0f);
}
else {
// No wireframe. Draw shaded only.
params.drawMode = UsdImagingGLEngine::DRAW_SHADED_SMOOTH;
}
renderer->Render(
stage->GetPrimAtPath(SdfPath::AbsoluteRootPath()),
params);
}
//
// Returns the point in world space corresponding to a given
// depth. The depth is specified as 0.0 for the near clipping plane and
// 1.0 for the far clipping plane.
//
MPoint ShapeUI::getPointAtDepth(
MSelectInfo &selectInfo,
double depth)
{
MDagPath cameraPath;
M3dView view = selectInfo.view();
view.getCamera(cameraPath);
MStatus status;
MFnCamera camera(cameraPath, &status);
// Ortho cam maps [0,1] to [near,far] linearly
// persp cam has non linear z:
//
// fp np
// -------------------
// 1. fp - d fp + d np
//
// Maps [0,1] -> [np,fp]. Then using linear mapping to get back to
// [0,1] gives.
//
// d np
// ---------------- for linear mapped distance
// fp - d fp + d np
if (!camera.isOrtho())
{
double np = camera.nearClippingPlane();
double fp = camera.farClippingPlane();
depth *= np / (fp - depth * (fp - np));
}
MPoint cursor;
MVector rayVector;
selectInfo.getLocalRay(cursor, rayVector);
cursor = cursor * selectInfo.multiPath().inclusiveMatrix();
short x,y;
view.worldToView(cursor, x, y);
MPoint res, neardb, fardb;
view.viewToWorld(x,y, neardb, fardb);
res = neardb + depth*(fardb-neardb);
return res;
}
bool ShapeUI::select(
MSelectInfo &selectInfo,
MSelectionList &selectionList,
MPointArray &worldSpaceSelectPts ) const
{
MSelectionMask mask(ShapeNode::selectionMaskName);
if (!selectInfo.selectable(mask)){
return false;
}
// Get the geometry information
//
ShapeNode* node = (ShapeNode*)surfaceShape();
const bool wireframeSelection =
(M3dView::kWireFrame == selectInfo.displayStyle() ||
!selectInfo.singleSelection());
// USD Selection.
MSelectionMask objectsMask(MSelectionMask::kSelectObjectsMask);
// selectable() takes MSelectionMask&, not const MSelectionMask. :(.
if (!selectInfo.selectable(objectsMask))
{
return false;
}
// Get USD stuff from the node.
UsdStageRefPtr stage = node->getStage();
UsdImagingGLSharedPtr renderer = node->getRenderer();
if (!renderer || !stage)
{
return false;
}
M3dView view = selectInfo.view();
GfMatrix4d viewMatrix;
GfMatrix4d projectionMatrix;
// We need to get the view and projection matrices for the area of the
// view that the user has clicked or dragged. Unfortunately the M3dView
// does not give us that in an easy way. If we extract the view and
// projection matrices from the M3dView object, it is just for the
// regular camera. MSelectInfo also gives us the selection box, so we
// could use that to construct the correct view and projection matrixes,
// but if we call beginSelect on the view as if we were going to use the
// selection buffer, Maya will do all the work for us and we can just
// extract the matrices from OpenGL.
// Hit record can just be one because we are not going to draw
// anything anyway. We only want the matrices
GLuint glHitRecord;
view.beginSelect(&glHitRecord, 1);
glGetDoublev(GL_MODELVIEW_MATRIX, viewMatrix.GetArray());
glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix.GetArray());
view.endSelect();
GfVec3d outHitPoint;
SdfPath outHitPrimPath;
UsdImagingGL::RenderParams params;
params.frame = UsdTimeCode(node->time * getCurrentFPS());
if (wireframeSelection)
{
params.drawMode = UsdImagingGLEngine::DRAW_WIREFRAME;
}
else
{
params.drawMode = UsdImagingGLEngine::DRAW_SHADED_SMOOTH;
}
bool didHit = renderer->TestIntersection(
viewMatrix,
projectionMatrix,
GfMatrix4d(1.0),
stage->GetPrimAtPath(SdfPath::AbsoluteRootPath()),
params,
&outHitPoint,
&outHitPrimPath);
// Sub-Selection
if (didHit && selectInfo.displayStatus() == M3dView::kLead)
{
UsdPrim prim;
// It can be an instance object. It's not allowed to get prim. We need
// to find the first valid prim.
while (true)
{
prim = stage->GetPrimAtPath(outHitPrimPath);
if (prim.IsValid())
{
break;
}
outHitPrimPath = outHitPrimPath.GetParentPath();
}
assert(prim.IsValid());
// Check the purpose of selected object.
if (prim.IsA<UsdGeomImageable>())
{
UsdGeomImageable imageable(prim);
if (imageable.ComputePurpose() == UsdGeomTokens->proxy)
{
// It's a proxy. Level up.
outHitPrimPath = outHitPrimPath.GetParentPath();
}
}
// If object was selected, set sub-selection.
node->setSubSelectedObjects(outHitPrimPath.GetText());
// Execute the callback to change the UI.
// selectPath() returns the tranform, multiPath() returns the shape.
MDagPath path = selectInfo.multiPath();
// Form the MEL command. It looks like this:
// callbacks
// -executeCallbacks
// -hook walterPanelSelectionChanged
// "objectName" "subSelectedObject";
MString command =
"callbacks -executeCallbacks "
"-hook walterPanelSelectionChanged \"";
command += path.fullPathName();
command += "\" \"";
command += outHitPrimPath.GetText();
command += "\";";
MGlobal::executeCommandOnIdle(command);
}
else
{
// If object was not selected, clear sub-selection.
node->setSubSelectedObjects("");
}
if (didHit)
{
MSelectionList newSelectionList;
newSelectionList.add(selectInfo.selectPath());
// Transform the hit point into the correct space and make it a maya
// point
MPoint mayaHitPoint =
MPoint(outHitPoint[0], outHitPoint[1], outHitPoint[2]);
selectInfo.addSelection(
newSelectionList,
mayaHitPoint,
selectionList,
worldSpaceSelectPts,
// Even though this is an "object", we use the "meshes"
// selection mask here. This allows us to select usd
// assemblies that are switched to "full" as well as those
// that are still collapsed.
MSelectionMask(MSelectionMask::kSelectMeshes),
false);
}
return didHit;
}
void ShapeNode::getExternalContent(MExternalContentInfoTable& table) const
{
addExternalContentForFileAttr(table, aCacheFileName);
MPxSurfaceShape::getExternalContent(table);
}
void ShapeNode::setExternalContent(const MExternalContentLocationTable& table)
{
setExternalContentForFileAttr(aCacheFileName, table);
MPxSurfaceShape::setExternalContent(table);
}
MStatus ShapeNode::setDependentsDirty(const MPlug& plug, MPlugArray& plugArray)
{
if (plug == aTransformsMatrix)
{
// We don't want to make is slow so here we only save the number of the
// dirty connection.
MPlug array = plug.parent();
unsigned int index = array.logicalIndex();
// We are here because the user changed something in the network. This
// block is not called when playing the animation. So we need to specify
// that nothing is cached in this plug.
fCachedFrames[index].clear();
// Set this plug dirty.
fDirtyTransforms.insert(index);
return MStatus::kSuccess;
}
return MPxSurfaceShape::setDependentsDirty(plug, plugArray);
}
void ShapeNode::updateUSDStage() const
{
// We need to do it only if something is dirty.
if (!fDirtyTransforms.empty())
{
RDOPROFILE("");
#ifdef PERFORM_PROFILING
using namespace std;
using ChronoClock = chrono::high_resolution_clock;
using ChronoMS = chrono::microseconds;
unsigned int executionDuration = 0;
ChronoClock::time_point startTime = ChronoClock::now();
#endif
MObject node = thisMObject();
const MPlug transforms(node, aTransforms);
// Save all the matrices to the map.
std::unordered_map<std::string, MMatrix> matrices(
fDirtyTransforms.size());
for (int i : fDirtyTransforms)
{
const MPlug element = transforms.elementByLogicalIndex(i);
const MPlug objectPlug =
element.child(ShapeNode::aTransformsObject);
std::string subObjectName = objectPlug.asString().asChar();
if(subObjectName.empty())
{
continue;
}
const MPlug matrixPlug =
element.child(ShapeNode::aTransformsMatrix);
#ifdef PERFORM_PROFILING
ChronoClock::time_point executionTime = ChronoClock::now();
#endif
// Maya magic to get a matrix from the plug.
MObject matrixObject;
matrixPlug.getValue(matrixObject);
MFnMatrixData matrixData(matrixObject);
MTransformationMatrix transformationMatrix =
matrixData.transformation();
// Finally! It's the actual matrix.
matrices[subObjectName] = transformationMatrix.asMatrix();
#ifdef PERFORM_PROFILING
ChronoClock::time_point finishTime = ChronoClock::now();
executionDuration +=
chrono::duration_cast<ChronoMS>(finishTime - executionTime)
.count();
#endif
}
updateUSDTransforms(this, matrices);
// Save and clear the cache.
fPreviousDirtyTransforms = fDirtyTransforms;
fDirtyTransforms.clear();
#ifdef PERFORM_PROFILING
ChronoClock::time_point usdTime = ChronoClock::now();
#endif
#ifdef PERFORM_PROFILING
ChronoClock::time_point finishTime = ChronoClock::now();
unsigned int usdDuration =
chrono::duration_cast<ChronoMS>(usdTime - startTime).count();
unsigned int totalDuration =
chrono::duration_cast<ChronoMS>(finishTime - startTime).count();
printf(
"[WALTER]: profiling of updateUSDStage: total:%ims "
"execution:%.02f%% "
"updateUSDTransforms:%.02f%%\n",
totalDuration / 1000,
float(executionDuration) * 100 / totalDuration,
float(usdDuration) * 100 / totalDuration);
#endif
}
}
void ShapeNode::updateTextures(bool iTexturesEnabled) const
{
if (iTexturesEnabled != mTexturesEnabled)
{
mTexturesEnabled = iTexturesEnabled;
muteGLSLShaders(this, mTexturesEnabled);
}
if (mTexturesEnabled && mDirtyTextures)
{
processGLSLShaders(this);
mDirtyTextures = false;
}
}
void ShapeNode::setCachedFramesDirty()
{
RDOPROFILE("");
// Save and clear the cache.
fPreviousDirtyTransforms = fDirtyTransforms;
fDirtyTransforms.clear();
fCachedFrames.clear();
// Re-freeze transforms if it's necessary.
if (this->fFrozen)
{
freezeUSDTransforms(this);
}
else
{
unfreezeUSDTransforms(this);
}
}
void ShapeNode::onTimeChanged(double previous)
{
if (this->time == previous)
{
// There is a bug when the object was moved in one axis during the keyed
// animation, Maya ignores manual moving with the same axis.
// Investigation showed that in this case, Maya sends the signal that
// the time is changed, not the matrix. It looks like it's really the
// Maya bug. We use a workaround to resolve it. When we receive the
// signal that the time is changed, but the time value is the same, we
// update the matrices that were updated last time.
// TODO: Do we need fCachedFrames[].clear() here? Looks like not because
// it was already done in the setDependentsDirty. It's called each time
// before we get here.
fDirtyTransforms.insert(
fPreviousDirtyTransforms.begin(), fPreviousDirtyTransforms.end());
return;
}
// Iterate through all the transforms.
MPlug transforms(thisMObject(), aTransforms);
for (int i = 0, n = transforms.numElements(); i < n; i++)
{
// Check if this plug for this frame is cached.
std::set<double>& cachedFrames = fCachedFrames[i];
if (cachedFrames.find(this->time) != cachedFrames.end())
{
// Cached.
continue;
}
// Not cached. Make it dirty and set as cached.
fDirtyTransforms.insert(i);
cachedFrames.insert(this->time);
}
}
void ShapeNode::onLoaded()
{
RDOPROFILE("");
// Relod assignments and groups of the stage.
extractAssignments(this);
// Recompute the USD shaders.
mDirtyTextures = true;
// Refresh the renderer.
mRendererNeedsUpdate = true;
// Update it in the viewport. We need it to update the bounding box.
MHWRender::MRenderer::setGeometryDrawDirty(thisMObject());
}
void ShapeNode::setJustLoaded()
{
mJustLoaded=true;
// Update it in the viewport. We need it to update the bounding box.
MHWRender::MRenderer::setGeometryDrawDirty(thisMObject());
MFnDependencyNode nodeFn(thisMObject());
if(MFn::kPluginShape == thisMObject().apiType()) {
MString cmd =
"callbacks -executeCallbacks -hook \"WALTER_SCENE_CHANGED\" \"UPDATE_ITEMS\" \"" + nodeFn.name() + "\"";
MGlobal::executeCommandOnIdle(cmd);
}
}
void ShapeNode::refresh()
{
// Refresh the renderer.
mRendererNeedsUpdate = true;
// Update it in the viewport. We need it to update the bounding box.
MHWRender::MRenderer::setGeometryDrawDirty(thisMObject());
}
MStatus ShapeNode::connectionMade(
const MPlug& plug,
const MPlug& otherPlug,
bool asSrc)
{
if (plug == aTime)
{
// It will evaluate setInternalValueInContext and set the internal time.
// Without this the time is uninitialized when the scene is opened.
MTime time;
plug.getValue(time);
return MStatus::kSuccess;
}
else if (plug == aLayersAssignationSCShader)
{
// We need to copletely recompute the shaders because otherwise Hydra
// doesn't update the scene.
// TODO: We need to figure out how to fix it.
mDirtyTextures = true;
}
return MPxSurfaceShape::connectionMade(plug, otherPlug, asSrc);
}
MStatus ShapeNode::connectionBroken(
const MPlug& plug,
const MPlug& otherPlug,
bool asSrc)
{
if (plug == aTransformsMatrix)
{
// Reset name when the connection with matrix is broken.
const MPlug array = plug.parent();
MPlug objectPlug = array.child(aTransformsObject);
objectPlug.setString("");
return MStatus::kSuccess;
}
else if (plug == aLayersAssignationSCShader)
{
// We need to copletely recompute the shaders because otherwise Hydra
// doesn't update the scene.
// TODO: We need to figure out how to fix it.
mDirtyTextures = true;
}
return MPxSurfaceShape::connectionBroken(plug, otherPlug, asSrc);
}
const MString ShapeNode::resolvedCacheFileName() const
{
// If we have several archives, we need to split them and resolve the files
// separately. Split the string with ":" symbol, expand all the filenames
// and join it back.
// We don't use MString::split() because it skips empty lines. We need
// everything, otherwise we have errors in matching visibilities and layers.
std::vector<std::string> archives;
std::string cacheFileName(fCacheFileName.asChar());
boost::split(archives, cacheFileName, boost::is_any_of(":"));
MString resolvedFileName;
for (unsigned i = 0; i < archives.size(); i++)
{
if (fVisibilities.length() > i && !fVisibilities[i])
{
continue;
}
if (resolvedFileName.length())
{
resolvedFileName += ":";
}
resolvedFileName += archives[i].c_str();
}
return resolvedFileName;
}
void ShapeNode::setStage(UsdStageRefPtr iStage)
{
mRendererNeedsUpdate = true;
mStage = iStage;
}
UsdStageRefPtr ShapeNode::getStage() const
{
return mStage;
}
UsdImagingGLSharedPtr ShapeNode::getRenderer()
{
if (mJustLoaded)
{
mJustLoaded = false;
// Call onLoaded from here because USD doesn't like when it's called
// from not main thread.
onLoaded();
}
if (mRendererNeedsUpdate || !mRenderer)
{
// Updated. No need to update mode.
mRendererNeedsUpdate = false;
// Create the new instance of the Hydra renderer.
mRenderer = boost::make_shared<UsdImagingGL>();
// Get the name of the necessary Hydra plugin.
MFnDagNode fn(thisMObject());
MPlug plug = fn.findPlug(aHydraPlugin);
std::string hydraPlugin = plug.asString().asChar();
// Set Hydra plugin if it exists.
if(!hydraPlugin.empty())
{
for (const TfToken& current : mRenderer->GetRendererPlugins())
{
if( current.GetString() == hydraPlugin)
{
mRenderer->SetRendererPlugin(current);
break;
}
}
}
}
return mRenderer;
}
}
<|start_filename|>walter/katana/WalterIn/CameraCook.cpp<|end_filename|>
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ScalarPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
///////////////////////////////////////////////////////////////////////////////
void evalCamera(Alembic::AbcGeom::ICameraSchema & iSchema,
const OpArgs & iArgs,
FnAttribute::GroupBuilder & oGb)
{
Alembic::Abc::TimeSamplingPtr ts = iSchema.getTimeSampling();
SampleTimes sampleTimes;
iArgs.getRelevantSampleTimes(ts, iSchema.getNumSamples(), sampleTimes);
bool multiSample = sampleTimes.size() > 1;
oGb.set("geometry.projection", FnAttribute::StringAttribute("perspective"));
//geometry attributes which are meaningful to katana
FnAttribute::DoubleBuilder fovBuilder;
FnAttribute::DoubleBuilder nearBuilder;
FnAttribute::DoubleBuilder farBuilder;
FnAttribute::DoubleBuilder leftBuilder;
FnAttribute::DoubleBuilder rightBuilder;
FnAttribute::DoubleBuilder bottomBuilder;
FnAttribute::DoubleBuilder topBuilder;
//info attributes just for tracking purposes
FnAttribute::DoubleBuilder focalLengthBuilder;
FnAttribute::DoubleBuilder horizontalApertureBuilder;
FnAttribute::DoubleBuilder horizontalFilmOffsetBuilder;
FnAttribute::DoubleBuilder verticalApertureBuilder;
FnAttribute::DoubleBuilder verticalFilmOffsetBuilder;
FnAttribute::DoubleBuilder lensSqueezeRatioBuilder;
FnAttribute::DoubleBuilder overscanLeftBuilder;
FnAttribute::DoubleBuilder overscanRightBuilder;
FnAttribute::DoubleBuilder overscanTopBuilder;
FnAttribute::DoubleBuilder overscanBottomBuilder;
FnAttribute::DoubleBuilder fStopBuilder;
FnAttribute::DoubleBuilder focusDistanceBuilder;
FnAttribute::DoubleBuilder shutterOpenBuilder;
FnAttribute::DoubleBuilder shutterCloseBuilder;
std::map<std::string, FnAttribute::DoubleBuilder> filmBackBuilders;
for (SampleTimes::iterator I = sampleTimes.begin();
I != sampleTimes.end(); ++I)
{
Alembic::Abc::chrono_t inputSampleTime = (*I);
Alembic::Abc::ISampleSelector sampleSelector(inputSampleTime);
float relativeSampleTime = multiSample ?
iArgs.getRelativeSampleTime(inputSampleTime) : 0;
Alembic::AbcGeom::CameraSample sample =
iSchema.getValue(sampleSelector);
fovBuilder.get(relativeSampleTime).push_back(
sample.getFieldOfView());
nearBuilder.get(relativeSampleTime).push_back(
sample.getNearClippingPlane());
farBuilder.get(relativeSampleTime).push_back(
sample.getFarClippingPlane());
double top, bottom, left, right;
sample.getScreenWindow(top, bottom, left, right);
topBuilder.get(relativeSampleTime).push_back(top);
bottomBuilder.get(relativeSampleTime).push_back(bottom);
leftBuilder.get(relativeSampleTime).push_back(left);
rightBuilder.get(relativeSampleTime).push_back(right);
focalLengthBuilder.get(relativeSampleTime).push_back(
sample.getFocalLength());
horizontalApertureBuilder.get(relativeSampleTime).push_back(
sample.getHorizontalAperture());
horizontalFilmOffsetBuilder.get(relativeSampleTime).push_back(
sample.getHorizontalFilmOffset());
verticalApertureBuilder.get(relativeSampleTime).push_back(
sample.getVerticalAperture());
verticalFilmOffsetBuilder.get(relativeSampleTime).push_back(
sample.getVerticalFilmOffset());
lensSqueezeRatioBuilder.get(relativeSampleTime).push_back(
sample.getLensSqueezeRatio());
overscanLeftBuilder.get(relativeSampleTime).push_back(
sample.getOverScanLeft());
overscanRightBuilder.get(relativeSampleTime).push_back(
sample.getOverScanRight());
overscanTopBuilder.get(relativeSampleTime).push_back(
sample.getOverScanTop());
overscanBottomBuilder.get(relativeSampleTime).push_back(
sample.getOverScanBottom());
fStopBuilder.get(relativeSampleTime).push_back(
sample.getFStop());
focusDistanceBuilder.get(relativeSampleTime).push_back(
sample.getFocusDistance());
shutterOpenBuilder.get(relativeSampleTime).push_back(
sample.getShutterOpen() * iArgs.fps);
shutterCloseBuilder.get(relativeSampleTime).push_back(
sample.getShutterClose() * iArgs.fps);
for (std::size_t j = 0; j < sample.getNumOps(); ++j)
{
Alembic::AbcGeom::FilmBackXformOp fbop = sample.getOp(j);
// on the first sample, make sure our data builder is set up with
// the correct tuple
if (I == sampleTimes.begin())
{
int64_t tupleSize = fbop.getNumChannels();
// display the matrix as 3x3 instead of 1x9
if (tupleSize == 9)
{
tupleSize = 3;
}
filmBackBuilders[fbop.getHint()] =
FnAttribute::DoubleBuilder(tupleSize);
}
std::vector<double> & vals =
filmBackBuilders[fbop.getHint()].get(relativeSampleTime);
for (std::size_t k = 0; k < fbop.getNumChannels(); ++k)
{
vals.push_back(fbop.getChannelValue(k));
}
}
}
oGb.set("geometry.fov", fovBuilder.build());
oGb.set("geometry.near", nearBuilder.build());
oGb.set("geometry.far", farBuilder.build());
oGb.set("geometry.left", leftBuilder.build());
oGb.set("geometry.right", rightBuilder.build());
oGb.set("geometry.bottom", bottomBuilder.build());
oGb.set("geometry.top", topBuilder.build());
oGb.set("info.abcCamera.focalLength",focalLengthBuilder.build());
oGb.set("info.abcCamera.horizontalAperture",
horizontalApertureBuilder.build());
oGb.set("info.abcCamera.horizontalFilmOffset",
horizontalFilmOffsetBuilder.build());
oGb.set("info.abcCamera.verticalAperture",
verticalApertureBuilder.build());
oGb.set("info.abcCamera.verticalFilmOffset",
verticalFilmOffsetBuilder.build());
oGb.set("info.abcCamera.lensSqueezeRatio",
lensSqueezeRatioBuilder.build());
oGb.set("info.abcCamera.overscanLeft", overscanLeftBuilder.build());
oGb.set("info.abcCamera.overscanRight", overscanRightBuilder.build());
oGb.set("info.abcCamera.overscanTop", overscanTopBuilder.build());
oGb.set("info.abcCamera.overscanBottom", overscanBottomBuilder.build());
oGb.set("info.abcCamera.fStop", fStopBuilder.build());
oGb.set("info.abcCamera.focusDistance", focusDistanceBuilder.build());
oGb.set("info.abcCamera.shutterOpen", shutterOpenBuilder.build());
oGb.set("info.abcCamera.shutterClose", shutterCloseBuilder.build());
std::map<std::string, FnAttribute::DoubleBuilder>::iterator dbit;
for (dbit = filmBackBuilders.begin(); dbit != filmBackBuilders.end();
++dbit)
{
oGb.set("info.abcCamera." + dbit->first, dbit->second.build());
}
}
void cookCamera(AbcCookPtr ioCook, FnAttribute::GroupBuilder & oStaticGb)
{
Alembic::AbcGeom::ICameraPtr objPtr(
new Alembic::AbcGeom::ICamera(*(ioCook->objPtr),
Alembic::AbcGeom::kWrapExisting));
oStaticGb.set("type", FnAttribute::StringAttribute("camera"));
Alembic::AbcGeom::ICameraSchema schema = objPtr->getSchema();
Alembic::Abc::ICompoundProperty userProp = schema.getUserProperties();
Alembic::Abc::ICompoundProperty arbGeom = schema.getArbGeomParams();
std::string abcUser = "abcUser.";
processUserProperties(ioCook, userProp, oStaticGb, abcUser);
processArbGeomParams(ioCook, arbGeom, oStaticGb);
if (schema.isConstant())
{
OpArgs defaultArgs;
evalCamera(schema, defaultArgs, oStaticGb);
}
else
{
ioCook->objPtr = objPtr;
ioCook->animatedSchema = true;
}
}
}
<|start_filename|>walter/maya/walterMtoaConnection/pluginMain.cpp<|end_filename|>
/*Abc Shader Exporter
Copyright (c) 2014, <NAME>, All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.*/
#include "abcCacheExportCmd.h"
#include "convertToArnold.h"
#include <maya/MFnPlugin.h>
//#include <maya/MSceneMessage.h>
#include <maya/MGlobal.h>
#include <maya/MString.h>
#ifdef _WIN32
#define DLLEXPORT __declspec(dllexport)
#else
#undef DLLEXPORT
#define DLLEXPORT __attribute__ ((visibility("default")))
#endif
DLLEXPORT MStatus initializePlugin( MObject obj )
//
// Description:
// this method is called when the plug-in is loaded into Maya. It
// registers all of the services that this plug-in provides with
// Maya.
//
// Arguments:
// obj - a handle to the plug-in object (use MFnPlugin to access it)
//
{
MStatus status;
MFnPlugin plugin( obj, "RodeoFX", "2017", "Any");
plugin.registerCommand( "walterSaveShaders", abcCacheExportCmd::creator, abcCacheExportCmd::mySyntax);
plugin.registerCommand(
"walterConvertToArnold",
ConvertToArnoldCmd::creator,
ConvertToArnoldCmd::syntax);
return status;
}
DLLEXPORT MStatus uninitializePlugin( MObject obj)
//
// Description:
// this method is called when the plug-in is unloaded from Maya. It
// deregisters all of the services that it was providing.
//
// Arguments:
// obj - a handle to the plug-in object (use MFnPlugin to access it)
//
{
MStatus status;
MFnPlugin plugin( obj );
status = plugin.deregisterCommand("walterSaveShaders");
if (!status) {
status.perror("deregisterCommand");
return status;
}
status = plugin.deregisterCommand("walterConvertToArnold");
if (!status)
{
status.perror("deregisterCommand walterConvertToArnold");
return status;
}
return status;
}
<|start_filename|>walter/alembic/IWalterExpressionsSchema.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __IWALTEREXPRESSIONSSCHEMA_H_
#define __IWALTEREXPRESSIONSSCHEMA_H_
#include "IWalterLayersSchema.h"
#include "OWalterExpressionsSchema.h"
#include "SchemaInfoDeclarations.h"
#include <Alembic/Abc/ISchemaObject.h>
// Schema for reading and querying shader assignments from either an object or
// compound property.
class ALEMBIC_EXPORT IWalterExpressionsSchema :
public Alembic::Abc::ISchema<WalterExpressionsSchemaInfo>
{
public:
typedef IWalterExpressionsSchema this_type;
IWalterExpressionsSchema() {}
// This constructor creates a new assignments reader.
// The first argument is the parent ICompoundProperty, from which the error
// handler policy for is derived. The second argument is the name of the
// ICompoundProperty that contains this schemas properties. The remaining
// optional arguments can be used to override the ErrorHandlerPolicy and to
// specify schema interpretation matching.
IWalterExpressionsSchema(
const ICompoundProperty &iParent,
const std::string &iName,
const Alembic::Abc::Argument &iArg0 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg1 = Alembic::Abc::Argument() ) :
Alembic::Abc::ISchema<WalterExpressionsSchemaInfo>(
iParent, iName, iArg0, iArg1)
{
init();
}
// This constructor wraps an existing ICompoundProperty as the assignments
// reader, and the error handler policy is derived from it. The remaining
// optional arguments can be used to override the ErrorHandlerPolicy and to
// specify schema interpretation matching.
IWalterExpressionsSchema(
const ICompoundProperty &iProp,
const Alembic::Abc::Argument &iArg0 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg1 = Alembic::Abc::Argument() ) :
Alembic::Abc::ISchema<WalterExpressionsSchemaInfo>(iProp, iArg0, iArg1)
{
init();
}
// Copy constructor.
IWalterExpressionsSchema( const IWalterExpressionsSchema& iCopy ) :
Alembic::Abc::ISchema<WalterExpressionsSchemaInfo>()
{
*this = iCopy;
}
const std::string& getExpression(size_t n) const;
bool getHasGroup(size_t n) const;
const std::string& getExpressionGroup(size_t n) const;
IWalterLayersSchema getLayerSchema(size_t n) const;
private:
void init();
// It's vector for accessing by index.
std::vector<std::string> mExpressionKeys;
std::vector<std::string> mExpressions;
std::vector<bool> mGrouped;
std::vector<std::string> mGroupNames;
};
typedef Alembic::Abc::ISchemaObject<IWalterExpressionsSchema>
IWalterExpressions;
// Returns true and fills result within the given compound property.
bool hasExpressions(
Alembic::Abc::ICompoundProperty iCompound,
IWalterExpressionsSchema& oResult,
const std::string& iPropName = EXPRESSIONS_PROPNAME);
// Returns true and fills result within the given compound property.
bool hasExpressions(
Alembic::Abc::IObject iObject,
IWalterExpressionsSchema& oResult,
const std::string& iPropName = EXPRESSIONS_PROPNAME);
#endif
<|start_filename|>walter/katana/WalterIn/walterCompatibility.h<|end_filename|>
// Copyright 2018 <NAME>. All rights reserved.
#include <FnAPI/FnAPI.h>
// The logging is refactored in Katana 3. And it's not compiling anymore. This
// file brings Katana2 logging back.
#if KATANA_VERSION_MAJOR == 3
#include <string>
namespace Foundry
{
namespace Katana
{
namespace FnLogging
{
class FnLog
{
public:
FnLog(std::string const& module = "");
~FnLog();
void log(std::string const& message, unsigned int severity) const;
};
}
}
}
#endif
<|start_filename|>walter/usd/tests/test_usdProperties.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/variantSets.h>
#include <pxr/usd/usd/stage.h>
#include "walterUSDCommonUtils.h"
#include <string>
#include <vector>
#include <gtest/gtest.h>
PXR_NAMESPACE_USING_DIRECTIVE
TEST(propertiesUSD, test_usdProperties)
{
std::string stageAsStr = R"(#usda 1.0
(
endTimeCode = 1
startTimeCode = 1
upAxis = "Y"
)
def Xform "triangle" (
customData = {
bool zUp = 0
}
)
{
def Mesh "mesh0"
{
float3[] extent.timeSamples = {
1: [(-0.5, 0, 0), (0.5, 0.7853982, 0)],
}
int[] faceVertexCounts.timeSamples = {
1: [3],
}
int[] faceVertexIndices.timeSamples = {
1: [0, 1, 2],
}
uniform token orientation = "leftHanded"
point3f[] points.timeSamples = {
1: [(-0.5, 0, 0), (0.5, 0, 0), (0, 0.7853982, 0)],
}
uniform token subdivisionScheme = "none"
}
}
)";
UsdStageRefPtr stage = UsdStage::CreateInMemory();
SdfLayerHandle handle = stage->GetSessionLayer();
handle->ImportFromString(stageAsStr);
std::vector<std::string> properties = WalterUSDCommonUtils::propertiesUSD(
stage,
"/triangle/mesh0",
0,
true);
EXPECT_EQ(properties[0], "{ \"name\": \"cornerIndices\", \"type\": \"VtArray<int>\", \"arraySize\": 0, \"value\": [] }");
EXPECT_EQ(properties[1], "{ \"name\": \"cornerSharpnesses\", \"type\": \"VtArray<float>\", \"arraySize\": 0, \"value\": [] }");
EXPECT_EQ(properties[2], "{ \"name\": \"creaseIndices\", \"type\": \"VtArray<int>\", \"arraySize\": 0, \"value\": [] }");
EXPECT_EQ(properties[3], "{ \"name\": \"creaseLengths\", \"type\": \"VtArray<int>\", \"arraySize\": 0, \"value\": [] }");
EXPECT_EQ(properties[4], "{ \"name\": \"creaseSharpnesses\", \"type\": \"VtArray<float>\", \"arraySize\": 0, \"value\": [] }");
EXPECT_EQ(properties[5], "{ \"name\": \"doubleSided\", \"type\": \"bool\", \"arraySize\": -1, \"value\": 0 }");
EXPECT_EQ(properties[6], "{ \"name\": \"extent\", \"type\": \"VtArray<GfVec3f>\", \"arraySize\": 2, \"value\": [[-0.500000, 0.000000, 0.000000]] }");
EXPECT_EQ(properties[7], "{ \"name\": \"faceVaryingLinearInterpolation\", \"type\": \"TfToken\", \"arraySize\": -1, \"value\": \"\" }");
EXPECT_EQ(properties[8], "{ \"name\": \"faceVertexCounts\", \"type\": \"VtArray<int>\", \"arraySize\": 1, \"value\": [3] }");
EXPECT_EQ(properties[9], "{ \"name\": \"faceVertexIndices\", \"type\": \"VtArray<int>\", \"arraySize\": 3, \"value\": [0] }");
EXPECT_EQ(properties[10], "{ \"name\": \"holeIndices\", \"type\": \"VtArray<int>\", \"arraySize\": 0, \"value\": [] }");
}
<|start_filename|>walter/houdini/src/walterHoudiniUtils.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterHoudiniUtils.h"
#include "walterUSDCommonUtils.h"
#include <pxr/base/tf/instantiateSingleton.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usdGeom/curves.h>
#include <pxr/usd/usdGeom/mesh.h>
#include <boost/range/adaptors.hpp>
// Cache for USD data
class USDDataRegistry : boost::noncopyable
{
public:
typedef USDDataRegistry This;
static This& getInstance()
{
return TfSingleton<This>::GetInstance();
}
// Return the stage
UsdStageRefPtr getStage(const std::string& stageName)
{
auto it = mStages.find(stageName);
if (it == mStages.end())
{
SdfLayerRefPtr root = WalterUSDCommonUtils::getUSDLayer(stageName);
auto result = mStages.emplace(stageName, UsdStage::Open(root));
it = result.first;
}
return it->second;
}
// Return the Hydra renderer
UsdImagingGLRefPtr getRenderer(const std::string& stageName)
{
auto it = mRenderers.find(stageName);
if (it == mRenderers.end())
{
auto result =
mRenderers.emplace(stageName, std::make_shared<UsdImagingGL>());
it = result.first;
}
return it->second;
}
private:
// We need to cache the stage because we don't load it from the disk
// directly, instead, we generate it in the memory from the pipeline layers.
// That's why standard USD stage caching system doesn't work for us.
std::unordered_map<std::string, UsdStageRefPtr> mStages;
// We need renderers cache because it should be a separate renderer object
// per stage, otherwise it crashes. And we need a separate cache because it
// should be initialized in the correct OpenGL context, so we can't
// initialize it when we initialize the stage.
std::unordered_map<std::string, UsdImagingGLRefPtr> mRenderers;
};
TF_INSTANTIATE_SINGLETON(USDDataRegistry);
UsdStageRefPtr WalterHoudiniUtils::getStage(const std::string& stageName)
{
return USDDataRegistry::getInstance().getStage(stageName);
}
UsdImagingGLRefPtr WalterHoudiniUtils::getRenderer(const std::string& stageName)
{
return USDDataRegistry::getInstance().getRenderer(stageName);
}
void WalterHoudiniUtils::getObjectList(
const std::string& stageName,
const std::string& primPath,
bool geomOnly,
std::vector<std::string>& oList)
{
UsdStageRefPtr stage = getStage(stageName);
// TODO: reserve
UsdPrim root;
if (!primPath.empty() && SdfPath::IsValidPathString(primPath))
{
root = stage->GetPrimAtPath(SdfPath(primPath));
}
else
{
root = stage->GetPseudoRoot();
}
UsdPrimRange range(root);
for (const UsdPrim& prim : range)
{
if (!geomOnly || prim.IsA<UsdGeomMesh>() || prim.IsA<UsdGeomCurves>())
{
oList.push_back(prim.GetPath().GetString());
}
}
}
<|start_filename|>walter/alembic/OWalterExpressionsSchema.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "OWalterExpressionsSchema.h"
#include "OWalterLayersSchema.h"
#include <Alembic/AbcCoreLayer/Util.h>
#include <boost/algorithm/string.hpp>
#include "PathUtil.h"
OWalterExpressionsSchema::OWalterExpressionsSchema(
Alembic::AbcCoreAbstract::CompoundPropertyWriterPtr iParent,
const std::string &iName,
const Alembic::Abc::Argument &iArg0,
const Alembic::Abc::Argument &iArg1,
const Alembic::Abc::Argument &iArg2,
const Alembic::Abc::Argument &iArg3 ) :
Alembic::Abc::OSchema<WalterExpressionsSchemaInfo>(
iParent, iName, iArg0, iArg1, iArg2, iArg3 )
{
}
OWalterExpressionsSchema::OWalterExpressionsSchema(
Alembic::Abc::OCompoundProperty iParent,
const std::string &iName,
const Alembic::Abc::Argument &iArg0,
const Alembic::Abc::Argument &iArg1,
const Alembic::Abc::Argument &iArg2 ) :
Alembic::Abc::OSchema<WalterExpressionsSchemaInfo>(
iParent.getPtr(),
iName,
GetErrorHandlerPolicy( iParent ),
iArg0,
iArg1,
iArg2 )
{
}
OWalterExpressionsSchema::~OWalterExpressionsSchema()
{
// Put everything we have to Alembic.
if (mExpressions.empty()) {
// Nothing to do
return;
}
// The shaders should be with "replace" metadata.
Alembic::Abc::MetaData md;
Alembic::AbcCoreLayer::SetReplace( md, true );
for (auto eit=mExpressions.cbegin(); eit!=mExpressions.cend(); eit++) {
std::string expression = eit->first;
const ExpressionData& expressionData = eit->second;
const LayerMap& layers = expressionData.layerMap;
// Save layers
if (layers.empty()) {
// Nothing to do
continue;
}
expression = WalterCommon::mangleString(
WalterCommon::convertRegex(expression));
Alembic::Abc::OCompoundProperty expProperty(this->getPtr(), expression);
OWalterLayersSchema layersSchema = addLayers(expProperty);
for (auto it=layers.cbegin(); it!=layers.cend(); it++) {
const LayerKey& key = it->first;
const std::string& value = it->second;
layersSchema.setShader(key.first, key.second, value, md);
}
// Save groups
if (expressionData.grouped)
{
Alembic::Abc::OCompoundProperty group(
expProperty, EXPRESSIONS_GROUP, md);
Alembic::Abc::OStringProperty groupProp(
group, EXPRESSIONS_GROUPNAME);
groupProp.set(expressionData.groupname);
}
}
}
void OWalterExpressionsSchema::setExpressionShader(
const std::string & iExpression,
const std::string & iLayer,
const std::string & iShaderType,
const std::string & iShaderName)
{
// Save it to the internal map.
mExpressions[iExpression].layerMap[LayerKey(iLayer, iShaderType)] =
iShaderName;
}
void OWalterExpressionsSchema::setExpressionGroup(
const std::string & iExpression,
const std::string & iGroup)
{
mExpressions[iExpression].grouped = true;
mExpressions[iExpression].groupname = iGroup;
}
OWalterExpressionsSchema addExpressions(
Alembic::Abc::OCompoundProperty iProp,
const std::string& iPropName )
{
return OWalterExpressionsSchema( iProp.getPtr(), iPropName );
}
OWalterExpressionsSchema addExpressions(
Alembic::Abc::OObject iObject,
const std::string& iPropName )
{
return addExpressions( iObject.getProperties(), iPropName );
}
<|start_filename|>walter/maya/walterStandin/walterOverrideNode.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef _WALTEROVERRIDENODE_H_
#define _WALTEROVERRIDENODE_H_
#include <maya/MPxNode.h>
#include <maya/MTypeId.h>
class WalterOverride : public MPxNode {
public:
WalterOverride();
virtual ~WalterOverride();
static void* creator();
static MStatus initialize();
virtual void postConstructor();
static MTypeId mId;
private:
static void nameChanged(MObject& node, void *data);
};
#endif
<|start_filename|>walter/viewer/Scene.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "Scene.h"
#include "FreeCamera.h"
#include "walterUSDCommonUtils.h"
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usdGeom/bboxCache.h>
#include <pxr/usd/usdGeom/camera.h>
namespace walter_viewer
{
Scene::Scene(
const Options& opt,
FreeCameraPtr camera)
{
SdfLayerRefPtr root = WalterUSDCommonUtils::getUSDLayer(opt.filePath);
mStage = UsdStage::Open(root);
if(camera)
{
mCamera = camera;
mCamera->reset();
mRenderer = std::make_shared<UsdImagingGL>();
setRenderer(opt.renderer);
mParams.frame = opt.frame;
mParams.complexity = opt.complexity;
mParams.highlight = true;
mDefaultPrim = mStage->GetDefaultPrim();
if (!mDefaultPrim)
{
mDefaultPrim = mStage->GetPseudoRoot();
}
}
}
void Scene::setRenderer(const std::string& name)
{
if (name == "Embree")
{
mRenderer->SetRendererPlugin(TfToken("HdEmbreeRendererPlugin"));
}
else
{
mRenderer->SetRendererPlugin(TfToken("HdStreamRendererPlugin"));
}
}
void Scene::resetCamera()
{
mCamera->reset();
}
void Scene::updateCamera(int height)
{
mCamera->updateZoom();
mCamera->updatePan(height);
mCamera->updateTumble();
}
void Scene::frameSelection()
{
GfBBox3d bbox = computeStageBBox();
if (bbox.GetRange().IsEmpty())
{
bbox = getDefaultBBox();
}
auto center = bbox.ComputeCentroid();
mCamera->controler().setCenter(center[0], center[1], center[2]);
const float frameFit = 1.1f;
float fov = mCamera->GetFieldOfView(GfCamera::FOVVertical);
float halfFov = fov > 0 ? fov * 0.5f : 0.5f;
auto range = bbox.ComputeAlignedRange();
std::array<double, 3> rangeArray{
{range.GetSize()[0], range.GetSize()[1], range.GetSize()[1]}};
auto maxSize = *std::max_element(rangeArray.begin(), rangeArray.end());
float dist = (maxSize * frameFit * 0.5) /
atan(GfDegreesToRadians(static_cast<double>(halfFov)));
mCamera->SetFocusDistance(dist);
}
void Scene::select(double xpos, double ypos, int width, int height)
{
GfVec2d point(xpos / double(width), ypos / double(height));
point[0] = (point[0] * 2.0 - 1.0);
point[1] = -1.0 * (point[1] * 2.0 - 1.0);
auto size = GfVec2d(1.0 / width, 1.0 / height);
auto pickFrustum =
mCamera->GetFrustum().ComputeNarrowedFrustum(point, size);
GfVec3d hitPoint;
SdfPath hitPrimPath;
SdfPath hitInstancerPath;
int hitInstanceIndex;
int hitElementIndex;
auto results = mRenderer->TestIntersection(
pickFrustum.ComputeViewMatrix(),
pickFrustum.ComputeProjectionMatrix(),
GfMatrix4d(1.0),
mStage->GetPseudoRoot(),
mParams,
&hitPoint,
&hitPrimPath,
&hitInstancerPath,
&hitInstanceIndex,
&hitElementIndex);
mRenderer->ClearSelected();
if (!hitPrimPath.IsEmpty())
{
SdfPathVector selection;
selection.push_back(hitPrimPath);
mRenderer->SetSelected(selection);
printf("[Walter] Prim path:%s\n", hitPrimPath.GetText());
}
}
void Scene::updateSubdiv(float value)
{
mParams.complexity += value;
if (mParams.complexity < 1.f)
{
mParams.complexity = 1.f;
}
else if (mParams.complexity > 2.f)
{
mParams.complexity = 2.f;
}
}
void Scene::setDrawMode(UsdImagingGLEngine::DrawMode value)
{
mParams.drawMode = value;
}
void Scene::draw(int width, int height)
{
auto frustum = mCamera->GetFrustum();
mRenderer->SetCameraState(
frustum.ComputeViewMatrix(),
frustum.ComputeProjectionMatrix(),
GfVec4d(0, 0, width, height));
// Add a light positonned at the camera
auto light = GlfSimpleLight();
light.SetAmbient(GfVec4f(0.0f));
auto position = frustum.GetPosition();
light.SetPosition(GfVec4f(
static_cast<float>(position[0]),
static_cast<float>(position[1]),
static_cast<float>(position[2]),
1.0f));
GlfSimpleLightVector lights;
lights.push_back(light);
auto material = GlfSimpleMaterial();
GfVec4f sceneAmbient(0.01f);
mRenderer->SetLightingState(lights, material, sceneAmbient);
mRenderer->Render(mDefaultPrim, mParams);
if (this->mFramed)
{
auto angles = mCamera->angles();
mCamera->controler().setRotation(angles[0], angles[1], angles[2]);
}
this->mFramed = false;
}
GfBBox3d Scene::getDefaultBBox()
{
return GfBBox3d(GfRange3d(GfVec3d(-10.0), GfVec3d(10.0)));
}
GfBBox3d Scene::computeStageBBox()
{
TfTokenVector includedPurposes;
includedPurposes.push_back(UsdGeomTokens->default_);
includedPurposes.push_back(UsdGeomTokens->render);
bool useExtentsHint = true;
UsdGeomBBoxCache bboxCache(mParams.frame, includedPurposes, useExtentsHint);
return bboxCache.ComputeWorldBound(mDefaultPrim);
}
void Scene::Export(const std::string& outputPath) const
{
if(outputPath != "")
{
mStage->Export(outputPath);
std::cout << "[walterViewer] USD stage exported to " << outputPath << '\n';
}
}
} // end namespace walter_viewer
<|start_filename|>walter/maya/walterMtoaConnection/mtoaScene.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "mtoaScene.h"
#include <link.h>
#include <boost/foreach.hpp>
// Returns true if str ends with ending
inline bool endsWith(const std::string& str, const std::string& ending)
{
if (ending.size() > str.size()) {
return false;
}
return std::equal(ending.rbegin(), ending.rend(), str.rbegin());
}
MTOAScene::MTOAScene()
:
mEnd(NULL),
fSession(NULL),
mExportNode(NULL),
mExportNodeA(NULL)
{
void* maya = dlopen(NULL, RTLD_NOW);
link_map* map = reinterpret_cast<link_map*>(maya)->l_next;
void* mtoa = NULL;
// Looking for mtoa.so
static const std::string looking = "/mtoa.so";
while (map) {
if (endsWith(map->l_name, looking)) {
// Found
mtoa = map;
break;
}
map = map->l_next;
}
if (!mtoa) {
AiMsgError("[EXPORT] Error loading mtoa.so");
return;
}
// Get MStatus CMayaScene::Begin(ArnoldSessionMode)
MStatus (*begin)(int);
*(void **)(&begin) =
dlsym(mtoa, "_ZN10CMayaScene5BeginE17ArnoldSessionMode");
// Get CArnoldSession* CMayaScene::GetArnoldSession();
void* (*getArnoldSession)();
*(void **)(&getArnoldSession) =
dlsym(mtoa, "_ZN10CMayaScene16GetArnoldSessionEv");
// Get CRenderSession* CMayaScene::GetRenderSession();
void* (*getRenderSession)();
*(void **)(&getRenderSession) =
dlsym(mtoa, "_ZN10CMayaScene16GetRenderSessionEv");
// Get MStatus CMayaScene::Export(MSelectionList* selected = NULL)
MStatus (*expor)(void*);
#if MAYA_API_VERSION >= 201800 // mtoa >= 3.0.1 (maya 2018)
*(void **)(&expor) =
dlsym(mtoa, "_ZN10CMayaScene6ExportEPN8Autodesk4Maya16OpenMaya2018000014MSelectionListE");
#else
*(void **)(&expor) =
dlsym(mtoa, "_ZN10CMayaScene6ExportEP14MSelectionList");
#endif
// Get CArnoldSession::ExportNode of MTOA 2.0
const char* symbol =
"_ZN14CArnoldSession10ExportNodeERK5MPlugPNSt3tr113"
"unordered_setIP6AtNodeNS3_4hashIS6_EESt8equal_toIS6_ESaIS6_EEEPSt3"
"setI4CAOVSt4lessISF_ESaISF_EEbiP7MStatus";
*(void **)(&mExportNode) = dlsym(mtoa, symbol);
const char* symbolA = nullptr;
#if MAYA_API_VERSION >= 201800 // mtoa >= 3.0.1 (maya 2018)
// Get CArnoldSession::ExportNode of MTOA 3.0.1
symbolA = "_ZN14CArnoldSession10ExportNodeERKN8Autodesk4Maya16OpenMaya201800005MPlugEbiPNS2_7MStatusE";
#else
// Get CArnoldSession::ExportNode of MTOA >= 2.1
symbolA = "_ZN14CArnoldSession10ExportNodeERK5MPlugbiP7MStatus";
#endif
*(void**)(&mExportNodeA) = dlsym(mtoa, symbolA);
// Get CMayaScene::End()
*(void **)(&mEnd) = dlsym(mtoa, "_ZN10CMayaScene3EndEv");
if (!begin ||
!getArnoldSession ||
!getRenderSession ||
!expor ||
(!mExportNode && !mExportNodeA) ||
!mEnd) {
// Something is not loaded. Return.
AiMsgError("[EXPORT] Error loading symbols from mtoa.so");
return;
}
// Call MStatus CMayaScene::Begin(MTOA_SESSION_ASS)
(*begin)(MTOA_SESSION_ASS);
// Call CMayaScene::GetArnoldSession()
fSession = (*getArnoldSession)();
// Call CMayaScene::GetRenderSession()
void *renderSession = (*getRenderSession)();
// TODO:
// renderSession->SetOutputAssMask(16)
// fSession->SetExportFilterMask(16)
// renderSession->SetForceTranslateShadingEngines(true)
// Call CMayaScene::Export(NULL)
(*expor)(NULL);
}
MTOAScene::~MTOAScene()
{
if (mEnd) {
// Call CMayaScene::End()
(*mEnd)();
}
}
CNodeTranslator* MTOAScene::exportNode(const MPlug& plug, AtNodeSet* nodes)
{
if (mExportNode) {
// Call fSession->ExportNode(plug, nodes)
return (*mExportNode)(fSession, plug, nodes, NULL, false, -1, NULL);
}
if (mExportNodeA)
{
return (*mExportNodeA)(fSession, plug, false, -1, NULL);
}
return nullptr;
}
<|start_filename|>walter/katana/WalterIn/walterUSDOpIndex.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterUSDOpIndex.h"
#include <boost/algorithm/string.hpp>
#include "walterUSDOpUtils.h"
OpIndex::OpIndex()
{}
const SdfPath& OpIndex::getMaterialAssignment(
const SdfPath& objectPath,
const std::string& target) const
{
ScopedLock lock(mMutex);
// Getting the necessary target. If it's not exist, we have to create it
// because we need to cache the result.
ObjectToShader& objects = mResolvedAssignments[target];
// Looking for necessary material. Returns a pair consisting of an iterator
// to the inserted element, or the already-existing element if no insertion
// happened, and a bool denoting whether the insertion took place. True for
// Insertion, False for No Insertion.
const auto result = objects.emplace(
std::piecewise_construct,
std::forward_as_tuple(objectPath),
std::forward_as_tuple());
SdfPath& assigned = result.first->second;
if (result.second)
{
// There was no object name in the index. We just created it, so we need
// to replace it with the good value.
assigned = resolveMaterialAssignment(objectPath.GetString(), target);
}
return assigned;
}
const OpIndex::NameToAttribute* OpIndex::getAttributes(
SdfPath iOverridePath) const
{
auto it = mAttributes.find(iOverridePath);
if (it == mAttributes.end())
{
return nullptr;
}
const NameToAttribute& attributes = it->second;
return &attributes;
}
void OpIndex::insertExpression(
const std::string& iExpression,
const WalterExpression::AssignmentLayers& iLayers)
{
// WalterExpression::AssignmentLayers is {"layer": {"target": "material"}}
// WalterExpression::AssignmentTargets is {"target": "material"}
static const std::string defaultRenderLayer = "defaultRenderLayer";
const WalterExpression::AssignmentTargets* targets = nullptr;
if (iLayers.size() == 1)
{
// We use the only available layer.
targets = &iLayers.begin()->second;
}
else
{
// In the case there are several layers, we use defaultRenderLayer.
auto layerIt = iLayers.find(defaultRenderLayer);
if (layerIt != iLayers.end())
{
targets = &layerIt->second;
}
}
if (!targets)
{
return;
}
const std::string fullExpression =
WalterCommon::demangleString(iExpression);
for (const auto& t : *targets)
{
// targetName is "shader"
const std::string& targetName = t.first;
const SdfPath& materialPath = t.second;
mAssignments[targetName].emplace(
std::piecewise_construct,
std::forward_as_tuple(fullExpression),
std::forward_as_tuple(materialPath));
}
}
SdfPath OpIndex::resolveMaterialAssignment(
const std::string& iObjectName,
const std::string& iTarget) const
{
// Looking for necessary target.
auto targetIt = mAssignments.find(iTarget);
if (targetIt == mAssignments.end())
{
return SdfPath();
}
const ExprToMat& expressionList = targetIt->second;
const SdfPath* shader =
WalterCommon::resolveAssignment<SdfPath>(iObjectName, expressionList);
if (!shader)
{
return SdfPath();
}
return *shader;
}
void OpIndex::insertAttribute(
const SdfPath& iOverridePath,
const std::string& iAttributeName,
const OpCaboose::ClientAttributePtr& iAttribute)
{
mAttributes[iOverridePath].emplace(iAttributeName, iAttribute);
}
<|start_filename|>walter/maya/walterStandin/rdoProfiling.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "rdoProfiling.h"
#include <sys/syscall.h>
#include <unistd.h>
std::map<size_t, std::stack<RdoProfiling*>> RdoProfiling::s_stacks;
RdoProfiling::RdoProfiling(
const char* i_function,
const char* i_file,
int i_line,
const char* i_message) :
m_function(i_function),
m_file(i_file),
m_line(i_line),
m_message(i_message),
m_start(std::chrono::high_resolution_clock::now()),
m_others(0),
mThreadID(syscall(SYS_gettid))
{
std::stack<RdoProfiling*>& stack = s_stacks[mThreadID];
stack.push(this);
std::string indent;
for (unsigned int i = 0; i < stack.size(); i++)
{
indent += " ";
}
printf(
"%s{ <%zu> %s:%i %s: %s\n",
indent.c_str(),
mThreadID,
m_file.c_str(),
m_line,
m_function.c_str(),
m_message.c_str());
}
RdoProfiling::~RdoProfiling()
{
std::stack<RdoProfiling*>& stack = s_stacks[mThreadID];
std::chrono::high_resolution_clock::time_point finish =
std::chrono::high_resolution_clock::now();
auto delta = finish - m_start;
int duration =
std::chrono::duration_cast<std::chrono::milliseconds>(delta).count();
std::string indent;
for (unsigned int i = 0; i < stack.size(); i++)
{
indent += " ";
}
printf(
"%s} <%zu> %ims %s: %s\n",
indent.c_str(),
mThreadID,
duration - m_others,
m_function.c_str(),
m_message.c_str());
stack.pop();
if (stack.size())
{
stack.top()->m_others += duration;
}
}
<|start_filename|>walter/common/abcExporterUtils.cpp<|end_filename|>
/*Abc Shader Exporter
Copyright (c) 2014, <NAME>, All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.*/
#include "abcExporterUtils.h"
#include "to_string_patch.h"
namespace // <anonymous>
{
static std::string RGB_COMPONENTS[] = {"r", "g", "b"};
static std::string RGBA_COMPONENTS[] = {"r", "g", "b", "a"};
static std::string POINT2_COMPONENTS[] = {"x", "y"};
static std::string VECTOR_COMPONENTS[] = {"x", "y", "z"};
}
const std::vector< std::string > GetComponentNames(int arnoldParamType)
{
switch (arnoldParamType)
{
case AI_TYPE_RGB:
return std::vector<std::string> (RGB_COMPONENTS , RGB_COMPONENTS +2);
case AI_TYPE_RGBA:
return std::vector<std::string> (RGBA_COMPONENTS , RGBA_COMPONENTS + 3);
case AI_TYPE_VECTOR:
case AI_TYPE_POINT:
return std::vector<std::string> (VECTOR_COMPONENTS , VECTOR_COMPONENTS + 2);
case AI_TYPE_POINT2:
return std::vector<std::string> (POINT2_COMPONENTS , POINT2_COMPONENTS + 1);
default:
return std::vector<std::string> ();
}
}
void getAllArnoldNodes(AtNode* node, AtNodeSet* nodes)
{
AtParamIterator* iter = AiNodeEntryGetParamIterator(AiNodeGetNodeEntry(node));
while (!AiParamIteratorFinished(iter))
{
const AtParamEntry *pentry = AiParamIteratorGetNext(iter);
const char* paramName = AiParamGetName(pentry);
int inputType = AiParamGetType(pentry);
if(inputType == AI_TYPE_ARRAY)
{
AtArray* paramArray = AiNodeGetArray(node, paramName);
if(paramArray->type == AI_TYPE_NODE ||paramArray->type == AI_TYPE_POINTER)
{
for(unsigned int i=0; i < paramArray->nelements; i++)
{
AtNode* linkedNode = (AtNode*)AiArrayGetPtr(paramArray, i);
if(linkedNode != NULL)
{
nodes->insert(linkedNode);
getAllArnoldNodes(linkedNode, nodes);
}
}
}
else
{
if(AiNodeIsLinked(node, paramName))
{
int comp;
for(unsigned int i=0; i < paramArray->nelements; i++)
{
std::string paramNameArray = std::string(paramName) + "[" + to_string(i) +"]";
if (AiNodeIsLinked(node, paramNameArray.c_str()))
{
//AiMsgDebug("%s has a link", paramNameArray.c_str());
AtNode* linkedNode = NULL;
linkedNode = AiNodeGetLink(node, paramNameArray.c_str(), &comp);
if(linkedNode)
{
nodes->insert(linkedNode);
getAllArnoldNodes(linkedNode, nodes);
}
else
{
std::vector<std::string> componentNames = GetComponentNames(inputType);
unsigned int numComponents = componentNames.size();
for (unsigned int i=0; i < numComponents; i++)
{
std::string compAttrName = paramNameArray + "." + componentNames[i];
if(AiNodeIsLinked(node, compAttrName.c_str()))
{
linkedNode = AiNodeGetLink(node, compAttrName.c_str(), &comp);
if(linkedNode)
{
nodes->insert(linkedNode);
getAllArnoldNodes(linkedNode, nodes);
}
}
}
}
}
}
}
}
}
else if(AiNodeIsLinked(node, paramName))
{
{
AtNode* linkedNode = NULL;
int comp;
linkedNode = AiNodeGetLink(node, paramName, &comp);
if(linkedNode)
{
nodes->insert(linkedNode);
getAllArnoldNodes(linkedNode, nodes);
}
else
{
std::vector<std::string> componentNames = GetComponentNames(inputType);
unsigned int numComponents = componentNames.size();
for (unsigned int i=0; i < numComponents; i++)
{
std::string compAttrName = std::string(paramName) + "." + componentNames[i];
if(AiNodeIsLinked(node, compAttrName.c_str()))
{
linkedNode = AiNodeGetLink(node, compAttrName.c_str(), &comp);
if(linkedNode)
{
nodes->insert(linkedNode);
getAllArnoldNodes(linkedNode, nodes);
}
}
}
}
}
}
}
AiParamIteratorDestroy(iter);
}
void processArrayValues(AtNode* sit, const char *paramName, AtArray* paramArray, int outputType, Mat::OMaterial matObj, std::string nodeName)
{
int typeArray = paramArray->type;
if (typeArray == AI_TYPE_INT || typeArray == AI_TYPE_ENUM)
{
//type int
Abc::OInt32ArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName);
std::vector<int> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
vals.push_back(AiArrayGetInt(paramArray, i));
prop.set(vals);
}
else if (typeArray == AI_TYPE_UINT)
{
//type int
Abc::OUInt32ArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName);
std::vector<unsigned int> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
vals.push_back(AiArrayGetUInt(paramArray, i));
prop.set(vals);
}
else if (typeArray == AI_TYPE_BYTE)
{
Alembic::AbcCoreAbstract::MetaData md;
md.set("type", boost::lexical_cast<std::string>("byte"));
//type int
Abc::OUInt32ArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName, md);
std::vector<unsigned int> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
vals.push_back(AiArrayGetByte(paramArray, i));
prop.set(vals);
}
else if (typeArray == AI_TYPE_FLOAT)
{
// type float
Abc::OFloatArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName);
std::vector<float> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
vals.push_back(AiArrayGetFlt(paramArray, i));
prop.set(vals);
}
else if (typeArray == AI_TYPE_BOOLEAN)
{
// type bool
Abc::OBoolArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName);
std::vector<Abc::bool_t> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
vals.push_back(AiArrayGetBool(paramArray, i));
prop.set(vals);
}
else if (typeArray == AI_TYPE_RGB)
{
// type rgb
Abc::OC3fArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName);
std::vector<Imath::C3f> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
{
AtColor a_val = AiArrayGetRGB(paramArray, i);
Imath::C3f color_val( a_val.r, a_val.g, a_val.b );
vals.push_back(color_val);
}
prop.set(vals);
}
else if (typeArray == AI_TYPE_RGBA)
{
// type rgba
Abc::OC4fArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName);
std::vector<Imath::C4f> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
{
AtRGBA a_val = AiArrayGetRGBA(paramArray, i);
Imath::C4f color_val( a_val.r, a_val.g, a_val.b, a_val.a );
vals.push_back(color_val);
}
prop.set(vals);
}
else if (typeArray == AI_TYPE_POINT2)
{
// type point2
Abc::OP2fArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName);
std::vector<Imath::V2f> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
{
AtPoint2 a_val = AiArrayGetPnt2(paramArray, i);
Imath::V2f vec_val( a_val.x, a_val.y );
vals.push_back(vec_val);
}
prop.set(vals);
}
else if (typeArray == AI_TYPE_POINT)
{
// type point
Abc::OP3fArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName);
std::vector<Imath::V3f> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
{
AtPoint a_val = AiArrayGetPnt(paramArray, i);
Imath::V3f vec_val( a_val.x, a_val.y, a_val.z );
vals.push_back(vec_val);
}
prop.set(vals);
}
else if (typeArray == AI_TYPE_VECTOR)
{
Abc::OV3fArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName);
std::vector<Imath::V3f> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
{
AtPoint a_val = AiArrayGetPnt(paramArray, i);
Imath::V3f vec_val( a_val.x, a_val.y, a_val.z );
vals.push_back(vec_val);
}
prop.set(vals);
}
else if (typeArray == AI_TYPE_STRING)
{
// type string
Abc::OStringArrayProperty prop(matObj.getSchema().getNetworkNodeParameters(nodeName.c_str()), paramName);
std::vector<std::string> vals;
for(unsigned int i=0; i < paramArray->nelements; i++)
vals.push_back(AiArrayGetStr(paramArray, i));
prop.set(vals);
}
// cout << "exported " << paramArray->nelements << " array values of type " << typeArray << " for " << nodeName.c_str() << "." << paramName << endl;
}
void processArrayParam(AtNode* sit, const char *paramName, AtArray* paramArray, int index, int outputType, Mat::OMaterial matObj, std::string nodeName, std::string containerName)
{
//first, test if the entry is linked
//Build the paramname...
AiMsgTab (+2);
int typeArray = paramArray->type;
if(typeArray == AI_TYPE_NODE || typeArray == AI_TYPE_POINTER)
{
for(unsigned int i=0; i < paramArray->nelements; i++)
{
AtNode* linkedNode = (AtNode*)AiArrayGetPtr(paramArray, i);
if(linkedNode != NULL)
{
std::string nodeNameLinked = containerName + ":" + std::string(AiNodeGetName(linkedNode));
std::string paramNameArray = std::string(paramName) + "[" + to_string(i) +"]";
//AiMsgInfo("%s.%s is linked", nodeName.c_str(), paramName);
//AiMsgInfo("Exporting link from %s.%s to %s.%s", nodeNameLinked.c_str(), paramNameArray.c_str(), nodeName.c_str(), paramName);
matObj.getSchema().setNetworkNodeConnection(nodeName.c_str(), paramNameArray.c_str(), nodeNameLinked.c_str(), "");
}
}
}
else
{
std::string paramNameArray = std::string(paramName) + "[" + to_string(index) +"]";
if (!AiNodeGetLink(sit, paramNameArray.c_str()) == NULL)
processLinkedParam(sit, typeArray, outputType, matObj, nodeName, paramNameArray, containerName);
}
AiMsgTab (-2);
}
void processLinkedParam(AtNode* sit, int inputType, int outputType, Mat::OMaterial matObj, std::string nodeName, std::string paramName, std::string containerName)
{
AiMsgTab (+2);
if (AiNodeIsLinked(sit, paramName.c_str()))
{
// check what is linked exactly
if(AiNodeGetLink(sit, paramName.c_str()))
{
//AiMsgInfo("%s.%s is linked", nodeName.c_str(), paramName.c_str());
exportLink(sit, matObj, nodeName, paramName, containerName);
}
else
{
const std::vector<std::string> componentNames = GetComponentNames(inputType);
unsigned int numComponents = componentNames.size();
for (unsigned int i=0; i < numComponents; i++)
{
std::string compAttrName = paramName + "." + componentNames[i];
if(AiNodeIsLinked(sit, compAttrName.c_str()))
{
//cout << "exporting link : " << nodeName << "." << compAttrName.c_str() << endl;
exportLink(sit, matObj, nodeName, compAttrName, containerName);
}
}
}
}
else
exportParameter(sit, matObj, inputType, nodeName, paramName);
AiMsgTab (-2);
}
void exportLink(AtNode* sit, Mat::OMaterial matObj, std::string nodeName, std::string paramName, std::string containerName)
{
AiMsgTab (+2);
int comp;
AiMsgDebug("Checking link %s.%s", nodeName.c_str(), paramName.c_str());
AtNode* linked = AiNodeGetLink(sit, paramName.c_str(), &comp);
int outputType = AiNodeEntryGetOutputType(AiNodeGetNodeEntry(linked));
std::string nodeNameLinked = containerName + ":" + std::string(AiNodeGetName(linked));
//We need to replace the "." stuff from the name as we does it from the exporter.
boost::replace_all(nodeNameLinked, ".message", "");
boost::replace_all(nodeNameLinked, ".", "_");
std::string outPlug;
if(comp == -1)
outPlug = "";
else
{
if(outputType == AI_TYPE_RGB || outputType == AI_TYPE_RGBA)
{
if(comp == 0)
outPlug = "r";
else if(comp == 1)
outPlug = "g";
else if(comp == 2)
outPlug = "b";
else if(comp == 3)
outPlug = "a";
}
else if(outputType == AI_TYPE_VECTOR || outputType == AI_TYPE_POINT ||outputType == AI_TYPE_POINT2)
{
if(comp == 0)
outPlug = "x";
else if(comp == 1)
outPlug = "y";
else if(comp == 2)
outPlug = "z";
}
}
//AiMsgInfo("Exporting link from %s.%s to %s.%s", nodeNameLinked.c_str(), outPlug.c_str(), nodeName.c_str(), paramName);
matObj.getSchema().setNetworkNodeConnection(nodeName.c_str(), paramName, nodeNameLinked.c_str(), outPlug);
AiMsgTab (-2);
}
void exportParameter(AtNode* sit, Mat::OMaterial matObj, int type, std::string nodeName, std::string paramName)
{
const char* c_paramName = paramName.c_str();
const char* c_nodeName = nodeName.c_str();
//header->setMetaData(md);
if (type == AI_TYPE_INT || type == AI_TYPE_ENUM)
{
//type int
Abc::OInt32Property prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName);
prop.set(AiNodeGetInt(sit, c_paramName));
}
else if (type == AI_TYPE_UINT)
{
//type int
Abc::OUInt32Property prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName);
prop.set(AiNodeGetUInt(sit, c_paramName));
}
else if (type == AI_TYPE_BYTE)
{
Alembic::AbcCoreAbstract::MetaData md;
md.set("type", boost::lexical_cast<std::string>("byte"));
//type Byte
Abc::OUInt32Property prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName, md);
prop.set(AiNodeGetByte(sit, c_paramName));
}
else if (type == AI_TYPE_FLOAT)
{
// type float
Alembic::AbcCoreAbstract::MetaData md;
const AtNodeEntry* arnoldNodeEntry = AiNodeGetNodeEntry(sit);
float val;
bool success = AiMetaDataGetFlt(arnoldNodeEntry, c_paramName, "min", &val);
if(success)
md.set("min", boost::lexical_cast<std::string>(val));
success = AiMetaDataGetFlt(arnoldNodeEntry, c_paramName, "max", &val);
if(success)
md.set("max", boost::lexical_cast<std::string>(val));
success = AiMetaDataGetFlt(arnoldNodeEntry, c_paramName, "softmin", &val);
if(success)
md.set("softmin", boost::lexical_cast<std::string>(val));
success = AiMetaDataGetFlt(arnoldNodeEntry, c_paramName, "softmax", &val);
if(success)
md.set("softmax", boost::lexical_cast<std::string>(val));
Abc::OFloatProperty prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName, md);
prop.set(AiNodeGetFlt(sit, c_paramName));
}
else if (type == AI_TYPE_BOOLEAN)
{
// type bool
Abc::OBoolProperty prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName);
prop.set(AiNodeGetBool(sit, c_paramName));
}
else if (type == AI_TYPE_RGB)
{
// type rgb
Abc::OC3fProperty prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName);
AtColor a_val = AiNodeGetRGB(sit, c_paramName);
Imath::C3f color_val( a_val.r, a_val.g, a_val.b );
prop.set(color_val);
//cout << "exporting RGB value of " << a_val.r << " " << a_val.g << " " << a_val.b << " for " << c_nodeName <<"."<<paramName << endl;
}
else if (type == AI_TYPE_RGBA)
{
// type rgb
Abc::OC4fProperty prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName);
AtRGBA a_val = AiNodeGetRGBA(sit, c_paramName);
Imath::C4f color_val( a_val.r, a_val.g, a_val.b, a_val.a );
prop.set(color_val);
//cout << "exporting RGB value of " << a_val.r << " " << a_val.g << " " << a_val.b << " for " << c_nodeName <<"."<<paramName << endl;
}
else if (type == AI_TYPE_POINT2)
{
// type point
Abc::OP2fProperty prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName);
AtPoint2 a_val = AiNodeGetPnt2(sit, c_paramName);
Imath::V2f vec_val( a_val.x, a_val.y);
prop.set(vec_val);
}
else if (type == AI_TYPE_POINT)
{
// type point
Abc::OP3fProperty prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName);
AtVector a_val = AiNodeGetPnt(sit, c_paramName);
Imath::V3f vec_val( a_val.x, a_val.y, a_val.z );
prop.set(vec_val);
}
else if (type == AI_TYPE_VECTOR)
{
// type vector
Abc::OV3fProperty prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName);
AtVector a_val = AiNodeGetVec(sit, c_paramName);
Imath::V3f vec_val( a_val.x, a_val.y, a_val.z );
prop.set(vec_val);
}
else if (type == AI_TYPE_STRING)
{
// type string
Abc::OStringProperty prop(matObj.getSchema().getNetworkNodeParameters(c_nodeName), c_paramName);
prop.set(AiNodeGetStr(sit, c_paramName));
}
if(strcmp(c_paramName,"name") != 0 && isDefaultValue(sit, c_paramName) == false)
if (type == AI_TYPE_BYTE || type == AI_TYPE_INT || type == AI_TYPE_UINT || type == AI_TYPE_ENUM || type == AI_TYPE_FLOAT || type == AI_TYPE_BOOLEAN || type == AI_TYPE_RGB ||type == AI_TYPE_STRING)
{
std::string interfaceName = std::string(AiNodeGetName(sit)) + ":" + paramName;
matObj.getSchema().setNetworkInterfaceParameterMapping(interfaceName.c_str(), c_nodeName, c_paramName);
}
}
bool isDefaultValue(AtNode* node, const char* paramName)
{
const AtParamEntry* pentry = AiNodeEntryLookUpParameter (AiNodeGetNodeEntry(node), paramName);
if(pentry == NULL)
return false;
const AtParamValue * pdefaultvalue = AiParamGetDefault (pentry);
switch(AiParamGetType(pentry))
{
case AI_TYPE_BYTE:
if (AiNodeGetByte(node, paramName) == pdefaultvalue->BYTE)
return true;
break;
case AI_TYPE_INT:
if (AiNodeGetInt(node, paramName) == pdefaultvalue->INT)
return true;
break;
case AI_TYPE_UINT:
if (AiNodeGetUInt(node, paramName) == pdefaultvalue->UINT)
return true;
break;
case AI_TYPE_BOOLEAN:
if (AiNodeGetBool (node, paramName) == pdefaultvalue->BOOL)
return true;
break;
case AI_TYPE_FLOAT:
if (AiNodeGetFlt (node, paramName) == pdefaultvalue->FLT)
return true;
break;
case AI_TYPE_RGB:
if (AiNodeGetRGB (node, paramName) == pdefaultvalue->RGB)
return true;
break;
case AI_TYPE_RGBA:
if (AiNodeGetRGBA (node, paramName) == pdefaultvalue->RGBA)
return true;
break;
case AI_TYPE_VECTOR:
if (AiNodeGetVec (node, paramName) == pdefaultvalue->VEC)
return true;
break;
case AI_TYPE_POINT:
if (AiNodeGetPnt (node, paramName) == pdefaultvalue->PNT)
return true;
break;
case AI_TYPE_POINT2:
if (AiNodeGetPnt2 (node, paramName) == pdefaultvalue->PNT2)
return true;
break;
case AI_TYPE_STRING:
if (strcmp(AiNodeGetStr(node, paramName), pdefaultvalue->STR) == 0)
return true;
break;
default:
return false;
}
return false;
}
<|start_filename|>walter/cmake/FindPyString.cmake<|end_filename|>
# The module defines the following variables:
# PYSTRING_LIBRARY_DIR - path to PYstring static libs
# PYSTRING_FOUND - true if the Alembic was found
#
# Example usage:
# find_package(PYSTRING)
# if(PYSTRING_FOUND)
# message("Pystring found: ${PYSTRING_LIBRARY_DIR}")
# endif()
#
#=============================================================================
message("-- Searching PyString libraries.......")
IF(NOT PYSTRING_DIR AND NOT $ENV{PYSTRING_DIR} STREQUAL "")
SET(PYSTRING_DIR $ENV{PYSTRING_DIR})
ENDIF()
set(LIBRARY_PATHS
${PYSTRING_DIR}/lib/
${PYSTRING_DIR}/lib/static)
# Find PYstring lib
find_library(PYSTRING_LIBRARY
NAMES pystring libpystring
PATHS ${LIBRARY_PATHS})
set ( PYSTRING_LIBRARIES
${PYSTRING_LIBRARY}
)
get_filename_component( PYSTRING_LIBRARY_DIR ${PYSTRING_LIBRARY} PATH )
find_path ( PYSTRING_INCLUDE_DIR pystring.h
${PYSTRING_DIR}/include/pystring
)
include( FindPackageHandleStandardArgs )
find_package_handle_standard_args( "PYSTRING" DEFAULT_MSG
PYSTRING_LIBRARIES
PYSTRING_LIBRARY_DIR
PYSTRING_INCLUDE_DIR
)
if(NOT PYSTRING_FOUND)
message(FATAL_ERROR "Try using -D PYSTRING_DIR=/path/to/pystring")
endif()
<|start_filename|>walter/usd/tests/test_purpose.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "schemas/walterHdStream/primvar.h"
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/prim.h>
#include "walterUSDCommonUtils.h"
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usd/variantSets.h>
#include <pxr/usd/usdGeom/imageable.h>
#include <gtest/gtest.h>
PXR_NAMESPACE_USING_DIRECTIVE
TEST(test_purpose, test1)
{
std::string stageAsStr = R"(#usda 1.0
(
endTimeCode = 1
startTimeCode = 1
upAxis = "Y"
)
def Xform "triangle" (
)
{
def Mesh "mesh0"
{
float3[] extent = [(-0.5, 0, 0), (0.5, 0.7853982, 0)]
int[] faceVertexCounts = [3]
int[] faceVertexIndices = [0, 1, 2]
point3f[] points = [(-0.5, 0, 0), (0.5, 0, 0), (0, 0.7853982, 0)]
}
}
)";
UsdStageRefPtr stage = UsdStage::CreateInMemory();
SdfLayerHandle handle = stage->GetSessionLayer();
handle->ImportFromString(stageAsStr);
// By default the prim is visible
EXPECT_EQ(WalterUSDCommonUtils::purpose(stage, "/triangle/mesh0"), "default");
// Hide it and test
WalterUSDCommonUtils::setPurpose(stage, "/triangle/mesh0", "render");
EXPECT_EQ(WalterUSDCommonUtils::purpose(stage, "/triangle/mesh0"), "render");
// Make it visible and test
WalterUSDCommonUtils::setPurpose(stage, "/triangle/mesh0", "proxy");
EXPECT_EQ(WalterUSDCommonUtils::purpose(stage, "/triangle/mesh0"), "proxy");
}
<|start_filename|>walter/maya/walterStandin/walterAttributes.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERATTRIBUTES_H_
#define __WALTERATTRIBUTES_H_
// Several utilities to save/load attributes from Alembic files.
#include <maya/MString.h>
// Save all the attributes from given walter node to a separate Alembic file.
bool saveAttributes(const MString& objectName, const MString& fileName);
#endif
<|start_filename|>walter/maya/mtoa/mtoaVersion.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __MTOAVERSION_H_
#define __MTOAVERSION_H_
#include <utils/Version.h>
#define WALTER_MTOA_VERSION ((MTOA_ARCH_VERSION_NUM*100 + MTOA_MAJOR_VERSION_NUM)*100 + MTOA_MINOR_VERSION_NUM)
#endif
<|start_filename|>walter/usd/walterUsdConversion.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERUSDCONVERSION_H_
#define __WALTERUSDCONVERSION_H_
#include <pxr/usd/usd/attribute.h>
#include <pxr/usd/usd/property.h>
#include <pxr/usd/usd/relationship.h>
#include <string>
#include <type_traits>
PXR_NAMESPACE_USING_DIRECTIVE
namespace WalterUSDToString
{
// It's in a separate namespace because it's not possible to specialize
// member functions without explicitly specializing the containing class due
// to C++04, §14.7.3/3.
template <typename T> std::string convert(const T& value);
}
// Sets of functions to cast USD properties into a json.
struct WalterUsdConversion
{
// Gets the value of an attribute of type T (all excepted strings).
template <class T>
static T getAttributeValue(UsdAttribute const& attr, UsdTimeCode const& tc)
{
T value;
attr.Get<T>(&value, tc);
return value;
}
// Gets the value an attribute of basic type T (excepted strings) as a
// json.
template <class T>
static std::string getAttributeValueAsString(
UsdAttribute const& attr,
UsdTimeCode const& tc)
{
return std::is_same<T, std::string>::value
? "\"" + WalterUSDToString::convert(getAttributeValue<T>(attr, tc)) + "\""
: WalterUSDToString::convert(getAttributeValue<T>(attr, tc));
}
// Gets the value of an attribute array of basic type T (excepted strings)
// as a json.
template <class T>
static std::string getArrayAttributeValueAsString(
UsdAttribute const& attr,
UsdTimeCode const& tc,
int maxElementCount,
int& arraySize)
{
VtArray<T> vtArray = getAttributeValue<VtArray<T>>(attr, tc);
arraySize = (int)vtArray.size();
unsigned maxCount = maxElementCount > -1 ?
std::min(maxElementCount, arraySize) :
arraySize;
std::string str = "[";
for (unsigned i = 0; i < maxCount; ++i)
{
str += std::is_same<T, std::string>::value
? "\"" + WalterUSDToString::convert(vtArray[i]) + "\""
: WalterUSDToString::convert(vtArray[i]);
if (i < maxCount - 1)
str += ", ";
}
str += "]";
return str;
}
// Gets the value of an relationship as strings.
static std::string getRelationShipValueAsString(
UsdRelationship const& rl,
UsdTimeCode const& tc);
// Gets the value of a scalar attribute as strings.
static std::string getScalarAttributeValueAsString(
UsdAttribute const& attr,
UsdTimeCode const& tc);
// Gets the value of an attribute array as a json array.
static std::string getArrayAttributeValueAsString(
UsdAttribute const& attr,
UsdTimeCode const& tc,
int maxElementCount,
int& arraySize);
// Gets the type and the value of an attribute as a json.
static bool getAttributeValueAsString(
UsdAttribute const& attr,
UsdTimeCode const& tc,
std::string& propertyType,
std::string& strValue,
int& arraySize,
int maxElementCount = -1);
// Gets the type and the value of a property as json.
static bool getPropertyValueAsString(
UsdProperty const& prop,
UsdTimeCode const& tc,
std::string& propertyType,
std::string& strValue,
int& arraySize,
int maxElementCount = -1,
bool attributeOnly = true);
// Constructs a single json representing a property.
static std::string constuctStringRepresentation(
std::string const& name,
std::string const& propertyType,
std::string const& valueType,
std::string const& strValue,
int arraySize);
};
#endif // __WALTERUSDCONVERSION_H_
<|start_filename|>walter/usd/tests/test_getVariantsLayerAsText.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/variantSets.h>
#include <string>
#include <vector>
#include "walterUSDCommonUtils.h"
#include <gtest/gtest.h>
PXR_NAMESPACE_USING_DIRECTIVE
TEST(getVariantsLayerAsText, test1)
{
UsdStageRefPtr stage = UsdStage::CreateInMemory();
UsdPrim prim = stage->DefinePrim(SdfPath("/Foo"));
UsdVariantSets vsets = prim.GetVariantSets();
UsdVariantSet colorsVset = vsets.AddVariantSet("colors");
colorsVset.AddVariant("red");
colorsVset.AddVariant("green");
colorsVset.AddVariant("blue");
colorsVset.SetVariantSelection("green");
std::vector<std::string> result = WalterUSDCommonUtils::getVariantsUSD(
stage, "", true);
EXPECT_EQ(result[0], "{ \"prim\": \"/Foo\", \"variants\": [{ \"set\": \"colors\", \"names\": [\"blue\", \"green\", \"red\"], \"selection\": \"green\" } ] }");
}
<|start_filename|>walter/arnold/procedural/engine.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "engine.h"
#include <pxr/base/tf/instantiateSingleton.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usdGeom/pointInstancer.h>
#include <boost/algorithm/string.hpp>
#include <boost/noncopyable.hpp>
#include <unordered_map>
#include "walterUSDCommonUtils.h"
PXR_NAMESPACE_USING_DIRECTIVE
// Cache for RendererEngines
class EngineRegistry : boost::noncopyable
{
public:
typedef EngineRegistry This;
static EngineRegistry& getInstance()
{
return TfSingleton<This>::GetInstance();
}
// Clear mCache.
void clear() { mCache.clear(); }
RendererEngine& getEngine(
const std::string& fileName,
const std::vector<std::string>& layers)
{
// It's possible that the procedurals request the engine at the same
// time.
ScopedLock lock(mMutex);
// TODO: Initialize and keep the cache with UsdStage ID or the hash, not
// with the filename.
auto it = mCache.find(fileName);
if (it == mCache.end())
{
auto result = mCache.emplace(
std::piecewise_construct,
std::forward_as_tuple(fileName),
std::forward_as_tuple(fileName, layers));
it = result.first;
}
return it->second;
}
private:
typedef std::mutex Mutex;
typedef std::lock_guard<Mutex> ScopedLock;
std::unordered_map<std::string, RendererEngine> mCache;
Mutex mMutex;
};
TF_INSTANTIATE_SINGLETON(EngineRegistry);
RendererEngine* RendererEngine::getInstance(
const std::string& fileName,
const std::vector<std::string>& layers)
{
RendererEngine& engine =
EngineRegistry::getInstance().getEngine(fileName, layers);
return &engine;
}
void RendererEngine::clearCaches()
{
EngineRegistry::getInstance().clear();
}
RendererEngine::RendererEngine(
const std::string& fileName,
const std::vector<std::string>& layers) :
mPlugin(),
mIndex(),
mDelegate(mIndex, mPlugin)
{
SdfLayerRefPtr root = WalterUSDCommonUtils::getUSDLayer(fileName);
if (!layers.empty())
{
// Create the layer-container with the sub-layers.
char layername[100];
sprintf(layername, "anonymous%i.usda", rand());
SdfLayerRefPtr overrideLayer = SdfLayer::CreateAnonymous(layername);
// List of the layer IDs to put it to the container.
std::vector<std::string> allLayers;
allLayers.reserve(layers.size());
// We need this cache to be sure that the layer will not be killed.
std::vector<SdfLayerRefPtr> cacheLayers;
cacheLayers.reserve(layers.size());
for (const std::string& layer : layers)
{
// We need a unique name because USD can open the previous layer if
// it has the same name.
// TODO: make a really unique name using UUID.
sprintf(layername, "anonymous%i.usda", rand());
SdfLayerRefPtr overrideLayer = SdfLayer::CreateAnonymous(layername);
if (overrideLayer->ImportFromString(layer))
{
allLayers.push_back(overrideLayer->GetIdentifier());
cacheLayers.push_back(overrideLayer);
}
}
// Put all the sub-layers.
overrideLayer->SetSubLayerPaths(allLayers);
// Form the stage.
mStage = UsdStage::Open(root, overrideLayer);
}
if (!mStage)
{
mStage = UsdStage::Open(root);
}
}
int RendererEngine::getNumNodes(
const SdfPath& path,
const std::vector<float>& times)
{
const UsdPrim prim = mStage->GetPrimAtPath(path);
if (prim)
{
// If the given path is not the root path or a children of /materials
// and if global materials are not already found we need to force
// the check of materials location, which will produce one more
// procedural node set to the '/materials' location.
int numNodes = 0;
if (path != SdfPath("/") &&
!boost::starts_with(path.GetString(), "/materials") &&
!mIndex.hasGlobalMaterials())
{
numNodes = 1;
}
if (prim.IsA<UsdGeomPointInstancer>())
{
UsdGeomPointInstancer instancer(prim);
UsdAttribute positionsAttr = instancer.GetPositionsAttr();
if (!positionsAttr.HasValue())
{
return 0;
}
float averageTime =
std::accumulate(times.begin(), times.end(), 0.0f) /
times.size();
VtVec3fArray positions;
positionsAttr.Get(&positions, static_cast<double>(averageTime));
int pointInstancerNumNodes = static_cast<int>(positions.size());
mIndex.insertNumNodes(prim.GetPath(), pointInstancerNumNodes);
return numNodes + pointInstancerNumNodes;
}
prepare(prim);
// 2x because we need to output a reference and an inctance for each
// object.
return numNodes + 2 * mIndex.getNumNodes(path);
}
return 0;
}
void* RendererEngine::render(
const SdfPath& path,
int id,
const std::vector<float>& times,
const void* userData)
{
// If the locations '/' or '/materials' are not in the hierarchy map,
// create a walter procedural for /materials. This happend when the first
// "objectPath" given to the procedural was a children of '/'.
//
// If '/materials' need to be scanned we force it to be the first
// thing done.
if (!mIndex.hasGlobalMaterials() && id == 0)
{
SdfPath materialPath("/materials");
UsdPrim materialPrim = mStage->GetPrimAtPath(materialPath);
if (materialPrim)
{
return mPlugin.output(materialPrim, times, userData);
}
}
const UsdPrim parentPrim = mStage->GetPrimAtPath(path);
if (parentPrim.IsA<UsdGeomPointInstancer>())
{
int realID = id % mIndex.getNumNodes(path);
return mPlugin.outputBBoxFromPoint(
parentPrim, realID, times, userData, mIndex);
}
int numNodes = mIndex.getNumNodes(path);
// It's impossible that numNodes is 0 at this point because render() is
// called from arnoldProceduralGetNode. And arnoldProceduralGetNode is
// called after arnoldProceduralNumNodes. If the number of nodes is 0,
// render() should never be called.
assert(numNodes > 0);
// This is to ensure the id we get is independant of whether material
// were forced to be scanned or not. In any other case than point instancer
// the number of nodes returned to arnold was multiply by 2, that explain
// the manipulation bellow.
id = id % (numNodes * 2);
// Since we output a reference and an instance for each object, the real id
// is id % numNodes. With this we can use variants if variant is 0, we need
// to output a reference object. Otherwise we need to output an instance. We
// use following terminology: a reference is an invisible object that
// contains the actual mesh data, and an instance is an object with the
// transformation matrix and it uses the data of the instance to draw a
// mesh.
int realID = id % numNodes;
int variant = id / numNodes;
const SdfPath* primPath = mIndex.getPath(path, realID);
if (!primPath)
{
// Just in case.
return nullptr;
}
// Check if it's a shader or something.
const UsdPrim prim = mStage->GetPrimAtPath(*primPath);
if (prim.IsInstance() && prim.IsInstanceable())
{
// We are here because user specified he wants to render precisely this
// object. We know that it was the user because we never create bounding
// boxes that point to instances. Instead, we continue iteration inside
// the master object as it's the "continuation" of the instance. So we
// need to continue iteration inside the master, outputBBox will
// automatically handle it.
if (variant == 0)
{
return mPlugin.outputBBox(prim, times, userData, mIndex);
}
return nullptr;
}
if (mPlugin.isImmediate(prim))
{
if (variant == 0)
{
RendererIndex::RenderNodeMap::accessor accessor;
mIndex.getRenderNodeData(*primPath, accessor);
// First pass of shading nodes. We need to create Arnold nodes
// without any connections. That's why we output null.
accessor->second =
mPlugin.outputReference(prim, times, userData, mIndex);
return nullptr;
}
else
{
RendererIndex::RenderNodeMap::const_accessor accessor;
if (mIndex.getRenderNodeData(*primPath, accessor))
{
// The second pass. Add the connections and output the node.
mPlugin.establishConnections(prim, accessor->second, mIndex);
return accessor->second;
}
}
return nullptr;
}
if (path == *primPath)
{
// We are here because we need to output a reference or an instance.
if (variant == 0)
{
RendererIndex::RenderNodeMap::accessor accessor;
mIndex.getRenderNodeData(*primPath, accessor);
if (!accessor->second)
{
// Output reference and save the node.
accessor->second =
mPlugin.outputReference(prim, times, userData, mIndex);
return accessor->second;
}
}
else
{
RendererIndex::RenderNodeMap::const_accessor accessor;
if (mIndex.getRenderNodeData(*primPath, accessor) &&
accessor->second)
{
// Output instance. Render object.
return mPlugin.render(
prim, times, accessor->second, userData, mIndex);
}
}
}
else if (variant == 0)
{
// We are here because we need to output the procedural that can contain
// other procedurals/instances/references.
return mPlugin.outputBBox(prim, times, userData, mIndex);
}
return nullptr;
}
void RendererEngine::prepare(const UsdPrim& root)
{
mDelegate.populate(root);
}
<|start_filename|>walter/maya/walterMtoaConnection/convertToArnold.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __CONVERT_TO_ARNOLD_H__
#define __CONVERT_TO_ARNOLD_H__
#include <maya/MPxCommand.h>
#include <maya/MSyntax.h>
/** @brief A MEL command that exports given objects to Arnold and returns the
* description of the objects using Json. */
class ConvertToArnoldCmd : public MPxCommand
{
public:
ConvertToArnoldCmd(){};
static void* creator() { return new ConvertToArnoldCmd; }
static MSyntax syntax();
virtual MStatus doIt(const MArgList&);
};
#endif
<|start_filename|>walter/arnold/procedural/plugin.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __PLUGIN_H__
#define __PLUGIN_H__
#include <pxr/base/tf/debug.h>
#include <pxr/usd/usd/attribute.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usdGeom/bboxCache.h>
// Declare USD debugging messages.
PXR_NAMESPACE_OPEN_SCOPE
TF_DEBUG_CODES(WALTER_ARNOLD_PLUGIN);
PXR_NAMESPACE_CLOSE_SCOPE
PXR_NAMESPACE_USING_DIRECTIVE
struct RendererPluginData
{
std::string prefix;
std::string filePaths;
boost::optional<float> motionStart;
boost::optional<float> motionEnd;
};
class AtNode;
class RendererAttribute;
class RendererIndex;
typedef std::unordered_map<std::string, RendererAttribute> NameToAttribute;
class RendererAttribute
{
public:
typedef std::function<void(AtNode*)> ArnoldParameter;
typedef std::shared_ptr<ArnoldParameter> ArnoldParameterPtr;
RendererAttribute(ArnoldParameterPtr function) :
mFunction(function),
mVisibility(false),
mVisibilityFlag(0)
{}
RendererAttribute(const RendererAttribute& src) :
mFunction(src.mFunction),
mVisibility(src.mVisibility),
mVisibilityFlag(src.mVisibilityFlag)
{}
/**
* @brief Constructs visibility attribute.
*
* @param visibilityFlag The visibility flag to save.
*/
RendererAttribute(uint8_t visibilityFlag) :
mFunction(nullptr),
mVisibility(true),
mVisibilityFlag(visibilityFlag)
{}
void evaluate(AtNode* node) const;
bool valid() const;
/**
* @brief Returns true if it's a visibility attribute.
*/
bool isVisibility() const;
/**
* @brief Returns the visibility flag if it's a visibility attribte.
*/
uint8_t visibilityFlag() const;
private:
ArnoldParameterPtr mFunction;
// True if this attribute contains a visiblity flag.
bool mVisibility;
uint8_t mVisibilityFlag;
};
// Everything related to the conversion from USD to Arnold is here.
class RendererPlugin
{
public:
RendererPlugin();
// True if it's a supported privitive.
bool isSupported(const UsdPrim& prim) const;
// True it it's necessary to output it immediatly and avoid self-expanding
// stuff.
bool isImmediate(const UsdPrim& prim) const;
// Output the procedural from any prim.
void* output(
const UsdPrim& prim,
const std::vector<float>& times,
const void* userData
) const;
// Output the procedural with the primitive.
void* outputBBox(
const UsdPrim& prim,
const std::vector<float>& times,
const void* userData,
RendererIndex& index) const;
// Output the procedural from a point of the PointInstancer.
void* outputBBoxFromPoint(
const UsdPrim& prim,
const int id,
const std::vector<float>& times,
const void* userData,
RendererIndex& index) const;
// Output an object and return AiNode.
void* outputReference(
const UsdPrim& prim,
const std::vector<float>& times,
const void* userData,
RendererIndex& index) const;
// Set the Arnold connections for the node specified with data. We need the
// index to get the pointers to another nodes.
void establishConnections(
const UsdPrim& prim,
void* data,
RendererIndex& index) const;
// Output polymesh. We need index to access the shaders.
void* render(
const UsdPrim& prim,
const std::vector<float>& times,
void* renderData,
const void* userData,
RendererIndex& index) const;
// Return an object that it's possible use to output Arnold parameter.
// Basically, it convers UsdAttribute to Arnold Parameter.
RendererAttribute createRendererAttribute(
const UsdAttribute& attr,
UsdTimeCode time = UsdTimeCode::Default()) const;
private:
AtNode* outputGeomMesh(
const UsdPrim& prim,
const std::vector<float>& times,
const char* name,
const void* userData) const;
AtNode* outputGeomCurves(
const UsdPrim& prim,
const std::vector<float>& times,
const char* name,
const void* userData) const;
AtNode* outputShader(
const UsdPrim& prim,
const std::vector<float>& times,
const char* name) const;
void outputPrimvars(
const UsdPrim& prim,
float times,
AtNode* node,
const VtIntArray* numVertsArray,
const int pointInstanceId=-1) const;
/**
* @brief Returns path to walterOverride object assigned to the given node
* and computes the visibility of the given node. We need it as a separate
* function to be able to skip the object if it's not visible.
*
* @param path USD path to the object.
* @param layer "defaultRenderLayer"
* @param userData The arnold user data.
* @param index RendererIndex object.
* @param oVisibility The computed visibility.
*
* @return Path to walterOverride object assigned to the given node.
*/
const NameToAttribute* getAssignedAttributes(
const SdfPath& path,
const std::string& layer,
const void* userData,
RendererIndex& index,
uint8_t* oVisibility) const;
/**
* @brief Ouput attributes and shaders to Arnold node.
*
* @param node Arnold node.
* @param path USD path.
* @param attributePath USD path to the walterOverride object.
* @param index RendererIndex object.
* @param layer "defaultRenderLayer"
* @param userData The arnold user data.
* @param forReference True if it's necessary to output attributes of the
* reference.
*/
void outputAttributes(
AtNode* node,
const SdfPath& path,
const NameToAttribute* attributes,
RendererIndex& index,
const std::string& layer,
const void* userData,
bool forReference) const;
/**
* @brief Output shader or displacemet.
*
* @param node Arnold node.
* @param objectName USD path. It's a string because we keep all the
* assignments as strings and resolve them with boost::regex as std::string.
* @param index RendererIndex object.
* @param layer "defaultRenderLayer"
* @param target "shader" or "displacement"
*/
void outputShadingAttribute(
AtNode* node,
const std::string& objectName,
RendererIndex& index,
const std::string& layer,
const std::string& target) const;
/**
* @brief It's a hack. We can't disable objects with Walter Override because
* of Arnold bug. We filed the bug report to Solid Angle on Nov 7 and still
* waiting them. The subject of email is "Issue with our custom procedural [
* ref:_00DD0rHEv._500D01aInPJ:ref ]". So to disable the object we output a
* very small point that is visible only for volume rays.
*
* @param iNodeName the arnold name of the node.
*
* @return The Arnold node.
*/
void* outputEmptyNode(const std::string& iNodeName) const;
};
#endif
<|start_filename|>walter/katana/WalterIn/ScalarPropUtils.h<|end_filename|>
#ifndef FnGeolibOp_WalterIn_ScalarPropUtils_H
#define FnGeolibOp_WalterIn_ScalarPropUtils_H
#include <Alembic/Abc/All.h>
#include <FnAttribute/FnGroupBuilder.h>
#include "AbcCook.h"
namespace WalterIn
{
void scalarPropertyToAttr(
Alembic::Abc::ICompoundProperty & iParent,
const Alembic::AbcCoreAbstract::PropertyHeader & iHeader,
const std::string & iPropName,
AbcCookPtr ioCook,
Foundry::Katana::GroupBuilder & oStaticGb);
void scalarPropertyToAttr(ScalarProp & iProp,
const OpArgs & iArgs,
Foundry::Katana::GroupBuilder & oGb);
}
#endif
<|start_filename|>walter/common/PathUtil.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "PathUtil.h"
#include <boost/algorithm/string.hpp>
#include <boost/range/algorithm/count_if.hpp>
#include <boost/regex.hpp>
#include <boost/tokenizer.hpp>
/**
* @brief Erase everything in a string between two symbols.
*
* @param ioStr Input-output string.
* @param iOpen The open bracket.
* @param iClose The close bracket.
*/
void eraseBrackets(std::string& ioStr, char iOpen, char iClose)
{
size_t foundOpen = 0;
while (true)
{
size_t foundOpen = ioStr.find(iOpen);
if (foundOpen == std::string::npos)
{
break;
}
size_t foundClose = ioStr.find(iClose, foundOpen);
if (foundClose == std::string::npos)
{
break;
}
ioStr.erase(foundOpen, foundClose - foundOpen);
}
}
bool WalterCommon::matchPattern(const std::string& str, const std::string& pat)
{
void* rx = createRegex(pat);
bool result = searchRegex(rx, str);
clearRegex(rx);
return result;
}
void* WalterCommon::createRegex(const std::string& exp)
{
return new boost::regex(exp);
}
bool WalterCommon::searchRegex(void* regex, const std::string& str)
{
return boost::regex_match(str, *reinterpret_cast<boost::regex*>(regex));
}
std::string WalterCommon::mangleString(const std::string& expression)
{
return boost::replace_all_copy(expression, "/", "\\");
}
std::string WalterCommon::demangleString(const std::string& expression)
{
return boost::replace_all_copy(expression, "\\", "/");
}
std::string WalterCommon::convertRegex(const std::string& expression)
{
std::string expr = boost::replace_all_copy(expression, "\\d", "[0-9]");
boost::replace_all(expr, "\\D", "[^0-9]");
boost::replace_all(expr, "\\w", "[a-zA-Z0-9_]");
boost::replace_all(expr, "\\W", "[^a-zA-Z0-9_]");
return expr;
}
void WalterCommon::clearRegex(void* regex)
{
delete reinterpret_cast<boost::regex*>(regex);
}
WalterCommon::Expression::Expression(const std::string& iExpression) :
mExpression(iExpression),
mMinSize(mExpression.size())
{
// The list of characters that characterize a regex.
static const char* sExpChars = ".*+|<>&-[](){}?$^\\";
// We need to detect if it's an expression to be able to skip expensive
// matching stuff.
if (boost::find_token(mExpression, boost::is_any_of(sExpChars)))
{
mRegex = createRegex(mExpression);
// Compute the minimal number of characters in the object name and the
// text of the expression without regex special symbols. It can be a
// good filter.
mTextWithoutRegex = mExpression;
// Don't consider anything inside brackets.
eraseBrackets(mTextWithoutRegex, '[', ']');
eraseBrackets(mTextWithoutRegex, '(', ')');
eraseBrackets(mTextWithoutRegex, '{', '}');
mTextWithoutRegex.erase(
std::remove_if(
mTextWithoutRegex.begin(),
mTextWithoutRegex.end(),
boost::is_any_of(sExpChars)),
mTextWithoutRegex.end());
// Don't consider anything from sExpChars.
mMinSize = mTextWithoutRegex.size();
}
else
{
mRegex = nullptr;
}
}
WalterCommon::Expression::~Expression()
{
if (mRegex)
{
clearRegex(mRegex);
}
}
bool WalterCommon::Expression::isParentOf(
const std::string& iFullName,
bool* oIsItself) const
{
if (isRegex() || iFullName.size() < mMinSize)
{
// Filter them out.
return false;
}
if (boost::starts_with(iFullName, mExpression))
{
if (iFullName.size() == mMinSize)
{
// Two strings exactly match.
if (oIsItself)
{
*oIsItself = true;
}
return true;
}
// We are here because the length of iFullName is more than mMinSize. We
// need to check that it's a parent and we don't have a case like this:
// "/Hello" "/HelloWorld".
return iFullName[mMinSize] == '/';
}
return false;
}
bool WalterCommon::Expression::matchesPath(const std::string& iFullName) const
{
if (!isRegex() || iFullName.size() < mMinSize)
{
// Filter them out.
return false;
}
return searchRegex(mRegex, iFullName);
}
bool WalterCommon::Expression::matchesPath(
const WalterCommon::Expression& iExpression) const
{
if (!isRegex())
{
// Filter them out.
return false;
}
if (!iExpression.isRegex())
{
// The inpot is a string, we can match is as a string.
return matchesPath(iExpression.getExpression());
}
// We need to match it with something left from the expression.
return matchesPath(iExpression.mTextWithoutRegex);
}
<|start_filename|>walter/maya/mtoa/plugin.cpp<|end_filename|>
#include "walterTranslator.h"
#include "extension/Extension.h"
extern "C" {
DLLEXPORT void initializeExtension(CExtension& plugin)
{
MStatus status;
status = plugin.RegisterTranslator("walterStandin",
"",
CWalterStandinTranslator::creator,
CWalterStandinTranslator::NodeInitializer);
}
DLLEXPORT void deinitializeExtension(CExtension& plugin)
{
}
}
<|start_filename|>walter/katana/WalterIn/NuPatchCook.cpp<|end_filename|>
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ScalarPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
void evalNuPatch(Alembic::AbcGeom::INuPatchSchema & iSchema,
const OpArgs & iArgs,
bool iIgnoreConstant,
FnAttribute::GroupBuilder & oGb)
{
Alembic::Abc::IP3fArrayProperty pointsProp =
iSchema.getPositionsProperty();
Alembic::Abc::IFloatArrayProperty weightsProp =
iSchema.getPositionWeightsProperty();
Alembic::Abc::TimeSamplingPtr ts = iSchema.getTimeSampling();
SampleTimes sampleTimes;
iArgs.getRelevantSampleTimes(ts, iSchema.getNumSamples(), sampleTimes);
if (!iIgnoreConstant || !pointsProp.isConstant() ||
!weightsProp.isConstant())
{
FnAttribute::FloatBuilder pwBuilder(4);
for (SampleTimes::iterator it = sampleTimes.begin();
it != sampleTimes.end(); ++it)
{
Alembic::Util::Dimensions dims;
Alembic::Abc::ISampleSelector ss(*it);
pointsProp.getDimensions(dims, ss);
size_t numPoints = dims.numPoints();
size_t numWeights = 0;
if (weightsProp.valid())
{
weightsProp.getDimensions(dims, ss);
numWeights = dims.numPoints();
}
std::vector< float > pointsVal;
std::vector< float > weightsVal;
// make it bigger than what we need
pointsVal.resize(numPoints * 4);
if (numPoints != 0)
{
pointsProp.getAs(&(pointsVal.front()), ss);
}
if (numPoints == numWeights && numPoints != 0)
{
weightsVal.resize(numPoints);
weightsProp.getAs(&(weightsVal.front()), ss);
}
for (std::size_t i = numPoints; i > 0; --i)
{
if (weightsVal.empty())
{
pointsVal[(i - 1) * 4 + 3] = 1.0f;
}
else
{
pointsVal[(i - 1) * 4 + 3] = weightsVal[i - 1];
}
pointsVal[(i - 1) * 4 + 2] = pointsVal[(i - 1) * 3 + 2];
pointsVal[(i - 1) * 4 + 1] = pointsVal[(i - 1) * 3 + 1];
pointsVal[(i - 1) * 4 ] = pointsVal[(i - 1) * 3 ];
}
if (sampleTimes.size() == 1)
{
// hopefully this will use a fancy attr
oGb.set("geometry.point.Pw",
FnAttribute::FloatAttribute(&(pointsVal.front()),
pointsVal.size(), 4));
}
else
{
pwBuilder.set(pointsVal, iArgs.getRelativeSampleTime(*it));
}
}
if (sampleTimes.size() > 1)
{
oGb.set("geometry.point.Pw", pwBuilder.build());
}
}
// handle u.min, u.max, v.min, v.max and the knots themselves
Alembic::Abc::IFloatArrayProperty uknotProp =
iSchema.getUKnotsProperty();
if (!iIgnoreConstant || !uknotProp.isConstant())
{
FnAttribute::FloatBuilder uBuilder;
FnAttribute::FloatBuilder umaxBuilder;
for (SampleTimes::iterator it = sampleTimes.begin();
it != sampleTimes.end(); ++it)
{
Alembic::Abc::ISampleSelector ss(*it);
Alembic::Util::Dimensions dims;
uknotProp.getDimensions(dims, ss);
size_t numU = dims.numPoints();
std::vector< float > uVal(numU);
if (numU != 0)
{
uknotProp.getAs(&(uVal.front()), ss);
umaxBuilder.push_back(uVal[uVal.size() - 1],
iArgs.getRelativeSampleTime(*it));
}
uBuilder.set(uVal, iArgs.getRelativeSampleTime(*it));
}
oGb.set("geometry.u.knots", uBuilder.build());
oGb.set("geometry.u.min", FnAttribute::FloatAttribute(0.0));
oGb.set("geometry.u.max", umaxBuilder.build());
}
Alembic::Abc::IFloatArrayProperty vknotProp =
iSchema.getVKnotsProperty();
if (!iIgnoreConstant || !vknotProp.isConstant())
{
FnAttribute::FloatBuilder vBuilder;
FnAttribute::FloatBuilder vmaxBuilder;
for (SampleTimes::iterator it = sampleTimes.begin();
it != sampleTimes.end(); ++it)
{
Alembic::Abc::ISampleSelector ss(*it);
Alembic::Util::Dimensions dims;
vknotProp.getDimensions(dims, ss);
size_t numV = dims.numPoints();
std::vector< float > vVal(numV);
if (numV != 0)
{
vknotProp.getAs(&(vVal.front()), ss);
vmaxBuilder.push_back(vVal[vVal.size() - 1],
iArgs.getRelativeSampleTime(*it));
}
vBuilder.set(vVal, iArgs.getRelativeSampleTime(*it));
}
oGb.set("geometry.v.knots", vBuilder.build());
oGb.set("geometry.v.min", FnAttribute::FloatAttribute(0.0));
oGb.set("geometry.v.max", vmaxBuilder.build());
}
}
void cookNuPatch(AbcCookPtr ioCook, FnAttribute::GroupBuilder & oStaticGb)
{
Alembic::AbcGeom::INuPatchPtr objPtr(
new Alembic::AbcGeom::INuPatch(*(ioCook->objPtr),
Alembic::AbcGeom::kWrapExisting));
Alembic::AbcGeom::INuPatchSchema schema = objPtr->getSchema();
oStaticGb.set("type", FnAttribute::StringAttribute("nurbspatch"));
Alembic::Abc::ICompoundProperty userProp = schema.getUserProperties();
Alembic::Abc::ICompoundProperty arbGeom = schema.getArbGeomParams();
std::string abcUser = "abcUser.";
processUserProperties(ioCook, userProp, oStaticGb, abcUser);
processArbGeomParams(ioCook, arbGeom, oStaticGb);
Alembic::AbcGeom::IV2fGeomParam uvsProp = schema.getUVsParam();
if (uvsProp.valid())
{
processArbitraryGeomParam(ioCook, schema, uvsProp.getHeader(),
oStaticGb, "geometry.arbitrary.st");
}
Alembic::AbcGeom::IN3fGeomParam normProp = schema.getNormalsParam();
if (normProp.valid())
{
Alembic::AbcGeom::GeometryScope scope = normProp.getScope();
if (scope == Alembic::AbcGeom::kVertexScope)
{
processArbitraryGeomParam(ioCook, schema, normProp.getHeader(),
oStaticGb, "geometry.point.N");
}
else
{
processArbitraryGeomParam(ioCook, schema, normProp.getHeader(),
oStaticGb, "geometry.arbitrary.N");
}
}
Alembic::Abc::IV3fArrayProperty velocProp =
schema.getVelocitiesProperty();
if (velocProp.valid())
{
arrayPropertyToAttr(schema, velocProp.getHeader(),
"geometry.point.v", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
Alembic::Abc::IBox3dProperty boundsProp =
schema.getSelfBoundsProperty();
if (boundsProp.valid())
{
scalarPropertyToAttr(schema, boundsProp.getHeader(),
"bound", ioCook, oStaticGb);
}
const Alembic::AbcCoreAbstract::PropertyHeader * propHeader;
// uOrder, vOrder, nu, nv don't have getters so we'll do it directly
propHeader = schema.getPropertyHeader("uOrder");
if (propHeader != NULL)
{
scalarPropertyToAttr(schema, *propHeader, "geometry.u.order",
ioCook, oStaticGb);
}
propHeader = schema.getPropertyHeader("vOrder");
if (propHeader != NULL)
{
scalarPropertyToAttr(schema, *propHeader, "geometry.v.order",
ioCook, oStaticGb);
}
propHeader = schema.getPropertyHeader("nu");
if (propHeader != NULL)
{
scalarPropertyToAttr(schema, *propHeader, "geometry.uSize",
ioCook, oStaticGb);
}
propHeader = schema.getPropertyHeader("nv");
if (propHeader != NULL)
{
scalarPropertyToAttr(schema, *propHeader, "geometry.vSize",
ioCook, oStaticGb);
}
// trim stuff, INuPatch currently doesn't have getters for this, so
// we will try to get it directly
propHeader = schema.getPropertyHeader("trim_n");
if (propHeader != NULL)
{
arrayPropertyToAttr(schema, *propHeader,
"geometry.trimCurves.trim_n", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
propHeader = schema.getPropertyHeader("trim_ncurves");
if (propHeader != NULL)
{
arrayPropertyToAttr(schema, *propHeader,
"geometry.trimCurves.trim_ncurves", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
propHeader = schema.getPropertyHeader("trim_order");
if (propHeader != NULL)
{
arrayPropertyToAttr(schema, *propHeader,
"geometry.trimCurves.trim_order", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
// read all of these as doubles
propHeader = schema.getPropertyHeader("trim_knot");
if (propHeader != NULL)
{
arrayPropertyToAttr(schema, *propHeader,
"geometry.trimCurves.trim_knot", kFnKatAttributeTypeDouble,
ioCook, oStaticGb);
}
propHeader = schema.getPropertyHeader("trim_min");
if (propHeader != NULL)
{
arrayPropertyToAttr(schema, *propHeader,
"geometry.trimCurves.trim_min", kFnKatAttributeTypeDouble,
ioCook, oStaticGb);
}
propHeader = schema.getPropertyHeader("trim_max");
if (propHeader != NULL)
{
arrayPropertyToAttr(schema, *propHeader,
"geometry.trimCurves.trim_max", kFnKatAttributeTypeDouble,
ioCook, oStaticGb);
}
propHeader = schema.getPropertyHeader("trim_u");
if (propHeader != NULL)
{
arrayPropertyToAttr(schema, *propHeader,
"geometry.trimCurves.trim_u", kFnKatAttributeTypeDouble,
ioCook, oStaticGb);
}
propHeader = schema.getPropertyHeader("trim_v");
if (propHeader != NULL)
{
arrayPropertyToAttr(schema, *propHeader,
"geometry.trimCurves.trim_v", kFnKatAttributeTypeDouble,
ioCook, oStaticGb);
}
propHeader = schema.getPropertyHeader("trim_w");
if (propHeader != NULL)
{
arrayPropertyToAttr(schema, *propHeader,
"geometry.trimCurves.trim_w", kFnKatAttributeTypeDouble,
ioCook, oStaticGb);
}
if (!schema.isConstant())
{
ioCook->objPtr = objPtr;
ioCook->animatedSchema = true;
}
else
{
OpArgs defaultArgs;
evalNuPatch(schema, defaultArgs, false, oStaticGb);
}
}
}
<|start_filename|>walter/maya/mtoa/walterTranslator.cpp<|end_filename|>
#include "walterTranslator.h"
#include <ai_array.h>
#include <ai_nodes.h>
#include <ai_ray.h>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <vector>
#include "attributes/AttrHelper.h"
#include "common/UtilityFunctions.h"
#include "mayaUtils.h"
#include <maya/MBoundingBox.h>
#include <maya/MDagPath.h>
#include <maya/MFileObject.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MFnStringArrayData.h>
#include <maya/MPlugArray.h>
#include <maya/MRenderUtil.h>
#include <maya/MSelectionList.h>
#include <sstream>
#ifdef _WIN32
#include <platform/win32/dirent.h>
#define LIBEXT MString(".dll")
#else
#include <sys/types.h>
#include <dirent.h>
#include <dlfcn.h>
#endif
CWalterStandinTranslator::CWalterStandinTranslator() :
m_arnoldRootNode(NULL)
{
}
AtNode* CWalterStandinTranslator::GetArnoldRootNode()
{
return m_arnoldRootNode;
}
AtNode* CWalterStandinTranslator::CreateArnoldNodes()
{
m_arnoldRootNode = AddArnoldNode("walter");
return m_arnoldRootNode;
}
void CWalterStandinTranslator::ProcessRenderFlagsCustom(AtNode* node)
{
AiNodeSetByte(node, "visibility", ComputeVisibility());
MPlug plug;
if(m_DagNode.findPlug("aiSelfShadows").asBool() == false)
ProcessParameter(node, "self_shadows", AI_TYPE_BOOLEAN, "aiSelfShadows");
if(m_DagNode.findPlug("aiOpaque").asBool() == false)
ProcessParameter(node, "opaque", AI_TYPE_BOOLEAN, "aiOpaque");
if(m_DagNode.findPlug("aiMatte").asBool() == true)
ProcessParameter(node, "matte", AI_TYPE_BOOLEAN, "aiMatte");
if(m_DagNode.findPlug("receiveShadows").asBool() == false)
ProcessParameter(node, "receive_shadows", AI_TYPE_BOOLEAN, "receiveShadows");
MStatus status;
plug = FindMayaPlug("aiSssSetname", &status);
if (status && !plug.isNull())
{
MString setname = plug.asString();
if (setname != "")
{
AiNodeDeclareConstant(node, "sss_setname", AI_TYPE_STRING);
AiNodeSetStr(node, "sss_setname", setname.asChar());
}
}
ExportTraceSets(node, FindMayaPlug("aiTraceSets"));
}
void CWalterStandinTranslator::Export(AtNode* procedural)
{
ExportProcedural(procedural, false);
}
void CWalterStandinTranslator::ExportProcedural(AtNode* procedural, bool update)
{
MStatus stat;
m_DagNode.setObject(m_dagPath.node());
ExportMatrix(procedural);
ProcessRenderFlagsCustom(procedural);
if (!update)
{
// Export material assigned on the node.
ExportStandinsShaders(procedural);
AiNodeSetStr(procedural, "name", m_dagPath.partialPathName().asChar());
// Try to find the procedural name on the standin node.
MString procLib = m_DagNode.findPlug("arnoldProcedural").asString();
if (!procLib.length())
{
// Use the standard name if not found.
procLib = MString("walterProcedural") + LIBEXT;
}
// Split the string with ":" symbol, expand all the filenames and join
// it back.
std::string cacheFileName(
m_DagNode.findPlug("cacheFileName").asString().asChar());
// Split the line with ":" symbol and put everything to Alembic. We
// don't use MString::split() because it skips empty lines. We need
// everything, otherwise we have errors in matching visibilities and
// layers.
std::vector<std::string> archives;
// TODO: Windows paths
boost::split(archives, cacheFileName, boost::is_any_of(":"));
MString abcfiles;
MPlug renderables = m_DagNode.findPlug("renderables");
for (unsigned i=0; i<archives.size(); i++)
{
MString archive(archives[i].c_str());
if (!renderables.isNull())
{
// Skip it if it's not renderable
MPlug renderable = renderables.elementByLogicalIndex(i);
if (!renderable.asBool())
{
continue;
}
}
// Compute the resolved filename
MFileObject fileObject;
fileObject.setRawFullName(archive);
fileObject.setResolveMethod(MFileObject::kInputFile);
if (abcfiles.length())
{
abcfiles += ":";
}
MString resolved = fileObject.resolvedFullName();
if (resolved.length())
{
abcfiles += resolved.expandEnvironmentVariablesAndTilde();
}
else
{
abcfiles += archive.expandEnvironmentVariablesAndTilde();
}
}
// TODO: do we still need this block? We export nodes directly from our
// connections. We might need this for compatibility with the first
// versions.
MPlug shaders = m_DagNode.findPlug("shaders", &stat);
if(stat == MS::kSuccess)
{
for (unsigned int i=0;i<shaders.numElements();++i)
{
MPlug plug = shaders.elementByPhysicalIndex(i, &stat);
if(stat == MS::kSuccess)
{
MPlugArray connections;
plug.connectedTo(connections, true, false, &stat);
if(stat == MS::kSuccess)
for (unsigned int k=0; k<connections.length(); ++k)
{
MPlug sgPlug = connections[k];
if (sgPlug.node().apiType() == MFn::kShadingEngine || sgPlug.node().apiType() == MFn::kDisplacementShader)
{
ExportConnectedNode(sgPlug);
}
}
}
}
}
MPlug usdSessionLayer = m_DagNode.findPlug("USDSessionLayer");
MPlug usdVariantsLayer = m_DagNode.findPlug("USDVariantsLayer");
MPlug usdMayaStateLayer = m_DagNode.findPlug("USDMayaStateLayer");
MPlug usdPurposeLayer = m_DagNode.findPlug("USDPurposeLayer");
MPlug usdVisibilityLayer = m_DagNode.findPlug("USDVisibilityLayer");
ExportMayaShadingGraph();
// It's a list of materials from the Alembic file.
// We don't use MStringArray because MStringArray::indexOf() absent in
// our Maya SDK for unknown reason.
std::vector<MString> embeddedShaderList;
const MPlug embeddedShaders = m_DagNode.findPlug("embeddedShaders");
if (!embeddedShaders.isNull())
{
unsigned int numElements = embeddedShaders.numElements();
embeddedShaderList.reserve(numElements);
for (unsigned int i=0; i<numElements; i++)
{
embeddedShaderList.push_back(
embeddedShaders.elementByLogicalIndex(i).asString());
}
}
ExportFrame(procedural);
AiNodeSetStr(procedural, "objectPath", "/");
static const MTime sec(1.0, MTime::kSeconds);
float fps = sec.as(MTime::uiUnit());
AiNodeDeclare(procedural, "fps", "constant FLOAT");
AiNodeSetFlt(procedural, "fps", fps);
AiNodeSetStr(procedural, "filePaths", abcfiles.asChar());
// Output the USD session layer if exists.
if (!usdSessionLayer.isNull())
{
MString sessionLayer = usdSessionLayer.asString();
if (sessionLayer.length())
{
AiNodeSetStr(procedural, "sessionLayer", sessionLayer.asChar());
}
}
// Output the USD variants layer if exists.
if (!usdVariantsLayer.isNull())
{
MString variantsLayer = usdVariantsLayer.asString();
if (variantsLayer.length())
{
AiNodeSetStr(procedural, "variantsLayer", variantsLayer.asChar());
}
}
// Output the USD puropse layer if exists.
if (!usdPurposeLayer.isNull())
{
MString purposeLayer = usdPurposeLayer.asString();
if (purposeLayer.length())
{
AiNodeSetStr(procedural, "purposeLayer", purposeLayer.asChar());
}
}
// Output the USD session layer if exists.
if (!usdMayaStateLayer.isNull())
{
MString mayaStateLayer = usdMayaStateLayer.asString();
if (mayaStateLayer.length())
{
AiNodeSetStr(
procedural, "mayaStateLayer", mayaStateLayer.asChar());
}
}
// Output the USD visiblity layer if exists.
if (!usdVisibilityLayer.isNull())
{
MString visibilityLayer = usdVisibilityLayer.asString();
if (visibilityLayer.length())
{
AiNodeSetStr(procedural, "visibilityLayer", visibilityLayer.asChar());
}
}
// MTOA does this for every node.
if (RequiresMotionData())
{
double motionStart, motionEnd;
GetSessionOptions().GetMotionRange(motionStart, motionEnd);
AiNodeSetFlt(procedural, "motion_start", (float)motionStart);
AiNodeSetFlt(procedural, "motion_end", (float)motionEnd);
}
}
}
void CWalterStandinTranslator::ExportShaders()
{
ExportStandinsShaders(GetArnoldRootNode());
}
void CWalterStandinTranslator::ExportStandinsShaders(AtNode* procedural)
{
int instanceNum = m_dagPath.isInstanced() ? m_dagPath.instanceNumber() : 0;
MPlug shadingGroupPlug = GetNodeShadingGroup(m_dagPath.node(), instanceNum);
if (!shadingGroupPlug.isNull())
{
AtNode *shader = ExportConnectedNode(shadingGroupPlug);
if (shader != NULL)
{
// We can't put it to "shader" attribute because in this way we will
// not be able to assign different shader.
const char* shaderAttribute = "walterStandinShader";
const AtNodeEntry* nodeEntry = AiNodeGetNodeEntry(procedural);
const AtParamEntry* paramEntry =
AiNodeEntryLookUpParameter(nodeEntry, shaderAttribute);
if (!paramEntry)
{
// The param doesn't exists, add it!
AiNodeDeclare(
procedural,
shaderAttribute,
"constant NODE");
}
AiNodeSetPtr(procedural, shaderAttribute, shader);
}
}
}
void CWalterStandinTranslator::ExportMotion(AtNode* anode)
{
// Check if motionblur is enabled and early out if it's not.
if (!IsMotionBlurEnabled())
{
return;
}
ExportMatrix(anode);
ExportFrame(anode);
}
void CWalterStandinTranslator::NodeInitializer(CAbTranslator context)
{
CExtensionAttrHelper helper(context.maya, "walter");
CShapeTranslator::MakeCommonAttributes(helper);
}
bool CWalterStandinTranslator::ExportMayaShadingGraph()
{
const MPlug layersAssignation = m_DagNode.findPlug("layersAssignation");
if (layersAssignation.isNull())
{
AiMsgWarning(
"[mtoa] [%s] Can't find %s.layersAssignation.",
GetTranslatorName().asChar(),
m_DagNode.name().asChar());
return false;
}
if (layersAssignation.numElements() <= 0)
{
return false;
}
for (unsigned i=0; i<layersAssignation.numElements(); i++)
{
// Get walterStandin.layersAssignation[i]
const MPlug currentLayerCompound =
layersAssignation.elementByPhysicalIndex(i);
// Get walterStandin.layersAssignation[i].layer
MPlug layerPlug;
if (!GetChildMPlug(currentLayerCompound, "layer", layerPlug))
{
continue;
}
MPlugArray connections;
if (!layerPlug.connectedTo(connections, true, false) ||
!connections.length())
{
continue;
}
// The layer is the first connected node. We consider we have only one
// connection.
const MFnDependencyNode layer(connections[0].node());
const std::string layerName = layer.name().asChar();
bool mainLayer = layerName == "defaultRenderLayer";
MPlug shadersPlug;
if (!GetChildMPlug(
currentLayerCompound, "shaderConnections", shadersPlug))
{
continue;
}
for (unsigned j=0; j<shadersPlug.numElements(); j++)
{
// Get walterStandin.layersAssignation[i].shaderConnections[j]
const MPlug shadersCompound = shadersPlug.elementByPhysicalIndex(j);
// Get walterStandin.layersAssignation[].shaderConnections[].abcnode
MPlug abcnodePlug;
if (!GetChildMPlug(shadersCompound, "abcnode", abcnodePlug))
{
continue;
}
const MString abcnode = abcnodePlug.asString().asChar();
if (!abcnode.length())
{
continue;
}
// Get walterStandin.layersAssignation[].shaderConnections[].shader
MPlug shaderPlug;
if (GetChildMPlug(shadersCompound, "shader", shaderPlug))
{
ExportConnections(
abcnode.asChar(), shaderPlug);
}
// The same for displacement
MPlug dispPlug;
if (GetChildMPlug(shadersCompound, "displacement", dispPlug))
{
ExportConnections(abcnode.asChar(), dispPlug);
}
}
}
return true;
}
void CWalterStandinTranslator::ExportConnections(
const char* abcnode, const MPlug& shaderPlug)
{
MPlugArray connections;
if (!shaderPlug.connectedTo(connections, true, false) ||
!connections.length())
{
return;
}
// Push this connection to the shader to Arnold.
ExportConnectedNode(connections[0]);
}
int CWalterStandinTranslator::ComputeWalterVisibility(
const MFnDependencyNode& node)const
{
unsigned visibility = AI_RAY_ALL;
bool exists = false;
MPlug plug;
plug = node.findPlug("walterVisibility");
if (!plug.isNull())
{
exists = true;
if (!plug.asBool())
{
return 0;
}
}
plug = node.findPlug("walterCastsShadows");
if (!plug.isNull())
{
exists = true;
if(!plug.asBool())
{
visibility &= ~AI_RAY_SHADOW;
}
}
plug = node.findPlug("walterPrimaryVisibility");
MString plugName = plug.name();
if (!plug.isNull())
{
exists = true;
if (!plug.asBool())
{
visibility &= ~AI_RAY_CAMERA;
}
}
plug = node.findPlug("walterVisibleInReflections");
if (!plug.isNull())
{
exists = true;
if (!plug.asBool())
{
visibility &= ~AI_RAY_ALL_REFLECT;
}
}
plug = node.findPlug("walterVisibleInRefractions");
if (!plug.isNull())
{
exists = true;
if (!plug.asBool())
{
visibility &= ~AI_RAY_ALL_TRANSMIT;
}
}
plug = node.findPlug("walterVisibleInDiffuse");
if (!plug.isNull())
{
exists = true;
if (!plug.asBool())
{
visibility &= ~AI_RAY_ALL_DIFFUSE;
}
}
plug = node.findPlug("walterVisibleInGlossy");
if (!plug.isNull())
{
exists = true;
if (!plug.asBool())
{
visibility &= ~AI_RAY_ALL_SPECULAR;
}
}
if (!exists)
{
return -1;
}
return visibility;
}
void CWalterStandinTranslator::ExportFrame(AtNode* node)
{
// The reference implementation is CDagTranslator::ExportMatrix.
MTime time = m_DagNode.findPlug("time").asMTime() +
m_DagNode.findPlug("timeOffset").asMTime();
float frame = time.as(time.unit());
if (!IsExportingMotion())
{
// We are here because it's called from Export.
if (RequiresMotionData())
{
int step = GetMotionStep();
AiNodeDeclare(node, "frame", "constant ARRAY FLOAT");
AtArray* frames =
AiArrayAllocate(1, GetNumMotionSteps(), AI_TYPE_FLOAT);
AiArraySetFlt(frames, step, frame);
AiNodeSetArray(node, "frame", frames);
}
else
{
AiNodeDeclare(node, "frame", "constant FLOAT");
AiNodeSetFlt(node, "frame", frame);
}
}
else if (IsMotionBlurEnabled(MTOA_MBLUR_OBJECT) && RequiresMotionData())
{
// We are here because it's called from ExportMotion. Everything should
// be delared. We need to set specific keys in the Arnold attribute.
AtArray* frames = AiNodeGetArray(node, "frame");
if (frames)
{
int step = GetMotionStep();
int arraySize = AiArrayGetNumKeys(frames) * AiArrayGetNumElements(frames);
if (step >= arraySize)
{
AiMsgError(
"Time steps are not set properly for %s",
m_dagPath.partialPathName().asChar());
}
else
{
AiArraySetFlt(frames, step, frame);
}
}
}
}
<|start_filename|>walter/houdini/src/UsdToGtPrim.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "UsdToGtPrim.h"
#include <gusd/curvesWrapper.h>
#include <gusd/meshWrapper.h>
PXR_NAMESPACE_USING_DIRECTIVE
namespace WalterHoudini
{
GT_PrimitiveHandle getGtPrimFromUsd(
const UsdPrim& prim,
const UsdTimeCode& time,
const GusdPurposeSet purpose)
{
GT_PrimitiveHandle gtPrimHandle;
UsdGeomImageable imageable(prim);
if (prim.IsA<UsdGeomMesh>())
{
gtPrimHandle = GusdMeshWrapper::defineForRead(
imageable, time, purpose);
}
else if (prim.IsA<UsdGeomCurves>())
{
gtPrimHandle = GusdCurvesWrapper::defineForRead(
imageable, time, purpose);
}
return gtPrimHandle;
}
}; // end namespace WalterHoudini
<|start_filename|>walter/katana/WalterIn/MaterialCook.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ScalarPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
// When we output attribute "name", we rename the node, and sometimes a node
// with the same name already exists. Arnold can successfully track it, but
// it produces a warning.
static const NameMap shaderAttributes = {
{"name", "original_name"}};
void cookMaterial(
Alembic::AbcMaterial::IMaterialSchema& iSchema,
AbcCookPtr ioCook,
FnAttribute::GroupBuilder& oStaticGb)
{
// We don't use GroupBuilder for groups because if we call this function
// twice, we want to add additional nodes to the current oStaticGb. If
// we use GroupBuilder for "material" or "node" groups, the second call
// override these groups. ...
const std::string material = "material.";
const std::string nodes = material + "nodes.";
for (size_t i = 0, e = iSchema.getNumNetworkNodes(); i < e; ++i)
{
Alembic::AbcMaterial::IMaterialSchema::NetworkNode node =
iSchema.getNetworkNode(i);
// Get name, type and target.
const std::string name(node.getName());
std::string type = "<undefined>";
node.getNodeType(type);
std::string target = "<undefined>";
node.getTarget(target);
// ... But it's good to use GroupBuilder here, because we need to
// override the specific shading node, if we already have it.
FnAttribute::GroupBuilder nodeGroup;
nodeGroup.set("name", FnAttribute::StringAttribute(name));
nodeGroup.set("srcName", FnAttribute::StringAttribute(name));
nodeGroup.set("type", FnAttribute::StringAttribute(type));
nodeGroup.set("target", FnAttribute::StringAttribute(target));
// Fill the parameters.
Alembic::Abc::ICompoundProperty parameters = node.getParameters();
FnAttribute::GroupBuilder parametersGroup;
processUserProperties(
ioCook, parameters, parametersGroup, "", &shaderAttributes);
// Fill the connections.
FnAttribute::GroupBuilder connectionsGroup;
size_t numConnections = node.getNumConnections();
for (size_t i = 0; i < numConnections; ++i)
{
std::string inputName, connectedNodeName, connectedOutputName;
if (!node.getConnection(
i,
inputName,
connectedNodeName,
connectedOutputName))
{
continue;
}
// The name of the connected output should contain "out" to be
// recognized by ktoa.
if (!connectedOutputName.empty())
{
connectedOutputName = "." + connectedOutputName;
}
connectedOutputName = "out" + connectedOutputName;
connectionsGroup.set(
inputName,
FnAttribute::StringAttribute(
connectedOutputName + "@" + connectedNodeName));
}
nodeGroup.set("parameters", parametersGroup.build());
if (numConnections)
{
nodeGroup.set("connections", connectionsGroup.build());
}
oStaticGb.set(nodes + name, nodeGroup.build());
}
// Get terminals.
const std::string terminals = material + "terminals.";
std::vector<std::string> targetNames;
iSchema.getNetworkTerminalTargetNames(targetNames);
for (auto tit = targetNames.begin(); tit != targetNames.end(); tit++)
{
const std::string& targetName = *tit;
std::vector<std::string> shaderTypes;
iSchema.getNetworkTerminalShaderTypesForTarget(
targetName, shaderTypes);
for (auto sit = shaderTypes.begin(); sit!=shaderTypes.end(); sit++)
{
std::string shaderType = *sit;
std::string connectedNodeName = "<undefined>";
std::string connectedOutputName = "out";
if (!iSchema.getNetworkTerminal(
targetName,
shaderType,
connectedNodeName,
connectedOutputName))
{
continue;
}
// it should be "arnoldSurface". We need to be sure that the
// second word is capitalized.
shaderType[0] = toupper(shaderType[0]);
oStaticGb.set(
terminals + targetName + shaderType,
FnAttribute::StringAttribute(connectedNodeName));
oStaticGb.set(
terminals + targetName + shaderType + "Port",
FnAttribute::StringAttribute(connectedOutputName));
}
}
// Set style.
oStaticGb.set(
material + "style",
FnAttribute::StringAttribute("network"));
}
void cookMaterial(AbcCookPtr ioCook, FnAttribute::GroupBuilder& oStaticGb)
{
Alembic::AbcMaterial::IMaterialPtr objPtr(
new Alembic::AbcMaterial::IMaterial(
*(ioCook->objPtr), Alembic::AbcGeom::kWrapExisting));
Alembic::AbcMaterial::IMaterialSchema schema = objPtr->getSchema();
cookMaterial(schema, ioCook, oStaticGb);
// Set type.
oStaticGb.set("type", FnAttribute::StringAttribute("material"));
}
void cookLight(AbcCookPtr ioCook, FnAttribute::GroupBuilder& oStaticGb)
{
Alembic::AbcGeom::ILightPtr objPtr(new Alembic::AbcGeom::ILight(
*(ioCook->objPtr), Alembic::AbcGeom::kWrapExisting));
Alembic::AbcGeom::ILightSchema schema = objPtr->getSchema();
Alembic::AbcMaterial::IMaterialSchema material(
schema.getPtr(), ".material");
cookMaterial(material, ioCook, oStaticGb);
// Set type.
oStaticGb.set("type", FnAttribute::StringAttribute("light"));
}
} //end of namespace WalterIn
<|start_filename|>walter/maya/walterMtoaConnection/abcCacheExportCmd.h<|end_filename|>
/*Abc Shader Exporter
Copyright (c) 2014, <NAME>, All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.*/
#ifndef ABC_CACHE_EXPORT_CMD_H
#define ABC_CACHE_EXPORT_CMD_H
#include <maya/MPxCommand.h>
#include <maya/MSyntax.h>
#include <maya/MString.h>
#include <maya/MSelectionList.h>
#include <maya/MItSelectionList.h>
#include <maya/MDagPath.h>
#include <maya/MItDag.h>
#include <maya/MItDependencyNodes.h>
#include <maya/MArgDatabase.h>
#include <maya/MGlobal.h>
#include <maya/MPlugArray.h>
class abcCacheExportCmd : public MPxCommand {
public:
abcCacheExportCmd() {};
~abcCacheExportCmd() {};
virtual MStatus doIt( const MArgList &args );
virtual MStatus undoIt();
virtual MStatus redoIt();
virtual bool isUndoable() const;
virtual bool hasSyntax() const;
static MSyntax mySyntax();
static void* creator() {return new abcCacheExportCmd;};
bool isHistoryOn() const;
MString commandString() const;
MStatus setHistoryOn( bool state );
MStatus setCommandString( const MString & );
};
#endif //FX_MANAGER_CMD_H
<|start_filename|>walter/maya/walterStandin/walterThreadingUtils.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterThreadingUtils.h"
#include <maya/MFileIO.h>
#include <maya/MFnDagNode.h>
#include <pxr/base/tf/instantiateSingleton.h>
#include <pxr/usd/sdf/layer.h>
#include <pxr/usd/usd/stage.h>
#include <tbb/concurrent_unordered_set.h>
#include <tbb/tbb.h>
#include <boost/noncopyable.hpp>
#include <chrono>
#include <thread>
#include <limits>
#include "walterShapeNode.h"
#include "walterUSDCommonUtils.h"
PXR_NAMESPACE_USING_DIRECTIVE
using namespace WalterMaya;
class WalterLoader : boost::noncopyable
{
public:
typedef WalterLoader This;
/**
* @brief The instance of this singleton.
*
* @return
*/
static WalterLoader& getInstance()
{
return TfSingleton<This>::GetInstance();
}
/**
* @brief Starts loading stage in a background thread.
*
* @param iObj Walter standin to load.
*/
void loadStage(const MObject& iObj)
{
mThreads.emplace_back(loadStageTask, this, iObj);
}
void joinAll()
{
// TODO: mutex
for (auto& t : mThreads)
{
if (t.joinable())
{
t.join();
}
}
mThreads.clear();
}
private:
/**
* @brief The thread function that loads the stage.
*
* @param iLoader
* @param iObj
*/
static void loadStageTask(const WalterLoader* iLoader, MObject iObj)
{
// Maya node
MFnDagNode dagNode(iObj);
ShapeNode* shape = dynamic_cast<ShapeNode*>(dagNode.userNode());
if (!shape)
{
return;
}
// Be sure we get filename when the scene is loaded.
while (MFileIO::isReadingFile())
{
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
// Get the filename and the session layer.
std::string fileName = shape->resolvedCacheFileName().asChar();
std::string session = shape->getSessionLayerBuffer().asChar();
std::string variants = shape->getVariantsLayerBuffer().asChar();
std::string visibility = shape->getVisibilityLayerBuffer().asChar();
std::string purpose = shape->getPurposeLayerBuffer().asChar();
const MPlug timePlug =
MFnDependencyNode(shape->thisMObject()).findPlug(ShapeNode::aTime);
if (!timePlug.isConnected())
{
shape->onTimeChanged(std::numeric_limits<float>::min());
}
// Root layer
SdfLayerRefPtr root = WalterUSDCommonUtils::getUSDLayer(fileName);
// USD stage
UsdStageRefPtr stage;
if (!session.empty())
{
char layername[100];
// We need a unique name because USD can open the previous layer if
// it has the same name.
// TODO: make a really unique name using UUID.
sprintf(layername, "anonymous%i.usda", rand());
SdfLayerRefPtr sessionLayer = SdfLayer::CreateAnonymous(layername);
if (sessionLayer->ImportFromString(session))
{
stage = UsdStage::Open(root, sessionLayer);
}
}
if (!stage)
{
// We are here because the session layer is empty or corrupted.
stage = UsdStage::Open(root);
}
if (!variants.empty())
{
WalterUSDCommonUtils::setUSDVariantsLayer(
stage, variants.c_str());
}
if (!visibility.empty())
{
WalterUSDCommonUtils::setUSDVisibilityLayer(
stage, visibility.c_str());
}
if (!purpose.empty())
{
WalterUSDCommonUtils::setUSDPurposeLayer(
stage, purpose.c_str());
}
// Save the stage to the maya node.
shape->setStage(stage);
// Callback
shape->setJustLoaded();
}
// The vector with all the created threads.
std::vector<tbb::tbb_thread> mThreads;
};
TF_INSTANTIATE_SINGLETON(WalterLoader);
void WalterThreadingUtils::loadStage(const MObject& iObj)
{
WalterLoader::getInstance().loadStage(iObj);
}
void WalterThreadingUtils::joinAll()
{
WalterLoader::getInstance().joinAll();
}
<|start_filename|>walter/houdini/src/GU_WalterPackedImpl.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __GU_WalterPackedImpl__
#define __GU_WalterPackedImpl__
#include <GU/GU_PackedImpl.h>
#include <SYS/SYS_Version.h>
class GU_PrimPacked;
namespace WalterHoudini
{
class GU_WalterPackedImpl : public GU_PackedImpl
{
public:
GU_WalterPackedImpl();
GU_WalterPackedImpl(const GU_WalterPackedImpl& src);
virtual ~GU_WalterPackedImpl();
static void install(GA_PrimitiveFactory* factory);
// Get the type ID for the GU_WalterPackedImpl primitive type.
static GA_PrimitiveTypeId typeId()
{
return theTypeId;
}
// Virtual interface from GU_PackedImpl interface
virtual GU_PackedFactory* getFactory() const;
virtual GU_PackedImpl* copy() const;
virtual void clearData();
virtual bool isValid() const;
virtual bool supportsJSONLoad() const
{
return true;
}
virtual bool loadFromJSON(GU_PrimPacked *prim, const UT_JSONValueMap& options, const GA_LoadMap&)
{
updateFrom(options);
return true;
}
virtual bool save(UT_Options& options, const GA_SaveMap& map) const;
virtual bool getBounds(UT_BoundingBox& box) const;
virtual bool getRenderingBounds(UT_BoundingBox& box) const;
virtual void getVelocityRange(
UT_Vector3& minVelocity,
UT_Vector3& maxVelocity) const;
virtual void getWidthRange(fpreal& min, fpreal& max) const;
// Unpack the procedural into a GU_Detail. By default, this calls
// getGTFull() and converts the GT geometry to a GU_Detail.
virtual bool unpack(GU_Detail& destgdp) const;
virtual bool unpackWithContext(
GU_Detail& destgdp,
GU_PackedContext& context) const;
// Report memory usage (includes all shared memory)
virtual int64 getMemoryUsage(bool inclusive) const;
// Count memory usage using a UT_MemoryCounter in order to count
// shared memory correctly.
virtual void countMemory(
UT_MemoryCounter& memoryCounter,
bool inclusiveUsage) const;
// Member data accessors for intrinsics
const GU_ConstDetailHandle& detail() const
{
return mDetail;
}
void setDetail(const GU_ConstDetailHandle& h)
{
mDetail = h;
}
void setFileName(const UT_StringHolder& v);
UT_StringHolder intrinsicFileName() const
{
return mFileName;
}
UT_StringHolder intrinsicFileName(const GU_PrimPacked* prim) const
{
return intrinsicFileName();
}
void setFileName(GU_PrimPacked* prim, const UT_StringHolder& fileName)
{
setFileName(fileName);
}
void setPrimPath(const UT_StringHolder& v);
UT_StringHolder intrinsicPrimPath() const
{
return mPrimPath;
}
UT_StringHolder intrinsicPrimPath(const GU_PrimPacked* prim) const
{
return intrinsicPrimPath();
}
void setPrimPath(GU_PrimPacked* prim, const UT_StringHolder& p)
{
setPrimPath(p);
}
void setFrame(fpreal frame);
fpreal intrinsicFrame() const
{
return mFrame;
}
fpreal intrinsicFrame(const GU_PrimPacked* prim) const
{
return intrinsicFrame();
}
void setFrame(GU_PrimPacked* prim, fpreal frame) { setFrame(frame); }
void setRendererName(const UT_StringHolder& v);
UT_StringHolder intrinsicRendererName() const
{
return mRendererName;
}
UT_StringHolder intrinsicRendererName(const GU_PrimPacked* prim) const
{
return intrinsicRendererName();
}
void setRendererName(GU_PrimPacked* prim, const UT_StringHolder& p)
{
setRendererName(p);
}
// Note: The caller is responsible for setting the vertex/point for the
// primitive.
// In non-Walter packed primitive code, you probably just want to call
// GU_PrimPacked::build(gdp, "AlembicRef")
// which handles the point creation automatically.
static GU_PrimPacked* build(
GU_Detail& gdp,
const std::string& fileName,
const std::string& primPath,
const std::string& rendererName,
fpreal frame);
void update(const UT_Options& options);
virtual bool load(
GU_PrimPacked* prim,
const UT_Options& options,
const GA_LoadMap& map) override;
virtual void update(GU_PrimPacked* prim, const UT_Options& options) override
{
update(options);
}
static const UT_StringRef usdFileName;
static const UT_StringRef usdFrame;
static const UT_StringRef usdPrimPath;
static const UT_StringRef rendererName;
protected:
/// updateFrom() will update from either UT_Options or UT_JSONValueMap
template <typename T> void updateFrom(const T& options);
private:
void clearWalter();
GU_ConstDetailHandle mDetail;
// Intrinsics
UT_StringHolder mFileName;
UT_StringHolder mPrimPath;
fpreal mFrame;
UT_StringHolder mRendererName;
static GA_PrimitiveTypeId theTypeId;
};
} // end namespace WalterHoudini
#endif
<|start_filename|>walter/maya/walterStandin/walterShaderUtils.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERSHADERUTILS_H_
#define __WALTERSHADERUTILS_H_
#include <pxr/base/gf/vec3f.h>
#include <pxr/usd/usd/attribute.h>
#include <pxr/usd/usdShade/connectableAPI.h>
#include <string>
PXR_NAMESPACE_USING_DIRECTIVE
namespace walterShaderUtils
{
/**
* @brief Scans shading network and returns the main texture or the main color
* if the texture is not found.
*
* @param shaderObj Maya shader as MObject or UsdShadeShader.
* @param oTexture Returned texture.
* @param oColor Returned color.
*/
template <typename T>
void getTextureAndColor(
const T& shaderObj,
std::string& oTexture,
GfVec3f& oColor);
/**
* @brief Checks the image and saves only one specific mipmap to the image in
* the temporary directory.
*
* @param filename Requested image.
*
* @return The new image path if the mipmap was successfully copied or the input
* path otherwise.
*/
std::string cacheTexture(const std::string& filename);
/**
* @brief USD routine to get the connected scheme.
*
* @tparam T The desired scheme.
* @param attr The destination attribute to querry the connection.
*
* @return Requested scheme.
*/
template <class T> T getConnectedScheme(const UsdAttribute& attr)
{
// Get the connection using ConnectableAPI.
UsdShadeConnectableAPI connectableAPISource;
TfToken sourceName;
UsdShadeAttributeType sourceType;
if (!UsdShadeConnectableAPI::GetConnectedSource(
attr, &connectableAPISource, &sourceName, &sourceType))
{
// No connection.
return T();
}
const UsdPrim prim = connectableAPISource.GetPrim();
if (!prim || !prim.IsA<T>())
{
// Different object.
return T();
}
return T(prim);
}
}
#endif
<|start_filename|>walter/cmake/version.cmake<|end_filename|>
find_package(Git REQUIRED)
# Get the current git commit
execute_process(
COMMAND
${GIT_EXECUTABLE} rev-parse HEAD
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE CURRENT_COMMIT
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
# Get the latest git commit that contains a tag
execute_process(
COMMAND
${GIT_EXECUTABLE} rev-list --tags --max-count=1
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE LATEST_TAG_COMMIT
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(LATEST_TAG_COMMIT)
# Get the latest git tag
execute_process(
COMMAND
${GIT_EXECUTABLE} describe --tags ${LATEST_TAG_COMMIT}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE WALTER_VERSION
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
else()
set(WALTER_VERSION "0.0.0")
message(WARNING "No git tag found, using version ${WALTER_VERSION}")
endif()
# Split it with '.' symbol
string(REPLACE "-" ";" VERSION_LIST ${WALTER_VERSION})
string(REPLACE "." ";" VERSION_LIST ${VERSION_LIST})
# Get the version list
list(GET VERSION_LIST 0 WALTER_MAJOR_VERSION)
list(GET VERSION_LIST 1 WALTER_MINOR_VERSION)
list(GET VERSION_LIST 2 WALTER_PATCH_VERSION)
# Increase the patch version if current commit is not tagged.
if( NOT "${CURRENT_COMMIT}" MATCHES "${LATEST_TAG_COMMIT}" )
math(EXPR WALTER_PATCH_VERSION "${WALTER_PATCH_VERSION}+1")
endif()
message( "Walter version is ${WALTER_MAJOR_VERSION}.${WALTER_MINOR_VERSION}.${WALTER_PATCH_VERSION}" )
<|start_filename|>walter/katana/WalterIn/walterUSDExtern.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERUSDEXTERN_H_
#define __WALTERUSDEXTERN_H_
#include "pxr/usd/usd/stage.h"
#include <string>
#include <vector>
PXR_NAMESPACE_USING_DIRECTIVE
class WalterUSDExtern
{
public:
/**
* @brief Sets the USD identifier (url/filepath).
*
* @param identifier The USD identifier.
*
*/
void setIdentifier(const char* identifiers);
/**
* @brief Extracts the variants contained in the USD scene.
*
*/
void extractVariantsUsd();
/**
* @brief Gets the variants list (per primitive).
*
* @return A serie of json separate by `|`.
*/
std::string& getVariantsUsd();
/**
* @brief Sets the variants of the primitive.
*
* @param primPath The primitive path (as string).
* @param variantName The variants name.
* @param variantSetName The variant set name.
*
* @return The variant lists as a flat string.
*/
std::string setVariantUsd(
const char* primPath,
const char* variantSetName,
const char* variantName);
/**
* @brief Sets the variants of the primitive.
*
* @param variants The variant (primPath{variantSet=variant}).
*
* @return A flatten representation of the operation.
*/
std::string setVariantUsd(const char* variants);
/**
* @brief Gets the number of USD primitives.
*
* @return Number of USD primitives.
*/
int getPrimsCount();
private:
int mPrimsCount;
std::string mFlattenVariants;
std::vector<std::string> mIdentifiers;
};
#endif
<|start_filename|>walter/houdini/src/walterSpriteRenderer.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <glcorearb.h>
#include <RE/RE_Render.h>
#include <pxr/imaging/glf/drawTarget.h>
PXR_NAMESPACE_USING_DIRECTIVE
namespace WalterSpriteRenderer
{
/** @brief A handle for a single OpenGL shader. */
class GLSLProgram
{
public:
/**
* @brief Initialize GLSL shader and save the ID.
*
* @param iVertexSrc the source of the vertex shader.
* @param iFragmentSrc the source of the fragment shader.
*/
GLSLProgram(const char* iVertexSrc, const char* iFragmentSrc);
/** @brief Installs the shader program object as part of current rendering
* state. */
void use();
/**
* @brief Returns the ID of the shader program object.
*
* @return ID of the shader program object.
*/
GLuint getID() { return mShaderProgram; }
private:
GLuint mShaderProgram;
};
/** @brief It saves the OpenGL state when constructed and restores it when
* deconstructed. */
class GLScopeGuard
{
public:
GLScopeGuard(RE_Render* r);
~GLScopeGuard();
private:
GLint mLastProgram;
GLint mLastTexture;
GLint mLastVAO;
RE_Render* mRender;
RE_RenderAutoLock lock;
};
/** @brief A helper to simplify rendering to the external framebuffer and move
* the rendered data back to the current framebuffer. We need for two reasons:
* 1) Transfer data from the raytracer plugin to the current framebuffer.
* 2) Replace the color of the rendered object to produce the Houdini ID pass.
*/
class SpriteRenderer
{
public:
SpriteRenderer();
/** @brief Changes the current framebuffer. All the OpenGL draws will be
* performed in the external texture framebuffer. */
void drawToBufferBegin();
/** @brief Restores framebuffer back to normal. */
void drawToBufferEnd();
/** @brief Draws the color and the depth data saved with
* drawToBufferBegin/drawToBufferEnd to the current framebuffer. */
void drawBeauty() const;
/** @brief Draws the Houdini pass ID from the data saved with
* drawToBufferBegin/drawToBufferEnd to the current framebuffer. */
void drawPick(int* iPickBaseID, int* iPickCompID);
/** @brief Draws the matte pass from the data saved with
* drawToBufferBegin/drawToBufferEnd to the current framebuffer. */
void drawMatte() const;
private:
/** @brief Init the OpenGL buffers. */
void init();
/** @brief Init the OpenGL buffers for Houdini pass ID. */
void initPick(int* iPickBaseID, int* iPickCompID);
/** @brief Draw a quad that takes all the area of the viewport. */
void drawPoly() const;
// OpenGL buffer for render to.
GlfDrawTargetRefPtr mHyraDrawTarget;
// OpenGL gometry buffers.
GLuint mVertexArray;
GLuint mPointBuffer;
GLuint mUVBuffer;
// Flags that the buffers are already initialized.
bool mPickInitialized;
bool mInitialized;
// The index of the binding point of the uniform block of the fragment
// shader.
GLuint mUniformPickIndex;
// The name of a buffer object to bind to the specified binding point.
GLuint mUniformPickBuffer;
// The shaders. They are static because we don't need to produce a shader
// per object.
static std::shared_ptr<GLSLProgram> sBeautyShader;
static std::shared_ptr<GLSLProgram> sPickShader;
static std::shared_ptr<GLSLProgram> sMatteShader;
};
}
<|start_filename|>walter/viewer/main.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "FreeCamera.h"
#include "Scene.h"
#include "Types.h"
#include "View.h"
#include <cstring>
#include <iostream>
void help(const char* progName, int status)
{
(status == EXIT_SUCCESS ? std::cout : std::cerr)
<< "Basic application to display Walter layers in a 3d viewer\n"
<< "Usage: " << progName << " file.usd [file.usd ...] [options]\n"
<< "Require: walter layers:\n"
<< " A list of files supported by Walter (.usd, .usda, .abc\n"
<< "Options:\n"
<< " -h, -help Print this usage message and exit\n"
<< " -c, -complexity Set geometry complexity from 1.0 to 2.0 "
"(default 1.0)\n"
<< " -f, -frame The frame to view (default 1)\n"
<< " -o, -output Export the stage instead of viewing it\n"
<< " -r, -renderer Set the renderer to 'Embree' or 'Stream' "
"(default 'Stream')\n"
<< "\n"
<< "Shortcuts:\n"
<< "\tf: Frame the whole scene\n"
<< "\tr: Reset camera\n"
<< "\te: Set Hydra renderer to use Embree (scene is rendered on CPU "
"and the result is sent to GPU for display)\n"
<< "\ts: Set Hydra renderer to use Stream (whole scene is sent to GPU "
"and "
"rendered by OpenGL)\n"
<< "\tw: Switch between wireframe and shaded\n"
<< "\t+: Increment subdiv\n"
<< "\t-: Decrement subdiv\n"
<< "\n";
exit(status);
}
namespace walter_viewer
{
void exec(const std::string& output, const Scene::Options& opt)
{
if(output != "")
{
auto scene = std::make_shared<Scene>(opt);
scene->Export(output);
}
else
{
auto view = getView();
if (!view->isValid())
{
exit(EXIT_FAILURE);
}
view->setScene(std::make_shared<Scene>(
opt, std::make_shared<FreeCamera>()));
view->show();
view->refresh();
}
}
} // end namespace walter_viewer
int main(int argc, char* argv[])
{
const char* progName = argv[0];
if (const char* ptr = ::strrchr(progName, '/'))
{
progName = ptr + 1;
}
// Parse the command line.
walter_viewer::Scene::Options opt;
std::string layers, output;
if (argc == 1)
{
help(progName, EXIT_FAILURE);
}
for (int n = 1; n < argc; ++n)
{
std::string str(argv[n]);
if (str == "-h" || str == "-help" || str == "--help")
{
help(progName, EXIT_SUCCESS);
}
else if (str == "-c" || str == "-complexity")
{
opt.complexity = std::stof(argv[n + 1]);
++n;
continue;
}
else if (str == "-f" || str == "-frame")
{
opt.frame = std::stof(argv[n + 1]);
++n;
continue;
}
else if (str == "-o" || str == "-output")
{
output = argv[n + 1];
++n;
continue;
}
else if (str == "-r" || str == "-renderer")
{
opt.renderer = argv[n + 1];
++n;
continue;
}
if (str[0] != '-')
{
opt.filePath += str;
if (n < argc - 1)
{
opt.filePath += ":";
}
}
}
walter_viewer::exec(output, opt);
exit(EXIT_SUCCESS);
}
<|start_filename|>walter/maya/AbcExport/MayaLightWriter.cpp<|end_filename|>
//-*****************************************************************************
//
// Copyright (c) 2009-2012,
// Sony Pictures Imageworks Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// All rights reserved.
//
// 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.
// * Neither the name of Sony Pictures Imageworks, nor
// Industrial Light & Magic, nor the names of their contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// 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.
//
//-*****************************************************************************
//
// Copyright 2017 <NAME>. All rights reserved.
#include "MayaLightWriter.h"
MayaLightWriter::MayaLightWriter(
MDagPath& iDag,
Alembic::Abc::OObject& iParent,
Alembic::Util::uint32_t iTimeIndex,
const JobArgs& iArgs) :
mIsAnimated(false),
mDagPath(iDag)
{
MStatus status = MS::kSuccess;
MFnDagNode mfnLight(iDag, &status);
if (!status)
{
MGlobal::displayError("MFnLight() failed for MayaLightWriter");
}
MString name = mfnLight.name();
name = util::stripNamespaces(name, iArgs.stripNamespace);
Alembic::AbcCoreAbstract::MetaData md;
util::setMeta(mfnLight, iArgs, md);
Alembic::AbcGeom::OLight obj(iParent, name.asChar(), iTimeIndex, md);
mSchema = obj.getSchema();
MObject lightObj = iDag.node();
if (iTimeIndex != 0 && util::isAnimated(lightObj))
{
mIsAnimated = true;
}
else
{
iTimeIndex = 0;
}
// Setup default properties.
Alembic::Abc::OCompoundProperty light(mSchema.getPtr(), ".light");
mType = Alembic::Abc::OStringProperty(light, ".type");
mColor = Alembic::Abc::OC3fProperty(light, ".color", iTimeIndex);
mIntensity = Alembic::Abc::OFloatProperty(light, ".intensity", iTimeIndex);
mDecay = Alembic::Abc::OFloatProperty(light, ".decay", iTimeIndex);
// The type of the light should never be animated, so we can setup it here.
mType.set(mfnLight.typeName().asChar());
Alembic::Abc::OCompoundProperty cp;
Alembic::Abc::OCompoundProperty up;
if (AttributesWriter::hasAnyAttr(mfnLight, iArgs))
{
cp = mSchema.getArbGeomParams();
up = mSchema.getUserProperties();
}
mAttrs = AttributesWriterPtr(
new AttributesWriter(cp, up, obj, mfnLight, iTimeIndex, iArgs, true));
if (!mIsAnimated || iArgs.setFirstAnimShape)
{
write();
}
}
void MayaLightWriter::write()
{
MFnDagNode mfnLight(mDagPath);
// Save color
MPlug colorPlug = mfnLight.findPlug("color");
if (!colorPlug.isNull())
{
Alembic::Abc::C3f colorVal(
colorPlug.child(0).asFloat(),
colorPlug.child(1).asFloat(),
colorPlug.child(2).asFloat());
mColor.set(colorVal);
}
// Save intensity
MPlug intensityPlug = mfnLight.findPlug("intensity");
if (!intensityPlug.isNull())
{
mIntensity.set(intensityPlug.asFloat());
}
// Get decay
MPlug decayPlug = mfnLight.findPlug("decayRate");
if (!decayPlug.isNull())
{
mDecay.set(decayPlug.asFloat());
}
}
bool MayaLightWriter::isAnimated() const
{
return mIsAnimated || (mAttrs != NULL && mAttrs->isAnimated());
}
<|start_filename|>walter/maya/walterStandin/walterUsdUtils.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERUSDUTILS_H_
#define __WALTERUSDUTILS_H_
#ifdef MFB_ALT_PACKAGE_NAME
#include <maya/MMatrix.h>
#include <maya/MObject.h>
#include <maya/MString.h>
#include <maya/MStringArray.h>
#include <maya/MTime.h>
#include <string>
#include <unordered_map>
namespace WalterMaya
{
class ShapeNode;
}
// Several utilities to Import/Export data to USD.
/**
* @brief Construct and return the session layer from the given object.
*
* @param obj Walter Standin node.
*
* @return The session layer as a text.
*/
std::string constructUSDSessionLayer(MObject obj);
/**
* @brief Construct and return the variants layer from the given object.
*
* @param obj Walter Standin node.
*
* @return The variants layer as a text.
*/
std::string getVariantsLayerAsText(MObject obj);
/**
* @brief Construct and return the purpose layer from the given object.
*
* @param obj Walter Standin node.
*
* @return The purpose layer as a text.
*/
std::string getPurposeLayerAsText(MObject obj);
/**
* @brief Construct and return the visibility layer from the given object.
*
* @param obj Walter Standin node.
*
* @return The visibility layer as a text.
*/
std::string getVisibilityLayerAsText(MObject obj);
/**
* @brief Puts a new session layer to the object.
*
* @param obj Walter Standin node.
* @param session The session layer as a text.
*/
void setUSDSessionLayer(MObject obj, const std::string& session);
/**
* @brief Puts a new variants layer to the object.
*
* @param obj Walter Standin node.
* @param variants The variants layer as a text.
*/
void setUSDVariantsLayer(MObject obj, const std::string& variants);
/**
* @brief Puts a new purpose layer to the object.
*
* @param obj Walter Standin node.
* @param purpose The purpose layer as a text.
*/
void setUSDPurposeLayer(MObject obj, const std::string& purpose);
// Gets the transform of an USD object. Returns true if success.
bool getUSDTransform(
MObject obj,
const std::string& object,
double time,
double matrix[4][4]);
/**
* @brief resets all the transforms at any time.
*
* @param node A ShapeNode.
* @param subNodeName The subnode name (path).
*/
void resetUSDTransforms(
const WalterMaya::ShapeNode* node,
const MString& subNodeName);
/**
* @brief Fills result with names of children of the subNode `subNodeName`.
*
* @param node A ShapeNode.
* @param subNodeName The subnode name (path).
* @param result The children names (as string array).
*
* @return True if succeded, false otherwise.
*/
bool dirUSD(
const WalterMaya::ShapeNode* node,
const MString& subNodeName,
MStringArray& result);
/**
* @brief Puts a new visibility layer to the object.
*
* @param obj Walter Standin node.
* @param visibility The visibility layer as a text.
*/
void setUSDVisibilityLayer(MObject obj, const std::string& visibility);
/**
* @brief Fills result with names/values of properties (USD attributes and/or
* relationships) of the subNode `subNodeName`.
*
* @param node A ShapeNode.
* @param subNodeName The subnode name (path).
* @param result The children names (as an array of json).
* @param attributeOnly If true, only attributes properties (no relation-ship)
*
* @return True if succeded, false otherwise.
*/
bool propertiesUSD(
const WalterMaya::ShapeNode* node,
const MString& subNodeName,
MStringArray& result,
bool attributeOnly = true);
/**
* @brief Fills result with all the USD variants of the stage of the node.
*
* @param node A ShapeNode.
* @param result The variants (as an array of json).
*
* @return True if succeded, false otherwise.
*/
bool getVariantsUSD(
const WalterMaya::ShapeNode* node,
const MString& subNodeName,
bool recursively,
MStringArray& result);
/**
* @brief Sets the variants of the primitive at path primPath.
*
* @param node A ShapeNode.
* @param subNodeName The subnode name (path).
* @param variantName The variants name.
* @param variantSetName The variant set name.
*
* @return True if succeded, false otherwise.
*/
bool setVariantUSD(
WalterMaya::ShapeNode* node,
const MString& subNodeName,
const MString& variantName,
const MString& variantSetName);
// Fills result with names/values of walter assigned overrides of subNodeName.
bool assignedOverridesUSD(
const WalterMaya::ShapeNode* node,
const MString& subNodeName,
MStringArray& result);
/**
* @brief Fills result with names/values of USD primVars attributes of
* subNodeName.
*
* @param stage The USD stage.
* @param subNodeName The subnode name (path).
* @param result The properties (as an array of json).
*
*/
bool primVarUSD(
const WalterMaya::ShapeNode* node,
const MString& subNodeName,
MStringArray& result);
// Sets the transformations of several of objects to the USD stage.
bool updateUSDTransforms(
const WalterMaya::ShapeNode* node,
const std::unordered_map<std::string, MMatrix>& matrices);
/**
* @brief Export the transformations to the external file.
*
* @param objectName The Walter shape name.
* @param fileName The USD file path.
* @param start The start frame.
* @param end The end frame.
* @param step The time step.
* @param resetSessionLayer Clear the session layer before export.
*/
bool saveUSDTransforms(
const MString& objectName,
const MString& fileName,
const MTime& start,
const MTime& end,
const MTime& step,
bool resetSessionLayer = true);
// Merge all the objects togeteger based on the connected transformations.
bool freezeUSDTransforms(const WalterMaya::ShapeNode* userNode);
bool unfreezeUSDTransforms(const WalterMaya::ShapeNode* userNode);
/**
* @brief Attach she GLSL material to the objects so it can be rendered with
* Hydra.
*
* @param userNode The walterStandin node
*/
void processGLSLShaders(
const WalterMaya::ShapeNode* userNode,
bool logErrorIfTokenNotFound = false);
/**
* @brief Mute/unmute layer with Hydra shaders, to it's possible to
* disable/enable textures.
*
* @param userNode The walterStandin node
* @param iSetVisible True for UnmuteLayer.
*/
void muteGLSLShaders(const WalterMaya::ShapeNode* userNode, bool iSetVisible);
/**
* @brief Returns USD layer exported to the string.
*
* @param userNode The standin object
* @param layerName The name of the requested layer. If the name is empty, the
* flatten stage will be returned. To get the session layer, it's necessary to
* specify "session".
*
* @return USD layer as string.
*/
MString getLayerAsString(
const WalterMaya::ShapeNode* userNode,
const MString& layerName);
/**
* @brief Construct and return the layer with in-scene modification of the
* object like assignments, attributes, transforms.
*
* @param obj Walter Standin node.
*
* @return The layer as a string.
*/
std::string getMayaStateAsUSDLayer(MObject obj);
bool extractAssignments(WalterMaya::ShapeNode* iUserNode);
/**
* @brief Gets all the Hydra plugins.
*
* @param result The list of Hydra plugins.
*/
void getHydraPlugins(MStringArray& result);
/**
* @brief Checks if the object is an USD pseudo-root.
*
* @param node Walter Standin node.
* @param subNodeName The subnode name (path).
*
* @param result True if the object is a USD pseudo-root, false otherwise.
*/
bool isPseudoRoot(
const WalterMaya::ShapeNode* node,
const MString& subNodeName);
/**
* @brief Checks if the object is visible.
*
* @param node Walter Standin node.
* @param subNodeName The subnode name (path).
*
* @param result True if the object is a visible, false otherwise.
*/
bool isVisible(
const WalterMaya::ShapeNode* node,
const MString& subNodeName);
/**
* @brief Toggles the visibility state (show, hidden) of the prim.
*
* @param node Walter Standin node.
* @param subNodeName The subnode name (path).
*
* @return True if the prim at path is visible, false otherwise.
*/
bool toggleVisibility(
const WalterMaya::ShapeNode* node,
const MString& subNodeName);
/**
* @brief Sets the visibility state (show, hidden) of the prim.
*
* @param node Walter Standin node.
* @param subNodeName The subnode name (path).
*
* @return True if the prim at path is visible, false otherwise.
*/
bool setVisibility(
const WalterMaya::ShapeNode* node,
const MString& subNodeName,
bool visible);
/**
* @brief Hides all the prims stage execpted the primitive at path.
*
* @param node Walter Standin node.
* @param subNodeName The subnode name (path).
*
* @param result True if the object is a visible, false otherwise.
*/
bool hideAllExceptedThis(
const WalterMaya::ShapeNode* node,
const MString& subNodeName);
/**
* @brief Gets the list of primitives path matching the expression.
*
* @param node Walter Standin node.
* @param expression A regex expression.
*
* @return An array of USD prims path.
*/
MStringArray primPathsMatchingExpression(
const WalterMaya::ShapeNode* node,
const MString& expression);
/**
* @brief Sets the prim purpose token (default, render, proxy, guide).
*
* @param node Walter Standin node.
* @param subNodeName The subnode name (path).
* @param purpose The purpose token.
*
* @return The purpose token (as string)
*/
MString setPurpose(
WalterMaya::ShapeNode* node,
const MString& subNodeName,
const MString& purpose);
/**
* @brief Gets the prim purpose token.
*
* @param node Walter Standin node.
* @param subNodeName The subnode name (path).
*
* @return The purpose token (as string)
*/
MString getPurpose(
const WalterMaya::ShapeNode* node,
const MString& subNodeName);
/**
* @brief Sets the render engine purposes list, i.e the prim
* purposes that the engine can render.
*
* @param node Walter Standin node.
* @param purposes Array of purpose token.
*/
void setRenderPurpose(
WalterMaya::ShapeNode* node,
const MStringArray& purposes);
/**
* @brief Gets the render engine purposes list, i.e the prim
* purposes that the engine can render.
*
* @param node Walter Standin node.
*
* @return Array of purpose token.
*/
MStringArray getRenderPurpose(
const WalterMaya::ShapeNode* node);
/**
* @brief Export the purposes layer content to the external file.
*
* @param objectName The Walter shape name.
* @param fileName The USD file path.
*/
bool savePurposes(
const MString& objectName,
const MString& fileName);
/**
* @brief Export the variants layer content to the external file.
*
* @param objectName The Walter shape name.
* @param fileName The USD file path.
*/
bool saveVariantsLayer(
const MString& objectName,
const MString& fileName);
#endif // MFB_ALT_PACKAGE_NAME
#endif // __WALTERUSDUTILS_H_
<|start_filename|>walter/arnold/procedural/delegate.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __DELEGATE_H__
#define __DELEGATE_H__
#include "index.h"
#include "plugin.h"
#include <pxr/usd/usd/prim.h>
#include <tbb/concurrent_hash_map.h>
PXR_NAMESPACE_USING_DIRECTIVE
class RendererDelegate
{
public:
RendererDelegate(RendererIndex& index, RendererPlugin& plugin);
// Populate index with all the objects.
void populate(const UsdPrim& root);
private:
// A cache with the necessary objects.
RendererIndex& mIndex;
// Renderer. For now it's Arnold only. But in future we will be able to
// initialize other render plugins.
RendererPlugin& mPlugin;
// We use int as a dummy type. We only need to lock if the same SdfPath is
// in process.
typedef tbb::concurrent_hash_map<SdfPath, int, RendererIndex::TbbHash>
SdfPathMutex;
SdfPathMutex mPopulateGuard;
};
#endif
<|start_filename|>walter/katana/WalterIn/ScalarPropUtils.cpp<|end_filename|>
#include "ScalarPropUtils.h"
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
///////////////////////////////////////////////////////////////////////////////
template <typename attrT, typename builderT, typename podT>
void readScalarProp(
ScalarProp & iProp,
const OpArgs & iArgs,
FnAttribute::GroupBuilder & oGb)
{
bool isBound = isBoundBox(iProp.prop.getHeader()) && (iProp.name == "bound");
size_t extent = iProp.prop.getDataType().getExtent();
size_t tupleSize = extent;
if (isBound)
tupleSize = 2;
builderT b(tupleSize);
Alembic::Abc::TimeSamplingPtr ts = iProp.prop.getTimeSampling();
SampleTimes sampleTimes;
iArgs.getRelevantSampleTimes(ts, iProp.prop.getNumSamples(), sampleTimes);
for (SampleTimes::iterator it = sampleTimes.begin();
it != sampleTimes.end(); ++it)
{
Alembic::Abc::ISampleSelector ss(*it);
std::vector<podT> scalarValue(extent);
iProp.prop.get(&scalarValue.front(), ss);
std::vector<typename attrT::value_type> value(extent);
for (size_t i = 0; i < extent; ++i)
{
value[i] = static_cast<typename attrT::value_type> (scalarValue[i]);
}
if (isBound)
{
// from min X,Y,Z max X,Y,Z
if (value.size() == 6)
{
typename attrT::value_type
minX = value[0], minY = value[1], minZ = value[2],
maxX = value[3], maxY = value[4], maxZ = value[5];
// to min/max X, Y, Z
value[0] = minX; value[1] = maxX;
value[2] = minY; value[3] = maxY;
value[4] = minZ; value[5] = maxZ;
}
}
if (sampleTimes.size() == 1)
{
// hopefully this will use a fancy attr
oGb.set(iProp.name, attrT(&value.front(), value.size(), tupleSize));
}
else
{
b.set(value, iArgs.getRelativeSampleTime(*it));
}
}
if (sampleTimes.size() > 1)
{
oGb.set(iProp.name, b.build());
}
}
void scalarPropertyToAttr(
ScalarProp & iProp,
const OpArgs & iArgs,
FnAttribute::GroupBuilder & oGb)
{
Alembic::Util::PlainOldDataType pod = iProp.prop.getDataType().getPod();
switch(pod)
{
case Alembic::Util::kBooleanPOD:
readScalarProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::bool_t>(
iProp, iArgs, oGb);
break;
case Alembic::Util::kUint8POD:
readScalarProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::uint8_t>(
iProp, iArgs, oGb);
break;
case Alembic::Util::kInt8POD:
readScalarProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::int8_t>(
iProp, iArgs, oGb);
break;
case Alembic::Util::kUint16POD:
readScalarProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::uint16_t>(
iProp, iArgs, oGb);
break;
case Alembic::Util::kInt16POD:
readScalarProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::int16_t>(
iProp, iArgs, oGb);
break;
case Alembic::Util::kUint32POD:
readScalarProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::uint32_t>(
iProp, iArgs, oGb);
break;
case Alembic::Util::kInt32POD:
readScalarProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::int32_t>(
iProp, iArgs, oGb);
break;
case Alembic::Util::kFloat16POD:
readScalarProp<FnAttribute::FloatAttribute,
FnAttribute::FloatBuilder,
Alembic::Util::float16_t>(
iProp, iArgs, oGb);
break;
case Alembic::Util::kFloat32POD:
readScalarProp<FnAttribute::FloatAttribute,
FnAttribute::FloatBuilder,
Alembic::Util::float32_t>(
iProp, iArgs, oGb);
break;
case Alembic::Util::kFloat64POD:
readScalarProp<FnAttribute::DoubleAttribute,
FnAttribute::DoubleBuilder,
Alembic::Util::float64_t>(
iProp, iArgs, oGb);
break;
case Alembic::Util::kStringPOD:
readScalarProp<FnAttribute::StringAttribute,
FnAttribute::StringBuilder,
std::string>(
iProp, iArgs, oGb);
break;
default:
break;
}
}
void scalarPropertyToAttr(
Alembic::Abc::ICompoundProperty & iParent,
const Alembic::Abc::PropertyHeader & iHeader,
const std::string & iPropName,
AbcCookPtr ioCook,
FnAttribute::GroupBuilder & oStaticGb)
{
Alembic::Abc::IScalarProperty prop(iParent, iHeader.getName());
// bad prop don't bother with it
if (!prop.valid() || prop.getNumSamples() == 0)
{
return;
}
ScalarProp item;
item.name = iPropName;
item.prop = prop;
if (!prop.isConstant())
{
ioCook->scalarProps.push_back(item);
return;
}
OpArgs defaultArgs;
scalarPropertyToAttr(item, defaultArgs, oStaticGb);
}
}
<|start_filename|>walter/houdini/src/SOP_WalterNode.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "SOP_WalterNode.h"
#include "GU_WalterPackedImpl.h"
#include "walterHoudiniUtils.h"
#include <CH/CH_LocalVariable.h>
#include <CMD/CMD_Manager.h>
#include <GEO/GEO_PrimPoly.h>
#include <GU/GU_Detail.h>
#include <GU/GU_PrimPacked.h>
#include <OP/OP_Operator.h>
#include <OP/OP_OperatorTable.h>
#include <PRM/PRM_Include.h>
#include <PRM/PRM_SpareData.h>
#include <SYS/SYS_Math.h>
#include <UT/UT_Interrupt.h>
#include <UT/UT_StringStream.h>
#include <limits.h>
namespace WalterHoudini
{
int pickNodes(void* data, int index, fpreal t, const PRM_Template* tplate);
static PRM_Name fileName("fileName#", "Path");
static PRM_SpareData fileData(
PRM_SpareArgs() << PRM_SpareToken(
PRM_SpareData::getFileChooserPatternToken(),
"*.abc,*.usd,*.usda,*.usdb,*.usdc")
<< PRM_SpareToken(
PRM_SpareData::getFileChooserModeToken(),
PRM_SpareData::getFileChooserModeValRead()));
static PRM_Name hydraPlugins[] = {
PRM_Name("HdStreamRendererPlugin", "Stream"),
PRM_Name("HdEmbreeRendererPlugin", "Embree"),
PRM_Name()};
static PRM_Name hydraPluginName("hdPlugin", "Hydra Plugin");
static PRM_Default hydraPluginDefault(0, "HdStreamRendererPlugin");
static PRM_ChoiceList hydraPluginChoice(PRM_CHOICELIST_SINGLE, hydraPlugins);
static PRM_Name layersName("layers", "Layers");
static PRM_Template layersTemplates[] = {
PRM_Template(PRM_FILE, 1, &fileName, 0, 0, 0, 0, &fileData),
PRM_Template()};
static PRM_Name primPathName("primPath", "Prim Path");
static PRM_Name pickObjectPathName("pickObjectPath", "Pick");
static PRM_SpareData pickObjectPathData(
PRM_SpareArgs()
<< PRM_SpareToken(PRM_SpareData::getButtonIconToken(), "BUTTONS_tree"));
static PRM_Name primModeName("primMode", "Create Primitives For");
static PRM_Name primModeOptions[] = {
PRM_Name("root", "Specified Primitive Only"),
PRM_Name("children", "Children Primitives"),
PRM_Name()};
static PRM_Default primModeDefault(0, "root");
static PRM_ChoiceList primModeChoice(PRM_CHOICELIST_SINGLE, primModeOptions);
static PRM_Name frameName("frame", "Frame");
static PRM_Default frameDef(0, "$FF");
PRM_Template SOP_WalterNode::sTemplateList[] = {
PRM_Template(PRM_ORD, 1, &hydraPluginName, &hydraPluginDefault, &hydraPluginChoice),
PRM_Template(PRM_MULTITYPE_SCROLL, layersTemplates, 1, &layersName),
PRM_Template(PRM_STRING, PRM_TYPE_JOIN_PAIR, 1, &primPathName),
PRM_Template(
PRM_CALLBACK,
PRM_TYPE_NO_LABEL,
1,
&pickObjectPathName,
0,
0,
0,
pickNodes,
&pickObjectPathData),
PRM_Template(PRM_ORD, 1, &primModeName, &primModeDefault, &primModeChoice),
PRM_Template(PRM_FLT, 1, &frameName, &frameDef),
PRM_Template()};
// This is called when the user presses the tree button to see the tree of the
// loaded stage.
int pickNodes(void* data, int index, fpreal t, const PRM_Template* tplate)
{
SOP_WalterNode* sop = (SOP_WalterNode*)(data);
// The treechooser command presents the list of strings using a tree-style
// graphical interface. If _-r_ option is not present, the command will
// return multiple choices as a space-separated list.
UT_WorkBuffer cmd;
cmd.strcpy("treechooser -r");
UT_String primPath;
sop->evalString(primPath, primPathName.getToken(), 0, t);
if (primPath.isstring())
{
// Specify initial selection of nodes in the tree.
cmd.strcat(" -s ");
cmd.protectedStrcat(primPath);
}
std::vector<std::string> objects;
WalterHoudiniUtils::getObjectList(
sop->evalSessionName(t), "", false, objects);
for (auto object : objects)
{
cmd.strcat(" ");
cmd.protectedStrcat(object.c_str());
}
CMD_Manager* mgr = CMDgetManager();
UT_OStringStream os;
mgr->execute(cmd.buffer(), 0, &os);
UT_String result(os.str().buffer());
result.trimBoundingSpace();
sop->setChRefString(
result, CH_STRING_LITERAL, primPathName.getToken(), 0, t);
return 0;
}
// newSopOperator is the hook that Houdini grabs from this dll and invokes to
// register the SOP. In this case we add ourselves to the specified operator
// table.
void SOP_WalterNode::install(OP_OperatorTable* table)
{
OP_Operator* op = new OP_Operator(
"walter_import", // Internal name
"Walter", // UI name
constructor, // How to build the SOP
sTemplateList, // My parameters
0, // Min # of sources
0, // Max # of sources
0, // Local variables
OP_FLAG_GENERATOR); // Flag it as generator
op->setIconName("Walter_round_logo_gold.png");
table->addOperator(op);
}
OP_Node* SOP_WalterNode::constructor(
OP_Network* net,
const char* name,
OP_Operator* op)
{
return new SOP_WalterNode(net, name, op);
}
std::string SOP_WalterNode::evalSessionName(fpreal time) const
{
// Get number of layers.
int nLayers = evalInt(layersName.getToken(), 0, time);
// We need to create a string that contains all the layers separated with
// the semicolon.
UT_String fullFileName;
// Houdini iterates parameters from 1.
for (int i = 1; i <= nLayers; i++)
{
// Form the name.
char buffer[64];
sprintf(buffer, "fileName%i", i);
// Get the value.
UT_String current;
evalString(current, buffer, 0, time);
if (current && current.length())
{
if (fullFileName)
{
fullFileName += ":";
}
fullFileName += current;
}
}
return fullFileName.toStdString();
}
SOP_WalterNode::SOP_WalterNode(
OP_Network* net,
const char* name,
OP_Operator* op) :
SOP_Node(net, name, op)
{
// This SOP always generates fresh geometry, so setting this flag is a bit
// redundant, but one could change it to check for the old star and only
// bump relevant data IDs, (P and the primitive list), depending on what
// parameters changed.
mySopFlags.setManagesDataIDs(true);
}
OP_ERROR SOP_WalterNode::cookMySop(OP_Context& context)
{
if (lockInputs(context) >= UT_ERROR_ABORT)
{
return error();
}
Parms parms;
evaluateParms(parms, context);
if (mLastParms.needsUpdate(parms))
{
// Clear all.
// TODO: It's possible to keep and reuse all the primitives.
gdp->clearAndDestroy();
std::vector<std::string> primPathVec;
switch (parms.mPrimMode)
{
case PrimLoadingMode::single:
default:
primPathVec.push_back(parms.mPrimPath);
break;
case PrimLoadingMode::children:
WalterHoudiniUtils::getObjectList(
parms.mFileName, parms.mPrimPath, true, primPathVec);
break;
}
for (const std::string& primPath : primPathVec)
{
// Create a packed Walter primitive.
GU_PrimPacked* packed = GU_WalterPackedImpl::build(
*gdp,
parms.mFileName,
primPath,
parms.mHdRendererName,
parms.mFrame);
if (!packed)
{
fprintf(stderr, "[WALTER]: Can't create packed Walter\n");
// TODO: continue;
return error();
}
// Assign it as a point.
GA_Offset pt = gdp->appendPointOffset();
packed->setVertexPoint(pt);
// TODO: Set the position.
// UT_Vector3 pivot(0, 0, 0);
// gdp->setPos3(pt, pivot);
}
}
else if (mLastParms.timeChanged(parms))
{
for (GA_Offset pt : gdp->getPrimitiveRange())
{
GA_Primitive* prm = gdp->getPrimitive(pt);
GU_PrimPacked* pack = UTverify_cast<GU_PrimPacked*>(prm);
// Cast it to Walter.
GU_WalterPackedImpl* walter =
UTverify_cast<GU_WalterPackedImpl*>(pack->implementation());
walter->setFrame(parms.mFrame);
}
}
mLastParms = parms;
return error();
}
SOP_WalterNode::~SOP_WalterNode()
{}
SOP_WalterNode::Parms::Parms() :
mFileName(),
mFrame(std::numeric_limits<float>::min()),
mPrimPath(),
mPrimMode(PrimLoadingMode::single),
mHdRendererName()
{}
SOP_WalterNode::Parms::Parms(const SOP_WalterNode::Parms& src)
{
*this = src;
}
bool SOP_WalterNode::Parms::needsUpdate(const SOP_WalterNode::Parms& parms)
{
return mFileName != parms.mFileName || mPrimPath != parms.mPrimPath ||
mPrimMode != parms.mPrimMode || mHdRendererName != parms.mHdRendererName;
}
bool SOP_WalterNode::Parms::timeChanged(const SOP_WalterNode::Parms& parms)
{
return mFrame != parms.mFrame;
}
SOP_WalterNode::Parms& SOP_WalterNode::Parms::operator=(
const SOP_WalterNode::Parms& src)
{
mFileName = src.mFileName;
mPrimPath = src.mPrimPath;
mFrame = src.mFrame;
mPrimMode = src.mPrimMode;
mHdRendererName = src.mHdRendererName;
return *this;
}
void SOP_WalterNode::evaluateParms(Parms& parms, OP_Context& context)
{
fpreal now = context.getTime();
UT_String primPath;
evalString(primPath, primPathName.getToken(), 0, now);
parms.mFileName = evalSessionName(now);
parms.mPrimPath = primPath.toStdString();
parms.mFrame = evalFloat(frameName.getToken(), 0, now);
parms.mPrimMode =
static_cast<PrimLoadingMode>(evalInt(primModeName.getToken(), 0, now));
UT_String hdName;
evalString(hdName, hydraPluginName.getToken(), 0, now);
parms.mHdRendererName = hdName.toStdString();
}
} // end namespace WalterHoudini
<|start_filename|>walter/usd/fileFormat/usdArnold/arnoldApi.h<|end_filename|>
// Copyright 2018 <NAME>. All rights reserved.
#ifndef __ARNOLD_API__
#define __ARNOLD_API__
#include <ai.h>
#include <memory>
class ArnoldAPI;
typedef std::shared_ptr<ArnoldAPI> ArnoldAPIPtr;
class ArnoldAPI
{
public:
static ArnoldAPIPtr create();
ArnoldAPI();
~ArnoldAPI();
int GetArchVersion() const { return valid() ? mArch : -1; }
bool valid() const;
typedef int (*AiASSLoadFuncPtr)(const char* filename, int mask);
typedef void (*AiBeginFuncPtr)();
typedef void (*AiEndFuncPtr)();
typedef const char* (
*AiGetVersionFuncPtr)(char* arch, char* major, char* minor, char* fix);
typedef void (*AiLoadPluginsFuncPtr)(const char* directory);
typedef const char* (*AiNodeEntryGetNameFuncPtr)(const AtNodeEntry* nentry);
typedef AtParamIterator* (*AiNodeEntryGetParamIteratorFuncPtr)(
const AtNodeEntry* nentry);
typedef bool (
*AiNodeGetBoolFuncPtr)(const AtNode* node, const AtString param);
typedef float (
*AiNodeGetFltFuncPtr)(const AtNode* node, const AtString param);
typedef int (
*AiNodeGetIntFuncPtr)(const AtNode* node, const AtString param);
typedef AtNode* (*AiNodeGetLinkFuncPtr)(
const AtNode* node,
const char* input,
int* comp);
typedef AtMatrix (
*AiNodeGetMatrixFuncPtr)(const AtNode* node, const AtString param);
typedef const char* (*AiNodeGetNameFuncPtr)(const AtNode* node);
typedef const AtNodeEntry* (*AiNodeGetNodeEntryFuncPtr)(const AtNode* node);
typedef AtRGBA (
*AiNodeGetRGBAFuncPtr)(const AtNode* node, const AtString param);
typedef AtRGB (
*AiNodeGetRGBFuncPtr)(const AtNode* node, const AtString param);
typedef AtString (
*AiNodeGetStrFuncPtr)(const AtNode* node, const AtString param);
typedef unsigned int (
*AiNodeGetUIntFuncPtr)(const AtNode* node, const AtString param);
typedef AtVector2 (
*AiNodeGetVec2FuncPtr)(const AtNode* node, const AtString param);
typedef AtVector (
*AiNodeGetVecFuncPtr)(const AtNode* node, const AtString param);
typedef bool (
*AiNodeIsLinkedFuncPtr)(const AtNode* node, const char* input);
typedef void (*AiNodeIteratorDestroyFuncPtr)(AtNodeIterator* iter);
typedef bool (*AiNodeIteratorFinishedFuncPtr)(const AtNodeIterator* iter);
typedef AtNode* (*AiNodeIteratorGetNextFuncPtr)(AtNodeIterator* iter);
typedef void (*AiNodeResetFuncPtr)(AtNode* node);
typedef AtString (*AiParamGetNameFuncPtr)(const AtParamEntry* pentry);
typedef uint8_t (*AiParamGetTypeFuncPtr)(const AtParamEntry* pentry);
typedef void (*AiParamIteratorDestroyFuncPtr)(AtParamIterator* iter);
typedef bool (*AiParamIteratorFinishedFuncPtr)(const AtParamIterator* iter);
typedef const AtParamEntry* (*AiParamIteratorGetNextFuncPtr)(
AtParamIterator* iter);
typedef AtNodeIterator* (*AiUniverseGetNodeIteratorFuncPtr)(
unsigned int node_mask);
typedef bool (*AiUniverseIsActiveFuncPtr)();
typedef AtArray* (
*AiNodeGetArrayFuncPtr)(const AtNode* node, const AtString param);
typedef uint8_t (*AiArrayGetTypeFuncPtr)(const AtArray* array);
typedef AtRGB (*AiArrayGetRGBFuncFuncPtr)(
const AtArray* a,
uint32_t i,
const char*,
int line);
typedef float (*AiArrayGetFltFuncFuncPtr)(
const AtArray* a,
uint32_t i,
const char*,
int line);
typedef int (*AiArrayGetIntFuncFuncPtr)(
const AtArray* a,
uint32_t i,
const char*,
int line);
typedef uint8_t (*AiArrayGetByteFuncFuncPtr)(
const AtArray* a,
uint32_t i,
const char*,
int line);
typedef AtString (*AiArrayGetStrFuncFuncPtr)(
const AtArray* a,
uint32_t i,
const char*,
int line);
typedef uint32_t (*AiArrayGetNumElementsFuncPtr)(const AtArray* array);
typedef int (*AiNodeEntryGetTypeFuncPtr)(const AtNodeEntry* nentry);
typedef const AtParamEntry* (*AiNodeEntryLookUpParameterFuncPtr)(
const AtNodeEntry* nentry,
const AtString param);
typedef void* (
*AiNodeGetPtrFuncPtr)(const AtNode* node, const AtString param);
AiASSLoadFuncPtr AiASSLoad;
AiBeginFuncPtr AiBegin;
AiGetVersionFuncPtr AiGetVersion;
AiEndFuncPtr AiEnd;
AiLoadPluginsFuncPtr AiLoadPlugins;
AiNodeEntryGetNameFuncPtr AiNodeEntryGetName;
AiNodeEntryGetParamIteratorFuncPtr AiNodeEntryGetParamIterator;
AiNodeGetBoolFuncPtr AiNodeGetBool;
AiNodeGetFltFuncPtr AiNodeGetFlt;
AiNodeGetIntFuncPtr AiNodeGetInt;
AiNodeGetLinkFuncPtr AiNodeGetLink;
AiNodeGetMatrixFuncPtr AiNodeGetMatrix;
AiNodeGetNameFuncPtr AiNodeGetName;
AiNodeGetNodeEntryFuncPtr AiNodeGetNodeEntry;
AiNodeGetRGBAFuncPtr AiNodeGetRGBA;
AiNodeGetRGBFuncPtr AiNodeGetRGB;
AiNodeGetStrFuncPtr AiNodeGetStr;
AiNodeGetUIntFuncPtr AiNodeGetUInt;
AiNodeGetVec2FuncPtr AiNodeGetVec2;
AiNodeGetVecFuncPtr AiNodeGetVec;
AiNodeIsLinkedFuncPtr AiNodeIsLinked;
AiNodeIteratorDestroyFuncPtr AiNodeIteratorDestroy;
AiNodeIteratorFinishedFuncPtr AiNodeIteratorFinished;
AiNodeIteratorGetNextFuncPtr AiNodeIteratorGetNext;
AiNodeResetFuncPtr AiNodeReset;
AiParamGetNameFuncPtr AiParamGetName;
AiParamGetTypeFuncPtr AiParamGetType;
AiParamIteratorDestroyFuncPtr AiParamIteratorDestroy;
AiParamIteratorFinishedFuncPtr AiParamIteratorFinished;
AiParamIteratorGetNextFuncPtr AiParamIteratorGetNext;
AiUniverseGetNodeIteratorFuncPtr AiUniverseGetNodeIterator;
AiUniverseIsActiveFuncPtr AiUniverseIsActive;
AiNodeGetArrayFuncPtr AiNodeGetArray;
AiArrayGetTypeFuncPtr AiArrayGetType;
AiArrayGetRGBFuncFuncPtr AiArrayGetRGBFunc;
AiArrayGetFltFuncFuncPtr AiArrayGetFltFunc;
AiArrayGetIntFuncFuncPtr AiArrayGetIntFunc;
AiArrayGetByteFuncFuncPtr AiArrayGetByteFunc;
AiArrayGetStrFuncFuncPtr AiArrayGetStrFunc;
AiArrayGetNumElementsFuncPtr AiArrayGetNumElements;
AiNodeEntryGetTypeFuncPtr AiNodeEntryGetType;
AiNodeEntryLookUpParameterFuncPtr AiNodeEntryLookUpParameter;
AiNodeGetPtrFuncPtr AiNodeGetPtr;
private:
// The library address
void* mArnoldDSO;
// The Arnold version
int mArch;
};
#endif
<|start_filename|>walter/maya/walterStandin/walterDrawOverride.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef _walterDrawOverride_h_
#define _walterDrawOverride_h_
#ifdef MFB_ALT_PACKAGE_NAME
#include <maya/MPxDrawOverride.h>
#if MAYA_API_VERSION >= 201800
#include <maya/MSelectionContext.h>
#endif
namespace WalterMaya {
// Handles the drawing of the USD stage in the viewport 2.0.
class DrawOverride : public MHWRender::MPxDrawOverride
{
public:
// Used by the MDrawRegistry to create new instances of this class.
static MPxDrawOverride* creator(const MObject& obj);
private:
// Data used by the draw call back.
class UserData;
// Invoked by the Viewport 2.0 when it is time to draw.
static void drawCb(
const MHWRender::MDrawContext& drawContext,
const MUserData* data);
DrawOverride(const MObject& obj);
virtual ~DrawOverride();
// Prohibited and not implemented.
DrawOverride(const DrawOverride& obj);
const DrawOverride& operator=(const DrawOverride& obj);
// Overrides of MPxDrawOverride member funtions.
virtual MHWRender::DrawAPI supportedDrawAPIs() const;
virtual bool isBounded(
const MDagPath& objPath,
const MDagPath& cameraPath) const;
virtual MBoundingBox boundingBox(
const MDagPath& objPath,
const MDagPath& cameraPath) const;
virtual bool disableInternalBoundingBoxDraw() const;
virtual MUserData* prepareForDraw(
const MDagPath& objPath,
const MDagPath& cameraPath,
const MHWRender::MFrameContext& frameContext,
MUserData* oldData);
#if MAYA_API_VERSION >= 201800
virtual bool wantUserSelection() const;
virtual bool userSelect(
MSelectionInfo &selectInfo,
const MHWRender::MDrawContext &context,
MPoint &hitPoint,
const MUserData *data);
virtual bool refineSelectionPath (
const MSelectionInfo &selectInfo,
const MRenderItem &hitItem,
MDagPath &path,
MObject &components,
MSelectionMask &objectMask);
#endif
};
}
#endif
#endif
<|start_filename|>walter/usd/walterUsdConversion.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterUsdConversion.h"
#include <pxr/base/gf/matrix4d.h>
#include <pxr/base/gf/vec3f.h>
namespace WalterUSDToString
{
#define MY_SCALARS \
(bool)(int)(long)(float)(double)(unsigned int)(unsigned char)(unsigned long)
#define MY_VECTORS \
(GfVec2d)(GfVec3d)(GfVec4d)(GfVec2f)(GfVec3f)(GfVec4f)(GfVec2i)(GfVec3i)( \
GfVec4i)
#define MY_MATRICES (GfMatrix2d)(GfMatrix3d)(GfMatrix4d)
#define MY_QUATS (GfQuatd)(GfQuatf)
// Generate extern template declarations in the header
#define MY_SCALAR_TEMPLATE(r, data, arg) \
template <> std::string convert<arg>(const arg& value) \
{ \
return std::to_string(value); \
}
// Generate extern template declarations in the header
#define MY_VECTOR_TEMPLATE(r, data, arg) \
template <> std::string convert<arg>(const arg& value) \
{ \
return convertDim(value, arg::dimension); \
}
// Generate extern template declarations in the header
#define MY_MATRIX_TEMPLATE(r, data, arg) \
template <> std::string convert<arg>(const arg& value) \
{ \
return convertDim(value, arg::numRows * arg::numColumns); \
}
// Generate extern template declarations in the header
#define MY_QUAT_TEMPLATE(r, data, arg) \
template <> std::string convert<arg>(const arg& value) \
{ \
const typename arg::ScalarType* rawBuffer = \
value.GetImaginary().GetArray(); \
std::string str = "[";\
for (unsigned j = 0; j < 3; ++j) \
{ \
str += convert(rawBuffer[j]); \
str += ", "; \
} \
str += convert(value.GetReal()); \
str += "]"; \
return str; \
}
template <typename T> std::string convertDim(const T& value, int dim)
{
const typename T::ScalarType* rawBuffer = value.GetArray();
std::string str = "[";
for (unsigned j = 0; j < dim; ++j)
{
str += convert(rawBuffer[j]);
if (j < dim - 1)
str += ", ";
}
str += "]";
return str;
}
BOOST_PP_SEQ_FOR_EACH(MY_SCALAR_TEMPLATE, _, MY_SCALARS)
BOOST_PP_SEQ_FOR_EACH(MY_VECTOR_TEMPLATE, _, MY_VECTORS)
BOOST_PP_SEQ_FOR_EACH(MY_MATRIX_TEMPLATE, _, MY_MATRICES)
BOOST_PP_SEQ_FOR_EACH(MY_QUAT_TEMPLATE, _, MY_QUATS)
template <> std::string convert<std::string>(const std::string& value)
{
return value;
}
#undef MY_SCALARS
#undef MY_VECTORS
#undef MY_MATRICES
#undef MY_QUATS
#undef MY_SCALAR_TEMPLATE
#undef MY_VECTOR_TEMPLATE
#undef MY_MATRIX_TEMPLATE
#undef MY_QUAT_TEMPLATE
}
PXR_NAMESPACE_USING_DIRECTIVE
std::string WalterUsdConversion::getScalarAttributeValueAsString(
UsdAttribute const& attr,
UsdTimeCode const& tc)
{
std::string strValue;
const SdfValueTypeName attrTypeName = attr.GetTypeName();
// Basic type
if (attrTypeName == SdfValueTypeNames->Bool)
strValue = getAttributeValueAsString<bool>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->UChar)
strValue = getAttributeValueAsString<uint8_t>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->Int)
strValue = getAttributeValueAsString<int32_t>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->UInt)
strValue = getAttributeValueAsString<uint32_t>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->Int64)
strValue = getAttributeValueAsString<int64_t>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->UInt64)
strValue = getAttributeValueAsString<uint64_t>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->Float)
strValue = getAttributeValueAsString<float>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->Double)
strValue = getAttributeValueAsString<double>(attr, tc);
else if (
attrTypeName == SdfValueTypeNames->String ||
attrTypeName == SdfValueTypeNames->Token ||
attrTypeName == SdfValueTypeNames->Asset)
strValue = getAttributeValueAsString<std::string>(attr, tc);
// Double array/matrix
else if (attrTypeName == SdfValueTypeNames->Matrix2d)
strValue = getAttributeValueAsString<GfMatrix2d>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->Matrix3d)
strValue = getAttributeValueAsString<GfMatrix3d>(attr, tc);
else if (
attrTypeName == SdfValueTypeNames->Matrix4d ||
attrTypeName == SdfValueTypeNames->Frame4d)
strValue = getAttributeValueAsString<GfMatrix4d>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->Quatd)
strValue = getAttributeValueAsString<GfQuatd>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->Double2)
strValue = getAttributeValueAsString<GfVec2d>(attr, tc);
else if (
attrTypeName == SdfValueTypeNames->Double3 ||
attrTypeName == SdfValueTypeNames->Color3d ||
attrTypeName == SdfValueTypeNames->Vector3d ||
attrTypeName == SdfValueTypeNames->Normal3d ||
attrTypeName == SdfValueTypeNames->Point3d)
strValue = getAttributeValueAsString<GfVec3d>(attr, tc);
else if (
attrTypeName == SdfValueTypeNames->Double4 ||
attrTypeName == SdfValueTypeNames->Color4d)
strValue = getAttributeValueAsString<GfVec4d>(attr, tc);
// Float array/matrix
else if (attrTypeName == SdfValueTypeNames->Quatf)
strValue = getAttributeValueAsString<GfQuatf>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->Float2)
strValue = getAttributeValueAsString<GfVec2f>(attr, tc);
else if (
attrTypeName == SdfValueTypeNames->Float3 ||
attrTypeName == SdfValueTypeNames->Color3f ||
attrTypeName == SdfValueTypeNames->Vector3f ||
attrTypeName == SdfValueTypeNames->Normal3f ||
attrTypeName == SdfValueTypeNames->Point3f)
strValue = getAttributeValueAsString<GfVec3f>(attr, tc);
else if (
attrTypeName == SdfValueTypeNames->Float4 ||
attrTypeName == SdfValueTypeNames->Color4f)
strValue = getAttributeValueAsString<GfVec4f>(attr, tc);
// Int array/matrix
else if (attrTypeName == SdfValueTypeNames->Int2)
strValue = getAttributeValueAsString<GfVec2i>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->Int3)
strValue = getAttributeValueAsString<GfVec3i>(attr, tc);
else if (attrTypeName == SdfValueTypeNames->Int4)
strValue = getAttributeValueAsString<GfVec4i>(attr, tc);
return strValue;
}
std::string WalterUsdConversion::getArrayAttributeValueAsString(
UsdAttribute const& attr,
UsdTimeCode const& tc,
int maxElementCount,
int& arraySize)
{
std::string strValue;
const SdfValueTypeName& attrTypeName = attr.GetTypeName();
// Basic type
if (attrTypeName == SdfValueTypeNames->BoolArray)
strValue = getArrayAttributeValueAsString<bool>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->UCharArray)
strValue = getArrayAttributeValueAsString<uint8_t>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->IntArray)
strValue = getArrayAttributeValueAsString<int32_t>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->UIntArray)
strValue = getArrayAttributeValueAsString<uint32_t>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->Int64Array)
strValue = getArrayAttributeValueAsString<int64_t>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->UInt64Array)
strValue = getArrayAttributeValueAsString<uint64_t>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->FloatArray)
strValue = getArrayAttributeValueAsString<float>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->DoubleArray)
strValue = getArrayAttributeValueAsString<double>(
attr, tc, maxElementCount, arraySize);
else if (
attrTypeName == SdfValueTypeNames->StringArray ||
attrTypeName == SdfValueTypeNames->TokenArray ||
attrTypeName == SdfValueTypeNames->AssetArray)
strValue = getArrayAttributeValueAsString<std::string>(
attr, tc, maxElementCount, arraySize);
// Double array/matrix
else if (attrTypeName == SdfValueTypeNames->Matrix2dArray)
strValue = getArrayAttributeValueAsString<GfMatrix2d>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->Matrix3dArray)
strValue = getArrayAttributeValueAsString<GfMatrix3d>(
attr, tc, maxElementCount, arraySize);
else if (
attrTypeName == SdfValueTypeNames->Matrix4dArray ||
attrTypeName == SdfValueTypeNames->Frame4dArray)
strValue = getArrayAttributeValueAsString<GfMatrix4d>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->QuatdArray)
strValue = getArrayAttributeValueAsString<GfQuatd>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->Double2Array)
strValue = getArrayAttributeValueAsString<GfVec2d>(
attr, tc, maxElementCount, arraySize);
else if (
attrTypeName == SdfValueTypeNames->Double3Array ||
attrTypeName == SdfValueTypeNames->Color3dArray ||
attrTypeName == SdfValueTypeNames->Vector3dArray ||
attrTypeName == SdfValueTypeNames->Normal3dArray ||
attrTypeName == SdfValueTypeNames->Point3dArray)
strValue = getArrayAttributeValueAsString<GfVec3d>(
attr, tc, maxElementCount, arraySize);
else if (
attrTypeName == SdfValueTypeNames->Double4Array ||
attrTypeName == SdfValueTypeNames->Color4dArray)
strValue = getArrayAttributeValueAsString<GfVec4d>(
attr, tc, maxElementCount, arraySize);
// Float array/matrix
else if (attrTypeName == SdfValueTypeNames->QuatfArray)
strValue = getArrayAttributeValueAsString<GfQuatf>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->Float2Array)
strValue = getArrayAttributeValueAsString<GfVec2f>(
attr, tc, maxElementCount, arraySize);
else if (
attrTypeName == SdfValueTypeNames->Float3Array ||
attrTypeName == SdfValueTypeNames->Color3fArray ||
attrTypeName == SdfValueTypeNames->Vector3fArray ||
attrTypeName == SdfValueTypeNames->Normal3fArray ||
attrTypeName == SdfValueTypeNames->Point3fArray)
strValue = getArrayAttributeValueAsString<GfVec3f>(
attr, tc, maxElementCount, arraySize);
else if (
attrTypeName == SdfValueTypeNames->Float4Array ||
attrTypeName == SdfValueTypeNames->Color4fArray)
strValue = getArrayAttributeValueAsString<GfVec4f>(
attr, tc, maxElementCount, arraySize);
// Int array/matrix
else if (attrTypeName == SdfValueTypeNames->Int2Array)
strValue = getArrayAttributeValueAsString<GfVec2i>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->Int3Array)
strValue = getArrayAttributeValueAsString<GfVec3i>(
attr, tc, maxElementCount, arraySize);
else if (attrTypeName == SdfValueTypeNames->Int4Array)
strValue = getArrayAttributeValueAsString<GfVec4i>(
attr, tc, maxElementCount, arraySize);
return strValue;
}
std::string WalterUsdConversion::getRelationShipValueAsString(
const UsdRelationship& rl,
UsdTimeCode const& tc)
{
SdfPathVector targets;
rl.GetTargets(&targets);
std::string strValue = "[";
for (auto it = targets.begin(); it != targets.end(); ++it)
strValue += it->GetString();
strValue += "]";
return strValue;
}
bool WalterUsdConversion::getAttributeValueAsString(
UsdAttribute const& attr,
UsdTimeCode const& tc,
std::string& propertyType,
std::string& strValue,
int& arraySize,
int maxElementCount)
{
SdfValueTypeName attrTypeName;
attrTypeName = attr.GetTypeName();
propertyType = attrTypeName.GetType().GetTypeName();
if (attrTypeName.IsScalar())
{
strValue = getScalarAttributeValueAsString(attr, tc);
return true;
}
else if (attrTypeName.IsArray())
{
strValue = getArrayAttributeValueAsString(
attr, tc, maxElementCount, arraySize);
return true;
}
return false;
}
bool WalterUsdConversion::getPropertyValueAsString(
UsdProperty const& prop,
UsdTimeCode const& tc,
std::string& propertyType,
std::string& strValue,
int& arraySize,
int maxElementCount,
bool attributeOnly)
{
SdfValueTypeName attrTypeName;
if (prop.Is<UsdAttribute>())
{
getAttributeValueAsString(
prop.As<UsdAttribute>(),
tc,
propertyType,
strValue,
arraySize,
maxElementCount);
return true;
}
else if (!attributeOnly && prop.Is<UsdRelationship>())
{
propertyType = prop.GetBaseName().GetText();
const UsdRelationship& rl = prop.As<UsdRelationship>();
strValue = getRelationShipValueAsString(rl, tc);
return true;
}
return false;
}
std::string WalterUsdConversion::constuctStringRepresentation(
std::string const& name,
std::string const& propertyType,
std::string const& valueType,
std::string const& strValue,
int arraySize)
{
std::string jsonStr = "{ ";
jsonStr += "\"name\": \"" + name + "\"";
jsonStr += ", \"type\": \"" + valueType + "\"";
jsonStr += ", \"arraySize\": " + std::to_string(arraySize);
jsonStr += ", \"value\": " + strValue;
jsonStr += " }";
return jsonStr;
}
<|start_filename|>walter/usd/schemas/expression.h<|end_filename|>
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef WALTERUSDEXTRAS_GENERATED_EXPRESSION_H
#define WALTERUSDEXTRAS_GENERATED_EXPRESSION_H
/// \file walterUsdExtras/expression.h
#include "pxr/pxr.h"
#include ".//api.h"
#include "pxr/usd/usd/typed.h"
#include "pxr/usd/usd/prim.h"
#include "pxr/usd/usd/stage.h"
#include ".//tokens.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/gf/vec3d.h"
#include "pxr/base/gf/vec3f.h"
#include "pxr/base/gf/matrix4d.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/type.h"
PXR_NAMESPACE_OPEN_SCOPE
class SdfAssetPath;
// -------------------------------------------------------------------------- //
// EXPRESSION //
// -------------------------------------------------------------------------- //
/// \class WalterExpression
///
/// Reading and querying layers definitions.
///
class WalterExpression : public UsdTyped
{
public:
/// Compile-time constant indicating whether or not this class corresponds
/// to a concrete instantiable prim type in scene description. If this is
/// true, GetStaticPrimDefinition() will return a valid prim definition with
/// a non-empty typeName.
static const bool IsConcrete = false;
/// Compile-time constant indicating whether or not this class inherits from
/// UsdTyped. Types which inherit from UsdTyped can impart a typename on a
/// UsdPrim.
static const bool IsTyped = true;
/// Construct a WalterExpression on UsdPrim \p prim .
/// Equivalent to WalterExpression::Get(prim.GetStage(), prim.GetPath())
/// for a \em valid \p prim, but will not immediately throw an error for
/// an invalid \p prim
explicit WalterExpression(const UsdPrim& prim=UsdPrim())
: UsdTyped(prim)
{
}
/// Construct a WalterExpression on the prim held by \p schemaObj .
/// Should be preferred over WalterExpression(schemaObj.GetPrim()),
/// as it preserves SchemaBase state.
explicit WalterExpression(const UsdSchemaBase& schemaObj)
: UsdTyped(schemaObj)
{
}
/// Destructor.
WALTERUSDEXTRAS_API
virtual ~WalterExpression();
/// Return a vector of names of all pre-declared attributes for this schema
/// class and all its ancestor classes. Does not include attributes that
/// may be authored by custom/extended methods of the schemas involved.
WALTERUSDEXTRAS_API
static const TfTokenVector &
GetSchemaAttributeNames(bool includeInherited=true);
/// Return a WalterExpression holding the prim adhering to this
/// schema at \p path on \p stage. If no prim exists at \p path on
/// \p stage, or if the prim at that path does not adhere to this schema,
/// return an invalid schema object. This is shorthand for the following:
///
/// \code
/// WalterExpression(stage->GetPrimAtPath(path));
/// \endcode
///
WALTERUSDEXTRAS_API
static WalterExpression
Get(const UsdStagePtr &stage, const SdfPath &path);
private:
// needs to invoke _GetStaticTfType.
friend class UsdSchemaRegistry;
WALTERUSDEXTRAS_API
static const TfType &_GetStaticTfType();
static bool _IsTypedSchema();
// override SchemaBase virtuals.
WALTERUSDEXTRAS_API
virtual const TfType &_GetTfType() const;
public:
// --------------------------------------------------------------------- //
// EXPRESSION
// --------------------------------------------------------------------- //
/// The expression.
///
/// \n C++ Type: std::string
/// \n Usd Type: SdfValueTypeNames->String
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: No Fallback
WALTERUSDEXTRAS_API
UsdAttribute GetExpressionAttr() const;
/// See GetExpressionAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateExpressionAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// GROUP
// --------------------------------------------------------------------- //
/// The name of the group the expression belongs to.
///
/// \n C++ Type: std::string
/// \n Usd Type: SdfValueTypeNames->String
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: No Fallback
WALTERUSDEXTRAS_API
UsdAttribute GetGroupAttr() const;
/// See GetGroupAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateGroupAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// ===================================================================== //
// Feel free to add custom code below this line, it will be preserved by
// the code generator.
//
// Just remember to:
// - Close the class declaration with };
// - Close the namespace with PXR_NAMESPACE_CLOSE_SCOPE
// - Close the include guard with #endif
// ===================================================================== //
// --(BEGIN CUSTOM CODE)--
// Building following structure:
// {"layer": {"target": "shader"}}
typedef std::unordered_map<std::string, SdfPath> AssignmentTargets;
typedef std::unordered_map<std::string, AssignmentTargets> AssignmentLayers;
std::string GetExpression() const;
void SetExpression(const std::string& expression);
// Get all the render layers and the shader assignments.
AssignmentLayers GetLayers() const;
void SetConnection(
const std::string& layer,
const std::string& target,
const SdfPath& shader);
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif
<|start_filename|>walter/houdini/src/walterHoudiniUtils.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __walterHoudiniUtils_h__
#define __walterHoudiniUtils_h__
#include <pxr/usd/usd/stage.h>
#include <pxr/usdImaging/usdImagingGL/gl.h>
PXR_NAMESPACE_USING_DIRECTIVE
typedef std::shared_ptr<UsdImagingGL> UsdImagingGLRefPtr;
namespace WalterHoudiniUtils
{
// Return the stage
UsdStageRefPtr getStage(const std::string& stageName);
// Return the Hydra renderer
UsdImagingGLRefPtr getRenderer(const std::string& stageName);
// Fill the output with the object names
void getObjectList(
const std::string& stageName,
const std::string& primPath,
bool geomOnly,
std::vector<std::string>& oList);
template <class To, class From> inline To MatrixConvert(const From& from)
{
// It's very ugly. Can't beleive GfMatrix4d can't take a pointer to the
// data.
return To(
from[0][0],
from[0][1],
from[0][2],
from[0][3],
from[1][0],
from[1][1],
from[1][2],
from[1][3],
from[2][0],
from[2][1],
from[2][2],
from[2][3],
from[3][0],
from[3][1],
from[3][2],
from[3][3]);
}
}
#endif
<|start_filename|>walter/cmake/FindGLFW.cmake<|end_filename|>
set(GLFW_STATIC_LIBRARIES ${GLFW_DIR}/lib/libglfw3.a)
set(GLFW_INCLUDE_DIR ${GLFW_DIR}/include)
include( FindPackageHandleStandardArgs )
find_package_handle_standard_args( "GLFW" DEFAULT_MSG
GLFW_STATIC_LIBRARIES
GLFW_INCLUDE_DIR
)
if(NOT GLFW_FOUND)
message(FATAL_ERROR "Try using -D GLFW_DIR=/path/to/glfw")
endif()
<|start_filename|>walter/viewer/CameraControler.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERVIEWER_CAMERACONTROLER_H__
#define __WALTERVIEWER_CAMERACONTROLER_H__
#include <cstdio>
namespace walter_viewer
{
class CameraControler
{
public:
CameraControler();
float rotTheta() const { return mRotTheta; }
float rotPhi() const { return mRotPhi; }
float rotPsi() const { return mRotPsi; }
float zoom() const { return mZoom; }
float panX() const { return mPanX; }
float panY() const { return mPanY; }
void setRotation(float theta, float phi, float psi);
void updateRotation(float dx, float dy);
void setZoom(float value) { mZoom = value; }
void updateZoom(float dx, float dy);
bool isPanning() const { return mPaning; }
void setPanning(bool value) { mPaning = value; }
void setPan(float x, float y)
{
mPanX = x;
mPanY = y;
}
void updatePan(float x, float y);
void setCenter(float x, float y, float z);
float const* center() const { return mCenter; }
void reset();
float mousePosLastX{0.f};
float mousePosLastY{0.f};
private:
// state
bool mPaning{false};
// cam rotation angles
float mRotTheta{0.f};
float mRotPhi{0.f};
float mRotPsi{0.f};
// cam zoom
float mZoom{0.f};
// cam pan
float mPanX{0.f};
float mPanY{0.f};
float mCenter[3] = {0.f};
};
} // end namespace walter_viewer
#endif
<|start_filename|>walter/cmake/FindMtoa.cmake<|end_filename|>
IF(NOT MTOA_BASE_DIR AND NOT $ENV{MTOA_BASE_DIR} STREQUAL "")
SET(MTOA_BASE_DIR $ENV{MTOA_BASE_DIR})
ENDIF()
set(MTOA_BASE_DIR
"${MTOA_BASE_DIR}"
CACHE
PATH
"Directory to search for MTOA")
find_library(MTOA_LIBRARY
NAMES
mtoa_api
PATHS
"${MTOA_BASE_DIR}/lib"
"${MTOA_BASE_DIR}/bin"
PATH_SUFFIXES
${_pathsuffixes})
find_path(MTOA_INCLUDE_DIR
NAMES
utils/Version.h
PATHS
"${MTOA_BASE_DIR}"
PATH_SUFFIXES
include)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(MTOACPP
DEFAULT_MSG
MTOA_LIBRARY
MTOA_INCLUDE_DIR)
if(MTOA_FOUND)
set(MTOA_LIBRARY "${MTOA_LIBRARY}")
set(MTOA_INCLUDE_DIR "${MTOA_INCLUDE_DIR}")
mark_as_advanced(MTOA_BASE_DIR)
endif()
mark_as_advanced(MTOA_INCLUDE_DIR MTOA_LIBRARY)
<|start_filename|>walter/katana/WalterIn/walterUSDOp.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERUSDOP_H_
#define __WALTERUSDOP_H_
#include <FnGeolib/op/FnGeolibOp.h>
/**
* @brief The entry point for USD scene graph generation.
*
* @param ioInterface A reference to a valid GeolibCookInterface object.
* @param iArchives List of USD archives to load.
*/
void cookUSDRoot(
Foundry::Katana::GeolibCookInterface& ioInterface,
const std::vector<std::string>& iArchives);
/** @brief */
void registerUSDPlugins();
#endif
<|start_filename|>walter/maya/AbcExport/walterAbcExportExtensions.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERABCEXPORTEXTENSIONS_H__
#define __WALTERABCEXPORTEXTENSIONS_H__
#include "MayaLightWriter.h"
/** @brief This is a helper object that exports lights to Alembic performing
* conversion to Arnold. */
class ArnoldLightExporter
{
public:
ArnoldLightExporter();
/**
* @brief Adds a light to the internal list.
*
* @param iLight Given light.
*/
void add(MayaLightWriterPtr iLight) { mLightList.push_back(iLight); }
/**
* @brief Export all the saved lights to Alembic.
*
* @param isFirst true if it's the first frame.
*/
void eval(bool isFirst);
/**
* @brief Checks if the given object is a light.
*
* @param iObject The given object.
*
* @return True if it's a light.
*/
static bool isLight(const MObject& iObject);
private:
bool mValid;
std::vector<Alembic::Util::shared_ptr<MayaLightWriter>> mLightList;
};
#endif
<|start_filename|>walter/katana/WalterIn/walterUSDOpDelegate.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterUSDOpDelegate.h"
#include "walterUSDOpCaboose.h"
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usdShade/connectableAPI.h>
#include <pxr/usd/usdShade/material.h>
#include <boost/algorithm/string.hpp>
void OpDelegate::populate(const UsdPrim& iRoot, OpIndex& oIndex)
{
UsdPrimRange range(iRoot);
for (const UsdPrim& prim : range)
{
// We already processed everything and since all the materials are
// loaded, we can work with expressions.
if (prim.IsA<WalterExpression>())
{
// Get expressions.
WalterExpression expression(prim);
// Insert them into a cache.
oIndex.insertExpression(
expression.GetExpression(), expression.GetLayers());
}
else if (prim.IsA<UsdShadeMaterial>())
{
// Check and save WalterOverrides.
// Iterate the connections.
for (const UsdAttribute& attr : prim.GetAttributes())
{
// The name is "arnold:surface"
std::string name = attr.GetName();
std::vector<std::string> splitted;
boost::split(splitted, name, boost::is_any_of(":"));
if (splitted.size() < 2)
{
continue;
}
// Extract the render and the target.
std::string render = splitted[0];
std::string target = splitted[1];
// TODO: other renders?
if (render != "arnold")
{
continue;
}
if (!UsdShadeConnectableAPI::HasConnectedSource(attr))
{
// This block saves Walter Overrides.
// We need to save the arnold attributes if any.
if (target != "attribute" && splitted.size() >= 3)
{
continue;
}
// Get the renderer attribute
OpCaboose::ClientAttributePtr clientAttribute =
OpCaboose::createClientAttribute(attr);
if (!clientAttribute->valid())
{
continue;
}
// Save it to the index.
oIndex.insertAttribute(
prim.GetPath(), attr.GetBaseName(), clientAttribute);
}
}
}
}
}
<|start_filename|>walter/houdini/src/plugin.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "GU_WalterPackedImpl.h"
#include "SOP_WalterNode.h"
#include <SYS/SYS_Version.h>
#include <UT/UT_DSOVersion.h>
#include <UT/UT_ScopedPtr.h>
SYS_VISIBILITY_EXPORT void newSopOperator(OP_OperatorTable *operators)
{
WalterHoudini::SOP_WalterNode::install(operators);
}
SYS_VISIBILITY_EXPORT void newGeometryPrim(GA_PrimitiveFactory *f)
{
WalterHoudini::GU_WalterPackedImpl::install(f);
}
<|start_filename|>walter/maya/walterMtoaConnection/abcCacheExportCmd.cpp<|end_filename|>
/*Abc Shader Exporter
Copyright (c) 2014, <NAME>, All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.*/
#include "mayaUtils.h"
#include "abcCacheExportCmd.h"
#include "abcExporterUtils.h"
#include "mtoaScene.h"
#include "mtoaVersion.h"
#include <Alembic/AbcCoreLayer/Util.h>
#include <boost/algorithm/string.hpp>
#include <unordered_set>
namespace Abc = Alembic::Abc;
namespace Mat = Alembic::AbcMaterial;
typedef std::pair<MPlug, std::string> TargetPlug;
// MPlug hasher to be able to create an unordered_set of MPlugs.
struct TargetPlugHash {
size_t operator()(const TargetPlug& targetPlug) const
{
std::hash<std::string> hasher;
return hasher(targetPlug.second + targetPlug.first.name().asChar());
}
};
MStatus abcCacheExportCmd::doIt( const MArgList &args)
{
MArgDatabase argData( syntax(), args);
if(!argData.isFlagSet( "-f"))
{
MGlobal::displayError("no output file!");
return MStatus::kFailure;
}
MString filename("");
argData.getFlagArgument( "-f", 0, filename);
// Used to mark that an Alembic object or property are meant to be replaced
// when reading via AbcCoreLayer. Replacing an object or compound property
// will also replace all of the children encountered and shading network so
// far.
Alembic::Abc::MetaData replace;
Alembic::AbcCoreLayer::SetReplace(replace, true);
Abc::OArchive archive(Alembic::AbcCoreOgawa::WriteArchive(), filename.asChar() );
Abc::OObject root(archive, Abc::kTop);
Abc::OObject materials(root, "materials");
MSelectionList list;
if(argData.isFlagSet( "-sl"))
{
MGlobal::getActiveSelectionList (list);
}
else if (argData.isFlagSet( "-node"))
{
MString node("");
argData.getFlagArgument( "-node", 0, node);
if (list.add(node) != MS::kSuccess)
{
MString warn = node;
warn += " could not be select, skipping.";
MGlobal::displayWarning(warn);
return MStatus::kFailure;
}
}
else
{
MItDependencyNodes nodeIt;
for (; !nodeIt.isDone(); nodeIt.next())
{
MObject node = nodeIt.item();
if (node.isNull())
continue;
list.add (node);
}
}
MTOAScene scene;
// Set because we shouldn't export materials twice.
std::unordered_set<TargetPlug, TargetPlugHash> shaderToExport;
static const char* exportKeys[][2] = {
{"shader", "surface"},
{"displacement", "displacement"} };
MItSelectionList iter(list, MFn::kPluginShape);
for (; !iter.isDone(); iter.next())
{
MObject dependNode;
iter.getDependNode(dependNode);
MFnDagNode dagNode(dependNode);
if (dagNode.typeId() == WALTER_MAYA_SHAPE_ID)
{
// TODO: Implement a walter iterator to iterate this stuff.
const MPlug layersAssignation =
dagNode.findPlug("layersAssignation");
if (layersAssignation.isNull())
{
continue;
}
if (layersAssignation.numElements() <= 0)
{
continue;
}
for (unsigned i=0; i<layersAssignation.numElements(); i++)
{
// Get walterStandin.layersAssignation[i]
const MPlug currentLayerCompound =
layersAssignation.elementByPhysicalIndex(i);
// Get walterStandin.layersAssignation[i].layer
MPlug layerPlug;
if (!GetChildMPlug(currentLayerCompound, "layer", layerPlug))
{
continue;
}
MPlugArray connections;
if (!layerPlug.connectedTo(connections, true, false) ||
!connections.length())
{
continue;
}
// The layer is the first connected node. We consider we have
// only one connection.
const MFnDependencyNode layer(connections[0].node());
const std::string layerName = layer.name().asChar();
MPlug shadersPlug;
if (!GetChildMPlug(
currentLayerCompound,
"shaderConnections",
shadersPlug))
{
continue;
}
for (unsigned j=0; j<shadersPlug.numElements(); j++)
{
// Get
// walterStandin.
// layersAssignation[i].
// shaderConnections[j]
const MPlug shadersCompound =
shadersPlug.elementByPhysicalIndex(j);
// Get
// walterStandin.
// layersAssignation[].
// shaderConnections[].
// abcnode
MPlug abcnodePlug;
if (!GetChildMPlug(
shadersCompound, "abcnode", abcnodePlug))
{
continue;
}
const MString abcnode = abcnodePlug.asString().asChar();
if (!abcnode.length()) {
continue;
}
BOOST_FOREACH (auto key, exportKeys) {
// Get
// walterStandin.
// layersAssignation[].
// shaderConnections[].
// shader
MPlug shaderPlug;
if (GetChildMPlug(shadersCompound, key[0], shaderPlug))
{
// Get the connected shader name
MPlugArray connections;
if (!shaderPlug.connectedTo(connections, 1, 0) ||
!connections.length())
{
continue;
}
shaderToExport.insert(
TargetPlug(connections[0], key[1]));
}
}
}
}
}
else
{
MPlug shaders = dagNode.findPlug("shaders");
for (unsigned int i=0;i<shaders.numElements();++i)
{
MPlug plug = shaders.elementByPhysicalIndex(i);
MPlugArray connections;
plug.connectedTo(connections, true, false);
for (unsigned int k=0; k<connections.length(); ++k)
{
MPlug sgPlug = connections[k];
if (sgPlug.node().apiType() == MFn::kShadingEngine ||
sgPlug.node().apiType() == MFn::kDisplacementShader)
{
shaderToExport.insert(TargetPlug(sgPlug, "surface"));
}
}
}
}
BOOST_FOREACH(const TargetPlug& toExport, shaderToExport)
{
// TODO: WTF is this? It looks like it's a set that contains all the
// nodes that are in the Alembic container. But it's filled, then
// it's iterated, then filled, then iterated again. Thus, they
// output nodes to alembic in the middle of filling exportedNodes.
// And when they iterate the second time, Alembic crashes because
// Alembic already has some nodes stored. It's a mess, and I don't
// refactor it right now just because I have a fear to break it
// just before my vacation. A couple notes how to refactor it
// properly. We don't need two nested loops. It would be better to
// pull the loop "for(;sit!=send;++sit)" out from "BOOST_FOREACH".
// Also, detecting the root node is wrong, there can be problems and
// in some case the material can look differently.
AtNodeSet* exportedNodes = new AtNodeSet;
// Ugly fix. We keep the exported nodes here because they output
// nodes to alembic in the middle of filling exportedNodes. So we
// need an alternative set to don't mix everything up.
AtNodeSet nodesInContainer;
// create the material
MFnDependencyNode container(toExport.first.node());
AiMsgInfo("[EXPORT] Creating container : %s", container.name().asChar());
AiMsgTab(+2);
// TODO: crashes when container.name() is already exported
Mat::OMaterial matObj(
materials, container.name().asChar(), replace);
// Export nodes to Arnold using MTOA
AtNodeSet roots;
CNodeTranslator* translator = scene.exportNode(toExport.first, &roots);
// exportNode() from the latest MTOA doesn't fill roots. The only
// way to get the node is using the translator.
AtNode* root = translator->GetArnoldNode();
{
exportedNodes->insert(root);
// We need to traverse the tree again...
getAllArnoldNodes(root, exportedNodes);
AtNodeSet::const_iterator sit (exportedNodes->begin()), send(exportedNodes->end());
for(;sit!=send;++sit)
{
// adding the node to the network
MString nodeName(container.name());
nodeName = nodeName + ":" + MString(AiNodeGetName(*sit));
nodeName = MString(boost::replace_all_copy(boost::replace_all_copy(std::string(nodeName.asChar()), ".message", ""), ".", "_").c_str());
if (!nodesInContainer.insert(*sit).second)
{
// See comment near definition of nodesInContainer.
// With this we are isolating the Alembic crash and
// leave everything else unchanged.
continue;
}
AiMsgInfo("[EXPORTING %s] Added node : %s", container.name().asChar(), nodeName.asChar());
matObj.getSchema().addNetworkNode(nodeName.asChar(), "arnold", AiNodeEntryGetName(AiNodeGetNodeEntry(*sit)));
if(root == *sit)
{
AiMsgInfo("[EXPORTING %s] Root node is : %s", container.name().asChar(), nodeName.asChar());
//TODO : get if it's a volume, eventually
matObj.getSchema().setNetworkTerminal(
"arnold",
toExport.second,
nodeName.asChar(),
"out");
}
//export parameters
AtParamIterator* nodeParam = AiNodeEntryGetParamIterator(AiNodeGetNodeEntry(*sit));
int outputType = AiNodeEntryGetOutputType(AiNodeGetNodeEntry(*sit));
while (!AiParamIteratorFinished(nodeParam))
{
const AtParamEntry *paramEntry = AiParamIteratorGetNext(nodeParam);
const char* paramName = AiParamGetName(paramEntry);
if(AiParamGetType(paramEntry) == AI_TYPE_ARRAY)
{
AtArray* paramArray = AiNodeGetArray(*sit, paramName);
processArrayValues(*sit, paramName, paramArray, outputType, matObj, nodeName, container.name());
for(unsigned int i=0; i < AiArrayGetNumElements(paramArray); i++)
{
processArrayParam(*sit, paramName, paramArray, i, outputType, matObj, nodeName, container.name());
}
}
else
{
processLinkedParam(*sit, AiParamGetType(paramEntry), outputType, matObj, nodeName, paramName, container.name(), true);
}
}
AiParamIteratorDestroy(nodeParam);
}
}
AiMsgTab(-2);
delete exportedNodes;
}
}
AiMsgInfo("[EXPORT] Success!");
return MStatus::kSuccess;
}
// There is never anything to undo.
//////////////////////////////////////////////////////////////////////
MStatus abcCacheExportCmd::undoIt(){
return MStatus::kSuccess;
}
//
// There is never really anything to redo.
//////////////////////////////////////////////////////////////////////
MStatus abcCacheExportCmd::redoIt(){
return MStatus::kSuccess;
}
//
//
//////////////////////////////////////////////////////////////////////
bool abcCacheExportCmd::isUndoable() const{
return false;
}
//
//
//////////////////////////////////////////////////////////////////////
bool abcCacheExportCmd::hasSyntax() const {
return true;
}
//
//
//////////////////////////////////////////////////////////////////////
MSyntax abcCacheExportCmd::mySyntax() {
MSyntax syntax;
syntax.addFlag( "-sl", "-selection", MSyntax::kString);
syntax.addFlag( "-f", "-file", MSyntax::kString);
syntax.addFlag( "-n", "-node", MSyntax::kString);
return syntax;
}
//
//
//////////////////////////////////////////////////////////////////////
bool abcCacheExportCmd::isHistoryOn() const {
//what is this supposed to do?
return false;
}
MString abcCacheExportCmd::commandString() const {
return MString();
}
MStatus abcCacheExportCmd::setHistoryOn( bool state ){
//ignore it for now
return MStatus::kSuccess;
}
MStatus abcCacheExportCmd::setCommandString( const MString &str) {
//ignore it for now
return MStatus::kSuccess;
}
<|start_filename|>walter/maya/walterStandin/walterAssignment.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterAssignment.h"
#include "OWalterExpressionsSchema.h"
#include <Alembic/Abc/All.h>
#include <Alembic/AbcCoreFactory/All.h>
#include <Alembic/AbcCoreLayer/Util.h>
#include <Alembic/AbcCoreOgawa/All.h>
#include <maya/MGlobal.h>
#include <maya/MSelectionList.h>
bool saveAssignment(const MString& objectName, const MString& fileName)
{
// Looking for MFnDependencyNode object in the scene.
MSelectionList selectionList;
selectionList.add(objectName);
MObject obj;
selectionList.getDependNode(0, obj);
MFnDependencyNode depNode(obj);
const MPlug layersAssignation = depNode.findPlug("layersAssignation");
if (layersAssignation.isNull())
{
MString msg;
msg.format("[walter] Can't find ^1s.layersAssignation", depNode.name());
MGlobal::displayError(msg);
return false;
}
if (layersAssignation.numElements() <= 0)
{
MString msg;
msg.format(
"[walter] There are no assignments to save in ^1s", objectName);
MGlobal::displayError(msg);
return false;
}
// Create Alembic file. Exceptions is a standard alembic way to get an error
// as a string.
Alembic::Abc::OArchive archive;
try
{
archive = Alembic::Abc::OArchive(
Alembic::AbcCoreOgawa::WriteArchive(), fileName.asChar());
}
catch (std::exception& exc)
{
MString msg;
msg.format(
"[walter] Can't write alembic ^1s. Exception:\n^2s",
fileName,
exc.what());
MGlobal::displayError(msg);
return false;
}
OWalterExpressionsSchema expressions = addExpressions(archive.getTop());
for (unsigned int i = 0; i < layersAssignation.numElements(); i++)
{
// Get walterStandin.layersAssignation[i]
const MPlug currentLayerCompound =
layersAssignation.elementByPhysicalIndex(i);
// Get walterStandin.layersAssignation[i].layer
MPlug layerPlug;
if (!GetChildMPlug(currentLayerCompound, "layer", layerPlug))
{
continue;
}
MPlugArray connections;
if (!layerPlug.connectedTo(connections, true, false) ||
!connections.length())
{
continue;
}
// The layer is the first connected node. We consider we have only one
// connection.
const MFnDependencyNode layer(connections[0].node());
const std::string layerName = layer.name().asChar();
// The list of plugs to look up.
static const char* plugsToFind[] = {
"shader", "displacement", "attribute"};
// It's the three maps of sub-node names to assigned matrials.
typedef std::map<WalterCommon::Expression, MObject> ExpressionToMObject;
std::vector<ExpressionToMObject> assignments(
sizeof(plugsToFind) / sizeof(*plugsToFind));
// Get all the assignments.
getAllAssignments(
currentLayerCompound,
MStringArray(plugsToFind, assignments.size()),
assignments);
if (assignments.empty())
{
// We are here because currentLayerCompound doesn't have the plug
// shaderConnections.
continue;
}
// Iterate the result of getAllAssignments.
for (int n = 0; n < sizeof(plugsToFind) / sizeof(*plugsToFind); n++)
{
const auto& subNodeToMaterial = assignments[n];
for (const auto& item : subNodeToMaterial)
{
const MObject node(item.second);
std::string shader = MFnDependencyNode(node).name().asChar();
expressions.setExpressionShader(
item.first.getExpression(),
layerName,
plugsToFind[n],
shader);
}
}
}
// Set expression groups
const MPlug expressionsPlug = depNode.findPlug("expressions");
if (!expressionsPlug.isNull())
{
for (unsigned int i = 0; i < expressionsPlug.numElements(); i++)
{
// Get expressions[i]
const MPlug expressionCompound =
expressionsPlug.elementByPhysicalIndex(i);
MPlug namePlug;
if (!GetChildMPlug(expressionCompound, "en", namePlug))
{
continue;
}
MPlug groupPlug;
if (!GetChildMPlug(expressionCompound, "egn", groupPlug))
{
continue;
}
std::string name(namePlug.asString().asChar());
std::string group(groupPlug.asString().asChar());
if (name.empty())
{
continue;
}
expressions.setExpressionGroup(name, group);
}
}
return true;
}
<|start_filename|>walter/usd/schemas/volume.h<|end_filename|>
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#ifndef WALTERUSDEXTRAS_GENERATED_VOLUME_H
#define WALTERUSDEXTRAS_GENERATED_VOLUME_H
/// \file walterUsdExtras/volume.h
#include "pxr/pxr.h"
#include ".//api.h"
#include "pxr/usd/usdGeom/gprim.h"
#include "pxr/usd/usd/prim.h"
#include "pxr/usd/usd/stage.h"
#include ".//tokens.h"
#include "pxr/base/vt/value.h"
#include "pxr/base/gf/vec3d.h"
#include "pxr/base/gf/vec3f.h"
#include "pxr/base/gf/matrix4d.h"
#include "pxr/base/tf/token.h"
#include "pxr/base/tf/type.h"
PXR_NAMESPACE_OPEN_SCOPE
class SdfAssetPath;
// -------------------------------------------------------------------------- //
// VOLUME //
// -------------------------------------------------------------------------- //
/// \class WalterVolume
///
/// Defines a primive volume centered at the origin.
///
class WalterVolume : public UsdGeomGprim
{
public:
/// Compile-time constant indicating whether or not this class corresponds
/// to a concrete instantiable prim type in scene description. If this is
/// true, GetStaticPrimDefinition() will return a valid prim definition with
/// a non-empty typeName.
static const bool IsConcrete = true;
/// Compile-time constant indicating whether or not this class inherits from
/// UsdTyped. Types which inherit from UsdTyped can impart a typename on a
/// UsdPrim.
static const bool IsTyped = true;
/// Construct a WalterVolume on UsdPrim \p prim .
/// Equivalent to WalterVolume::Get(prim.GetStage(), prim.GetPath())
/// for a \em valid \p prim, but will not immediately throw an error for
/// an invalid \p prim
explicit WalterVolume(const UsdPrim& prim=UsdPrim())
: UsdGeomGprim(prim)
{
}
/// Construct a WalterVolume on the prim held by \p schemaObj .
/// Should be preferred over WalterVolume(schemaObj.GetPrim()),
/// as it preserves SchemaBase state.
explicit WalterVolume(const UsdSchemaBase& schemaObj)
: UsdGeomGprim(schemaObj)
{
}
/// Destructor.
WALTERUSDEXTRAS_API
virtual ~WalterVolume();
/// Return a vector of names of all pre-declared attributes for this schema
/// class and all its ancestor classes. Does not include attributes that
/// may be authored by custom/extended methods of the schemas involved.
WALTERUSDEXTRAS_API
static const TfTokenVector &
GetSchemaAttributeNames(bool includeInherited=true);
/// Return a WalterVolume holding the prim adhering to this
/// schema at \p path on \p stage. If no prim exists at \p path on
/// \p stage, or if the prim at that path does not adhere to this schema,
/// return an invalid schema object. This is shorthand for the following:
///
/// \code
/// WalterVolume(stage->GetPrimAtPath(path));
/// \endcode
///
WALTERUSDEXTRAS_API
static WalterVolume
Get(const UsdStagePtr &stage, const SdfPath &path);
/// Attempt to ensure a \a UsdPrim adhering to this schema at \p path
/// is defined (according to UsdPrim::IsDefined()) on this stage.
///
/// If a prim adhering to this schema at \p path is already defined on this
/// stage, return that prim. Otherwise author an \a SdfPrimSpec with
/// \a specifier == \a SdfSpecifierDef and this schema's prim type name for
/// the prim at \p path at the current EditTarget. Author \a SdfPrimSpec s
/// with \p specifier == \a SdfSpecifierDef and empty typeName at the
/// current EditTarget for any nonexistent, or existing but not \a Defined
/// ancestors.
///
/// The given \a path must be an absolute prim path that does not contain
/// any variant selections.
///
/// If it is impossible to author any of the necessary PrimSpecs, (for
/// example, in case \a path cannot map to the current UsdEditTarget's
/// namespace) issue an error and return an invalid \a UsdPrim.
///
/// Note that this method may return a defined prim whose typeName does not
/// specify this schema class, in case a stronger typeName opinion overrides
/// the opinion at the current EditTarget.
///
WALTERUSDEXTRAS_API
static WalterVolume
Define(const UsdStagePtr &stage, const SdfPath &path);
private:
// needs to invoke _GetStaticTfType.
friend class UsdSchemaRegistry;
WALTERUSDEXTRAS_API
static const TfType &_GetStaticTfType();
static bool _IsTypedSchema();
// override SchemaBase virtuals.
WALTERUSDEXTRAS_API
virtual const TfType &_GetTfType() const;
public:
// --------------------------------------------------------------------- //
// VOLUMEPADDING
// --------------------------------------------------------------------- //
/// Enlarge the volume by Padding. This is useful when
/// displacing a volume with a noise for example.
///
/// \n C++ Type: float
/// \n Usd Type: SdfValueTypeNames->Float
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: 0.0
WALTERUSDEXTRAS_API
UsdAttribute GetVolumePaddingAttr() const;
/// See GetVolumePaddingAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateVolumePaddingAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// STEPSIZE
// --------------------------------------------------------------------- //
/// Sets the size for sampling inside the volume.
///
/// \n C++ Type: float
/// \n Usd Type: SdfValueTypeNames->Float
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: 0.0
WALTERUSDEXTRAS_API
UsdAttribute GetStepSizeAttr() const;
/// See GetStepSizeAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateStepSizeAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// FILENAME
// --------------------------------------------------------------------- //
/// The location of the VDB file.
///
/// \n C++ Type: std::string
/// \n Usd Type: SdfValueTypeNames->String
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: No Fallback
WALTERUSDEXTRAS_API
UsdAttribute GetFilenameAttr() const;
/// See GetFilenameAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateFilenameAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// FILEDATA
// --------------------------------------------------------------------- //
/// The volume data.
///
/// \n C++ Type: VtArray<unsigned char>
/// \n Usd Type: SdfValueTypeNames->UCharArray
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: No Fallback
WALTERUSDEXTRAS_API
UsdAttribute GetFiledataAttr() const;
/// See GetFiledataAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateFiledataAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// STEPSCALE
// --------------------------------------------------------------------- //
/// A scaling factor applied to the step size, mostly useful
/// when the Volume Step is set to Automatic, to modulate the automatic
/// value.
///
/// \n C++ Type: float
/// \n Usd Type: SdfValueTypeNames->Float
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: 1.0
WALTERUSDEXTRAS_API
UsdAttribute GetStepScaleAttr() const;
/// See GetStepScaleAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateStepScaleAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// COMPRESS
// --------------------------------------------------------------------- //
/// Compress grids to reduce memory usage.
///
/// \n C++ Type: bool
/// \n Usd Type: SdfValueTypeNames->Bool
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: True
WALTERUSDEXTRAS_API
UsdAttribute GetCompressAttr() const;
/// See GetCompressAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateCompressAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// GRIDS
// --------------------------------------------------------------------- //
/// A list of OpenVDB grids to read and make available as
/// channels in the volume shading context.
///
/// \n C++ Type: VtArray<std::string>
/// \n Usd Type: SdfValueTypeNames->StringArray
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: No Fallback
WALTERUSDEXTRAS_API
UsdAttribute GetGridsAttr() const;
/// See GetGridsAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateGridsAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// VELOCITYSCALE
// --------------------------------------------------------------------- //
/// A scale factor for the velocity field. A value of 0
/// disables motion blur.
///
/// \n C++ Type: float
/// \n Usd Type: SdfValueTypeNames->Float
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: 1.0
WALTERUSDEXTRAS_API
UsdAttribute GetVelocityScaleAttr() const;
/// See GetVelocityScaleAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateVelocityScaleAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// VELOCITYFPS
// --------------------------------------------------------------------- //
/// FPS for the velocity field.
///
/// \n C++ Type: float
/// \n Usd Type: SdfValueTypeNames->Float
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: 24.0
WALTERUSDEXTRAS_API
UsdAttribute GetVelocityFpsAttr() const;
/// See GetVelocityFpsAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateVelocityFpsAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// VELOCITYOUTLIERTHRESHOLD
// --------------------------------------------------------------------- //
/// Controls filtering of noisy velocities resulting in the
/// faster rendering of motion blur from physics simulations.
///
/// \n C++ Type: float
/// \n Usd Type: SdfValueTypeNames->Float
/// \n Variability: SdfVariabilityVarying
/// \n Fallback Value: 0.0010000000475
WALTERUSDEXTRAS_API
UsdAttribute GetVelocityOutlierThresholdAttr() const;
/// See GetVelocityOutlierThresholdAttr(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create.
/// If specified, author \p defaultValue as the attribute's default,
/// sparsely (when it makes sense to do so) if \p writeSparsely is \c true -
/// the default for \p writeSparsely is \c false.
WALTERUSDEXTRAS_API
UsdAttribute CreateVelocityOutlierThresholdAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// ===================================================================== //
// Feel free to add custom code below this line, it will be preserved by
// the code generator.
//
// Just remember to:
// - Close the class declaration with };
// - Close the namespace with PXR_NAMESPACE_CLOSE_SCOPE
// - Close the include guard with #endif
// ===================================================================== //
// --(BEGIN CUSTOM CODE)--
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif
<|start_filename|>walter/usd/tests/test_getUSDLayer.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/stage.h>
#include "walterUSDCommonUtils.h"
#include <gtest/gtest.h>
PXR_NAMESPACE_USING_DIRECTIVE
TEST(getUSDLayer, testOneIdentifier)
{
SdfLayerRefPtr rootLayer = WalterUSDCommonUtils::getUSDLayer("A");
EXPECT_EQ(rootLayer->GetNumSubLayerPaths(), 1);
}
TEST(getUSDLayer, testTwoIdentifiers)
{
SdfLayerRefPtr rootLayer = WalterUSDCommonUtils::getUSDLayer("A:B");
EXPECT_EQ(rootLayer->GetNumSubLayerPaths(), 2);
}
<|start_filename|>walter/viewer/FreeCamera.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERVIEWER_FREECAMERA_H__
#define __WALTERVIEWER_FREECAMERA_H__
#include "Types.h"
#include "CameraControler.h"
#include <pxr/base/gf/camera.h>
PXR_NAMESPACE_USING_DIRECTIVE
namespace walter_viewer
{
class FreeCamera : public GfCamera
{
public:
FreeCamera();
void updateZoom();
void updatePan(int height);
void updateTumble();
void reset();
const GfVec3d& angles() const;
const GfVec3d& center() const { return mCenter; }
CameraControler& controler() { return mControler; }
private:
GfVec3d mCenter{0.0};
CameraControler mControler;
};
} // end namespace walter_viewer
#endif
<|start_filename|>walter/houdini/src/DM_WalterRenderHook.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include <GL/gl.h>
#include <DM/DM_GeoDetail.h>
#include <DM/DM_RenderTable.h>
#include <DM/DM_SceneHook.h>
#include <DM/DM_VPortAgent.h>
#include <GR/GR_Primitive.h>
#include <RE/RE_Render.h>
#include <SOP/SOP_Node.h>
#include <UT/UT_Map.h>
#include <pxr/imaging/glf/drawTarget.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/stage.h>
#include "GU_WalterPackedImpl.h"
#include "walterHoudiniUtils.h"
#include "walterSpriteRenderer.h"
PXR_NAMESPACE_USING_DIRECTIVE
namespace {
typedef std::pair<exint, GA_Index> PrimUniqueID;
typedef std::set<PrimUniqueID> WirefameSet;
/**
* @brief Extracts the WalterPacked intrinsinc attributes
*
* @param iPrim The pointer to the GEO_Primitive object.
* @param oFileName The USD stage name will be writtent here.
* @param oRendererName The Hudra renderer plugin name.
* @param oPrimPath The USD path to the prim will be there.
* @param oTransform The local transform will be there.
* @param oFrame The frame will be there.
*/
void getPrimData(
const GEO_Primitive* iPrim,
std::string& oFileName,
std::string& oRendererName,
SdfPath& oPrimPath,
UT_Matrix4D& oTransform,
float& oFrame)
{
assert(iPrim);
UT_String fileName;
iPrim->getIntrinsic(
iPrim->findIntrinsic(WalterHoudini::GU_WalterPackedImpl::usdFileName), fileName);
oFileName = fileName.toStdString();
UT_String rendererName;
iPrim->getIntrinsic(
iPrim->findIntrinsic(WalterHoudini::GU_WalterPackedImpl::rendererName), rendererName);
oRendererName = rendererName.toStdString();
UT_String primPath;
iPrim->getIntrinsic(
iPrim->findIntrinsic(WalterHoudini::GU_WalterPackedImpl::usdPrimPath), primPath);
// Generate SdfPath
if (primPath && primPath.length() > 0)
{
oPrimPath = SdfPath(primPath.toStdString());
}
else
{
oPrimPath = SdfPath::EmptyPath();
}
iPrim->getLocalTransform4(oTransform);
iPrim->getIntrinsic(
iPrim->findIntrinsic(WalterHoudini::GU_WalterPackedImpl::usdFrame), oFrame);
}
/**
* @brief Draw the USD object in the current OpenGL state. It sets up Hydra and
* calls the drawing methods.
*
* @param iFileName The name of the USD stage to draw.
* @param iPrimPath The path to the prim to draw in the USD stage.
* @param iView The view matrix.
* @param iProjection The projection matrix.
* @param iWidth The width of the current viewport.
* @param iHeight The height of the current viewport.
* @param iParams The Hydra params. The frame can be changed.
*/
void drawWalterPrim(
const std::string& iRendererName,
const std::string& iFileName,
const SdfPath& iPrimPath,
const UT_Matrix4D& iView,
const UT_Matrix4D& iProjection,
int iWidth,
int iHeight,
const UsdImagingGLEngine::RenderParams& iParams)
{
UsdStageRefPtr stage = WalterHoudiniUtils::getStage(iFileName);
UsdImagingGLRefPtr renderer = WalterHoudiniUtils::getRenderer(iFileName);
if (stage && renderer)
{
// Set renderer plugin
// TODO: set only when the renderer change.
for (const TfToken& current : renderer->GetRendererPlugins())
{
if( current.GetString() == iRendererName )
{
renderer->SetRendererPlugin(current);
break;
}
}
// Draw all.
UsdPrim prim;
if (iPrimPath.IsEmpty() || iPrimPath == SdfPath::AbsoluteRootPath())
{
prim = stage->GetPseudoRoot();
}
else
{
prim = stage->GetPrimAtPath(iPrimPath);
}
if (prim)
{
// Hydra.
auto viewMatrix = WalterHoudiniUtils::MatrixConvert<GfMatrix4d>(iView);
renderer->SetCameraState(
viewMatrix,
WalterHoudiniUtils::MatrixConvert<GfMatrix4d>(iProjection),
GfVec4d(0, 0, iWidth, iHeight));
// Add a light positonned at the camera
auto light = GlfSimpleLight();
light.SetAmbient(GfVec4f(0.0f));
GfVec3d translation = viewMatrix.GetInverse().ExtractTranslation();
light.SetPosition(GfVec4f(
static_cast<float>(translation[0]),
static_cast<float>(translation[1]),
static_cast<float>(translation[2]),
1.0f));
GlfSimpleLightVector lights;
lights.push_back(light);
auto material = GlfSimpleMaterial();
GfVec4f sceneAmbient(0.01f);
renderer->SetLightingState(lights, material, sceneAmbient);
renderer->Render(prim, iParams);
}
}
}
} // end anonymous namespace
class DM_WalterRenderHook : public DM_SceneRenderHook
{
public:
DM_WalterRenderHook(DM_VPortAgent& vport, WirefameSet& iWireframedObjects) :
DM_SceneRenderHook(vport, DM_VIEWPORT_ALL_3D),
mRefCount(0),
mWireframedObjects(iWireframedObjects)
{
static const float colorData[] = {1.0f, 0.699394f, 0.0f, 0.5f};
mParams.wireframeColor.Set(colorData);
}
virtual ~DM_WalterRenderHook() {}
virtual bool supportsRenderer(GR_RenderVersion version)
{
return version >= GR_RENDER_GL3;
}
// Because this hook is bound to multiple passes, differentiate between the
// various passes in our render method.
virtual bool render(RE_Render* r, const DM_SceneHookData& hook_data)
{
// SideFX support told us to use this to fix shading problems. Without
// those lines, all the other objects are black because Hydra modifies
// OpenGL state. It works well starting from 16.5.349.
r->unbindPipeline();
r->invalidateCachedState();
// View matrix.
const UT_Matrix4D view =
viewport().getViewStateRef().getTransformMatrix();
// Projection matrix.
const UT_Matrix4D projection =
viewport().getViewStateRef().getProjectionMatrix();
// Viewport.
int width = viewport().getViewStateRef().getViewWidth();
int height = viewport().getViewStateRef().getViewHeight();
// It changes the framebuffer to draw.
mSprite.drawToBufferBegin();
// Iterate the objects in the object list.
for (int i = 0; i < viewport().getNumOpaqueObjects(); i++)
{
DM_GeoDetail detail = viewport().getOpaqueObject(i);
if (!detail.isValid() || detail.getNumDetails() == 0)
{
continue;
}
// The SOP the detail represents.
OP_Node* op = detail.getSop();
if (!op)
{
continue;
}
SOP_Node* sop = reinterpret_cast<SOP_Node*>(op);
const GU_Detail* gdp = sop->getLastGeo();
if (!gdp)
{
continue;
}
exint detailID = gdp->getUniqueId();
// Transform of the object.
const UT_Matrix4D objXForm = detail.getDetailTransform(0);
const GEO_PrimList list = gdp->primitives();
// Iterate all the prims
const GEO_Primitive* prim =
list.head(GA_PrimCompat::TypeMask::fullMask());
if(!prim)
{
continue;
}
while (prim)
{
if (prim->getTypeDef().getId() == WalterHoudini::GU_WalterPackedImpl::typeId())
{
std::string fileName;
float frame;
std::string rendererName;
SdfPath primPath;
UT_Matrix4D transform;
getPrimData(
prim,
fileName,
rendererName,
primPath,
transform,
frame);
mParams.frame = frame;
// Check the cache if we should draw wireframe.
const auto it = mWireframedObjects.find(
std::make_pair(detailID, prim->getMapIndex()));
if (it == mWireframedObjects.end())
{
mParams.drawMode =
UsdImagingGLEngine::DRAW_SHADED_SMOOTH;
}
else
{
mParams.drawMode =
UsdImagingGLEngine::DRAW_WIREFRAME_ON_SURFACE;
}
drawWalterPrim(
rendererName,
fileName,
primPath,
transform * objXForm * view,
projection,
width,
height,
mParams);
}
prim = list.next(prim, GA_PrimCompat::TypeMask::fullMask());
}
}
// Clear the cache.
mWireframedObjects.clear();
// It restores the framebuffer.
mSprite.drawToBufferEnd();
mSprite.drawBeauty();
// Allow other hooks bound to this pass to render by returning false
return false;
}
virtual void viewportClosed()
{
// For some unknown reasons, this virtual method is never called.
}
// Reference count so that the DM_WalterSceneHook knows when to delete this
// object.
int bumpRefCount(bool inc)
{
mRefCount += (inc ? 1 : -1);
return mRefCount;
}
private:
int mRefCount;
UsdImagingGLEngine::RenderParams mParams;
WalterSpriteRenderer::SpriteRenderer mSprite;
WirefameSet& mWireframedObjects;
};
class GUI_WalterPrimFramework : public GR_Primitive
{
public:
GUI_WalterPrimFramework(
const GR_RenderInfo* info,
const char* cache_name,
const GEO_Primitive* prim,
WirefameSet& iWireframedObjects) :
GR_Primitive(info, cache_name, GA_PrimCompat::TypeMask(0)),
mWireframedObjects(iWireframedObjects)
{}
virtual ~GUI_WalterPrimFramework() {}
virtual const char* className() const { return "GUI_WalterPrimFramework"; }
// See if the primitive can be consumed by this GR_Primitive. Only
// primitives from the same detail will ever be passed in. If the primitive
// hook specifies GUI_HOOK_COLLECT_PRIMITIVES then it is possible to have
// this called more than once for different GR_Primitives. A GR_Primitive
// that collects multiple GT or GEO primitives is responsible for keeping
// track of them (in a list, table, tree, etc).
virtual GR_PrimAcceptResult acceptPrimitive(
GT_PrimitiveType t,
int geo_type,
const GT_PrimitiveHandle& ph,
const GEO_Primitive* prim)
{
static const int walterPrimID = WalterHoudini::GU_WalterPackedImpl::typeId().get();
if (geo_type == walterPrimID)
{
return GR_PROCESSED;
}
return GR_NOT_PROCESSED;
}
// Called whenever the parent detail is changed, draw modes are changed,
// selection is changed, or certain volatile display options are changed
// (such as level of detail).
virtual void update(
RE_Render* r,
const GT_PrimitiveHandle& primh,
const GR_UpdateParms& p)
{
// Fetch the GEO primitive from the GT primitive handle
const GEO_Primitive* prim = nullptr;
getGEOPrimFromGT<GEO_Primitive>(primh, prim);
if (!prim)
{
return;
}
float frame;
getPrimData(
prim, mFileName, mRendererName, mPrimPath, mTransform, frame);
mParams.frame = frame;
mID = std::make_pair(
prim->getDetail().getUniqueId(), prim->getMapIndex());
}
// Called to do a variety of render tasks (beauty, wire, shadow, object
// pick)
virtual void render(
RE_Render* r,
GR_RenderMode render_mode,
GR_RenderFlags flags,
GR_DrawParms draw_parms)
{
// See comments in newRenderHook(). Since GR_Primitive::render is called
// before DM_WalterRenderHook::render, we can form the set here and
// clean it up after reading in DM_WalterRenderHook::render.
if (render_mode == GR_RENDER_BEAUTY && flags & GR_RENDER_FLAG_WIRE_OVER)
{
mWireframedObjects.insert(mID);
return;
}
bool isPick = render_mode == GR_RENDER_OBJECT_PICK;
bool isMatte = render_mode == GR_RENDER_MATTE;
// For now we only support pick, matte and wireframe.
if (!isPick && !isMatte)
{
return;
}
RE_Uniform* base = r->getUniform(RE_UNIFORM_PICK_BASE_ID);
RE_Uniform* comp = r->getUniform(RE_UNIFORM_PICK_COMPONENT_ID);
int* baseVec = (int*)base->getValue();
int* compVec = (int*)comp->getValue();
WalterSpriteRenderer::GLScopeGuard scopeRestore(r);
// It changes the framebuffer to draw.
mSprite.drawToBufferBegin();
// From SideFX support.
UT_Matrix4D projection =
r->getUniform(RE_UNIFORM_PROJECT_MATRIX)->getMatrix4();
UT_Matrix4D view = r->getUniform(RE_UNIFORM_VIEW_MATRIX)->getMatrix4();
UT_Matrix4D objXForm =
r->getUniform(RE_UNIFORM_OBJECT_MATRIX)->getMatrix4();
// TODO: Is there a way to get rid of this? It's the only OpenGL call in
// this file.
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
drawWalterPrim(
mRendererName,
mFileName,
mPrimPath,
mTransform * objXForm * view,
projection,
viewport[2],
viewport[3],
mParams);
// It restores the framebuffer.
mSprite.drawToBufferEnd();
if (isPick)
{
mSprite.drawPick(baseVec, compVec);
}
else
{
mSprite.drawMatte();
}
}
// Render this primitive for picking, where pick_type is defined as one of
// the pickable bits in GU_SelectType.h (like GU_PICK_GEOPOINT) return the
// number of picks
virtual int renderPick(
RE_Render* r,
const GR_DisplayOption* opt,
unsigned int pick_type,
GR_PickStyle pick_style,
bool has_pick_map)
{
// For some unknown reason it's never called.
return 0;
}
private:
WalterSpriteRenderer::SpriteRenderer mSprite;
UsdImagingGLEngine::RenderParams mParams;
std::string mFileName;
SdfPath mPrimPath;
std::string mRendererName;
float mFrame;
UT_Matrix4D mTransform;
PrimUniqueID mID;
WirefameSet& mWireframedObjects;
};
class DM_WalterSceneHook : public DM_SceneHook
{
public:
DM_WalterSceneHook() : DM_SceneHook("WalterScene", 0) {}
virtual ~DM_WalterSceneHook() {}
virtual DM_SceneRenderHook* newSceneRender(
DM_VPortAgent& vport,
DM_SceneHookType type,
DM_SceneHookPolicy policy)
{
// Only for 3D views (persp, top, bottom; not the UV viewport)
if (!(vport.getViewType() & DM_VIEWPORT_ALL_3D))
{
return nullptr;
}
DM_WalterRenderHook* hook = nullptr;
// Create only 1 per viewport.
const int id = vport.getUniqueId();
UT_Map<int, DM_WalterRenderHook*>::iterator it = mSceneHooks.find(id);
if (it != mSceneHooks.end())
{
// Found existing hook for this viewport, reuse it.
hook = it->second;
}
else
{
// No hook for this viewport; create it.
hook = new DM_WalterRenderHook(vport, mWireframedObjects);
mSceneHooks[id] = hook;
}
// Increase reference count on the render so we know when to delete it.
hook->bumpRefCount(true);
return hook;
}
virtual void retireSceneRender(
DM_VPortAgent& vport,
DM_SceneRenderHook* hook)
{
// If the ref count is zero, we're the last retire call. delete the
// hook.
// RND-613: When closing Houdini, (if there is at least one open
// viewport), the Houdini process is not released for some unknown
// reason. If all the Houdini viewports are closed BEFORE closing
// Houdini, there is no issue. It looks like when Houdini exit,
// the "viewport delete" calls are not done the same way than when just
// closing a scene view tab...
if (static_cast<DM_WalterRenderHook*>(hook)->bumpRefCount(false) == 0)
{
// Remove from the map and delete the hook.
const int id = vport.getUniqueId();
UT_Map<int, DM_WalterRenderHook*>::iterator it =
mSceneHooks.find(id);
if (it != mSceneHooks.end())
{
mSceneHooks.erase(id);
}
delete hook;
}
}
WirefameSet& getWireframedObjects() { return mWireframedObjects; }
private:
// Keeps a hook per viewport.
UT_Map<int, DM_WalterRenderHook*> mSceneHooks;
// List of GEO_Primitives that should be drawn with wireframe. See comments
// in newRenderHook().
WirefameSet mWireframedObjects;
};
class GUI_WalterPrimHook : public GUI_PrimitiveHook
{
public:
GUI_WalterPrimHook(WirefameSet& iWireframedObjects) :
GUI_PrimitiveHook("Walter Prim Hook"),
mWireframedObjects(iWireframedObjects)
{}
virtual ~GUI_WalterPrimHook() {}
// If the geo_prim is a WalterPacked, return a new GUI_WalterPrimFramework.
virtual GR_Primitive* createPrimitive(
const GT_PrimitiveHandle& gt_prim,
const GEO_Primitive* geo_prim,
const GR_RenderInfo* info,
const char* cache_name,
GR_PrimAcceptResult& processed)
{
if (geo_prim->getTypeId() != WalterHoudini::GU_WalterPackedImpl::typeId())
{
return nullptr;
}
// We're going to process this prim and prevent any more lower-priority
// hooks from hooking on it. Alternatively, GR_PROCESSED_NON_EXCLUSIVE
// could be passed back, in which case any hooks of lower priority would
// also be called.
processed = GR_PROCESSED;
// In this case, we aren't doing anything special, like checking
// attribs to see if this is a flagged native primitive we want
// to hook on.
return new GUI_WalterPrimFramework(
info, cache_name, geo_prim, mWireframedObjects);
}
private:
WirefameSet& mWireframedObjects;
};
void newRenderHook(DM_RenderTable* table)
{
DM_WalterSceneHook* hook = new DM_WalterSceneHook();
// Register the hook so that it executes after the beauty pass. We use Scene
// Hook to draw everything at once. It's much faster than drawing objects
// one by one.
table->registerSceneHook(hook, DM_HOOK_BEAUTY, DM_HOOK_AFTER_NATIVE);
// We draw all the objects of the scene in DM_SceneRenderHook::render at
// once. But we don't know if we need to draw objects with wireframe from
// there. So, if we draw wireframed objects in GR_Primitive::render, it's
// very slow because each wire object will be drawn twice. To avoid it, we
// collect the indexes of wireframed objects and use them in
// DM_SceneRenderHook::render when we draw all the scene at once. It's the
// cache we keep the indexes.
WirefameSet& wireframedObjects = hook->getWireframedObjects();
// The priority only matters if multiple hooks are assigned to the same
// primitive type. If this is the case, the hook with the highest priority
// (largest priority value) is processed first. We use GEO Hook to draw
// selection. Unfortunately, there is no option to draw pass ID in a scene
// hook, and we need to draw it one by one.
GA_PrimitiveTypeId type = WalterHoudini::GU_WalterPackedImpl::typeId();
table->registerGEOHook(new GUI_WalterPrimHook(wireframedObjects), type, 0);
}
<|start_filename|>walter/usd/rdoCustomResource.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __RDOCUSTOMRESOURCE_H__
#define __RDOCUSTOMRESOURCE_H__
#ifdef __cplusplus
extern "C" {
#endif
void setResource(const char* filename, const char* contents);
const char* getResource(const char* filename);
#ifdef __cplusplus
}
#endif
#endif
<|start_filename|>walter/katana/WalterIn/walterUSDExtern.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterUSDExtern.h"
#include "walterUSDCommonUtils.h"
#include "walterUSDOpEngine.h"
#include <boost/algorithm/string.hpp>
PXR_NAMESPACE_USING_DIRECTIVE
void WalterUSDExtern::setIdentifier(const char* identifiers)
{
mPrimsCount = 0;
mFlattenVariants = "";
if ((identifiers != 0) && (identifiers[0] == '\0'))
return;
mIdentifiers.clear();
boost::split(mIdentifiers, identifiers, boost::is_any_of(":"));
}
void WalterUSDExtern::extractVariantsUsd()
{
OpEngine& engine = OpEngine::getInstance(mIdentifiers);
std::vector<std::string> variants =
WalterUSDCommonUtils::getVariantsUSD(
engine.getUsdStage(), "", true);
mFlattenVariants = "";
mPrimsCount = variants.size();
for (int i = 0; i < variants.size(); ++i)
{
mFlattenVariants += variants[i];
if (variants.size() > 1 && i < (variants.size() - 1))
mFlattenVariants += "|";
}
}
std::string& WalterUSDExtern::getVariantsUsd()
{
return mFlattenVariants;
}
int WalterUSDExtern::getPrimsCount()
{
return mPrimsCount;
}
std::string WalterUSDExtern::setVariantUsd(
const char* primPath,
const char* variantSetName,
const char* variantName)
{
std::string variants = primPath + std::string("{") + variantSetName +
std::string("=") + variantName + std::string("}");
return setVariantUsd(variants.c_str());
}
std::string WalterUSDExtern::setVariantUsd(const char* variants)
{
OpEngine& engine = OpEngine::getInstance(mIdentifiers);
WalterUSDCommonUtils::setVariantUSD(engine.getUsdStage(), variants);
return variants;
}
extern "C" {
WalterUSDExtern* WalterUSDExtern_new()
{
return new WalterUSDExtern();
}
void WalterUSDExtern_setIdentifier(
WalterUSDExtern* walterExtern,
const char* flattenIdentifiers)
{
walterExtern->setIdentifier(flattenIdentifiers);
}
void WalterUSDExtern_extractVariantsUsd(WalterUSDExtern* walterExtern)
{
walterExtern->extractVariantsUsd();
}
const char* WalterUSDExtern_getVariantsUsd(WalterUSDExtern* walterExtern)
{
return walterExtern->getVariantsUsd().c_str();
}
const char* WalterUSDExtern_setVariantUsd(
WalterUSDExtern* walterExtern,
const char* primPath,
const char* variantSetName,
const char* variantName)
{
return walterExtern->setVariantUsd(primPath, variantSetName, variantName)
.c_str();
}
void WalterUSDExtern_setVariantUsdFlat(
WalterUSDExtern* walterExtern,
const char* variants)
{
walterExtern->setVariantUsd(variants);
}
int WalterUSDExtern_getPrimsCount(WalterUSDExtern* walterExtern)
{
return walterExtern->getPrimsCount();
}
}
<|start_filename|>walter/usd/fileFormat/usdArnold/fileFormat.cpp<|end_filename|>
#include "fileFormat.h"
#include <pxr/base/tf/fileUtils.h>
#include <pxr/base/tf/pathUtils.h>
#include <pxr/base/tf/registryManager.h>
#include <pxr/usd/sdf/layer.h>
#include <pxr/usd/usd/usdaFileFormat.h>
#include <pxr/usd/usd/stage.h>
#include <string>
#include "arnoldTranslator.h"
PXR_NAMESPACE_OPEN_SCOPE
TF_DEFINE_PUBLIC_TOKENS(
UsdArnoldFileFormatTokens,
USDARNOLD_FILE_FORMAT_TOKENS);
TF_REGISTRY_FUNCTION(TfType)
{
SDF_DEFINE_FILE_FORMAT(UsdArnoldFileFormat, SdfFileFormat);
}
UsdArnoldFileFormat::UsdArnoldFileFormat() :
SdfFileFormat(
UsdArnoldFileFormatTokens->Id,
UsdArnoldFileFormatTokens->Version,
UsdArnoldFileFormatTokens->Target,
UsdArnoldFileFormatTokens->Id),
mUsda(SdfFileFormat::FindById(UsdUsdaFileFormatTokens->Id))
{}
UsdArnoldFileFormat::~UsdArnoldFileFormat()
{}
bool UsdArnoldFileFormat::CanRead(const std::string& filePath) const
{
auto extension = TfGetExtension(filePath);
if (extension.empty())
{
return false;
}
return extension == this->GetFormatId();
}
bool UsdArnoldFileFormat::Read(
const SdfLayerBasePtr& layerBase,
const std::string& filePath,
bool metadataOnly) const
{
SdfLayerHandle layer = TfDynamic_cast<SdfLayerHandle>(layerBase);
if (!TF_VERIFY(layer))
{
return false;
}
// Translate obj to usd schema.
SdfLayerRefPtr objAsUsd = ArnoldUSDTranslator::arnoldToUsdLayer(filePath);
if (!objAsUsd)
{
return false;
}
// Move generated content into final layer.
layer->TransferContent(objAsUsd);
return true;
}
bool UsdArnoldFileFormat::ReadFromString(
const SdfLayerBasePtr& layerBase,
const std::string& str) const
{
return false;
}
bool UsdArnoldFileFormat::WriteToString(
const SdfLayerBase* layerBase,
std::string* str,
const std::string& comment) const
{
// It's super important to have it like this. Otherwise usdcat doesn't work.
return mUsda->WriteToString(layerBase, str, comment);
}
bool UsdArnoldFileFormat::WriteToStream(
const SdfSpecHandle& spec,
std::ostream& out,
size_t indent) const
{
// It's super important to have it like this. Otherwise usdcat doesn't work.
return mUsda->WriteToStream(spec, out, indent);
}
bool UsdArnoldFileFormat::_IsStreamingLayer(const SdfLayerBase& layer) const
{
return true;
}
PXR_NAMESPACE_CLOSE_SCOPE
<|start_filename|>walter/maya/walterStandin/walterCmd.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef _walterCmd_h_
#define _walterCmd_h_
#include <maya/MPxCommand.h>
#include <maya/MArgDatabase.h>
#include <maya/MDagModifier.h>
#include <maya/MDagPath.h>
#include <maya/MSelectionList.h>
#include <maya/MTime.h>
#include <cassert>
#include <map>
#include <set>
#include <string>
#include <vector>
namespace WalterMaya
{
class Command : public MPxCommand
{
public:
static const char* LOCATOR_ATTR_PRIM_PATH;
static MSyntax cmdSyntax();
static void* creator();
Command();
virtual ~Command();
virtual MStatus doIt(const MArgList&);
virtual bool isUndoable() const;
virtual bool hasSyntax() const;
private:
MStatus clearSubSelection(const MString& objectName) const;
MStatus addSubSelection(
const MString& objectName,
const MString& subNodeName) const;
MStatus dirAlembic(const MString& objectName, const MString& subNodeName)
const;
MStatus propsAlembic(const MString& objectName, const MString& subNodeName)
const;
MStatus getVariants(
const MString& objectName,
const MString& subNodeName,
bool recursively) const;
MStatus setVariant(
const MString& objectName,
const MString& subNodeName,
const MString& variantName,
const MString& variantSetName) const;
// Write list of objects with given layer and target to the result of the
// command.
MStatus getAssignmentObjects(
const MString& objectName,
const std::string& layer,
const std::string& target) const;
// Write all the used layers to the result of the command.
MStatus getAssignmentLayers(const MString& objectName) const;
// Write the shader name of the specified object to the result of the
// command.
MStatus getAssignment(
const MString& objectName,
const MString& subNodeName,
const MString& layer,
const MString& type) const;
// Write all the used layers to the result of the command.
MStatus getAlembicAllGroups(const MString& objectName) const;
// Write all the expressions of the specified group to the result of the
// command.
MStatus getAlembicExpressions(
const MString& objectName,
const MString* groupName) const;
// Create a locator node(s) and pass their transforms to the walterStandin.
MStatus exposeTransform(
const MString& objectName,
const MString& subObjectName) const;
MStatus detachTransform(
const MString& objectName,
const MString& subObjectName) const;
// Clear the USD playback cache.
MStatus setCachedFramesDirty(const MString& objectName) const;
/**
* @brief Sets a text copy of a USD layer as a result of the script
* execution.
*
* @param objectName The name of the standin shape.
* @param layerName The name of the requested layer.
*
* @return The status.
*/
MStatus getLayerAsString(
const MString& objectName,
const MString& layerName) const;
/**
* @brief Calls onLoaded if it was never called.
*/
MStatus join(const MString& objectName) const;
/**
* @brief Checks that a regex represents a valid walter expression.
*
* @param objectName The name of the standin shape.
* @param expression The regex expression to validate.
*
* @return The status.
*/
MStatus expressionIsMatching(
const MString& objectName,
const MString& expression) const;
/**
* @brief Checks if the object is an USD pseudo-root.
*
* @param objectName The name of the standin shape.
* @param subObjectName The subnode name (path).
*
* @return The status.
*/
MStatus isPseudoRoot(
const MString& objectName,
const MString& subObjectName) const;
/**
* @brief Checks if the object is visible.
*
* @param objectName The name of the standin shape.
* @param subObjectName The subnode name (path).
*
* @return The status.
*/
MStatus isVisible(
const MString& objectName,
const MString& subObjectName) const;
/**
* @brief Toggles the visibility state (show, hidden) of the object.
*
* @param objectName The name of the standin shape.
* @param subObjectName The subnode name (path).
*
* @return The status.
*/
MStatus toggleVisibility(
const MString& objectName,
const MString& subObjectName) const;
/**
* @brief Sets the visibility state (show, hidden) of the object.
*
* @param objectName The name of the standin shape.
* @param subObjectName The subnode name (path).
*
* @return The status.
*/
MStatus setVisibility(
const MString& objectName,
const MString& subObjectName,
bool visibility) const;
/**
* @brief Hides all the scene execpted the object at subObjectName.
*
* @param objectName The name of the standin shape.
* @param subObjectName The subnode name (path).
*
* @return The status.
*/
MStatus hideAllExceptedThis(
const MString& objectName,
const MString& subObjectName) const;
/**
* @brief Gets the list of objects path matching the expression.
*
* @param objectName The name of the standin shape.
* @param expression A regex expression.
*
* @return The status.
*/
MStatus primPathsMatchingExpression(
const MString& objectName,
const MString& expression) const;
/**
* @brief Sets the prim purpose token (default, render, proxy, guide).
*
* @param obj Walter Standin node.
* @param subNodeName The subnode name (path).
* @param purpose The purpose token.
*
* @return The status.
*/
MStatus setPurpose(
const MString& objectName,
const MString& subObjectName,
const MString& purpose) const;
/**
* @brief Gets the prim purpose token.
*
* @param obj Walter Standin node.
* @param subNodeName The subnode name (path).
*
* @return The status.
*/
MStatus getPurpose(
const MString& objectName,
const MString& subObjectName) const;
/**
* @brief Sets the render engine purposes list, i.e the prim
* purposes that the engine can render.
*
* @param objectName The name of the standin shape.
* @param purposes List of purpose tokens separated by ":".
*
* @return The status.
*/
MStatus setRenderPurpose(
const MString& objectName,
const MString& purposeList) const;
/**
* @brief Gets the render engine purposes list, i.e the prim
* purposes that the engine can render.
*
* @param objectName The name of the standin shape.
*
* @return The status.
*/
MStatus getRenderPurpose(
const MString& objectName) const;
};
} // namespace WalterMaya
#endif
<|start_filename|>walter/arnold/procedural/index.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __INDEX_H__
#define __INDEX_H__
#include "plugin.h"
#include "PathUtil.h"
#include "schemas/expression.h"
#include <pxr/base/tf/hashmap.h>
#include <pxr/base/tf/hashset.h>
#include <pxr/usd/sdf/path.h>
#include <tbb/concurrent_hash_map.h>
#include <mutex>
#include <unordered_map>
PXR_NAMESPACE_USING_DIRECTIVE
// The object that indexes and keeps USD data for fast access. Generally,
// UsdStage keeps caches but not everything.
class RendererIndex
{
public:
/** @brief Tbb hash for SdfPath. */
struct TbbHash
{
static size_t hash(const SdfPath& x) { return SdfPath::Hash{}(x); }
static bool equal(const SdfPath& x, const SdfPath& y) { return x == y; }
};
typedef std::mutex Mutex;
typedef std::lock_guard<Mutex> ScopedLock;
typedef tbb::concurrent_hash_map<SdfPath, void*, TbbHash> RenderNodeMap;
// Insert the prim to the index.
void insertPrim(const SdfPath& parentPath, const SdfPath& objectPath);
// Return true if the object is in the index.
bool isProcessed(const SdfPath& path) const;
// The number of the children (number found is cached for next call).
int getNumNodes(const SdfPath& path);
// Insert a number of nodes for a given path (needed for any path that
// didn't go through the delegate.populate function such as point instancer)
void insertNumNodes(const SdfPath& path, int numNodes);
// Return true if children of this path are already in the index
bool isChildrenKnown(const SdfPath& path) const;
// Return true if a parent of this path is already in the index.
bool isParentKnown(const SdfPath& root, const SdfPath& path) const;
// Assignment are always checked from "/" and on the entire stage, so it
// doesn't need to be done twice. This function return true if it has
// already be done.
bool isAssignmentDone() const;
// Return true if `/` or `/materials` has already been registered as
// parent location in the hierarchy map.
bool hasGlobalMaterials() const;
// Get children.
const SdfPath* getPath(const SdfPath& parentPath, unsigned int i)const;
/**
* @brief Get the arnold render node data for specific path and provide a
* writer lock that permits exclusive access to the given enry of the map by
* a thread. Blocks access to the given enry of the map by other threads.
*
* @param path The given path.
* @param accessor The tbb accessor.
*
* @return True if new entry was inserted; false if key was already in the
* map.
*/
bool getRenderNodeData(
const SdfPath& path,
RenderNodeMap::accessor& accessor);
/**
* @brief Get the arnold render node data for specific path and provide a
* reader lock that permits shared access with other readers.
*
* @param path The given path.
* @param accessor The tbb accessor.
*
* @return True if the entry was found; false if key was not found.
*/
bool getRenderNodeData(
const SdfPath& path,
RenderNodeMap::const_accessor& accessor);
// Save the expression in the index.
void insertExpression(
const SdfPath& expressionPrimPath,
const SdfPath& rootPath,
const std::string& expression,
const WalterExpression::AssignmentLayers& layers);
// Save the material in the index.
void insertMaterial(
const SdfPath& material,
const std::string& target,
const SdfPath& shader);
/**
* @brief Save Walter Override's single attribute.
*
* @param iOverridePath Walter Override.
* @param iAttributeName Attribute name.
* @param iAttribute The attribute.
*/
void insertAttribute(
const SdfPath& iOverridePath,
const std::string& iAttributeName,
const RendererAttribute& iAttribute);
// Get the assigned shader.
SdfPath getShaderAssignment(
const std::string& objectName,
const std::string& layer,
const std::string& target)const;
/**
* @brief Returns the attributes of the Walter Override object.
*
* @param iOverridePath Walter Override object
*
* @return The pointer to the attributes.
*/
const NameToAttribute* getAttributes(SdfPath iOverridePath) const;
/**
* @brief Returns the attributes of the object. It merges the attributes
* (strong) with the attributes of all the parents (weak), so we have all
* the propagated attributes here. It uses a cache to store the object name
* as a key and all the attributes as a value. Thus, it doesn't resolve the
* attributes for all the parents each time. It resolves them for the
* current object and merges them with the parent.
*
* @param iVirtualObjectName The virtual name of the object.
* @param iLayer The current render layer.
*
* @return The pointer to the attributes.
*/
const NameToAttribute* getObjectAttribute(
const std::string& iVirtualObjectName,
const std::string& iLayer);
/**
* @brief Get the full path of the given prefix.
*
* @param iPrefix It's the arnold parameter "prefix" that is used to keep
* the name of the original procedural arnold node.
*
* @return The full path of the original procedural arnold node.
*/
const std::string& getPrefixPath(const std::string& iPrefix) const;
/**
* @brief Save the full path of the given prefix. It is used to generate
* a 'virtual path'. Such path does not exist in USD stage. Its purpose
* is to resolve expressions.
*
* @param iPrefix It's the arnold parameter "prefix" that is used to keep
* the name of the original procedural arnold node.
* @param iPath The full path of the original procedural arnold node.
*
* @return Returns true if item is new.
*/
bool setPrefixPath(const std::string& iPrefix, const std::string& iPath);
private:
typedef TfHashSet<SdfPath, SdfPath::Hash> ObjectSet;
typedef tbb::concurrent_hash_map<SdfPath, ObjectSet, TbbHash> ObjectMap;
// Building following structure:
// {"layer": {"target": {"object": "shader"}}}
// In Katana and Maya, we need to get the shader only if the shader is
// really assigned to the object and we don't consider inheritance. But here
// we need to consider inheritance, so we need layer and target at the first
// layer for fast and easy extracting {"object": "shader"} because we need
// to ignore if it's another target or shader is assigned in another render
// layer.
typedef std::map<WalterCommon::Expression, SdfPath> ObjectToShader;
typedef std::unordered_map<std::string, ObjectToShader> TargetToObjShader;
typedef std::unordered_map<std::string, TargetToObjShader> Assignments;
// Building following structure:
// {"material": {"target": "shader"}}
typedef TfHashMap<
SdfPath,
WalterExpression::AssignmentTargets,
SdfPath::Hash>
Materials;
// Building following structure:
// {"walterOverride": {"attribute name": "renderer attribute"}}
typedef TfHashMap<SdfPath, NameToAttribute, SdfPath::Hash> Attributes;
typedef tbb::concurrent_hash_map<std::string, NameToAttribute> ObjectAttrs;
typedef std::map<SdfPath, int> NumNodesMap;
// All the objects that are in the index. They are considered as processed.
// TODO: If using tbb:concurrent_unordered_set, we can ge rid of
// mCachedObjectSetLock
ObjectSet mCachedObjectSet;
// Key: parent, value: the list of the objects.
ObjectMap mHierarchyMap;
// Name to arnold render nodes map for fast access.
RenderNodeMap mRenderNodeMap;
// All the assignments of the cache.
Assignments mAssignments;
// Materials
Materials mMaterials;
// Walter Overrides to Attributes
Attributes mAttributes;
// Object to Attributes. List of attributes for each object in the scene. We
// need it to fast query attributes of the parent object.
ObjectAttrs mObjectAttributes;
NumNodesMap mNumNodes;
// The storage to keep the full paths of the given prefixes. Prefixe is the
// arnold parameter of the walter procedural that is used to keep the name
// of the original procedural arnold node. We use this object to track the
// instances.
typedef tbb::concurrent_hash_map<std::string, std::string> StringMap;
StringMap mPrefixPathsForProcedurals;
// TODO: We probably need to use tbb::spin_mutex here. We need to test it.
typedef Mutex FastMutex;
typedef ScopedLock FastMutexLock;
mutable FastMutex mCachedObjectSetLock;
};
#endif
<|start_filename|>walter/common/abcExporterUtils.h<|end_filename|>
/*Abc Shader Exporter
Copyright (c) 2014, <NAME>, All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.*/
#ifndef _Abc_Exporter_Utils_h_
#define _Abc_Exporter_Utils_h_
#include "ai.h"
#include <Alembic/Abc/All.h>
#include <Alembic/AbcCoreOgawa/All.h>
#include <Alembic/AbcMaterial/OMaterial.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/lexical_cast.hpp>
#include <set>
//#include <pystring.h>
#include <sstream>
namespace Abc = Alembic::Abc;
namespace Mat = Alembic::AbcMaterial;
typedef std::set<AtNode*> AtNodeSet;
const std::vector<std::string> GetComponentNames(int arnoldParamType);
void getAllArnoldNodes(AtNode* node, AtNodeSet* nodes);
void processArrayValues(AtNode* sit, const char *paramName, AtArray* paramArray, int outputType, Mat::OMaterial matObj, std::string nodeName);
void processArrayParam(AtNode* sit, const char *paramName, AtArray* paramArray, int index, int outputType, Mat::OMaterial matObj, std::string nodeName, std::string containerName);
void processLinkedParam(AtNode* sit, int inputType, int outputType, Mat::OMaterial matObj, std::string nodeName, std::string paramName, std::string containerName);
void exportLink(AtNode* sit, Mat::OMaterial matObj, std::string nodeName, std::string paramName, std::string containerName);
void exportParameter(AtNode* sit, Mat::OMaterial matObj, int type, std::string nodeName, std::string paramName);
bool isDefaultValue(AtNode* node, const char* paramName);
#endif
<|start_filename|>walter/viewer/View.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "View.h"
#include "CameraControler.h"
#include "FreeCamera.h"
#include "Scene.h"
#include <pxr/base/gf/gamma.h>
#include <cstdio>
PXR_NAMESPACE_USING_DIRECTIVE
static walter_viewer::ViewPtr sView = nullptr;
static void errorCallback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
static void keyCallback(
GLFWwindow* window,
int key,
int scancode,
int action,
int mods)
{
if (!sView)
return;
if (key == GLFW_KEY_KP_ADD && action == GLFW_PRESS)
{
sView->scene()->updateSubdiv(0.1f);
}
if (key == GLFW_KEY_KP_SUBTRACT && action == GLFW_PRESS)
{
sView->scene()->updateSubdiv(-0.1f);
}
if (key == GLFW_KEY_W && action == GLFW_PRESS)
{
if (sView->drawMode == UsdImagingGLEngine::DRAW_SHADED_SMOOTH)
{
sView->drawMode = UsdImagingGLEngine::DRAW_WIREFRAME;
}
else
{
sView->drawMode = UsdImagingGLEngine::DRAW_SHADED_SMOOTH;
}
sView->scene()->setDrawMode(sView->drawMode);
}
if (key == GLFW_KEY_Q && action == GLFW_PRESS)
{
sView->mode = walter_viewer::InteractionMode::selection;
}
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
sView->mode = walter_viewer::InteractionMode::camera;
}
if (key == GLFW_KEY_E && action == GLFW_PRESS)
{
sView->scene()->setRenderer("Embree");
}
else if (key == GLFW_KEY_S && action == GLFW_PRESS)
{
sView->scene()->setRenderer("Stream");
}
if (key == GLFW_KEY_F && action == GLFW_PRESS)
{
sView->scene()->frameSelection();
sView->scene()->updateCamera(sView->height);
}
if (key == GLFW_KEY_R && action == GLFW_PRESS)
{
sView->scene()->resetCamera();
}
}
static void mouseButtonCallback(
GLFWwindow* window,
int button,
int action,
int mods)
{
if (!sView)
return;
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
{
if (sView->pressState == walter_viewer::ButtonPressState::released)
{
sView->pressState = walter_viewer::ButtonPressState::click;
sView->mouseClickCallback(walter_viewer::ButtonPressed::left);
}
}
if (button == GLFW_MOUSE_BUTTON_MIDDLE && action == GLFW_PRESS)
{
if (sView->pressState == walter_viewer::ButtonPressState::released)
{
sView->pressState = walter_viewer::ButtonPressState::click;
sView->mouseClickCallback(walter_viewer::ButtonPressed::middle);
}
}
else if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS)
{
if (sView->pressState == walter_viewer::ButtonPressState::released)
{
sView->pressState = walter_viewer::ButtonPressState::click;
sView->mouseClickCallback(walter_viewer::ButtonPressed::right);
}
}
else if (action == GLFW_RELEASE)
{
sView->pressState = walter_viewer::ButtonPressState::released;
}
}
void cursorPosCallback(GLFWwindow*, double x, double y)
{
if (sView)
{
sView->mouseMoveCallback(int(x), int(y));
}
}
namespace walter_viewer
{
View::View()
{
if (glfwInit())
{
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwSetErrorCallback(errorCallback);
mWindow = glfwCreateWindow(640, 480, "Walter Viewer", nullptr, nullptr);
if (!mWindow)
{
glfwTerminate();
}
else
{
glfwMakeContextCurrent(mWindow);
glfwSetWindowPos(mWindow, 200, 200);
glewExperimental = GL_TRUE;
GlfGlewInit();
mIsValid = true;
}
}
}
View::~View()
{
glfwDestroyWindow(mWindow);
glfwTerminate();
}
bool View::show()
{
if (mIsValid)
{
glfwShowWindow(mWindow);
glfwSetKeyCallback(mWindow, keyCallback);
glfwSetMouseButtonCallback(mWindow, mouseButtonCallback);
glfwSetCursorPosCallback(mWindow, cursorPosCallback);
}
return mIsValid;
}
void View::setScene(ScenePtr scene)
{
mScene = scene;
mScene->frameSelection();
}
void View::refresh()
{
while (!glfwWindowShouldClose(mWindow))
{
// Check if any events have been activiated (key pressed, mouse moved
// etc.) and call corresponding response functions.
glfwPollEvents();
glfwGetFramebufferSize(mWindow, &width, &height);
glViewport(0, 0, width, height);
{
GfVec4d clearColor(0.333, 0.333, 0.333, 1.0);
SRGBContext ctx(clearColor);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (this->pressState == ButtonPressState::drag || mFirstRefresh)
{
mScene->updateCamera(height);
mFirstRefresh = false;
}
mScene->draw(width, height);
// When rendering after a call to UsdImagingGL::TestIntersection,
// a lot of errors are printing. We clear them.
// TODO: investigate why it prints so many errors.
while (glGetError() != GL_NO_ERROR)
{
}
// Swap the screen buffers.
glfwSwapBuffers(mWindow);
}
}
}
void View::mouseClickCallback(ButtonPressed button)
{
this->button = button;
if (this->mode == InteractionMode::selection)
{
double xpos, ypos;
glfwGetCursorPos(mWindow, &xpos, &ypos);
mScene->select(xpos, ypos, width, height);
}
}
void View::mouseMoveCallback(int x, int y)
{
if (this->mode == InteractionMode::camera)
{
if (this->pressState == ButtonPressState::released)
{
mScene->camera()->controler().setPanning(false);
mScene->camera()->controler().setZoom(0.f);
mScene->camera()->controler().setPan(0.f, 0.f);
return;
}
if (this->pressState == ButtonPressState::click)
{
mScene->camera()->controler().mousePosLastX = x;
mScene->camera()->controler().mousePosLastY = y;
this->pressState = ButtonPressState::drag;
}
int dx = x - mScene->camera()->controler().mousePosLastX;
int dy = y - mScene->camera()->controler().mousePosLastY;
if (dx == 0 && dy == 0)
{
return;
}
mScene->camera()->controler().mousePosLastX = x;
mScene->camera()->controler().mousePosLastY = y;
switch (this->button)
{
case ButtonPressed::undefined:
break;
case ButtonPressed::left:
mScene->camera()->controler().updateRotation(dx, dy);
break;
case ButtonPressed::middle:
mScene->camera()->controler().setPanning(true);
mScene->camera()->controler().setZoom(0.f);
mScene->camera()->controler().setPan(dx, dy);
break;
case ButtonPressed::right:
mScene->camera()->controler().updateZoom(dx, dy);
break;
}
}
}
View::SRGBContext::SRGBContext(GfVec4d clearColor)
{
glEnable(GL_FRAMEBUFFER_SRGB_EXT);
clearColor = GfConvertDisplayToLinear(clearColor);
glClearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
}
View::SRGBContext::~SRGBContext()
{
glDisable(GL_FRAMEBUFFER_SRGB_EXT);
}
ViewPtr getView()
{
if (!sView)
{
sView = new View;
}
return sView;
}
} // end namespace walter_viewer
<|start_filename|>walter/usd/fileFormat/usdArnold/fileFormat.h<|end_filename|>
#ifndef USDARNOLD_FILE_FORMAT_H
#define USDARNOLD_FILE_FORMAT_H
#include <pxr/base/tf/staticTokens.h>
#include <pxr/pxr.h>
#include <pxr/usd/sdf/fileFormat.h>
#include <iosfwd>
#include <string>
PXR_NAMESPACE_OPEN_SCOPE
#define USDARNOLD_FILE_FORMAT_TOKENS \
((Id, "ass"))((Version, "1.0"))((Target, "usd"))
TF_DECLARE_PUBLIC_TOKENS(
UsdArnoldFileFormatTokens,
USDARNOLD_FILE_FORMAT_TOKENS);
TF_DECLARE_WEAK_AND_REF_PTRS(UsdArnoldFileFormat);
TF_DECLARE_WEAK_AND_REF_PTRS(SdfLayerBase);
/// \class UsdArnoldFileFormat
class UsdArnoldFileFormat : public SdfFileFormat
{
public:
virtual bool CanRead(const std::string& file) const override;
virtual bool Read(
const SdfLayerBasePtr& layerBase,
const std::string& filePath,
bool metadataOnly) const override;
virtual bool ReadFromString(
const SdfLayerBasePtr& layerBase,
const std::string& str) const override;
// We override Write methods so SdfLayer::ExportToString() etc, work. We
// don't support writing general Usd data back to ass files. So
// SdfLayer::Save() doesn't work, for example.
virtual bool WriteToString(
const SdfLayerBase* layerBase,
std::string* str,
const std::string& comment = std::string()) const override;
virtual bool WriteToStream(
const SdfSpecHandle& spec,
std::ostream& out,
size_t indent) const override;
protected:
SDF_FILE_FORMAT_FACTORY_ACCESS;
virtual ~UsdArnoldFileFormat();
UsdArnoldFileFormat();
private:
virtual bool _IsStreamingLayer(const SdfLayerBase& layer) const;
SdfFileFormatConstPtr mUsda;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif // USDARNOLD_FILE_FORMAT_H
<|start_filename|>walter/cmake/FindGoogleTest.cmake<|end_filename|>
# Example usage:
# find_package(GoogleTest)
# if(GoogleTest_FOUND)
# message("GTest found: ${GoogleTest_LIBRARIES}")
# endif()
#
#=============================================================================
set(GoogleTest_LIBRARIES
${GoogleTest_DIR}/lib/libgtest.a
${GoogleTest_DIR}/lib/libgtest_main.a
)
set(GoogleTest_INCLUDE_DIR ${GoogleTest_DIR}/include)
include( FindPackageHandleStandardArgs )
find_package_handle_standard_args( "GoogleTest" DEFAULT_MSG
GoogleTest_LIBRARIES
GoogleTest_INCLUDE_DIR
)
if(NOT GoogleTest_FOUND)
message(FATAL_ERROR "Try using -D GoogleTest_DIR=/path/to/GTest")
endif()
<|start_filename|>vfx_platform_builder/system/Makefile<|end_filename|>
# Save the current directory
THIS_DIR := $(shell pwd)
# Versions
BISON_VERSION := 3.0.4
FLEX_VERSION := 2.6.4
ISPC_VERSION := v1.9.1
LLVM_VERS := 3.9.0
# Version files that should indicate that the build is successfull
BISON_STAMP := $(PREFIX_ROOT)/built_bison
FLEX_STAMP := $(PREFIX_ROOT)/built_flex
ISPC_STAMP := $(PREFIX_ROOT)/built_ispc
LLVM_STAMP := $(PREFIX_ROOT)/built_llvm
BISON_SOURCE := https://ftp.gnu.org/gnu/bison/bison-$(BISON_VERSION).tar.gz
CLANGTOOLSEXTRA_SOURCE := http://releases.llvm.org/$(LLVM_VERS)/clang-tools-extra-$(LLVM_VERS).src.tar.xz
CLANG_SOURCE := http://releases.llvm.org/$(LLVM_VERS)/cfe-$(LLVM_VERS).src.tar.xz
COMPILERRT_SOURCE := http://releases.llvm.org/$(LLVM_VERS)/compiler-rt-$(LLVM_VERS).src.tar.xz
FLEX_SOURCE := https://github.com/westes/flex/releases/download/v$(FLEX_VERSION)/flex-$(FLEX_VERSION).tar.gz
ISPC_SOURCE := <EMAIL>@github.com:ispc/ispc.git
LLVM_SOURCE := http://releases.llvm.org/$(LLVM_VERS)/llvm-$(LLVM_VERS).src.tar.xz
BISON_FILE := $(SOURCES_ROOT)/$(notdir $(BISON_SOURCE))
CLANGTOOLSEXTRA_FILE := $(SOURCES_ROOT)/$(notdir $(CLANGTOOLSEXTRA_SOURCE))
CLANG_FILE := $(SOURCES_ROOT)/$(notdir $(CLANG_SOURCE))
COMPILERRT_FILE := $(SOURCES_ROOT)/$(notdir $(COMPILERRT_SOURCE))
FLEX_FILE := $(SOURCES_ROOT)/$(notdir $(FLEX_SOURCE))
ISPC_FILE := $(SOURCES_ROOT)/$(notdir $(ISPC_SOURCE))
LLVM_FILE := $(SOURCES_ROOT)/$(notdir $(LLVM_SOURCE))
# Defaults
CMAKE := cmake
CMAKE_BUILD_TYPE := Release
MAKE := $(shell which make)
PREFIX_ROOT=/tmp/lib
PYTHON_BIN := python
SOURCES_ROOT=/tmp/src
CLANG := $(PREFIX_ROOT)/llvm/bin/clang
CLANGXX := $(CLANG)++
ISPC := $(PREFIX_ROOT)/ispc/bin/ispc
ifneq ("$(wildcard $(CLANG))","")
LLVM_STAMP:=
endif
ifneq ("$(wildcard $(ISPC))","")
ISPC_STAMP:=
endif
# Number of processors
ifeq "$(OS)" "Darwin"
JOB_COUNT := $(shell sysctl -n machdep.cpu.thread_count)
endif
ifeq "$(OS)" "linux"
JOB_COUNT := $(shell cat /sys/devices/system/cpu/cpu*/topology/thread_siblings | wc -l)
endif
$(BISON_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(BISON_FILE)... && \
curl --tlsv1.2 -s -o $@ -L $(BISON_SOURCE)
$(CLANGTOOLSEXTRA_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(CLANGTOOLSEXTRA_FILE)... && \
curl -s -o $@ -L $(CLANGTOOLSEXTRA_SOURCE)
$(CLANG_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(CLANG_FILE)... && \
curl -s -o $@ -L $(CLANG_SOURCE)
$(COMPILERRT_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(COMPILERRT_FILE)... && \
curl -s -o $@ -L $(COMPILERRT_SOURCE)
$(FLEX_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(FLEX_FILE)... && \
curl --tlsv1.2 -s -o $@ -L $(FLEX_SOURCE)
$(ISPC_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(ISPC_FILE)... && \
git clone -q --bare $(ISPC_SOURCE) $(ISPC_FILE)
$(LLVM_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(LLVM_FILE)... && \
curl -s -o $@ -L $(LLVM_SOURCE)
all: clang ispc
bison: $(BISON_STAMP)
clang: llvm
flex: $(FLEX_STAMP)
ispc: $(ISPC_STAMP)
llvm: $(LLVM_STAMP)
$(BISON_STAMP) : $(LLVM_STAMP) $(BISON_FILE)
@echo Building Bison $(BISON_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(basename $(BISON_FILE)))) && \
tar xf $(SOURCES_ROOT)/$(notdir $(BISON_FILE)) && \
cd $(notdir $(basename $(basename $(BISON_FILE)))) && \
CC=$(CLANG) \
CXX=$(CLANGXX) \
./configure \
--prefix=$(PREFIX_ROOT)/bison && \
$(MAKE) \
install -j$(JOB_COUNT) && \
cd .. && \
rm -rf $(notdir $(basename $(basename $(BISON_FILE)))) && \
cd $(THIS_DIR) && \
echo $(BISON_VERSION) > $@
$(FLEX_STAMP) : $(BISON_STAMP) $(LLVM_STAMP) $(FLEX_FILE)
@echo Building Flex $(FLEX_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(basename $(FLEX_FILE)))) && \
tar xf $(SOURCES_ROOT)/$(notdir $(FLEX_FILE)) && \
cd $(notdir $(basename $(basename $(FLEX_FILE)))) && \
CC=$(CLANG) \
CXX=$(CLANGXX) \
./configure \
--prefix=$(PREFIX_ROOT)/flex && \
PATH=$(PREFIX_ROOT)/llvm/bin:$(PREFIX_ROOT)/bison/bin:$(PATH) \
$(MAKE) \
install -j$(JOB_COUNT) && \
cd .. && \
rm -rf $(notdir $(basename $(basename $(FLEX_FILE)))) && \
cd $(THIS_DIR) && \
echo $(FLEX_VERSION) > $@
$(LLVM_STAMP) : $(LLVM_FILE) $(CLANG_FILE) $(COMPILERRT_FILE) $(CLANGTOOLSEXTRA_FILE)
@echo Building llvm and clang $(LLVM_VERS) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(basename $(LLVM_FILE)))) && \
tar xf $(SOURCES_ROOT)/$(notdir $(LLVM_FILE)) && \
cd $(notdir $(basename $(basename $(LLVM_FILE)))) && \
cd tools && \
tar xf $(SOURCES_ROOT)/$(notdir $(CLANG_FILE)) && \
mv $(notdir $(basename $(basename $(CLANG_FILE)))) clang && \
cd clang/tools && \
tar xf $(SOURCES_ROOT)/$(notdir $(CLANGTOOLSEXTRA_FILE)) && \
mv $(notdir $(basename $(basename $(CLANGTOOLSEXTRA_FILE)))) extra && \
cd ../../../projects && \
tar xf $(SOURCES_ROOT)/$(notdir $(COMPILERRT_FILE)) && \
mv $(notdir $(basename $(basename $(COMPILERRT_FILE)))) compiler-rt && \
cd .. && \
mkdir build && cd build && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DCMAKE_INSTALL_PREFIX:STRING=$(PREFIX_ROOT)/llvm \
-DLLVM_ENABLE_RTTI:BOOL=1 \
-DLLVM_ENABLE_TERMINFO:BOOL=0 \
-DLLVM_ENABLE_WARNINGS:BOOL=0 \
-DLLVM_ENABLE_ZLIB:BOOL=0 \
-DLLVM_REQUIRES_EH:BOOL=1 \
-DLLVM_REQUIRES_RTTI:BOOL=1 \
-DLLVM_TARGETS_TO_BUILD:STRING=X86 \
-DLLVM_USE_CRT_DEBUG:STRING=MTd \
-DLLVM_USE_CRT_RELEASE:STRING=MT \
-DPYTHON_EXECUTABLE:STRING=$(PYTHON_BIN) \
.. && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) && \
cd ../.. && \
rm -rf $(notdir $(basename $(basename $(LLVM_FILE)))) && \
cd $(THIS_DIR) && \
echo $(LLVM_VERS) > $@
# Intel(r) SPMD Program Compiler
$(ISPC_STAMP) : $(BISON_STAMP) $(FLEX_STAMP) $(LLVM_STAMP) $(ISPC_FILE)/HEAD
@echo Building ISPC $(ISPC_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(ISPC_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(ISPC_FILE)) $(notdir $(basename $(ISPC_FILE))) && \
cd $(notdir $(basename $(ISPC_FILE))) && \
git checkout -q $(ISPC_VERSION) && \
( printf '/ISPC_LLVM_3_9/a\n#define ISPC_LLVM_4_0 40000\n.\nw\nq' | ed -s ispc_version.h ) && \
( printf '/LATEST_SUPPORTED_LLVM/s/3_9/4_0/\nw\nq' | ed -s ispc_version.h ) && \
PATH=$(dir $(CLANG)):$(PREFIX_ROOT)/bison/bin:$(PREFIX_ROOT)/flex/bin:$(PATH) \
$(MAKE) \
CXX=$(CLANGXX) \
LLVM_HOME=$(dir $(dir $(CLANG))) \
-j$(JOB_COUNT) && \
mkdir -p $(PREFIX_ROOT)/ispc/bin && \
mv ./ispc $(PREFIX_ROOT)/ispc/bin && \
cd .. && \
rm -rf $(notdir $(basename $(ISPC_FILE))) && \
cd $(THIS_DIR) && \
echo $(ISPC_VERSION) > $@
<|start_filename|>walter/maya/walterStandin/rdoProfiling.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef _RDOPROFILING_H_
#define _RDOPROFILING_H_
#include <chrono>
#include <map>
#include <stack>
#include <string>
// Profiling output. Just add RDOPROFILE to the begin of a function to output
// the execution time.
#ifdef RDO_ENABLE_PROFILE
#define RDOPROFILE(message) \
RdoProfiling __prf(__FUNCTION__, __FILE__, __LINE__, message)
#else
#define RDOPROFILE(message)
#endif
// TODO: It only works in a single thread.
class RdoProfiling
{
public:
RdoProfiling(
const char* i_function,
const char* i_file,
int i_line,
const char* i_message);
~RdoProfiling();
private:
static std::map<size_t, std::stack<RdoProfiling*>> s_stacks;
std::chrono::high_resolution_clock::time_point m_start;
unsigned int m_others;
std::string m_function;
std::string m_file;
std::string m_message;
int m_line;
// Current thread id.
size_t mThreadID;
};
#endif
<|start_filename|>walter/common/PathUtil.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERCOMMONPATHUTIL_H_
#define __WALTERCOMMONPATHUTIL_H_
#include <boost/noncopyable.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <map>
namespace WalterCommon
{
/**
* @brief Checks if regex matches string.
*
* @param str Regex
* @param pat String
*
* @return True if matches.
*/
bool matchPattern(const std::string& str, const std::string& pat);
/**
* @brief Creates regex object. It's `void*` to be able to use this function
* without including boost::regex stuff. It's the responsibility of the
* programmer to remove this object with `clearRegex`. Right now the functions
* `createRegex` and `searchRegex` are wraps on `boost::regex` and
* `boost::regex_match`.
*
* @param exp Regex string.
*
* @return A pointer to the regex object.
*/
void* createRegex(const std::string& exp);
/**
* @brief Checks if regex matches string. Right now the functions `createRegex`
* and `searchRegex` are wraps on `boost::regex` and `boost::regex_match`.
*
* @param regex The poiter created with `matchPattern`.
* @param str The string to check.
*
* @return True if matches.
*/
bool searchRegex(void* regex, const std::string& str);
/**
* @brief Mangles the string to replace '/' by '\'. It's because Alembic doesn't
* allow to use '/' in an attribute name so we need to replace it by '\' and
* replace it back when we read it (cf. demangleString).
*
* @param str The string to mangle
*
* @return The mangled string.
*/
std::string mangleString(const std::string& str);
/**
* @brief Demangles the string to replace '\' by '/'.
*
* @param str The string to demangle
*
* @return The demangled string.
*/
std::string demangleString(const std::string& str);
/**
* @brief Replace special regex symbols using a backslash (e.g '\d')
* so the regex expression is not broken when converted back and
* forth between different 'modules' (Walter, UDS, Abc, ...) that
* converts slashs to backslashs and conversely.
*
* @param expression The regex expression to convert
*
* @return The converted expression.
*/
std::string convertRegex(const std::string& expression);
/**
* @brief Removes regex created with `matchPattern`.
*
* @param regex The poiter created with `matchPattern`.
*/
void clearRegex(void* regex);
class Expression : private boost::noncopyable
{
public:
explicit Expression(const std::string& iExpression);
~Expression();
/**
* @brief Checks if this is a full path and if it's a parent of the provided
* path.
*
* @param iFullName The full name of an object to check.
* @param oIsItself It's set to true if iFullName matches to this.
*
* @return True of it's a parent or it it's the same object.
*/
bool isParentOf(const std::string& iFullName, bool* oIsItself) const;
/**
* @brief Checks if this is the regex and if it matches the provided path.
*
* @param iFullName The full name of an object to check.
*
* @return True if matches.
*/
bool matchesPath(const std::string& iFullName) const;
/**
* @brief Checks if this is the regex and if it matches another one.
*
* @param iExpression The another expression to match.
*
* @return True if matches.
*/
bool matchesPath(const Expression& iExpression) const;
/**
* @brief Return the expression or object name.
*
* @return The reference to the std::string object.
*/
const std::string& getExpression() const { return mExpression; }
/**
* @brief Checks if this object is considered as regex.
*
* @return True if this object contains symbols of regex.
*/
const bool isRegex() const { return mRegex; }
// std::map routines that allow using this object as a key.
bool operator<(const Expression& rhs) const
{
return mExpression < rhs.mExpression;
}
bool operator==(const Expression& rhs) const
{
return mExpression == rhs.mExpression;
}
private:
// The expression or full name.
std::string mExpression;
// The regex cache.
void* mRegex;
// The min size the path should have to be comparable. We use it as a filter
// to prevent comparison of the objects that will not match.
size_t mMinSize;
// The string with no regex characters. We use it to detect the similar
// expressions.
std::string mTextWithoutRegex;
};
/**
* @brief Check the map with all the assignments and return the assignment that
* closely fits the specified object name. It should work with following
* priority:
* 1) Exact name
* 2) Exact expression match
* 3) Closest parent
*
* @param iFullName Full object name
* @param iExpressions All the assignments in sorted map.
*
* @return The pointer to the second element of the map.
*/
template <class T>
T const* resolveAssignment(
const std::string& iFullName,
const std::map<Expression, T>& iExpressions)
{
T const* shader = nullptr;
// Since AssignmentLayers is std::map, it's already sorted.
// boost::adaptors::reverse wraps an existing range to provide a new range
// whose iterators behave as if they were wrapped in reverse_iterator. We
// need it reversed to be sure we meet the parent close to the object before
// the parent close to the root.
for (const auto& object : boost::adaptors::reverse(iExpressions))
{
const Expression& expr = object.first;
bool isItself = false;
if (!shader && expr.isParentOf(iFullName, &isItself))
{
// We don't return if we found a parent because we can find
// expression that matches this object. The expression has higher
// priority than the parent object.
shader = &object.second;
if (isItself)
{
// It's the exact match.
return shader;
}
}
if (expr.matchesPath(iFullName))
{
// It's the expression that matches the name. Return.
return &object.second;
}
}
return shader;
}
}
#endif
<|start_filename|>walter/katana/WalterIn/walterUSDOpUtils.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERUSDOPUTILS_H_
#define __WALTERUSDOPUTILS_H_
#include <pxr/base/tf/debug.h>
#include <pxr/usd/sdf/path.h>
#include <sys/syscall.h>
#include <sys/types.h>
#ifndef NDEBUG
#define W_DEBUG(MSG, ...) \
TF_DEBUG(WALTER_KATANA) \
.Msg( \
"[WALTER d 0x%lx %s]: " MSG "\n", \
syscall(SYS_gettid), \
__FUNCTION__, \
__VA_ARGS__)
#else
#define W_DEBUG(MSG, ...)
#endif
PXR_NAMESPACE_OPEN_SCOPE
TF_DEBUG_CODES(WALTER_KATANA);
PXR_NAMESPACE_CLOSE_SCOPE
PXR_NAMESPACE_USING_DIRECTIVE
class OpEngine;
namespace OpUtils
{
/** @brief Represents the time and all the samples that it has. We should
* use this object everywhere it possible. */
class Time : private boost::noncopyable
{
public:
typedef double TimeType;
typedef std::vector<TimeType> TimeRange;
Time(
TimeType iCurrent,
TimeType iOpen,
TimeType iClose,
size_t iSamples = 1);
TimeType current() const { return mCurrent; }
size_t size() const { return mSamples.size(); }
const TimeRange& samples() const { return mSamples; }
private:
TimeRange mSamples;
TimeType mCurrent;
};
typedef std::shared_ptr<Time> TimePtr;
/** @brief The class that should be created for each single Katana node and
* contains the information for this node that it's not possible to put into
* index. */
class PrivateData
{
public:
PrivateData(
OpEngine& iEngine,
const std::string iKatanaRoot,
const SdfPath& iCurrentPath,
TimePtr iTime);
OpEngine& engine() const { return *mEngine; }
const SdfPath& path() const { return mCurrentPath; }
const std::string& root() const { return mKatanaRoot; }
TimePtr time() const { return mTime; }
/**
* @brief Delete this object.
*
* @param data It should always be PrivateData.
*/
static void kill(void* data) { delete (PrivateData*)data; }
private:
OpEngine* mEngine;
// The Katana path to the WalterIn object. We can't put it to engine/index
// because it's possible to have several nodes with the same engine.
std::string mKatanaRoot;
SdfPath mCurrentPath;
TimePtr mTime;
};
/**
* @brief The attribute name in USD and in Katana are different. It converts USD
* name to full Katana name. "disp_height" -> "arnoldStatements.disp_height".
*
* @param iName "disp_height"
*
* @return "arnoldStatements.disp_height"
*/
std::string getClientAttributeName(const std::string& iName);
}
#endif
<|start_filename|>walter/maya/AbcExport/walterAbcExportExtensions.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterAbcExportExtensions.h"
#include "AbcWriteJob.h"
#define MNoVersionString
#include <Alembic/AbcMaterial/OMaterial.h>
#include <maya/MFnPlugin.h>
#include <maya/MGlobal.h>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/json_parser.hpp>
/**
* @brief Returns true if the string presents in the given array.
*
* @param iArray The given array.
* @param iMember The string to check.
*
* @return True/false.
*/
inline bool presentsIn(const MStringArray& iArray, const MString& iMember)
{
unsigned int len = iArray.length();
for (unsigned int i = 0; i < len; i++)
{
if (iArray[i] == iMember)
{
return true;
}
}
return false;
}
/**
* @brief Save the given parameter to Alembic.
*
* @param iName The name of the parameter.
* @param iParam The parameter as a Json object.
* @param oProperty The parent Alembic property with all the parameters.
*
* @return Return the link name if the parameter is linked.
*/
std::string saveParam(
const std::string& iName,
const boost::property_tree::ptree iParam,
Alembic::Abc::OCompoundProperty& oProperty)
{
const auto link = iParam.get_optional<std::string>("link");
if (link)
{
return link.get();
}
const auto typeOpt = iParam.get_optional<std::string>("type");
const auto valueOpt = iParam.get_child_optional("value");
if (!typeOpt || !valueOpt)
{
// Can't do anything without type.
return {};
}
const std::string& type = typeOpt.get();
const auto& value = valueOpt.get();
if (type == "STRING")
{
Alembic::Abc::OStringProperty prop(oProperty, iName);
prop.set(value.get_value<std::string>());
}
else if (type == "BOOL")
{
Alembic::Abc::OBoolProperty prop(oProperty, iName);
prop.set(value.get_value<bool>());
}
else if (type == "RGB")
{
Alembic::Abc::OC3fProperty color(oProperty, iName);
Alembic::Abc::C3f colorVal;
// Get color component by component.
size_t counter = 0;
for (const auto& c : value)
{
colorVal[counter++] = c.second.get_value<float>();
}
color.set(colorVal);
}
else if (type == "VECTOR")
{
Alembic::Abc::OV3fProperty vector(oProperty, iName);
Alembic::Abc::V3f vectorVal;
// Get color component by component.
size_t counter = 0;
for (const auto& c : value)
{
vectorVal[counter++] = c.second.get_value<float>();
}
vector.set(vectorVal);
}
else if (type == "FLOAT")
{
Alembic::Abc::OFloatProperty prop(oProperty, iName);
prop.set(value.get_value<float>());
}
else if (type == "INT")
{
Alembic::Abc::OInt32Property prop(oProperty, iName);
prop.set(value.get_value<int>());
}
else if (type == "BYTE")
{
Alembic::Abc::OUcharProperty prop(oProperty, iName);
prop.set(value.get_value<int>());
}
return {};
}
ArnoldLightExporter::ArnoldLightExporter()
{
MObject plugin = MFnPlugin::findPlugin("walterMtoaConnection");
mValid = !plugin.isNull();
}
void ArnoldLightExporter::eval(bool isFirst)
{
if (!isFirst || mLightList.empty())
{
return;
}
if (!mValid)
{
MGlobal::displayError(
"Can't save Arnold properties because plugin walterMtoaConnection "
"is not loaded.");
return;
}
// Generate a command to ask walterMtoaConnection to convert the lights.
// Since walterConvertToArnold opens Arnold session, we need to call it only
// once with the list of all the lights.
MString command = "walterConvertToArnold";
for (MayaLightWriterPtr light : mLightList)
{
command += " " + light->mDagPath.partialPathName();
}
// The result is Json string with all the lights.
MString result = MGlobal::executeCommandStringResult(command);
// Parse it.
boost::property_tree::ptree tree;
{
std::istringstream resultStream(result.asChar());
boost::property_tree::read_json(resultStream, tree);
}
// Check each light separately.
for (MayaLightWriterPtr light : mLightList)
{
std::string lightName = light->mDagPath.partialPathName().asChar();
const auto& nodes = tree.get_child(lightName);
if (nodes.empty())
{
continue;
}
// Save the light information to ".material" schema.
Alembic::AbcMaterial::OMaterialSchema material(
light->mSchema.getPtr(), ".material");
// Set the root node.
static const std::string target = "arnold";
material.setNetworkTerminal(target, "light", lightName, "out");
for (const auto& node : nodes)
{
// Process all the nodes.
const std::string& nodeName = node.first;
std::string type = node.second.get<std::string>("type");
if (type.empty())
{
continue;
}
material.addNetworkNode(nodeName, target, type);
const auto& params = node.second.get_child("params");
if (params.empty())
{
continue;
}
Alembic::Abc::OCompoundProperty property =
material.getNetworkNodeParameters(nodeName);
for (const auto& param : params)
{
// Process all the parameters.
const std::string& paramName = param.first;
// Get name of the linked node. If nothing is linked, this
// function will create the parameter.
std::string linked =
saveParam(paramName, param.second, property);
if (linked.empty())
{
// Nothing is linked.
continue;
}
// This parameter is linked to some node.
// Split the linked string in case we have components.
std::vector<std::string> components;
boost::split(components, linked, boost::is_any_of("."));
std::string connectedNodeName;
std::string connectedOutputName;
if (components.empty())
{
// Boost doesn't bahave like python. If the input doesn't
// have '.', the output is empty.
connectedNodeName = linked;
}
else
{
connectedNodeName = components.front();
if (components.size() > 1)
{
connectedOutputName = components.back();
}
}
// Save it in Alembic.
material.setNetworkNodeConnection(
nodeName,
paramName,
connectedNodeName,
connectedOutputName);
}
}
}
}
bool ArnoldLightExporter::isLight(const MObject& iObject)
{
// The list of Maya/Arnold light type.
// We support all the Maya lights that mtoa supports, cf.
// https://support.solidangle.com/display/AFMUG/Lights
static const char* arnoldTypes[] = {"pointLight",
"directionalLight",
"spotLight",
"areaLight",
"aiAreaLight",
"aiLightPortal",
"aiMeshLight",
"aiPhotometricLight",
"aiSkyDomeLight"};
static const MStringArray arnoldTypesArray(
arnoldTypes, sizeof(arnoldTypes) / sizeof(arnoldTypes[0]));
MFnDagNode dagNode(iObject);
return iObject.hasFn(MFn::kLight) ||
presentsIn(arnoldTypesArray, dagNode.typeName());
}
<|start_filename|>walter/arnold/procedural/main.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "engine.h"
#include <ai.h>
#include <pxr/usd/sdf/path.h>
#include <cstring>
#include <string>
PXR_NAMESPACE_USING_DIRECTIVE
struct ProceduralData
{
ProceduralData(
const std::string& prefix,
const std::string& filePaths,
RendererEngine* engine,
const SdfPath& path) :
mData{prefix, filePaths},
mEngine(engine),
mPath(path)
{}
RendererPluginData mData;
RendererEngine* mEngine;
SdfPath mPath;
std::vector<float> mTimes;
};
const char* AiNodeLookUpAndGetStr(AtNode* node, const char* param)
{
if (AiNodeLookUpUserParameter(node, param))
{
return AiNodeGetStr(node, param);
}
return nullptr;
}
static int arnoldProceduralInit(AtNode* node, void** user_ptr)
{
// Get parameters
const char* file = AiNodeGetStr(node, "filePaths");
const char* object = AiNodeGetStr(node, "objectPath");
const char* sessionLayer = AiNodeGetStr(node, "sessionLayer");
const char* variantsLayer = AiNodeGetStr(node, "variantsLayer");
const char* purposeLayer = AiNodeGetStr(node, "purposeLayer");
const char* mayaStateLayer = AiNodeGetStr(node, "mayaStateLayer");
const char* visibilityLayer = AiNodeGetStr(node, "visibilityLayer");
std::vector<std::string> overrides;
for (const char* o : {sessionLayer, variantsLayer, mayaStateLayer, visibilityLayer, purposeLayer})
{
if (o && o[0] != '\0')
{
overrides.push_back(o);
}
}
// Get USD stuff
RendererEngine* engine = RendererEngine::getInstance(file, overrides);
SdfPath path;
if(std::string(object) != "")
{
path = SdfPath(object);
}
else
{
AiMsgWarning(
"[RodeoFX]: Object path is empty in Walter USD Procedural! "
" Use '/' if you want to load the whole stage.");
}
// Get the prefix. We need it because we produce a lot of objects. Each
// of them should have the unique name. The idea that the root object
// doesn't have a prefix attribute so that we can use the name as a
// prefix. All the children should have the prefix because we generate
// it.
const char* prefix;
const char* prefixName = "prefix";
const AtUserParamEntry* prefixEntry =
AiNodeLookUpUserParameter(node, prefixName);
if (prefixEntry)
{
prefix = AiNodeGetStr(node, prefixName);
}
else
{
prefix = AiNodeGetName(node);
}
ProceduralData* data = new ProceduralData(prefix, file, engine, path);
// Get times
const char* timeName = "frame";
const AtUserParamEntry* timeEntry =
AiNodeLookUpUserParameter(node, timeName);
if (timeEntry)
{
int type = AiUserParamGetType(timeEntry);
switch (type)
{
case AI_TYPE_FLOAT:
data->mTimes.push_back(AiNodeGetFlt(node, timeName));
break;
case AI_TYPE_ARRAY:
{
AtArray* array = AiNodeGetArray(node, timeName);
int keys = AiArrayGetNumElements(array) *
AiArrayGetNumKeys(array);
data->mTimes.reserve(keys);
for (int i = 0; i < keys; i++)
{
data->mTimes.push_back(AiArrayGetFlt(array, i));
}
}
break;
default:
break;
}
}
if (data->mTimes.empty())
{
data->mTimes.push_back(1.0f);
}
// It's possible that motion_start/motion_end are not there if motion blur
// is disabled.
const AtNodeEntry* entry = AiNodeGetNodeEntry(node);
if (AiNodeEntryLookUpParameter(entry, "motion_start"))
{
data->mData.motionStart = AiNodeGetFlt(node, "motion_start");
}
if (AiNodeEntryLookUpParameter(entry, "motion_end"))
{
data->mData.motionEnd = AiNodeGetFlt(node, "motion_end");
}
// Save it for future
*user_ptr = data;
return 1;
}
static int arnoldProceduralCleanup(void* user_ptr)
{
ProceduralData* data = reinterpret_cast<ProceduralData*>(user_ptr);
delete data;
return 1;
}
static int arnoldProceduralNumNodes(void* user_ptr)
{
ProceduralData* data = reinterpret_cast<ProceduralData*>(user_ptr);
return data->mEngine->getNumNodes(data->mPath, data->mTimes);
}
static AtNode* arnoldProceduralGetNode(void* user_ptr, int i)
{
ProceduralData* data = reinterpret_cast<ProceduralData*>(user_ptr);
void* result =
data->mEngine->render(data->mPath, i, data->mTimes, &data->mData);
return reinterpret_cast<AtNode*>(result);
}
bool arnoldProceduralInitPlugin(void** plugin_user_ptr)
{
AiMsgInfo(
"[RodeoFX] Walter USD Procedural %s.%s.%s, built on %s at %s",
WALTER_MAJOR_VERSION,
WALTER_MINOR_VERSION,
WALTER_PATCH_VERSION,
__DATE__,
__TIME__);
if (!AiCheckAPIVersion(AI_VERSION_ARCH, AI_VERSION_MAJOR, AI_VERSION_MINOR))
{
AiMsgWarning(
"[RodeoFX]: Walter USD Procedural is compiled with "
"Arnold %s but is running with %s",
AI_VERSION,
AiGetVersion(nullptr, nullptr, nullptr, nullptr));
}
*plugin_user_ptr = nullptr;
return true;
}
bool arnoldProceduralCleanupPlugin(void* plugin_user_ptr)
{
RendererEngine::clearCaches();
return true;
}
AI_PROCEDURAL_NODE_EXPORT_METHODS(WalterMtd);
node_parameters
{
AiParameterStr("filePaths", "");
AiParameterStr("objectPath", "");
AiParameterStr("sessionLayer", "");
AiParameterStr("variantsLayer", "");
AiParameterStr("purposeLayer", "");
AiParameterStr("mayaStateLayer", "");
AiParameterStr("visibilityLayer", "");
}
node_plugin_initialize
{
arnoldProceduralInitPlugin(plugin_data);
}
node_plugin_cleanup
{
arnoldProceduralCleanupPlugin(plugin_data);
}
procedural_init
{
return arnoldProceduralInit(node, user_ptr);
}
procedural_cleanup
{
return arnoldProceduralCleanup(user_ptr);
}
procedural_num_nodes
{
return arnoldProceduralNumNodes(user_ptr);
}
procedural_get_node
{
return arnoldProceduralGetNode(user_ptr, i);
}
node_loader
{
if (i > 0)
return false;
node->methods = WalterMtd;
node->output_type = AI_TYPE_NONE;
node->name = "walter";
node->node_type = AI_NODE_SHAPE_PROCEDURAL;
strcpy(node->version, AI_VERSION);
return true;
}
<|start_filename|>walter/alembic/OWalterLayersSchema.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "OWalterLayersSchema.h"
#include <Alembic/AbcMaterial/All.h>
OWalterLayersSchema::OWalterLayersSchema(
Alembic::AbcCoreAbstract::CompoundPropertyWriterPtr iParent,
const std::string &iName,
const Alembic::Abc::Argument &iArg0,
const Alembic::Abc::Argument &iArg1,
const Alembic::Abc::Argument &iArg2,
const Alembic::Abc::Argument &iArg3 ) :
Alembic::Abc::OSchema<WalterLayersSchemaInfo>(
iParent, iName, iArg0, iArg1, iArg2, iArg3 )
{
}
OWalterLayersSchema::OWalterLayersSchema(
Alembic::Abc::OCompoundProperty iParent,
const std::string &iName,
const Alembic::Abc::Argument &iArg0,
const Alembic::Abc::Argument &iArg1,
const Alembic::Abc::Argument &iArg2 ) :
Alembic::Abc::OSchema<WalterLayersSchemaInfo>(
iParent.getPtr(),
iName,
GetErrorHandlerPolicy( iParent ),
iArg0,
iArg1,
iArg2 )
{
}
void OWalterLayersSchema::setShader(
const std::string & iTarget,
const std::string & iShaderType,
const std::string & iShaderName,
const Alembic::Abc::MetaData& md)
{
// Create a compound attribute with name ".layer1.displacement"
// TODO: Check layer and type names.
Alembic::Abc::OCompoundProperty layer(
this->getPtr(),
std::string(".") + iTarget + "." + iShaderType,
md );
Alembic::AbcMaterial::addMaterialAssignment(layer, iShaderName);
}
OWalterLayersSchema addLayers(
Alembic::Abc::OCompoundProperty iProp,
const std::string& iPropName)
{
return OWalterLayersSchema( iProp.getPtr(), iPropName );
}
OWalterLayersSchema addLayers(
Alembic::Abc::OObject iObject,
const std::string& iPropName)
{
return addLayers( iObject.getProperties(), iPropName );
}
<|start_filename|>walter/katana/WalterIn/ArrayPropUtils.cpp<|end_filename|>
#include "ArrayPropUtils.h"
#include <FnAttribute/FnDataBuilder.h>
#define POINT_ATTR_EXTRAPOLATION 1
namespace WalterIn
{
namespace {
// Converts the specified Alembic property array to an FnAttribute array type.
template <typename attrT, typename podT>
void convertAlembicTypesToKatanaTypes(
ArrayProp& iProp,
Alembic::Abc::ISampleSelector sampleSelector,
typename attrT::value_type* sampleBuffer,
size_t numPodValues)
{
try
{
// Perform a conversion from the stored POD type to the proper
// POD type for the Katana attribute.
Alembic::Util::PlainOldDataType alembicType =
FnAttrTypeToPODType(attrT::getKatAttributeType());
iProp.prop.getAs(sampleBuffer, alembicType, sampleSelector);
}
catch (Alembic::Abc::Exception&)
{
// Because certain types cannot be automatically converted by
// certain backends (HDF5 does not do well converting float16 to
// float32, for example), catch the exception and perform a direct
// cast below. We don't do this for everything, because the
// above is faster and works for the vast majority of cases.
Alembic::Abc::ArraySamplePtr valuePtr;
iProp.prop.get(valuePtr, sampleSelector);
if (valuePtr && valuePtr->valid())
{
const podT* typedData =
static_cast<const podT*>(valuePtr->getData());
typename attrT::value_type* buffer =
(typename attrT::value_type*)sampleBuffer;
for (size_t i = 0; i < numPodValues; ++i)
{
buffer[i] =
static_cast<typename attrT::value_type>(typedData[i]);
}
}
}
}
template<typename attrT>
attrT makeAttribute(float* sampleTimes,
int64_t numSampleTimes,
const typename attrT::value_type** samplePtrs,
int64_t numValues,
int64_t tupleSize)
{
return attrT(sampleTimes, numSampleTimes, samplePtrs, numValues, tupleSize);
}
// Unused, but satisfies the compiler
template<>
FnAttribute::StringAttribute makeAttribute<FnAttribute::StringAttribute>(float*, int64_t, const std::string**, int64_t, int64_t)
{
return FnAttribute::StringAttribute();
}
template<typename attrT>
typename attrT::value_type extrapolateAttr(const std::vector<typename attrT::value_type>& values,
int64_t tupleSize,
int64_t index,
double t0,
double tDelta,
double targetTime)
{
typename attrT::value_type vel = (tDelta != 0.0f) ? ((values[index + tupleSize] - values[index]) / tDelta) : 0.0f;
return values[index] + vel * (targetTime - t0);
}
// Unused, but satisfies the compiler
template<>
std::string extrapolateAttr<FnAttribute::StringAttribute>(const std::vector<std::string>&,
int64_t,
int64_t,
double,
double,
double)
{
return std::string();
}
} // namespace
// read iProp.prop into oGb
template <typename attrT, typename builderT, typename podT>
void readArrayProp(
ArrayProp & iProp,
const OpArgs & iArgs,
FnAttribute::GroupBuilder & oGb,
Alembic::Abc::IUInt64ArrayProperty * iIdsProperty)
{
size_t extent = iProp.prop.getDataType().getExtent();
int64_t tupleSize = extent;
builderT b(tupleSize);
Alembic::Abc::TimeSamplingPtr ts = iProp.prop.getTimeSampling();
SampleTimes sampleTimes;
iArgs.getRelevantSampleTimes(ts, iProp.prop.getNumSamples(), sampleTimes);
if (iIdsProperty && iProp.name != "geometry.poly.startIndex" && sampleTimes.size() > 1)
{
// Motion blur with varying topology, we correlate array elements between
// motion samples by ID so we keep as much motion data as possible
Alembic::Abc::TimeSamplingPtr idTs = iIdsProperty->getTimeSampling();
SampleTimes idSampleTimes;
iArgs.getRelevantSampleTimes(idTs, iIdsProperty->getNumSamples(), idSampleTimes);
std::map<uint64_t, std::vector<typename attrT::value_type> > idToValueMap;
std::map<uint64_t, std::vector<double> > idToSampleTimeMap;
bool foundCorrespondence = idSampleTimes.size() == sampleTimes.size();
if (foundCorrespondence)
{
ArrayProp iIdProp;
iIdProp.name = iIdsProperty->getName();
iIdProp.prop = *iIdsProperty;
iIdProp.asPod = iIdsProperty->getHeader().getDataType().getPod();
Alembic::Util::Dimensions dims;
std::vector<double>::iterator stIter = sampleTimes.begin();
std::vector<double>::iterator idStIter = idSampleTimes.begin();
for ( ; stIter != sampleTimes.end() && idStIter != idSampleTimes.end(); ++stIter, ++idStIter)
{
// Make sure sample times and sizes match between IDs and the array
double sampleTime = *stIter;
double idSampleTime = *idStIter;
if (idSampleTime != sampleTime)
{
foundCorrespondence = false;
break;
}
Alembic::Abc::ISampleSelector sampleSelector(sampleTime);
iProp.prop.getDimensions(dims, sampleSelector);
const size_t numVals = dims.numPoints();
const size_t numPodValues = numVals * tupleSize;
iIdsProperty->getDimensions(dims, sampleSelector);
const size_t numIdPodValues = dims.numPoints();
if (numVals != numIdPodValues)
{
foundCorrespondence = false;
break;
}
if (numPodValues == 0)
{
continue;
}
std::vector<typename attrT::value_type> sampleValues;
sampleValues.resize(numPodValues);
convertAlembicTypesToKatanaTypes<attrT, podT>(iProp, sampleSelector, &sampleValues[0], numPodValues);
std::vector<FnAttribute::IntAttribute::value_type> idValues;
idValues.resize(numIdPodValues);
convertAlembicTypesToKatanaTypes<FnAttribute::IntAttribute, Alembic::Util::uint64_t>(iIdProp, sampleSelector, &idValues[0], numIdPodValues);
// Map each value to its ID-based sequence of samples
for (size_t i = 0; i < numVals; ++i)
{
std::vector<typename attrT::value_type>& values = idToValueMap[idValues[i]];
std::vector<double>& times = idToSampleTimeMap[idValues[i]];
times.push_back(sampleTime);
for (int64_t tupleIndex = 0; tupleIndex < tupleSize; ++tupleIndex)
{
values.push_back(sampleValues[i * tupleSize + tupleIndex]);
}
}
}
}
if (foundCorrespondence)
{
// Build time-sampled array with all found IDs, and extrapolate
// samples from nearby times when they don't exist
const size_t numPodValues = idToValueMap.size() * tupleSize;
typename attrT::value_type *finalValues = new typename attrT::value_type[sampleTimes.size() * numPodValues];
size_t idIndex = 0;
for (auto idValueMapIter = idToValueMap.begin(); idValueMapIter != idToValueMap.end(); ++idValueMapIter, ++idIndex)
{
uint64_t id = idValueMapIter->first;
const std::vector<typename attrT::value_type>& values = idValueMapIter->second;
const std::vector<double>& times = idToSampleTimeMap[id];
if (times.size() == sampleTimes.size())
{
for (size_t i = 0; i < sampleTimes.size(); ++i)
{
::memcpy(&finalValues[i * numPodValues + idIndex * tupleSize],
&values[i * tupleSize],
tupleSize * sizeof(typename attrT::value_type));
}
}
else
{
size_t idSampleTimeIdx = 0;
for (size_t i = 0; i < sampleTimes.size(); ++i)
{
if (sampleTimes[i] < times[idSampleTimeIdx])
{
#if !POINT_ATTR_EXTRAPOLATION
// This element had no sample at this early time, so copy the first available
::memcpy(&finalValues[i * numPodValues + idIndex * tupleSize], &values[0], tupleSize * sizeof(typename attrT::value_type));
#else
if (idSampleTimeIdx + 1 < times.size())
{
// This element had no sample at this early time, so extrapolate from the first two available if possible
float tDelta = times[idSampleTimeIdx + 1] - times[idSampleTimeIdx];
for (int64_t j = 0; j < tupleSize; ++j)
{
finalValues[i * numPodValues + idIndex * tupleSize + j] =
extrapolateAttr<attrT>(values,
tupleSize,
j,
times[idSampleTimeIdx],
tDelta,
sampleTimes[i]);
}
}
else
{
// This element had no sample at this early time, so copy the only available
::memcpy(&finalValues[i * numPodValues + idIndex * tupleSize],
&values[0],
tupleSize * sizeof(typename attrT::value_type));
}
#endif
}
else
{
#if !POINT_ATTR_EXTRAPOLATION
// Copy the last available sample
::memcpy(&finalValues[i * numPodValues + idIndex * tupleSize],
&values[idSampleTimeIdx * tupleSize],
tupleSize * sizeof(typename attrT::value_type));
#else
if (sampleTimes[i] > times[idSampleTimeIdx] && idSampleTimeIdx > 0)
{
// This element had no sample at this early time, so extrapolate from the first two available if possible
float tDelta = times[idSampleTimeIdx] - times[idSampleTimeIdx - 1];
for (int64_t j = 0; j < tupleSize; ++j)
{
finalValues[i * numPodValues + idIndex * tupleSize + j] =
extrapolateAttr<attrT>(values,
tupleSize,
(idSampleTimeIdx - 1) * tupleSize + j,
times[idSampleTimeIdx - 1],
tDelta,
sampleTimes[i]);
}
}
else
{
// Copy the only available sample
::memcpy(&finalValues[i * numPodValues + idIndex * tupleSize],
&values[idSampleTimeIdx * tupleSize],
tupleSize * sizeof(typename attrT::value_type));
}
#endif
// If the sample times match, advance the source sample time if we can
if (sampleTimes[i] == times[idSampleTimeIdx] && idSampleTimeIdx + 1 < times.size())
idSampleTimeIdx++;
}
}
}
}
float* katanaSampleTimes = new float[sampleTimes.size()];
const typename attrT::value_type** sampleDataPtrs = new const typename attrT::value_type*[sampleTimes.size()];
for (size_t i = 0; i < sampleTimes.size(); ++i)
{
// Store the samples (with frame-relative times)
katanaSampleTimes[i] = iArgs.getRelativeSampleTime(sampleTimes[i]);
sampleDataPtrs[i] = &finalValues[i * numPodValues];
}
oGb.set(iProp.name,
makeAttribute<attrT>(katanaSampleTimes, sampleTimes.size(),
sampleDataPtrs, numPodValues, tupleSize));
delete[] katanaSampleTimes;
delete[] sampleDataPtrs;
}
else
{
// IDs not usable? Re-try without IDs.
readArrayProp<attrT, builderT, podT>(iProp, iArgs, oGb, NULL);
}
}
else
{
size_t numVals = 0;
Alembic::Util::Dimensions dims;
if (!sampleTimes.empty())
{
SampleTimes::iterator it = sampleTimes.begin();
iProp.prop.getDimensions(dims, Alembic::Abc::ISampleSelector(*it));
numVals = dims.numPoints();
++it;
// make sure every sample we are using is the same size
bool sameSize = true;
for (; it != sampleTimes.end(); ++it)
{
iProp.prop.getDimensions(dims, Alembic::Abc::ISampleSelector(*it));
if (numVals != dims.numPoints())
{
sameSize = false;
break;
}
}
// not the same, use just a single time
if (!sameSize)
{
sampleTimes.clear();
sampleTimes.push_back(iArgs.getAbcFrameTime());
Alembic::Abc::ISampleSelector ss(*sampleTimes.begin());
iProp.prop.getDimensions(dims, ss);
numVals = dims.numPoints();
}
}
for (SampleTimes::iterator it = sampleTimes.begin();
it != sampleTimes.end(); ++it)
{
Alembic::Abc::ISampleSelector ss(*it);
const size_t numPodValues = extent * numVals;
std::vector<typename attrT::value_type> value;
size_t bufOffset = 0;
if (iProp.name == "geometry.poly.startIndex" && numVals != 0)
{
bufOffset = 1;
}
value.resize(numPodValues + bufOffset);
try
{
// Perform a conversion from the stored POD type to the proper
// POD type for the Katana attribute.
iProp.prop.getAs(&value[bufOffset], FnAttrTypeToPODType(attrT::getKatAttributeType()), ss);
}
catch(Alembic::Util::Exception&)
{
// Because certain types cannot be automatically converted by
// certain backends (HDF5 does not do well converting float16 to
// float32, for example), catch the exception and perform a direct
// cast below. We don't do this for everything, because the
// above is faster and works for the vast majority of cases.
Alembic::Abc::ArraySamplePtr valuePtr;
iProp.prop.get(valuePtr, ss);
if (valuePtr && valuePtr->valid())
{
const podT* typedData = static_cast<const podT*>(valuePtr->getData());
for (size_t i = 0; i < numPodValues; ++i)
{
value[i + bufOffset] = static_cast<typename attrT::value_type> (typedData[i]);
}
}
}
if (iProp.name == "geometry.poly.startIndex" && !value.empty())
{
for (size_t i = 2; i < value.size(); ++i)
{
value[i] += value[i-1];
}
}
if (sampleTimes.size() == 1)
{
// hopefully this will use a fancy attr
oGb.set(iProp.name,
attrT(&(value.front()), value.size(), tupleSize));
}
else
{
b.set(value, iArgs.getRelativeSampleTime(*it));
}
}
if (sampleTimes.size() > 1)
{
oGb.set(iProp.name, b.build());
}
}
}
void arrayPropertyToAttr(ArrayProp & iProp,
const OpArgs & iArgs,
FnAttribute::GroupBuilder & oGb,
Alembic::Abc::IUInt64ArrayProperty * iIdsProperty)
{
switch(iProp.asPod)
{
case Alembic::Util::kBooleanPOD:
readArrayProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::bool_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kUint8POD:
readArrayProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::uint8_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kInt8POD:
readArrayProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::int8_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kUint16POD:
readArrayProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::uint16_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kInt16POD:
readArrayProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::int16_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kUint32POD:
readArrayProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::uint32_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kInt32POD:
readArrayProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::int32_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kUint64POD:
readArrayProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::uint64_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kInt64POD:
readArrayProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder,
Alembic::Util::int64_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kFloat16POD:
readArrayProp<FnAttribute::FloatAttribute,
FnAttribute::FloatBuilder,
Alembic::Util::float16_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kFloat32POD:
readArrayProp<FnAttribute::FloatAttribute,
FnAttribute::FloatBuilder,
Alembic::Util::float32_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kFloat64POD:
readArrayProp<FnAttribute::DoubleAttribute,
FnAttribute::DoubleBuilder,
Alembic::Util::float64_t>(
iProp, iArgs, oGb, iIdsProperty);
break;
case Alembic::Util::kStringPOD:
readArrayProp<FnAttribute::StringAttribute,
FnAttribute::StringBuilder,
std::string>(
iProp, iArgs, oGb, NULL); // NOTE: no support for strings correlated by IDs (varying topologies)
break;
default:
break;
}
}
void arrayPropertyToAttr(Alembic::Abc::ICompoundProperty & iParent,
const Alembic::Abc::PropertyHeader & iPropHeader,
const std::string & iPropName,
FnKatAttributeType iType,
AbcCookPtr ioCook,
FnAttribute::GroupBuilder & oStaticGb,
Alembic::Abc::v10::IUInt64ArrayProperty * iIdsProperty)
{
Alembic::Abc::IArrayProperty prop(iParent, iPropHeader.getName());
// bad prop don't bother with it
if (!prop.valid() || prop.getNumSamples() == 0)
{
return;
}
ArrayProp item;
item.name = iPropName;
item.prop = prop;
item.asPod = iPropHeader.getDataType().getPod();
if (!prop.isConstant() && item.asPod != Alembic::Util::kUnknownPOD)
{
ioCook->arrayProps.push_back(item);
return;
}
OpArgs defaultArgs;
arrayPropertyToAttr(item, defaultArgs, oStaticGb, iIdsProperty);
}
}
<|start_filename|>walter/viewer/FreeCamera.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "FreeCamera.h"
#include "CameraControler.h"
#include <pxr/base/gf/frustum.h>
namespace walter_viewer
{
static float DEFAULT_FOCUS_DISTANCE = 5.0f;
FreeCamera::FreeCamera()
{
this->SetFocusDistance(DEFAULT_FOCUS_DISTANCE);
}
void FreeCamera::updateZoom()
{
float scaleFactor = 1.f + mControler.zoom();
float dist = this->GetFocusDistance();
if (scaleFactor > 1.f && dist < 2.f)
{
scaleFactor -= 1.0;
dist += scaleFactor;
}
else
{
dist *= scaleFactor;
}
this->SetFocusDistance(dist);
}
void FreeCamera::updatePan(int height)
{
// From usdView code
auto frustrum = this->GetFrustum();
auto camUp = frustrum.ComputeUpVector();
auto camRight = GfCross(frustrum.ComputeViewDirection(), camUp);
auto offRatio =
frustrum.GetWindow().GetSize()[1] * this->GetFocusDistance() / height;
mCenter += -offRatio * mControler.panX() * camRight;
mCenter += offRatio * mControler.panY() * camUp;
mControler.setPan(0.f, 0.f);
}
void FreeCamera::updateTumble()
{
GfMatrix4d newTransfo;
newTransfo.SetTranslate(GfVec3d::ZAxis() * this->GetFocusDistance());
newTransfo *= GfMatrix4d().SetRotate(
GfRotation(GfVec3d::ZAxis(), -mControler.rotPsi()));
newTransfo *= GfMatrix4d().SetRotate(
GfRotation(GfVec3d::XAxis(), -mControler.rotPhi()));
newTransfo *= GfMatrix4d().SetRotate(
GfRotation(GfVec3d::YAxis(), -mControler.rotTheta()));
newTransfo *= GfMatrix4d().SetTranslate(mCenter);
this->SetTransform(newTransfo);
}
void FreeCamera::reset()
{
this->SetFocusDistance(DEFAULT_FOCUS_DISTANCE);
GfMatrix4d newTransfo;
newTransfo.SetIdentity();
GfVec3d translate = GfVec3d::ZAxis() * this->GetFocusDistance();
newTransfo.SetTranslateOnly(translate);
this->SetTransform(newTransfo);
mCenter = GfVec3d(0.0);
mControler.reset();
}
const GfVec3d& FreeCamera::angles() const
{
auto transform = this->GetTransform();
transform.Orthonormalize();
auto angles = transform.DecomposeRotation(
GfVec3d::XAxis(), GfVec3d::YAxis(), GfVec3d::ZAxis());
return angles;
}
} // end namespace walter_viewer
<|start_filename|>walter/usd/readPlugInfoObject.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
/*
For static linking only:
We need to create plugInfo.json with descriptions of all the plugins and
convert it to an ELF object like this:
objcopy \
--input binary \
--output elf64-x86-64 \
--binary-architecture i386 \
plugInfo.json plugInfo.o
After that we will be able to read this file as an external symbol. Since we
compile static USD with weak _ReadPlugInfoObject, we are able to replace it
here.
*/
#ifdef MFB_ALT_PACKAGE_NAME
#include <pxr/base/js/json.h>
#include <pxr/base/tf/diagnosticLite.h>
extern char _binary_plugInfo_json_start;
extern char _binary_plugInfo_json_end;
PXR_NAMESPACE_USING_DIRECTIVE
extern "C" bool _ReadPlugInfoObject(
const std::string& pathname, JsObject* result)
{
std::string json(
&_binary_plugInfo_json_start,
size_t(&_binary_plugInfo_json_end - &_binary_plugInfo_json_start));
result->clear();
// Read JSON.
JsParseError error;
JsValue plugInfo = JsParseString(json, &error);
// Validate.
if (plugInfo.IsNull())
{
TF_RUNTIME_ERROR("Plugin info file %s couldn't be read "
"(line %d, col %d): %s", pathname.c_str(),
error.line, error.column, error.reason.c_str());
}
else if (!plugInfo.IsObject())
{
// The contents didn't evaluate to a json object....
TF_RUNTIME_ERROR("Plugin info file %s did not contain a JSON object",
pathname.c_str());
}
else
{
*result = plugInfo.GetJsObject();
}
return true;
}
#endif
<|start_filename|>walter/arnold/procedural/delegate.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "delegate.h"
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usdGeom/pointInstancer.h>
#include <pxr/usd/usdShade/connectableAPI.h>
#include <pxr/usd/usdShade/material.h>
#include <boost/algorithm/string.hpp>
#include "schemas/expression.h"
PXR_NAMESPACE_USING_DIRECTIVE
RendererDelegate::RendererDelegate(
RendererIndex& index,
RendererPlugin& plugin) :
mIndex(index),
mPlugin(plugin)
{}
void RendererDelegate::populate(const UsdPrim& root)
{
const SdfPath rootPath = root.GetPath();
bool childrenKnown = mIndex.isChildrenKnown(rootPath);
// This accessor will freeze if there is another accessor in different
// thread with the same rootPath.
SdfPathMutex::accessor it;
if (!mPopulateGuard.insert(it, rootPath))
{
// We already did it before. Skip.
return;
}
// TODO: limit type.
UsdPrimRange range(root);
for (const UsdPrim& prim : range)
{
// We need to process the expressions at the end because we need all the
// materials loaded.
if (prim.IsA<WalterExpression>())
{
continue;
}
const SdfPath primPath = prim.GetPath();
// This will check if, in the hierarchy of the root path, a parent prim
// of primPath has already been added to the index.
// If it's the case, it means that a walter procedural will be created
// for it (the parent) and so children will be populate at this time.
if (mIndex.isParentKnown(rootPath, primPath))
{
continue;
}
// In some cases like a bbox generated from a "point instance" a path could
// already be added to the index, but not from the same parent. In this case
// we can't skip to early.
bool skipLater = false;
// Skip if it's already cached. In USD it's possible to have several
// parents. We need to be sure that we output the object only once.
if (rootPath != primPath && mIndex.isProcessed(primPath))
{
if (childrenKnown)
{
continue;
}
else
{
skipLater = true;
}
}
if (mPlugin.isSupported(prim))
{
mIndex.insertPrim(rootPath, primPath);
}
else if (mPlugin.isImmediate(prim))
{
mIndex.insertPrim(rootPath, primPath);
}
if (skipLater)
{
continue;
}
if (prim.IsA<UsdShadeMaterial>())
{
// Iterate the connections.
for (const UsdAttribute& attr : prim.GetAttributes())
{
// The name is "arnold:surface"
std::string name = attr.GetName();
std::vector<std::string> splitted;
boost::split(splitted, name, boost::is_any_of(":"));
if (splitted.size() < 2)
{
continue;
}
// Extract the render and the target.
std::string render = splitted[0];
std::string target = splitted[1];
// TODO: other renders?
if (render != "arnold")
{
continue;
}
if (!UsdShadeConnectableAPI::HasConnectedSource(attr))
{
// This block saved Walter Overrides.
// We need to save the arnold attributes if any.
if (target != "attribute" && splitted.size() >= 3)
{
continue;
}
// Get the renderer attribute.
RendererAttribute rendererAttribute =
mPlugin.createRendererAttribute(attr);
if (!rendererAttribute.valid())
{
continue;
}
// Save it to the index.
mIndex.insertAttribute(
primPath, attr.GetBaseName(), rendererAttribute);
continue;
}
// Get the connection using ConnectableAPI.
UsdShadeConnectableAPI connectableAPISource;
TfToken sourceName;
UsdShadeAttributeType sourceType;
if (!UsdShadeConnectableAPI::GetConnectedSource(
attr, &connectableAPISource, &sourceName, &sourceType))
{
// Should never happen because we already checked it.
continue;
}
mIndex.insertMaterial(
primPath, target, connectableAPISource.GetPrim().GetPath());
}
}
}
// If the locations '/' or '/materials' were not already "scanned" we don't
// want to check for expression and assignment as materials may not be
// retrieved to do it properly. So skip the Expression scan until
// '/materials' has been scanned in the loop above.
//
// If materials are retrieved and the check for expression and assignment
// are already done there is nothing else to do and we can skip the last
// loop on WalterExpression.
if (!mIndex.hasGlobalMaterials() || mIndex.isAssignmentDone())
{
return;
}
// Always check assignment from the pseudo root "/" whatever the given
// root prim was as material are usually under "/" directly.
UsdPrim pseudoRoot = root.GetStage()->GetPseudoRoot();
range = UsdPrimRange(pseudoRoot);
for (const UsdPrim& prim : range)
{
// We already processed everything and since all the materials are
// loaded, we can work with expressions.
if (!prim.IsA<WalterExpression>())
{
continue;
}
// Get expressions.
WalterExpression expression(prim);
std::string expressionText = expression.GetExpression();
WalterExpression::AssignmentLayers layers = expression.GetLayers();
// Insert them into a cache.
mIndex.insertExpression(
prim.GetPath(), pseudoRoot.GetPath(), expressionText, layers);
}
}
<|start_filename|>walter/usd/resourcer.c<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Convert a text file to a cpp file with c++ string containing the source. It's
// necessary to include the source to the binary.
int main(int argc, const char* argv[])
{
const char* fileNameSrc = NULL;
const char* fileNameDst = NULL;
const char** arg = &fileNameSrc;
int i;
for (i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
{
printf(
"Converts any file to the C source file\n"
"USAGE:\n"
"%s source -o destination\n",
argv[0]);
}
if (!strcmp(argv[i], "-o"))
{
arg = &fileNameDst;
continue;
}
*arg = argv[i];
arg = &fileNameSrc;
}
if (!fileNameSrc)
{
printf("Error: The source is not specified\n");
return 1;
}
if (!fileNameDst)
{
printf("Error: The destination is not specified\n");
return 1;
}
/* Form the name of the variable and the function. */
char* name = strdup(fileNameSrc);
const char* badChars = "/\\.-+<>";
char* badOne;
char* p;
for (badOne = badChars; *badOne != '\0'; badOne++)
{
for (p = name; (p = strchr(p, *badOne)); ++p)
{
*p = '_';
}
}
/* Open the files. */
FILE* fileSrc = fopen(fileNameSrc, "rb");
FILE* fileDst = fopen(fileNameDst, "w");
/* First line of the file. */
fprintf(fileDst, "/* Generated with Walter resourcer. */\n\n");
fprintf(fileDst, "#include \"pxr/base/tf/registryManager.h\"\n\n");
fprintf(fileDst, "#include \"pxr/base/tf/type.h\"\n\n");
fprintf(fileDst, "#include \"rdoCustomResource.h\"\n\n");
/* Declare the variable. */
fprintf(fileDst, "static const unsigned char %s_begin[] = {", name);
/* Generate the byte code. */
int counter = 0;
unsigned char current = '\0';
while (!feof(fileSrc))
{
if (counter++ % 16 == 0)
{
fprintf(fileDst, "\n");
}
fread(¤t, 1, 1, fileSrc);
fprintf(fileDst, "0x%02x, ", current);
// 'current' needs to be set to a null character. This is because on last
// call to fread (when we are at the end of the file) previous value is
// used (probably a compiler optimisation).
// For example if the last char is a '}', without this line it would add
// it twice leading to an error while trying to compile the souce code
// from the generated byte code (like when glCompileShader() is called).
current = '\0';
}
/* The final 0 symbol. */
fprintf(fileDst, "0x00};\n");
/* The function that returns the string. */
fprintf(
fileDst,
"PXR_NAMESPACE_USING_DIRECTIVE;\n"
"TF_REGISTRY_FUNCTION(TfType)\n"
"{\n"
"setResource(\"%s\", (const char*)&%s_begin[0]);\n"
"}\n",
fileNameSrc,
name);
fclose(fileSrc);
fclose(fileDst);
free(name);
return 0;
}
<|start_filename|>walter/maya/walterMtoaConnection/abcExporterUtils.h<|end_filename|>
/*Abc Shader Exporter
Copyright (c) 2014, <NAME>, All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.*/
#ifndef _Abc_Exporter_Utils_h_
#define _Abc_Exporter_Utils_h_
#include "mtoaScene.h"
#include "mtoaVersion.h"
#include <ai.h>
// FIXME: private mtoa headers:
#include "translators/NodeTranslator.h"
#include <Alembic/Abc/All.h>
#include <Alembic/AbcCoreOgawa/All.h>
#include <Alembic/AbcMaterial/OMaterial.h>
#include <boost/lexical_cast.hpp>
#include <sstream>
namespace Abc = Alembic::Abc;
namespace Mat = Alembic::AbcMaterial;
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
const MStringArray& GetComponentNames(int arnoldParamType);
void processLinkedParam(AtNode* sit, int inputType, int outputType, Mat::OMaterial matObj, MString nodeName, const char* paramName, MString containerName, bool interfacing = false);
void processArrayParam(AtNode* sit, const char *paramName, AtArray* paramArray, int index, int outputType, Mat::OMaterial matObj, MString nodeName, MString containerName);
void processArrayValues(AtNode* sit, const char *paramName, AtArray* paramArray, int outputType, Mat::OMaterial matObj, MString nodeName, MString containerName);
void exportParameterFromArray(AtNode* sit, Mat::OMaterial matObj, AtArray* paramArray, int index, MString nodeName, const char* paramName);
void exportParameter(AtNode* sit, Mat::OMaterial matObj, int type, MString nodeName, const char* paramName, bool interfacing = false);
void exportLink(AtNode* sit, Mat::OMaterial matObj, MString nodeName, const char* paramName, MString containerName);
bool relink(AtNode* src, AtNode* dest, const char* input, int comp);
AtNode* renameAndCloneNodeByParent(AtNode* node, AtNode* parent);
void getAllArnoldNodes(AtNode* node, AtNodeSet* nodes);
bool isDefaultValue(const AtNode* node, const char* paramName);
#endif
<|start_filename|>walter/alembic/IWalterLayersSchema.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __IWALTERLAYERSSCHEMA_H_
#define __IWALTERLAYERSSCHEMA_H_
#include "SchemaInfoDeclarations.h"
// Schema for reading and querying layers definitions from either an object or
// compound property.
class ALEMBIC_EXPORT IWalterLayersSchema :
public Alembic::Abc::ISchema<WalterLayersSchemaInfo>
{
public:
typedef IWalterLayersSchema this_type;
// This constructor creates a new layers reader.
// The first argument is the parent ICompoundProperty, from which the error
// handler policy for is derived. The second argument is the name of the
// ICompoundProperty that contains this schemas properties. The remaining
// optional arguments can be used to override the
// ErrorHandlerPolicy and to specify schema interpretation matching.
IWalterLayersSchema(
const ICompoundProperty &iParent,
const std::string &iName,
const Alembic::Abc::Argument &iArg0 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg1 = Alembic::Abc::Argument() ) :
Alembic::Abc::ISchema<WalterLayersSchemaInfo>(
iParent, iName, iArg0, iArg1 )
{
init();
}
// This constructor wraps an existing ICompoundProperty as the layers
// reader, and the error handler policy is derived from it. The remaining
// optional arguments can be used to override the ErrorHandlerPolicy and to
// specify schema interpretation matching.
IWalterLayersSchema(
const ICompoundProperty &iProp,
const Alembic::Abc::Argument &iArg0 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg1 = Alembic::Abc::Argument() ) :
Alembic::Abc::ISchema<WalterLayersSchemaInfo>( iProp, iArg0, iArg1 )
{
init();
}
// Copy constructor.
IWalterLayersSchema( const IWalterLayersSchema& iCopy ) :
Alembic::Abc::ISchema<WalterLayersSchemaInfo>()
{
*this = iCopy;
}
size_t getNumTargets() const;
const std::string& getTargetName(size_t n) const;
std::string getShaderName(
const std::string& iTarget,
const std::string& iShaderType) const;
private:
typedef std::pair<std::string, std::string> TargetKey;
typedef std::map<TargetKey, std::string> TargetMap;
void init();
std::vector<std::string> mTargets;
TargetMap mShaders;
};
#endif
<|start_filename|>walter/maya/common/mayaUtils.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTER_MAYA_UTILS_H_
#define __WALTER_MAYA_UTILS_H_
#include <maya/MString.h>
#include <maya/MPlug.h>
#include <string>
// namespace walter {
// namespace maya {
static const unsigned int WALTER_MAYA_SHAPE_ID(0x07201);
// Search child plug with given name in the given plug's children.
bool GetChildMPlug(const MPlug& i_plug, const MString& name, MPlug& o_plug);
// Maya name to arnold name convert. "walterSubdivType" -> "subdiv_type".
// Set oIsUserData to true if it's a User Data.
std::string attributeNameDemangle(
const std::string& name,
bool* oIsUserData = nullptr);
// } // end namespace walter
// } // end namespace maya
#endif // end __WALTER_MAYA_UTILS_H_
<|start_filename|>walter/houdini/src/walterSpriteRenderer.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterSpriteRenderer.h"
static const char* sBeautyVertexSrc =
"#version 420\n"
"layout(location = 0) in vec3 P;"
"layout(location = 1) in vec2 st;"
"out vec2 uv;"
"void main()"
"{"
" uv = st;"
" gl_Position = vec4(P, 1.0);"
"}";
static const char* sBeautyFragmentSrc =
"#version 420\n"
"in vec2 uv;"
"layout (binding = 0) uniform sampler2D colorTexture;"
"layout (binding = 1) uniform sampler2D depthTexture;"
"void main()"
"{"
" gl_FragColor = texture(colorTexture, uv);"
" gl_FragDepth = texture(depthTexture, uv).x;"
"}";
static const char* sPickFragmentSrc =
"#version 420\n"
"in vec2 uv;"
"uniform PickSettings"
"{"
" ivec3 glH_PickBaseID;"
" ivec3 glH_PickComponentID;"
"};"
"layout (binding = 0) uniform sampler2D colorTexture;"
"layout (binding = 1) uniform sampler2D depthTexture;"
"out ivec3 pickBaseID;"
"out ivec3 pickComponentID;"
"void main()"
"{"
" vec4 Ci = texture(colorTexture, uv);"
" float alpha = Ci.a;"
" float depth = abs(texture(depthTexture, uv).x);"
" if (alpha < 1)"
" {"
" gl_FragDepth = 1.0;"
" pickBaseID = ivec3(0, 0, 0);"
" pickComponentID = ivec3(0, 0, 0);"
" }"
" else"
" {"
" pickBaseID = glH_PickBaseID;"
" pickComponentID = glH_PickComponentID;"
" gl_FragDepth = depth;"
" }"
"}";
static const char* sMatteFragmentSrc =
"#version 420\n"
"in vec2 uv;"
"layout (binding = 0) uniform sampler2D colorTexture;"
"layout (binding = 1) uniform sampler2D depthTexture;"
"void main()"
"{"
" gl_FragColor = vec4(1.0, 0.699394, 0.0, 0.25);"
" gl_FragDepth = texture(depthTexture, uv).x;"
"}";
std::shared_ptr<WalterSpriteRenderer::GLSLProgram>
WalterSpriteRenderer::SpriteRenderer::sBeautyShader;
std::shared_ptr<WalterSpriteRenderer::GLSLProgram>
WalterSpriteRenderer::SpriteRenderer::sPickShader;
std::shared_ptr<WalterSpriteRenderer::GLSLProgram>
WalterSpriteRenderer::SpriteRenderer::sMatteShader;
void printCompileErrors(GLuint iShaderID)
{
GLint maxLength = 0;
glGetShaderiv(iShaderID, GL_INFO_LOG_LENGTH, &maxLength);
// The maxLength includes the NULL character
std::vector<GLchar> errorLog(maxLength);
glGetShaderInfoLog(iShaderID, maxLength, &maxLength, &errorLog[0]);
printf(
"ERROR: Shader %i is not compiled:\n{\n%s\n}\n",
iShaderID,
&errorLog[0]);
}
WalterSpriteRenderer::GLSLProgram::GLSLProgram(
const char* iVertexSrc,
const char* iFragmentSrc)
{
// Copy the shader strings into GL shaders, and compile them. Then
// create an executable shader and attach both of the compiled shaders,
// link this, which matches the outputs of the vertex shader to the
// inputs of the fragment shader, etc. Add it is then ready to use.
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, &iVertexSrc, NULL);
glCompileShader(vs);
GLint success = GL_FALSE;
glGetShaderiv(vs, GL_COMPILE_STATUS, &success);
if (success == GL_FALSE)
{
printCompileErrors(vs);
}
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, &iFragmentSrc, NULL);
glCompileShader(fs);
success = GL_FALSE;
glGetShaderiv(fs, GL_COMPILE_STATUS, &success);
if (success == GL_FALSE)
{
printCompileErrors(vs);
}
mShaderProgram = glCreateProgram();
glAttachShader(mShaderProgram, fs);
glAttachShader(mShaderProgram, vs);
glLinkProgram(mShaderProgram);
// TODO: Release attached shaders?
}
void WalterSpriteRenderer::GLSLProgram::use()
{
assert(mShaderProgram);
glUseProgram(mShaderProgram);
}
WalterSpriteRenderer::GLScopeGuard::GLScopeGuard(RE_Render* r) :
mRender(r),
lock(r)
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
glGetIntegerv(GL_CURRENT_PROGRAM, &mLastProgram);
glGetIntegerv(GL_TEXTURE_BINDING_2D, &mLastTexture);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &mLastVAO);
}
WalterSpriteRenderer::GLScopeGuard::~GLScopeGuard()
{
glUseProgram(mLastProgram);
glBindTexture(GL_TEXTURE_2D, mLastTexture);
glBindVertexArray(mLastVAO);
glPopAttrib();
}
WalterSpriteRenderer::SpriteRenderer::SpriteRenderer() :
mVertexArray(0),
mPointBuffer(0),
mUVBuffer(0),
mPickInitialized(false),
mInitialized(false)
{}
void WalterSpriteRenderer::SpriteRenderer::drawToBufferBegin()
{
init();
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
if (!mHyraDrawTarget)
{
// Initialize hydra framebuffer to viewport width and height.
mHyraDrawTarget = GlfDrawTarget::New(GfVec2i(viewport[2], viewport[3]));
mHyraDrawTarget->Bind();
// Add color and depth buffers.
mHyraDrawTarget->AddAttachment("color", GL_RGBA, GL_FLOAT, GL_RGBA);
mHyraDrawTarget->AddAttachment(
"depth",
GL_DEPTH_STENCIL,
GL_UNSIGNED_INT_24_8,
GL_DEPTH24_STENCIL8);
}
else
{
mHyraDrawTarget->Bind();
mHyraDrawTarget->SetSize(GfVec2i(viewport[2], viewport[3]));
}
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
// Clear the framebuffer's colour and depth buffers.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void WalterSpriteRenderer::SpriteRenderer::drawToBufferEnd()
{
mHyraDrawTarget->Unbind();
}
void WalterSpriteRenderer::SpriteRenderer::drawBeauty() const
{
assert(sBeautyShader);
sBeautyShader->use();
drawPoly();
}
void WalterSpriteRenderer::SpriteRenderer::drawPick(
int* iPickBaseID,
int* iPickCompID)
{
initPick(iPickBaseID, iPickCompID);
assert(sPickShader);
assert(mUniformPickBuffer);
sPickShader->use();
glBindBufferBase(GL_UNIFORM_BUFFER, mUniformPickIndex, mUniformPickBuffer);
drawPoly();
}
void WalterSpriteRenderer::SpriteRenderer::drawMatte() const
{
assert(sBeautyShader);
sMatteShader->use();
drawPoly();
}
void WalterSpriteRenderer::SpriteRenderer::init()
{
if (mInitialized)
{
return;
}
// Never repeat it again.
mInitialized = true;
if (!sBeautyShader)
{
sBeautyShader =
std::make_shared<GLSLProgram>(sBeautyVertexSrc, sBeautyFragmentSrc);
}
if (!sPickShader)
{
sPickShader =
std::make_shared<GLSLProgram>(sBeautyVertexSrc, sPickFragmentSrc);
}
if (!sMatteShader)
{
sMatteShader =
std::make_shared<GLSLProgram>(sBeautyVertexSrc, sMatteFragmentSrc);
}
// Geometry to use. These are 4 xyz points to make a quad.
static const GLfloat points[] = {
-1.f, -1.f, 0.f, 1.f, -1.f, 0.f, 1.f, 1.f, 0.f, -1., 1., 0.};
// These are 4 UVs.
static const GLfloat uvs[] = {0.f, 0.f, 1.f, 0.f, 1.f, 1.f, 0.f, 1.f};
// Create a vertex buffer object. It stores an array of data on the
// graphics adapter's memory. The vertex points in our case.
glGenBuffers(1, &mPointBuffer);
glBindBuffer(GL_ARRAY_BUFFER, mPointBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
// The same for UVs.
glGenBuffers(1, &mUVBuffer);
glBindBuffer(GL_ARRAY_BUFFER, mUVBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(uvs), uvs, GL_STATIC_DRAW);
// The vertex array object is a descriptor that defines which data from
// vertex buffer objects should be used as input variables to vertex
// shaders.
glGenVertexArrays(1, &mVertexArray);
glBindVertexArray(mVertexArray);
// Normally we need to bind vertes buffer objects here. But since
// Houdini resets them each frame we
}
void WalterSpriteRenderer::SpriteRenderer::initPick(
int* iPickBaseID,
int* iPickCompID)
{
if (mPickInitialized)
{
return;
}
// Never repeat it again.
mPickInitialized = true;
mUniformPickIndex =
glGetUniformBlockIndex(sPickShader->getID(), "PickSettings");
GLint blockSize;
glGetActiveUniformBlockiv(
sPickShader->getID(),
mUniformPickIndex,
GL_UNIFORM_BLOCK_DATA_SIZE,
&blockSize);
GLubyte* blockBuffer = (GLubyte*)malloc(blockSize);
// Query for the offsets of each block variable
const GLchar* names[] = {"glH_PickBaseID", "glH_PickComponentID"};
GLuint indices[2];
glGetUniformIndices(sPickShader->getID(), 2, names, indices);
GLint offset[2];
glGetActiveUniformsiv(
sPickShader->getID(), 2, indices, GL_UNIFORM_OFFSET, offset);
memcpy(blockBuffer + offset[0], iPickBaseID, 3 * sizeof(GLint));
memcpy(blockBuffer + offset[1], iPickCompID, 3 * sizeof(GLint));
glGenBuffers(1, &mUniformPickBuffer);
glBindBuffer(GL_UNIFORM_BUFFER, mUniformPickBuffer);
glBufferData(GL_UNIFORM_BUFFER, blockSize, blockBuffer, GL_STATIC_DRAW);
free(blockBuffer);
}
void WalterSpriteRenderer::SpriteRenderer::drawPoly() const
{
assert(mVertexArray);
assert(mPointBuffer);
assert(mUVBuffer);
glBindVertexArray(mVertexArray);
// Normally we only should do it on init, but Houdini resets buffers.
glBindBuffer(GL_ARRAY_BUFFER, mPointBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glBindBuffer(GL_ARRAY_BUFFER, mUVBuffer);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
// Get color and depts buffers as texture.
glActiveTexture(GL_TEXTURE0);
glBindTexture(
GL_TEXTURE_2D,
mHyraDrawTarget->GetAttachment("color")->GetGlTextureName());
glActiveTexture(GL_TEXTURE1);
glBindTexture(
GL_TEXTURE_2D,
mHyraDrawTarget->GetAttachment("depth")->GetGlTextureName());
// Draw points 0-4 from the currently bound VAO with current in-use
// shader.
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
<|start_filename|>walter/maya/walterStandin/walterCmd.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
///////////////////////////////////////////////////////////////////////////////
//
// Walter MEL command
//
// Creates one or more cache files on disk to store attribute data for
// a span of frames.
//
////////////////////////////////////////////////////////////////////////////////
#include "walterCmd.h"
#include "PathUtil.h"
#include "walterShapeNode.h"
#include "walterAssignment.h"
#include "walterAttributes.h"
#include "walterThreadingUtils.h"
#include "walterUsdUtils.h"
#include <AbcExport.h>
#include <maya/MAnimControl.h>
#include <maya/MArgList.h>
#include <maya/MFnDagNode.h>
#include <maya/MFnTransform.h>
#include <maya/MPlugArray.h>
#include <maya/MSyntax.h>
#include <maya/MFnStringData.h>
#include <maya/MFnDependencyNode.h>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_set.hpp>
#include <cfloat>
#include <fstream>
#include <iomanip>
#include <limits>
#include <list>
#include <map>
#include <sstream>
PXR_NAMESPACE_USING_DIRECTIVE
namespace WalterMaya
{
void* Command::creator()
{
return new Command();
}
const char* Command::LOCATOR_ATTR_PRIM_PATH = "walterPrimPath";
MSyntax Command::cmdSyntax()
{
MSyntax syntax;
syntax.addFlag("-css", "-clearSubSelection", MSyntax::kString);
syntax.addFlag(
"-ass", "-addSubSelection", MSyntax::kString, MSyntax::kString);
syntax.addFlag("-da", "-dirAlembic", MSyntax::kString, MSyntax::kString);
syntax.addFlag("-pa", "-propsAlembic", MSyntax::kString, MSyntax::kString);
syntax.addFlag(
"-gva",
"-getVariants",
MSyntax::kString,
MSyntax::kString,
MSyntax::kBoolean);
syntax.addFlag(
"-sva",
"-setVariant",
MSyntax::kString,
MSyntax::kString,
MSyntax::kString,
MSyntax::kString);
syntax.addFlag("-v", "-version", MSyntax::kString, MSyntax::kString);
syntax.addFlag("-s", "-saveAssignment", MSyntax::kString, MSyntax::kString);
syntax.addFlag("-s", "-saveAttributes", MSyntax::kString, MSyntax::kString);
syntax.addFlag(
"-st", "-saveTransforms", MSyntax::kString, MSyntax::kString);
syntax.addFlag("-st", "-startTime", MSyntax::kTime);
syntax.addFlag("-et", "-endTime", MSyntax::kTime);
syntax.addFlag("-smr", "-simulationRate", MSyntax::kTime);
syntax.addFlag("-rsl", "-resetSessionLayer", MSyntax::kBoolean);
syntax.addFlag(
"-ao",
"-assignmentObjects",
MSyntax::kString,
MSyntax::kString,
MSyntax::kString);
syntax.addFlag("-al", "-assignmentLayers", MSyntax::kString);
syntax.addFlag(
"-a",
"-assignment",
MSyntax::kString,
MSyntax::kString,
MSyntax::kString,
MSyntax::kString);
syntax.addFlag("-aag", "-alembicAllGroups", MSyntax::kString);
syntax.addFlag("-ae", "-alembicExpressions", MSyntax::kString);
syntax.addFlag(
"-age", "-alembicGroupExpressions", MSyntax::kString, MSyntax::kString);
syntax.addFlag(
"-ext", "-exposeTransform", MSyntax::kString, MSyntax::kString);
syntax.addFlag(
"-det", "-detachTransform", MSyntax::kString, MSyntax::kString);
syntax.addFlag("-cfd", "-setCachedFramesDirty", MSyntax::kString);
syntax.addFlag("-e", "-export", MSyntax::kString);
syntax.addFlag(
"-gls", "-getLayerAsString", MSyntax::kString, MSyntax::kString);
syntax.addFlag("-ja", "-joinAll");
syntax.addFlag("-hp", "-hydraPlugins");
syntax.addFlag("-j", "-join", MSyntax::kString);
syntax.addFlag(
"-cev",
"-expressionIsMatching",
MSyntax::kString,
MSyntax::kString);
syntax.addFlag(
"-ipr",
"-isPseudoRoot",
MSyntax::kString,
MSyntax::kString);
syntax.addFlag(
"-iv",
"-isVisible",
MSyntax::kString,
MSyntax::kString);
syntax.addFlag(
"-sv",
"-setVisibility",
MSyntax::kString,
MSyntax::kString,
MSyntax::kBoolean);
syntax.addFlag(
"-tv",
"-toggleVisibility",
MSyntax::kString,
MSyntax::kString);
syntax.addFlag(
"-hat",
"-hideAllExceptedThis",
MSyntax::kString,
MSyntax::kString);
syntax.addFlag(
"-pme",
"-primPathsMatchingExpression",
MSyntax::kString,
MSyntax::kString);
syntax.addFlag(
"-spp",
"-setPurpose",
MSyntax::kString,
MSyntax::kString,
MSyntax::kString);
syntax.addFlag(
"-gpp",
"-getPurpose",
MSyntax::kString,
MSyntax::kString);
syntax.addFlag(
"-srp",
"-setRenderPurpose",
MSyntax::kString,
MSyntax::kString);
syntax.addFlag(
"-grp",
"-getRenderPurpose",
MSyntax::kString);
syntax.addFlag(
"-sp",
"-savePurposes",
MSyntax::kString,
MSyntax::kString);
syntax.addFlag(
"-svl",
"-saveVariantsLayer",
MSyntax::kString,
MSyntax::kString);
syntax.useSelectionAsDefault(true);
syntax.setObjectType(MSyntax::kSelectionList, 0);
syntax.enableQuery(true);
syntax.enableEdit(true);
return syntax;
}
Command::Command()
{}
Command::~Command()
{}
bool Command::isUndoable() const
{
return false;
}
bool Command::hasSyntax() const
{
return true;
}
MStatus Command::doIt(const MArgList& args)
{
MStatus status;
MArgDatabase argsDb(syntax(), args, &status);
if (!status)
return status;
if (argsDb.isFlagSet("-clearSubSelection"))
{
MString objectName;
argsDb.getFlagArgument("-clearSubSelection", 0, objectName);
// Return. Don't execute anything.
return clearSubSelection(objectName);
}
// Check if it's related to the sub-selection.
if (argsDb.isFlagSet("-addSubSelection"))
{
MString objectName;
MString subNodeName;
argsDb.getFlagArgument("-addSubSelection", 0, objectName);
argsDb.getFlagArgument("-addSubSelection", 1, subNodeName);
// Return. Don't execute anything.
return addSubSelection(objectName, subNodeName);
}
if (argsDb.isFlagSet("-dirAlembic"))
{
MString objectName;
MString subNodeName;
argsDb.getFlagArgument("-dirAlembic", 0, objectName);
argsDb.getFlagArgument("-dirAlembic", 1, subNodeName);
// Return. Don't execute anything else.
return dirAlembic(objectName, subNodeName);
}
if (argsDb.isFlagSet("-propsAlembic"))
{
MString objectName;
MString subNodeName;
argsDb.getFlagArgument("-propsAlembic", 0, objectName);
argsDb.getFlagArgument("-propsAlembic", 1, subNodeName);
// Return. Don't execute anything else.
return propsAlembic(objectName, subNodeName);
}
if (argsDb.isFlagSet("-getVariants"))
{
MString objectName;
MString subNodeName;
bool recursively;
argsDb.getFlagArgument("-getVariants", 0, objectName);
argsDb.getFlagArgument("-getVariants", 1, subNodeName);
argsDb.getFlagArgument("-getVariants", 2, recursively);
// Return. Don't execute anything else.
return getVariants(objectName, subNodeName, recursively);
}
if (argsDb.isFlagSet("-setVariant"))
{
MString objectName;
MString subNodeName;
MString variantName;
MString variantSetName;
argsDb.getFlagArgument("-setVariant", 0, objectName);
argsDb.getFlagArgument("-setVariant", 1, subNodeName);
argsDb.getFlagArgument("-setVariant", 2, variantName);
argsDb.getFlagArgument("-setVariant", 3, variantSetName);
// Return. Don't execute anything else.
return setVariant(
objectName, subNodeName, variantName, variantSetName);
}
if (argsDb.isFlagSet("-saveAssignment"))
{
MString objectName;
MString fileName;
argsDb.getFlagArgument("-saveAssignment", 0, objectName);
argsDb.getFlagArgument("-saveAssignment", 1, fileName);
// Return. Don't execute anything else.
if (saveAssignment(objectName, fileName))
{
return MS::kSuccess;
}
return MS::kFailure;
}
if (argsDb.isFlagSet("-saveAttributes"))
{
MString objectName;
MString fileName;
argsDb.getFlagArgument("-saveAttributes", 0, objectName);
argsDb.getFlagArgument("-saveAttributes", 1, fileName);
// Return. Don't execute anything else.
if (saveAttributes(objectName, fileName))
{
return MS::kSuccess;
}
return MS::kFailure;
}
if (argsDb.isFlagSet("-saveTransforms"))
{
MString objectName;
MString fileName;
argsDb.getFlagArgument("-saveTransforms", 0, objectName);
argsDb.getFlagArgument("-saveTransforms", 1, fileName);
MTime start = MAnimControl::minTime();
MTime end = MAnimControl::maxTime();
MTime step = 1.0 / getCurrentFPS();
if (argsDb.isFlagSet("-startTime"))
{
argsDb.getFlagArgument("-startTime", 0, start);
}
if (argsDb.isFlagSet("-endTime"))
{
argsDb.getFlagArgument("-endTime", 0, end);
}
if (argsDb.isFlagSet("-simulationRate"))
{
argsDb.getFlagArgument("-simulationRate", 0, step);
}
bool resetSessionLayer = true;
if (argsDb.isFlagSet("-resetSessionLayer"))
{
argsDb.getFlagArgument("-resetSessionLayer", 0, resetSessionLayer);
}
// Return. Don't execute anything else.
if (saveUSDTransforms(
objectName, fileName, start, end, step, resetSessionLayer))
{
return MS::kSuccess;
}
return MS::kFailure;
}
if (argsDb.isFlagSet("-savePurposes"))
{
MString objectName;
MString fileName;
argsDb.getFlagArgument("-savePurposes", 0, objectName);
argsDb.getFlagArgument("-savePurposes", 1, fileName);
// Return. Don't execute anything else.
if (savePurposes(objectName, fileName))
{
return MS::kSuccess;
}
return MS::kFailure;
}
if (argsDb.isFlagSet("-saveVariantsLayer"))
{
MString objectName;
MString fileName;
argsDb.getFlagArgument("-saveVariantsLayer", 0, objectName);
argsDb.getFlagArgument("-saveVariantsLayer", 1, fileName);
// Return. Don't execute anything else.
if (saveVariantsLayer(objectName, fileName))
{
return MS::kSuccess;
}
return MS::kFailure;
}
if (argsDb.isFlagSet("-assignmentObjects"))
{
MString objectName;
MString layer;
MString target;
argsDb.getFlagArgument("-assignmentObjects", 0, objectName);
argsDb.getFlagArgument("-assignmentObjects", 1, layer);
argsDb.getFlagArgument("-assignmentObjects", 2, target);
// Return. Don't execute anything else.
return getAssignmentObjects(
objectName, layer.asChar(), target.asChar());
}
if (argsDb.isFlagSet("-assignmentLayers"))
{
MString objectName;
argsDb.getFlagArgument("-assignmentLayers", 0, objectName);
// Return. Don't execute anything else.
return getAssignmentLayers(objectName);
}
if (argsDb.isFlagSet("-assignment"))
{
MString objectName;
MString subNodeName;
MString layer;
MString type;
argsDb.getFlagArgument("-assignment", 0, objectName);
argsDb.getFlagArgument("-assignment", 1, subNodeName);
argsDb.getFlagArgument("-assignment", 2, layer);
argsDb.getFlagArgument("-assignment", 3, type);
// Return. Don't execute anything else.
return getAssignment(objectName, subNodeName, layer, type);
}
if (argsDb.isFlagSet("-alembicAllGroups"))
{
MString objectName;
argsDb.getFlagArgument("-alembicAllGroups", 0, objectName);
// Return. Don't execute anything else.
return getAlembicAllGroups(objectName);
}
if (argsDb.isFlagSet("-alembicExpressions"))
{
MString objectName;
argsDb.getFlagArgument("-alembicExpressions", 0, objectName);
// Return. Don't execute anything else.
return getAlembicExpressions(objectName, NULL);
}
if (argsDb.isFlagSet("-alembicGroupExpressions"))
{
MString objectName;
MString groupName;
argsDb.getFlagArgument("-alembicGroupExpressions", 0, objectName);
argsDb.getFlagArgument("-alembicGroupExpressions", 1, groupName);
// Return. Don't execute anything else.
return getAlembicExpressions(objectName, &groupName);
}
if (argsDb.isFlagSet("-exposeTransform"))
{
MString objectName;
MString subObjectName;
argsDb.getFlagArgument("-exposeTransform", 0, objectName);
argsDb.getFlagArgument("-exposeTransform", 1, subObjectName);
// Return. Don't execute anything else.
return exposeTransform(objectName, subObjectName);
}
if (argsDb.isFlagSet("-detachTransform"))
{
MString objectName;
MString subObjectName;
argsDb.getFlagArgument("-detachTransform", 0, objectName);
argsDb.getFlagArgument("-detachTransform", 1, subObjectName);
// Return. Don't execute anything else.
return detachTransform(objectName, subObjectName);
}
if (argsDb.isFlagSet("-setCachedFramesDirty"))
{
MString objectName;
argsDb.getFlagArgument("-setCachedFramesDirty", 0, objectName);
setCachedFramesDirty(objectName);
// Return. Don't execute anything else.
return MS::kSuccess;
}
if (argsDb.isFlagSet("-getLayerAsString"))
{
MString objectName;
MString layerName;
argsDb.getFlagArgument("-getLayerAsString", 0, objectName);
argsDb.getFlagArgument("-getLayerAsString", 1, layerName);
getLayerAsString(objectName, layerName);
// Return. Don't execute anything else.
return MS::kSuccess;
}
if (argsDb.isFlagSet("-isPseudoRoot"))
{
MString objectName;
MString subObjectName;
argsDb.getFlagArgument("-isPseudoRoot", 0, objectName);
argsDb.getFlagArgument("-isPseudoRoot", 1, subObjectName);
return isPseudoRoot(objectName, subObjectName);
}
if (argsDb.isFlagSet("-toggleVisibility"))
{
MString objectName;
MString subObjectName;
argsDb.getFlagArgument("-toggleVisibility", 0, objectName);
argsDb.getFlagArgument("-toggleVisibility", 1, subObjectName);
return toggleVisibility(objectName, subObjectName);
}
if (argsDb.isFlagSet("-setVisibility"))
{
MString objectName;
MString subObjectName;
bool visibility;
argsDb.getFlagArgument("-setVisibility", 0, objectName);
argsDb.getFlagArgument("-setVisibility", 1, subObjectName);
argsDb.getFlagArgument("-setVisibility", 2, visibility);
return setVisibility(objectName, subObjectName, visibility);
}
if (argsDb.isFlagSet("-hideAllExceptedThis"))
{
MString objectName;
MString subObjectName;
argsDb.getFlagArgument("-hideAllExceptedThis", 0, objectName);
argsDb.getFlagArgument("-hideAllExceptedThis", 1, subObjectName);
return hideAllExceptedThis(objectName, subObjectName);
}
if (argsDb.isFlagSet("-primPathsMatchingExpression"))
{
MString objectName, expression;
argsDb.getFlagArgument("-primPathsMatchingExpression", 0, objectName);
argsDb.getFlagArgument("-primPathsMatchingExpression", 1, expression);
return primPathsMatchingExpression(objectName, expression);
}
if (argsDb.isFlagSet("-setPurpose"))
{
MString objectName, subObjectName, purpose;
argsDb.getFlagArgument("-setPurpose", 0, objectName);
argsDb.getFlagArgument("-setPurpose", 1, subObjectName);
argsDb.getFlagArgument("-setPurpose", 2, purpose);
return setPurpose(objectName, subObjectName, purpose);
}
if (argsDb.isFlagSet("-getPurpose"))
{
MString objectName, subObjectName;
argsDb.getFlagArgument("-getPurpose", 0, objectName);
argsDb.getFlagArgument("-getPurpose", 1, subObjectName);
return getPurpose(objectName, subObjectName);
}
if (argsDb.isFlagSet("-setRenderPurpose"))
{
MString objectName, purposeList;
argsDb.getFlagArgument("-setRenderPurpose", 0, objectName);
argsDb.getFlagArgument("-setRenderPurpose", 1, purposeList);
return setRenderPurpose(objectName, purposeList);
}
if (argsDb.isFlagSet("-getRenderPurpose"))
{
MString objectName;
argsDb.getFlagArgument("-getRenderPurpose", 0, objectName);
return getRenderPurpose(objectName);
}
if (argsDb.isFlagSet("-isVisible"))
{
MString objectName;
MString subObjectName;
argsDb.getFlagArgument("-isVisible", 0, objectName);
argsDb.getFlagArgument("-isVisible", 1, subObjectName);
return isVisible(objectName, subObjectName);
}
if (argsDb.isFlagSet("-export"))
{
// Looks like MArgList stores references, so we can't pass the value.
MString jobArg("-jobArg");
// Get the parameters.
MString params;
argsDb.getFlagArgument("-export", 0, params);
// Form the arguments for AbcExport.
MArgList newArgs;
newArgs.addArg(jobArg);
newArgs.addArg(params);
// Create a new instance of AbcExport.
boost::scoped_ptr<AbcExport> exportCmd(
reinterpret_cast<AbcExport*>(AbcExport::creator()));
// Run AbcExport as it's executed by Maya.
return exportCmd->doIt(newArgs);
}
if (argsDb.isFlagSet("-version"))
{
/* Return the version. It has following format: 1.2.3[ debug]. */
MString version;
version += WALTER_MAJOR_VERSION;
version += ".";
version += WALTER_MINOR_VERSION;
version += ".";
version += WALTER_PATCH_VERSION;
#ifdef DEBUG
version += " debug";
#endif
MPxCommand::setResult(version);
return MS::kSuccess;
}
if (argsDb.isFlagSet("-joinAll"))
{
WalterThreadingUtils::joinAll();
return MS::kSuccess;
}
if (argsDb.isFlagSet("-join"))
{
MString objectName;
argsDb.getFlagArgument("-join", 0, objectName);
join(objectName);
return MS::kSuccess;
}
if (argsDb.isFlagSet("-hydraPlugins"))
{
static MStringArray sHydraPlugins;
if (sHydraPlugins.length() == 0)
{
// Init the list of the plugins. All of them are initialized on
// startup, so we can reuse this array. We can compare it with 0
// because we know that there is always at least one hydra plugin.
getHydraPlugins(sHydraPlugins);
}
MPxCommand::setResult(sHydraPlugins);
return MS::kSuccess;
}
if (argsDb.isFlagSet("-expressionIsMatching"))
{
MString objectName;
MString expression;
argsDb.getFlagArgument("-expressionIsMatching", 0, objectName);
argsDb.getFlagArgument("-expressionIsMatching", 1, expression);
return expressionIsMatching(objectName, expression);
}
return status;
}
// TODO: kill?
MStatus Command::clearSubSelection(const MString& objectName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
/* Save the sub-selection to update it in the next redraw cycle. */
userNode->setSubSelectedObjects("");
return MS::kSuccess;
}
MStatus Command::addSubSelection(
const MString& objectName,
const MString& subNodeName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
userNode->setSubSelectedObjects(subNodeName);
return MS::kSuccess;
}
MStatus Command::dirAlembic(
const MString& objectName,
const MString& subNodeName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
MStringArray result;
dirUSD(userNode, subNodeName, result);
MPxCommand::setResult(result);
return MS::kSuccess;
}
MStatus Command::propsAlembic(
const MString& objectName,
const MString& subNodeName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
std::string jsonStr = "{ ";
jsonStr += "\"prim\": \"" + std::string(subNodeName.asChar()) + "\"";
MStringArray resultArray;
primVarUSD(userNode, subNodeName, resultArray);
if(resultArray.length() > 0)
{
jsonStr += ", \"properties\": [ ";
for(unsigned i=0; i<resultArray.length(); ++i)
{
jsonStr += resultArray[i].asChar();
if(i < (resultArray.length()-1))
jsonStr += ", ";
}
jsonStr += "]";
}
resultArray.clear();
assignedOverridesUSD(userNode, subNodeName, resultArray);
if(resultArray.length() > 0)
{
jsonStr += ", \"overrides\": [ ";
for(unsigned i=0; i<resultArray.length(); ++i)
{
jsonStr += resultArray[i].asChar();
if(i < (resultArray.length()-1))
jsonStr += ", ";
}
jsonStr += "]";
}
jsonStr += " }";
MPxCommand::setResult(jsonStr.c_str());
return MS::kSuccess;
}
MStatus Command::getVariants(
const MString& objectName,
const MString& subNodeName,
bool recursively) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
// RND-537: Update the variants menu when a path to a walter layer changed.
// Call this method so the variants off all the layers (for this object)
// are available. To-Do: RND-554. Investigate why we have to call joinAll,
// join should be enough
WalterThreadingUtils::joinAll();
MStringArray resultArray;
getVariantsUSD(
userNode,
subNodeName,
recursively,
resultArray);
MPxCommand::setResult(resultArray);
return MS::kSuccess;
}
MStatus Command::setVariant(
const MString& objectName,
const MString& subNodeName,
const MString& variantName,
const MString& variantSetName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
setVariantUSD(userNode, subNodeName, variantName, variantSetName);
return MS::kSuccess;
}
MStatus Command::getAssignmentObjects(
const MString& objectName,
const std::string& layer,
const std::string& target) const
{
MStatus status;
const ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
const ShapeNode::ExpMap& assignments = userNode->getAssignments();
std::set<std::string> objects;
BOOST_FOREACH (const auto& exp, assignments)
{
BOOST_FOREACH (const auto& l, exp.second)
{
if (l.first.first == layer && l.first.second == target)
{
objects.insert(exp.first);
break;
}
}
}
// Convert std::set to MStringArray
// TODO: reserve
MStringArray result;
BOOST_FOREACH (const auto& o, objects)
{
result.append(o.c_str());
}
MPxCommand::setResult(result);
return MS::kSuccess;
}
MStatus Command::getAssignmentLayers(const MString& objectName) const
{
MStatus status;
const ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
const ShapeNode::ExpMap& assignments = userNode->getAssignments();
std::set<std::string> layers;
// Get all the layers
BOOST_FOREACH (const auto& exp, assignments)
{
BOOST_FOREACH (const auto& layer, exp.second)
{
layers.insert(layer.first.first);
}
}
// Convert std::set to MStringArray
// TODO: reserve
MStringArray result;
BOOST_FOREACH (const auto& l, layers)
{
result.append(l.c_str());
}
MPxCommand::setResult(result);
return MS::kSuccess;
}
MStatus Command::getAssignment(
const MString& objectName,
const MString& subNodeName,
const MString& layer,
const MString& type) const
{
MStatus status;
const ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
const ShapeNode::ExpMap& assignments = userNode->getAssignments();
ShapeNode::ExpMap::const_iterator layersIt =
assignments.find(subNodeName.asChar());
MString shader;
if (layersIt != assignments.end())
{
ShapeNode::LayerMap::const_iterator shaderIt = layersIt->second.find(
ShapeNode::LayerKey(layer.asChar(), type.asChar()));
if (shaderIt != layersIt->second.end())
{
shader = shaderIt->second.c_str();
}
}
MPxCommand::setResult(shader);
return MS::kSuccess;
}
MStatus Command::getAlembicAllGroups(const MString& objectName) const
{
MStatus status;
const ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
std::set<std::string> groups;
for (const auto& group : userNode->getGroups())
{
if (!group.second.empty())
{
groups.insert(group.second);
}
}
// Convert std::set to MStringArray
// TODO: reserve
MStringArray result;
BOOST_FOREACH (const auto& group, groups)
{
result.append(group.c_str());
}
MPxCommand::setResult(result);
return MS::kSuccess;
}
MStatus Command::getAlembicExpressions(
const MString& objectName,
const MString* groupName) const
{
MStatus status;
const ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
std::set<std::string> expressions;
// We are going to compare std::string, we need to compare it with the same
// type.
std::string groupNameStr(groupName ? groupName->asChar() : "");
for (const auto& group : userNode->getGroups())
{
if (!groupName || group.second == groupNameStr)
{
expressions.insert(group.first);
}
}
// Convert std::set to MStringArray
// TODO: reserve
MStringArray result;
BOOST_FOREACH (const auto& expression, expressions)
{
result.append(expression.c_str());
}
MPxCommand::setResult(result);
return MS::kSuccess;
}
MStatus Command::exposeTransform(
const MString& objectName,
const MString& subObjectName) const
{
MStatus status;
const ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
MObject node = userNode->thisMObject();
MFnDagNode dagNode(node);
std::unordered_map<std::string, MPlug> plugCache;
const MPlug transformsPlug(node, ShapeNode::aTransforms);
// We can't remove the elements from the middle of the plug array. Instead,
// we can reuse plugs that are not connected to anything. To reuse them,
// it's necessary to seve the list of them.
std::vector<std::pair<const MPlug, const MPlug>> availablePlugs;
assert(!transformsPlug.isNull());
for (int i = 0, n = transformsPlug.numElements(); i < n; i++)
{
const MPlug element = transformsPlug.elementByPhysicalIndex(i);
const MPlug objectPlug = element.child(ShapeNode::aTransformsObject);
const MPlug matrixPlug = element.child(ShapeNode::aTransformsMatrix);
const MString currentSubObjectName = objectPlug.asString();
if (currentSubObjectName.length() == 0 || !matrixPlug.isConnected())
{
availablePlugs.push_back(std::make_pair(objectPlug, matrixPlug));
continue;
}
// Emplace to avoid overwriting if it already exists.
plugCache.emplace(currentSubObjectName.asChar(), matrixPlug);
}
// Split the sub object name so we have all the parents in the vector.
// TODO: it's better to use SdfPath but I don't want to include pixar stuff
// here, so for now it's boost::split and boost::join.
std::vector<std::string> path, pathres;
const std::string subObjectNameStr = subObjectName.asChar();
boost::split(path, subObjectNameStr, boost::is_any_of("/"));
boost::split(pathres, subObjectNameStr, boost::is_any_of("/"));
// Looking if we already have a transform connected to this sub-object or to
// its parents. We are looking starting from the full object name and each
// iteration we go to its parent. At the same time we save all the objects
// to pathChildren, so at the end we have the list of objects we need to
// create.
std::string firstParentObjectName;
MPlug* firstParentPlug = NULL;
std::vector<std::string> pathChildren;
while (true)
{
firstParentObjectName = boost::algorithm::join(path, "/");
if (firstParentObjectName.empty())
{
// Nothing is found.
break;
}
auto found = plugCache.find(firstParentObjectName);
if (found != plugCache.end())
{
// Found.
firstParentPlug = &(found->second);
break;
}
pathChildren.push_back(path.back());
path.pop_back();
}
std::string currentObjectFullName = firstParentObjectName;
MObject parent;
if (firstParentPlug && firstParentPlug->isConnected())
{
// We found that we already have the connection to a parent of the
// requested sub-object. All the created transforms should be the
// children of this connection.
MPlugArray connectedTo;
firstParentPlug->connectedTo(connectedTo, true, false);
parent = connectedTo[0].node();
}
else
{
// Nothing is found. We can create all the transforms as children of
// current walter standin.
parent = dagNode.parent(0);
}
// Dependency graph modifier.
MDagModifier mod;
MFnDagNode standinNode(parent);
std::string currentObjectFullMayaName = std::string(standinNode.fullPathName().asChar());
// Create the transforms.
while (!pathChildren.empty())
{
MFnDagNode standinNode(parent);
const std::string& currentObjectName = pathChildren.back();
currentObjectFullName += "/" + currentObjectName;
currentObjectFullMayaName += "|" + currentObjectName;
MObject locatorTransform;
MObject locator;
int tmp = standinNode.childCount();
for(uint32_t i = tmp; i--;) {
auto transformObj = standinNode.child(i);
MFnDagNode transformDagNode(transformObj);
if(transformDagNode.fullPathName().asChar() == currentObjectFullMayaName) {
locator = transformDagNode.child(0);
locatorTransform = transformObj;
break;
}
}
// Create a locator node and parent it to the transform.
if(locatorTransform.isNull())
locatorTransform = mod.createNode("transform", parent);
if(locator.isNull())
locator = mod.createNode("locator", locatorTransform);
MFnDependencyNode locatorDepNode(locatorTransform);
const MPlug matrix = locatorDepNode.findPlug("matrix");
parent = locatorTransform;
MPlug objectPlug;
MPlug matrixPlug;
if (availablePlugs.empty())
{
// No available plugs. Create new.
MPlug ancestor = transformsPlug;
ancestor.selectAncestorLogicalIndex(
ancestor.numElements(), ShapeNode::aTransforms);
objectPlug = ancestor.child(ShapeNode::aTransformsObject);
matrixPlug = ancestor.child(ShapeNode::aTransformsMatrix);
}
else
{
// Reuse existing plugs.
objectPlug = availablePlugs.back().first;
matrixPlug = availablePlugs.back().second;
availablePlugs.pop_back();
}
// Set transformation from USD stage.
MFnTransform locatorFnTransform(locatorTransform);
double transform[4][4];
if (getUSDTransform(
node,
currentObjectFullName,
userNode->time * getCurrentFPS(),
transform))
{
locatorFnTransform.set(MTransformationMatrix(MMatrix(transform)));
}
MString currentObjectFullNameStr(currentObjectFullName.c_str());
// Set object name.
objectPlug.setString(currentObjectFullNameStr);
locatorDepNode.setName(currentObjectName.c_str());
// Create a string attribute on the locator to store the
// full path of the USD prim the locator points to.
MFnStringData stringFn;
MFnTypedAttribute typedAttribute;
MObject pathObject = stringFn.create(currentObjectFullName.c_str());
MObject pathAttribute = typedAttribute.create(
LOCATOR_ATTR_PRIM_PATH,
LOCATOR_ATTR_PRIM_PATH,
MFnData::kString,
pathObject);
typedAttribute.setStorable(true);
locatorDepNode.addAttribute(pathAttribute);
// TODO: Disconnect if connected.
mod.connect(matrix, matrixPlug);
mod.doIt();
pathChildren.pop_back();
}
MStringArray result;
std::string currentObjectFullNameRes;
// Skip the first element since it's emnpty
for(int i=1; i<pathres.size(); ++i) {
std::string p = pathres[i];
currentObjectFullNameRes += "/" + p;
result.append(currentObjectFullNameRes.c_str());
result.append(p.c_str());
}
MPxCommand::setResult(result);
return MS::kSuccess;
}
MStatus Command::detachTransform(
const MString& objectName,
const MString& subObjectName) const
{
MStatus status;
auto* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
auto node = userNode->thisMObject();
MDagModifier modifier;
std::unordered_map<std::string, MPlug> plugCache;
const MPlug transformsPlug2(node, ShapeNode::aTransforms);
// We can't remove the elements from the middle of the plug array. Instead,
// we can reuse plugs that are not connected to anything. To reuse them,
// it's necessary to seve the list of them.
std::vector<std::pair<const MPlug, const MPlug>> availablePlugs;
assert(!transformsPlug2.isNull());
for (int i = 0, n = transformsPlug2.numElements(); i < n; i++)
{
const MPlug element = transformsPlug2.elementByPhysicalIndex(i);
const MPlug objectPlug = element.child(ShapeNode::aTransformsObject);
const MPlug matrixPlug = element.child(ShapeNode::aTransformsMatrix);
const MString currentSubObjectName = objectPlug.asString();
if (currentSubObjectName.length() == 0 || !matrixPlug.isConnected())
{
availablePlugs.push_back(std::make_pair(objectPlug, matrixPlug));
continue;
}
// Emplace to avoid overwriting if it already exists.
plugCache.emplace(currentSubObjectName.asChar(), matrixPlug);
}
// Split the sub object name so we have all the parents in the vector.
// TODO: it's better to use SdfPath but I don't want to include pixar stuff
// here, so for now it's boost::split and boost::join.
std::vector<std::string> path, pathres;
const std::string subObjectNameStr = subObjectName.asChar();
boost::split(path, subObjectNameStr, boost::is_any_of("/"));
boost::split(pathres, subObjectNameStr, boost::is_any_of("/"));
// Looking if we already have a transform connected to this sub-object or to
// its parents. We are looking starting from the full object name and each
// iteration we go to its parent. At the same time we save all the objects
// to pathChildren, so at the end we have the list of objects we need to
// create.
std::string firstParentObjectName;
MPlug* firstParentPlug = NULL;
std::vector<std::string> pathChildren;
while (true)
{
firstParentObjectName = boost::algorithm::join(path, "/");
if (firstParentObjectName.empty())
{
// Nothing is found.
break;
}
auto found = plugCache.find(firstParentObjectName);
if (found != plugCache.end())
{
// Found.
firstParentPlug = &(found->second);
break;
}
pathChildren.push_back(path.back());
path.pop_back();
break;
}
std::string currentObjectFullName = firstParentObjectName;
MObject parent;
if (firstParentPlug)
{
// We found that we already have the connection to a parent of the
// requested sub-object. All the created transforms should be the
// children of this connection.
MPlugArray connectedTo;
firstParentPlug->connectedTo(connectedTo, true, true);
parent = connectedTo[0].node();
modifier.deleteNode(parent);
}
modifier.doIt();
::resetUSDTransforms(userNode, subObjectName);
return MS::kSuccess;
}
MStatus Command::setCachedFramesDirty(const MString& objectName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
// Set animation caches dirty.
userNode->setCachedFramesDirty();
// Recreate the viewport materials.
processGLSLShaders(userNode);
return MS::kSuccess;
}
MStatus Command::getLayerAsString(
const MString& objectName,
const MString& layerName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
MString layer = ::getLayerAsString(userNode, layerName);
MPxCommand::setResult(layer);
return MS::kSuccess;
}
MStatus Command::join(const MString& objectName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
// This will call onLoaded if it was never called.
userNode->getRenderer();
return MS::kSuccess;
}
MStatus Command::expressionIsMatching(
const MString& objectName,
const MString& expression) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
{
return status;
}
MPxCommand::setResult(
userNode->expressionIsMatching(expression));
return MS::kSuccess;
}
MStatus Command::isPseudoRoot(
const MString& objectName,
const MString& subObjectName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
return status;
MPxCommand::setResult(::isPseudoRoot(
userNode, subObjectName));
return MS::kSuccess;
}
MStatus Command::isVisible(
const MString& objectName,
const MString& subObjectName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
return status;
MPxCommand::setResult(::isVisible(
userNode, subObjectName));
return MS::kSuccess;
}
MStatus Command::toggleVisibility(
const MString& objectName,
const MString& subObjectName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
return status;
MPxCommand::setResult(::toggleVisibility(
userNode, subObjectName));
return MS::kSuccess;
}
MStatus Command::setVisibility(
const MString& objectName,
const MString& subObjectName,
bool visibility) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
return status;
MPxCommand::setResult(::setVisibility(
userNode, subObjectName, visibility));
return MS::kSuccess;
}
MStatus Command::hideAllExceptedThis(
const MString& objectName,
const MString& subObjectName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
return status;
MPxCommand::setResult(::hideAllExceptedThis(
userNode, subObjectName));
return MS::kSuccess;
}
MStatus Command::primPathsMatchingExpression(
const MString& objectName,
const MString& expression) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
return status;
MPxCommand::setResult(::primPathsMatchingExpression(
userNode, expression));
return MS::kSuccess;
}
MStatus Command::setPurpose(
const MString& objectName,
const MString& subObjectName,
const MString& purpose) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
return status;
MPxCommand::setResult(::setPurpose(
userNode, subObjectName, purpose));
return MS::kSuccess;
}
MStatus Command::getPurpose(
const MString& objectName,
const MString& subObjectName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
return status;
MPxCommand::setResult(::getPurpose(
userNode, subObjectName));
return MS::kSuccess;
}
MStatus Command::setRenderPurpose(
const MString& objectName,
const MString& purposeList) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
return status;
std::string tmp = purposeList.asChar();
std::vector<std::string> path;
boost::split(path, tmp, boost::is_any_of(":"));
MStringArray purposeArray;
for(auto const& strPurpose: path)
purposeArray.append(strPurpose.c_str());
::setRenderPurpose(userNode, purposeArray);
return MS::kSuccess;
}
MStatus Command::getRenderPurpose(
const MString& objectName) const
{
MStatus status;
ShapeNode* userNode = getShapeNode(objectName, &status);
if (!userNode)
return status;
MPxCommand::setResult(::getRenderPurpose(userNode));
return MS::kSuccess;
}
}
<|start_filename|>walter/houdini/src/GU_WalterPackedImpl.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "GU_WalterPackedImpl.h"
#include "walterHoudiniUtils.h"
#include "UsdToGtPrim.h"
#include <FS/UT_DSO.h>
#include <GT/GT_Primitive.h>
#include <GT/GT_RefineParms.h>
#include <GT/GT_Util.h>
#include <GU/GU_PackedFactory.h>
#include <GU/GU_PrimPacked.h>
#include <UT/UT_MemoryCounter.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usdGeom/curves.h>
#include <pxr/usd/usdGeom/imageable.h>
#include <pxr/usd/usdGeom/mesh.h>
PXR_NAMESPACE_USING_DIRECTIVE
namespace WalterHoudini
{
const UT_StringRef GU_WalterPackedImpl::usdFileName = "usdFileName";
const UT_StringRef GU_WalterPackedImpl::usdFrame = "usdFrame";
const UT_StringRef GU_WalterPackedImpl::usdPrimPath = "usdPrimPath";
const UT_StringRef GU_WalterPackedImpl::rendererName = "hdRendererName";
static bool IsSupportedPrim(const UsdPrim& prim)
{
if (!prim || !prim.IsA<UsdGeomImageable>())
{
return false;
}
return prim.IsA<UsdGeomMesh>() || prim.IsA<UsdGeomCurves>();
}
class WalterFactory : public GU_PackedFactory
{
public:
WalterFactory() : GU_PackedFactory("PackedWalter", "Packed Walter")
{
registerIntrinsic(
GU_WalterPackedImpl::usdFileName,
StringHolderGetterCast(&GU_WalterPackedImpl::intrinsicFileName),
StringHolderSetterCast(&GU_WalterPackedImpl::setFileName));
registerIntrinsic(
GU_WalterPackedImpl::usdPrimPath,
StringHolderGetterCast(&GU_WalterPackedImpl::intrinsicPrimPath),
StringHolderSetterCast(&GU_WalterPackedImpl::setPrimPath));
registerIntrinsic(
GU_WalterPackedImpl::usdFrame,
FloatGetterCast(&GU_WalterPackedImpl::intrinsicFrame),
FloatSetterCast(&GU_WalterPackedImpl::setFrame));
registerIntrinsic(
GU_WalterPackedImpl::rendererName,
StringHolderGetterCast(&GU_WalterPackedImpl::intrinsicRendererName),
StringHolderSetterCast(&GU_WalterPackedImpl::setRendererName));
}
virtual ~WalterFactory()
{}
virtual GU_PackedImpl* create() const
{
return new GU_WalterPackedImpl();
}
};
static WalterFactory* theFactory = NULL;
static UT_Lock theLock;
GA_PrimitiveTypeId GU_WalterPackedImpl::theTypeId(-1);
GU_WalterPackedImpl::GU_WalterPackedImpl() : GU_PackedImpl(), mDetail()
{}
GU_WalterPackedImpl::GU_WalterPackedImpl(const GU_WalterPackedImpl& src) :
GU_PackedImpl(src),
mDetail()
{
setFileName(src.intrinsicFileName());
setPrimPath(src.intrinsicPrimPath());
setFrame(src.intrinsicFrame());
setRendererName(src.intrinsicRendererName());
}
GU_WalterPackedImpl::~GU_WalterPackedImpl()
{
clearWalter();
}
void GU_WalterPackedImpl::install(GA_PrimitiveFactory* gafactory)
{
UT_ASSERT(!theFactory);
if (theFactory)
return;
theFactory = new WalterFactory();
GU_PrimPacked::registerPacked(gafactory, theFactory);
if (theFactory->isRegistered())
{
theTypeId = theFactory->typeDef().getId();
}
else
{
fprintf(
stderr,
"[WALTER]: Unable to register packed Walter from %s\n",
UT_DSO::getRunningFile());
}
}
void GU_WalterPackedImpl::clearWalter()
{
mDetail = GU_ConstDetailHandle();
}
GU_PackedFactory* GU_WalterPackedImpl::getFactory() const
{
return theFactory;
}
GU_PackedImpl* GU_WalterPackedImpl::copy() const
{
return new GU_WalterPackedImpl(*this);
}
void GU_WalterPackedImpl::clearData()
{
// This method is called when primitives are "stashed" during the cooking
// process. However, primitives are typically immediately "unstashed" or
// they are deleted if the primitives aren't recreated after the fact. We
// can just leave our data.
}
bool GU_WalterPackedImpl::isValid() const
{
return detail().isValid();
}
template <typename T> void GU_WalterPackedImpl::updateFrom(const T& options)
{
UT_StringHolder sval;
if (import(options, GU_WalterPackedImpl::usdFileName, sval))
{
setFileName(sval);
}
if (import(options, GU_WalterPackedImpl::usdPrimPath, sval))
{
setPrimPath(sval);
}
fpreal fval;
if (import(options, GU_WalterPackedImpl::usdFrame, fval))
{
setFrame(fval);
}
if (import(options, GU_WalterPackedImpl::rendererName, sval))
{
setRendererName(sval);
}
}
bool GU_WalterPackedImpl::save(UT_Options& options, const GA_SaveMap& map) const
{
options.setOptionS(GU_WalterPackedImpl::usdFileName, intrinsicFileName());
options.setOptionF(GU_WalterPackedImpl::usdFrame, intrinsicFrame());
options.setOptionS(GU_WalterPackedImpl::usdPrimPath, intrinsicPrimPath());
options.setOptionS(GU_WalterPackedImpl::rendererName, intrinsicRendererName());
return true;
}
bool GU_WalterPackedImpl::getBounds(UT_BoundingBox& box) const
{
// All spheres are unit spheres with transforms applied
box.initBounds(-1, -1, -1);
box.enlargeBounds(1, 1, 1);
// TODO: If computing the bounding box is expensive, you may want to cache
// the box by calling SYSconst_cast(this)->setBoxCache(box);
return true;
}
bool GU_WalterPackedImpl::getRenderingBounds(UT_BoundingBox& box) const
{
// When geometry contains points or curves, the width attributes need to be
// taken into account when computing the rendering bounds.
return getBounds(box);
}
void GU_WalterPackedImpl::getVelocityRange(
UT_Vector3& minVelocity,
UT_Vector3& maxVelocity) const
{
// No velocity attribute on geometry
minVelocity = 0;
maxVelocity = 0;
}
void GU_WalterPackedImpl::getWidthRange(fpreal& min, fpreal& max) const
{
min = max = 0; // Width is only important for curves/points.
}
bool GU_WalterPackedImpl::unpack(GU_Detail& destgdp) const
{
// This may allocate geometry for the primitive
GU_DetailHandleAutoReadLock rlock(getPackedDetail());
if (!rlock.getGdp())
{
return false;
}
return unpackToDetail(destgdp, rlock.getGdp());
}
bool GU_WalterPackedImpl::unpackWithContext(
GU_Detail& destgdp,
GU_PackedContext& context) const
{
UsdStageRefPtr stage =
WalterHoudiniUtils::getStage(intrinsicFileName().toStdString());
if (!stage)
{
return GU_PackedImpl::unpackWithContext(destgdp, context);
}
UsdTimeCode time(intrinsicFrame());
UsdPrim root;
if (intrinsicPrimPath().length() > 0)
{
root = stage->GetPrimAtPath(SdfPath(intrinsicPrimPath().toStdString()));
}
else
{
root = stage->GetPseudoRoot();
}
UsdPrimRange range(root);
for (const UsdPrim& prim : range)
{
if (!IsSupportedPrim(prim))
{
continue;
}
// Create a list of geometry details for a single GT primitive. Each
// refined primitive is stored in a separate detail.
UT_Array<GU_Detail*> details;
GT_PrimitiveHandle gtPrim =
WalterHoudini::getGtPrimFromUsd(prim, time);
UsdGeomImageable imageable(prim);
GfMatrix4d gfMatrix = imageable.ComputeLocalToWorldTransform(time);
UT_Matrix4D utMatrix =
WalterHoudiniUtils::MatrixConvert<UT_Matrix4D>(gfMatrix);
// New because it requres GT_TransformHandle. So no need to delete.
gtPrim->setPrimitiveTransform(new GT_Transform(&utMatrix, 1));
GT_RefineParms rparms;
// Need to manually force polysoup to be turned off.
rparms.setAllowPolySoup(false);
rparms.set("usd:primvarPattern", "*");
GA_Size startIndex = destgdp.getNumPrimitives();
GT_Util::makeGEO(details, gtPrim, &rparms);
for (GU_Detail* detail : details)
{
unpackToDetail(destgdp, detail, true);
// These details must be deleted by the caller.
delete detail;
}
// Add usdpath and usdprimpath attributes to unpacked geometry.
GA_Size endIndex = destgdp.getNumPrimitives();
const char* path = prim.GetPrim().GetPath().GetString().c_str();
if (endIndex > startIndex)
{
GA_RWHandleS primPathAttr(destgdp.addStringTuple(
GA_ATTRIB_PRIMITIVE, "usdprimpath", 1));
GA_RWHandleS pathAttr(
destgdp.addStringTuple(GA_ATTRIB_PRIMITIVE, "usdpath", 1));
for (GA_Size i = startIndex; i < endIndex; ++i)
{
primPathAttr.set(destgdp.primitiveOffset(i), 0, path);
pathAttr.set(
destgdp.primitiveOffset(i), 0, intrinsicFileName().c_str());
}
}
}
return true;
}
int64 GU_WalterPackedImpl::getMemoryUsage(bool inclusive) const
{
int64 mem = inclusive ? sizeof(*this) : 0;
// Don't count the (shared) GU_Detail, since that will greatly
// over-estimate the overall memory usage.
mem += detail().getMemoryUsage(false);
return mem;
}
void GU_WalterPackedImpl::countMemory(
UT_MemoryCounter& memoryCounter,
bool inclusiveUsage) const
{
if (memoryCounter.mustCountUnshared())
{
size_t mem = inclusiveUsage ? sizeof(*this) : 0;
mem += detail().getMemoryUsage(false);
UT_MEMORY_DEBUG_LOG("GU_WalterPackedImpl", int64(mem));
memoryCounter.countUnshared(mem);
}
}
GU_PrimPacked* GU_WalterPackedImpl::build(
GU_Detail& gdp,
const std::string& fileName,
const std::string& primPath,
const std::string& rendererName,
fpreal frame)
{
GA_Primitive* prim = gdp.appendPrimitive(theFactory->typeDef().getId());
// Note: The primitive is invalid until you do something like
// prim->setVertexPoint(gdp.appendPointOffset());
GU_PrimPacked* pack = UTverify_cast<GU_PrimPacked*>(prim);
// Cast it to Walter.
GU_WalterPackedImpl* walter =
UTverify_cast<GU_WalterPackedImpl*>(pack->implementation());
walter->setFileName(fileName);
walter->setPrimPath(primPath);
walter->setRendererName(rendererName);
walter->setFrame(frame);
return pack;
}
void GU_WalterPackedImpl::setFileName(const UT_StringHolder& v)
{
if (mFileName != v)
{
mFileName = v;
// TODO: Clear cache, make dirty.
}
}
void GU_WalterPackedImpl::setPrimPath(const UT_StringHolder& v)
{
if (mPrimPath != v)
{
mPrimPath = v;
// TODO: Clear cache, make dirty.
}
}
void GU_WalterPackedImpl::setFrame(fpreal frame)
{
if (frame != mFrame)
{
mFrame = frame;
// TODO: Reset cache, make dirty, update transforms.
}
}
void GU_WalterPackedImpl::setRendererName(const UT_StringHolder& v)
{
if (mRendererName != v)
{
mRendererName = v;
// TODO: Clear cache, make dirty.
}
}
void GU_WalterPackedImpl::update(const UT_Options& options)
{
updateFrom(options);
}
bool GU_WalterPackedImpl::load(
GU_PrimPacked* prim,
const UT_Options& options,
const GA_LoadMap&)
{
// Loading Walter is simple, we can just update the parameters.
updateFrom(options);
return true;
}
} // end namespace WalterHoudini
<|start_filename|>walter/katana/WalterIn/FaceSetCook.cpp<|end_filename|>
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ScalarPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
void cookFaceset(AbcCookPtr ioCook, FnAttribute::GroupBuilder & oStaticGb)
{
Alembic::AbcGeom::IFaceSetPtr objPtr(
new Alembic::AbcGeom::IFaceSet(*(ioCook->objPtr),
Alembic::AbcGeom::kWrapExisting));
Alembic::AbcGeom::IFaceSetSchema schema = objPtr->getSchema();
Alembic::Abc::ICompoundProperty userProp = schema.getUserProperties();
Alembic::Abc::ICompoundProperty arbGeom = schema.getArbGeomParams();
std::string abcUser = "abcUser.";
processUserProperties(ioCook, userProp, oStaticGb, abcUser);
processArbGeomParams(ioCook, arbGeom, oStaticGb);
oStaticGb.set("type", FnAttribute::StringAttribute("faceset"));
// IFaceSetSchema doesn't expose this yet
const Alembic::AbcCoreAbstract::PropertyHeader * propHeader =
schema.getPropertyHeader(".faces");
if (propHeader != NULL)
{
arrayPropertyToAttr(schema, *propHeader, "geometry.faces",
kFnKatAttributeTypeInt, ioCook, oStaticGb);
}
}
}
<|start_filename|>walter/katana/WalterIn/walterUSDOpIndex.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERUSDOPINDEX_H_
#define __WALTERUSDOPINDEX_H_
#include <pxr/usd/sdf/path.h>
#include <boost/noncopyable.hpp>
#include "PathUtil.h"
#include "schemas/expression.h"
PXR_NAMESPACE_USING_DIRECTIVE
class OpDelegate;
// custom specialization of std::hash for SdfPath
namespace std
{
template <> struct hash<SdfPath>
{
typedef SdfPath argument_type;
typedef std::size_t result_type;
result_type operator()(argument_type const& path) const noexcept
{
return SdfPath::Hash{}(path);
}
};
}
namespace OpCaboose
{
class ClientAttribute;
// TODO: get rid of double definition
typedef std::shared_ptr<ClientAttribute> ClientAttributePtr;
}
/** @brief It should contain material assignments and the stuff that we would
* like to cache to use in the future. */
class OpIndex : private boost::noncopyable
{
private:
template <typename K, typename T> using hashmap = std::unordered_map<K, T>;
public:
typedef hashmap<std::string, OpCaboose::ClientAttributePtr> NameToAttribute;
OpIndex();
/**
* @brief Resolve the assigned shader using expressions. The difference with
* resolveMaterialAssignment is this method caches the result and if it was
* resolved previously, it returns cached path. resolveMaterialAssignment
* resolves it each time.
*
* @param objectName The full name of the object in USD.
* @param target "shader", "displacement", "attribute"
*
* @return The path of the assigned material.
*/
const SdfPath& getMaterialAssignment(
const SdfPath& objectPath,
const std::string& target) const;
/**
* @brief Returns attributes of specified path.
*
* @param iOverridePath Path to walterOverride object.
*
* @return {"attribute name": pointer to attribute}
*/
const NameToAttribute* getAttributes(SdfPath iOverridePath) const;
private:
friend class OpDelegate;
// Building following structure:
// {"target": {"object": "material"}}
// In Katana and Maya, we need to get the material only if the material is
// really assigned to the object and we don't consider inheritance. But here
// we need to consider inheritance, so we need layer and target at the first
// layer for fast and easy extracting {"object": "material"} because we need
// to ignore if it's another target or material is assigned in another
// render layer.
typedef std::map<WalterCommon::Expression, SdfPath> ExprToMat;
typedef hashmap<std::string, ExprToMat> Assignments;
typedef hashmap<SdfPath, SdfPath> ObjectToShader;
typedef hashmap<std::string, ObjectToShader> ResolvedAssignments;
typedef hashmap<SdfPath, NameToAttribute> Attributes;
/**
* @brief Save the expression to the index.
*
* @param iExpression "/pCube1/pCube2/.*"
* @param iLayers The structure like this: {"layer": {"target":
* "material"}}.
*/
void insertExpression(
const std::string& iExpression,
const WalterExpression::AssignmentLayers& iLayers);
/**
* @brief Resolve the assigned shader using expressions.
*
* @param iObjectName The full name of the object in USD.
* @param iTarget "shader", "displacement", "attribute"
*
* @return The path of the assigned material.
*/
SdfPath resolveMaterialAssignment(
const std::string& iObjectName,
const std::string& iTarget) const;
/**
* @brief Save Walter Override's single attribute.
*
* @param iOverridePath Walter Override.
* @param iAttributeName Attribute name.
* @param iAttribute The attribute.
*/
void insertAttribute(
const SdfPath& iOverridePath,
const std::string& iAttributeName,
const OpCaboose::ClientAttributePtr& iAttribute);
typedef std::mutex Mutex;
typedef std::lock_guard<Mutex> ScopedLock;
mutable Mutex mMutex;
// All the assignments of the cache. We don't need TBB here because we fill
// it from OpDelegate::populate, when OpEngine is constructed.
Assignments mAssignments;
// The assignments that was already resolved. We need it for fast access.
// TODO: TBB
mutable ResolvedAssignments mResolvedAssignments;
// Walter Overrides to Attributes
Attributes mAttributes;
};
#endif
<|start_filename|>walter/usd/fileFormat/usdArnold/arnoldTranslator.h<|end_filename|>
// Copyright 2018 <NAME>. All rights reserved.
#ifndef __ARNOLDTRANSLATOR_H__
#define __ARNOLDTRANSLATOR_H__
#include <pxr/usd/sdf/layer.h>
PXR_NAMESPACE_OPEN_SCOPE
namespace ArnoldUSDTranslator
{
/**
* @brief Convert ass file to SdfLayer.
*
* @param iFile Full file name.
*
* @return The pointer to the created layer.
*/
SdfLayerRefPtr arnoldToUsdLayer(const std::string& iFile);
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif
<|start_filename|>walter/katana/WalterIn/PointsCook.cpp<|end_filename|>
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ScalarPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
void cookPoints(AbcCookPtr ioCook, FnAttribute::GroupBuilder & oStaticGb)
{
Alembic::AbcGeom::IPointsPtr objPtr(
new Alembic::AbcGeom::IPoints(*(ioCook->objPtr),
Alembic::AbcGeom::kWrapExisting));
Alembic::AbcGeom::IPointsSchema schema = objPtr->getSchema();
oStaticGb.set("type", FnAttribute::StringAttribute("pointcloud"));
Alembic::Abc::IUInt64ArrayProperty idsProp = schema.getIdsProperty();
Alembic::Abc::IUInt64ArrayProperty *idsPropPtr = NULL;
if (idsProp.valid())
{
arrayPropertyToAttr(schema, idsProp.getHeader(),
"geometry.point.id", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
idsPropPtr = &idsProp;
}
Alembic::Abc::ICompoundProperty userProp = schema.getUserProperties();
Alembic::Abc::ICompoundProperty arbGeom = schema.getArbGeomParams();
std::string abcUser = "abcUser.";
processUserProperties(ioCook, userProp, oStaticGb, abcUser, nullptr, idsPropPtr);
processArbGeomParams(ioCook, arbGeom, oStaticGb, idsPropPtr);
Alembic::Abc::IP3fArrayProperty pointsProp =
schema.getPositionsProperty();
if (pointsProp.valid())
{
arrayPropertyToAttr(schema, pointsProp.getHeader(),
"geometry.point.P", kFnKatAttributeTypeFloat,
ioCook, oStaticGb, idsPropPtr);
}
Alembic::Abc::IV3fArrayProperty velocProp =
schema.getVelocitiesProperty();
if (velocProp.valid())
{
arrayPropertyToAttr(schema, velocProp.getHeader(),
"geometry.point.v", kFnKatAttributeTypeFloat,
ioCook, oStaticGb, idsPropPtr);
}
Alembic::Abc::IBox3dProperty boundsProp =
schema.getSelfBoundsProperty();
if (boundsProp.valid())
{
scalarPropertyToAttr(schema, boundsProp.getHeader(),
"bound", ioCook, oStaticGb);
}
Alembic::AbcGeom::IFloatGeomParam widthProp = schema.getWidthsParam();
if (widthProp.valid())
{
Alembic::AbcGeom::GeometryScope scope = widthProp.getScope();
std::string widthName = "geometry.point.";
if (scope == Alembic::AbcGeom::kVertexScope)
{
widthName += "width";
}
else
{
widthName += "constantwidth";
}
processArbitraryGeomParam(ioCook, schema, widthProp.getHeader(),
oStaticGb, widthName, idsPropPtr);
}
}
} //end of namespace WalterIn
<|start_filename|>walter/common/abcshaderutils.cpp<|end_filename|>
#include "abcshaderutils.h"
#include <boost/algorithm/string.hpp>
#include "PathUtil.h"
void setUserParameter(AtNode* source, std::string interfaceName, Alembic::AbcCoreAbstract::PropertyHeader header, AtNode* node, std::map<std::string, std::string> remapping)
{
if (Abc::IFloatProperty::matches(header))
{
// float type
AiNodeSetFlt(node, header.getName().c_str(), AiNodeGetFlt(source, interfaceName.c_str()));
}
else if (Abc::IInt32Property::matches(header))
{
// int type
AiNodeSetInt(node, header.getName().c_str(), AiNodeGetInt(source, interfaceName.c_str()));
}
else if (Abc::IUInt32Property::matches(header))
{
// Uint type
AiNodeSetUInt(node, header.getName().c_str(), AiNodeGetUInt(source, interfaceName.c_str()));
}
else if (Abc::IBoolProperty::matches(header))
{
// bool type
AiNodeSetBool(node, header.getName().c_str(), AiNodeGetBool(source, interfaceName.c_str()));
}
else if (Abc::IStringProperty::matches(header))
{
// string type
std::string value = AiNodeGetStr(source, interfaceName.c_str());
value = WalterCommon::demangleString(value);
for (std::map<std::string,std::string>::iterator it=remapping.begin(); it!=remapping.end(); ++it)
value = boost::replace_all_copy(value, it->first, it->second);
AiNodeSetStr(node, header.getName().c_str(), value.c_str());
}
else if (Abc::IP3fProperty::matches(header))
{
// point type
// We don't really have point type in maya, so the source is a vector.
AtVector val = AiNodeGetVec(source, interfaceName.c_str());
AiNodeSetPnt(node, header.getName().c_str(), val.x, val.y, val.z);
}
else if (Abc::IV3fProperty::matches(header))
{
// vector type
AtVector val = AiNodeGetVec(source, interfaceName.c_str());
AiNodeSetVec(node, header.getName().c_str(), val.x, val.y, val.z);
}
else if (Abc::IC3fProperty::matches(header))
{
// color type
AtColor val = AiNodeGetRGB(source, interfaceName.c_str());
AiNodeSetRGB(node, header.getName().c_str(), val.r, val.g, val.b);
}
}
void setArrayParameter(Alembic::Abc::ICompoundProperty props, Alembic::AbcCoreAbstract::PropertyHeader header, AtNode* node, std::map<std::string, std::string> remapping)
{
AtArray *arrayValues;
if (Abc::IFloatArrayProperty::matches(header))
{
// float type
Abc::FloatArraySamplePtr samp;
Abc::IFloatArrayProperty prop(props, header.getName());
if (prop.valid())
{
size_t numSamples = prop.getNumSamples();
if (numSamples > 0)
{
prop.get( samp, Alembic::Abc::ISampleSelector((Alembic::Abc::index_t)0) );
arrayValues = AiArrayAllocate(samp->size(), numSamples, AI_TYPE_FLOAT);
for (unsigned int i = 0; i < samp->size(); ++i)
{
AiArraySetFlt(arrayValues, i, (*samp)[i]);
}
AiNodeSetArray(node, header.getName().c_str(), arrayValues);
}
}
}
else if (Abc::IInt32ArrayProperty::matches(header))
{
// int type
Abc::Int32ArraySamplePtr samp;
Abc::IInt32ArrayProperty prop(props, header.getName());
if (prop.valid())
{
size_t numSamples = prop.getNumSamples();
if (numSamples > 0)
{
prop.get( samp, Alembic::Abc::ISampleSelector((Alembic::Abc::index_t)0) );
arrayValues = AiArrayAllocate(samp->size(), numSamples, AI_TYPE_INT);
for (unsigned int i = 0; i < samp->size(); ++i)
{
AiArraySetInt(arrayValues, i, (*samp)[i]);
}
AiNodeSetArray(node, header.getName().c_str(), arrayValues);
}
}
}
else if (Abc::IBoolArrayProperty::matches(header))
{
// bool type
Abc::BoolArraySamplePtr samp;
Abc::IBoolArrayProperty prop(props, header.getName());
if (prop.valid())
{
size_t numSamples = prop.getNumSamples();
if (numSamples > 0)
{
prop.get( samp, Alembic::Abc::ISampleSelector((Alembic::Abc::index_t)0) );
arrayValues = AiArrayAllocate(samp->size(), numSamples, AI_TYPE_BOOLEAN);
for (unsigned int i = 0; i < samp->size(); ++i)
{
AiArraySetBool(arrayValues, i, (*samp)[i]);
}
AiNodeSetArray(node, header.getName().c_str(), arrayValues);
}
}
}
else if (Abc::IStringArrayProperty::matches(header))
{
// string type
Abc::StringArraySamplePtr samp;
Abc::IStringArrayProperty prop(props, header.getName());
if (prop.valid())
{
size_t numSamples = prop.getNumSamples();
if (numSamples > 0)
{
prop.get( samp, Alembic::Abc::ISampleSelector((Alembic::Abc::index_t)0) );
arrayValues = AiArrayAllocate(samp->size(), numSamples, AI_TYPE_STRING);
for (unsigned int i = 0; i < samp->size(); ++i)
{
std::string value = (*samp)[i];
value = WalterCommon::demangleString(value);
for (std::map<std::string,std::string>::iterator it=remapping.begin(); it!=remapping.end(); ++it)
value = boost::replace_all_copy(value, it->first, it->second);
AiArraySetStr(arrayValues, i, value.c_str());
}
AiNodeSetArray(node, header.getName().c_str(), arrayValues);
}
}
}
else if (Abc::IV3fArrayProperty::matches(header))
{
// vector type
Abc::V3fArraySamplePtr samp;
Abc::IV3fArrayProperty prop(props, header.getName());
if (prop.valid())
{
size_t numSamples = prop.getNumSamples();
if (numSamples > 0)
{
prop.get( samp, Alembic::Abc::ISampleSelector((Alembic::Abc::index_t)0) );
arrayValues = AiArrayAllocate(samp->size(), numSamples, AI_TYPE_VECTOR);
for (unsigned int i = 0; i < samp->size(); ++i)
{
AtVector val;
val.x = (*samp)[i].x;
val.y = (*samp)[i].y;
val.z = (*samp)[i].z;
AiArraySetVec(arrayValues,i, val);
}
AiNodeSetArray(node, header.getName().c_str(), arrayValues);
}
}
}
else if (Abc::IP3fArrayProperty::matches(header))
{
// point type
Abc::P3fArraySamplePtr samp;
Abc::IP3fArrayProperty prop(props, header.getName());
if (prop.valid())
{
size_t numSamples = prop.getNumSamples();
if (numSamples > 0)
{
prop.get( samp, Alembic::Abc::ISampleSelector((Alembic::Abc::index_t)0) );
arrayValues = AiArrayAllocate(samp->size(), numSamples, AI_TYPE_POINT);
for (unsigned int i = 0; i < samp->size(); ++i)
{
AtPoint val;
val.x = (*samp)[i].x;
val.y = (*samp)[i].y;
val.z = (*samp)[i].z;
AiArraySetPnt(arrayValues,i, val);
}
AiNodeSetArray(node, header.getName().c_str(), arrayValues);
}
}
}
else if (Abc::IC3fArrayProperty::matches(header))
{
// color type
Abc::C3fArraySamplePtr samp;
Abc::IC3fArrayProperty prop(props, header.getName());
if (prop.valid())
{
size_t numSamples = prop.getNumSamples();
if (numSamples > 0)
{
prop.get( samp, Alembic::Abc::ISampleSelector((Alembic::Abc::index_t)0) );
arrayValues = AiArrayAllocate(samp->size(), numSamples, AI_TYPE_RGB);
for (unsigned int i = 0; i < samp->size(); ++i)
{
AtColor val;
val.r = (*samp)[i].x;
val.g = (*samp)[i].y;
val.b = (*samp)[i].z;
AiArraySetRGB(arrayValues,i, val);
}
AiNodeSetArray(node, header.getName().c_str(), arrayValues);
}
}
}
else if (Abc::IC4fArrayProperty::matches(header))
{
// color type + alpha
Abc::C4fArraySamplePtr samp;
Abc::IC4fArrayProperty prop(props, header.getName());
if (prop.valid())
{
size_t numSamples = prop.getNumSamples();
if (numSamples > 0)
{
prop.get( samp, Alembic::Abc::ISampleSelector((Alembic::Abc::index_t)0) );
arrayValues = AiArrayAllocate(samp->size(), numSamples, AI_TYPE_RGBA);
for (unsigned int i = 0; i < samp->size(); ++i)
{
AtRGBA val;
val.r = (*samp)[i].r;
val.g = (*samp)[i].g;
val.b = (*samp)[i].b;
val.a = (*samp)[i].a;
AiArraySetRGBA(arrayValues,i, val);
}
AiNodeSetArray(node, header.getName().c_str(), arrayValues);
}
}
}
else if (Abc::IP2fArrayProperty::matches(header))
{
// point2
Abc::P2fArraySamplePtr samp;
Abc::IP2fArrayProperty prop(props, header.getName());
if (prop.valid())
{
size_t numSamples = prop.getNumSamples();
if (numSamples > 0)
{
prop.get( samp, Alembic::Abc::ISampleSelector((Alembic::Abc::index_t)0) );
arrayValues = AiArrayAllocate(samp->size(), numSamples, AI_TYPE_POINT2);
for (unsigned int i = 0; i < samp->size(); ++i)
{
AtPoint2 val;
val.x = (*samp)[i].x;
val.y = (*samp)[i].y;
AiArraySetPnt2(arrayValues,i, val);
}
AiNodeSetArray(node, header.getName().c_str(), arrayValues);
}
}
}
}
void setParameter(Alembic::Abc::ICompoundProperty props, Alembic::AbcCoreAbstract::PropertyHeader header, AtNode* node, std::map<std::string, std::string> remapping)
{
const AtParamEntry* pentry = AiNodeEntryLookUpParameter (AiNodeGetNodeEntry(node), header.getName().c_str());
if(pentry == NULL)
return;
const AtParamValue * pdefaultvalue = AiParamGetDefault (pentry);
if (Abc::IFloatProperty::matches(header))
{
// float type
Abc::IFloatProperty prop(props, header.getName());
if (prop.valid() && prop.getValue() != pdefaultvalue->FLT)
{
AiNodeSetFlt(node, header.getName().c_str(), prop.getValue());
AiMsgDebug("Setting float parameter %s.%s with value %f", AiNodeGetName(node), header.getName().c_str(), prop.getValue());
}
}
else if (Abc::IInt32Property::matches(header))
{
// int type
Abc::IInt32Property prop(props, header.getName());
if (prop.valid() && prop.getValue() != pdefaultvalue->INT)
{
AiNodeSetInt(node, header.getName().c_str(), prop.getValue());
AiMsgDebug("Setting int32 parameter %s.%s with value %i", AiNodeGetName(node), header.getName().c_str(), prop.getValue());
}
}
else if (Abc::IUInt32Property::matches(header))
{
// int type
Abc::IUInt32Property prop(props, header.getName());
if (prop.valid())
{
Alembic::AbcCoreAbstract::MetaData md = prop.getMetaData();
if(md.get("type") == "byte" && prop.getValue() != pdefaultvalue->BYTE)
{
AiNodeSetByte(node, header.getName().c_str(), prop.getValue());
AiMsgDebug("Setting Byte parameter %s.%s with value %i", AiNodeGetName(node), header.getName().c_str(), prop.getValue());
}
else if(prop.getValue() != pdefaultvalue->UINT)
{
AiNodeSetUInt(node, header.getName().c_str(), prop.getValue());
AiMsgDebug("Setting Uint32 parameter %s.%s with value %i", AiNodeGetName(node), header.getName().c_str(), prop.getValue());
}
}
}
else if (Abc::IBoolProperty::matches(header))
{
// bool type
Abc::IBoolProperty prop(props, header.getName());
if (prop.valid() && prop.getValue() != pdefaultvalue->BOOL)
{
AiNodeSetBool(node, header.getName().c_str(), prop.getValue());
AiMsgDebug(
"Setting bool parameter %s.%s with value %i",
AiNodeGetName(node),
header.getName().c_str(),
(int)prop.getValue());
}
}
else if (Abc::IStringProperty::matches(header))
{
// string type
Abc::IStringProperty prop(props, header.getName());
if (prop.valid() && (strcmp(prop.getValue().c_str(),pdefaultvalue->STR) != 0))
{
std::string value = prop.getValue();
value = WalterCommon::demangleString(value);
for (std::map<std::string,std::string>::iterator it=remapping.begin(); it!=remapping.end(); ++it)
value = boost::replace_all_copy(value, it->first, it->second);
AiNodeSetStr(node, header.getName().c_str(), value.c_str());
AiMsgDebug("Setting string parameter %s.%s with value %s", AiNodeGetName(node), header.getName().c_str(), value.c_str());
}
}
else if (Abc::IV3fProperty::matches(header))
{
// vector type
Abc::IV3fProperty prop(props, header.getName());
if (prop.valid() && (prop.getValue().x != pdefaultvalue->VEC.x || prop.getValue().y != pdefaultvalue->VEC.y || prop.getValue().z != pdefaultvalue->VEC.z))
{
AiNodeSetVec(node, header.getName().c_str(), prop.getValue().x , prop.getValue().y, prop.getValue().z);
AiMsgDebug("Setting vector parameter %s.%s with value %f %f %f", AiNodeGetName(node), header.getName().c_str(),prop.getValue().x , prop.getValue().y, prop.getValue().z);
}
}
else if (Abc::IP3fProperty::matches(header))
{
// vector type
Abc::IP3fProperty prop(props, header.getName());
if (prop.valid() && (prop.getValue().x != pdefaultvalue->PNT.x || prop.getValue().y != pdefaultvalue->PNT.y || prop.getValue().z != pdefaultvalue->PNT.z))
{
AiNodeSetPnt(node, header.getName().c_str(), prop.getValue().x , prop.getValue().y, prop.getValue().z);
AiMsgDebug("Setting point parameter %s.%s with value %f %f %f", AiNodeGetName(node), header.getName().c_str(),prop.getValue().x , prop.getValue().y, prop.getValue().z);
}
}
else if (Abc::IC3fProperty::matches(header))
{
// color type
Abc::IC3fProperty prop(props, header.getName());
if (prop.valid() && (prop.getValue().x != pdefaultvalue->RGB.r || prop.getValue().y != pdefaultvalue->RGB.g || prop.getValue().z != pdefaultvalue->RGB.b))
{
AiNodeSetRGB(node, header.getName().c_str(), prop.getValue().x , prop.getValue().y, prop.getValue().z);
AiMsgDebug("Setting color parameter %s.%s with value %f %f %f", AiNodeGetName(node), header.getName().c_str(),prop.getValue().x , prop.getValue().y, prop.getValue().z);
}
}
else if (Abc::IC4fProperty::matches(header))
{
// color type
Abc::IC4fProperty prop(props, header.getName());
if (prop.valid() && (prop.getValue().r != pdefaultvalue->RGBA.r || prop.getValue().g != pdefaultvalue->RGBA.g || prop.getValue().b != pdefaultvalue->RGBA.b || prop.getValue().a != pdefaultvalue->RGBA.a))
{
AiNodeSetRGBA(node, header.getName().c_str(), prop.getValue().r , prop.getValue().g, prop.getValue().b, prop.getValue().a);
AiMsgDebug("Setting color parameter %s.%s with value %f %f %f %f", AiNodeGetName(node), header.getName().c_str(),prop.getValue().r , prop.getValue().g, prop.getValue().b, prop.getValue().a);
}
}
else if (Abc::IP2fProperty::matches(header))
{
// point2
Abc::IP2fProperty prop(props, header.getName());
if (prop.valid() && (prop.getValue().x != pdefaultvalue->PNT2.x || prop.getValue().y != pdefaultvalue->PNT2.y))
{
AiNodeSetPnt2(node, header.getName().c_str(), prop.getValue().x , prop.getValue().y);
AiMsgDebug("Setting point2 parameter %s.%s with value %f %f", AiNodeGetName(node), header.getName().c_str(), prop.getValue().x , prop.getValue().y);
}
}
}
<|start_filename|>walter/viewer/View.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERVIEWER_VIEW_H__
#define __WALTERVIEWER_VIEW_H__
#include "Types.h"
#include <pxr/base/gf/vec4d.h>
#include <pxr/imaging/glf/glew.h>
#include <pxr/usdImaging/usdImagingGL/engine.h>
#include <GL/gl.h>
#include <GLFW/glfw3.h>
PXR_NAMESPACE_USING_DIRECTIVE
namespace walter_viewer
{
ViewPtr getView();
class Scene;
enum class ButtonPressState { released, click, drag };
enum class ButtonPressed {undefined, left, middle, right };
enum class InteractionMode {camera, selection };
class View
{
class SRGBContext
{
public:
SRGBContext(GfVec4d clearColor);
~SRGBContext();
};
public:
View();
~View();
bool show();
bool isValid() const { return mIsValid; }
void setScene(ScenePtr scene);
const ScenePtr scene() { return mScene; }
void refresh();
// void mouseReleased();
void mouseClickCallback(ButtonPressed button);
void mouseMoveCallback(int x, int y);
ButtonPressState pressState{ButtonPressState::released};
ButtonPressed button{ButtonPressed::undefined};
int width{0};
int height{0};
InteractionMode mode{InteractionMode::camera};
UsdImagingGLEngine::DrawMode drawMode{UsdImagingGLEngine::DRAW_SHADED_SMOOTH};
private:
GLFWwindow* mWindow;
bool mIsValid{false};
bool mFirstRefresh{true};
ScenePtr mScene;
};
} // end namespace walter_viewer
#endif
<|start_filename|>walter/usd/schemas/volume.cpp<|end_filename|>
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include ".//volume.h"
#include "pxr/usd/usd/schemaRegistry.h"
#include "pxr/usd/usd/typed.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/assetPath.h"
PXR_NAMESPACE_OPEN_SCOPE
// Register the schema with the TfType system.
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define<WalterVolume,
TfType::Bases< UsdGeomGprim > >();
// Register the usd prim typename as an alias under UsdSchemaBase. This
// enables one to call
// TfType::Find<UsdSchemaBase>().FindDerivedByName("Volume")
// to find TfType<WalterVolume>, which is how IsA queries are
// answered.
TfType::AddAlias<UsdSchemaBase, WalterVolume>("Volume");
}
/* virtual */
WalterVolume::~WalterVolume()
{
}
/* static */
WalterVolume
WalterVolume::Get(const UsdStagePtr &stage, const SdfPath &path)
{
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return WalterVolume();
}
return WalterVolume(stage->GetPrimAtPath(path));
}
/* static */
WalterVolume
WalterVolume::Define(
const UsdStagePtr &stage, const SdfPath &path)
{
static TfToken usdPrimTypeName("Volume");
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return WalterVolume();
}
return WalterVolume(
stage->DefinePrim(path, usdPrimTypeName));
}
/* static */
const TfType &
WalterVolume::_GetStaticTfType()
{
static TfType tfType = TfType::Find<WalterVolume>();
return tfType;
}
/* static */
bool
WalterVolume::_IsTypedSchema()
{
static bool isTyped = _GetStaticTfType().IsA<UsdTyped>();
return isTyped;
}
/* virtual */
const TfType &
WalterVolume::_GetTfType() const
{
return _GetStaticTfType();
}
UsdAttribute
WalterVolume::GetVolumePaddingAttr() const
{
return GetPrim().GetAttribute(WalterTokens->volumePadding);
}
UsdAttribute
WalterVolume::CreateVolumePaddingAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->volumePadding,
SdfValueTypeNames->Float,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
WalterVolume::GetStepSizeAttr() const
{
return GetPrim().GetAttribute(WalterTokens->stepSize);
}
UsdAttribute
WalterVolume::CreateStepSizeAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->stepSize,
SdfValueTypeNames->Float,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
WalterVolume::GetFilenameAttr() const
{
return GetPrim().GetAttribute(WalterTokens->filename);
}
UsdAttribute
WalterVolume::CreateFilenameAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->filename,
SdfValueTypeNames->String,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
WalterVolume::GetFiledataAttr() const
{
return GetPrim().GetAttribute(WalterTokens->filedata);
}
UsdAttribute
WalterVolume::CreateFiledataAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->filedata,
SdfValueTypeNames->UCharArray,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
WalterVolume::GetStepScaleAttr() const
{
return GetPrim().GetAttribute(WalterTokens->stepScale);
}
UsdAttribute
WalterVolume::CreateStepScaleAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->stepScale,
SdfValueTypeNames->Float,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
WalterVolume::GetCompressAttr() const
{
return GetPrim().GetAttribute(WalterTokens->compress);
}
UsdAttribute
WalterVolume::CreateCompressAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->compress,
SdfValueTypeNames->Bool,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
WalterVolume::GetGridsAttr() const
{
return GetPrim().GetAttribute(WalterTokens->grids);
}
UsdAttribute
WalterVolume::CreateGridsAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->grids,
SdfValueTypeNames->StringArray,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
WalterVolume::GetVelocityScaleAttr() const
{
return GetPrim().GetAttribute(WalterTokens->velocityScale);
}
UsdAttribute
WalterVolume::CreateVelocityScaleAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->velocityScale,
SdfValueTypeNames->Float,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
WalterVolume::GetVelocityFpsAttr() const
{
return GetPrim().GetAttribute(WalterTokens->velocityFps);
}
UsdAttribute
WalterVolume::CreateVelocityFpsAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->velocityFps,
SdfValueTypeNames->Float,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
WalterVolume::GetVelocityOutlierThresholdAttr() const
{
return GetPrim().GetAttribute(WalterTokens->velocityOutlierThreshold);
}
UsdAttribute
WalterVolume::CreateVelocityOutlierThresholdAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->velocityOutlierThreshold,
SdfValueTypeNames->Float,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
namespace {
static inline TfTokenVector
_ConcatenateAttributeNames(const TfTokenVector& left,const TfTokenVector& right)
{
TfTokenVector result;
result.reserve(left.size() + right.size());
result.insert(result.end(), left.begin(), left.end());
result.insert(result.end(), right.begin(), right.end());
return result;
}
}
/*static*/
const TfTokenVector&
WalterVolume::GetSchemaAttributeNames(bool includeInherited)
{
static TfTokenVector localNames = {
WalterTokens->volumePadding,
WalterTokens->stepSize,
WalterTokens->filename,
WalterTokens->filedata,
WalterTokens->stepScale,
WalterTokens->compress,
WalterTokens->grids,
WalterTokens->velocityScale,
WalterTokens->velocityFps,
WalterTokens->velocityOutlierThreshold,
};
static TfTokenVector allNames =
_ConcatenateAttributeNames(
UsdGeomGprim::GetSchemaAttributeNames(true),
localNames);
if (includeInherited)
return allNames;
else
return localNames;
}
PXR_NAMESPACE_CLOSE_SCOPE
// ===================================================================== //
// Feel free to add custom code below this line. It will be preserved by
// the code generator.
//
// Just remember to wrap code in the appropriate delimiters:
// 'PXR_NAMESPACE_OPEN_SCOPE', 'PXR_NAMESPACE_CLOSE_SCOPE'.
// ===================================================================== //
// --(BEGIN CUSTOM CODE)--
<|start_filename|>walter/katana/WalterIn/XformCook.cpp<|end_filename|>
#include <sstream>
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ScalarPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
///////////////////////////////////////////////////////////////////////////////
void evalXform(Alembic::AbcGeom::IXformSchema & iSchema,
const OpArgs & iArgs,
FnAttribute::GroupBuilder & oGb)
{
//this can't be multi-sampled in katana so we'll query it at the current
//time and hope for the best.
bool inheritsXform = iSchema.getInheritsXforms(
Alembic::Abc::ISampleSelector(iArgs.getAbcFrameTime()));
Alembic::Abc::TimeSamplingPtr ts = iSchema.getTimeSampling();
SampleTimes sampleTimes;
iArgs.getRelevantSampleTimes(ts, iSchema.getNumSamples(), sampleTimes);
bool multiSample = sampleTimes.size() > 1;
Alembic::AbcGeom::XformSample referenceOps;
iSchema.get(referenceOps,
Alembic::Abc::ISampleSelector(*sampleTimes.begin()));
typedef std::vector<double> DoubleVector;
typedef std::map<float, DoubleVector> DoubleAttrSampleMap;
std::vector<FnAttribute::DoubleBuilder> builders;
builders.reserve(referenceOps.getNumOps());
for (SampleTimes::iterator I = sampleTimes.begin();
I != sampleTimes.end(); ++I)
{
Alembic::Abc::chrono_t inputSampleTime = (*I);
float relativeSampleTime = multiSample ?
iArgs.getRelativeSampleTime(inputSampleTime) : 0.0f;
Alembic::AbcGeom::XformSample ops;
iSchema.get(ops, Alembic::Abc::ISampleSelector(inputSampleTime));
for (size_t opindex = 0; opindex < ops.getNumOps(); ++opindex)
{
const Alembic::AbcGeom::XformOp & xformOp = ops[opindex];
if (builders.size() <= opindex)
{
int tupleSize = (int) xformOp.getNumChannels();
switch (xformOp.getType())
{
case Alembic::AbcGeom::kRotateXOperation:
case Alembic::AbcGeom::kRotateYOperation:
case Alembic::AbcGeom::kRotateZOperation:
tupleSize = 4;
break;
case Alembic::AbcGeom::kMatrixOperation:
tupleSize = 4;
break;
default:
break;
}
builders.push_back(FnAttribute::DoubleBuilder(tupleSize));
}
DoubleVector & sampleVector =
builders[opindex].get(relativeSampleTime);
//rotation is the only case in which our order differs
//if (xformOp.getType() == AbcGeom::kRotateOperation)
switch (xformOp.getType())
{
case Alembic::AbcGeom::kRotateOperation:
case Alembic::AbcGeom::kRotateXOperation:
case Alembic::AbcGeom::kRotateYOperation:
case Alembic::AbcGeom::kRotateZOperation:
{
sampleVector.resize(4);
sampleVector[0] = xformOp.getAngle();
Alembic::AbcGeom::V3d axis = xformOp.getAxis();
sampleVector[1] = axis[0];
sampleVector[2] = axis[1];
sampleVector[3] = axis[2];
}
break;
default:
sampleVector.resize(xformOp.getNumChannels());
for (size_t i = 0; i < sampleVector.size(); ++i)
{
sampleVector[i] = xformOp.getChannelValue(i);
}
break;
}
}
}
if (!builders.empty() || !inheritsXform)
{
if (!inheritsXform)
{
oGb.set("xform.origin", FnAttribute::DoubleAttribute(0.0), false);
}
size_t opindex = 0;
size_t opTypeCount[4] = {0, 0, 0, 0};
for (opindex = 0; opindex < referenceOps.getNumOps(); ++opindex)
{
const Alembic::AbcGeom::XformOp & xformOp = referenceOps[opindex];
std::string attrName;
size_t curCount = 0;
switch (xformOp.getType())
{
case Alembic::AbcGeom::kScaleOperation:
{
attrName = "xform.scale";
curCount = opTypeCount[0]++;
}
break;
case Alembic::AbcGeom::kTranslateOperation:
{
attrName = "xform.translate";
curCount = opTypeCount[1]++;
}
break;
case Alembic::AbcGeom::kRotateOperation:
case Alembic::AbcGeom::kRotateXOperation:
case Alembic::AbcGeom::kRotateYOperation:
case Alembic::AbcGeom::kRotateZOperation:
{
attrName = "xform.rotate";
curCount = opTypeCount[2]++;
}
break;
case Alembic::AbcGeom::kMatrixOperation:
{
attrName = "xform.matrix";
curCount = opTypeCount[3]++;
}
break;
}
if (curCount > 0)
{
std::stringstream strm;
strm << curCount;
attrName += strm.str();
}
oGb.set(attrName, builders[opindex].build(), false);
}
}
}
///////////////////////////////////////////////////////////////////////////////
void cookXform(AbcCookPtr ioCook, FnAttribute::GroupBuilder & oStaticGb)
{
Alembic::AbcGeom::IXformPtr objPtr(
new Alembic::AbcGeom::IXform(*(ioCook->objPtr),
Alembic::AbcGeom::kWrapExisting));
Alembic::AbcGeom::IXformSchema schema = objPtr->getSchema();
oStaticGb.set("type", FnAttribute::StringAttribute("group"));
Alembic::Abc::ICompoundProperty userProp = schema.getUserProperties();
Alembic::Abc::ICompoundProperty arbGeom = schema.getArbGeomParams();
std::string abcUser = "abcUser.";
processUserProperties(ioCook, userProp, oStaticGb, abcUser);
processArbGeomParams(ioCook, arbGeom, oStaticGb);
//check for child bounds
Alembic::Abc::IBox3dProperty boundsProp = schema.getChildBoundsProperty();
if (boundsProp.valid())
{
scalarPropertyToAttr(schema, boundsProp.getHeader(), "bound",
ioCook, oStaticGb);
}
if (schema.isConstant())
{
OpArgs defaultArgs;
evalXform(schema, defaultArgs, oStaticGb);
}
if (!schema.isConstant())
{
ioCook->objPtr = objPtr;
ioCook->animatedSchema = true;
}
}
} //end of namespace WalterIn
<|start_filename|>walter/usd/tests/test_setUSDVariantsLayer.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/prim.h>
#include "walterUSDCommonUtils.h"
#include <gtest/gtest.h>
PXR_NAMESPACE_USING_DIRECTIVE
TEST(setUSDVariantsLayer, test1)
{
UsdStageRefPtr stage = UsdStage::CreateInMemory();
std::string variantData = "#usda 1.0\n\ndef \"Foo\"\n{\n}\n\n";
bool result = WalterUSDCommonUtils::setUSDVariantsLayer(stage, variantData.c_str());
EXPECT_TRUE(result);
UsdPrim prim(stage->GetPrimAtPath(SdfPath("/Foo")));
EXPECT_TRUE(prim);
EXPECT_EQ(WalterUSDCommonUtils::getVariantsLayerAsText(stage), variantData);
}
<|start_filename|>walter/katana/WalterIn/ObjectCook.cpp<|end_filename|>
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ScalarPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
namespace WalterIn
{
bool isBoundBox(const Alembic::Abc::PropertyHeader & iPropHeader)
{
if (iPropHeader.getDataType().getExtent() != 6)
{
return false;
}
Alembic::Util::PlainOldDataType podType =
iPropHeader.getDataType().getPod();
if (podType != Alembic::Util::kFloat64POD &&
podType != Alembic::Util::kFloat32POD)
{
return false;
}
std::string interp = iPropHeader.getMetaData().get("interpretation");
if (interp != "box")
{
return false;
}
return true;
}
int64_t getTupleSize(const Alembic::AbcCoreAbstract::PropertyHeader & iHeader)
{
int64_t extent = iHeader.getDataType().getExtent();
if (iHeader.getMetaData().get("interpretation") == "box")
{
if (extent == 6)
{
extent = 3;
}
else if (extent == 4)
{
extent = 2;
}
}
if (extent == 0)
{
extent = 1;
}
return extent;
}
void evalObject(AbcCookPtr ioCookPtr, const OpArgs & iArgs,
FnAttribute::GroupBuilder & oGb,
Alembic::Abc::IUInt64ArrayProperty * iIdsProperty)
{
if (ioCookPtr->visProp.valid())
{
Alembic::Util::int8_t visValue = -1;
Alembic::Abc::ISampleSelector ss(iArgs.getAbcFrameTime());
ioCookPtr->visProp.get(visValue, ss);
if (visValue > -1)
{
oGb.set("visible", FnAttribute::IntAttribute(visValue));
}
}
if (!ioCookPtr->objPtr)
{
return;
}
std::vector< ArrayProp >::iterator at = ioCookPtr->arrayProps.begin();
for (; at != ioCookPtr->arrayProps.end(); ++at)
{
arrayPropertyToAttr(*at, iArgs, oGb, iIdsProperty);
}
std::vector< ScalarProp >::iterator st = ioCookPtr->scalarProps.begin();
for (; st != ioCookPtr->scalarProps.end(); ++st)
{
scalarPropertyToAttr(*st, iArgs, oGb);
}
std::vector< IndexedGeomParamPair >::iterator it =
ioCookPtr->forcedExpandProps.begin();
for (; it != ioCookPtr->forcedExpandProps.end(); ++it)
{
indexedParamToAttr(*it, iArgs, oGb);
}
Alembic::AbcGeom::IXformPtr xformPtr = Alembic::Util::dynamic_pointer_cast<
Alembic::AbcGeom::IXform, Alembic::Abc::IObject >(ioCookPtr->objPtr);
if (xformPtr)
{
evalXform(xformPtr->getSchema(), iArgs, oGb);
return;
}
Alembic::AbcGeom::INuPatchPtr patchPtr =
Alembic::Util::dynamic_pointer_cast<Alembic::AbcGeom::INuPatch,
Alembic::Abc::IObject >(ioCookPtr->objPtr);
if (patchPtr)
{
evalNuPatch(patchPtr->getSchema(), iArgs, false, oGb);
return;
}
Alembic::AbcGeom::ICurvesPtr curvesPtr =
Alembic::Util::dynamic_pointer_cast<Alembic::AbcGeom::ICurves,
Alembic::Abc::IObject >(ioCookPtr->objPtr);
if (curvesPtr)
{
evalCurves(curvesPtr->getSchema(), iArgs, oGb);
return;
}
Alembic::AbcGeom::ICameraPtr cameraPtr =
Alembic::Util::dynamic_pointer_cast<Alembic::AbcGeom::ICamera,
Alembic::Abc::IObject >(ioCookPtr->objPtr);
if (cameraPtr)
{
evalCamera(cameraPtr->getSchema(), iArgs, oGb);
return;
}
}
// fills in the static group, and the animated array and static props
void initAbcCook(AbcCookPtr ioCookPtr,
FnAttribute::GroupBuilder & oStaticGb)
{
const Alembic::AbcCoreAbstract::ObjectHeader & header =
ioCookPtr->objPtr->getHeader();
Alembic::AbcGeom::IVisibilityProperty visProp =
Alembic::AbcGeom::GetVisibilityProperty(*ioCookPtr->objPtr);
if (visProp.valid() && visProp.isConstant())
{
Alembic::Util::int8_t visValue = -1;
visProp.get(visValue);
if (visValue > -1)
{
oStaticGb.set("visible", FnAttribute::IntAttribute(visValue));
}
}
else
{
if (visProp.valid())
ioCookPtr->animatedSchema = true;
ioCookPtr->visProp = visProp;
}
if (Alembic::AbcGeom::IXform::matches(header))
{
cookXform(ioCookPtr, oStaticGb);
}
else if (Alembic::AbcGeom::IPolyMesh::matches(header))
{
cookPolyMesh(ioCookPtr, oStaticGb);
}
else if (Alembic::AbcGeom::ISubD::matches(header))
{
cookSubd(ioCookPtr, oStaticGb);
}
else if (Alembic::AbcGeom::ICamera::matches(header))
{
cookCamera(ioCookPtr, oStaticGb);
}
else if (Alembic::AbcGeom::IFaceSet::matches(header))
{
cookFaceset(ioCookPtr, oStaticGb);
}
else if (Alembic::AbcGeom::ICurves::matches(header))
{
cookCurves(ioCookPtr, oStaticGb);
}
else if (Alembic::AbcGeom::INuPatch::matches(header))
{
cookNuPatch(ioCookPtr, oStaticGb);
}
else if (Alembic::AbcGeom::IPoints::matches(header))
{
cookPoints(ioCookPtr, oStaticGb);
}
else if (Alembic::AbcMaterial::IMaterial::matches(header))
{
cookMaterial(ioCookPtr, oStaticGb);
}
else if (Alembic::AbcGeom::ILight::matches(header))
{
cookLight(ioCookPtr, oStaticGb);
}
else
{
// just set this up as a group, we'll ignore all the properties for now
oStaticGb.set("type", FnAttribute::StringAttribute("group"));
}
}
namespace
{
std::string safeAttrName(const std::string & name)
{
std::string result = name;
for (size_t i = 0; i < result.size(); ++i)
{
if (result[i] == '.')
{
result[i] = '_';
}
}
return result;
}
}
void processUserProperties(AbcCookPtr ioCook,
Alembic::Abc::ICompoundProperty & iParent,
FnAttribute::GroupBuilder & oStaticGb,
const std::string & iAttrPath,
const NameMap* iRenameMap,
Alembic::Abc::v10::IUInt64ArrayProperty * iIdsProperty)
{
if (!iParent.valid())
{
return;
}
for (size_t i = 0; i < iParent.getNumProperties(); ++i)
{
const Alembic::AbcCoreAbstract::PropertyHeader &propHeader =
iParent.getPropertyHeader(i);
// Check meta. We need only Arnold official data.
const auto& meta = propHeader.getMetaData();
const std::string arnoldUserData = meta.get("userData");
if (arnoldUserData == "yes")
{
continue;
}
std::string propName = iAttrPath + safeAttrName(propHeader.getName());
// Rename attribute if we have a map for it.
if (iRenameMap)
{
NameMap::const_iterator it = iRenameMap->find(propName);
if (it != iRenameMap->end())
{
propName = it->second;
}
}
//recurse if it's a compound
if (propHeader.isCompound())
{
Alembic::Abc::ICompoundProperty childCompound(iParent,
propHeader.getName());
if (childCompound.valid())
{
processUserProperties(ioCook, childCompound, oStaticGb,
propName+".", nullptr, iIdsProperty);
}
}
// It may be important to test if it's a Compound first in case
// visibility has been activated or deactivated in a more precise way
// than just "visibility=<bool>".
else if (propName == "visibility")
{
setArnoldVisibility(ioCook, iParent, propHeader,
propName, oStaticGb);
}
else if (propHeader.isScalar())
{
scalarPropertyToAttr(iParent, propHeader, propName,
ioCook, oStaticGb);
}
else if (propHeader.isArray())
{
arrayPropertyToAttr(iParent, propHeader, propName,
FnAttribute::NullAttribute::getKatAttributeType(),
ioCook, oStaticGb, iIdsProperty);
}
}
}
void setArnoldVisibility(
AbcCookPtr ioCook,
Alembic::Abc::ICompoundProperty & iParent,
const Alembic::AbcCoreAbstract::PropertyHeader & iPropHeader,
const std::string & iPropName,
FnAttribute::GroupBuilder & oStaticGb)
{
// All those attributes are different ways to enable/disable visibility.
// If visibility change, we need to reflect it on each of those.
static std::array<std::string, 7> visibilityAttributes{
"AI_RAY_CAMERA",
"AI_RAY_SHADOW",
"AI_RAY_DIFFUSE_TRANSMIT",
"AI_RAY_SPECULAR_TRANSMIT",
"AI_RAY_VOLUME",
"AI_RAY_DIFFUSE_REFLECT",
"AI_RAY_SPECULAR_REFLECT"
};
for (auto attribute: visibilityAttributes)
{
std::string attributeName = iPropName + "." + attribute;
scalarPropertyToAttr(iParent, iPropHeader, attributeName,
ioCook, oStaticGb);
}
}
void processArnoldUserProperties(
AbcCookPtr ioCook,
Alembic::Abc::ICompoundProperty & iParent,
FnAttribute::GroupBuilder & oStaticGb,
const std::string & iAttrPath)
{
if (!iParent.valid())
{
return;
}
for (size_t i = 0; i < iParent.getNumProperties(); ++i)
{
const Alembic::AbcCoreAbstract::PropertyHeader &propHeader =
iParent.getPropertyHeader(i);
if (!propHeader.isScalar())
{
continue;
}
// Check meta. We need only Arnold UserData.
const auto& meta = propHeader.getMetaData();
const std::string arnoldUserData = meta.get("userData");
if (arnoldUserData != "yes")
{
continue;
}
// Check type. We only support color, int and float.
std::string type;
if (Alembic::AbcGeom::IFloatProperty::matches(propHeader))
{
type = "float";
}
else if (Alembic::AbcGeom::IInt32Property::matches(propHeader))
{
type = "int";
}
else if (Alembic::AbcGeom::IV3fProperty::matches(propHeader))
{
type = "color3";
}
else if (Alembic::AbcGeom::IStringProperty::matches(propHeader))
{
type = "string";
}
else
{
continue;
}
std::string propName =
iAttrPath + safeAttrName(propHeader.getName());
scalarPropertyToAttr(
iParent,
propHeader,
propName + ".value",
ioCook,
oStaticGb);
oStaticGb.set(
propName + ".scope", FnAttribute::StringAttribute("primitive"));
oStaticGb.set(
propName + ".inputType",
FnAttribute::StringAttribute(type));
oStaticGb.set(
propName + ".outputType",
FnAttribute::StringAttribute(type));
}
}
Alembic::Util::PlainOldDataType FnAttrTypeToPODType(FnKatAttributeType iType)
{
if (iType == kFnKatAttributeTypeInt)
{
return Alembic::Util::kInt32POD;
}
else if (iType == kFnKatAttributeTypeFloat)
{
return Alembic::Util::kFloat32POD;
}
else if (iType == kFnKatAttributeTypeDouble)
{
return Alembic::Util::kFloat64POD;
}
else if (iType == kFnKatAttributeTypeString)
{
return Alembic::Util::kStringPOD;
}
return Alembic::Util::kUnknownPOD;
}
} //end of namespace WalterIn
<|start_filename|>walter/viewer/Scene.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERVIEWER_SCENE_H__
#define __WALTERVIEWER_SCENE_H__
#include "Types.h"
#include <pxr/usd/usd/stage.h>
#include <pxr/usdImaging/usdImagingGL/engine.h>
#include <pxr/usdImaging/usdImagingGL/gl.h>
#include <memory>
#include <string>
PXR_NAMESPACE_USING_DIRECTIVE
namespace walter_viewer
{
typedef std::shared_ptr<UsdImagingGL> UsdImagingGLRefPtr;
class Scene
{
public:
struct Options
{
float frame {1.f};
float complexity { 1.1f};
std::string filePath;
std::string renderer {"Stream"};
};
Scene(
const Options& opt,
FreeCameraPtr camera = nullptr);
void setRenderer(const std::string& name);
void draw(int width, int height);
void framed() { mFramed = true; }
void resetCamera();
void updateCamera(int height);
void frameSelection();
void select(double xpos, double ypos, int width, int height);
void updateSubdiv(float value);
void setDrawMode(UsdImagingGLEngine::DrawMode value);
void Export(const std::string& outputPath) const;
FreeCameraPtr camera() { return mCamera; }
private:
static GfBBox3d getDefaultBBox();
GfBBox3d computeStageBBox();
private:
bool mFramed{false};
FreeCameraPtr mCamera;
UsdStageRefPtr mStage;
UsdPrim mDefaultPrim;
UsdImagingGLEngine::RenderParams mParams;
UsdImagingGLRefPtr mRenderer;
};
} // end namespace walter_viewer
#endif
<|start_filename|>walter/common/to_string_patch.h<|end_filename|>
#ifndef TO_STRING_PATCH_
#define TO_STRING_PATCH_
#include <sstream>
template <typename T> std::string to_string( T Number )
{
std::stringstream ss;
ss << Number;
return ss.str();
}
#endif //TO_STRING_PATCH_
#ifndef TO_STRING_PATCH_
#define TO_STRING_PATCH_
#include <sstream>
template <typename T> std::string to_string( T Number )
{
std::stringstream ss;
ss << Number;
return ss.str();
}
#endif //TO_STRING_PATCH_
<|start_filename|>walter/common/abcshaderutils.h<|end_filename|>
#ifndef ABCSHADERUTILS_H_
#define ABCSHADERUTILS_H_
#include <ai.h>
#include <Alembic/Abc/All.h>
#include <Alembic/AbcMaterial/IMaterial.h>
namespace Abc = Alembic::Abc;
namespace Mat = Alembic::AbcMaterial;
namespace {
std::map<std::string, std::string> emptyRemap;
}
void setUserParameter(AtNode* source, std::string interfaceName, Alembic::AbcCoreAbstract::PropertyHeader header, AtNode* node, std::map<std::string, std::string> remapping = emptyRemap);
void setArrayParameter(Alembic::Abc::ICompoundProperty props, Alembic::AbcCoreAbstract::PropertyHeader header, AtNode* node, std::map<std::string, std::string> remapping = emptyRemap);
void setParameter(Alembic::Abc::ICompoundProperty props, Alembic::AbcCoreAbstract::PropertyHeader header, AtNode* node, std::map<std::string, std::string> remapping = emptyRemap);
#endif
<|start_filename|>walter/maya/walterStandin/walterThreadingUtils.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERTHREADINGUTILS_H_
#define __WALTERTHREADINGUTILS_H_
#include <maya/MObject.h>
namespace WalterThreadingUtils
{
/**
* @brief Starts loading stage in a background thread.
*
* @param iObj Walter standin to load.
*/
void loadStage(const MObject& iObj);
void joinAll();
}
#endif
<|start_filename|>walter/houdini/src/SOP_WalterNode.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __SOP_WalterNode_h__
#define __SOP_WalterNode_h__
#include <SOP/SOP_Node.h>
namespace WalterHoudini
{
class SOP_WalterNode : public SOP_Node
{
enum class PrimLoadingMode
{
single,
children
};
public:
static void install(OP_OperatorTable* table);
static OP_Node* constructor(OP_Network*, const char*, OP_Operator*);
// Get all the file names combined in one string
std::string evalSessionName(fpreal time) const;
// Stores the description of the interface of the SOP in Houdini.
// Each parm template refers to a parameter.
static PRM_Template sTemplateList[];
protected:
SOP_WalterNode(OP_Network* net, const char* name, OP_Operator* op);
virtual ~SOP_WalterNode();
// cookMySop does the actual work of the SOP computing, in this
// case, a star shape.
virtual OP_ERROR cookMySop(OP_Context& context);
private:
struct Parms
{
Parms();
Parms(const Parms& src);
/// Compare this set of parameters with the other set of parameters to
/// see if the update is needed (i.e. the filename has changed, etc.)
bool needsUpdate(const Parms& parms);
bool timeChanged(const Parms& parms);
Parms& operator=(const Parms& src);
std::string mFileName;
std::string mPrimPath;
fpreal mFrame;
PrimLoadingMode mPrimMode;
std::string mHdRendererName;
};
void evaluateParms(Parms& parms, OP_Context& context);
Parms mLastParms;
};
} // end namespace WalterHoudini
#endif
<|start_filename|>walter/alembic/IWalterLayersSchema.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "IWalterLayersSchema.h"
#include <Alembic/AbcMaterial/All.h>
#include <boost/algorithm/string.hpp>
size_t IWalterLayersSchema::getNumTargets() const
{
return mTargets.size();
}
const std::string& IWalterLayersSchema::getTargetName(size_t n) const
{
return mTargets[n];
}
std::string IWalterLayersSchema::getShaderName(
const std::string& iTarget,
const std::string& iShaderType) const
{
TargetKey key(iTarget, iShaderType);
TargetMap::const_iterator found = mShaders.find(key);
if (found != mShaders.end()) {
return found->second;
}
return std::string();
}
void IWalterLayersSchema::init()
{
for (size_t i=0; i<getNumProperties(); i++) {
std::string layerAndType = getPropertyHeader(i).getName();
std::vector<std::string> split;
boost::split(split, layerAndType, boost::is_any_of("."));
if (split.size()<3)
continue;
Alembic::Abc::ICompoundProperty layerProp(this->getPtr(), layerAndType);
std::string shader;
if (!Alembic::AbcMaterial::getMaterialAssignmentPath(layerProp, shader))
continue;
const std::string& target = split[1];
const std::string& type = split[2];
if (std::find(mTargets.begin(),mTargets.end(),target) == mTargets.end())
mTargets.push_back(target);
mShaders[TargetKey(target, type)] = shader;
}
}
<|start_filename|>walter/alembic/IWalterExpressionsSchema.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "IWalterExpressionsSchema.h"
#include "OWalterLayersSchema.h"
#include <boost/algorithm/string.hpp>
#include "PathUtil.h"
void IWalterExpressionsSchema::init()
{
unsigned int numProps = getNumProperties();
// Pre-allocate the vectors.
mExpressionKeys.reserve(numProps);
mExpressions.reserve(numProps);
mGrouped.reserve(numProps);
mGroupNames.reserve(numProps);
for (size_t i=0; i<numProps; i++)
{
std::string expressionKey = getPropertyHeader(i).getName();
mExpressionKeys.push_back(expressionKey);
Alembic::Abc::ICompoundProperty expression(
this->getPtr(), expressionKey);
// We have mangled expressions. It's necessary to demangle them.
// TODO: Save something like ".name" field
mExpressions.push_back(WalterCommon::demangleString(expressionKey));
// Get the name of the group
if (expression.getPropertyHeader(EXPRESSIONS_GROUP))
{
Alembic::Abc::ICompoundProperty group(
expression, EXPRESSIONS_GROUP);
Alembic::Abc::IStringProperty sprop(
group, EXPRESSIONS_GROUPNAME);
mGrouped.push_back(true);
mGroupNames.push_back(sprop.getValue());
}
else
{
mGrouped.push_back(false);
mGroupNames.push_back(std::string());
}
}
}
const std::string& IWalterExpressionsSchema::getExpression(size_t n) const
{
return mExpressions[n];
}
bool IWalterExpressionsSchema::getHasGroup(size_t n) const
{
return mGrouped[n];
}
const std::string& IWalterExpressionsSchema::getExpressionGroup(size_t n) const
{
return mGroupNames[n];
}
IWalterLayersSchema IWalterExpressionsSchema::getLayerSchema(size_t n) const
{
Alembic::Abc::ICompoundProperty expression(
this->getPtr(), mExpressionKeys[n]);
return IWalterLayersSchema(expression, LAYERS_PROPNAME);
}
bool hasExpressions(
Alembic::Abc::ICompoundProperty iCompound,
IWalterExpressionsSchema& oResult,
const std::string& iPropName)
{
if (!iCompound.valid())
{
return false;
}
if (const Alembic::AbcCoreAbstract::PropertyHeader * header =
iCompound.getPropertyHeader(iPropName))
{
if (IWalterExpressionsSchema::matches(*header))
{
oResult = IWalterExpressionsSchema(iCompound, iPropName);
return true;
}
}
return false;
}
bool hasExpressions(
Alembic::Abc::IObject iObject,
IWalterExpressionsSchema& oResult,
const std::string& iPropName)
{
//don't indicate has-a for matching Material objects
if (iObject.valid() && iPropName == EXPRESSIONS_PROPNAME)
{
if (IWalterExpressions::matches(iObject.getHeader()))
{
return false;
}
}
return hasExpressions(iObject.getProperties(), oResult, iPropName);
}
<|start_filename|>walter/maya/AbcExport/MayaLightWriter.h<|end_filename|>
//-*****************************************************************************
//
// Copyright (c) 2009-2012,
// Sony Pictures Imageworks Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// All rights reserved.
//
// 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.
// * Neither the name of Sony Pictures Imageworks, nor
// Industrial Light & Magic, nor the names of their contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// 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.
//
//-*****************************************************************************
//
// Copyright 2017 <NAME>. All rights reserved.
#ifndef _AbcExport_MayaLightWriter_h_
#define _AbcExport_MayaLightWriter_h_
#include "AttributesWriter.h"
#include "Foundation.h"
#include "MayaTransformWriter.h"
#include <Alembic/AbcGeom/OLight.h>
// Writes an MFnLight
class MayaLightWriter
{
friend class ArnoldLightExporter;
public:
MayaLightWriter(
MDagPath& iDag,
Alembic::Abc::OObject& iParent,
Alembic::Util::uint32_t iTimeIndex,
const JobArgs& iArgs);
AttributesWriterPtr getAttrs() { return mAttrs; };
void write();
bool isAnimated() const;
private:
bool mIsAnimated;
MDagPath mDagPath;
Alembic::AbcGeom::OLightSchema mSchema;
AttributesWriterPtr mAttrs;
Alembic::Abc::OStringProperty mType;
Alembic::Abc::OC3fProperty mColor;
Alembic::Abc::OFloatProperty mIntensity;
Alembic::Abc::OFloatProperty mDecay;
};
typedef Alembic::Util::shared_ptr<MayaLightWriter> MayaLightWriterPtr;
#endif // _AbcExport_MayaLightWriter_h_
<|start_filename|>walter/katana/WalterIn/op.cpp<|end_filename|>
#include "walterUSDOp.h"
#include "walterUSDCommonUtils.h"
#include <boost/shared_ptr.hpp>
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnGroupBuilder.h>
#include <pystring/pystring.h>
#include <FnPluginSystem/FnPlugin.h>
#include <FnGeolib/op/FnGeolibOp.h>
#include <FnGeolib/op/FnGeolibCookInterface.h>
#include <FnGeolib/util/AttributeKeyedCache.h>
#include <FnGeolibServices/FnGeolibCookInterfaceUtilsService.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usdLux/light.h>
#include <pxr/usd/usdGeom/camera.h>
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
#include "ScalarPropUtils.h"
#include "PathUtil.h"
#include <Alembic/AbcCoreFactory/All.h>
#include "IWalterExpressionsSchema.h"
#include <hdf5.h> // for H5dont_atexit
#include <boost/algorithm/string.hpp>
#include <unordered_map>
#include <unordered_set>
namespace { // anonymous
/**
* @brief Split long string that contains the list of Alembic layers into
* vector. It considers hidden layers.
*
* @param iFileNameStr The string that contains the list of Alembic layers.
* @param oArchives Output vector.
*/
void splitArchives(
const std::string& iFileNameStr,
std::vector<std::string>& oArchives)
{
std::vector<std::string> archives;
boost::split(archives, iFileNameStr, boost::is_any_of(":"));
// We should ignore the archives if they start with '!' symbol
for (const auto& archive : archives)
{
if (!archive.empty() && archive[0] != '^')
{
oArchives.push_back(archive);
}
}
}
Alembic::Abc::IArchive getArchive(
Alembic::AbcCoreFactory::IFactory& iFactory,
const std::string& iFileNames,
Alembic::AbcCoreFactory::IFactory::CoreType& oType)
{
std::vector<std::string> archives;
splitArchives(iFileNames, archives);
Alembic::AbcCoreFactory::IFactory factory;
if (archives.size() == 0)
{
return Alembic::Abc::IArchive();
}
else if (archives.size() == 1)
{
return iFactory.getArchive(archives[0], oType);
}
return iFactory.getArchive(archives, oType);
}
class PathMap
{
public:
PathMap()
{
};
~PathMap()
{
}
WalterIn::AbcCookPtr get(const std::string & iFullName,
Alembic::Abc::IObject & iParent,
const std::string & iName)
{
boost::lock_guard<boost::mutex> lock(mutex);
std::map<std::string, WalterIn::AbcCookPtr>::iterator it =
pathMap.find(iFullName);
if (it != pathMap.end())
{
return it->second;
}
WalterIn::AbcCookPtr cookPtr(new WalterIn::AbcCook());
cookPtr->objPtr =
Alembic::Abc::IObjectPtr(new Alembic::Abc::IObject(iParent, iName));
pathMap[iFullName] = cookPtr;
return cookPtr;
}
private:
std::map<std::string, WalterIn::AbcCookPtr> pathMap;
boost::mutex mutex;
};
typedef boost::shared_ptr< PathMap > PathMapPtr;
// Building following structure:
// {"target": {"object": "shader"}},
// where target is shader/displacement/attribute, object is "/.*", shader is
// "marble1"
typedef std::map<WalterCommon::Expression, std::string> ObjectToShader;
typedef std::unordered_map<std::string, ObjectToShader> TargetToAssignments;
typedef boost::shared_ptr<TargetToAssignments> AssignmentsPtr;
// Building following structure:
// ({"target": "shader"})
typedef std::pair<std::string, std::string> Material;
typedef std::unordered_set<Material, boost::hash<Material>> ShaderSet;
typedef boost::shared_ptr<ShaderSet> ShaderSetPtr;
// Keeps all the atributes of Alembic
typedef FnAttribute::GroupAttribute GroupAttribute;
// The first is the standard attribute, the second is the user attribute.
typedef std::pair<GroupAttribute, GroupAttribute> AttributePair;
typedef std::unordered_map<std::string, AttributePair> Attributes;
typedef boost::shared_ptr<Attributes> AttributesPtr;
// Some of the KTOA attributes don't match to the Arnold attributes. We receive
// Arnold attributes, and we need to make KTOA understanding them. The only way
// to do it is remapping them.
static const WalterIn::NameMap arnoldAttributes = {
{"subdiv_iterations", "iterations"},
{"disp_zero_value", "zero_value"},
{"primary_visibility", "sidedness.AI_RAY_CAMERA"},
{"casts_shadows", "sidedness.AI_RAY_SHADOW"},
{"visible_in_reflections", "sidedness.AI_RAY_REFLECTED"},
{"visible_in_refractions", "sidedness.AI_RAY_REFRACTED"},
{"visible_in_diffuse", "sidedness.AI_RAY_DIFFUSE"},
{"visible_in_glossy", "sidedness.AI_RAY_GLOSSY"}};
// Read assignments from Alembic's root and save it to oAssignments
bool readAssignments(
Alembic::Abc::IObject iTop,
AssignmentsPtr oAssignments)
{
static const char* keys[] = {"shader", "displacement", "attribute"};
if (!oAssignments)
{
return false;
}
oAssignments->clear();
IWalterExpressionsSchema expressions;
if (!hasExpressions(iTop, expressions) || !expressions.valid())
{
return false;
}
for (size_t i=0; i<expressions.getNumProperties(); i++)
{
const std::string& objName = expressions.getExpression(i);
if (objName.empty())
{
continue;
}
IWalterLayersSchema layers = expressions.getLayerSchema(i);
if (!layers.valid())
{
continue;
}
for (size_t j=0; j<layers.getNumTargets(); j++)
{
// Skip all the render layers except the default one.
const std::string& layer = layers.getTargetName(j);
if (!layer.empty() && layer != "defaultRenderLayer")
{
continue;
}
BOOST_FOREACH (auto key, keys)
{
std::string value = layers.getShaderName(layer, key);
if (!value.empty())
{
(*oAssignments)[key].emplace(
std::piecewise_construct,
std::forward_as_tuple(objName),
std::forward_as_tuple(value));
}
}
}
}
return true;
}
// Read attributes from Alembic and save it to oAttributes
bool readAttributes(
Alembic::Abc::IObject iTop,
AttributesPtr oAttributes)
{
Alembic::Abc::IObject materials(iTop, "materials");
size_t numChildren = materials.getNumChildren();
for (size_t i = 0; i < numChildren; i++)
{
const Alembic::AbcCoreAbstract::ObjectHeader& header =
materials.getChildHeader(i);
const std::string& name = header.getName();
Alembic::AbcMaterial::IMaterial material(materials, name);
Alembic::AbcMaterial::IMaterialSchema& schema = material.getSchema();
std::string shader;
if (!schema.getShader("arnold", "attribute", shader) ||
shader != "walterOverride")
{
// We only need walterOverride.
continue;
}
Alembic::Abc::ICompoundProperty parameters =
schema.getShaderParameters("arnold", "attribute");
// Convert Alembic parameters to Katana.
auto cookPtr = boost::make_shared<WalterIn::AbcCook>();
FnAttribute::GroupBuilder parametersGroup;
processUserProperties(
cookPtr,
parameters,
parametersGroup,
"",
&arnoldAttributes);
// Save user parameters.
FnAttribute::GroupBuilder userParametersGroup;
processArnoldUserProperties(
cookPtr,
parameters,
userParametersGroup,
"");
// Save them to use in the future.
// TODO: emplace?
(*oAttributes)[name] =
std::make_pair(
parametersGroup.build(),
userParametersGroup.build());
}
}
// Returns the shader name for specified object, layer and target.
std::string getShaderAssignment(
const std::string& iObjectName,
const AssignmentsPtr& iAssignments,
const std::string& iTarget)
{
// target is shader/displacement/attribute
auto target = iAssignments->find(iTarget);
if (target == iAssignments->end())
{
return "";
}
const std::string* layers = WalterCommon::resolveAssignment<std::string>(
iObjectName, target->second);
if (!layers)
{
return "";
}
// Found. Use the line before '.' character.
const std::string& result = *layers;
return result.substr(0, result.find('.'));
}
// Analyze the assignments and make a list of materials with both surface and
// displacement shaders.
bool produceShaderSets(
const AssignmentsPtr& iAssignments,
ShaderSetPtr oShaderSet)
{
// Save all the surface and displacement shaders.
auto surfaceIt = iAssignments->find("shader");
auto displacementIt = iAssignments->find("displacement");
if (surfaceIt != iAssignments->end() &&
displacementIt != iAssignments->end())
{
// Iterate all the shaders to know if the combinations are possible.
for (const auto& surface : surfaceIt->second)
{
for (const auto& displacement : displacementIt->second)
{
const WalterCommon::Expression& surfExp = surface.first;
const WalterCommon::Expression& dispExp = displacement.first;
// The combination is possible if the expressions are the same
// and if it's possible to resolve the one with another as an
// expression.
if (!surfExp.isRegex() && !dispExp.isRegex())
{
const std::string& surfStr = surfExp.getExpression();
const std::string& dispStr = dispExp.getExpression();
// Both are direct paths.
if (!surfExp.isParentOf(dispStr, nullptr) &&
!dispExp.isParentOf(surfStr, nullptr))
{
// Both are not a parent of each others.
continue;
}
}
else if (
!surfExp.matchesPath(dispExp) &&
!dispExp.matchesPath(surfExp))
{
continue;
}
oShaderSet->emplace(surface.second, displacement.second);
}
}
}
return true;
}
// Add a default set of Arnold attributes to the node.
void setArnoldDefaults(Foundry::Katana::GeolibCookInterface &interface)
{
// We have only smoothing for now.
// We need smoothing because Arnold doesn't read normals it this attribute
// is off.
interface.setAttr(
"arnoldStatements.smoothing",
FnAttribute::IntAttribute(1));
}
struct ArchiveAndFriends
{
ArchiveAndFriends(Alembic::Abc::IArchive & iArchive,
Alembic::AbcCoreFactory::IFactory::CoreType iCoreType) :
pathMap(new PathMap()),
assignments(new TargetToAssignments()),
attributes(boost::make_shared<Attributes>()),
shaderSet(new ShaderSet())
{
objArchive = iArchive.getTop();
coreType = iCoreType;
// Read and initialize assignments
readAssignments(objArchive, assignments);
readAttributes(objArchive, attributes);
produceShaderSets(assignments, shaderSet);
}
Alembic::Abc::IObject objArchive;
Alembic::AbcCoreFactory::IFactory::CoreType coreType;
PathMapPtr pathMap;
// All the assignments of the cache
AssignmentsPtr assignments;
AttributesPtr attributes;
// List of materials with both surface and displacement shaders.
ShaderSetPtr shaderSet;
};
class AlembicCache :
public FnGeolibUtil::AttributeKeyedCache< ArchiveAndFriends >
{
public:
AlembicCache() :
FnGeolibUtil::AttributeKeyedCache< ArchiveAndFriends >(100, 1000)
{
factory.setPolicy(Alembic::Abc::ErrorHandler::kQuietNoopPolicy);
}
// number of streams to open per file
void setNumStreams( std::size_t iNumStreams )
{
factory.setOgawaNumStreams( iNumStreams );
}
private:
AlembicCache::IMPLPtr createValue(const FnAttribute::Attribute & iAttr)
{
AlembicCache::IMPLPtr val;
Alembic::AbcCoreFactory::IFactory::CoreType coreType;
Alembic::Abc::IArchive archive =
getArchive(
factory,
FnAttribute::StringAttribute(iAttr).getValue(),
coreType);
if ( archive.valid() )
{
val.reset(new ArchiveAndFriends(archive, coreType));
}
return val;
}
Alembic::AbcCoreFactory::IFactory factory;
};
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wexit-time-destructors"
#endif
AlembicCache g_cache;
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
class WalterInPrivateData : public Foundry::Katana::GeolibPrivateData
{
public:
WalterInPrivateData() :
Foundry::Katana::GeolibPrivateData(),
material(NULL)
{
}
virtual ~WalterInPrivateData(){};
WalterIn::AbcCookPtr cookPtr;
PathMapPtr pathMap;
// All the assignments of the cache
AssignmentsPtr assignments;
// All the attributes
AttributesPtr attributes;
// List of materials with both surface and displacement shaders.
ShaderSetPtr shaderSet;
// TODO: use reference
std::string root;
// Pointer to material inside shaderSet. Used to generate virtual materials.
const Material* material;
// We save the parent's material to be able to skip material assignment if
// it's already assigned to the parent and produce clean data.
std::string parentMaterial;
};
WalterIn::AbcCookPtr getTopObject(
const FnAttribute::StringAttribute & iAttr,
const FnAttribute::StringAttribute & iRootAttr,
std::string & oOpType,
PathMapPtr & oPathMap,
AssignmentsPtr& oAssignments,
AttributesPtr& oAttributes,
ShaderSetPtr& oShaderSet)
{
WalterIn::AbcCookPtr retVal;
Alembic::Abc::IObject obj;
AlembicCache::IMPLPtr entry = g_cache.getValue(iAttr);
if (!entry || !entry->objArchive.valid())
{
return retVal;
}
obj = entry->objArchive;
std::string pathToRoot;
if (iRootAttr.isValid())
{
pathToRoot = iRootAttr.getValue();
}
if (!pathToRoot.empty())
{
std::vector< std::string > tokens;
pathToRoot = pystring::strip(pathToRoot, " /\n\t");
pystring::split(pathToRoot, tokens, "/");
std::vector< std::string >::const_iterator i;
for (i = tokens.begin(); i != tokens.end(); ++i)
{
if (!obj.getChildHeader(*i))
{
return retVal;
}
obj = obj.getChild(*i);
}
}
// TODO, do something with entry->coreType
if (entry->coreType == Alembic::AbcCoreFactory::IFactory::kOgawa)
{
oOpType = "WalterInOgawa";
}
else if (entry->coreType == Alembic::AbcCoreFactory::IFactory::kHDF5)
{
oOpType = "WalterInHDF";
}
else if (entry->coreType == Alembic::AbcCoreFactory::IFactory::kLayer)
{
oOpType = "WalterInLayer";
}
retVal = WalterIn::AbcCookPtr(new WalterIn::AbcCook());
retVal->objPtr = Alembic::Abc::IObjectPtr(new Alembic::Abc::IObject(obj));
if (retVal->objPtr->valid())
{
Alembic::Abc::ICompoundProperty prop = retVal->objPtr->getProperties();
const Alembic::Abc::PropertyHeader * childBnds =
prop.getPropertyHeader(".childBnds");
if (childBnds)
{
FnAttribute::GroupBuilder staticGb;
scalarPropertyToAttr(prop, *childBnds, "bound", retVal, staticGb);
retVal->staticGroup = staticGb.build();
}
}
oPathMap = entry->pathMap;
oAssignments = entry->assignments;
oAttributes = entry->attributes;
oShaderSet = entry->shaderSet;
return retVal;
}
// Report fatal errors to the scene graph and halt traversal.
static void reportAlembicError(Foundry::Katana::GeolibCookInterface &interface,
const std::string &filePath,
const std::string &errorMessage)
{
interface.setAttr("type", FnAttribute::StringAttribute("error"));
interface.setAttr("errorMessage",
FnAttribute::StringAttribute("Can not load: " +
filePath + " : " +
errorMessage));
interface.stopChildTraversal();
return;
}
// Extracts bookkeeping information from an AbcCook pointer and sets them
// under the 'info' attribute at the root location.
static void fillRootInfo(Foundry::Katana::GeolibCookInterface &interface,
WalterIn::AbcCookPtr ioCookPtr)
{
if (!ioCookPtr->objPtr || ioCookPtr->objPtr->getParent().valid())
{
return;
}
double fps = FnAttribute::DoubleAttribute(interface.getOpArg(
"fps")).getValue(24.0, false);
std::vector<double> frameRange(2);
frameRange[0] = DBL_MAX;
frameRange[1] = -DBL_MAX;
Alembic::Abc::IArchive archive = ioCookPtr->objPtr->getArchive();
uint32_t numSampling = archive.getNumTimeSamplings();
// ignore the default time sampling at index 0
for (uint32_t i = 1; i < numSampling; ++i)
{
Alembic::AbcCoreAbstract::index_t maxIndex =
archive.getMaxNumSamplesForTimeSamplingIndex(i);
if (maxIndex < 2 || maxIndex == INDEX_UNKNOWN)
{
continue;
}
Alembic::AbcCoreAbstract::TimeSamplingPtr ts =
archive.getTimeSampling(i);
std::vector<double> samples(maxIndex);
for (Alembic::AbcCoreAbstract::index_t j = 0; j < maxIndex; ++j)
{
samples[j] = ts->getSampleTime(j) * fps;
}
if (samples.front() < frameRange[0])
{
frameRange[0] = samples.front();
}
if (samples.back() < frameRange[0])
{
frameRange[0] = samples.back();
}
if (samples.front() > frameRange[1])
{
frameRange[1] = samples.front();
}
if (samples.back() > frameRange[1])
{
frameRange[1] = samples.back();
}
std::stringstream strm;
strm << "info.frameSamples" << i;
interface.setAttr(strm.str().c_str(), FnAttribute::DoubleAttribute(
&(samples.front()), samples.size(), 1));
}
if (frameRange[0] < frameRange[1])
{
interface.setAttr("info.frameRange", FnAttribute::DoubleAttribute(
&(frameRange.front()), frameRange.size(), 1));
}
}
// Builds and returns a GroupAttribute from an AbcCookPtr with all its
// static and non-static properties.
static FnAttribute::GroupAttribute getAllProps(
const Foundry::Katana::GeolibCookInterface &interface,
const WalterIn::AbcCookPtr &ioCookPtr)
{
if (!ioCookPtr->arrayProps.empty() || !ioCookPtr->scalarProps.empty() ||
ioCookPtr->objPtr || ioCookPtr->visProp.valid())
{
// let's get our other args which we will need for our animated
// reads
WalterIn::OpArgs args;
args.currentTime = FnAttribute::FloatAttribute(interface.getOpArg(
"system.timeSlice.currentTime")).getValue(0.0, false);
args.shutterOpen = FnAttribute::FloatAttribute(interface.getOpArg(
"system.timeSlice.shutterOpen")).getValue(0.0, false);
args.shutterClose = FnAttribute::FloatAttribute(interface.getOpArg(
"system.timeSlice.shutterClose")).getValue(0.0, false);
args.numSamples = FnAttribute::IntAttribute(interface.getOpArg(
"system.timeSlice.numSamples")).getValue(0, false);
args.fps = FnAttribute::DoubleAttribute(interface.getOpArg(
"fps")).getValue(24.0, false);
std::string beyondRange =
FnAttribute::StringAttribute(interface.getOpArg(
"beyondRangeBehavior")).getValue("", false);
if (beyondRange == "error")
{
args.behavior = WalterIn::OpArgs::kError;
}
else if (beyondRange == "hold")
{
args.behavior = WalterIn::OpArgs::kHold;
}
const int useOnlyShutterOpenCloseTimesFlag =
FnAttribute::IntAttribute(interface.getOpArg(
"useOnlyShutterOpenCloseTimes")).getValue(0, false);
args.useOnlyShutterOpenCloseTimes =
(useOnlyShutterOpenCloseTimesFlag == 1);
FnAttribute::GroupBuilder bld;
{
// Query to ioCookPtr->staticGroup should be locked. It's not locked
// in the original Alembic because they don't have setAttributes()
// and they don't access it from there.
boost::lock_guard<boost::mutex> lock(ioCookPtr->mutex);
bld.deepUpdate(ioCookPtr->staticGroup);
}
Alembic::Abc::IUInt64ArrayProperty idsProp;
Alembic::Abc::IUInt64ArrayProperty * iIdsProperty = NULL;
if (ioCookPtr->objPtr)
{
const Alembic::AbcCoreAbstract::ObjectHeader & header =
ioCookPtr->objPtr->getHeader();
if (Alembic::AbcGeom::IPoints::matches(header))
{
Alembic::AbcGeom::IPointsPtr objPtr(
new Alembic::AbcGeom::IPoints(*(ioCookPtr->objPtr),
Alembic::AbcGeom::kWrapExisting));
Alembic::AbcGeom::IPointsSchema schema = objPtr->getSchema();
idsProp = schema.getIdsProperty();
if (idsProp.valid())
{
iIdsProperty = &idsProp;
}
}
}
for (std::vector< WalterIn::ArrayProp >::iterator at =
ioCookPtr->arrayProps.begin();
at != ioCookPtr->arrayProps.end(); ++at)
{
if (iIdsProperty && at->prop.getPtr() != iIdsProperty->getPtr())
{
WalterIn::arrayPropertyToAttr(*at, args, bld, iIdsProperty);
}
else
{
WalterIn::arrayPropertyToAttr(*at, args, bld);
}
}
for (std::vector< WalterIn::ScalarProp >::iterator st =
ioCookPtr->scalarProps.begin();
st != ioCookPtr->scalarProps.end(); ++st)
{
WalterIn::scalarPropertyToAttr(*st, args, bld);
}
for (std::vector< WalterIn::IndexedGeomParamPair >::iterator ft =
ioCookPtr->forcedExpandProps.begin();
ft != ioCookPtr->forcedExpandProps.end(); ++ft)
{
WalterIn::indexedParamToAttr(*ft, args, bld);
}
if (ioCookPtr->animatedSchema)
{
WalterIn::evalObject(ioCookPtr, args, bld, iIdsProperty);
}
return bld.build();
}
// no animation set our static attrs
return ioCookPtr->staticGroup;
}
static void setAllAttrs(Foundry::Katana::GeolibCookInterface &interface,
const FnAttribute::GroupAttribute &attrs)
{
for (int64_t i = 0; i < attrs.getNumberOfChildren(); ++i)
{
interface.setAttr(attrs.getChildName(i), attrs.getChildByIndex(i));
}
}
// Set the material. Returns material assigned on the current object or parent.
static std::string setAssignment(
Foundry::Katana::GeolibCookInterface &interface,
const std::string& iName,
const AssignmentsPtr& iAssignments,
const std::string& iRoot,
const std::string& iParentMaterial)
{
const std::string shader =
getShaderAssignment(iName, iAssignments, "shader");
const std::string displacement =
getShaderAssignment(iName, iAssignments, "displacement");
std::vector<std::string> names;
if (!shader.empty())
{
names.push_back(shader);
}
if (!displacement.empty())
{
names.push_back(displacement);
}
if (names.empty())
{
return "";
}
const std::string material =
iRoot + "/materials/" + boost::algorithm::join(names, "_");
if (material != iParentMaterial)
{
// Assign material only if the parent doesn't have the same material.
// TODO: use ioCookPtr->staticGroup for that
interface.setAttr(
"materialAssign",
FnAttribute::StringAttribute(material));
}
return material;
}
// Set the material. Returns material assigned on the current object or parent.
static std::string setAttributes(
const WalterIn::AbcCookPtr &ioCookPtr,
const AssignmentsPtr& iAssignments,
const AttributesPtr& iAttributes,
const std::string& iRoot,
const std::string& iParentAttributes)
{
const std::string& name = ioCookPtr->objPtr->getFullName();
const std::string attributes =
getShaderAssignment(name, iAssignments, "attribute");
if (attributes.empty())
{
return "";
}
auto it = iAttributes->find(attributes);
if (it != iAttributes->end() && attributes != iParentAttributes)
{
FnAttribute::GroupBuilder walterBuilder;
walterBuilder.set("arnoldStatements", it->second.first);
// Set the User Data. KTOA needs it at "geometry.arbitrary".
walterBuilder.set("geometry.arbitrary", it->second.second);
// Query to ioCookPtr->staticGroup should be locked.
boost::lock_guard<boost::mutex> lock(ioCookPtr->mutex);
// Katana magic to merge groups. We don't use `set`, `update`,
// `interface::setAttr` because it removes the children and replaces
// entire group and there is a chance that we loose something important
// that was there from the original Alembic because we fill the
// "geometry.arbitrary" group from two places. From Arnold code and the
// code related to Walter Override. We loosed attributes when there were
// intersections because Katana overrode whole group. It's fixed with
// following Katana magic.
FnAttribute::GroupBuilder groupBuilder;
groupBuilder.update(ioCookPtr->staticGroup);
groupBuilder.deepUpdate(walterBuilder.build());
ioCookPtr->staticGroup = groupBuilder.build();
}
return attributes;
}
// Set the material. Returns materials assigned on the current object or parent.
// This flavor of the setAttributes function is to be used on already created
// Katana locations (usually generated by a WalterInOp).
static std::string setAttributes(
Foundry::Katana::GeolibCookInterface &iInterface,
const std::string& iName,
const AssignmentsPtr& iAssignments,
const AttributesPtr& iAttributes,
const std::string& iRoot,
const std::string& iParentAttributes)
{
const std::string attributes =
getShaderAssignment(iName, iAssignments, "attribute");
if (attributes.empty())
{
return "";
}
auto it = iAttributes->find(attributes);
if (it != iAttributes->end() && attributes != iParentAttributes)
{
iInterface.setAttr("arnoldStatements", it->second.first);
iInterface.setAttr("geometry.arbitrary", it->second.second);
}
return attributes;
}
// Utility function to handle extracting all the properties from an AbcCookPtr
// as a GroupAttribute and setting them on the current location.
// Returns material name assigned on the current object or parent.
static void fillAllProps(
Foundry::Katana::GeolibCookInterface &interface,
WalterIn::AbcCookPtr ioCookPtr,
const AssignmentsPtr& iAssignments,
const AttributesPtr& iAttributes,
const std::string& iRoot,
const std::string& iParentMaterial,
std::string& oAssignedMaterial,
std::string& oAssignedAttributes)
{
fillRootInfo(interface, ioCookPtr);
oAssignedMaterial = setAssignment(
interface,
ioCookPtr->objPtr->getFullName(),
iAssignments,
iRoot,
iParentMaterial);
oAssignedAttributes = setAttributes(
ioCookPtr, iAssignments, iAttributes, iRoot, iParentMaterial);
FnAttribute::GroupAttribute allProps = getAllProps(interface, ioCookPtr);
setAllAttrs(interface, allProps);
}
static void cookAlembic(
Foundry::Katana::GeolibCookInterface &interface,
const std::string & iOpType,
WalterIn::AbcCookPtr ioCookPtr,
PathMapPtr & iPathMap,
const AssignmentsPtr& iAssignments,
const AttributesPtr& iAttributes,
const ShaderSetPtr& iShaderSet,
const std::string& iRoot,
const std::string& iParentMaterial)
{
if (!ioCookPtr->staticGroup.isValid())
{
boost::lock_guard<boost::mutex> lock(ioCookPtr->mutex);
if (!ioCookPtr->staticGroup.isValid())
{
FnAttribute::GroupBuilder staticBld;
WalterIn::initAbcCook(ioCookPtr, staticBld);
ioCookPtr->staticGroup = staticBld.build();
}
}
std::string assignedMaterial;
std::string assignedAttributes;
fillAllProps(
interface,
ioCookPtr,
iAssignments,
iAttributes,
iRoot,
iParentMaterial,
assignedMaterial,
assignedAttributes);
// Check if we need to add "forceExpand".
FnAttribute::IntAttribute addForceExpandAttr =
interface.getOpArg("addForceExpand");
// In case we found "addForceExpand" we have to remove it from the opArgs
// so that it will be set only by the first-level children
FnAttribute::Attribute childOpArgs = interface.getOpArg();
if (addForceExpandAttr.isValid() && addForceExpandAttr.getValue(1, false))
{
interface.setAttr("forceExpand", FnAttribute::IntAttribute(1));
FnAttribute::GroupBuilder newOpArgs;
newOpArgs.update(childOpArgs);
newOpArgs.del("addForceExpand");
childOpArgs = newOpArgs.build();
}
// Check wether we need to copy the bounds from our parent
FnAttribute::DoubleAttribute parentBound =
interface.getOpArg("parentBound");
if (parentBound.isValid())
{
FnAttribute::GroupBuilder boundsFromParentOpArgsGb;
boundsFromParentOpArgsGb.set("parentBound", parentBound);
interface.execOp("BoundsFromParent", boundsFromParentOpArgsGb.build());
// Remove the parent bound from the OpArgs since we do not want the
// grandchildren to set it.
FnAttribute::GroupBuilder newOpArgs;
newOpArgs.update(childOpArgs);
newOpArgs.del("parentBound");
childOpArgs = newOpArgs.build();
}
std::size_t numChildren = ioCookPtr->objPtr->getNumChildren();
for (std::size_t i = 0; i < numChildren; ++i)
{
const Alembic::AbcCoreAbstract::ObjectHeader & header =
ioCookPtr->objPtr->getChildHeader(i);
WalterInPrivateData * childData = new WalterInPrivateData();
childData->pathMap = iPathMap;
childData->assignments = iAssignments;
childData->attributes = iAttributes;
childData->shaderSet = iShaderSet;
childData->cookPtr = iPathMap->get(header.getFullName(),
*ioCookPtr->objPtr, header.getName());
childData->root = iRoot;
childData->parentMaterial = assignedMaterial;
interface.createChild(header.getName(), iOpType, childOpArgs,
Foundry::Katana::GeolibCookInterface::ResetRootAuto, childData,
WalterInPrivateData::Delete);
}
if (ioCookPtr->objPtr->getFullName() == "/materials")
{
// Add virtual shaders.
BOOST_FOREACH (const auto& material, *iShaderSet)
{
std::string name = material.first + "_" + material.second;
WalterInPrivateData * childData = new WalterInPrivateData();
childData->pathMap = iPathMap;
childData->root = iRoot;
childData->material = &material;
childData->cookPtr = ioCookPtr;
interface.createChild(
name,
"WalterInVirtualMat",
childOpArgs,
Foundry::Katana::GeolibCookInterface::ResetRootAuto,
childData,
WalterInPrivateData::Delete);
}
}
}
class WalterInHDFOp : public Foundry::Katana::GeolibOp
{
public:
static void setup(Foundry::Katana::GeolibSetupInterface &interface)
{
interface.setThreading(Foundry::Katana::GeolibSetupInterface::ThreadModeGlobalUnsafe);
}
static void cook(Foundry::Katana::GeolibCookInterface &interface)
{
WalterInPrivateData *privateData =
static_cast<WalterInPrivateData *>(interface.getPrivateData());
if (!privateData || !privateData->cookPtr || !privateData->pathMap)
{
interface.stopChildTraversal();
return;
}
cookAlembic(
interface,
"WalterInHDF",
privateData->cookPtr,
privateData->pathMap,
privateData->assignments,
privateData->attributes,
privateData->shaderSet,
privateData->root,
privateData->parentMaterial);
}
};
class WalterAssignOp : public Foundry::Katana::GeolibOp
{
public:
static void setup(Foundry::Katana::GeolibSetupInterface& interface)
{
interface.setThreading(
Foundry::Katana::GeolibSetupInterface::ThreadModeConcurrent);
}
static void cook(Foundry::Katana::GeolibCookInterface& interface)
{
// In order to run the Op we need a valid CEL statement
FnAttribute::StringAttribute celAttr = interface.getOpArg("CEL");
if (!celAttr.isValid())
{
interface.stopChildTraversal();
return;
}
FnGeolibServices::FnGeolibCookInterfaceUtils::MatchesCELInfo info;
FnGeolibServices::FnGeolibCookInterfaceUtils::matchesCEL(
info, interface, celAttr);
if (!info.canMatchChildren)
{
interface.stopChildTraversal();
}
// If the CEL doesn't match the current location, stop cooking
if (!info.matches)
{
return;
}
FnAttribute::StringAttribute fileAttr = interface.getOpArg("fileName");
std::vector<std::string> archives;
if (fileAttr.isValid())
{
splitArchives(fileAttr.getValue(), archives);
}
if (archives.empty())
{
interface.setAttr("type", FnAttribute::StringAttribute("error"));
interface.setAttr("errorMessage",
FnAttribute::StringAttribute("No file specified"));
interface.stopChildTraversal();
return;
}
FnAttribute::StringAttribute rootAttr = interface.getOpArg("root");
if(!rootAttr.isValid())
{
return;
}
const std::string root = rootAttr.getValue();
const std::string inputLocation = interface.getInputLocationPath();
if(inputLocation.size() < root.size() || inputLocation.size() == root.size())
{
return;
}
const std::string objPath = inputLocation.substr(root.size());
AlembicCache::IMPLPtr entry = g_cache.getValue(fileAttr);
setAssignment(interface, objPath, entry->assignments, root, "");
setAttributes(
interface,
objPath,
entry->assignments,
entry->attributes,
root,
"");
}
};
class WalterInOgawaOp : public Foundry::Katana::GeolibOp
{
public:
static void setup(Foundry::Katana::GeolibSetupInterface &interface)
{
interface.setThreading(Foundry::Katana::GeolibSetupInterface::ThreadModeConcurrent);
}
static void cook(Foundry::Katana::GeolibCookInterface &interface)
{
WalterInPrivateData *privateData =
static_cast<WalterInPrivateData *>(interface.getPrivateData());
if (!privateData || !privateData->cookPtr || !privateData->pathMap)
{
interface.stopChildTraversal();
return;
}
cookAlembic(
interface,
"WalterInOgawa",
privateData->cookPtr,
privateData->pathMap,
privateData->assignments,
privateData->attributes,
privateData->shaderSet,
privateData->root,
privateData->parentMaterial);
}
};
// Virtual shaders.
class WalterInVirtualMatOp : public Foundry::Katana::GeolibOp
{
public:
static void setup(Foundry::Katana::GeolibSetupInterface &interface)
{
interface.setThreading(
Foundry::Katana::GeolibSetupInterface::ThreadModeConcurrent);
}
static void cook(Foundry::Katana::GeolibCookInterface &interface)
{
WalterInPrivateData *privateData =
static_cast<WalterInPrivateData *>(interface.getPrivateData());
if (!privateData ||
!privateData->cookPtr ||
!privateData->pathMap ||
!privateData->material)
{
interface.stopChildTraversal();
return;
}
const std::string& shaderName = privateData->material->first;
const std::string& displacementName = privateData->material->second;
const std::string& parentName =
privateData->cookPtr->objPtr->getFullName();
std::string fullShaderName = parentName + "/" + shaderName;
std::string fullDisplacementName = displacementName + "/" + shaderName;
WalterIn::AbcCookPtr shaderCookPtr = privateData->pathMap->get(
fullShaderName, *privateData->cookPtr->objPtr, shaderName);
WalterIn::AbcCookPtr displacementCookPtr = privateData->pathMap->get(
fullDisplacementName,
*privateData->cookPtr->objPtr,
displacementName);
if (!shaderCookPtr || !displacementCookPtr)
{
return;
}
FnAttribute::GroupBuilder staticBld;
WalterIn::initAbcCook(shaderCookPtr, staticBld);
WalterIn::initAbcCook(displacementCookPtr, staticBld);
setAllAttrs(interface, staticBld.build());
}
};
class WalterInLayerOp : public WalterInOgawaOp
{
};
class WalterInOp : public Foundry::Katana::GeolibOp
{
public:
static void setup(Foundry::Katana::GeolibSetupInterface &interface)
{
// FIXME: Should this top level Alembic op being more optimistic?
// (I.e., concurrent). For the pure ogawa situation, it would be
// nice if ThreadModeGlobalUnsafe was *never* encountered by the runtime.
interface.setThreading(Foundry::Katana::GeolibSetupInterface::ThreadModeGlobalUnsafe);
}
static void cook(Foundry::Katana::GeolibCookInterface &interface)
{
FnAttribute::StringAttribute fileAttr = interface.getOpArg("fileName");
std::vector<std::string> archives;
if (fileAttr.isValid())
{
splitArchives(fileAttr.getValue(), archives);
}
if (archives.empty())
{
interface.setAttr("type", FnAttribute::StringAttribute("error"));
interface.setAttr("errorMessage",
FnAttribute::StringAttribute("No file specified"));
interface.stopChildTraversal();
return;
}
else
{
// Check if layers have a usd file. In this way it should be a USD
// variant of WalterIn.
bool isUSD = false;
// Check if we have to force USD engine to load this node.
auto forceUSDAttr = interface.getOpArg("forceUSD");
int forceUSD =
FnAttribute::IntAttribute(forceUSDAttr).getValue(0, false);
if (!forceUSD)
{
for (const std::string& f : archives)
{
if (f.find(".usd") != std::string::npos)
{
isUSD = true;
break;
}
}
}
if (isUSD || forceUSD)
{
cookUSDRoot(interface, archives);
return;
}
}
FnAttribute::StringAttribute pathFromRootAttr =
interface.getOpArg("pathFromRoot");
PathMapPtr pathMap;
AssignmentsPtr assignments;
AttributesPtr attributes;
ShaderSetPtr shaderSet;
std::string opType;
WalterIn::AbcCookPtr curObj =
getTopObject(
fileAttr,
pathFromRootAttr,
opType,
pathMap,
assignments,
attributes,
shaderSet);
const std::string filePath = fileAttr.getValue();
// Check and report our error conditions
if(!curObj)
{
reportAlembicError(interface, filePath, "Top-level object was NULL");
return;
}
if(!curObj->objPtr)
{
reportAlembicError(interface, filePath, "Got top-level object but objPtr was NULL");
return;
}
if(!curObj->objPtr->valid())
{
reportAlembicError(interface, filePath, "Top-level objPtr was invalid");
return;
}
if(opType == "")
{
reportAlembicError(interface, filePath, "Specified opType was empty");
return;
}
if(!pathMap)
{
reportAlembicError(interface, filePath, "Path map was NULL");
return;
}
// Check if we need to set bounds. On the root we can set it here,
// for the children we pass it as opArg for them to deal with it.
std::string addBounds = FnAttribute::StringAttribute(
interface.getOpArg("addBounds")).getValue("none", false);
FnAttribute::GroupAttribute childOpArgs = interface.getOpArg();
if (addBounds != "none")
{
fillRootInfo(interface, curObj);
FnAttribute::GroupAttribute allProps = getAllProps(interface,
curObj);
FnAttribute::DoubleAttribute rootBound =
allProps.getChildByName("bound");
if (rootBound.isValid()
&& (addBounds == "both" || addBounds == "children"))
{
// If we want the children to inherit the bound we need to
// pass it via the OpArgs
FnAttribute::GroupBuilder gb;
gb.update(childOpArgs);
gb.set("parentBound", rootBound);
childOpArgs = gb.build();
}
if (addBounds == "children")
{
// remove bound from the attribute to set
FnAttribute::GroupBuilder gb;
gb.update(allProps);
gb.del("bound");
allProps = gb.build();
}
setAllAttrs(interface, allProps);
}
// Check if we need to set Arnold defaults. We should do it on the root
// only.
std::string addDefaultAttrs = FnAttribute::StringAttribute(
interface.getOpArg("addDefaultAttrs")).getValue("Arnold", false);
if (addDefaultAttrs == "Arnold")
{
setArnoldDefaults(interface);
}
// invoke the children
std::size_t numChildren = curObj->objPtr->getNumChildren();
for (std::size_t i = 0; i < numChildren; ++i)
{
const Alembic::AbcCoreAbstract::ObjectHeader & header =
curObj->objPtr->getChildHeader(i);
WalterInPrivateData * childData = new WalterInPrivateData();
childData->pathMap = pathMap;
childData->assignments = assignments;
childData->attributes = attributes;
childData->shaderSet = shaderSet;
childData->cookPtr = pathMap->get(header.getFullName(),
*curObj->objPtr, header.getName());
childData->root = interface.getOutputLocationPath();
interface.createChild(header.getName(), opType,
childOpArgs,
Foundry::Katana::GeolibCookInterface::ResetRootAuto, childData,
WalterInPrivateData::Delete);
}
}
static void flush()
{
g_cache.clear();
}
};
DEFINE_GEOLIBOP_PLUGIN(WalterInOp)
DEFINE_GEOLIBOP_PLUGIN(WalterAssignOp)
DEFINE_GEOLIBOP_PLUGIN(WalterInHDFOp)
DEFINE_GEOLIBOP_PLUGIN(WalterInOgawaOp)
DEFINE_GEOLIBOP_PLUGIN(WalterInLayerOp)
DEFINE_GEOLIBOP_PLUGIN(WalterInVirtualMatOp)
class CameraAndLightPathCache :
public FnGeolibUtil::AttributeKeyedCache< FnAttribute::GroupAttribute >
{
private:
CameraAndLightPathCache::IMPLPtr createValue(const FnAttribute::Attribute & iAttr)
{
CameraAndLightPathCache::IMPLPtr val(new FnAttribute::GroupAttribute);
Alembic::AbcCoreFactory::IFactory factory;
Alembic::AbcCoreFactory::IFactory::CoreType coreType;
std::string attrValue =
FnAttribute::StringAttribute(iAttr).getValue("", false);
std::vector<std::string> archives;
splitArchives(attrValue, archives);
// Check if layers have a usd file. In this way it should be a USD
// variant of WalterIn.
bool isUSD = false;
for (const std::string& f : archives)
{
if (f.find(".usd") != std::string::npos)
{
isUSD = true;
break;
}
}
std::vector<std::string> cameras, lights;
if (isUSD)
{
SdfLayerRefPtr root = WalterUSDCommonUtils::getUSDLayer(archives);
const UsdStageRefPtr stage = UsdStage::Open(root);
UsdPrim rootPrim = stage->GetPseudoRoot();
walk(rootPrim, cameras, lights);
}
else
{
Alembic::Abc::IArchive archive =
getArchive(factory, attrValue, coreType);
if (archive.valid())
{
walk(archive.getTop(), cameras, lights);
}
}
val.reset(
new FnAttribute::GroupAttribute(
"cameras", FnAttribute::StringAttribute(cameras, 1),
"lights", FnAttribute::StringAttribute(lights, 1),
true)
);
return val;
}
void walk(Alembic::Abc::IObject object, std::vector<std::string> & cameras,
std::vector<std::string> & lights)
{
if (!object.valid())
{
return;
}
if (Alembic::AbcGeom::ICamera::matches(object.getHeader()))
{
cameras.push_back(object.getFullName());
}
else if (Alembic::AbcGeom::ILight::matches(object.getHeader()))
{
lights.push_back(object.getFullName());
}
for (size_t i = 0, e = object.getNumChildren(); i < e; ++i)
{
walk(object.getChild(i), cameras, lights);
}
}
void walk(UsdPrim prim, std::vector<std::string> & cameras,
std::vector<std::string> & lights)
{
if (prim.IsA<UsdGeomCamera>())
{
cameras.push_back(prim.GetPath().GetString());
}
else if (prim.IsA<UsdLuxLight>())
{
lights.push_back(prim.GetPath().GetString());
}
for (const UsdPrim& childPrim: prim.GetChildren())
{
walk(childPrim, cameras, lights);
}
}
};
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wexit-time-destructors"
#endif
CameraAndLightPathCache g_cameraAndLightCache;
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
class WalterInAddToLightAndCameraListsOp : public Foundry::Katana::GeolibOp
{
public:
static void setup(Foundry::Katana::GeolibSetupInterface& interface)
{
interface.setThreading(
Foundry::Katana::GeolibSetupInterface::ThreadModeGlobalUnsafe);
}
static void cook(Foundry::Katana::GeolibCookInterface& interface)
{
interface.stopChildTraversal();
bool setLightList = false;
bool setCamList = false;
FnAttribute::IntAttribute setLightListAttr =
FnAttribute::IntAttribute(interface.getOpArg("setLightList"));
if(setLightListAttr.isValid())
{
setLightList = static_cast<bool>(setLightListAttr.getValue());
}
FnAttribute::IntAttribute setCamListAttr =
FnAttribute::IntAttribute(interface.getOpArg("setCameraList"));
if(setCamListAttr.isValid())
{
setCamList = static_cast<bool>(setCamListAttr.getValue());
}
FnAttribute::GroupAttribute pathsGroup =
*(g_cameraAndLightCache.getValue(interface.getOpArg("fileName")));
if (!pathsGroup.isValid())
{
return;
}
std::string scenegraphPath =
FnAttribute::StringAttribute(interface.getOpArg("scenegraphPath"))
.getValue("/root", false);
if (setLightList)
{
// Add lights
FnAttribute::StringAttribute ligthsAttr =
pathsGroup.getChildByName("lights");
if (ligthsAttr.isValid() && ligthsAttr.getNumberOfValues())
{
std::vector<std::string> lightList;
lightList.reserve(ligthsAttr.getNumberOfValues());
FnAttribute::StringAttribute::array_type values =
ligthsAttr.getNearestSample(0.0);
for (FnAttribute::StringAttribute::array_type::const_iterator
I = values.begin(),
E = values.end();
I != E;
++I)
{
const std::string lightPath = scenegraphPath + (*I);
lightList.emplace_back(scenegraphPath + (*I));
const std::string prefix =
pystring::replace(lightPath, "/", "_");
interface.extendAttr(
"lightList." + prefix + ".path",
FnAttribute::StringAttribute(lightPath),
"",
false);
}
}
}
if (setCamList)
{
// Add cameras
FnAttribute::StringAttribute camerasAttr =
pathsGroup.getChildByName("cameras");
if (camerasAttr.isValid() && camerasAttr.getNumberOfValues())
{
std::vector<std::string> cameraList;
cameraList.reserve(camerasAttr.getNumberOfValues());
FnAttribute::StringAttribute::array_type values =
camerasAttr.getNearestSample(0.0);
for (FnAttribute::StringAttribute::array_type::const_iterator
I = values.begin(),
E = values.end();
I != E;
++I)
{
cameraList.emplace_back(scenegraphPath + (*I));
}
interface.extendAttr(
"globals.cameraList",
FnAttribute::StringAttribute(cameraList),
"",
false);
}
}
}
};
DEFINE_GEOLIBOP_PLUGIN(WalterInAddToLightAndCameraListsOp)
} // anonymous
void registerPlugins()
{
H5dont_atexit();
REGISTER_PLUGIN(WalterInOp, "WalterIn", 0, 1);
REGISTER_PLUGIN(WalterAssignOp, "WalterAssign", 0, 1);
REGISTER_PLUGIN(WalterInHDFOp, "WalterInHDF", 0, 1);
REGISTER_PLUGIN(WalterInOgawaOp, "WalterInOgawa", 0, 1);
REGISTER_PLUGIN(WalterInLayerOp, "WalterInLayer", 0, 1);
REGISTER_PLUGIN(WalterInVirtualMatOp, "WalterInVirtualMat", 0, 1);
REGISTER_PLUGIN(WalterInAddToLightAndCameraListsOp,
"WalterInAddToLightAndCameraLists", 0, 1);
registerUSDPlugins();
}
<|start_filename|>walter/usd/tests/test_resources_GetFileStream.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
/*
This test check that we can load glslfx from the Walter resources.
To do that we are patching the Usd file 'glslfx.cpp' by overriding
_GetFileStream() (that is called in GlfGLSLFX constructor).
*/
#include <pxr/imaging/glf/glslfx.h>
#include <gtest/gtest.h>
PXR_NAMESPACE_USING_DIRECTIVE
const std::string sources = R"(// line 50 "fallbackSurface.glslfx"
vec4 surfaceShader(vec4 Peye, vec3 Neye, vec4 color, vec4 patchCoord)
{
// lighting
color.rgb = FallbackLighting(Peye.xyz, Neye, color.rgb);
return color;
}
)";
TEST(test_resources_GetFileStream, fallbackSurface)
{
GlfGLSLFX glslfx("fallbackSurface.glslfx");
EXPECT_TRUE(glslfx.IsValid());
EXPECT_EQ(glslfx.GetSurfaceSource(), sources);
}
<|start_filename|>Makefile<|end_filename|>
################################################################################
# Copyright 2018 <NAME>. All rights reserved.
#
# Master Makefile to build Walter and all its dependencies
#
# VFX platform libraries and Walter are built using this file.
# Usd and Walter are built in two flavors. A 'dcc' one the for Katana, Houdini
# and Maya plugins and a 'procedural' one for the Arnold.
#
# Run 'make help' to list helpful targets.
#
################################################################################
#===============================================================================
# Set environment variables for the build.
# 'Release' or 'Debug'
MAKE_MODE := release
ifeq "$(MAKE_MODE)" "debug"
CMAKE_BUILD_TYPE := Debug
else
CMAKE_BUILD_TYPE := Release
endif
VERBOSE := 1
BUILD_TESTS := ON
BUILD_HOUDINI_PLUGINS := ON
BUILD_KATANA_PLUGINS := ON
BUILD_MAYA_PLUGINS := ON
BUILD_VIEWER := ON
THIS_DIR = $(shell pwd)
JOB_COUNT := $(shell cat /sys/devices/system/cpu/cpu*/topology/thread_siblings | wc -l)
SOURCES_ROOT := ${THIS_DIR}/build/src
BUILD_ROOT := ${THIS_DIR}/build/build
PREFIX_ROOT := ${THIS_DIR}/build/lib
USD_DCC_PACKAGE_NAME := usdDCC
USD_DCC_STAMP := $(PREFIX_ROOT)/built_$(USD_DCC_PACKAGE_NAME)
USD_PROCEDURAL_PACKAGE_NAME := usdProcedural
USD_PROCEDURAL_STAMP := $(PREFIX_ROOT)/built_$(USD_PROCEDURAL_PACKAGE_NAME)
JSONCPP_STAMP := $(PREFIX_ROOT)/built_jsoncpp
GOOGLETEST_STAMP := $(PREFIX_ROOT)/built_googletest
OPENVDB_STAMP := $(PREFIX_ROOT)/built_openvdb
WALTER_DCC_STAMP := $(PREFIX_ROOT)/built_walterDCC
WALTER_PROCEDURAL_STAMP := $(PREFIX_ROOT)/built_walterProcedural
GCC_BIN_PATH := /usr/bin
CMAKE=$(PREFIX_ROOT)/cmake/bin/cmake
CTEST=$(PREFIX_ROOT)/cmake/bin/ctest
ALL_TARGETS :=\
$(USD_DCC_STAMP) \
$(USD_PROCEDURAL_STAMP) \
$(WALTER_DCC_STAMP) \
$(WALTER_PROCEDURAL_STAMP)
BOOST_NAMESPACE := rdoBoostWalter
TBB_NAMESPACE := rdoTbbWalter
USD_RESOLVER_NAME := AbcCoreLayerResolver
WALTER_VERSION = 1.0.0
WALTER_MAJOR_VERSION := $(word 1, $(subst ., ,$(WALTER_VERSION)))
WALTER_MINOR_VERSION := $(word 2, $(subst ., ,$(WALTER_VERSION)))
WALTER_PATCH_VERSION := $(word 3, $(subst ., ,$(WALTER_VERSION)))
#=============================================================================
# Shortcuts
all : $(ALL_TARGETS)
usd_dcc : $(USD_DCC_STAMP)
usd_procedural : $(USD_PROCEDURAL_STAMP)
walter_dcc: $(WALTER_DCC_STAMP)
walter_procedural: $(WALTER_PROCEDURAL_STAMP)
#=============================================================================
# Clean target for Walter DCC.
clean_dcc:
rm -f $(WALTER_DCC_STAMP)
.PHONY : clean_dcc
#=============================================================================
# Clean target for Walter DCC.
clean_procedural:
rm -f $(WALTER_PROCEDURAL_STAMP)
.PHONY : clean_procedural
#=============================================================================
# Clean target for Walter (DCC and Procedural).
clean: clean_dcc clean_procedural
.PHONY : clean
#=============================================================================
# Clean target for USD (DCC and Procedural).
clean_usd:
rm -f $(USD_DCC_STAMP) && \
rm -f $(USD_PROCEDURAL_STAMP)
.PHONY : clean_usd
#=============================================================================
# Clean Walter and USD
clean_all: clean_usd clean
.PHONY : clean_all
#=============================================================================
# Target to list tests.
ls_tests :
@echo "DCC plugins integration tests:" && \
test -d $(BUILD_ROOT)/walter && cd $(BUILD_ROOT)/walter && $(CTEST) -N
@echo "Procedural plugins integration tests:" && \
test -d $(BUILD_ROOT)/walter_procedural && cd $(BUILD_ROOT)/walter_procedural && $(CTEST) -N
.PHONY: ls_tests
#=============================================================================
# Target to for TEST in DCC plugins test.
test :
@cd $(BUILD_ROOT)/walter && \
$(CTEST) -V -R $(TEST)
.PHONY: test
# Target to for TEST in Procedural tests.
test_p :
@cd $(BUILD_ROOT)/walter_procedural && \
$(CTEST) -V -R $(TEST)
.PHONY: test
#=============================================================================
# Target for dcc tests.
test_dcc :
@cd $(BUILD_ROOT)/walter && \
$(CTEST) -V
.PHONY: test_dcc
#=============================================================================
# Target for Arnold procedural tests.
test_procedural :
@cd $(BUILD_ROOT)/walter_procedural && \
$(CTEST) -V
.PHONY: test_procedural
#=============================================================================
# Target for all tests.
tests : test_dcc test_procedural
.PHONY: tests
#=============================================================================
# Target rules for usd (used by Walter DCC plugins)
$(USD_DCC_STAMP) :
@$(call vfx_builder,"USD for DCC plugins",$(USD_DCC_PACKAGE_NAME),$(BOOST_NAMESPACE),$(TBB_NAMESPACE),$(BUILD_HOUDINI_PLUGINS),$(BUILD_KATANA_PLUGINS),usd)
#=============================================================================
# Target rules for usd (used by Walter for Arnold Procedural)
$(USD_PROCEDURAL_STAMP) :
@$(call vfx_builder,"USD for Arnold procedural",$(USD_PROCEDURAL_PACKAGE_NAME),$(BOOST_NAMESPACE),$(TBB_NAMESPACE),"OFF","OFF",usd)
#=============================================================================
# Target rules for Walter dependencies not needed by USD
$(JSONCPP_STAMP) :
@$(call vfx_builder,"Json CPP","",$(BOOST_NAMESPACE),$(TBB_NAMESPACE),"OFF","OFF",jsoncpp)
$(GOOGLETEST_STAMP) :
@$(call vfx_builder,"Google Test","",$(BOOST_NAMESPACE),$(TBB_NAMESPACE),"OFF","OFF",googletest)
$(OPENVDB_STAMP) :
@$(call vfx_builder,"Open VDB","",$(BOOST_NAMESPACE),$(TBB_NAMESPACE),"OFF","OFF",openvdb)
################################################################################
# Target rules for walter DCC plugins
# Build rule for target.
$(WALTER_DCC_STAMP) : $(USD_DCC_STAMP) $(JSONCPP_STAMP) $(GOOGLETEST_STAMP) $(OPENVDB_STAMP)
@echo Building Walter
rm -rf $(BUILD_ROOT)/walter && \
mkdir $(BUILD_ROOT)/walter && cd $(BUILD_ROOT)/walter && \
$(CMAKE) \
-DWALTER_MAJOR_VERSION=$(WALTER_MAJOR_VERSION) \
-DWALTER_MINOR_VERSION=$(WALTER_MINOR_VERSION) \
-DWALTER_PATCH_VERSION=$(WALTER_PATCH_VERSION) \
-DUSD_RESOLVER_NAME=$(USD_RESOLVER_NAME) \
-DRDO_RESOLVER_ROOT=$(PREFIX_ROOT)/RdoResolver \
-DALEMBIC_ROOT=$(PREFIX_ROOT)/alembic \
-DARNOLD_BASE_DIR=$(ARNOLD_ROOT) \
-DBOOST_ROOT=$(PREFIX_ROOT)/boost \
-DBUILD_ARNOLD_PROCEDURALS=OFF \
-DBUILD_HOUDINI_PLUGINS=$(BUILD_HOUDINI_PLUGINS) \
-DBUILD_KATANA_PLUGINS=$(BUILD_KATANA_PLUGINS) \
-DBUILD_MAYA_PLUGINS=$(BUILD_MAYA_PLUGINS) \
-DBUILD_TESTS=$(BUILD_TESTS) \
-DBUILD_VIEWER=$(BUILD_VIEWER) \
-DBoost_NAMESPACE=$(BOOST_NAMESPACE) \
-DCMAKE_BUILD_TYPE=$(CMAKE_BUILD_TYPE) \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/walter \
-DCMAKE_SHARED_LINKER_FLAGS=-Wl,--no-undefined \
-DCMAKE_VERBOSE_MAKEFILE=$(VERBOSE) \
-DGLEW_INCLUDE_DIR=$(PREFIX_ROOT)/glew/include \
-DGLEW_LOCATION=$(PREFIX_ROOT)/glew \
-DGLFW_DIR=$(PREFIX_ROOT)/glfw \
-DGoogleTest_DIR=$(PREFIX_ROOT)/googletest \
-DHDF5_ROOT=$(PREFIX_ROOT)/hdf5 \
-DHOUDINI_ROOT=$(HOUDINI_ROOT) \
-DILMBASE_HOME=$(PREFIX_ROOT)/ilmbase \
-DILMBASE_ROOT=$(PREFIX_ROOT)/ilmbase \
-DJPEG_PATH=$(PREFIX_ROOT)/jpeg \
-DJSONCPP_ROOT_DIR=$(PREFIX_ROOT)/jsoncpp \
-DKATANA_HOME=$(KATANA_ROOT) \
-DKTOA_HOME=$(KTOA_ROOT) \
-DMAYA_LOCATION=$(MAYA_ROOT) \
-DMTOA_BASE_DIR=$(MTOA_ROOT) \
-DOCIO_PATH=$(PREFIX_ROOT)/ocio \
-DOIIO_LOCATION=$(PREFIX_ROOT)/oiio \
-DOPENEXR_HOME=$(PREFIX_ROOT)/openexr \
-DOPENSUBDIV_ROOT_DIR=$(PREFIX_ROOT)/opensubdiv \
-DOPENVDB_LOCATION=$(PREFIX_ROOT)/openvdb \
-DBLOSC_LOCATION=$(PREFIX_ROOT)/blosc \
-DPNG_LIBRARY=$(PREFIX_ROOT)/png/lib/libpng.a \
-DPNG_PNG_INCLUDE_DIR=$(PREFIX_ROOT)/png/include \
-DPTEX_LOCATION=$(PREFIX_ROOT)/ptex \
-DPYSTRING_DIR=$(PREFIX_ROOT)/pystring \
-DPYSTRING_INCLUDE_DIR=$(PREFIX_ROOT)/pystring/include \
-DPYTHON_EXECUTABLE=$(HOUDINI_ROOT)/python/bin/python \
-DTBB_LIBRARIES=$(PREFIX_ROOT)/tbb/lib \
-DTBB_LIBRARY=$(PREFIX_ROOT)/tbb/lib \
-DTBB_NAMESPACE=$(TBB_NAMESPACE) \
-DTBB_ROOT_DIR=$(PREFIX_ROOT)/tbb/include \
-DTIFF_INCLUDE_DIR=$(PREFIX_ROOT)/tiff/include \
-DTIFF_LIBRARY=$(PREFIX_ROOT)/tiff/lib/libtiff.a \
-DUSD_ROOT=$(PREFIX_ROOT)/$(USD_DCC_PACKAGE_NAME) \
-DUSE_HDF5=ON \
-DUSE_STATIC_BOOST=OFF \
-DUSE_STATIC_HDF5=ON \
-DZLIB_ROOT=$(PREFIX_ROOT)/zlib \
$(THIS_DIR)/walter && \
$(CMAKE) --build . --target install --config $(CMAKE_BUILD_TYPE) -- -j$(JOB_COUNT) && \
echo timestamp > $(WALTER_DCC_STAMP)
# fast build rule for target.
walter_dcc_fast :
@cd $(BUILD_ROOT)/walter && \
make install
################################################################################
# Target rules for walter for Arnold
# Build rule for target.
$(WALTER_PROCEDURAL_STAMP) : $(USD_PROCEDURAL_STAMP) $(JSONCPP_STAMP) $(OPENVDB_STAMP) $(GOOGLETEST_STAMP)
@echo Building Walter Procedural && \
rm -rf $(BUILD_ROOT)/walter_procedural && \
mkdir $(BUILD_ROOT)/walter_procedural && cd $(BUILD_ROOT)/walter_procedural && \
$(CMAKE) \
-DWALTER_MAJOR_VERSION=$(WALTER_MAJOR_VERSION) \
-DWALTER_MINOR_VERSION=$(WALTER_MINOR_VERSION) \
-DWALTER_PATCH_VERSION=$(WALTER_PATCH_VERSION) \
-DUSD_RESOLVER_NAME=$(USD_RESOLVER_NAME) \
-DRDO_RESOLVER_ROOT=$(PREFIX_ROOT)/RdoResolverProcedural \
-DALEMBIC_ROOT=$(PREFIX_ROOT)/alembic \
-DARNOLD_BASE_DIR=$(ARNOLD_ROOT) \
-DBOOST_ROOT=$(PREFIX_ROOT)/boost \
-DBUILD_ARNOLD_PROCEDURALS=ON \
-DBUILD_HOUDINI_PLUGINS=OFF \
-DBUILD_KATANA_PLUGINS=OFF \
-DBUILD_MAYA_PLUGINS=OFF \
-DBUILD_TESTS=ON \
-DBoost_NAMESPACE=$(BOOST_NAMESPACE) \
-DCMAKE_BUILD_TYPE=$(CMAKE_BUILD_TYPE) \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/walter \
-DCMAKE_SHARED_LINKER_FLAGS=-Wl,--no-undefined \
-DCMAKE_VERBOSE_MAKEFILE=$(VERBOSE) \
-DGLEW_INCLUDE_DIR=$(PREFIX_ROOT)/glew/include \
-DGLEW_LOCATION=$(PREFIX_ROOT)/glew \
-DGLFW_DIR=$(PREFIX_ROOT)/glfw \
-DGoogleTest_DIR=$(PREFIX_ROOT)/googletest \
-DHDF5_ROOT=$(PREFIX_ROOT)/hdf5 \
-DHOUDINI_ROOT=$(HOUDINI_ROOT) \
-DILMBASE_HOME=$(PREFIX_ROOT)/ilmbase \
-DILMBASE_ROOT=$(PREFIX_ROOT)/ilmbase \
-DJPEG_PATH=$(PREFIX_ROOT)/jpeg \
-DJSONCPP_ROOT_DIR=$(PREFIX_ROOT)/jsoncpp \
-DKATANA_HOME=$(KATANA_ROOT) \
-DKTOA_HOME=$(KTOA_ROOT) \
-DMAYA_LOCATION=$(MAYA_ROOT) \
-DMTOA_BASE_DIR=$(MTOA_ROOT) \
-DOCIO_PATH=$(PREFIX_ROOT)/ocio \
-DOIIO_LOCATION=$(PREFIX_ROOT)/oiio \
-DOPENEXR_HOME=$(PREFIX_ROOT)/openexr \
-DOPENSUBDIV_ROOT_DIR=$(PREFIX_ROOT)/opensubdiv \
-DOPENVDB_LOCATION=$(PREFIX_ROOT)/openvdb \
-DBLOSC_LOCATION=$(PREFIX_ROOT)/blosc \
-DPNG_LIBRARY=$(PREFIX_ROOT)/png/lib/libpng.a \
-DPNG_PNG_INCLUDE_DIR=$(PREFIX_ROOT)/png/include \
-DPTEX_LOCATION=$(PREFIX_ROOT)/ptex \
-DPYSTRING_DIR=$(PREFIX_ROOT)/pystring \
-DPYSTRING_INCLUDE_DIR=$(PREFIX_ROOT)/pystring/include \
-DPYTHON_EXECUTABLE=$(HOUDINI_ROOT)/python/bin/python \
-DTBB_LIBRARIES=$(PREFIX_ROOT)/tbb/lib \
-DTBB_LIBRARY=$(PREFIX_ROOT)/tbb/lib \
-DTBB_NAMESPACE=$(TBB_NAMESPACE) \
-DTBB_ROOT_DIR=$(PREFIX_ROOT)/tbb/include \
-DTIFF_INCLUDE_DIR=$(PREFIX_ROOT)/tiff/include \
-DTIFF_LIBRARY=$(PREFIX_ROOT)/tiff/lib/libtiff.a \
-DUSD_ROOT=$(PREFIX_ROOT)/$(USD_PROCEDURAL_PACKAGE_NAME) \
-DUSE_HDF5=ON \
-DUSE_STATIC_BOOST=OFF \
-DUSE_STATIC_HDF5=ON \
-DZLIB_ROOT=$(PREFIX_ROOT)/zlib \
$(THIS_DIR)/walter && \
$(CMAKE) --build . --target install --config $(CMAKE_BUILD_TYPE) -- -j$(JOB_COUNT)
echo timestamp > $(WALTER_PROCEDURAL_STAMP)
# fast build rule for target.
walter_procedural_fast :
@cd $(BUILD_ROOT)/walter_procedural && \
make install
#===============================================================================
# Function to build libraries using vfx_platform_builder Makefile
# Args:
# $(1): lib name for message
# $(2): USD_DCC_PACKAGE_NAME
# $(3): BOOST_NAMESPACE
# $(4): TBB_NAMESPACE
# $(5): BUILD_HOUDINI_PLUGINS
# $(6): BUILD_KATANA_PLUGINS
# $(7): targets
vfx_builder = \
echo "Building" $(1) "for Walter" && \
cd $(THIS_DIR)/vfx_platform_builder && \
make CC=$(GCC_BIN_PATH)/gcc CXX=$(GCC_BIN_PATH)/g++ \
MAKE_MODE=$(MAKE_MODE) \
USD_PACKAGE_NAME=$(2) \
BOOST_NAMESPACE=$(3) \
TBB_NAMESPACE=$(4) \
BUILD_HOUDINI_PLUGINS=$(5) \
HOUDINI_ROOT=$(HOUDINI_ROOT) \
BUILD_KATANA_PLUGINS=$(6) \
KATANA_ROOT=$(KATANA_ROOT) \
SOURCES_ROOT=$(SOURCES_ROOT) \
BUILD_ROOT=$(BUILD_ROOT) \
PREFIX_ROOT=$(PREFIX_ROOT) -j$(JOB_COUNT) \
$(7)
# Help Target
help:
@printf '********************* Open Walter building system *********************\n\n' ; \
printf 'Packages required before install:\n' ; \
printf '\tnasm libtool autoconf mesa-libGL-devel mesa-libGLU-devel\n' ; \
printf '\tlibXxf86vm-devel libXrandr-devel libXinerama-devel\n' ; \
printf '\tlibXcursor-devel libXi-devel libXt-devel\n\n' ; \
printf 'Usage to build all (VFX Platform, Walter for Katana, Houdini, Maya and Arnold):\n' ; \
printf '\tmake\nor\n\tmake MAKE_MODE=debug\n\n' ; \
printf 'Options:\n' ; \
printf '\tCC\t\t: C copiler path.\t value: $(CC)\n' ; \
printf '\tCXX\t\t: C++ copiler path.\t value: $(CXX)\n' ; \
printf '\tMAKE_MODE\t: debug|release.\t value: $(MAKE_MODE)\n' ; \
printf '\tSOURCES_ROOT\t: Source directory.\t value: $(SOURCES_ROOT)\n' ; \
printf '\tBUILD_ROOT\t: Building directory.\t value: $(BUILD_ROOT)\n' ; \
printf '\tPREFIX_ROOT\t: Installation dir.\t value: $(PREFIX_ROOT)\n' ; \
printf '\tARNOLD_ROOT\t: The path to Arnold install directory.\t value: $(ARNOLD_ROOT)\n' ; \
printf '\tKATANA_ROOT\t: The path to Katana install directory.\t value: $(KATANA_ROOT)\n' ; \
printf '\tKTOA_ROOT\t: The path to KtoA install directory.\t value: $(KTOA_ROOT)\n' ; \
printf '\tHOUDINI_ROOT\t: The path to Houdini install directory. value: $(HOUDINI_ROOT)\n' ; \
printf '\tMAYA_ROOT\t: The path to Maya install directory.\t value: $(MAYA_ROOT)\n' ; \
printf '\tMTOA_ROOT\t: The path to MtoA install directory.\t value: $(MTOA_ROOT)\n' ; \
printf '\tUSD_RESOLVER_NAME\t: Usd resolver plugin to use (AbcCoreLayerResolver or RdoResolver).\t value: $(USD_RESOLVER_NAME)\n' ; \
printf '\nTo disable specific target:\n' ; \
printf '\tmake walter_dcc : only Walter for Houdini, Katana or Maya plugins\n' ; \
printf '\tmake walter_procedural : only Walter for Arnold\n' ; \
printf '\tmake BUILD_HOUDINI_PLUGINS=0 : No Houdini plugin\n' ; \
printf '\tmake BUILD_KATANA_PLUGINS=0 : No Katana plugin\n' ; \
printf '\tmake BUILD_MAYA_PLUGINS=0 : No Maya plugin\n\n' ; \
printf '\tmake BUILD_TESTS=0 : Skip tests\n' ; \
printf '\tmake BUILD_VIEWER=0 : No viewer\n' ; \
printf '\tmake usd_dcc : only USD for Houdini, Katana or Maya plugins\n' ; \
printf '\tmake usd_procedural : only USD for Arnold\n' ; \
printf '\nTo fast re-build specific target (work only if you already built once):\n' ; \
printf '\tmake walter_dcc_fast : fast re-build only Walter for Houdini, Katana or Maya plugins\n' ; \
printf '\tmake walter_procedural_fast : re-build only Walter for Arnold\n' ; \
printf '\nTo test:\n' ; \
printf '\tmake ls_tests : list all tests\n' ; \
printf '\tmake tests : run all tests\n' ; \
printf '\tmake test_dcc : run tests for Houdini, Katana and Maya\n' ; \
printf '\tmake test TEST=test_name : run just one test from the DCC plugins tests \n' ; \
printf '\tmake test_p TEST=test_name : run just one test from the Procedural plugin tests \n' ; \
printf '\tmake test_procedural : run tests for the Procedural plugin\n' ; \
printf '\nTo clean specific target:\n' ; \
printf '\tmake clean_dcc : clean DCC plugins\n' ; \
printf '\tmake clean_procedural : clean Procedural plugins\n' ; \
printf '\tmake clean : clean DCC and Procedural plugins\n' ; \
printf '\tmake clean_usd : clean USD for DCC and Procedural\n' ; \
printf '\tmake clean_all : clean Walter and USD\n' ; \
<|start_filename|>walter/alembic/OWalterLayersSchema.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __OWALTERLAYERSSCHEMA_H_
#define __OWALTERLAYERSSCHEMA_H_
#include <Alembic/Abc/All.h>
#include "SchemaInfoDeclarations.h"
#define LAYERS_PROPNAME ".layers"
// Schema for writing per layer shader assignments as either an object or a
// compound property.
class ALEMBIC_EXPORT OWalterLayersSchema :
public Alembic::Abc::OSchema<WalterLayersSchemaInfo>
{
public:
typedef OWalterLayersSchema this_type;
OWalterLayersSchema(
Alembic::AbcCoreAbstract::CompoundPropertyWriterPtr iParent,
const std::string &iName,
const Alembic::Abc::Argument &iArg0 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg1 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg2 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg3 = Alembic::Abc::Argument() );
OWalterLayersSchema(
Alembic::Abc::OCompoundProperty iParent,
const std::string &iName,
const Alembic::Abc::Argument &iArg0 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg1 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg2 = Alembic::Abc::Argument() );
// Copy constructor.
OWalterLayersSchema( const OWalterLayersSchema& iCopy ) :
Alembic::Abc::OSchema<WalterLayersSchemaInfo>()
{
*this = iCopy;
}
// Declare shader for a given target and shaderType.
// "Target's" value is an agreed upon convention for a render layer.
// "ShaderType's" value is an agreed upon convention for shader terminals
// such as "surface," "displacement," "light", "coshader_somename."
// "ShaderName's" value is an identifier meaningful to the target
// application (i.e. "paintedplastic," "fancy_spot_light").
// It's only valid to call this once per target/shaderType combo.
void setShader(
const std::string & iTarget,
const std::string & iShaderType,
const std::string & iShaderName,
const Alembic::Abc::MetaData& md);
};
// Adds a local layer schema within any compound.
OWalterLayersSchema addLayers(
Alembic::Abc::OCompoundProperty iProp,
const std::string& iPropName = LAYERS_PROPNAME );
// Adds a local layer schema to any object.
OWalterLayersSchema addLayers(
Alembic::Abc::OObject iObject,
const std::string& iPropName = LAYERS_PROPNAME );
#endif
<|start_filename|>walter/cmake/FindBlosc.cmake<|end_filename|>
# Copyright (c) 2012-2016 DreamWorks Animation LLC
#
# All rights reserved. This software is distributed under the
# Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
#
# Redistributions of source code must retain the above copyright
# and license notice and the following restrictions and disclaimer.
#
# * Neither the name of DreamWorks Animation nor the names of
# its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# 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 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.
# IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
# LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
#
# -*- cmake -*-
# - Find Blosc
#
# Author : <NAME> <EMAIL>
#
# BLOSC_FOUND set if Blosc is found.
# BLOSC_INCLUDE_DIR Blosc's include directory
# BLOSC_LIBRARYDIR Blosc's library directory
# BLOSC_LIBRARIES all Blosc libraries
FIND_PACKAGE ( PackageHandleStandardArgs )
FIND_PATH( BLOSC_LOCATION include/blosc.h
"$ENV{BLOSC_ROOT}"
NO_DEFAULT_PATH
NO_SYSTEM_ENVIRONMENT_PATH
)
FIND_PACKAGE_HANDLE_STANDARD_ARGS ( Blosc
REQUIRED_VARS BLOSC_LOCATION
)
IF ( BLOSC_FOUND )
SET ( BLOSC_LIBRARYDIR ${BLOSC_LOCATION}/lib
CACHE STRING "Blosc library directories")
SET ( _blosc_library_name "blosc" )
# Static library setup
IF (Blosc_USE_STATIC_LIBS)
SET(CMAKE_FIND_LIBRARY_SUFFIXES_BACKUP ${CMAKE_FIND_LIBRARY_SUFFIXES})
IF (WIN32)
SET ( _blosc_library_name "libblosc" )
ELSE ()
SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
ENDIF ()
ENDIF()
FIND_LIBRARY ( BLOSC_blosc_LIBRARY ${_blosc_library_name}
PATHS ${BLOSC_LIBRARYDIR}
NO_DEFAULT_PATH
NO_SYSTEM_ENVIRONMENT_PATH
)
# Static library tear down
IF (Blosc_USE_STATIC_LIBS)
SET( CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES_BACKUP} )
ENDIF()
SET( BLOSC_INCLUDE_DIR "${BLOSC_LOCATION}/include" CACHE STRING "Blosc include directory" )
ENDIF ( BLOSC_FOUND )
<|start_filename|>walter/katana/WalterIn/walterUSDOp.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterUSDOp.h"
#include "walterUSDOpEngine.h"
#include "walterUSDOpUtils.h"
#include <FnPluginSystem/FnPlugin.h>
class WalterInUSDOp : public Foundry::Katana::GeolibOp
{
public:
static void setup(Foundry::Katana::GeolibSetupInterface& ioInterface)
{
ioInterface.setThreading(
Foundry::Katana::GeolibSetupInterface::ThreadModeConcurrent);
}
/**
* @brief The entry point for each scene graph node.
*
* @param ioInterface A reference to a valid GeolibCookInterface object.
*/
static void cook(Foundry::Katana::GeolibCookInterface& ioInterface)
{
// We passed the engine as a private data previously.
// TODO: probably passing the list of the layers is better because it
// would be possible to create such node in OpScript.
OpUtils::PrivateData* privateData =
reinterpret_cast<OpUtils::PrivateData*>(
ioInterface.getPrivateData());
assert(privateData);
privateData->engine().cook(privateData, &ioInterface);
}
};
DEFINE_GEOLIBOP_PLUGIN(WalterInUSDOp)
void cookUSDRoot(
Foundry::Katana::GeolibCookInterface& ioInterface,
const std::vector<std::string>& iArchives)
{
W_DEBUG(
"i:%s o:%s",
ioInterface.getInputLocationPath().c_str(),
ioInterface.getOutputLocationPath().c_str());
FnAttribute::StringAttribute pathFromRootAttr =
ioInterface.getOpArg("pathFromRoot");
// False means don't throw an error if error occurs.
std::string rootStr = pathFromRootAttr.getValue(std::string{}, false);
SdfPath rootPath =
rootStr.empty() ? SdfPath::AbsoluteRootPath() : SdfPath(rootStr);
// Time related paramteters.
static std::string currentTimeStr = "system.timeSlice.currentTime";
static std::string shutterOpenStr = "system.timeSlice.shutterOpen";
static std::string shutterCloseStr = "system.timeSlice.shutterClose";
static std::string numSamplesStr = "system.timeSlice.numSamples";
FnAttribute::FloatAttribute currentTimeAttr(
ioInterface.getOpArg(currentTimeStr));
FnAttribute::FloatAttribute shutterOpenAttr(
ioInterface.getOpArg(shutterOpenStr));
FnAttribute::FloatAttribute shutterCloseAttr(
ioInterface.getOpArg(shutterCloseStr));
FnAttribute::IntAttribute numSamplesAttr(
ioInterface.getOpArg(numSamplesStr));
float currentTime = currentTimeAttr.getValue(0.0, false);
float shutterOpen = shutterOpenAttr.getValue(0.0, false);
float shutterClose = shutterCloseAttr.getValue(0.0, false);
int numSamples = numSamplesAttr.getValue(0, false);
OpUtils::TimePtr time = std::make_shared<OpUtils::Time>(
currentTime, shutterOpen, shutterClose, numSamples);
OpEngine& engine = OpEngine::getInstance(iArchives);
// Att the children PrivateDatas will have this outputLocationPath.
const OpUtils::PrivateData privateData(
engine, ioInterface.getOutputLocationPath(), rootPath, time);
engine.cook(&privateData, &ioInterface);
// If cookInstances is true we need to cook Masters locations.
// Then any instances will be cooked as Katana instances and point to the
// corresponding Masters location.
auto cookInstancesAttr = ioInterface.getOpArg("cookInstances");
int cookInstances =
FnAttribute::IntAttribute(cookInstancesAttr).getValue(0, false);
if (cookInstances)
engine.cookMasters(&privateData, &ioInterface);
}
void registerUSDPlugins()
{
REGISTER_PLUGIN(WalterInUSDOp, "WalterInUSD", 0, 1);
}
<|start_filename|>walter/maya/mtoa/walterTranslator.h<|end_filename|>
#include "translators/shape/ShapeTranslator.h"
#include "mtoaVersion.h"
#include <translators/NodeTranslator.h>
class CWalterStandinTranslator
: public CShapeTranslator
{
public:
CWalterStandinTranslator();
void ExportMotion(AtNode*);
AtNode* CreateArnoldNodes();
virtual void Export(AtNode* procedural);
static void NodeInitializer(CAbTranslator context);
static void* creator()
{
return new CWalterStandinTranslator();
}
protected:
void ProcessRenderFlagsCustom(AtNode* node);
void ExportBoundingBox(AtNode* procedural);
void ExportStandinsShaders(AtNode* procedural);
void ExportProcedural(AtNode* procedural, bool update);
virtual void ExportShaders();
protected:
MFnDagNode m_DagNode;
private:
// Export Arnold shader and displacement from the Maya shaders and displacements nodes
// connected to the shape.
bool ExportMayaShadingGraph();
// Export node graph connect to this plug
void ExportConnections(
const char* abcnode,
const MPlug& shaderPlug);
// Computes visibility attributes based on the node's attributes. Returns
// negative when the visibility can't be reached.
int ComputeWalterVisibility(const MFnDependencyNode& node)const;
// The node which is at the root of this translator.
AtNode* GetArnoldRootNode();
void ExportFrame(AtNode* node);
// Shortcut to the node which is at the root of this translator. Do not
// delete, it is supposed to be one of the translators nodes.
AtNode *m_arnoldRootNode;
};
<|start_filename|>walter/maya/walterStandin/walterAssignment.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERASSIGNMENT_H_
#define __WALTERASSIGNMENT_H_
// Several utilities to save/load assignment from Alembic files.
#include "PathUtil.h"
#include "mayaUtils.h"
#include <maya/MFnDependencyNode.h>
#include <maya/MObject.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>
#include <maya/MString.h>
#include <maya/MStringArray.h>
#include <map>
/**
* @brief Iterates the plug with the assignments and fills the map to with all
* the connections that was found.
*
* @param layerCompound The plug that represents
* walterStandin.layersAssignation[n]
* @param plugsToQuerry The list of plugs to query. Fox example if the list is
* {"shader", "displacement"}, then following plugs will be queried:
* * walterStandin.layersAssignation[].shaderConnections[].shader
* * walterStandin.layersAssignation[].shaderConnections[].displacement
* @param oAssignments The sub-node names to assigned matrials maps for each
* requested plug.
*/
template <typename T>
void getAllAssignments(
MPlug layerCompound,
MStringArray plugsToQuerry,
T& oAssignments)
{
MPlug shadersPlug;
if (!GetChildMPlug(layerCompound, "shaderConnections", shadersPlug))
{
return;
}
for (unsigned int j = 0; j < shadersPlug.numElements(); j++)
{
// Get walterStandin.layersAssignation[i].shaderConnections[j]
const MPlug shadersCompound = shadersPlug.elementByPhysicalIndex(j);
// Get walterStandin.layersAssignation[].shaderConnections[].abcnode
MPlug abcnodePlug;
if (!GetChildMPlug(shadersCompound, "abcnode", abcnodePlug))
{
continue;
}
const MString abcnode = abcnodePlug.asString().asChar();
if (!abcnode.length())
{
continue;
}
for (int i = 0, n = plugsToQuerry.length(); i < n; i++)
{
// walterStandin.layersAssignation[].shaderConnections[].xxx
MPlug shaderPlug;
if (!GetChildMPlug(shadersCompound, plugsToQuerry[i], shaderPlug))
{
continue;
}
// Get the connected shader name
MPlugArray connections;
if (!shaderPlug.connectedTo(connections, true, false) ||
!connections.length())
{
continue;
}
oAssignments[i].emplace(
std::piecewise_construct,
std::forward_as_tuple(abcnode.asChar()),
std::forward_as_tuple(connections[0].node()));
}
}
}
/**
* @brief Querry the connections of the walter standin to get the list of all
* the shaders connected to the default render layer.
*
* @param node Walter Standin node.
* @param type "shader", "displacement" or "attribute".
* @param oAssignments The sub-node names to assigned matrials output map.
*/
template <class T>
void getShaderAssignments(
MObject node,
const std::string& type,
T& oAssignments)
{
MFnDependencyNode depNode(node);
const MPlug layersAssignation = depNode.findPlug("layersAssignation");
if (layersAssignation.isNull())
{
printf(
"[walter] Can't find %s.layersAssignation.",
depNode.name().asChar());
return;
}
if (layersAssignation.numElements() <= 0)
{
return;
}
for (unsigned int i = 0; i < layersAssignation.numElements(); i++)
{
// Get walterStandin.layersAssignation[i]
const MPlug currentLayerCompound =
layersAssignation.elementByPhysicalIndex(i);
// Get walterStandin.layersAssignation[i].layer
MPlug layerPlug;
if (!GetChildMPlug(currentLayerCompound, "layer", layerPlug))
{
continue;
}
MPlugArray connections;
if (!layerPlug.connectedTo(connections, true, false) ||
!connections.length())
{
// Layer should be conneted, but it's not.
continue;
}
// The layer is the first connected node. We consider we have only one
// connection.
const MFnDependencyNode layer(connections[0].node());
const std::string layerName = layer.name().asChar();
if (layerName != "defaultRenderLayer")
{
// We don't need it.
continue;
}
// The list of plugs to look up.
const char* plugsToFind[] = {type.c_str()};
T* assignmentsPtr = &oAssignments;
// Get all the assignments.
getAllAssignments(
currentLayerCompound,
MStringArray(
plugsToFind, sizeof(plugsToFind) / sizeof(*plugsToFind)),
assignmentsPtr);
// We found everything. No need to continue.
break;
}
}
// Save all the assignments from given walter node to a separate Alembic file.
bool saveAssignment(const MString& objectName, const MString& fileName);
#endif
<|start_filename|>walter/cmake/FindZlib.cmake<|end_filename|>
set(ZLIB_NAMES z zlib zdll zlib1)
find_library(
ZLIB_LIB
NAMES ${ZLIB_NAMES}
HINTS ${ZLIB_ROOT}
PATH_SUFFIXES lib
NO_DEFAULT_PATH)
SET( ALEMBIC_ZLIB_LIBS ${ZLIB_LIB} )
MESSAGE(STATUS "ZLIB INCLUDE PATH: ${ZLIB_INCLUDE_DIR}" )
MESSAGE(STATUS "ZLIB LIBRARIES: ${ALEMBIC_ZLIB_LIBS}" )
<|start_filename|>walter/maya/common/mayaUtils.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "mayaUtils.h"
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <string.h>
// namespace walter {
// namespace maya {
// Search child plug with given name in the given plug's children.
bool GetChildMPlug(const MPlug& i_plug, const MString& name, MPlug& o_plug)
{
const MString dotName = "." + name;
unsigned dotNameLen = dotName.length();
for (unsigned i=0; i<i_plug.numChildren(); i++)
{
o_plug = i_plug.child(i);
if (o_plug.isNull())
{
continue;
}
// MPlug::partialName returns "la[0].layer"
const MString partial = o_plug.partialName();
unsigned partialLen = partial.length();
if (partialLen <= dotNameLen)
{
continue;
}
if (partial.substring(partialLen-dotNameLen, partialLen-1) == dotName)
{
return true;
}
}
return false;
}
std::string attributeNameDemangle(const std::string& name, bool* oIsUserData)
{
static const char* walter = "walter";
static const int walterLen = strlen(walter);
if (name.substr(0, walterLen) != "walter")
{
return "";
}
// Form the correct json name.
// Cut prefix. Prefix is walter. "walterSubdivType" -> "SubdivType"
std::string arnoldName = name.substr(walterLen, name.size()-walterLen);
if (arnoldName[0]=='_')
{
// It's a custom attribute. Just remove the first character.
arnoldName = arnoldName.substr(1);
if (oIsUserData)
{
*oIsUserData = true;
}
}
else
{
// Camel case to snack case. "SubdivType" -> "Subdiv_Type"
arnoldName = boost::regex_replace(
arnoldName, boost::regex("([a-z0-9])([A-Z])"), "\\1_\\2");
// Lower case. "Subdiv_Type" -> "subdiv_type"
boost::algorithm::to_lower(arnoldName);
if (oIsUserData)
{
*oIsUserData = false;
}
}
return arnoldName;
}
// } // end namespace walter
// } // end namespace maya
<|start_filename|>walter/cmake/FindJsonCPP.cmake<|end_filename|>
# - try to find JSONCPP library
#
# Cache Variables: (probably not for direct use in your scripts)
# JSONCPP_INCLUDE_DIR
# JSONCPP_LIBRARY
#
# Non-cache variables you might use in your CMakeLists.txt:
# JSONCPP_FOUND
# JSONCPP_INCLUDE_DIRS
# JSONCPP_LIBRARIES
#
# Requires these CMake modules:
# FindPackageHandleStandardArgs (known included with CMake >=2.6.2)
#
# Author:
# 2011 <NAME> (ENSAM ParisTech / Institut Image) p.crassous _at_ free.fr
IF(NOT JSONCPP_ROOT_DIR AND NOT $ENV{JSONCPP_ROOT_DIR} STREQUAL "")
SET(JSONCPP_ROOT_DIR $ENV{JSONCPP_ROOT_DIR})
ENDIF()
set(JSONCPP_ROOT_DIR
"${JSONCPP_ROOT_DIR}"
CACHE
PATH
"Directory to search for JSONCPP")
set(_jsoncppnames)
set(_pathsuffixes
suncc
vacpp
mingw
msvc6
msvc7
msvc71
msvc80
msvc90
linux-gcc)
if(CMAKE_COMPILER_IS_GNUCXX)
execute_process(COMMAND
${CMAKE_CXX_COMPILER}
-dumpversion
OUTPUT_VARIABLE
_gnucxx_ver
OUTPUT_STRIP_TRAILING_WHITESPACE)
list(APPEND
_jsoncppnames
json
jsoncpp
json_linux-gcc-${_gnucxx_ver}_libmt
json_linux-gcc_libmt)
list(APPEND _pathsuffixes linux-gcc-${_gnucxx_ver})
elseif(MSVC)
if(MSVC_VERSION EQUAL 1200)
list(APPEND _jsoncppnames json_vc6_libmt)
elseif(MSVC_VERSION EQUAL 1300)
list(APPEND _jsoncppnames json_vc7_libmt)
elseif(MSVC_VERSION EQUAL 1310)
list(APPEND _jsoncppnames json_vc71_libmt)
elseif(MSVC_VERSION EQUAL 1400)
list(APPEND _jsoncppnames json_vc8_libmt)
elseif(MSVC_VERSION EQUAL 1500)
list(APPEND _jsoncppnames json_vc9_libmt)
elseif(MSVC_VERSION EQUAL 1600)
list(APPEND _jsoncppnames json_vc10_libmt)
elseif(MSVC_VERSION EQUAL 1700)
list(APPEND _jsoncppnames json_vc11_libmt)
elseif(MSVC_VERSION EQUAL 1800)
list(APPEND _jsoncppnames json_vc12_libmt)
endif()
else()
list(APPEND _jsoncppnames
jsoncpp
json_suncc_libmt
json_vacpp_libmt)
endif()
list(APPEND _jsoncppnames
json_mingw_libmt)
find_library(JSONCPP_LIBRARY
NAMES
${_jsoncppnames}
PATHS
"${JSONCPP_ROOT_DIR}/lib"
PATH_SUFFIXES
${_pathsuffixes})
find_path(JSONCPP_INCLUDE_DIR
NAMES
json/json.h
PATHS
"${JSONCPP_ROOT_DIR}"
PATH_SUFFIXES
include include/jsoncpp)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(JSONCPP
DEFAULT_MSG
JSONCPP_LIBRARY
JSONCPP_INCLUDE_DIR)
if(JSONCPP_FOUND)
set(JSONCPP_LIBRARIES "${JSONCPP_LIBRARY}")
set(JSONCPP_INCLUDE_DIRS "${JSONCPP_INCLUDE_DIR}")
mark_as_advanced(JSONCPP_ROOT_DIR)
endif()
mark_as_advanced(JSONCPP_INCLUDE_DIR JSONCPP_LIBRARY)
<|start_filename|>walter/viewer/CameraControler.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "CameraControler.h"
#include <cmath>
#include <iostream>
namespace walter_viewer
{
CameraControler::CameraControler()
{}
void CameraControler::reset()
{
mPaning = false;
mRotTheta = 0.f;
mRotPhi = 0.f;
mRotPsi = 0.f;
mZoom = 0.f;
mPanX = 0.f;
mPanY = 0.f;
mCenter[0] = 0.f;
mCenter[1] = 0.f;
mCenter[2] = 0.f;
}
void CameraControler::setRotation(float theta, float phi, float psi)
{
mRotTheta = theta;
mRotPhi = phi;
mRotPsi = psi;
}
void CameraControler::updateRotation(float dx, float dy)
{
mRotTheta += 0.333 * dx;
mRotPhi += 0.333 * dy;
}
void CameraControler::updateZoom(float dx, float dy)
{
mZoom = -0.003f * (dx + dy);
}
void CameraControler::updatePan(float x, float y)
{
if (fabs(mPanX) - fabs(x) < 0.001)
{
mPanX = 0.f;
}
else
{
mPanX = x;
}
if (fabs(mPanY) - fabs(y) < 0.001)
{
mPanY = 0.f;
}
else
{
mPanY = y;
}
}
void CameraControler::setCenter(float x, float y, float z)
{
mCenter[0] = x;
mCenter[1] = y;
mCenter[2] = z;
}
}
<|start_filename|>walter/cmake/FindArnold.cmake<|end_filename|>
set(ARNOLD_BASE_DIR
"${ARNOLD_BASE_DIR}"
CACHE
PATH
"Directory to search for Arnold")
find_library(ARNOLD_LIBRARY
NAMES
ai
PATHS
"${ARNOLD_BASE_DIR}/lib"
"${ARNOLD_BASE_DIR}/bin"
PATH_SUFFIXES
${_pathsuffixes})
find_path(ARNOLD_INCLUDE_DIR
NAMES
ai.h
PATHS
"${ARNOLD_BASE_DIR}"
PATH_SUFFIXES
include)
find_program(ARNOLD_EXECUTABLE
NAMES
kick
PATHS
"${ARNOLD_BASE_DIR}/bin")
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
"ARNOLDCPP"
DEFAULT_MSG
ARNOLD_LIBRARY
ARNOLD_INCLUDE_DIR)
if(ARNOLD_FOUND)
set(ARNOLD_LIBRARY "${ARNOLD_LIBRARY}")
set(ARNOLD_INCLUDE_DIR "${ARNOLD_INCLUDE_DIR}")
set(ARNOLD_EXECUTABLE "${ARNOLD_EXECUTABLE}")
mark_as_advanced(ARNOLD_BASE_DIR)
endif()
mark_as_advanced(ARNOLD_INCLUDE_DIR ARNOLD_LIBRARY ARNOLD_EXECUTABLE)
<|start_filename|>walter/viewer/Types.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERVIEWER_TYPES_H__
#define __WALTERVIEWER_TYPES_H__
#include <memory>
namespace walter_viewer
{
class FreeCamera;
typedef std::shared_ptr<FreeCamera> FreeCameraPtr;
class Scene;
typedef std::shared_ptr<Scene> ScenePtr;
class View;
typedef View* ViewPtr;
} // end namespace walter_viewer
#endif
<|start_filename|>walter/alembic/SchemaInfoDeclarations.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __SCHEMAINFODECLARATIONS_H_
#define __SCHEMAINFODECLARATIONS_H_
#include <Alembic/Abc/ISchema.h>
#include <Alembic/Abc/OSchema.h>
ALEMBIC_ABC_DECLARE_SCHEMA_INFO(
"RodeoWalter_Layers_v1",
"",
".layers",
false,
WalterLayersSchemaInfo );
ALEMBIC_ABC_DECLARE_SCHEMA_INFO(
"RodeoWalter_Expressions_v1",
"",
".expressions",
false,
WalterExpressionsSchemaInfo );
#endif
<|start_filename|>walter/maya/walterMtoaConnection/convertToArnold.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "convertToArnold.h"
#include "abcExporterUtils.h"
#include "mtoaScene.h"
#include <json/value.h>
#include <json/writer.h>
#include <maya/MArgDatabase.h>
#include <maya/MSelectionList.h>
#include <maya/MStringArray.h>
/**
* @brief Converts AtRGB to Json array.
*
* @tparam I AtRGB, AtRGBA etc.
* @param in Input value.
*
* @return Json array.
*/
template <class I> inline Json::Value arnToJsonArray(I in)
{
Json::Value result(Json::arrayValue);
// It works with Arnold only.
int size = sizeof(I) / sizeof(float);
result.resize(size);
for (int i = 0; i < size; i++)
{
result[i] = in[i];
}
return result;
}
/**
* @brief Return Json representation of given Arnold parameter.
*
* @param node The node of the parameter.
* @param param Given parameter.
*
* @return Json object.
*/
Json::Value arnParamToJson(const AtNode* node, const AtParamEntry* param)
{
Json::Value result(Json::objectValue);
// Parameter name.
const char* name = AiParamGetName(param);
// Parameter type.
int type = AiParamGetType(param);
if (AiNodeIsLinked(node, name))
{
// There is no value because this param is linked to another node. We
// only need the name of the linked node.
int comp;
AtNode* linked = AiNodeGetLink(node, name, &comp);
std::string linkName = AiNodeGetName(linked);
if (type == AI_TYPE_RGB || type == AI_TYPE_RGBA)
{
switch (comp)
{
// if comp >= 0, then the param is linked to a component of the
// output.
case 0:
linkName += ".r";
break;
case 1:
linkName += ".g";
break;
case 2:
linkName += ".b";
break;
case 3:
linkName += ".a";
break;
}
}
else if (
type == AI_TYPE_VECTOR || type == AI_TYPE_VECTOR ||
type == AI_TYPE_VECTOR2)
{
switch (comp)
{
case 0:
linkName += ".x";
break;
case 1:
linkName += ".y";
break;
case 2:
linkName += ".z";
break;
}
}
result["link"] = linkName;
}
else
{
// Get the value.
switch (type)
{
case AI_TYPE_BYTE:
result["value"] = AiNodeGetByte(node, name);
break;
case AI_TYPE_INT:
result["value"] = AiNodeGetInt(node, name);
break;
case AI_TYPE_UINT:
result["value"] = AiNodeGetUInt(node, name);
break;
case AI_TYPE_BOOLEAN:
result["value"] = AiNodeGetBool(node, name);
break;
case AI_TYPE_FLOAT:
result["value"] = AiNodeGetFlt(node, name);
break;
case AI_TYPE_RGB:
result["value"] = arnToJsonArray(AiNodeGetRGB(node, name));
break;
case AI_TYPE_RGBA:
result["value"] = arnToJsonArray(AiNodeGetRGBA(node, name));
break;
case AI_TYPE_VECTOR:
result["value"] = arnToJsonArray(AiNodeGetVec(node, name));
break;
case AI_TYPE_VECTOR2:
result["value"] = arnToJsonArray(AiNodeGetVec2(node, name));
break;
case AI_TYPE_STRING:
result["value"] = std::string(AiNodeGetStr(node, name));
break;
default:
// Can't detect type.
return result;
}
}
// Save the type.
const char* typeName = AiParamGetTypeName(type);
result["type"] = typeName;
return result;
}
/**
* @brief Returns Json object with all the parameters of given Arnold node.
*
* @param node Arnold node.
*
* @return Json object.
*/
Json::Value arnNodeToJson(const AtNode* node)
{
Json::Value result(Json::objectValue);
assert(node);
const AtNodeEntry* entry = AiNodeGetNodeEntry(node);
Json::Value params;
// Iterate all the paramters
AtParamIterator* nodeParam = AiNodeEntryGetParamIterator(entry);
while (!AiParamIteratorFinished(nodeParam))
{
const AtParamEntry* paramEntry = AiParamIteratorGetNext(nodeParam);
const char* paramName = AiParamGetName(paramEntry);
Json::Value param = arnParamToJson(node, paramEntry);
if (!param.empty())
{
// We only need to keep a valid paramter.
params[paramName] = param;
}
}
AiParamIteratorDestroy(nodeParam);
if (!params.empty())
{
// We only need to keep a valid paramter.
result["params"] = params;
}
result["type"] = AiNodeEntryGetName(entry);
return result;
}
MSyntax ConvertToArnoldCmd::syntax()
{
MSyntax syntax;
syntax.setObjectType(MSyntax::kStringObjects);
return syntax;
}
MStatus ConvertToArnoldCmd::doIt(const MArgList& args)
{
MArgDatabase argData(syntax(), args);
MStringArray objects;
argData.getObjects(objects);
Json::Value result(Json::objectValue);
MTOAScene scene;
for (unsigned int i = 0; i < objects.length(); i++)
{
const MString& currentObject = objects[i];
// We need a dependency node first. It's the old trick to get it.
MObject obj;
MSelectionList sel;
sel.add(currentObject);
if (sel.isEmpty())
{
continue;
}
sel.getDependNode(0, obj);
MFnDependencyNode depFn(obj);
// MTOA needs a plug.
MPlug plug = depFn.findPlug("message");
// Export nodes to Arnold using MTOA
AtNodeSet roots;
CNodeTranslator* translator = scene.exportNode(plug, &roots);
if (!translator)
{
continue;
}
AtNode* translatedNode = translator->GetArnoldNode();
if (!translatedNode)
{
continue;
}
// We got it. Now we need to convert the Arnold data to string.
// Traverse the tree to get all the connected nodes.
AtNodeSet relatedNodes;
relatedNodes.insert(translatedNode);
getAllArnoldNodes(translatedNode, &relatedNodes);
std::string rootName = AiNodeGetName(translatedNode);
Json::Value nodes(Json::objectValue);
for (const AtNode* current : relatedNodes)
{
std::string currentName = AiNodeGetName(current);
Json::Value node = arnNodeToJson(current);
if (!node.empty())
{
// We only need to keep valid nodes.
nodes[currentName] = node;
}
}
if (!nodes.empty())
{
result[currentObject.asChar()] = nodes;
}
}
MString resultStr = Json::FastWriter().write(result).c_str();
MPxCommand::setResult(resultStr);
return MStatus::kSuccess;
}
<|start_filename|>walter/maya/AbcExport/MayaCameraWriter.cpp<|end_filename|>
//-*****************************************************************************
//
// Copyright (c) 2009-2012,
// Sony Pictures Imageworks Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// All rights reserved.
//
// 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.
// * Neither the name of Sony Pictures Imageworks, nor
// Industrial Light & Magic, nor the names of their contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// 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.
//
//-*****************************************************************************
#include "MayaCameraWriter.h"
MayaCameraWriter::MayaCameraWriter(MDagPath & iDag,
Alembic::Abc::OObject & iParent, Alembic::Util::uint32_t iTimeIndex,
const JobArgs & iArgs) :
mIsAnimated(false),
mDagPath(iDag),
mUseRenderShutter(false),
mShutterOpen(0.0),
mShutterClose(0.0)
{
MStatus status = MS::kSuccess;
MFnCamera cam(iDag, &status);
if (!status)
{
MGlobal::displayError( "MFnCamera() failed for MayaCameraWriter" );
}
MString name = cam.name();
name = util::stripNamespaces(name, iArgs.stripNamespace);
Alembic::AbcCoreAbstract::MetaData md;
util::setMeta(cam, iArgs, md);
Alembic::AbcGeom::OCamera obj(iParent, name.asChar(), iTimeIndex, md);
mSchema = obj.getSchema();
MObject cameraObj = iDag.node();
if (iTimeIndex != 0 && util::isAnimated(cameraObj))
{
mIsAnimated = true;
}
else
{
iTimeIndex = 0;
}
MObject renderObj;
MSelectionList sel;
sel.add("defaultRenderGlobals");
if (!sel.isEmpty())
{
sel.getDependNode(0, renderObj);
MFnDependencyNode dep(renderObj);
MPlug plug = dep.findPlug("motionBlurUseShutter");
if (plug.asBool())
{
MTime sec(1.0, MTime::kSeconds);
double val = sec.as(MTime::uiUnit());
mUseRenderShutter = true;
plug = dep.findPlug("motionBlurShutterOpen");
mShutterOpen = plug.asDouble() / val;
plug = dep.findPlug("motionBlurShutterClose");
mShutterClose = plug.asDouble() / val;
}
}
Alembic::Abc::OCompoundProperty cp;
Alembic::Abc::OCompoundProperty up;
if (AttributesWriter::hasAnyAttr(cam, iArgs))
{
cp = mSchema.getArbGeomParams();
up = mSchema.getUserProperties();
}
mAttrs = AttributesWriterPtr(new AttributesWriter(cp, up, obj, cam,
iTimeIndex, iArgs, true));
if (!mIsAnimated || iArgs.setFirstAnimShape)
{
write();
}
}
void MayaCameraWriter::write()
{
MFnCamera mfnCamera(mDagPath);
mSamp.setFocalLength(mfnCamera.focalLength());
mSamp.setLensSqueezeRatio(mfnCamera.lensSqueezeRatio());
mSamp.setHorizontalAperture(mfnCamera.horizontalFilmAperture() * 2.54);
mSamp.setVerticalAperture(mfnCamera.verticalFilmAperture() * 2.54);
mSamp.setHorizontalFilmOffset(mfnCamera.horizontalFilmOffset() * 2.54);
mSamp.setVerticalFilmOffset(mfnCamera.verticalFilmOffset() * 2.54);
double overscan = mfnCamera.overscan() - 1.0;
mSamp.setOverScanLeft(overscan);
mSamp.setOverScanRight(overscan);
mSamp.setOverScanTop(overscan);
mSamp.setOverScanBottom(overscan);
mSamp.setNearClippingPlane(mfnCamera.nearClippingPlane());
mSamp.setFarClippingPlane(mfnCamera.farClippingPlane());
mSamp.setFStop(mfnCamera.fStop());
mSamp.setFocusDistance(mfnCamera.focusDistance());
// should this be based on the shutterAngle? or the settings passed in?
if (mUseRenderShutter)
{
mSamp.setShutterOpen(mShutterOpen);
mSamp.setShutterClose(mShutterClose);
}
else
{
MTime sec(1.0, MTime::kSeconds);
mSamp.setShutterOpen(0.0);
mSamp.setShutterClose(
Alembic::AbcGeom::RadiansToDegrees(mfnCamera.shutterAngle()) /
( 360.0 * sec.as(MTime::uiUnit()) ));
}
// build up the film fit and post projection matrix
if (mSchema.getNumSamples() == 0)
{
// film fit first
std::string filmFitName = "filmFit";
mFilmFit = mfnCamera.filmFit();
switch (mFilmFit)
{
case MFnCamera::kFillFilmFit:
{
Alembic::AbcGeom::FilmBackXformOp fit(
Alembic::AbcGeom::kScaleFilmBackOperation, "filmFitFill");
mSamp.addOp(fit);
}
break;
case MFnCamera::kHorizontalFilmFit:
{
Alembic::AbcGeom::FilmBackXformOp fit(
Alembic::AbcGeom::kScaleFilmBackOperation, "filmFitHorz");
mSamp.addOp(fit);
Alembic::AbcGeom::FilmBackXformOp offset(
Alembic::AbcGeom::kTranslateFilmBackOperation,
"filmFitOffs");
mSamp.addOp(offset);
}
break;
case MFnCamera::kVerticalFilmFit:
{
Alembic::AbcGeom::FilmBackXformOp fit(
Alembic::AbcGeom::kScaleFilmBackOperation, "filmFitVert");
mSamp.addOp(fit);
Alembic::AbcGeom::FilmBackXformOp offset(
Alembic::AbcGeom::kTranslateFilmBackOperation,
"filmFitOffs");
mSamp.addOp(offset);
}
break;
case MFnCamera::kOverscanFilmFit:
{
Alembic::AbcGeom::FilmBackXformOp fit(
Alembic::AbcGeom::kScaleFilmBackOperation, "filmFitOver");
mSamp.addOp(fit);
}
break;
default:
break;
}
Alembic::AbcGeom::FilmBackXformOp preScale(
Alembic::AbcGeom::kScaleFilmBackOperation, "preScale");
mSamp.addOp(preScale);
Alembic::AbcGeom::FilmBackXformOp filmTranslate(
Alembic::AbcGeom::kTranslateFilmBackOperation, "filmTranslate");
mSamp.addOp(filmTranslate);
// skip film roll for now
Alembic::AbcGeom::FilmBackXformOp postScale(
Alembic::AbcGeom::kScaleFilmBackOperation, "postScale");
mSamp.addOp(postScale);
Alembic::AbcGeom::FilmBackXformOp cameraScale(
Alembic::AbcGeom::kScaleFilmBackOperation, "cameraScale");
mSamp.addOp(cameraScale);
}
std::size_t filmBackIndex = 0;
switch (mFilmFit)
{
case MFnCamera::kFillFilmFit:
{
if (mSamp.getLensSqueezeRatio() > 1.0)
{
mSamp[0].setChannelValue(0, 1.0/mSamp.getLensSqueezeRatio());
mSamp[0].setChannelValue(1, 1.0);
}
else
{
mSamp[0].setChannelValue(0, 1.0);
mSamp[0].setChannelValue(1, mSamp.getLensSqueezeRatio());
}
filmBackIndex = 1;
}
break;
case MFnCamera::kHorizontalFilmFit:
{
if (mSamp.getLensSqueezeRatio() > 1.0)
{
mSamp[0].setChannelValue(0, 1.0);
mSamp[0].setChannelValue(1, mSamp.getLensSqueezeRatio());
mSamp[1].setChannelValue(0, 0.0);
mSamp[1].setChannelValue(1, 2.0 *
mfnCamera.filmFitOffset()/
mfnCamera.horizontalFilmAperture() );
}
else
{
mSamp[0].setChannelValue(0, 1.0);
mSamp[0].setChannelValue(1, 1.0);
mSamp[1].setChannelValue(0, 0.0);
mSamp[1].setChannelValue(1, 0.0);
}
filmBackIndex = 2;
}
break;
case MFnCamera::kVerticalFilmFit:
{
if (1.0/mSamp.getLensSqueezeRatio() > 1.0)
{
mSamp[0].setChannelValue(0, 1.0/mSamp.getLensSqueezeRatio());
mSamp[0].setChannelValue(1, 1.0);
mSamp[1].setChannelValue(0, 2.0 *
mfnCamera.filmFitOffset() /
mfnCamera.horizontalFilmAperture() );
mSamp[1].setChannelValue(1, 0.0);
}
else
{
mSamp[0].setChannelValue(0, 1.0);
mSamp[0].setChannelValue(1, 1.0);
mSamp[1].setChannelValue(0, 0.0);
mSamp[1].setChannelValue(1, 0.0);
}
filmBackIndex = 2;
}
break;
case MFnCamera::kOverscanFilmFit:
{
if (mSamp.getLensSqueezeRatio() < 1.0)
{
mSamp[0].setChannelValue(0, 1.0);
mSamp[0].setChannelValue(1, mSamp.getLensSqueezeRatio());
}
else
{
mSamp[0].setChannelValue(0, 1.0/mSamp.getLensSqueezeRatio());
mSamp[0].setChannelValue(1, 1.0);
}
filmBackIndex = 1;
}
break;
default:
break;
}
mSamp[filmBackIndex].setChannelValue(0, 1.0/mfnCamera.preScale());
mSamp[filmBackIndex].setChannelValue(1, 1.0/mfnCamera.preScale());
mSamp[filmBackIndex+1].setChannelValue(0, mfnCamera.filmTranslateH());
mSamp[filmBackIndex+1].setChannelValue(1, mfnCamera.filmTranslateV());
mSamp[filmBackIndex+2].setChannelValue(0, 1.0/mfnCamera.postScale());
mSamp[filmBackIndex+2].setChannelValue(1, 1.0/mfnCamera.postScale());
mSamp[filmBackIndex+3].setChannelValue(0, mfnCamera.cameraScale());
mSamp[filmBackIndex+3].setChannelValue(1, mfnCamera.cameraScale());
mSchema.set(mSamp);
}
bool MayaCameraWriter::isAnimated() const
{
return mIsAnimated || (mAttrs != NULL && mAttrs->isAnimated());
}
<|start_filename|>walter/usd/walterUSDCommonUtils.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "PathUtil.h"
#include "walterUSDCommonUtils.h"
#include <pxr/usd/ar/resolver.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usd/variantSets.h>
#include <pxr/usd/usdGeom/imageable.h>
#include "schemas/expression.h"
#include "walterUsdConversion.h"
#include <boost/algorithm/string.hpp>
PXR_NAMESPACE_USING_DIRECTIVE
/**
* @brief Converts the primPath (Path of the primitive in the stage) to the
* corresponding SdfPath.
*
* @param primPath The primitive path as string.
*
* @return The SdfPath path.
*/
SdfPath GetSdfPathFromPrimPath(const char* primPath)
{
return (primPath != nullptr) && (primPath[0] == '\0') ?
SdfPath::AbsoluteRootPath() :
SdfPath(primPath);
}
SdfLayerRefPtr WalterUSDCommonUtils::getUSDLayer(const std::string& path)
{
std::vector<std::string> archives;
boost::algorithm::split(archives, path, boost::is_any_of(":"));
return getUSDLayer(archives);
}
SdfLayerRefPtr WalterUSDCommonUtils::getUSDLayer(
const std::vector<std::string>& paths)
{
ArResolver& resolver = ArGetResolver();
resolver.Clear();
// Open and compose several layers. Since we can compose several different
// formats, we need to be sure that alembics are composed with AbcCoreLayer.
// To do it, it's necessary to provide the list of alembics as a single
// layer. This trick doesn't work with .usd files, thus, we need to group
// all the layers to contain one usd or list of abc files.
std::vector<std::string> allArchives;
std::vector<std::string> alembicArchives;
for (const std::string archive : paths)
{
if (archive.empty())
{
continue;
}
if (boost::iends_with(archive, ".abc"))
{
// We need to compose the alembic files with AbcCoreLayer and we
// need to keep all the alembics in the one single string.
alembicArchives.push_back(archive);
}
else
{
if (!alembicArchives.empty())
{
allArchives.push_back(
boost::algorithm::join(alembicArchives, ":"));
alembicArchives.clear();
}
allArchives.push_back(archive);
}
}
if (!alembicArchives.empty())
{
allArchives.push_back(boost::algorithm::join(alembicArchives, ":"));
}
// We can check if we don't have archives or we have only one and skip the
// anonymous layer generation like this:
// if (allArchives.empty())
// return SdfLayerRefPtr();
// else if(allArchives.size() == 1)
// return SdfLayer::FindOrOpen(allArchives[0]);
// But we need anonymous layer to store internal sub-layers. For example to
// freeze all the transforms.
// In USD the first layer wins. In Walter the last layer wins. We just need
// to reverse it.
std::reverse(allArchives.begin(), allArchives.end());
// Create a layer that refers to all the layers.
SdfLayerRefPtr layer = SdfLayer::CreateAnonymous();
if (!allArchives.empty())
{
layer->SetSubLayerPaths(allArchives);
}
return layer;
}
SdfLayerRefPtr WalterUSDCommonUtils::getAnonymousLayer(
UsdStageRefPtr stage,
const std::string& name)
{
const std::string fullName = name + ".usd";
const std::string colonName = ":" + fullName;
SdfLayerRefPtr rootLayer = stage->GetRootLayer();
// Looking for the requested layer.
SdfLayerRefPtr anonymousLayer;
SdfSubLayerProxy subLayers = rootLayer->GetSubLayerPaths();
for (size_t i = 0, s = subLayers.size(); i < s; i++)
{
// Iteration with index to be able to remove the layer from the sublayer
// list.
const std::string& identifier = subLayers[i];
// TODO: Is there something better to determine if the layer is
// anonimous and to get its name?
if (boost::starts_with(identifier, "anon:") &&
boost::ends_with(identifier, colonName))
{
anonymousLayer = SdfLayer::FindOrOpen(identifier);
// USD destroys anonymous layer when calling UsdStage::MuteLayer. To
// avoid it, it's necessary to keep it somethere. But if it happens,
// we don't need to have its identifier in sub-layers, so it should
// be removed.
if (!anonymousLayer)
{
rootLayer->RemoveSubLayerPath(i);
}
break;
}
}
// Create it if it's not there.
if (!anonymousLayer)
{
anonymousLayer = SdfLayer::CreateAnonymous(fullName);
// Put it to the front
rootLayer->InsertSubLayerPath(anonymousLayer->GetIdentifier(), 0);
}
return anonymousLayer;
}
bool WalterUSDCommonUtils::setUSDVariantsLayer(
UsdStageRefPtr stage,
const char* variants)
{
SdfLayerRefPtr variantLayer = getAnonymousLayer(stage, "variantLayer");
if ((variants != nullptr) && (variants[0] == '\0'))
{
variantLayer->Clear();
}
else if (!variantLayer->ImportFromString(variants))
{
variantLayer->Clear();
return false;
}
return true;
}
bool WalterUSDCommonUtils::setUSDPurposeLayer(
UsdStageRefPtr stage,
const char* purpose)
{
SdfLayerRefPtr purposeLayer = getAnonymousLayer(stage, "purposeLayer");
if ((purpose != nullptr) && (purpose[0] == '\0'))
{
purposeLayer->Clear();
}
else if (!purposeLayer->ImportFromString(purpose))
{
purposeLayer->Clear();
return false;
}
return true;
}
std::string WalterUSDCommonUtils::getVariantsLayerAsText(UsdStageRefPtr stage)
{
std::string variants;
SdfLayerRefPtr variantLayer = getAnonymousLayer(stage, "variantLayer");
variantLayer->ExportToString(&variants);
return variants;
}
std::string WalterUSDCommonUtils::getPurposeLayerAsText(UsdStageRefPtr stage)
{
std::string purpose;
SdfLayerRefPtr purposeLayer = getAnonymousLayer(stage, "purposeLayer");
purposeLayer->ExportToString(&purpose);
return purpose;
}
bool WalterUSDCommonUtils::setUSDVisibilityLayer(
UsdStageRefPtr stage,
const char* visibility)
{
SdfLayerRefPtr visibilityLayer = getAnonymousLayer(stage, "visibilityLayer");
if ((visibility != nullptr) && (visibility[0] == '\0'))
{
visibilityLayer->Clear();
}
else if (!visibilityLayer->ImportFromString(visibility))
{
visibilityLayer->Clear();
return false;
}
return true;
}
std::vector<std::string> WalterUSDCommonUtils::dirUSD(
UsdStageRefPtr stage,
const char* primPath)
{
std::vector<std::string> result;
SdfPath path = GetSdfPathFromPrimPath(primPath);
UsdPrim prim = stage->GetPrimAtPath(path);
if (!prim)
{
return {};
}
UsdPrimSiblingRange children = prim.GetChildren();
for (const UsdPrim& prim : children)
result.push_back(prim.GetPath().GetText());
return result;
}
std::vector<std::string> WalterUSDCommonUtils::propertiesUSD(
UsdStageRefPtr stage,
const char* primPath,
double time,
bool attributeOnly)
{
std::vector<std::string> result;
SdfPath path = GetSdfPathFromPrimPath(primPath);
UsdPrim prim = stage->GetPrimAtPath(path);
if (!prim)
{
return {};
}
UsdTimeCode tc(time);
const std::vector<UsdProperty>& properties = prim.GetProperties();
for (unsigned i = 0; i < properties.size(); i++)
{
UsdProperty const& prop = properties[i];
int arraySize = -1;
std::string type, value;
if (WalterUsdConversion::getPropertyValueAsString(
prop, tc, type, value, arraySize, attributeOnly))
{
std::string description =
WalterUsdConversion::constuctStringRepresentation(
prop.GetBaseName().GetText(),
prop.Is<UsdAttribute>() ? "Attribute" : "Relationship",
type,
value,
arraySize);
result.push_back(description);
}
}
return result;
}
std::string WalterUSDCommonUtils::getVisibilityLayerAsText(UsdStageRefPtr stage)
{
std::string visibility;
SdfLayerRefPtr visibilityLayer = getAnonymousLayer(stage, "visibilityLayer");
visibilityLayer->ExportToString(&visibility);
return visibility;
}
/**
* @brief Traverses recursively the USD hierarchy to get the variants.
*
* @param prim The USD primitive the get the variants from.
* @param result The variants list (as an array of json).
*
*/
void GetPrimVariants(
UsdPrim const& prim,
bool recursively,
std::vector<std::string>& result)
{
const UsdVariantSets& variantsSets = prim.GetVariantSets();
std::vector<std::string> variantsSetsName = variantsSets.GetNames();
std::string jsonStr = "{ ";
if (variantsSetsName.size() > 0)
{
jsonStr += "\"prim\": \"" + prim.GetPath().GetString() + "\"";
jsonStr += ", \"variants\": [";
}
for (unsigned i = 0; i < variantsSetsName.size(); ++i)
{
const UsdVariantSet& variantsSet =
variantsSets.GetVariantSet(variantsSetsName[i]);
jsonStr += "{ ";
jsonStr += "\"set\": \"" + variantsSetsName[i] + "\", \"names\": [";
std::vector<std::string> variantsName = variantsSet.GetVariantNames();
for (unsigned j = 0; j < variantsName.size(); ++j)
{
jsonStr += "\"" + variantsName[j] + "\"";
if(j < (variantsName.size() - 1))
{
jsonStr += ", ";
}
}
jsonStr += "], \"selection\": \"" + variantsSet.GetVariantSelection() + "\"";
jsonStr += " } ";
if (i < variantsSetsName.size() - 1)
{
jsonStr += ", ";
}
else
{
jsonStr += "] ";
}
}
jsonStr += " }";
if (variantsSetsName.size() > 0)
{
result.push_back(jsonStr);
}
if(recursively)
{
for (const UsdPrim& child : prim.GetChildren())
{
GetPrimVariants(child, recursively, result);
}
}
}
std::vector<std::string> WalterUSDCommonUtils::getVariantsUSD(
UsdStageRefPtr stage,
const char* primPath,
bool recursively)
{
std::vector<std::string> result;
SdfPath path = GetSdfPathFromPrimPath(primPath);
UsdPrim prim = stage->GetPrimAtPath(path);
if (!prim)
{
return {};
}
GetPrimVariants(
prim,
recursively,
result);
return result;
}
/**
* @brief Traverses recursively the USD hierarchy to set the selected variant.
*
* @param prim The USD primitive.
* @param variantName const char* The variant to set.
* @param variantSetName const char* The variantSet.
*/
void SetVariantsRecursively(
UsdPrim const& prim,
const char* variantName,
const char* variantSetName)
{
UsdVariantSets variantsSets = prim.GetVariantSets();
if (variantsSets.HasVariantSet(variantSetName))
{
variantsSets.SetSelection(variantSetName, variantName);
}
for (const UsdPrim& child : prim.GetChildren())
{
SetVariantsRecursively(child, variantName, variantSetName);
}
}
void WalterUSDCommonUtils::setVariantUSD(
UsdStageRefPtr stage,
const char* primPath,
const char* variantName,
const char* variantSetName)
{
SdfPath path = GetSdfPathFromPrimPath(primPath);
UsdPrim prim = stage->GetPrimAtPath(path);
if (!prim)
{
return;
}
SetVariantsRecursively(prim, variantName, variantSetName);
}
void WalterUSDCommonUtils::setVariantUSD(
UsdStageRefPtr stage,
const char* variantDefStr)
{
std::string str = variantDefStr;
if (str.empty())
{
return;
}
std::vector<std::string> tmp;
boost::algorithm::split(tmp, str, boost::is_any_of("{"));
std::string nodePath = tmp[0];
boost::algorithm::split(tmp, tmp[1], boost::is_any_of("="));
std::string variantSetName = tmp[0];
std::string variantName = tmp[1];
variantName = variantName.substr(0, variantName.size() - 1);
setVariantUSD(
stage, nodePath.c_str(), variantName.c_str(), variantSetName.c_str());
}
std::vector<std::string> WalterUSDCommonUtils::primVarUSD(
UsdStageRefPtr stage,
const char* primPath,
double time)
{
std::vector<std::string> result;
SdfPath path = GetSdfPathFromPrimPath(primPath);
UsdPrim prim = stage->GetPrimAtPath(path);
if (!prim)
{
return {};
}
if (!prim.IsA<UsdGeomImageable>())
{
return {};
}
UsdGeomImageable imageable(prim);
const std::vector<UsdGeomPrimvar>& primVars = imageable.GetPrimvars();
UsdTimeCode tc(time);
for (unsigned i = 0; i < primVars.size(); ++i)
{
UsdGeomPrimvar const& primVar = primVars[i];
UsdAttribute const& attr = primVar.GetAttr();
int arraySize = -1;
std::string type, value;
if (WalterUsdConversion::getAttributeValueAsString(
attr, tc, type, value, arraySize))
{
std::string description =
WalterUsdConversion::constuctStringRepresentation(
attr.GetBaseName().GetText(),
"PrimVar",
type,
value,
arraySize);
result.push_back(description);
}
}
return result;
}
bool WalterUSDCommonUtils::isPseudoRoot(
UsdStageRefPtr stage,
const char* primPath)
{
std::string pathStr = primPath;
SdfPath path = pathStr.empty()
? SdfPath::AbsoluteRootPath()
: SdfPath(pathStr);
UsdPrim prim = stage->GetPrimAtPath(path);
return prim
? prim.IsPseudoRoot()
: false;
}
bool WalterUSDCommonUtils::isVisible(
UsdStageRefPtr stage,
const char* primPath)
{
std::string pathStr = primPath;
SdfPath path = pathStr.empty()
? SdfPath::AbsoluteRootPath()
: SdfPath(pathStr);
UsdPrim prim = stage->GetPrimAtPath(path);
if (prim && prim.IsA<UsdGeomImageable>())
{
UsdGeomImageable imageable(prim);
return imageable.ComputeVisibility() != TfToken("invisible");
}
return true;
}
bool WalterUSDCommonUtils::toggleVisibility(
UsdStageRefPtr stage,
const char* primPath)
{
std::string pathStr = primPath;
SdfPath path = pathStr.empty()
? SdfPath::AbsoluteRootPath()
: SdfPath(pathStr);
bool isVisible = true;
UsdPrim prim = stage->GetPrimAtPath(path);
if (prim && prim.IsA<UsdGeomImageable>())
{
UsdGeomImageable imageable(prim);
isVisible = imageable.ComputeVisibility() != TfToken("invisible");
isVisible = setVisibility(stage, primPath, !isVisible);
}
return !isVisible;
}
bool WalterUSDCommonUtils::setVisibility(
UsdStageRefPtr stage,
const char* primPath,
bool visible)
{
std::string pathStr = primPath;
SdfPath path = pathStr.empty()
? SdfPath::AbsoluteRootPath()
: SdfPath(pathStr);
UsdPrim parentPrim = stage->GetPrimAtPath(path);
// When making a prim visible, we fist must make its
// parent visible because this properties is inherited.
if(visible)
{
std::vector<UsdPrim> tmp;
UsdPrim prim = parentPrim;
while(prim && prim.IsValid()) {
tmp.push_back(prim);
prim = prim.GetParent();
}
for(uint32_t i=tmp.size(); i--;)
{
const UsdPrim& prim = tmp[i];
if(prim && prim.IsValid() && prim.IsA<UsdGeomImageable>())
{
UsdGeomImageable imageable(prim);
if(visible)
{
imageable.MakeVisible();
}
else
{
imageable.MakeInvisible();
}
}
}
}
UsdPrimRange range(parentPrim);
for (const UsdPrim& prim : range)
{
if( prim.IsA<UsdGeomImageable>())
{
UsdGeomImageable imageable(prim);
if(visible)
{
imageable.MakeVisible();
}
else
{
imageable.MakeInvisible();
}
}
}
bool isVisible = false;
if( parentPrim.IsA<UsdGeomImageable>()) {
UsdGeomImageable imageable(parentPrim);
isVisible = imageable.ComputeVisibility() != TfToken("invisible");
}
return isVisible;
}
bool WalterUSDCommonUtils::hideAllExceptedThis(
UsdStageRefPtr stage,
const char* primPath)
{
if (!stage)
{
return false;
}
// Hide all the prims
setVisibility(stage, "", false);
// Make visible the one we want
return setVisibility(stage, primPath, true);
}
bool WalterUSDCommonUtils::expressionIsMatching(
UsdStageRefPtr stage,
const char* expression)
{
if (!stage)
{
return false;
}
bool expressionIsValid = false;
// Generate a regexp object.
void* regexp = WalterCommon::createRegex(expression);
UsdPrimRange range(stage->GetPrimAtPath(SdfPath::AbsoluteRootPath()));
for (const UsdPrim& prim : range)
{
const SdfPath& path = prim.GetPath();
std::string current = path.GetString();
// TODO: What if we have '/cube' and '/cubeBig/shape' objects? If we
// try to select the first one, both of them will be selected.
if (boost::starts_with(current, expression) ||
WalterCommon::searchRegex(regexp, current))
{
expressionIsValid = true;
break;
}
}
// Delete a regexp object.
WalterCommon::clearRegex(regexp);
return expressionIsValid;
}
std::vector<UsdPrim> WalterUSDCommonUtils::primsMatchingExpression(
UsdStageRefPtr stage,
const char* expression)
{
std::vector<UsdPrim> res;
if (!stage)
{
return res;
}
// Generate a regexp object.
void* regexp = WalterCommon::createRegex(expression);
UsdPrimRange range(stage->GetPrimAtPath(SdfPath::AbsoluteRootPath()));
for (const UsdPrim& prim : range)
{
const SdfPath& path = prim.GetPath();
std::string current = path.GetString();
// TODO: What if we have '/cube' and '/cubeBig/shape' objects? If we
// try to select the first one, both of them will be selected.
if (boost::starts_with(current, expression) ||
WalterCommon::searchRegex(regexp, current))
{
res.push_back(prim);
}
}
// Delete a regexp object.
WalterCommon::clearRegex(regexp);
return res;
}
std::vector<std::string> WalterUSDCommonUtils::primPathsMatchingExpression(
UsdStageRefPtr stage,
const char* expression)
{
std::vector<UsdPrim> prims = primsMatchingExpression(
stage, expression);
std::vector<std::string> res;
for(auto prim : prims)
{
res.push_back(prim.GetPath().GetText());
}
return res;
}
std::string WalterUSDCommonUtils::setPurpose(
UsdStageRefPtr stage,
const char* primPath,
const char* purposeStr)
{
std::string pathStr = primPath;
SdfPath path = pathStr.empty()
? SdfPath::AbsoluteRootPath()
: SdfPath(pathStr);
UsdPrim parentPrim = stage->GetPrimAtPath(path);
std::vector<UsdPrim> tmp;
UsdPrim prim = parentPrim;
while(prim && prim.IsValid())
{
tmp.push_back(prim);
prim = prim.GetParent();
}
for(uint32_t i=tmp.size(); i--;)
{
const UsdPrim& prim = tmp[i];
if(prim && prim.IsValid() && prim.IsA<UsdGeomImageable>())
{
UsdGeomImageable imageable(prim);
TfToken token("default");
imageable.CreatePurposeAttr(VtValue(token));
}
}
UsdPrimRange range(parentPrim);
for (const UsdPrim& prim : range)
{
if( prim.IsA<UsdGeomImageable>())
{
UsdGeomImageable imageable(prim);
TfToken token(purposeStr);
imageable.CreatePurposeAttr(VtValue(token));
}
}
return purposeStr;
}
std::string WalterUSDCommonUtils::purpose(
UsdStageRefPtr stage,
const char* primPath)
{
std::string pathStr = primPath;
SdfPath path = pathStr.empty()
? SdfPath::AbsoluteRootPath()
: SdfPath(pathStr);
UsdPrim prim = stage->GetPrimAtPath(path);
if (prim.IsA<UsdGeomImageable>())
{
UsdGeomImageable imageable(prim);
TfToken token = imageable.ComputePurpose();
return token.GetText();
}
return "default";
}
WalterUSDCommonUtils::MastersInfoMap WalterUSDCommonUtils::getMastersInfo(
UsdStageRefPtr stage
)
{
WalterUSDCommonUtils::MastersInfoMap mastersInfo;
if (stage->GetMasters().empty())
{
return mastersInfo;
}
for (UsdPrim prim: stage->Traverse())
{
// If the primitive is not an instance there is no master prim
// information to look for...
if (!prim.IsInstance())
{
continue;
}
// ... Otherwise get the master primitive and look for more information
// if it's the first time we encounter it.
UsdPrim masterPrim = prim.GetMaster();
if (mastersInfo.find(masterPrim.GetName()) ==
mastersInfo.end())
{
const auto& primStack = prim.GetPrimStack();
// This Prim is the 'real' one represented by the masterPrim, we
// need it's name for material assignment and better naming in
// Katana.
SdfPrimSpec referencedPrim = primStack.back().GetSpec();
// Also get the eventual list of variant selection (just the variant
// name) to help construct a meaningful katana location for the
// master location (instance source).
SdfHandle<SdfPrimSpec> handle = *(primStack.rbegin() + 1);
SdfPrimSpec variantsPrim = handle.GetSpec();
std::vector<std::string> variantsSelection =
WalterUSDCommonUtils::getVariantsSelection(
variantsPrim.GetPath()
);
// Build a MasterPrimInfo object with the two previous information
// and mapped it with the USD master primitive name.
WalterUSDCommonUtils::MasterPrimInfo masterInfo = {
referencedPrim.GetName(),
variantsSelection
};
mastersInfo.emplace(
masterPrim.GetName(),
masterInfo
);
}
}
return mastersInfo;
}
void getVariantsSelectionRecursively(
const SdfPath& path,
std::vector<std::string>& variantSelections)
{
if (path.IsPrimVariantSelectionPath())
{
variantSelections.emplace_back(path.GetVariantSelection().second);
SdfPath parentPath = path.GetParentPath();
getVariantsSelectionRecursively(parentPath, variantSelections);
}
}
std::vector<std::string> WalterUSDCommonUtils::getVariantsSelection(const SdfPath& path)
{
std::vector<std::string> variantsSelection;
getVariantsSelectionRecursively(path, variantsSelection);
return variantsSelection;
}
<|start_filename|>walter/usd/resolver/abcCoreLayerResolver.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __ABCCORELAYERRESOLVER_H_
#define __ABCCORELAYERRESOLVER_H_
#include <pxr/usd/ar/defaultResolver.h>
PXR_NAMESPACE_OPEN_SCOPE
class AbcCoreLayerResolver : public ArDefaultResolver
{
typedef ArDefaultResolver BaseType;
public:
AbcCoreLayerResolver();
// Returns the resolved filesystem path for the file identified by path.
virtual std::string ResolveWithAssetInfo(
const std::string& path,
ArAssetInfo* assetInfo) override;
// Return a value representing the last time the asset identified by path
// was modified. resolvedPath is the resolved path of the asset.
virtual VtValue GetModificationTimestamp(
const std::string& path,
const std::string& resolvedPath) override;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif
<|start_filename|>walter/usd/tests/test_getAnonymousLayer.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usd/stage.h>
#include "walterUSDCommonUtils.h"
#include <gtest/gtest.h>
PXR_NAMESPACE_USING_DIRECTIVE
TEST(getAnonymousLayer, testCreateAndGet)
{
UsdStageRefPtr stage = UsdStage::CreateInMemory();
SdfLayerRefPtr layer = WalterUSDCommonUtils::getAnonymousLayer(stage, "foo");
EXPECT_TRUE(layer->IsAnonymous());
EXPECT_EQ(layer->GetDisplayName(), "foo.usd");
}
TEST(getAnonymousLayer, testGet)
{
SdfLayerRefPtr layer = SdfLayer::CreateAnonymous("foo.usd");
UsdStageRefPtr stage = UsdStage::CreateInMemory();
layer = WalterUSDCommonUtils::getAnonymousLayer(stage, "foo");
EXPECT_TRUE(layer->IsAnonymous());
EXPECT_EQ(layer->GetDisplayName(), "foo.usd");
}
<|start_filename|>walter/katana/WalterIn/walterUSDOpUtils.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterUSDOpUtils.h"
#include <unordered_map>
// Declare USD debugging messages.
PXR_NAMESPACE_OPEN_SCOPE
TF_REGISTRY_FUNCTION(TfDebug)
{
TF_DEBUG_ENVIRONMENT_SYMBOL(WALTER_KATANA, "Output to Katana");
}
PXR_NAMESPACE_CLOSE_SCOPE
OpUtils::Time::Time(
TimeType iCurrent,
TimeType iOpen,
TimeType iClose,
size_t iSamples) :
mCurrent(iCurrent)
{
assert(iSamples);
mSamples.reserve(iSamples);
if (iSamples == 1)
{
// We use 0.0 because if there are no motion blur, Katana sets shutter
// open/close times as 0.0 and 1.0.
mSamples.push_back((TimeType)0);
}
else
{
for (size_t i = 0; i < iSamples; i++)
{
mSamples.push_back(iOpen + (iClose - iOpen) * i / (iSamples - 1));
}
}
}
OpUtils::PrivateData::PrivateData(
OpEngine& iEngine,
const std::string iKatanaRoot,
const SdfPath& iCurrentPath,
TimePtr iTime) :
mEngine(&iEngine),
mKatanaRoot(iKatanaRoot),
mCurrentPath(iCurrentPath),
mTime(iTime)
{}
std::string OpUtils::getClientAttributeName(const std::string& iName)
{
// We receive Arnold attributes, and we need to make KTOA understanding
// them. The only way to do it is remapping them.
static const std::unordered_map<std::string, std::string> sArnoldAttrs = {
{ "casts_shadows", "arnoldStatements.visibility.AI_RAY_SHADOW" },
{ "disp_autobump", "arnoldStatements.disp_autobump" },
{ "disp_height", "arnoldStatements.disp_height" },
{ "disp_padding", "arnoldStatements.disp_padding" },
{ "disp_zero_value", "arnoldStatements.zero_value" },
{ "matte", "arnoldStatements.matte" },
{ "opaque", "arnoldStatements.opaque" },
{ "primary_visibility", "arnoldStatements.visibility.AI_RAY_CAMERA" },
{ "self_shadows", "arnoldStatements.visibility.AI_RAY_SHADOW" },
{ "subdiv_adaptive_error", "arnoldStatements.subdiv_adaptive_error" },
{ "subdiv_adaptive_metric", "arnoldStatements.subdiv_adaptive_metric" },
{ "subdiv_adaptive_space", "arnoldStatements.subdiv_adaptive_space" },
{ "subdiv_iterations", "arnoldStatements.iterations" },
{ "subdiv_smooth_derivs", "arnoldStatements.subdiv_smooth_derivs" },
{ "subdiv_type", "arnoldStatements.subdiv_type" },
{ "subdiv_uv_smoothing", "arnoldStatements.subdiv_uv_smoothing" },
{ "visibility", "visible" },
{ "visible_in_diffuse", "arnoldStatements.visibility.AI_RAY_DIFFUSE" },
{ "visible_in_diffuse_reflection",
"arnoldStatements.visibility.AI_RAY_DIFFUSE_REFLECT" },
{ "visible_in_diffuse_transmission",
"arnoldStatements.visibility.AI_RAY_DIFFUSE_TRANSMIT" },
{ "visible_in_glossy", "arnoldStatements.visibility.AI_RAY_GLOSSY" },
{ "visible_in_reflections",
"arnoldStatements.visibility.AI_RAY_REFLECTED" },
{ "visible_in_refractions",
"arnoldStatements.visibility.AI_RAY_REFRACTED" },
{ "visible_in_specular_reflection",
"arnoldStatements.visibility.AI_RAY_SPECULAR_REFLECT" },
{ "visible_in_specular_transmission",
"arnoldStatements.visibility.AI_RAY_SPECULAR_TRANSMIT" },
{ "visible_in_volume", "arnoldStatements.visibility.AI_RAY_VOLUME" }
};
const auto found = sArnoldAttrs.find(iName);
if (found != sArnoldAttrs.end())
{
return found->second;
}
return {};
}
<|start_filename|>walter/katana/WalterIn/SubDCook.cpp<|end_filename|>
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ScalarPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
void cookSubd(AbcCookPtr ioCook, FnAttribute::GroupBuilder & oStaticGb)
{
Alembic::AbcGeom::ISubDPtr meshPtr(
new Alembic::AbcGeom::ISubD(*(ioCook->objPtr),
Alembic::AbcGeom::kWrapExisting));
Alembic::AbcGeom::ISubDSchema schema = meshPtr->getSchema();
Alembic::Abc::ICompoundProperty userProp = schema.getUserProperties();
Alembic::Abc::ICompoundProperty arbGeom = schema.getArbGeomParams();
std::string abcUser = "abcUser.";
processUserProperties(ioCook, userProp, oStaticGb, abcUser);
processArbGeomParams(ioCook, arbGeom, oStaticGb);
oStaticGb.set("type", FnAttribute::StringAttribute("subdmesh"));
Alembic::AbcGeom::IV2fGeomParam uvsProp = schema.getUVsParam();
if (uvsProp.valid())
{
processArbitraryGeomParam(ioCook, schema, uvsProp.getHeader(),
oStaticGb, "geometry.arbitrary.st");
}
Alembic::Abc::IInt32ArrayProperty faceProp =
schema.getFaceCountsProperty();
if (faceProp.valid())
{
arrayPropertyToAttr(schema, faceProp.getHeader(),
"geometry.poly.startIndex", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
Alembic::Abc::IInt32ArrayProperty indexProp =
schema.getFaceIndicesProperty();
if (indexProp.valid())
{
arrayPropertyToAttr(schema, indexProp.getHeader(),
"geometry.poly.vertexList", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
Alembic::Abc::IP3fArrayProperty pointsProp =
schema.getPositionsProperty();
if (pointsProp.valid())
{
arrayPropertyToAttr(schema, pointsProp.getHeader(),
"geometry.point.P", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
Alembic::Abc::IV3fArrayProperty velocProp =
schema.getVelocitiesProperty();
if (velocProp.valid())
{
arrayPropertyToAttr(schema, velocProp.getHeader(),
"geometry.point.v", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
Alembic::Abc::IBox3dProperty boundsProp =
schema.getSelfBoundsProperty();
if (boundsProp.valid())
{
scalarPropertyToAttr(schema, boundsProp.getHeader(),
"bound", ioCook, oStaticGb);
}
Alembic::Abc::IInt32Property fvibProp =
schema.getFaceVaryingInterpolateBoundaryProperty();
if (fvibProp.valid())
{
scalarPropertyToAttr(schema, fvibProp.getHeader(),
"geometry.facevaryinginterpolateboundary", ioCook, oStaticGb);
}
Alembic::Abc::IInt32Property fvpcProp =
schema.getFaceVaryingPropagateCornersProperty();
if (fvpcProp.valid())
{
scalarPropertyToAttr(schema, fvpcProp.getHeader(),
"geometry.facevaryingpropagatecorners", ioCook, oStaticGb);
}
Alembic::Abc::IInt32Property ibProp =
schema.getInterpolateBoundaryProperty();
if (ibProp.valid())
{
scalarPropertyToAttr(schema, ibProp.getHeader(),
"geometry.interpolateBoundary", ioCook, oStaticGb);
}
Alembic::Abc::IInt32ArrayProperty holesProp = schema.getHolesProperty();
if (holesProp.valid())
{
arrayPropertyToAttr(schema, holesProp.getHeader(),
"geometry.holePolyIndices", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
Alembic::Abc::IInt32ArrayProperty crlProp =
schema.getCreaseLengthsProperty();
if (crlProp.valid())
{
arrayPropertyToAttr(schema, crlProp.getHeader(),
"geometry.creaseLengths", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
Alembic::Abc::IInt32ArrayProperty criProp =
schema.getCreaseIndicesProperty();
if (criProp.valid())
{
arrayPropertyToAttr(schema, criProp.getHeader(),
"geometry.creaseIndices", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
Alembic::Abc::IFloatArrayProperty crsProp =
schema.getCreaseSharpnessesProperty();
if (crsProp.valid())
{
arrayPropertyToAttr(schema, crsProp.getHeader(),
"geometry.creaseSharpness", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
Alembic::Abc::IInt32ArrayProperty coiProp =
schema.getCornerIndicesProperty();
if (coiProp.valid())
{
arrayPropertyToAttr(schema, coiProp.getHeader(),
"geometry.cornerIndices", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
Alembic::Abc::IFloatArrayProperty cosProp =
schema.getCornerSharpnessesProperty();
if (cosProp.valid())
{
arrayPropertyToAttr(schema, cosProp.getHeader(),
"geometry.cornerSharpness", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
}
} //end of namespace WalterIn
<|start_filename|>walter/usd/fileFormat/usdArnold/arnoldTranslator.cpp<|end_filename|>
// Copyright 2018 <NAME>. All rights reserved.
#include "arnoldTranslator.h"
#include "arnoldApi.h"
#include "schemas/volume.h"
#include <pxr/base/gf/matrix4f.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usdShade/connectableAPI.h>
#include <pxr/usd/usdShade/material.h>
#include <pxr/usd/usdShade/shader.h>
#include <boost/algorithm/string.hpp>
#include <boost/preprocessor/array/elem.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/range/algorithm/replace_copy_if.hpp>
PXR_NAMESPACE_OPEN_SCOPE
namespace ArnoldUSDTranslatorImpl
{
static const TfToken sOut("out");
// TODO:
// AI_TYPE_POINTER
// AI_TYPE_NODE
// AI_TYPE_USHORT
// AI_TYPE_HALF
// AI_TYPE_UNDEFINED
// AI_TYPE_NONE
#define AI_CONVERSION_TABLE \
((2, (AI_TYPE_BYTE, UChar)))((2, (AI_TYPE_INT, Int)))( \
(2, (AI_TYPE_UINT, UInt)))((2, (AI_TYPE_BOOLEAN, Bool)))( \
(2, (AI_TYPE_FLOAT, Float)))((2, (AI_TYPE_RGB, Color3f)))( \
(2, (AI_TYPE_VECTOR, Vector3f)))((2, (AI_TYPE_VECTOR2, Float2)))( \
(2, (AI_TYPE_STRING, String)))((2, (AI_TYPE_MATRIX, Matrix4d)))( \
(2, (AI_TYPE_ENUM, Int)))((2, (AI_TYPE_CLOSURE, Color3f)))( \
(2, (AI_TYPE_RGBA, Color4f)))
#define AI_CONVERSION_TEMPLATE(r, data, arg) \
case BOOST_PP_ARRAY_ELEM(0, arg): \
data = SdfValueTypeNames->BOOST_PP_ARRAY_ELEM(1, arg); \
break;
#define AI_CONVERSION_ARRAY_TEMPLATE(r, data, arg) \
case BOOST_PP_ARRAY_ELEM(0, arg): \
data = SdfValueTypeNames->BOOST_PP_CAT( \
BOOST_PP_ARRAY_ELEM(1, arg), Array); \
break;
SdfValueTypeName aiToUsdParamType(uint8_t iArnoldType, bool iIsArray = false)
{
SdfValueTypeName usdType;
if (iIsArray)
{
switch (iArnoldType)
{
BOOST_PP_SEQ_FOR_EACH(
AI_CONVERSION_ARRAY_TEMPLATE, usdType, AI_CONVERSION_TABLE);
}
}
else
{
switch (iArnoldType)
{
BOOST_PP_SEQ_FOR_EACH(
AI_CONVERSION_TEMPLATE, usdType, AI_CONVERSION_TABLE);
}
}
return usdType;
}
#undef AI_CONVERSION_ARRAY_TEMPLATE
#undef AI_CONVERSION_TEMPLATE
#undef AI_CONVERSION_TABLE
void loadArnoldPlugins(ArnoldAPIPtr ioAi)
{
char* envChar = std::getenv("ARNOLD_PLUGIN_PATH");
std::string envVar = envChar ? envChar : "";
std::vector<std::string> envPath;
boost::split(envPath, envVar, boost::is_any_of(":"));
envChar = std::getenv("ARNOLD_SHADERLIB_PATH");
envVar = envChar ? envChar : "";
std::vector<std::string> envPath2;
boost::split(envPath2, envVar, boost::is_any_of(":"));
envPath.insert(envPath.end(), envPath2.begin(), envPath2.end());
for (auto p : envPath)
{
ioAi->AiLoadPlugins(p.c_str());
}
}
std::string getGoodUSDName(const std::string& iName)
{
std::string processedString;
boost::replace_copy_if(
iName, std::back_inserter(processedString), boost::is_any_of(":"), '_');
return processedString;
}
UsdShadeShader createUSDShader(
UsdStageRefPtr ioStage,
ArnoldAPIPtr ioAi,
const SdfPath& iPath,
const AtNode* iNode)
{
SdfPath path(getGoodUSDName(ioAi->AiNodeGetName(iNode)));
path = iPath.AppendChild(path.GetNameToken());
UsdShadeShader shader = UsdShadeShader::Define(ioStage, path);
UsdPrim prim = shader.GetPrim();
const AtNodeEntry* entry = ioAi->AiNodeGetNodeEntry(iNode);
AtParamIterator* paramIterator = ioAi->AiNodeEntryGetParamIterator(entry);
// Create the type and the target.
// TODO: it should be a part of UsdShadeShader object but I didn't find it.
static const TfToken infoType("info:type");
UsdAttribute infoTypeAttrib = prim.CreateAttribute(
infoType, SdfValueTypeNames->Token, false, SdfVariabilityVarying);
infoTypeAttrib.Set(TfToken(ioAi->AiNodeEntryGetName(entry)));
static const TfToken infoTarget("info:target");
static const TfToken arnold("arnold");
UsdAttribute infoTargetAttrib = prim.CreateAttribute(
infoTarget, SdfValueTypeNames->Token, false, SdfVariabilityVarying);
infoTargetAttrib.Set(arnold);
// Iterate parameters.
while (!ioAi->AiParamIteratorFinished(paramIterator))
{
const AtParamEntry* paramEntry =
ioAi->AiParamIteratorGetNext(paramIterator);
AtArray* paramArray = nullptr;
AtString paramName = ioAi->AiParamGetName(paramEntry);
const TfToken usdParamName(paramName.c_str());
// Get the type
uint8_t paramType = ioAi->AiParamGetType(paramEntry);
SdfValueTypeName usdParamType;
if (paramType == AI_TYPE_ARRAY)
{
paramArray = ioAi->AiNodeGetArray(iNode, paramName);
uint8_t arrayType = ioAi->AiArrayGetType(paramArray);
usdParamType = aiToUsdParamType(arrayType, true);
}
else
{
usdParamType = aiToUsdParamType(paramType);
}
if (!usdParamType)
{
continue;
}
UsdAttribute attrib = prim.CreateAttribute(
usdParamName, usdParamType, false, SdfVariabilityVarying);
if (ioAi->AiNodeIsLinked(iNode, paramName.c_str()))
{
AtNode* linkedNode =
ioAi->AiNodeGetLink(iNode, paramName.c_str(), nullptr);
// TODO: Check if already created.
UsdShadeShader linkedShader =
createUSDShader(ioStage, ioAi, iPath, linkedNode);
UsdShadeConnectableAPI::ConnectToSource(
attrib, linkedShader.GetPrim().GetPath().AppendProperty(sOut));
}
else
{
// TODO: It could be a great template
if (usdParamType == SdfValueTypeNames->UChar)
{
int value = ioAi->AiNodeGetInt(iNode, paramName);
attrib.Set(VtValue(value));
}
else if (usdParamType == SdfValueTypeNames->Int)
{
int value = ioAi->AiNodeGetInt(iNode, paramName);
attrib.Set(VtValue(value));
}
else if (usdParamType == SdfValueTypeNames->UInt)
{
unsigned int value = ioAi->AiNodeGetUInt(iNode, paramName);
attrib.Set(VtValue(value));
}
else if (usdParamType == SdfValueTypeNames->Bool)
{
bool value = ioAi->AiNodeGetBool(iNode, paramName);
attrib.Set(VtValue(value));
}
else if (usdParamType == SdfValueTypeNames->Float)
{
float value = ioAi->AiNodeGetFlt(iNode, paramName);
attrib.Set(VtValue(value));
}
else if (usdParamType == SdfValueTypeNames->Color3f)
{
AtRGB value = ioAi->AiNodeGetRGB(iNode, paramName);
attrib.Set(VtValue(GfVec3f(value.r, value.g, value.b)));
}
else if (usdParamType == SdfValueTypeNames->Color4f)
{
AtRGBA value = ioAi->AiNodeGetRGBA(iNode, paramName);
attrib.Set(
VtValue(GfVec4f(value.r, value.g, value.b, value.a)));
}
else if (usdParamType == SdfValueTypeNames->Vector3f)
{
AtVector value = ioAi->AiNodeGetVec(iNode, paramName);
attrib.Set(VtValue(GfVec3f(value.x, value.y, value.z)));
}
else if (usdParamType == SdfValueTypeNames->Float2)
{
AtVector2 value = ioAi->AiNodeGetVec2(iNode, paramName);
attrib.Set(VtValue(GfVec2f(value.x, value.y)));
}
else if (usdParamType == SdfValueTypeNames->String)
{
AtString value = ioAi->AiNodeGetStr(iNode, paramName);
attrib.Set(VtValue(value.c_str()));
}
else if (usdParamType == SdfValueTypeNames->Matrix4d)
{
AtMatrix matrix = ioAi->AiNodeGetMatrix(iNode, paramName);
GfMatrix4f gfMatrix(matrix.data);
attrib.Set(VtValue(gfMatrix));
}
else if (usdParamType == SdfValueTypeNames->Color3fArray)
{
uint32_t nElements = ioAi->AiArrayGetNumElements(paramArray);
VtVec3fArray array(nElements);
for (uint32_t i = 0; i < nElements; i++)
{
AtRGB value = ioAi->AiArrayGetRGBFunc(
paramArray, i, __AI_FILE__, __AI_LINE__);
array[i] = GfVec3f(value.r, value.g, value.b);
}
attrib.Set(array);
}
else if (usdParamType == SdfValueTypeNames->FloatArray)
{
uint32_t nElements = ioAi->AiArrayGetNumElements(paramArray);
VtFloatArray array(nElements);
for (uint32_t i = 0; i < nElements; i++)
{
float value = ioAi->AiArrayGetFltFunc(
paramArray, i, __AI_FILE__, __AI_LINE__);
array[i] = value;
}
attrib.Set(array);
}
else if (usdParamType == SdfValueTypeNames->IntArray)
{
uint32_t nElements = ioAi->AiArrayGetNumElements(paramArray);
VtIntArray array(nElements);
for (uint32_t i = 0; i < nElements; i++)
{
int value = ioAi->AiArrayGetIntFunc(
paramArray, i, __AI_FILE__, __AI_LINE__);
array[i] = value;
}
attrib.Set(array);
}
else if (usdParamType == SdfValueTypeNames->UCharArray)
{
uint32_t nElements = ioAi->AiArrayGetNumElements(paramArray);
VtUCharArray array(nElements);
for (uint32_t i = 0; i < nElements; i++)
{
uint8_t value = ioAi->AiArrayGetByteFunc(
paramArray, i, __AI_FILE__, __AI_LINE__);
array[i] = value;
}
attrib.Set(array);
}
else if (usdParamType == SdfValueTypeNames->StringArray)
{
uint32_t nElements = ioAi->AiArrayGetNumElements(paramArray);
VtStringArray array(nElements);
for (uint32_t i = 0; i < nElements; i++)
{
AtString value = ioAi->AiArrayGetStrFunc(
paramArray, i, __AI_FILE__, __AI_LINE__);
array[i] = value;
}
attrib.Set(array);
AtString value = ioAi->AiNodeGetStr(iNode, paramName);
attrib.Set(VtValue(value.c_str()));
}
}
}
ioAi->AiParamIteratorDestroy(paramIterator);
return shader;
}
UsdShadeMaterial createUSDMaterial(
UsdStageRefPtr ioStage,
ArnoldAPIPtr ioAi,
const SdfPath& iPath,
const AtNode* iNode)
{
UsdShadeMaterial mat = UsdShadeMaterial::Define(ioStage, iPath);
UsdShadeShader rootShader = createUSDShader(ioStage, ioAi, iPath, iNode);
// Connect rootShader to mat.
// TODO: We need to detect if it's a surface or displacement
static const TfToken arnoldSurface("arnold:surface");
UsdAttribute attrib = mat.GetPrim().CreateAttribute(
arnoldSurface, SdfValueTypeNames->Float3, false, SdfVariabilityVarying);
UsdShadeConnectableAPI::ConnectToSource(
attrib, rootShader.GetPrim().GetPath().AppendProperty(sOut));
return mat;
}
WalterVolume createUSDVolume(
UsdStageRefPtr ioStage,
ArnoldAPIPtr ioAi,
const SdfPath& iPath,
const AtNode* iNode)
{
WalterVolume volume = WalterVolume::Define(ioStage, iPath);
const AtNodeEntry* entry = ioAi->AiNodeGetNodeEntry(iNode);
// It's so complicated with iterating parameters because we can't create
// AtString without linking to libai.so, and it means we can't query
// parameters by name. The only way is iterating.
AtParamIterator* paramIterator = ioAi->AiNodeEntryGetParamIterator(entry);
// Iterate parameters.
while (!ioAi->AiParamIteratorFinished(paramIterator))
{
const AtParamEntry* paramEntry =
ioAi->AiParamIteratorGetNext(paramIterator);
AtString paramName = ioAi->AiParamGetName(paramEntry);
std::string name(paramName);
if (name == "matrix")
{
AtMatrix matrix = ioAi->AiNodeGetMatrix(iNode, paramName);
// Convert it to double
GfMatrix4d gfMatrix(GfMatrix4f(matrix.data));
volume.AddXformOp(UsdGeomXformOp::TypeTransform).Set(gfMatrix);
}
else if (name == "volume_padding")
{
float value = ioAi->AiNodeGetFlt(iNode, paramName);
volume.CreateVolumePaddingAttr().Set(value);
}
else if (name == "step_size")
{
float value = ioAi->AiNodeGetFlt(iNode, paramName);
volume.CreateStepSizeAttr().Set(value);
}
else if (name == "filename")
{
std::string value(ioAi->AiNodeGetStr(iNode, paramName));
volume.CreateFilenameAttr().Set(value);
}
else if (name == "filedata")
{
AtArray* paramArray = ioAi->AiNodeGetArray(iNode, paramName);
uint32_t nElements = ioAi->AiArrayGetNumElements(paramArray);
VtUCharArray array(nElements);
for (uint32_t i = 0; i < nElements; i++)
{
uint8_t value = ioAi->AiArrayGetByteFunc(
paramArray, i, __AI_FILE__, __AI_LINE__);
array[i] = value;
}
volume.CreateFiledataAttr().Set(array);
}
else if (name == "step_scale")
{
float value = ioAi->AiNodeGetFlt(iNode, paramName);
volume.CreateStepScaleAttr().Set(value);
}
else if (name == "compress")
{
bool value = ioAi->AiNodeGetBool(iNode, paramName);
volume.CreateCompressAttr().Set(value);
}
else if (name == "grids")
{
if(ioAi->AiParamGetType(paramEntry) == AI_TYPE_ARRAY)
{
AtArray* paramArray = ioAi->AiNodeGetArray(iNode, paramName);
uint32_t nElements = ioAi->AiArrayGetNumElements(paramArray);
VtStringArray array(nElements);
for (uint32_t i = 0; i < nElements; i++)
{
AtString value = ioAi->AiArrayGetStrFunc(
paramArray, i, __AI_FILE__, __AI_LINE__);
array[i] = value;
}
volume.CreateGridsAttr().Set(array);
}
else
{
VtStringArray array(1);
std::string value(ioAi->AiNodeGetStr(iNode, paramName));
array[0] = value;
volume.CreateGridsAttr().Set(array);
}
}
else if (name == "velocity_scale")
{
float value = ioAi->AiNodeGetFlt(iNode, paramName);
volume.CreateVelocityScaleAttr().Set(value);
}
else if (name == "velocity_fps")
{
float value = ioAi->AiNodeGetFlt(iNode, paramName);
volume.CreateVelocityFpsAttr().Set(value);
}
else if (name == "velocity_outlier_threshold")
{
float value = ioAi->AiNodeGetFlt(iNode, paramName);
volume.CreateVelocityOutlierThresholdAttr().Set(value);
}
else if (name == "shader")
{
// Bind material to this prim.
AtNode* shader = (AtNode*)ioAi->AiNodeGetPtr(iNode, paramName);
if (!shader)
{
continue;
}
// Generate the path to the shader.
SdfPath shaderPath(getGoodUSDName(ioAi->AiNodeGetName(shader)));
// Connect the path and the prim.
UsdRelationship shaderRel = volume.GetPrim().CreateRelationship(
UsdShadeTokens->materialBinding, false);
SdfPathVector targets(1, shaderPath);
shaderRel.SetTargets(targets);
}
}
ioAi->AiParamIteratorDestroy(paramIterator);
return volume;
}
bool fillUSDStage(
UsdStageRefPtr ioStage,
ArnoldAPIPtr ioAi,
const std::string& iFile)
{
// Since it's possible that we didn't create Arnold context, we need to get
// the current nodes.
std::set<AtNode*> nodesBeforeLoad;
AtNodeIterator* nodeIterator = ioAi->AiUniverseGetNodeIterator(AI_NODE_ALL);
while (!ioAi->AiNodeIteratorFinished(nodeIterator))
{
AtNode* node = ioAi->AiNodeIteratorGetNext(nodeIterator);
nodesBeforeLoad.insert(node);
}
ioAi->AiNodeIteratorDestroy(nodeIterator);
if (ioAi->AiASSLoad(iFile.c_str(), AI_NODE_SHAPE | AI_NODE_SHADER) != 0)
{
return false;
}
// There is no API to get nodes that was loaded with AiASSLoad. To get them
// we need to get all the nodes and find the difference.
std::set<AtNode*> nodesAfterLoad;
nodeIterator = ioAi->AiUniverseGetNodeIterator(AI_NODE_ALL);
while (!ioAi->AiNodeIteratorFinished(nodeIterator))
{
AtNode* node = ioAi->AiNodeIteratorGetNext(nodeIterator);
nodesAfterLoad.insert(node);
}
ioAi->AiNodeIteratorDestroy(nodeIterator);
std::set<AtNode*> newNodes;
std::set_difference(
nodesAfterLoad.begin(),
nodesAfterLoad.end(),
nodesBeforeLoad.begin(),
nodesBeforeLoad.end(),
std::inserter(newNodes, newNodes.begin()));
// Arnold doesn't have inheritance and all the nodes are flat there. In USD
// it's a good practice to group the shading nodes into materials. To do it
// we need to know what shaders are "roots". The following code tries to
// recognize it. Grouping nodes is a classic linked list problem, we
// simplified it a little bit. We save the connected nodes on the first pass
// and output the nodes with no connection on the second pass.
std::set<AtNode*> nodesWithOutput;
for (const AtNode* node : newNodes)
{
const AtNodeEntry* entry = ioAi->AiNodeGetNodeEntry(node);
int type = ioAi->AiNodeEntryGetType(entry);
if (type == AI_NODE_SHADER)
{
AtParamIterator* paramIterator =
ioAi->AiNodeEntryGetParamIterator(entry);
while (!ioAi->AiParamIteratorFinished(paramIterator))
{
const AtParamEntry* paramEntry =
ioAi->AiParamIteratorGetNext(paramIterator);
AtString paramName = ioAi->AiParamGetName(paramEntry);
if (ioAi->AiNodeIsLinked(node, paramName.c_str()))
{
nodesWithOutput.insert(
ioAi->AiNodeGetLink(node, paramName.c_str(), nullptr));
break;
}
}
ioAi->AiParamIteratorDestroy(paramIterator);
}
}
// Output the nodes
for (AtNode* node : newNodes)
{
const AtNodeEntry* entry = ioAi->AiNodeGetNodeEntry(node);
// Type is "shader", "shape" etc.
int type = ioAi->AiNodeEntryGetType(entry);
if (type == AI_NODE_SHAPE)
{
// Nodetype is "volume", "options" etc.
const std::string nodeType(ioAi->AiNodeEntryGetName(entry));
if (nodeType != "volume")
{
continue;
}
SdfPath path(getGoodUSDName(ioAi->AiNodeGetName(node)));
createUSDVolume(ioStage, ioAi, path, node);
}
else if (type == AI_NODE_SHADER)
{
if (nodesWithOutput.find(node) != nodesWithOutput.end())
{
continue;
}
SdfPath path(getGoodUSDName(ioAi->AiNodeGetName(node)));
createUSDMaterial(ioStage, ioAi, path, node);
}
}
// Delete nodes that we just loaded. We don't need them anymore in the
// Arnold context.
for (AtNode* node : newNodes)
{
// AiNodeDestroy crashes. AiNodeReset removes all the parameters and
// Arnold will ignore such node which is not bad in our case.
ioAi->AiNodeReset(node);
}
return true;
}
}
SdfLayerRefPtr ArnoldUSDTranslator::arnoldToUsdLayer(const std::string& iFile)
{
// Create the layer to populate.
SdfLayerRefPtr layer = SdfLayer::CreateAnonymous(".usda");
ArnoldAPIPtr ai = ArnoldAPI::create();
if (!ai)
{
return layer;
}
// Create a UsdStage with that root layer.
UsdStageRefPtr stage = UsdStage::Open(layer);
stage->SetEditTarget(layer);
bool sessionCreated = false;
if (!ai->AiUniverseIsActive())
{
ai->AiBegin();
ArnoldUSDTranslatorImpl::loadArnoldPlugins(ai);
sessionCreated = true;
}
// Generate the stage.
ArnoldUSDTranslatorImpl::fillUSDStage(stage, ai, iFile);
if (sessionCreated)
{
ai->AiEnd();
}
return layer;
}
PXR_NAMESPACE_CLOSE_SCOPE
<|start_filename|>walter/usd/tests/test_setVariantUSD.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/variantSets.h>
#include <pxr/usd/usd/stage.h>
#include "walterUSDCommonUtils.h"
#include <string>
#include <vector>
#include <gtest/gtest.h>
PXR_NAMESPACE_USING_DIRECTIVE
TEST(setVariantUSD, testSetVariantOnChildPrimFromParent)
{
const char* primPath = "/Foo/Bar";
const char* variantSetName = "colors";
const char* variantName = "red";
UsdStageRefPtr stage = UsdStage::CreateInMemory();
UsdPrim prim = stage->DefinePrim(SdfPath(primPath));
UsdVariantSet colorsVset = prim.GetVariantSets().AddVariantSet(variantSetName);
colorsVset.AddVariant(variantName);
colorsVset.AddVariant("green");
colorsVset.SetVariantSelection("green");
const char* parentPrimPath = "/Foo";
std::string variants = parentPrimPath + std::string("{") + variantSetName +
std::string("=") + variantName + std::string("}");
WalterUSDCommonUtils::setVariantUSD(stage, variants.c_str());
std::vector<std::string> result =
WalterUSDCommonUtils::getVariantsUSD(stage, "", true);
EXPECT_EQ(result.size(), 1);
EXPECT_EQ(colorsVset.GetVariantSelection(), std::string(variantName));
}
<|start_filename|>walter/katana/WalterIn/walterUSDOpCaboose.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERUSDOPCABOOSE_H_
#define __WALTERUSDOPCABOOSE_H_
#include <pxr/usd/usd/prim.h>
#include "walterUSDOpIndex.h"
PXR_NAMESPACE_USING_DIRECTIVE
namespace OpUtils
{
class PrivateData;
}
/** @brief Everything related to the conversion from USD to Katana is here. At
* the moment there is no reason to have an object, so we use the namespace. The
* idea is not include Katana stuff in this header because in the future we
* might be using this file for the Arnold prcedural.
* P.S. Katana has the cook, we created the caboose for the cook.
* P.P.S. Caboose:
* 1. a railroad car with accommodations for the train crew, typically attached
* to the end of the train.
* 2. a kitchen on a ship's deck. */
namespace OpCaboose
{
/** @brief Represents an object that keeps a single attribute. And it can apply
* this attribute to the client's object very fast. We keep the attribute as a
* pointer to a function with pre-bound parameters. Since everything is already
* bound, there are no precomputations, and the applying of the attribute should
* be very fast. We don't use Katana Group builder directly because our code
* should be client-agnostic, in the future, we will use the same code for
* Arnold procedural. A client is a USD consumer (like Katana or Arnold). */
class ClientAttribute
{
public:
/** @brief We apply attributes into this object. For Katana it's
* GroupBuilder*, for Arnold, it's AtNode* */
typedef void* Carrier;
/** @brief We keep the attribute as a pointer to a function fith pre-bound
* parameters. */
typedef std::function<void(Carrier)> AttributeSetFn;
typedef std::shared_ptr<AttributeSetFn> AttributeSetFnPtr;
ClientAttribute(AttributeSetFnPtr iFunction) : mFunction(iFunction) {}
/**
* @brief Check if it's valid.
*
* @return True if valid.
*/
bool valid() const { return mFunction != nullptr; }
/**
* @brief Applies the parameter to the clien's object.
*
* @param iCarrier
*/
void evaluate(Carrier iCarrier) const;
private:
AttributeSetFnPtr mFunction;
};
typedef std::shared_ptr<ClientAttribute> ClientAttributePtr;
/**
* @brief Check if the prim is supported.
*
* @param prim The given prim.
*
* @return True if it's a supported privitive
*/
bool isSupported(const UsdPrim& iPrim);
/**
* @brief Check if it's necessary to output children.
*
* @param prim The given prim.
*
* @return False if it's necessary to output children
*/
bool skipChildren(const UsdPrim& iPrim);
/**
* @brief Output prim. We only support polymeshes
*
* @param iPrim The USD prim that is needed to output to the client.
* @param iPrivateData The object that is generated by us for each node we
* are going to produce.
* @param ioClientData The data coming from the client (like Katana or Arnold in
* the future) that is passed to the caboose. For Katana it's
* GeolibCookInterface.
*/
void cook(
const UsdPrim& iPrim,
const OpUtils::PrivateData* iPrivateData,
void* ioClientData);
/**
* @brief Create Geolib children.
*
* @param iPrim The children of this USD prim will be created.
* @param iPrivateData The object that is generated by us for each node we
* are going to produce.
* @param ioClientData The data coming from the client (like Katana or Arnold in
* the future) that is passed to the caboose. For Katana it's
* GeolibCookInterface.
*/
void cookChild(
const UsdPrim& iPrim,
const OpUtils::PrivateData* iPrivateData,
void* ioClientData,
std::string iCustomName = "");
/**
* @brief Return an object that it's possible to use to output client parameter.
* Basically, it converts UsdAttribute to Katana Attribute.
*
* @param iAttr UsdAttribute
* @param iTime Time
*
* @retur Shared pointer to the client attribute.
*/
ClientAttributePtr createClientAttribute(
const UsdAttribute& iAttr,
UsdTimeCode iTime = UsdTimeCode::Default());
}
#endif
<|start_filename|>walter/katana/WalterIn/AbcCook.h<|end_filename|>
#ifndef FnGeolibOp_WalterIn_AbcCook_H
#define FnGeolibOp_WalterIn_AbcCook_H
#include <Alembic/Abc/All.h>
#include <Alembic/AbcGeom/All.h>
#include <Alembic/AbcMaterial/All.h>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <unordered_map>
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnGroupBuilder.h>
namespace WalterIn
{
bool isBoundBox(const Alembic::AbcCoreAbstract::PropertyHeader & iPropHeader);
Alembic::Util::PlainOldDataType FnAttrTypeToPODType(FnKatAttributeType iType);
int64_t getTupleSize(const Alembic::AbcCoreAbstract::PropertyHeader & iHeader);
class AbcCook;
typedef boost::shared_ptr< AbcCook > AbcCookPtr;
typedef std::unordered_map<std::string, std::string> NameMap;
struct IndexedGeomParamPair
{
std::string name;
Alembic::Abc::IArrayProperty prop;
Alembic::Abc::IUInt32ArrayProperty indexed;
Alembic::Util::PlainOldDataType asPod;
};
struct ArrayProp
{
std::string name;
Alembic::Abc::IArrayProperty prop;
Alembic::Util::PlainOldDataType asPod;
};
struct ScalarProp
{
std::string name;
Alembic::Abc::IScalarProperty prop;
};
class AbcCook
{
public:
AbcCook() { animatedSchema = false; }
Foundry::Katana::GroupAttribute staticGroup;
std::vector< ArrayProp > arrayProps;
std::vector< ScalarProp > scalarProps;
std::vector< IndexedGeomParamPair > forcedExpandProps;
Alembic::AbcGeom::IVisibilityProperty visProp;
Alembic::Abc::IObjectPtr objPtr;
boost::mutex mutex;
bool animatedSchema;
};
typedef std::vector<double> SampleTimes;
struct OpArgs
{
double currentTime;
double shutterOpen;
double shutterClose;
double fps;
int numSamples;
enum ExtraFrameRangeBehavior
{
kError = 0,
kHold = 1,
kSkip = 2
};
ExtraFrameRangeBehavior behavior;
bool useOnlyShutterOpenCloseTimes;
OpArgs()
: currentTime(1.0)
, shutterOpen(0.0)
, shutterClose(0.0)
, fps(24.0)
, numSamples(1)
, behavior(kHold)
, useOnlyShutterOpenCloseTimes(false)
{}
double getAbcFrameTime() const { return currentTime / fps; }
void getRelevantSampleTimes(
Alembic::AbcCoreAbstract::TimeSamplingPtr iTimeSampling,
size_t iPropertyNumSamples,
SampleTimes & oTimes) const
{
double frameTime = currentTime / fps;
if (numSamples < 2)
{
oTimes.push_back(frameTime);
return;
}
if (iPropertyNumSamples < 2)
{
oTimes.push_back(0.0);
return;
}
//TODO, what's a reasonable epsilon?
static const double epsilon = 1.0/10000.0;
double shutterOpenTime =
(currentTime + shutterOpen) / fps;
double shutterCloseTime =
(currentTime + shutterClose) / fps;
//
// We don't want to grab samples from far outside the shutter window just
// because the samples immediately near the shutter open and shutter
// close times are a small epsilon outside the shutter we specify. The
// tolerance is already used for the upper bound below, but we'll use it
// to grab a more expected lower and upper bound.
//
std::pair<Alembic::Abc::index_t, Alembic::Abc::chrono_t> shutterOpenFloor =
iTimeSampling->getNearIndex(shutterOpenTime, iPropertyNumSamples);
if (fabs(shutterOpenFloor.second - shutterOpenTime) > epsilon)
{
shutterOpenFloor =
iTimeSampling->getFloorIndex(shutterOpenTime, iPropertyNumSamples);
}
std::pair<Alembic::Abc::index_t, Alembic::Abc::chrono_t> shutterCloseCeil =
iTimeSampling->getNearIndex(shutterCloseTime, iPropertyNumSamples);
if (fabs(shutterCloseCeil.second - shutterCloseTime) > epsilon)
{
shutterCloseCeil =
iTimeSampling->getCeilIndex(shutterCloseTime, iPropertyNumSamples);
}
// Use shutter open/close times only if the number of samples is 2 and
// we explicitly requested them to be used
if (numSamples == 2 && useOnlyShutterOpenCloseTimes)
{
oTimes.push_back(shutterOpenFloor.second);
oTimes.push_back(shutterCloseCeil.second);
return;
}
for (Alembic::Abc::index_t i = shutterOpenFloor.first;
i < shutterCloseCeil.first; ++i)
{
oTimes.push_back(iTimeSampling->getSampleTime(i));
}
//no samples above? put frame time in there and get out
if (oTimes.empty())
{
oTimes.push_back(frameTime);
return;
}
double lastSample = *(oTimes.rbegin());
//determine whether we need the extra sample at the end
if ((fabs(lastSample-shutterCloseTime) > epsilon)
&& lastSample<shutterCloseTime)
{
oTimes.push_back(shutterCloseCeil.second);
}
}
float getRelativeSampleTime(Alembic::Abc::chrono_t iTime) const
{
double frameTime = currentTime / fps;
double result = (iTime - frameTime) * fps;
const double tolerance = 0.000165;
if (Imath::equalWithAbsError(result, 0.0, tolerance))
{
result = 0;
}
else if (Imath::equalWithAbsError(result, shutterOpen, tolerance))
{
result = shutterOpen;
}
else if (Imath::equalWithAbsError(result, shutterClose, tolerance))
{
result = shutterClose;
}
return (float) result;
}
};
/*
* Note: This function construct the GroupBuilder with every
* parameters, users and arnold parameters. That's the one set
* under arnoldStatements in Katana.
*/
void processUserProperties(AbcCookPtr ioCook,
Alembic::Abc::ICompoundProperty & iParent,
Foundry::Katana::GroupBuilder & oStaticGb,
const std::string & iAttrPath,
const NameMap* iRenameMap=nullptr,
Alembic::Abc::v10::IUInt64ArrayProperty * iIdsProperty = NULL);
void setArnoldVisibility(
AbcCookPtr ioCook,
Alembic::Abc::ICompoundProperty & iParent,
const Alembic::AbcCoreAbstract::PropertyHeader & iPropHeader,
const std::string & iPropName,
FnAttribute::GroupBuilder & oStaticGb);
/*
* Note: This function construct the GroupBuilder with just user parameters.
* That's the one set under geometry.arbitrary in Katana.
*/
void processArnoldUserProperties(
AbcCookPtr ioCook,
Alembic::Abc::ICompoundProperty & iParent,
Foundry::Katana::GroupBuilder & oStaticGb,
const std::string & iAttrPath);
void initAbcCook(AbcCookPtr ioCookPtr,
Foundry::Katana::GroupBuilder & oStaticGb);
void evalObject(AbcCookPtr ioCookPtr, const OpArgs & iArgs,
Foundry::Katana::GroupBuilder & oGb,
Alembic::Abc::v10::IUInt64ArrayProperty * iIdsProperty = NULL);
void cookCamera(AbcCookPtr ioCook, Foundry::Katana::GroupBuilder & oStaticGb);
void evalCamera(Alembic::AbcGeom::ICameraSchema & iSchema,
const OpArgs & iArgs,
Foundry::Katana::GroupBuilder & oGb);
void cookCurves(AbcCookPtr ioCook, Foundry::Katana::GroupBuilder & oStaticGb);
void evalCurves(Alembic::AbcGeom::ICurvesSchema & iSchema,
const OpArgs & iArgs,
Foundry::Katana::GroupBuilder & oGb);
void cookFaceset(AbcCookPtr ioCook, Foundry::Katana::GroupBuilder & oStaticGb);
void cookNuPatch(AbcCookPtr ioCook, Foundry::Katana::GroupBuilder & oStaticGb);
void evalNuPatch(Alembic::AbcGeom::INuPatchSchema & iSchema,
const OpArgs & iArgs,
bool iIgnoreConstant,
Foundry::Katana::GroupBuilder & oGb);
void cookPoints(AbcCookPtr ioCook, Foundry::Katana::GroupBuilder & oStaticGb);
void cookPolyMesh(AbcCookPtr ioCook, Foundry::Katana::GroupBuilder & oStaticGb);
void cookSubd(AbcCookPtr ioCook, Foundry::Katana::GroupBuilder & oStaticGb);
void cookXform(AbcCookPtr ioCook, Foundry::Katana::GroupBuilder & oStaticGb);
void evalXform(Alembic::AbcGeom::IXformSchema & iSchema,
const OpArgs & iArgs,
Foundry::Katana::GroupBuilder & oGb);
void cookMaterial(AbcCookPtr ioCook, Foundry::Katana::GroupBuilder & oStaticGb);
void cookLight(AbcCookPtr ioCook, Foundry::Katana::GroupBuilder & oStaticGb);
}
#endif
<|start_filename|>walter/katana/WalterIn/PolyMeshCook.cpp<|end_filename|>
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ScalarPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
void cookPolyMesh(AbcCookPtr ioCook, FnAttribute::GroupBuilder & oStaticGb)
{
Alembic::AbcGeom::IPolyMeshPtr meshPtr(
new Alembic::AbcGeom::IPolyMesh(*(ioCook->objPtr),
Alembic::AbcGeom::kWrapExisting));
Alembic::AbcGeom::IPolyMeshSchema schema = meshPtr->getSchema();
oStaticGb.set("type", FnAttribute::StringAttribute("polymesh"));
Alembic::Abc::ICompoundProperty userProp = schema.getUserProperties();
Alembic::Abc::ICompoundProperty arbGeom = schema.getArbGeomParams();
std::string abcUser = "abcUser.";
processUserProperties(ioCook, userProp, oStaticGb, abcUser);
processArbGeomParams(ioCook, arbGeom, oStaticGb);
Alembic::AbcGeom::IV2fGeomParam uvsProp = schema.getUVsParam();
if (uvsProp.valid())
{
processArbitraryGeomParam(ioCook, schema, uvsProp.getHeader(),
oStaticGb, "geometry.arbitrary.st");
}
Alembic::AbcGeom::IN3fGeomParam normProp = schema.getNormalsParam();
if (normProp.valid())
{
Alembic::AbcGeom::GeometryScope scope = normProp.getScope();
if (scope == Alembic::AbcGeom::kVertexScope ||
scope == Alembic::AbcGeom::kVaryingScope)
{
processArbitraryGeomParam(ioCook, schema, normProp.getHeader(),
oStaticGb, "geometry.point.N");
}
else if (scope == Alembic::AbcGeom::kFacevaryingScope)
{
processArbitraryGeomParam(ioCook, schema, normProp.getHeader(),
oStaticGb, "geometry.vertex.N");
}
}
Alembic::Abc::IInt32ArrayProperty faceProp =
schema.getFaceCountsProperty();
if (faceProp.valid())
{
arrayPropertyToAttr(schema, faceProp.getHeader(),
"geometry.poly.startIndex", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
Alembic::Abc::IInt32ArrayProperty indexProp =
schema.getFaceIndicesProperty();
if (indexProp.valid())
{
arrayPropertyToAttr(schema, indexProp.getHeader(),
"geometry.poly.vertexList", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
Alembic::Abc::IP3fArrayProperty pointsProp =
schema.getPositionsProperty();
if (pointsProp.valid())
{
arrayPropertyToAttr(schema, pointsProp.getHeader(),
"geometry.point.P", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
Alembic::Abc::IV3fArrayProperty velocProp =
schema.getVelocitiesProperty();
if (velocProp.valid())
{
arrayPropertyToAttr(schema, velocProp.getHeader(),
"geometry.point.v", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
Alembic::Abc::IBox3dProperty boundsProp =
schema.getSelfBoundsProperty();
if (boundsProp.valid())
{
scalarPropertyToAttr(schema, boundsProp.getHeader(), "bound",
ioCook, oStaticGb);
}
}
} //end of namespace WalterIn
<|start_filename|>walter/usd/tests/test_resources_GetGeneratedSchema.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
/*
This test check that we can load usda schemas from the Walter resources.
To do that, we are patching the Usd file 'schemaRegistry.cpp' by overriding
_GetGeneratedSchema().
*/
#include <pxr/usd/usd/schemaRegistry.h>
#include <gtest/gtest.h>
PXR_NAMESPACE_USING_DIRECTIVE
TEST(test_resources_GetGeneratedSchema, test1)
{
SdfPrimSpecHandle primSpec = UsdSchemaRegistry::GetPrimDefinition(TfToken("ModelAPI"));
EXPECT_TRUE(primSpec);
}
<|start_filename|>walter/alembic/OWalterExpressionsSchema.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __OWALTEREXPRESSIONSSCHEMA_H_
#define __OWALTEREXPRESSIONSSCHEMA_H_
#include "SchemaInfoDeclarations.h"
#define EXPRESSIONS_PROPNAME ".expressions"
#define EXPRESSIONS_GROUP ".group"
#define EXPRESSIONS_GROUPNAME ".name"
// Schema for writing shader assignments as either an object or a compound
// property.
class ALEMBIC_EXPORT OWalterExpressionsSchema :
public Alembic::Abc::OSchema<WalterExpressionsSchemaInfo>
{
public:
typedef OWalterExpressionsSchema this_type;
OWalterExpressionsSchema(
Alembic::AbcCoreAbstract::CompoundPropertyWriterPtr iParent,
const std::string &iName,
const Alembic::Abc::Argument &iArg0 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg1 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg2 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg3 = Alembic::Abc::Argument() );
OWalterExpressionsSchema(
Alembic::Abc::OCompoundProperty iParent,
const std::string &iName,
const Alembic::Abc::Argument &iArg0 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg1 = Alembic::Abc::Argument(),
const Alembic::Abc::Argument &iArg2 = Alembic::Abc::Argument() );
// Put everything to Alembic when the object is destroyed.
~OWalterExpressionsSchema();
// Copy constructor.
OWalterExpressionsSchema( const OWalterExpressionsSchema& iCopy ) :
Alembic::Abc::OSchema<WalterExpressionsSchemaInfo>()
{
*this = iCopy;
}
// Declare shader for a given expression and shaderType. It can be called
// many times per expression/layer/shader type. The real information will go
// to Alembic when the object is destroyed.
void setExpressionShader(
const std::string & iExpression,
const std::string & iLayer,
const std::string & iShaderType,
const std::string & iShaderName);
// Declare a group for a given expression. It can be called many times. The
// real information will go to Alembic when the object is destroyed.
void setExpressionGroup(
const std::string & iExpression,
const std::string & iGroup);
private:
// Layer name, layer target (shader, displacement etc.)
typedef std::pair<std::string, std::string> LayerKey;
// Layer, shader
typedef std::map<LayerKey, std::string> LayerMap;
struct ExpressionData
{
bool grouped;
std::string groupname;
LayerMap layerMap;
// Default constructor
ExpressionData() : grouped(false) {}
};
// Expression, data
typedef std::map<std::string, ExpressionData> ExpMap;
ExpMap mExpressions;
};
// Adds a local material schema within any compound.
OWalterExpressionsSchema addExpressions(
Alembic::Abc::OCompoundProperty iProp,
const std::string& iPropName = EXPRESSIONS_PROPNAME );
// Adds a local expression schema to any object.
OWalterExpressionsSchema addExpressions(
Alembic::Abc::OObject iObject,
const std::string& iPropName = EXPRESSIONS_PROPNAME );
#endif
<|start_filename|>walter/maya/walterStandin/walterShaderUtils.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterShaderUtils.h"
#include "schemas/walterHdStream/shader.h"
#include "rdoProfiling.h"
#include <OpenImageIO/imageio.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MObject.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>
#include <boost/filesystem.hpp>
#include <memory>
#include <set>
#include <unordered_map>
#include <vector>
OIIO_NAMESPACE_USING
class ShaderNode;
typedef std::shared_ptr<ShaderNode> ShaderNodePtr;
/** @brief The type to attributes map. It represents the important attributes we
* are interested to scan. */
static const std::unordered_map<std::string, std::vector<std::string>>
sTypeToPlug = {
{"aiStandard", {"color"}},
{"aiStandardSurface", {"baseColor"}},
{"alCombineColor", {"input1", "input2", "input3"}},
{"alCombineFloat", {}},
{"alLayerColor",
{"layer1",
"layer2",
"layer3",
"layer4",
"layer5",
"layer6",
"layer7",
"layer8"}},
{"alLayerFloat", {}},
{"alRemapColor", {"input"}},
{"alRemapFloat", {}},
{"alSurface", {"diffuseColor"}},
{"alSwitchColor",
{"inputA", "inputB", "inputC", "inputD", "inputE", "inputF"}},
{"alSwitchFloat", {}},
{"anisotropic", {"color"}},
{"blinn", {"color"}},
{"lambert", {"color"}},
{"phong", {"color"}},
{"phongE", {"color"}},
{"standard", {"Kd_color"}},
{"surfaceShader", {"color"}}};
/** @brief This class represents a simple shading node that can store
* connections to another shaders and the colors. */
class ShaderNode
{
public:
ShaderNode(
const std::string& name,
const std::string& type,
const std::string& texture = {}) :
mName(name),
mType(type),
mTexture(texture)
{}
/**
* @brief Set the connection to the another shader.
*
* @param name Name of the connection.
* @param shaderNode Connected shader.
*/
void addPlug(const std::string& name, ShaderNodePtr shaderNode)
{
mPlugs[name] = shaderNode;
}
/**
* @brief Set the color.
*
* @param name The name of the color.
* @param color The color to set.
*/
void addColor(const std::string& name, const GfVec3f& color)
{
mColors[name] = color;
}
/**
* @brief Scan the network and return the textures in the plugs using
* sTypeToPlug map.
*
* @param textures Adds found textures there.
*
* @return True of the network has textures.
*/
bool getTextures(std::set<std::string>& textures)
{
if (!mTexture.empty())
{
// We found a texture, no need to scan.
textures.insert(mTexture);
return true;
}
// It will be true if we have found a texture.
bool found = false;
auto it = sTypeToPlug.find(mType);
if (it != sTypeToPlug.end())
{
// It's known type. We need to scan requested plugs only.
for (const std::string requestedPlug : it->second)
{
auto itRequested = mPlugs.find(requestedPlug);
if (itRequested == mPlugs.end())
{
// There is no requested plug.
continue;
}
// Check if the requested plug has a texture.
if (itRequested->second->getTextures(textures))
{
found = true;
// No necessary to continue scanning.
break;
}
}
}
else
{
// Unknown type. We need to scan everything.
for (const auto& plug : mPlugs)
{
if (plug.second->getTextures(textures))
{
// Even if we found a texture, there is no guarantee that
// this texture is important. So we continue scanning.
found = true;
}
}
}
return found;
}
/**
* @brief Scan the network and get the first available color from the
* sTypeToPlug map.
*
* @param oColor Returned color.
*
* @return True if success.
*/
bool getColor(GfVec3f& oColor)
{
// Get the list of attributes depending on the node type.
auto it = sTypeToPlug.find(mType);
if (it != sTypeToPlug.end())
{
// Check if we have the color stored.
for (const std::string requestedPlug : it->second)
{
auto itRequested = mColors.find(requestedPlug);
if (itRequested == mColors.end())
{
continue;
}
// Found the requested color.
oColor = itRequested->second;
return true;
}
}
// We don't have the color stored. Check all the connections.
for (const auto& plug : mPlugs)
{
if (plug.second->getColor(oColor))
{
return true;
}
}
return false;
}
private:
std::string mName;
std::string mType;
std::string mTexture;
std::unordered_map<std::string, ShaderNodePtr> mPlugs;
std::unordered_map<std::string, GfVec3f> mColors;
};
/**
* @brief Returns the color from the plug.
*
* @param plug Plug to scan.
* @param oColor Returned color.
*
* @return True if the plug is a color plug.
*/
bool getColor(const MPlug& plug, GfVec3f& oColor)
{
// Color compounf has three children.
unsigned int numChildren = plug.numChildren();
if (numChildren != 3)
{
return false;
}
bool found[] = {false, false, false};
// Look into the existing plugin code.
// devkit/plug-ins/D3DViewportRenderer.cpp, it extracts the
// "ambientColor" and other attributes.
for (unsigned int i = 0; i < numChildren; i++)
{
// Sometimes the children plugs are not sorted. We need to get the
// component by the name.
MPlug child = plug.child(i);
MString name = child.name();
char component = name.asChar()[name.length() - 1];
int index;
if (component == 'R')
{
index = 0;
}
else if (component == 'G')
{
index = 1;
}
else if (component == 'B')
{
index = 2;
}
else
{
// It's not a color. Stop the loop.
break;
}
// Save the color.
oColor[index] = child.asFloat();
found[index] = true;
}
return found[0] && found[1] && found[2];
}
/**
* @brief Scan Maya shading natwork and generate similar network with ShaderNode
* objects. We need it to have fast access to the network and scan it to get
* the main color and textures.
*
* @param shaderObj Maya shader.
* @param cache Cache with the shaders that was already scanned. We need it to
* avoid querying Maya objects several times.
*
* @return Pinter to the root shader.
*/
ShaderNodePtr getShader(
const MObject& shaderObj,
std::unordered_map<std::string, ShaderNodePtr>& cache)
{
RDOPROFILE("Scan Maya Shader");
MFnDependencyNode shader(shaderObj);
// Shader name.
std::string name = shader.name().asChar();
// Check if we already scanned this shader.
auto it = cache.find(name);
if (it != cache.end())
{
return it->second;
}
std::string type = shader.typeName().asChar();
std::string texture;
if (type == "file" || type == "aiImage")
{
// List of attributes where the texture can be placed.
static const char* attributes[] = {
"computedFileTextureNamePattern", "fileTextureName", "filename"};
for (const char* attr : attributes)
{
// Get the regular texture name from it.
MPlug fileTextureName = shader.findPlug(attr);
if (fileTextureName.isNull())
{
continue;
}
texture = fileTextureName.asString().asChar();
break;
}
}
// Create our simple cache node.
ShaderNodePtr shaderNode =
std::make_shared<ShaderNode>(name, type, texture);
// Save it to the cache to avoid querying Maya objects several times.
cache[name] = shaderNode;
for (int i = 0, n = shader.attributeCount(); i < n; i++)
{
// Iterate all the attributes.
MPlug plug = shader.findPlug(shader.attribute(i));
if (plug.isNull())
{
continue;
}
// Get plug name. No node name, no index, no instanced index, no full
// attribute path, no alias, return long name.
std::string plugName =
plug.partialName(false, false, false, false, false, true).asChar();
// Get the connections of the plug.
MPlugArray connections;
if (!plug.connectedTo(connections, true, false) ||
!connections.length())
{
// Check if it's a color.
GfVec3f color;
if (getColor(plug, color))
{
shaderNode->addColor(plugName, color);
}
continue;
}
// It's a connection. Generate connected shader and save it to our node.
ShaderNodePtr connectedNode = getShader(connections[0].node(), cache);
shaderNode->addPlug(plugName, connectedNode);
}
return shaderNode;
}
/**
* @brief Scan USD shading natwork and generate similar network with ShaderNode
* objects. We need it to have fast access to the network and scan it to get
* the main color and textures.
*
* @param shaderObj UsdShadeShader object that represents the shader.
* @param cache Cache with the shaders that was already scanned. We need it to
* avoid querying Maya objects several times.
*
* @return Pinter to the root shader.
*/
ShaderNodePtr getShader(
const UsdShadeShader& shaderObj,
std::unordered_map<std::string, ShaderNodePtr>& cache)
{
RDOPROFILE("Scan USD Shader");
// We checked it before in processGLSLShaders
assert(shaderObj);
const UsdPrim prim = shaderObj.GetPrim();
// Shader name.
std::string name = prim.GetPath().GetElementString();
// Check if we already scanned this shader.
auto it = cache.find(name);
if (it != cache.end())
{
return it->second;
}
// Get the arnold type of the shader.
UsdAttribute typeAttr = prim.GetAttribute(TfToken("info:type"));
TfToken type;
if (!typeAttr || !typeAttr.Get(&type))
{
type = TfToken("unknown");
}
// Get the texture file name.
std::string texture;
if (type == "image" || type == "MayaFile")
{
// Get the regular texture name from it.
UsdAttribute fileNameAttr = prim.GetAttribute(TfToken("filename"));
if (fileNameAttr)
{
fileNameAttr.Get(&texture);
}
}
// Create our simple cache node.
ShaderNodePtr shaderNode =
std::make_shared<ShaderNode>(name, type.GetString(), texture);
// Save it to the cache to avoid querying Maya objects several times.
cache[name] = shaderNode;
// Iterate the connections.
for (const UsdAttribute& attr : prim.GetAttributes())
{
const SdfValueTypeName attrTypeName = attr.GetTypeName();
if (attrTypeName != SdfValueTypeNames->Color3f &&
attrTypeName != SdfValueTypeNames->Float3)
{
// We need colors only.
continue;
}
const std::string attrName = attr.GetName();
// Check the connection.
UsdShadeShader connectedShader =
walterShaderUtils::getConnectedScheme<UsdShadeShader>(attr);
if (connectedShader)
{
// It's a connection. Generate connected shader and save it to our
// node.
ShaderNodePtr connectedNode = getShader(connectedShader, cache);
shaderNode->addPlug(attrName, connectedNode);
}
else
{
GfVec3f color;
if (attr.Get(&color))
{
shaderNode->addColor(attrName, color);
}
}
}
return shaderNode;
}
template <typename T>
void walterShaderUtils::getTextureAndColor(
const T& shaderObj,
std::string& oTexture,
GfVec3f& oColor)
{
// Shader name to shader cache pointer map. It's a list of shaders that are
// already converted. It's used to avoid double convertion of the same
// shader.
std::unordered_map<std::string, ShaderNodePtr> allShaders;
// Get the pointer to the shader cache node.
ShaderNodePtr shader = getShader(shaderObj, allShaders);
// Get all the textures that connected to the diffuse plug.
std::set<std::string> textures;
shader->getTextures(textures);
// Return the first texture with "dif" in the name.
for (const std::string& i : textures)
{
boost::filesystem::path filename(i);
if (filename.filename().string().find("dif") != std::string::npos)
{
oTexture = i;
return;
}
}
// We are here because there is no texture with "dif" in the name. Just
// return the first texture.
if (!textures.empty())
{
oTexture = *textures.begin();
return;
}
// We are here because thare are no textures at all. Return color.
shader->getColor(oColor);
}
// Explicit instantiations of getTextureAndColor.
template void walterShaderUtils::getTextureAndColor<MObject>(
const MObject& shaderObj,
std::string& oTexture,
GfVec3f& oColor);
template void walterShaderUtils::getTextureAndColor<UsdShadeShader>(
const UsdShadeShader& shaderObj,
std::string& oTexture,
GfVec3f& oColor);
std::string walterShaderUtils::cacheTexture(const std::string& filename)
{
// Convert file
boost::filesystem::path filePath(filename);
if (!boost::filesystem::exists(filePath))
{
return filename;
}
// Get the file modification time. It's much faster than finding SHA and
// it's pretty unique per file.
std::time_t t = boost::filesystem::last_write_time(filePath);
// Generate the new filename. It contains the old name, the file
// modification time and it's always EXR.
const std::string newName =
filePath.stem().native() + "." + std::to_string(t) + ".exr";
// The cache directory.
static const boost::filesystem::path outDir =
boost::filesystem::temp_directory_path() / "walter_texture_cache";
// The full file path of the new file. If it already exists, we can use it.
const boost::filesystem::path newPath = outDir / newName;
const std::string newFullName = newPath.native();
if (boost::filesystem::exists(newPath))
{
return newFullName;
}
// Create temp directory if it doesn't exist.
if (!boost::filesystem::exists(outDir))
{
boost::filesystem::create_directories(outDir);
}
// OpenImageIO. Open image.
ImageInput* in = ImageInput::open(filename);
if (!in)
{
return filename;
}
// Get the mipmap number of the best image.
ImageSpec spec;
int counter = 0;
int miplevel = -1;
while (in->seek_subimage(0, counter, spec))
{
// Ideally we need 512x512.
if (spec.width >= 512 && spec.height >= 512)
{
miplevel = counter;
}
else
{
break;
}
counter++;
}
// If 0, than nothing to cache, we can use the original. If -1, than there
// are no mipmaps.
if (miplevel <= 0)
{
in->close();
return filename;
}
// Create OpenImageIO object to output image.
ImageOutput* out = ImageOutput::create(newFullName);
if (!out)
{
in->close();
return filename;
}
// Write only mipmap we found.
out->open(newFullName, spec);
out->copy_image(in);
// Close files.
out->close();
in->close();
return newFullName;
}
<|start_filename|>walter/katana/WalterIn/CurvesCook.cpp<|end_filename|>
#include "AbcCook.h"
#include "ArrayPropUtils.h"
#include "ScalarPropUtils.h"
#include "ArbitraryGeomParamUtils.h"
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
void evalCurves(Alembic::AbcGeom::ICurvesSchema & iSchema,
const OpArgs & iArgs,
FnAttribute::GroupBuilder & oGb)
{
const Alembic::AbcCoreAbstract::PropertyHeader * header =
iSchema.getPropertyHeader("curveBasisAndType");
if (header != NULL)
{
Alembic::Abc::IScalarProperty basisAndTypeProp(iSchema,
"curveBasisAndType");
Alembic::Util::uint8_t data[4];
Alembic::Abc::ISampleSelector ss(iArgs.getAbcFrameTime());
basisAndTypeProp.get(data, ss);
Alembic::AbcGeom::CurveType curveType =
static_cast<Alembic::AbcGeom::CurveType>( data[0] );
Alembic::AbcGeom::CurvePeriodicity wrap =
static_cast<Alembic::AbcGeom::CurvePeriodicity>( data[1] );
if (curveType == Alembic::AbcGeom::kLinear)
{
oGb.set("geometry.degree", FnAttribute::IntAttribute(1));
}
else if (curveType == Alembic::AbcGeom::kCubic)
{
oGb.set("geometry.degree", FnAttribute::IntAttribute(3));
}
else
{
Alembic::Abc::IUcharArrayProperty orderProp =
iSchema.getOrdersProperty();
std::vector< FnAttribute::IntAttribute::value_type > degreeVec;
if (orderProp.valid())
{
Alembic::Util::Dimensions dims;
orderProp.getDimensions(dims, ss);
degreeVec.resize(dims.numPoints());
orderProp.getAs(degreeVec.data(), FnAttrTypeToPODType(
FnAttribute::IntAttribute::getKatAttributeType()), ss);
}
// it is stored as order so we need to subtract 1 to get degree
for (std::size_t i = 0; i < degreeVec.size(); ++i)
{
if (degreeVec[i] > 1)
{
degreeVec[i] -= 1;
}
else
{
degreeVec[i] = 1;
}
}
// fall back to linear, if there is no data
if (degreeVec.size() == 0)
{
degreeVec.push_back(1);
}
oGb.set("geometry.degree", FnAttribute::IntAttribute(
degreeVec.data(), (int64_t)degreeVec.size(), 1));
}
if (wrap == Alembic::AbcGeom::kPeriodic)
{
oGb.set("geometry.closed", FnAttribute::IntAttribute(1));
}
else
{
oGb.set("geometry.closed", FnAttribute::IntAttribute(0));
}
}
}
void cookCurves(AbcCookPtr ioCook, FnAttribute::GroupBuilder & oStaticGb)
{
Alembic::AbcGeom::ICurvesPtr objPtr(
new Alembic::AbcGeom::ICurves(*(ioCook->objPtr),
Alembic::AbcGeom::kWrapExisting));
Alembic::AbcGeom::ICurvesSchema schema = objPtr->getSchema();
oStaticGb.set("type", FnAttribute::StringAttribute("curves"));
Alembic::Abc::ICompoundProperty userProp = schema.getUserProperties();
Alembic::Abc::ICompoundProperty arbGeom = schema.getArbGeomParams();
std::string abcUser = "abcUser.";
processUserProperties(ioCook, userProp, oStaticGb, abcUser);
processArbGeomParams(ioCook, arbGeom, oStaticGb);
Alembic::AbcGeom::IV2fGeomParam uvsProp = schema.getUVsParam();
if (uvsProp.valid())
{
processArbitraryGeomParam(ioCook, schema,
uvsProp.getHeader(), oStaticGb,"geometry.arbitrary.st");
}
Alembic::AbcGeom::IN3fGeomParam normProp = schema.getNormalsParam();
if (normProp.valid())
{
Alembic::AbcGeom::GeometryScope scope = normProp.getScope();
//katana's first-class support for N for curves currently
//only supports prman "vertex" mapping. Arnold doesn't have
//meaningful normals support for curves at the moment so
//it has to be arbitrary
if (scope == Alembic::AbcGeom::kVertexScope)
{
processArbitraryGeomParam(ioCook, schema,
normProp.getHeader(), oStaticGb,"geometry.point.N");
}
else
{
processArbitraryGeomParam(ioCook, schema, normProp.getHeader(),
oStaticGb, "geometry.arbitrary.N");
}
}
Alembic::Abc::IP3fArrayProperty pointsProp =
schema.getPositionsProperty();
if (pointsProp.valid())
{
arrayPropertyToAttr(schema, pointsProp.getHeader(),
"geometry.point.P", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
Alembic::Abc::IV3fArrayProperty velocProp =
schema.getVelocitiesProperty();
if (velocProp.valid())
{
arrayPropertyToAttr(schema, velocProp.getHeader(),
"geometry.point.v", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
Alembic::Abc::IBox3dProperty boundsProp =
schema.getSelfBoundsProperty();
if (boundsProp.valid())
{
scalarPropertyToAttr(schema, boundsProp.getHeader(),
"bound", ioCook, oStaticGb);
}
Alembic::Abc::IInt32ArrayProperty numVertsProp =
schema.getNumVerticesProperty();
if (numVertsProp.valid())
{
arrayPropertyToAttr(schema, numVertsProp.getHeader(),
"geometry.numVertices", kFnKatAttributeTypeInt,
ioCook, oStaticGb);
}
Alembic::Abc::IFloatArrayProperty knotsProp = schema.getKnotsProperty();
if (knotsProp.valid())
{
arrayPropertyToAttr(schema, knotsProp.getHeader(),
"geometry.knots", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
else
{
// katana's viewer has historically looked for knots
oStaticGb.set("geometry.knots", FnAttribute::FloatAttribute(0.f));
}
Alembic::AbcGeom::IFloatGeomParam widthsProp = schema.getWidthsParam();
if (widthsProp.valid())
{
Alembic::AbcGeom::GeometryScope scope = widthsProp.getScope();
if (scope == Alembic::AbcGeom::kConstantScope)
{
Alembic::Abc::IFloatArrayProperty widthsValueProp =
widthsProp.getValueProperty();
arrayPropertyToAttr(schema, widthsValueProp.getHeader(),
"geometry.constantWidth", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
else if (scope == Alembic::AbcGeom::kVertexScope)
{
Alembic::Abc::IFloatArrayProperty widthsValueProp =
widthsProp.getValueProperty();
arrayPropertyToAttr(schema, widthsValueProp.getHeader(),
"geometry.point.width", kFnKatAttributeTypeFloat,
ioCook, oStaticGb);
}
else
{
processArbitraryGeomParam(ioCook, schema,
widthsProp.getHeader(), oStaticGb,
"geometry.arbitrary.width");
}
}
// set a default constantWidth
else
{
oStaticGb.set("geometry.constantWidth",
FnAttribute::FloatAttribute(0.1f));
}
// let's hack our way to the degree and closed values until
// ICurves has a convenience function not on the sample to get it
Alembic::Abc::IScalarProperty basisAndTypeProp(schema,
"curveBasisAndType");
if (basisAndTypeProp.valid() && basisAndTypeProp.isConstant())
{
OpArgs defaultArgs;
evalCurves(schema, defaultArgs, oStaticGb);
}
else if (basisAndTypeProp.valid())
{
// it's animated, gotta keep it around for further evaluation
// since it creates more than 1 attr
ioCook->objPtr = objPtr;
ioCook->animatedSchema = true;
}
}
}
<|start_filename|>walter/usd/fileFormat/usdArnold/arnoldApi.cpp<|end_filename|>
// Copyright 2018 <NAME>. All rights reserved.
#include "arnoldApi.h"
#include <dlfcn.h>
static const char* sLibAi = "libai.so";
#define INIT_AI_SYMBOL(A) \
A = (A##FuncPtr)dlsym(mArnoldDSO, #A); \
if (!A) \
{ \
printf("[WALTER ERROR] Can't load symbol " #A "\n"); \
}
ArnoldAPI::ArnoldAPI() : mArnoldDSO(dlopen(sLibAi, RTLD_NOW))
{
if (!mArnoldDSO)
{
printf("[WALTER ERROR] Can't load library %s.\n", sLibAi);
return;
}
INIT_AI_SYMBOL(AiGetVersion);
// Save the version
char arch[16];
AiGetVersion(arch, nullptr, nullptr, nullptr);
mArch = atoi(arch);
// Load the symbols
INIT_AI_SYMBOL(AiASSLoad);
INIT_AI_SYMBOL(AiBegin);
INIT_AI_SYMBOL(AiEnd);
INIT_AI_SYMBOL(AiLoadPlugins);
INIT_AI_SYMBOL(AiNodeEntryGetName);
INIT_AI_SYMBOL(AiNodeEntryGetParamIterator);
INIT_AI_SYMBOL(AiNodeGetBool);
INIT_AI_SYMBOL(AiNodeGetFlt);
INIT_AI_SYMBOL(AiNodeGetInt);
INIT_AI_SYMBOL(AiNodeGetLink);
INIT_AI_SYMBOL(AiNodeGetMatrix);
INIT_AI_SYMBOL(AiNodeGetName);
INIT_AI_SYMBOL(AiNodeGetNodeEntry);
INIT_AI_SYMBOL(AiNodeGetRGBA);
INIT_AI_SYMBOL(AiNodeGetRGB);
INIT_AI_SYMBOL(AiNodeGetStr);
INIT_AI_SYMBOL(AiNodeGetUInt);
INIT_AI_SYMBOL(AiNodeGetVec2);
INIT_AI_SYMBOL(AiNodeGetVec);
INIT_AI_SYMBOL(AiNodeIsLinked);
INIT_AI_SYMBOL(AiNodeIteratorDestroy);
INIT_AI_SYMBOL(AiNodeIteratorFinished);
INIT_AI_SYMBOL(AiNodeIteratorGetNext);
INIT_AI_SYMBOL(AiNodeReset);
INIT_AI_SYMBOL(AiParamGetName);
INIT_AI_SYMBOL(AiParamGetType);
INIT_AI_SYMBOL(AiParamIteratorDestroy);
INIT_AI_SYMBOL(AiParamIteratorFinished);
INIT_AI_SYMBOL(AiParamIteratorGetNext);
INIT_AI_SYMBOL(AiUniverseGetNodeIterator);
INIT_AI_SYMBOL(AiUniverseIsActive);
INIT_AI_SYMBOL(AiNodeGetArray);
INIT_AI_SYMBOL(AiArrayGetType);
INIT_AI_SYMBOL(AiArrayGetRGBFunc);
INIT_AI_SYMBOL(AiArrayGetFltFunc);
INIT_AI_SYMBOL(AiArrayGetIntFunc);
INIT_AI_SYMBOL(AiArrayGetByteFunc);
INIT_AI_SYMBOL(AiArrayGetStrFunc);
INIT_AI_SYMBOL(AiArrayGetNumElements);
INIT_AI_SYMBOL(AiNodeEntryGetType);
INIT_AI_SYMBOL(AiNodeEntryLookUpParameter);
INIT_AI_SYMBOL(AiNodeGetPtr);
}
ArnoldAPIPtr ArnoldAPI::create()
{
ArnoldAPIPtr ai = std::make_shared<ArnoldAPI>();
if (ai->valid())
{
return ai;
}
return ArnoldAPIPtr();
}
ArnoldAPI::~ArnoldAPI()
{
if (mArnoldDSO)
{
dlclose(mArnoldDSO);
}
}
bool ArnoldAPI::valid() const
{
return mArnoldDSO && mArch == 5;
}
<|start_filename|>walter/cmake/FindRdoResolver.cmake<|end_filename|>
# Copyright 2017 <NAME>. All rights reserved.
find_path (
RDO_USD_RESOLVER_INCLUDE_DIR
rdoResolver.h
PATHS ${RDO_RESOLVER_ROOT}/include
NO_DEFAULT_PATH)
find_library (
RDO_USD_RESOLVER_LIBRARY
NAMES librdoResolver${CMAKE_STATIC_LIBRARY_SUFFIX}
PATHS ${RDO_RESOLVER_ROOT}/lib
NO_DEFAULT_PATH)
find_package_handle_standard_args (
RdoResolver
REQUIRED_VARS RDO_USD_RESOLVER_INCLUDE_DIR RDO_USD_RESOLVER_LIBRARY
VERSION_VAR RdoResolver_VERSION)
<|start_filename|>walter/usd/resolver/abcCoreLayerResolver.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "abcCoreLayerResolver.h"
#include <boost/algorithm/string.hpp>
#include <pxr/base/arch/fileSystem.h>
#include <pxr/base/plug/registry.h>
#include <pxr/base/tf/type.h>
#include <pxr/base/vt/value.h>
#include <pxr/usd/ar/defineResolver.h>
#define ABC_CORE_LAYER_SEPARATOR ":"
PXR_NAMESPACE_OPEN_SCOPE
AR_DEFINE_RESOLVER(AbcCoreLayerResolver, ArResolver)
inline void splitPath(
const std::string& path, std::vector<std::string>& archives)
{
std::vector<std::string> parts;
boost::split(parts, path, boost::is_any_of(ABC_CORE_LAYER_SEPARATOR));
std::string drive;
for (const std::string& part : parts)
{
if (part.size() == 1)
{
// It's a drive. Just save it.
drive = part;
}
else
{
// Skip it if the part is empty.
if (!part.empty())
{
if (!drive.empty())
{
// Recontruct the path.
archives.push_back(drive + ":" + part);
}
else
{
archives.push_back(part);
}
}
// TODO: do we need a path with one letter only? Right now it's
// filtered out.
drive.clear();
}
}
}
AbcCoreLayerResolver::AbcCoreLayerResolver() :
ArDefaultResolver()
{}
std::string AbcCoreLayerResolver::ResolveWithAssetInfo(
const std::string& path,
ArAssetInfo* assetInfo)
{
// Special case: Alembic
if (boost::iends_with(path, ".abc"))
{
// Probably it's a set of Alembic Core Layers. In this way we need to
// split it and resolve the layers one by one.
std::vector<std::string> archives;
splitPath(path, archives);
std::vector<std::string> resolved;
resolved.reserve(archives.size());
// Resolve each archive with the default resolver.
for (const std::string& archive : archives)
{
std::string result =
BaseType::ResolveWithAssetInfo(archive, assetInfo);
if (result.empty())
{
continue;
}
resolved.push_back(result);
}
return boost::join(resolved, ABC_CORE_LAYER_SEPARATOR);
}
// Use the default resolver.
return BaseType::ResolveWithAssetInfo(path, assetInfo);
}
VtValue AbcCoreLayerResolver::GetModificationTimestamp(
const std::string& path,
const std::string& resolvedPath)
{
// Special case: Alembic
if (boost::iends_with(resolvedPath, ".abc"))
{
// Probably it's a set of Alembic Core Layers. In this way we need to
// split it, get the time of each layer and return the latest time.
std::vector<std::string> archives;
splitPath(resolvedPath, archives);
std::vector<double> times;
times.reserve(archives.size());
// Look at the time of the each archive.
for (const std::string& archive : archives)
{
double time;
if (!ArchGetModificationTime(archive.c_str(), &time))
{
continue;
}
times.push_back(time);
}
if (times.empty())
{
return VtValue();
}
double maxTime = *std::max_element(times.begin(), times.end());
return VtValue(maxTime);
}
// Use the default time.
return BaseType::GetModificationTimestamp(path, resolvedPath);
}
PXR_NAMESPACE_CLOSE_SCOPE
<|start_filename|>walter/katana/WalterIn/walterUSDOpEngine.cpp<|end_filename|>
#include "walterUSDOpEngine.h"
#include "walterUSDOpCaboose.h"
#include "walterUSDOpDelegate.h"
#include "walterUSDOpUtils.h"
#include <FnGeolib/op/FnGeolibOp.h>
#include <pxr/base/tf/instantiateSingleton.h>
#include <pxr/usd/usd/stage.h>
#include <boost/algorithm/string.hpp>
#include <boost/functional/hash.hpp>
#include <boost/noncopyable.hpp>
/** @brief Static cache for OpEngines */
class EngineRegistry : boost::noncopyable
{
public:
typedef EngineRegistry This;
/**
* @brief Get the instance of this registry singleton.
*
* @return This object.
*/
static EngineRegistry& getInstance()
{
return TfSingleton<This>::GetInstance();
}
/** @brief Clear mCache */
void clear() { mCache.clear(); }
/**
* @brief Returns the engine.
*
* @param iArchives the list of archives.
*
* @return The engine.
*/
OpEngine& getEngine(const std::vector<std::string>& iArchives)
{
// It's possible to request the engine at the same time.
ScopedLock lock(mMutex);
// Get the hash of the archives.
size_t hash = boost::hash_range(iArchives.begin(), iArchives.end());
auto it = mCache.find(hash);
if (it == mCache.end())
{
auto result = mCache.emplace(
std::piecewise_construct,
std::forward_as_tuple(hash),
std::forward_as_tuple(iArchives));
it = result.first;
}
return it->second;
}
private:
// Mutex stuff for concurrent access. We don't use TBB stuff because we
// would like to control hashing.
typedef std::mutex Mutex;
typedef std::lock_guard<Mutex> ScopedLock;
std::map<size_t, OpEngine> mCache;
Mutex mMutex;
};
TF_INSTANTIATE_SINGLETON(EngineRegistry);
OpEngine& OpEngine::getInstance(const std::vector<std::string>& iArchives)
{
return EngineRegistry::getInstance().getEngine(iArchives);
}
void OpEngine::clearCaches()
{
EngineRegistry::getInstance().clear();
}
OpEngine::OpEngine(const std::vector<std::string>& iArchives) :
mIdentifier(boost::algorithm::join(iArchives, ":"))
{
SdfLayerRefPtr root = WalterUSDCommonUtils::getUSDLayer(iArchives);
mStage = UsdStage::Open(root);
OpDelegate::populate(mStage->GetPseudoRoot(), mIndex);
}
void OpEngine::dress(void* ioClientData)
{
auto interface =
reinterpret_cast<Foundry::Katana::GeolibCookInterface*>(ioClientData);
static std::string currentTimeStr = "system.timeSlice.currentTime";
FnAttribute::FloatAttribute currentTimeAttr(
interface->getOpArg(currentTimeStr));
float currentTime = currentTimeAttr.getValue(0.0, false);
FnAttribute::StringAttribute variantsListAttr =
interface->getOpArg("variantsList");
auto variantsList = variantsListAttr.getNearestSample(currentTime);
for (auto const* variants : variantsList)
WalterUSDCommonUtils::setVariantUSD(mStage, variants);
}
void OpEngine::cook(
const OpUtils::PrivateData* iPrivateData,
void* ioClientData)
{
assert(iPrivateData);
dress(ioClientData);
const UsdPrim prim = mStage->GetPrimAtPath(iPrivateData->path());
// Output geo. For example polymesh.
OpCaboose::cook(prim, iPrivateData, ioClientData);
if (OpCaboose::skipChildren(prim))
{
return;
}
// Output children.
for (const auto& child : prim.GetChildren())
{
if (OpCaboose::isSupported(child))
{
// We pass this engine as a private data for fast access from the
// next generated scene graph node.
// TODO: probably passing the list of the layers is better because
// it would be possible to create such node in OpScript.
OpCaboose::cookChild(child, iPrivateData, ioClientData);
}
}
}
void OpEngine::cookMasters(
const OpUtils::PrivateData* iPrivateData,
void* ioClientData)
{
assert(iPrivateData);
mMastersInfoMap = WalterUSDCommonUtils::getMastersInfo(mStage);
for (const auto& master: mStage->GetMasters())
{
if (OpCaboose::isSupported(master))
{
std::string katanaName = getKatMasterName(master);
OpCaboose::cookChild(master, iPrivateData, ioClientData, katanaName);
}
}
}
WalterUSDCommonUtils::MasterPrimInfo OpEngine::getMasterPrimInfo(
const UsdPrim& iPrim)
{
WalterUSDCommonUtils::MasterPrimInfo masterInfo;
if (iPrim.IsInMaster() && !iPrim.IsMaster())
{
SdfPath masterRoot = iPrim.GetPath().GetPrefixes().front();
masterInfo = mMastersInfoMap.at(masterRoot.GetName());
}
else if (iPrim.IsInstance())
{
masterInfo = mMastersInfoMap.at(iPrim.GetMaster().GetName());
}
return masterInfo;
}
std::string OpEngine::getMasterName(const UsdPrim& iPrim)
{
WalterUSDCommonUtils::MasterPrimInfo masterInfo =
getMasterPrimInfo(iPrim);
return masterInfo.realName;
}
std::string OpEngine::getKatMasterName(const UsdPrim& iMasterPrim)
{
WalterUSDCommonUtils::MasterPrimInfo masterInfo =
mMastersInfoMap.at(iMasterPrim.GetName());
if (masterInfo.isEmpty())
return "";
std::string katanaName = "master_" + masterInfo.realName;
std::vector<std::string> variantsSelection = masterInfo.variantsSelection;
for (int i = variantsSelection.size(); i--;)
{
katanaName += "_" + variantsSelection[i];
}
return katanaName;
}
<|start_filename|>walter/cmake/FindUSD.cmake<|end_filename|>
# Copyright 2017 <NAME>. All rights reserved.
# Trying to find USD include path.
find_path (
USD_INCLUDE_DIR
pxr/pxr.h
PATHS ${USD_ROOT}/include
NO_DEFAULT_PATH)
# Trying to get version
file(STRINGS ${USD_INCLUDE_DIR}/pxr/pxr.h TMP REGEX "^#define PXR_VERSION .*$")
string (REGEX MATCHALL "[0-9]+" USD_VERSION ${TMP})
# The list of required libraries for minimal USD.
set (_usd_components
usdShade
usdGeom
usd
usdUtils
pcp
sdf
plug
js
ar
work
tf
trace
kind
arch
vt
gf
hf
cameraUtil
usdAbc
usdLux
usdSkel)
# The list of required libraries for Hydra.
set (_hydra_components
usdImagingGL
usdImaging
usdHydra
hdx
hdSt
hdStream
hd
glf
garch
pxOsd
usdRi
usdSkelImaging
usdUI)
set (_usd_all_components ${_usd_components} ${_hydra_components})
# Trying to find all the libraries.
foreach (COMPONENT ${_usd_all_components})
string (TOUPPER ${COMPONENT} UPPERCOMPONENT)
unset (USD_${UPPERCOMPONENT}_LIBRARY CACHE)
find_library (
USD_${UPPERCOMPONENT}_LIBRARY
NAMES ${COMPONENT} ${COMPONENT}${CMAKE_STATIC_LIBRARY_SUFFIX}
PATHS ${USD_ROOT}/lib ${USD_ROOT}/plugin/usd
NO_DEFAULT_PATH)
endforeach ()
set (USD_LIBRARIES "")
set (HYDRA_LIBRARIES "")
foreach (COMPONENT ${_usd_components})
string (TOUPPER ${COMPONENT} UPPERCOMPONENT)
list(APPEND USD_LIBRARIES ${USD_${UPPERCOMPONENT}_LIBRARY})
endforeach ()
foreach (COMPONENT ${_hydra_components})
string (TOUPPER ${COMPONENT} UPPERCOMPONENT)
list(APPEND HYDRA_LIBRARIES ${USD_${UPPERCOMPONENT}_LIBRARY})
endforeach ()
find_package_handle_standard_args (
USD
REQUIRED_VARS USD_INCLUDE_DIR USD_LIBRARIES HYDRA_LIBRARIES
VERSION_VAR USD_VERSION)
<|start_filename|>walter/maya/walterStandin/walterAttributes.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "OWalterExpressionsSchema.h"
#include "mayaUtils.h"
#include "walterAssignment.h"
#include <Alembic/Abc/All.h>
#include <Alembic/AbcCoreLayer/Util.h>
#include <Alembic/AbcCoreOgawa/All.h>
#include <Alembic/AbcMaterial/All.h>
#include <maya/MDataHandle.h>
#include <maya/MFnAttribute.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MGlobal.h>
#include <maya/MObject.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>
#include <maya/MSelectionList.h>
#include <unordered_set>
bool saveAttributes(const MString& objectName, const MString& fileName)
{
// Looking for MFnDependencyNode object in the scene.
MSelectionList selectionList;
selectionList.add(objectName);
MObject obj;
selectionList.getDependNode(0, obj);
MFnDependencyNode depNode(obj);
const MPlug layersAssignation = depNode.findPlug("layersAssignation");
if (layersAssignation.isNull())
{
MString msg;
msg.format("[walter] Can't find ^1s.layersAssignation", depNode.name());
MGlobal::displayError(msg);
return false;
}
if (layersAssignation.numElements() <= 0)
{
MString msg;
msg.format(
"[walter] There are no assignments to save in ^1s", objectName);
MGlobal::displayError(msg);
return false;
}
// Contain the names of the walterOverride nodes that are already in the
// Alembic file. We need it to avoid placing the same node several times.
std::unordered_set<std::string> nodeNameCache;
// Create Alembic file.
Alembic::Abc::OArchive archive;
try
{
archive = Alembic::Abc::OArchive(
Alembic::AbcCoreOgawa::WriteArchive(), fileName.asChar());
}
catch (std::exception& exc)
{
MString msg;
msg.format(
"[walter] Can't write alembic ^1s. Exception:\n^2s",
fileName,
exc.what());
MGlobal::displayError(msg);
return false;
}
Alembic::Abc::OObject root(archive, Alembic::Abc::kTop);
Alembic::Abc::OObject materials(root, "materials");
// Used to mark that an Alembic object or property are meant to be replaced
// when reading via AbcCoreLayer. Replacing an object or compound property
// will also replace all of the children encountered and shading network so
// far.
Alembic::Abc::MetaData replace;
Alembic::AbcCoreLayer::SetReplace(replace, true);
for (unsigned int i = 0; i < layersAssignation.numElements(); i++)
{
// Get walterStandin.layersAssignation[i]
const MPlug currentLayerCompound =
layersAssignation.elementByPhysicalIndex(i);
// Get walterStandin.layersAssignation[i].layer
MPlug layerPlug;
if (!GetChildMPlug(currentLayerCompound, "layer", layerPlug))
{
continue;
}
MPlugArray connections;
if (!layerPlug.connectedTo(connections, true, false) ||
!connections.length())
{
continue;
}
// The layer is the first connected node. We consider we have only one
// connection.
const MFnDependencyNode layer(connections[0].node());
const std::string layerName = layer.name().asChar();
MPlug shadersPlug;
if (!GetChildMPlug(
currentLayerCompound, "shaderConnections", shadersPlug))
{
continue;
}
for (unsigned int j = 0; j < shadersPlug.numElements(); j++)
{
// Get walterStandin.layersAssignation[i].shaderConnections[j]
const MPlug shadersCompound = shadersPlug.elementByPhysicalIndex(j);
// Get walterStandin.layersAssignation[].shaderConnections[].abcnode
MPlug abcnodePlug;
if (!GetChildMPlug(shadersCompound, "abcnode", abcnodePlug))
{
continue;
}
const MString abcnode = abcnodePlug.asString().asChar();
if (!abcnode.length())
{
continue;
}
// The same for attributes
MPlug attrPlug;
if (!GetChildMPlug(shadersCompound, "attribute", attrPlug))
{
continue;
}
// Get the connected attribute node
MPlugArray connections;
if (!attrPlug.connectedTo(connections, true, false) ||
!connections.length())
{
continue;
}
const MFnDependencyNode node(connections[0].node());
std::string nodeName = node.name().asChar();
if (!nodeNameCache.emplace(nodeName).second)
{
// If std::set::emplace successfully inserts the element, the
// function returns a pair of an iterator and a value of true.
// If we are here, we already placed walterOverride to the
// Alembic file.
continue;
}
// TODO: crashes when container.name() is already exported
Alembic::AbcMaterial::OMaterial matObj(
materials, nodeName, replace);
// Setup the material.
Alembic::AbcMaterial::OMaterialSchema& schema = matObj.getSchema();
schema.setShader("arnold", "attribute", "walterOverride");
Alembic::Abc::OCompoundProperty parameters =
schema.getShaderParameters("arnold", "attribute");
unsigned int nAttributes = node.attributeCount();
for (unsigned int a = 0; a < nAttributes; a++)
{
MObject object = node.attribute(a);
MFnAttribute attr(object);
// Set good name. Remove the prefix and convert it.
// "walterSubdivType" -> "subdiv_type"
bool isUserData = false;
std::string name =
attributeNameDemangle(attr.name().asChar(), &isUserData);
if (name.empty())
{
continue;
}
Alembic::Abc::MetaData meta;
if (isUserData)
{
// Save that it's a User Data.
meta.set("userData", "yes");
}
MPlug attrPlug = node.findPlug(object);
const MDataHandle data = attrPlug.asMDataHandle();
// Convert Maya type to Alembic type.
switch (data.numericType())
{
case MFnNumericData::kInvalid:
{
int v;
if (data.type() == MFnData::kString)
{
// It's a string.
Alembic::Abc::OStringProperty property(
parameters, name, meta);
property.set(data.asString().asChar());
}
else if (attrPlug.getValue(v) == MS::kSuccess)
{
// This plug doesn't have data. But we can try
// to get an int.
Alembic::Abc::OInt32Property property(
parameters, name, meta);
property.set(v);
}
break;
}
case MFnNumericData::kBoolean:
{
Alembic::Abc::OBoolProperty property(
parameters, name, meta);
property.set(data.asBool());
break;
}
case MFnNumericData::kShort:
case MFnNumericData::kLong:
{
Alembic::Abc::OInt32Property property(
parameters, name, meta);
property.set(data.asInt());
break;
}
case MFnNumericData::kFloat:
{
Alembic::Abc::OFloatProperty property(
parameters, name, meta);
property.set(data.asFloat());
break;
}
case MFnNumericData::kDouble:
{
Alembic::Abc::OFloatProperty property(
parameters, name, meta);
property.set(data.asDouble());
break;
}
case MFnNumericData::k3Float:
{
Alembic::Abc::OV3fProperty property(
parameters, name, meta);
const float3& color = data.asFloat3();
property.set(Imath::V3f(color[0], color[1], color[2]));
break;
}
default:
break;
}
}
}
}
return true;
}
<|start_filename|>walter/arnold/procedural/plugin.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "plugin.h"
#include "index.h"
#include <ai.h>
#include <boost/algorithm/string.hpp>
#include <functional>
#include <pxr/base/gf/matrix4f.h>
#include <pxr/base/gf/rotation.h>
#include <pxr/base/gf/transform.h>
#include <pxr/usd/usdGeom/basisCurves.h>
#include <pxr/usd/usdGeom/curves.h>
#include <pxr/usd/usdGeom/mesh.h>
#include <pxr/usd/usdGeom/pointInstancer.h>
#include <pxr/usd/usdShade/connectableAPI.h>
#include <pxr/usd/usdShade/shader.h>
#include <tbb/atomic.h>
PXR_NAMESPACE_USING_DIRECTIVE
/**
* @brief Searches the pre-defined (non-user) parameter entries of a given node
* looking for a parameter that matches the name string. If found, returns a
* pointer to the parameter entry. The difference with
* AiNodeEntryLookUpParameter is that it takes AiNode.
*
* @param node Input node.
* @param name Parameter name that we are looking for.
*
* @return If found, returns a pointer to the parameter entry. Otherwise, it
* returns NULL.
*/
const AtParamEntry* getArnoldParameter(AtNode* node, const char* name)
{
return AiNodeEntryLookUpParameter(AiNodeGetNodeEntry(node), name);
}
/**
* @brief Each time it returns a unique string. It's thread safety.
*
* @return "0", "1", "2", etc...
*/
inline std::string uniqueString()
{
// An atomic value is a value that cannot be divided. Thus, thread safety.
// The advantage of atomic operations is that they are relatively quick
// compared to locks.
static tbb::atomic<unsigned int> counter(0);
return std::to_string(counter.fetch_and_increment());
}
/**
* @brief Join instance root path and current path. It returns std::string
* because when resolving shaders, we work with strings.
*
* @param iInstanceRootPath The USD path of the root of the current USD
* instance.
* @param iPath Current path.
*
* @return Resolved/joined full path that is good for the expression resolving.
*/
inline std::string joinPaths(
const std::string& iInstanceRootPath,
const SdfPath& iPath)
{
assert(!iPath.IsEmpty());
if (iInstanceRootPath.empty())
{
// We don't have the instance, so the joined path is the current path.
return iPath.GetString();
}
const std::string& pathStr = iPath.GetString();
// Concat them. If we are in the instance, the path looks like this:
// "/__Master_01/normal/path", we don't need the first part.
return iInstanceRootPath + pathStr.substr(pathStr.find('/', 1));
}
/**
* @brief Set Arnold motion_start and motion_end.
*
* @param iNode Arnold node to set.
* @param iData Reference to RendererPluginData.
*/
void setMotionStartEnd(AtNode* iNode, const RendererPluginData& iData)
{
if (iData.motionStart)
{
AiNodeSetFlt(iNode, "motion_start", *iData.motionStart);
}
if (iData.motionEnd)
{
AiNodeSetFlt(iNode, "motion_end", *iData.motionEnd);
}
}
inline AtNode* createWalterProcedural(
const RendererPluginData* iData,
const std::string iName,
const std::vector<float>& iTimes,
const std::vector<float>& iXform,
const SdfPath& iObjectPath,
const std::string& iPrefix)
{
// Create a procedural.
AtNode* node = AiNode("walter");
AiNodeSetStr(node, "name", iName.c_str());
// Output frame.
assert(iTimes.size() > 0);
if (iTimes.size() == 1)
{
AiNodeDeclare(node, "frame", "constant FLOAT");
AiNodeSetFlt(node, "frame", iTimes[0]);
}
else
{
AiNodeDeclare(node, "frame", "constant ARRAY FLOAT");
AiNodeSetArray(
node,
"frame",
AiArrayConvert(1, iTimes.size(), AI_TYPE_FLOAT, iTimes.data()));
}
if (!iXform.empty())
{
AiNodeSetArray(
node,
"matrix",
AiArrayConvert(
1, iXform.size() / 16, AI_TYPE_MATRIX, iXform.data()));
}
// Set Arnold motion_start and motion_end.
setMotionStartEnd(node, *iData);
AiNodeSetStr(node, "filePaths", iData->filePaths.c_str());
AiNodeSetStr(node, "objectPath", iObjectPath.GetText());
AiNodeDeclare(node, "prefix", "constant STRING");
AiNodeSetStr(node, "prefix", iPrefix.c_str());
return node;
}
// Reverse an attribute of the face. Basically, it converts from the clockwise
// to the counterclockwise and back.
template <class T, class V>
void reverseFaceAttribute(T& attr, const V& counts)
{
size_t counter = 0;
// TODO: if it's slow, it can be faster with SIMD.
for (auto npoints : counts)
{
for (size_t j = 0; j < npoints / 2; j++)
{
size_t from = counter + j;
size_t to = counter + npoints - 1 - j;
std::swap(attr[from], attr[to]);
}
counter += npoints;
}
}
// Function template specialization for all the AiNodeSet*
// TODO: AiNodeSetVec, AiNodeSetPnt
template <class A>
void aiNodeSet(AtNode* node, std::string name, const A& value);
template <>
void aiNodeSet<unsigned int>(
AtNode* node,
std::string name,
const unsigned int& value)
{
if (!getArnoldParameter(node, name.c_str()))
{
AiNodeDeclare(node, name.c_str(), "constant UINT");
}
AiNodeSetUInt(node, name.c_str(), value);
}
template <>
void aiNodeSet<int>(AtNode* node, std::string name, const int& value)
{
if (!getArnoldParameter(node, name.c_str()))
{
AiNodeDeclare(node, name.c_str(), "constant INT");
}
AiNodeSetInt(node, name.c_str(), value);
}
template <>
void aiNodeSet<bool>(AtNode* node, std::string name, const bool& value)
{
if (!getArnoldParameter(node, name.c_str()))
{
AiNodeDeclare(node, name.c_str(), "constant INT");
}
AiNodeSetBool(node, name.c_str(), value);
}
template <>
void aiNodeSet<float>(AtNode* node, std::string name, const float& value)
{
if (!getArnoldParameter(node, name.c_str()))
{
AiNodeDeclare(node, name.c_str(), "constant FLOAT");
}
AiNodeSetFlt(node, name.c_str(), value);
}
template <>
void aiNodeSet<std::string>(
AtNode* node,
std::string name,
const std::string& value)
{
if (!getArnoldParameter(node, name.c_str()))
{
AiNodeDeclare(node, name.c_str(), "constant STRING");
}
AiNodeSetStr(node, name.c_str(), value.c_str());
}
template <>
void aiNodeSet<TfToken>(AtNode* node, std::string name, const TfToken& value)
{
if (!getArnoldParameter(node, name.c_str()))
{
AiNodeDeclare(node, name.c_str(), "constant STRING");
}
AiNodeSetStr(node, name.c_str(), value.GetText());
}
template <>
void aiNodeSet<GfVec3f>(AtNode* node, std::string name, const GfVec3f& value)
{
const AtParamEntry* entry = getArnoldParameter(node, name.c_str());
if (!entry)
{
AiNodeDeclare(node, name.c_str(), "constant RGB");
}
else if (AiParamGetType(entry) == AI_TYPE_VECTOR)
{
// This parameter exists and the type is Vector. We can't save it as
// RGB.
AiNodeSetVec(node, name.c_str(), value[0], value[1], value[2]);
return;
}
AiNodeSetRGB(node, name.c_str(), value[0], value[1], value[2]);
}
template <>
void aiNodeSet<GfVec4f>(AtNode* node, std::string name, const GfVec4f& value)
{
const AtParamEntry* entry = getArnoldParameter(node, name.c_str());
if (!entry)
{
AiNodeDeclare(node, name.c_str(), "constant RGBA");
}
AiNodeSetRGBA(node, name.c_str(), value[0], value[1], value[2], value[3]);
}
template <>
void aiNodeSet<GfVec2f>(AtNode* node, std::string name, const GfVec2f& value)
{
if (!getArnoldParameter(node, name.c_str()))
{
AiNodeDeclare(node, name.c_str(), "constant VECTOR2");
}
AiNodeSetVec2(node, name.c_str(), value[0], value[1]);
}
template <>
void aiNodeSet<uint8_t>(AtNode* node, std::string name, const uint8_t& value)
{
if (!getArnoldParameter(node, name.c_str()))
{
AiNodeDeclare(node, name.c_str(), "constant BYTE");
}
AiNodeSetByte(node, name.c_str(), value);
}
template <>
void aiNodeSet<GfMatrix4d>(AtNode* node, std::string name, const GfMatrix4d& value)
{
if (!getArnoldParameter(node, name.c_str()))
{
AiNodeDeclare(node, name.c_str(), "constant MATRIX");
}
// Usd GfMatrix4d is using doubles. We need to cast it for Arnold who is using floats
const double* data = value.GetArray();
AtMatrix mat;
mat.data[0][0] = static_cast<float>(data[0]);
mat.data[0][1] = static_cast<float>(data[1]);
mat.data[0][2] = static_cast<float>(data[2]);
mat.data[0][3] = static_cast<float>(data[3]);
mat.data[1][0] = static_cast<float>(data[4]);
mat.data[1][1] = static_cast<float>(data[5]);
mat.data[1][2] = static_cast<float>(data[6]);
mat.data[1][3] = static_cast<float>(data[7]);
mat.data[2][0] = static_cast<float>(data[8]);
mat.data[2][1] = static_cast<float>(data[9]);
mat.data[2][2] = static_cast<float>(data[10]);
mat.data[2][3] = static_cast<float>(data[11]);
mat.data[3][0] = static_cast<float>(data[12]);
mat.data[3][1] = static_cast<float>(data[13]);
mat.data[3][2] = static_cast<float>(data[14]);
mat.data[3][3] = static_cast<float>(data[15]);
AiNodeSetMatrix(node, name.c_str(), mat);
}
// Return the funstion that pushes USD attribute to Arnold.
template <class U, class A = U>
RendererAttribute attributeToArnold(
const UsdAttribute& attr,
const std::string& name,
UsdTimeCode time)
{
// Todo: samples.
U value;
if (!attr.Get(&value, time))
{
// We are here because this parameter is empty. It happens when USD has
// a connection to this parameter. In this way the USD Prim has both
// the parameter (to specify its type) and the relationship.
return RendererAttribute::ArnoldParameterPtr(nullptr);
}
return std::make_shared<RendererAttribute::ArnoldParameter>(
std::bind(aiNodeSet<A>, std::placeholders::_1, name, value));
}
RendererAttribute usdAttributeToArnold(
const std::string& attributeName,
const UsdAttribute& attr,
UsdTimeCode time)
{
SdfValueTypeName type;
// Sometimes we have to force the type.
if (attributeName == "subdiv_iterations")
{
type = SdfValueTypeNames->UChar;
}
else
{
type = attr.GetTypeName();
}
// Output the USD attribute depending on the type.
if (type == SdfValueTypeNames->Bool)
{
// Special case: Visibilities. Arnold doesn't have a separate attribute
// for different types of visibility. Instead, it has a single bitwise
// visibility attribute. It means we need to save all the flags and
// combine them.
uint8_t ray = AI_RAY_UNDEFINED;
if (attributeName == "casts_shadows")
{
ray = AI_RAY_SHADOW;
}
else if (attributeName == "primary_visibility")
{
ray = AI_RAY_CAMERA;
}
else if (attributeName == "visibility")
{
ray = AI_RAY_ALL;
}
else if (attributeName == "visible_in_diffuse")
{
ray = AI_RAY_ALL_DIFFUSE;
}
else if (attributeName == "visible_in_glossy")
{
ray = AI_RAY_ALL_SPECULAR;
}
else if (attributeName == "visible_in_reflections")
{
ray = AI_RAY_ALL_REFLECT;
}
else if (attributeName == "visible_in_refractions")
{
ray = AI_RAY_ALL_TRANSMIT;
}
else if (attributeName == "visible_in_diffuse_reflection")
{
ray = AI_RAY_DIFFUSE_REFLECT;
}
else if (attributeName == "visible_in_specular_reflection")
{
ray = AI_RAY_SPECULAR_REFLECT;
}
else if (attributeName == "visible_in_diffuse_transmission")
{
ray = AI_RAY_DIFFUSE_TRANSMIT;
}
else if (attributeName == "visible_in_specular_transmission")
{
ray = AI_RAY_SPECULAR_TRANSMIT;
}
else if (attributeName == "visible_in_volume")
{
ray = AI_RAY_VOLUME;
}
bool visibilityFlag;
if (ray && attr.Get(&visibilityFlag, time) && !visibilityFlag)
{
// We save the visibilities inverted to be able to combine them with
// AND operator in outputAttributes().
return ~ray;
}
return attributeToArnold<bool>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Int)
{
return attributeToArnold<int>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->UInt)
{
return attributeToArnold<unsigned int>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Float)
{
return attributeToArnold<float>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Double)
{
return attributeToArnold<double, float>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->String)
{
return attributeToArnold<std::string>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Token)
{
return attributeToArnold<TfToken>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Color3f)
{
return attributeToArnold<GfVec3f>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Vector3f)
{
return attributeToArnold<GfVec3f>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Point3f)
{
return attributeToArnold<GfVec3f>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Float2)
{
return attributeToArnold<GfVec2f>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Float3)
{
return attributeToArnold<GfVec3f>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Float4)
{
return attributeToArnold<GfVec4f>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->UChar)
{
return attributeToArnold<int, uint8_t>(attr, attributeName, time);
}
else if (type == SdfValueTypeNames->Matrix4d)
{
return attributeToArnold<GfMatrix4d>(attr, attributeName, time);
}
return RendererAttribute(nullptr);
}
// Push USD array attribute to Arnold.
// It extracts data from USD attribute, converts the USD data type to the type
// understandable by Arnold, and sets Arnold attribute.
// numVertsArray: a pointer to the face counts to reverce the attribute. If
// NULL, the attribute will not be reverced.
// TODO: Check A and U are the same and don't convert if it's so.
template <class A, class U>
size_t attributeArrayToArnold(
UsdAttribute attr,
AtNode* node,
const char* name,
uint8_t type,
const std::vector<float>& times,
const VtIntArray* numVertsArray)
{
// Number of motion keys.
size_t keys = times.size();
// The number of data items.
size_t size = 0;
std::vector<A> vect;
bool reserved = false;
for (float time : times)
{
VtArray<U> array;
attr.Get(&array, time);
if (numVertsArray)
{
// Arnold doesn't have an attribute to specify the orientation of
// data. If the data is in wrong order, we need to reorder it now.
reverseFaceAttribute(array, *numVertsArray);
}
if (!reserved)
{
// Reserve the vector.
size = array.size();
vect.reserve(size * keys);
reserved = true;
}
vect.insert(vect.end(), array.begin(), array.end());
}
if (!vect.empty())
{
// Output everything to Arnold only if we have data to output.
AiNodeSetArray(
node, name, AiArrayConvert(size, keys, type, vect.data()));
}
return size;
}
template <class T>
bool vtToArnold(
const VtValue& vtValue,
const VtIntArray& vtIndices,
const TfToken& name,
const SdfValueTypeName& typeName,
const TfToken& interpolation,
AtNode* node,
const VtIntArray* numVertsArray,
const int pointInstanceId)
{
if (!vtValue.IsHolding<VtArray<T>>())
{
return false;
}
TfToken arnoldName = name;
bool needDeclare = true;
// Convert interpolation -> scope
//
// USD Interpolation determines how the Primvar interpolates over a
// geometric primitive:
// constant One value remains constant over the entire surface
// primitive.
// uniform One value remains constant for each uv patch segment of the
// surface primitive (which is a face for meshes).
// varying Four values are interpolated over each uv patch segment of
// the surface. Bilinear interpolation is used for interpolation
// between the four values.
// vertex Values are interpolated between each vertex in the surface
// primitive. The basis function of the surface is used for
// interpolation between vertices.
// faceVarying For polygons and subdivision surfaces, four values are
// interpolated over each face of the mesh. Bilinear
// interpolation is used for interpolation between the four
// values.
//
// There are four kinds of user-defined data in Arnold:
//
// constant constant parameters are data that are defined on a
// per-object basis and do not vary across the surface of that
// object.
// uniform uniform parameters are data that are defined on a "per-face"
// basis. During subdivision (if appropriate) values are not
// interpolated. Instead, the newly subdivided faces will
// contain the value of their "parent" face.
// varying varying parameters are data that are defined on a per-vertex
// basis. During subdivision (if appropriate), the values at the
// new vertices are interpolated from the values at the old
// vertices. The user should only create parameters of
// "interpolatable" variable types (such as floats, colors,
// etc.)
// indexed indexed parameters are data that are defined on a
// per-face-vertex basis. During subdivision (if appropriate),
// the values at the new vertices are interpolated from the
// values at the old vertices, preserving edges where values
// were not shared. The user should only create parameters of
// "interpolatable" variable types (such as floats, colors,
// etc.)
std::string declaration = (interpolation == UsdGeomTokens->uniform) ?
"uniform " :
(interpolation == UsdGeomTokens->varying) ?
"varying " :
(interpolation == UsdGeomTokens->vertex) ?
"varying " :
(interpolation == UsdGeomTokens->faceVarying) ? "indexed " :
"constant ";
int arnoldAPIType;
if (std::is_same<T, GfVec2f>::value)
{
declaration += "VECTOR2";
arnoldAPIType = AI_TYPE_VECTOR2;
// A special case for UVs.
if (name == "uv")
{
arnoldName = TfToken("uvlist");
needDeclare = false;
}
}
else if (std::is_same<T, GfVec3f>::value)
{
TfToken role = typeName.GetRole();
if (role == SdfValueRoleNames->Color)
{
declaration += "RGB";
arnoldAPIType = AI_TYPE_RGB;
}
else
{
declaration += "VECTOR";
arnoldAPIType = AI_TYPE_VECTOR;
}
}
else if (std::is_same<T, float>::value)
{
declaration += "FLOAT";
arnoldAPIType = AI_TYPE_FLOAT;
}
else if (std::is_same<T, int>::value)
{
declaration += "INT";
arnoldAPIType = AI_TYPE_INT;
}
else
{
// Not supported.
return false;
}
// Declare a user-defined parameter.
if (needDeclare)
{
AiNodeDeclare(node, arnoldName.GetText(), declaration.c_str());
}
// Constant USD attributs are provided as an array of one element.
if (interpolation == UsdGeomTokens->constant)
{
if (std::is_same<T, GfVec3f>::value)
{
VtArray<GfVec3f> vecArray = vtValue.Get<VtArray<GfVec3f>>();
GfVec3f value;
if (pointInstanceId == -1)
{
value = vecArray[0];
}
else
{
value = vecArray[pointInstanceId];
}
TfToken role = typeName.GetRole();
if (role == SdfValueRoleNames->Color)
{
AiNodeSetRGB(
node, arnoldName.GetText(), value[0], value[1], value[2]);
}
else
{
AiNodeSetVec(
node, arnoldName.GetText(), value[0], value[1], value[2]);
}
}
else if (std::is_same<T, GfVec2f>::value)
{
auto vector = vtValue.Get<VtArray<GfVec2f>>()[0];
AiNodeSetVec2(node, arnoldName.GetText(), vector[0], vector[1]);
}
else if (std::is_same<T, float>::value)
{
AiNodeSetFlt(node, arnoldName.GetText(), vtValue.Get<VtArray<float>>()[0]);
}
else if (std::is_same<T, int>::value)
{
AiNodeSetInt(node, arnoldName.GetText(), vtValue.Get<VtArray<int>>()[0]);
}
}
else
{
const VtArray<T>& rawVal = vtValue.Get<VtArray<T>>();
AiNodeSetArray(
node,
arnoldName.GetText(),
AiArrayConvert(rawVal.size(), 1, arnoldAPIType, rawVal.data()));
if (interpolation == UsdGeomTokens->faceVarying)
{
const std::string indexName = name.GetString() + "idxs";
std::vector<unsigned int> indexes;
if (vtIndices.empty())
{
// Arnold doesn't have facevarying iterpolation. It has indexed
// instead. So it means it's necessary to generate indexes for this
// type.
// TODO: Try to generate indexes only once and use it for several
// primvars.
indexes.resize(rawVal.size());
// Fill it with 0, 1, ..., 99.
std::iota(std::begin(indexes), std::end(indexes), 0);
}
else
{
// We need to use indexes and we can't use vtIndices because we need
// unsigned int. Converting int to unsigned int.
indexes.resize(vtIndices.size());
std::copy(vtIndices.begin(), vtIndices.end(), indexes.begin());
}
// Reverse indexes.
if (numVertsArray)
{
reverseFaceAttribute(indexes, *numVertsArray);
}
AiNodeSetArray(
node,
indexName.c_str(),
AiArrayConvert(indexes.size(), 1, AI_TYPE_UINT, indexes.data()));
}
}
return true;
}
/**
* @brief Compute transform of the given prim.
*
* @param iPrim The given prim.
* @param times The given times.
*
* @return Vector of the 4x4 matrices that represent the transforms.
*/
std::vector<float> getPrimTransform(
const UsdPrim& iPrim,
const std::vector<float>& times)
{
std::vector<float> xform;
// A problem here is that it's not possible to use this to get the transform
// of non-imageable object:
// `UsdGeomXformCache(time).GetLocalToWorldTransform(prim)`
// It crashes for unknown reason. So if the transform is not available on
// the current prim, we need to manually find transform of the parents.
UsdPrim prim = iPrim;
while (!prim.IsA<UsdGeomImageable>())
{
prim = prim.GetParent();
if (prim.GetPath() == SdfPath::AbsoluteRootPath())
{
return xform;
}
}
// Output XForm
UsdGeomImageable imageable(prim);
size_t keys = times.size();
xform.reserve(16 * keys);
for (float time : times)
{
GfMatrix4d matrix = imageable.ComputeLocalToWorldTransform(time);
const double* matrixArray = matrix.GetArray();
xform.insert(xform.end(), matrixArray, matrixArray + 16);
}
return xform;
}
void RendererAttribute::evaluate(AtNode* node) const
{
if (mFunction)
{
(*mFunction)(node);
}
}
bool RendererAttribute::valid() const
{
return mFunction != nullptr || mVisibility;
}
bool RendererAttribute::isVisibility() const
{
return mVisibility;
}
uint8_t RendererAttribute::visibilityFlag() const
{
return mVisibilityFlag;
}
RendererPlugin::RendererPlugin()
{
#if 0
TfDebug::Enable(WALTER_ARNOLD_PLUGIN);
#endif
}
bool RendererPlugin::isSupported(const UsdPrim& prim) const
{
if (!prim)
{
return false;
}
return prim.IsInstance() || prim.IsA<UsdGeomMesh>() ||
prim.IsA<UsdGeomCurves>() || prim.IsA<UsdGeomPointInstancer>();
}
bool RendererPlugin::isImmediate(const UsdPrim& prim) const
{
if (!prim)
{
return false;
}
// Shaders should be output immediatly.
return prim.IsA<UsdShadeShader>();
}
void* RendererPlugin::output(
const UsdPrim& prim,
const std::vector<float>& times,
const void* userData) const
{
const RendererPluginData* data =
reinterpret_cast<const RendererPluginData*>(userData);
assert(data);
SdfPath objectPath = prim.GetPath();
std::string prefix = data->prefix;
std::string name = prefix + ":" + objectPath.GetText() + ":proc";
std::vector<float> xform;
return createWalterProcedural(
data,
name,
times,
xform,
objectPath,
prefix);
}
// TODO:
// AiNodeSetBool(node, "inherit_xform", false);
// AiNodeSetBool(node, "invert_normals", true);
// AiNodeSetByte(node, "sidedness", AI_RAY_ALL);
void* RendererPlugin::outputBBox(
const UsdPrim& prim,
const std::vector<float>& times,
const void* userData,
RendererIndex& index) const
{
// Get the user data
const RendererPluginData* data =
reinterpret_cast<const RendererPluginData*>(userData);
assert(data);
const SdfPath path = prim.GetPath();
// Form the name.
std::string name = data->prefix + ":" + path.GetText() + ":proc";
// Output XForm
std::vector<float> xform = getPrimTransform(prim, times);
SdfPath objectPath;
std::string prefix;
if (prim.IsInstance())
{
objectPath = prim.GetMaster().GetPath();
prefix = data->prefix + "_" + uniqueString();
// Save the full path that is good for expression resolving.
index.setPrefixPath(
prefix, joinPaths(index.getPrefixPath(data->prefix), path));
}
else
{
objectPath = prim.GetPath();
prefix = data->prefix;
}
return createWalterProcedural(
data,
name,
times,
xform,
objectPath,
prefix);
}
void* RendererPlugin::outputBBoxFromPoint(
const UsdPrim& prim,
const int id,
const std::vector<float>& times,
const void* userData,
RendererIndex& index) const
{
// Get the user data
const RendererPluginData* data =
reinterpret_cast<const RendererPluginData*>(userData);
assert(data);
UsdGeomPointInstancer instancer(prim);
float averageTime =
std::accumulate(times.begin(), times.end(), 0.0f) / times.size();
// Get prototype prim path (to set objectPath)
// [NOTE]: Not sure we should take the average time as the reference
// for point cloud topology...
VtIntArray protoIndices;
if (!instancer.GetProtoIndicesAttr().Get(&protoIndices, averageTime))
{
return nullptr;
}
SdfPathVector protoPaths;
instancer.GetPrototypesRel().GetTargets(&protoPaths);
const SdfPath& protoPath = protoPaths[protoIndices[id]];
// Form the name.
std::string name = data->prefix + ":" + protoPath.GetText() + ":proc_" +
std::to_string(id);
// Compute Xform from point
std::vector<float> xform;
xform.reserve(16 * times.size());
const UsdAttribute positionsAttr = instancer.GetPositionsAttr();
const UsdAttribute scalesAttr = instancer.GetScalesAttr();
const UsdAttribute orientationsAttr = instancer.GetOrientationsAttr();
for (const float time : times)
{
VtVec3fArray positions, scales;
VtQuathArray orientations;
scalesAttr.Get(&scales, static_cast<double>(time));
orientationsAttr.Get(&orientations, static_cast<double>(time));
positionsAttr.Get(&positions, static_cast<double>(time));
GfTransform xfo;
xfo.SetScale(scales[id]);
xfo.SetRotation(GfRotation(orientations[id]));
xfo.SetTranslation(positions[id]);
const double* matrixArray = xfo.GetMatrix().GetArray();
xform.insert(xform.end(), matrixArray, matrixArray + 16);
}
AtNode* node = createWalterProcedural(
data,
name,
times,
xform,
protoPath,
data->prefix);
outputPrimvars(prim, averageTime, node, nullptr, id);
return node;
}
void* RendererPlugin::outputReference(
const UsdPrim& prim,
const std::vector<float>& times,
const void* userData,
RendererIndex& index) const
{
assert(prim);
std::string name = prim.GetStage()->GetSessionLayer()->GetIdentifier() +
":" + prim.GetPath().GetText();
AtNode* node = nullptr;
if (prim.IsA<UsdGeomMesh>())
{
node = outputGeomMesh(prim, times, name.c_str(), userData);
}
else if (prim.IsA<UsdGeomCurves>())
{
node = outputGeomCurves(prim, times, name.c_str(), userData);
}
else if (prim.IsA<UsdShadeShader>())
{
node = outputShader(prim, times, name.c_str());
}
if (node)
{
// TODO: get rid of this. We don't support it.
static const std::string layer = "defaultRenderLayer";
SdfPath path = prim.GetPath();
// Walter overrides.
const NameToAttribute* attributes =
getAssignedAttributes(path, layer, userData, index, nullptr);
outputAttributes(node, path, attributes, index, layer, userData, true);
}
// Return node.
return node;
}
void RendererPlugin::establishConnections(
const UsdPrim& prim,
void* data,
RendererIndex& index) const
{
AtNode* node = reinterpret_cast<AtNode*>(data);
if (!prim.IsA<UsdShadeShader>())
{
return;
}
UsdShadeShader shader(prim);
for (const UsdShadeInput& input : shader.GetInputs())
{
UsdShadeConnectableAPI connectableAPISource;
TfToken sourceName;
UsdShadeAttributeType sourceType;
if (!UsdShadeConnectableAPI::GetConnectedSource(
input, &connectableAPISource, &sourceName, &sourceType))
{
continue;
}
std::string inputName = input.GetBaseName().GetString();
// Convert USD namespaces to Arnold components. We need it because we
// did conversion from Arnold components to USD namespaces in Alembic to
// USD plugin.
std::replace(inputName.begin(), inputName.end(), ':', '.');
RendererIndex::RenderNodeMap::const_accessor accessor;
if (!index.getRenderNodeData(
connectableAPISource.GetPrim().GetPath(), accessor))
{
continue;
}
AtNode* source = reinterpret_cast<AtNode*>(accessor->second);
if (sourceName.IsEmpty() || sourceName == "out")
{
AiNodeLink(source, inputName.c_str(), node);
}
else
{
// The difference between this and AiNodeLink is that a specific
// component can be selected for both the source output and the
// target input, so that the connection would only affect that
// component (the other components can be linked independently).
AiNodeLinkOutput(
source, sourceName.GetText(), node, inputName.c_str());
}
}
}
void* RendererPlugin::render(
const UsdPrim& prim,
const std::vector<float>& times,
void* renderData,
const void* userData,
RendererIndex& index) const
{
size_t keys = times.size();
std::vector<float> averageTime(
1, std::accumulate(times.begin(), times.end(), 0.0f) / keys);
// Get the user data
const RendererPluginData* data =
reinterpret_cast<const RendererPluginData*>(userData);
assert(data);
SdfPath primPath = prim.GetPath();
std::string name = data->prefix + ":" + primPath.GetText();
// TODO: get rid of this. We don't support it.
static const std::string layer = "defaultRenderLayer";
// We need to know if the object is visible before we create the node.
uint8_t visibility;
const NameToAttribute* attributes =
getAssignedAttributes(primPath, layer, userData, index, &visibility);
// We should also consider standard USD visibility flag.
UsdGeomImageable imageable = UsdGeomImageable(prim);
bool invisibleFromUSD = imageable &&
imageable.ComputeVisibility(averageTime[0]) == UsdGeomTokens->invisible;
bool canRender = imageable ?
imageable.ComputePurpose() != UsdGeomTokens->proxy &&
imageable.ComputePurpose() != UsdGeomTokens->guide :
true;
if (visibility == AI_RAY_UNDEFINED || invisibleFromUSD || !canRender)
{
// The object is not visible. Skip it.
TF_DEBUG(WALTER_ARNOLD_PLUGIN)
.Msg(
"[%s]: Skipping %s because it's not visible\n",
__FUNCTION__,
primPath.GetText());
return outputEmptyNode(name);
}
AtNode* node = AiNode("ginstance");
AiNodeSetStr(node, "name", name.c_str());
AiNodeSetPtr(node, "node", renderData);
// Make it visibile.
AiNodeSetByte(node, "visibility", visibility);
// All the attributes.
outputAttributes(node, primPath, attributes, index, layer, userData, false);
return node;
}
RendererAttribute RendererPlugin::createRendererAttribute(
const UsdAttribute& attr,
UsdTimeCode time) const
{
return usdAttributeToArnold(attr.GetBaseName(), attr, time);
}
AtNode* RendererPlugin::outputGeomMesh(
const UsdPrim& prim,
const std::vector<float>& times,
const char* name,
const void* userData) const
{
TF_DEBUG(WALTER_ARNOLD_PLUGIN)
.Msg("[%s]: Render: %s\n", __FUNCTION__, name);
size_t keys = times.size();
std::vector<float> averageTime(
1, std::accumulate(times.begin(), times.end(), 0.0f) / keys);
// Create a polymesh.
AtNode* node = AiNode("polymesh");
AiNodeSetStr(node, "name", name);
AiNodeSetBool(node, "smoothing", true);
AiNodeSetByte(node, "visibility", 0);
const RendererPluginData* data =
reinterpret_cast<const RendererPluginData*>(userData);
assert(data);
setMotionStartEnd(node, *data);
// Get mesh.
UsdGeomMesh mesh(prim);
// Get orientation.
bool reverse = false;
{
TfToken orientation;
if (mesh.GetOrientationAttr().Get(&orientation))
{
reverse = (orientation == UsdGeomTokens->leftHanded);
}
}
// Eval vertex counts of faces.
VtIntArray numVertsArray;
mesh.GetFaceVertexCountsAttr().Get(&numVertsArray, averageTime[0]);
// Type conversion
{
std::vector<unsigned char> numVertsVec(
numVertsArray.begin(), numVertsArray.end());
AiNodeSetArray(
node,
"nsides",
AiArrayConvert(
numVertsVec.size(), 1, AI_TYPE_BYTE, &(numVertsVec[0])));
}
// TODO: output motion samples only if they exist.
// Vertex indices
attributeArrayToArnold<unsigned int, int>(
mesh.GetFaceVertexIndicesAttr(),
node,
"vidxs",
AI_TYPE_UINT,
averageTime,
reverse ? &numVertsArray : nullptr);
// Eval points.
attributeArrayToArnold<GfVec3f, GfVec3f>(
mesh.GetPointsAttr(),
node,
"vlist",
AI_TYPE_VECTOR,
times,
nullptr);
// Output normals.
size_t numNormals = attributeArrayToArnold<GfVec3f, GfVec3f>(
mesh.GetNormalsAttr(), node, "nlist", AI_TYPE_VECTOR, times, nullptr);
if (numNormals)
{
// Generate a range with sequentially increasing values and use them as
// normal indexes.
std::vector<unsigned int> normIdxArray(numNormals);
std::iota(normIdxArray.begin(), normIdxArray.end(), 0);
if (reverse)
{
reverseFaceAttribute(normIdxArray, numVertsArray);
}
AiNodeSetArray(
node,
"nidxs",
AiArrayConvert(
normIdxArray.size(), 1, AI_TYPE_UINT, normIdxArray.data()));
}
outputPrimvars(
prim, averageTime[0], node, reverse ? &numVertsArray : nullptr);
// Return node.
return node;
}
AtNode* RendererPlugin::outputGeomCurves(
const UsdPrim& prim,
const std::vector<float>& times,
const char* name,
const void* userData) const
{
TF_DEBUG(WALTER_ARNOLD_PLUGIN)
.Msg("[%s]: Render: %s\n", __FUNCTION__, name);
size_t keys = times.size();
std::vector<float> averageTime(
1, std::accumulate(times.begin(), times.end(), 0.0f) / keys);
// Create curves.
AtNode* node = AiNode("curves");
AiNodeSetStr(node, "name", name);
AiNodeSetByte(node, "visibility", 0);
const RendererPluginData* data =
reinterpret_cast<const RendererPluginData*>(userData);
assert(data);
setMotionStartEnd(node, *data);
// Get the basis. From the Arnold docs: Can choose from Bezier, B-Spline,
// Catmull-Rom, Linear.
int basis = 3;
if (prim.IsA<UsdGeomBasisCurves>())
{
// TODO: use a scope_pointer for curves and basisCurves.
UsdGeomBasisCurves basisCurves(prim);
TfToken curveType;
basisCurves.GetTypeAttr().Get(&curveType, averageTime[0]);
if (curveType == UsdGeomTokens->cubic)
{
TfToken basisType;
basisCurves.GetBasisAttr().Get(&basisType, averageTime[0]);
if (basisType == UsdGeomTokens->bezier)
{
basis = 0;
}
else if (basisType == UsdGeomTokens->bspline)
{
basis = 1;
}
else if (basisType == UsdGeomTokens->catmullRom)
{
basis = 2;
}
}
}
AiNodeSetInt(node, "basis", basis);
// Get curves.
UsdGeomCurves curves(prim);
// Eval vertex counts of faces.
attributeArrayToArnold<int, int>(
curves.GetCurveVertexCountsAttr(),
node,
"num_points",
AI_TYPE_UINT,
times,
nullptr);
// TODO: output motion samples only if they exist.
// Eval points.
attributeArrayToArnold<GfVec3f, GfVec3f>(
curves.GetPointsAttr(),
node,
"points",
AI_TYPE_VECTOR,
times,
nullptr);
// Eval widths.
attributeArrayToArnold<float, float>(
curves.GetWidthsAttr(), node, "radius", AI_TYPE_FLOAT, times, nullptr);
outputPrimvars(prim, averageTime[0], node, nullptr);
// Return node.
return node;
}
AtNode* RendererPlugin::outputShader(
const UsdPrim& prim,
const std::vector<float>& times,
const char* name) const
{
if (!prim.IsA<UsdShadeShader>())
{
return nullptr;
}
size_t keys = times.size();
std::vector<float> averageTime(
1, std::accumulate(times.begin(), times.end(), 0.0f) / keys);
// Check if it's an Arnold shader.
UsdAttribute shaderTargetAttr = prim.GetAttribute(TfToken("info:target"));
TfToken shaderTarget;
shaderTargetAttr.Get(&shaderTarget, averageTime[0]);
if (shaderTarget != "arnold")
{
return nullptr;
}
UsdAttribute shaderTypeAttr = prim.GetAttribute(TfToken("info:type"));
TfToken shaderType;
shaderTypeAttr.Get(&shaderType, averageTime[0]);
// Create shader.
AtNode* node = AiNode(shaderType.GetText());
// Set the name
AiNodeSetStr(node, "name", name);
// Output XForm
static const char* matrix = "matrix";
if (getArnoldParameter(node, matrix))
{
std::vector<float> xform = getPrimTransform(prim, times);
if (!xform.empty())
{
// 16 is the size of regular matrix 4x4
// TODO: output motion samples only if they exist.
AiNodeSetArray(
node,
matrix,
AiArrayConvert(
1, xform.size() / 16, AI_TYPE_MATRIX, xform.data()));
}
}
// Iterate all the paramters.
for (const UsdAttribute& attr : prim.GetAttributes())
{
if (!attr.GetNamespace().IsEmpty())
{
continue;
}
const TfToken parameterName = attr.GetName();
if (parameterName == "name")
{
// Skip parameter with name "name" because it will rename the node.
continue;
}
RendererAttribute rndAttr = usdAttributeToArnold(
parameterName.GetString(), attr, averageTime[0]);
rndAttr.evaluate(node);
}
return node;
}
void RendererPlugin::outputPrimvars(
const UsdPrim& prim,
float time,
AtNode* node,
const VtIntArray* numVertsArray,
const int pointInstanceId) const
{
assert(prim);
UsdGeomImageable imageable = UsdGeomImageable(prim);
assert(imageable);
for (const UsdGeomPrimvar& primvar : imageable.GetPrimvars())
{
TfToken name;
SdfValueTypeName typeName;
TfToken interpolation;
int elementSize;
primvar.GetDeclarationInfo(
&name, &typeName, &interpolation, &elementSize);
if (pointInstanceId > -1)
{
assert(interpolation == UsdGeomTokens->uniform);
interpolation = UsdGeomTokens->constant;
}
// Resolve the value
VtValue vtValue;
VtIntArray vtIndices;
if (interpolation == UsdGeomTokens->constant)
{
if (!primvar.Get(&vtValue, time))
{
continue;
}
}
else if (interpolation == UsdGeomTokens->faceVarying && primvar.IsIndexed())
{
// It's an indexed value. We don't want to flatten it because it
// breaks subdivs.
if (!primvar.Get(&vtValue, time))
{
continue;
}
if (!primvar.GetIndices(&vtIndices, time))
{
continue;
}
}
else
{
// USD comments suggest using using the ComputeFlattened() API
// instead of Get even if they produce the same data.
if (!primvar.ComputeFlattened(&vtValue, time))
{
continue;
}
}
if (vtToArnold<GfVec2f>(
vtValue,
vtIndices,
name,
typeName,
interpolation,
node,
numVertsArray,
pointInstanceId))
{ /* Nothing to do */
}
else if (vtToArnold<GfVec3f>(
vtValue,
vtIndices,
name,
typeName,
interpolation,
node,
numVertsArray,
pointInstanceId))
{ /* Nothing to do */
}
else if (vtToArnold<float>(
vtValue,
vtIndices,
name,
typeName,
interpolation,
node,
numVertsArray,
pointInstanceId))
{ /* Nothing to do */
}
else if (vtToArnold<int>(
vtValue,
vtIndices,
name,
typeName,
interpolation,
node,
numVertsArray,
pointInstanceId))
{ /* Nothing to do */
}
}
}
const NameToAttribute* RendererPlugin::getAssignedAttributes(
const SdfPath& path,
const std::string& layer,
const void* userData,
RendererIndex& index,
uint8_t* oVisibility) const
{
const std::string& prefix =
reinterpret_cast<const RendererPluginData*>(userData)->prefix;
// Form the full path considering instancing that is good for expression
// resolving. The first part is saved in the index. The second part is the
// cuurent USD path.
std::string virtualObjectName =
joinPaths(index.getPrefixPath(prefix), path);
uint8_t visibility = AI_RAY_ALL;
// Get attributes.
const NameToAttribute* attributes =
index.getObjectAttribute(virtualObjectName, layer);
// Compute the visibility.
if (attributes && oVisibility)
{
for (const auto& attr : *attributes)
{
if (attr.second.isVisibility())
{
// Combine all the visibilities to the single attribute.
visibility &= attr.second.visibilityFlag();
}
}
*oVisibility = visibility;
}
return attributes;
}
void RendererPlugin::outputAttributes(
AtNode* node,
const SdfPath& path,
const NameToAttribute* attributes,
RendererIndex& index,
const std::string& layer,
const void* userData,
bool forReference) const
{
const std::string& prefix =
reinterpret_cast<const RendererPluginData*>(userData)->prefix;
// Output attributes to Arnold.
if (forReference && attributes)
{
// TODO: Query parents, get attributes right from the USD Prim.
// Get attributes.
if (attributes)
{
for (const auto& attr : *attributes)
{
attr.second.evaluate(node);
}
}
}
// Form the full path considering instancing that is good for expression
// resolving. The first part is saved in the index. The second part is the
// cuurent USD path.
std::string virtualObjectName =
joinPaths(index.getPrefixPath(prefix), path);
if (forReference)
{
// Set the displacement.
outputShadingAttribute(
node, virtualObjectName, index, layer, "displacement");
}
else
{
// Set the shader.
outputShadingAttribute(node, virtualObjectName, index, layer, "shader");
}
}
void RendererPlugin::outputShadingAttribute(
AtNode* node,
const std::string& objectName,
RendererIndex& index,
const std::string& layer,
const std::string& target) const
{
// Get shader
SdfPath shaderPath = index.getShaderAssignment(objectName, layer, target);
if (shaderPath.IsEmpty())
{
return;
}
bool isDisplacement = target == "displacement";
RendererIndex::RenderNodeMap::accessor accessor;
bool newEntry = index.getRenderNodeData(shaderPath, accessor);
if (newEntry)
{
// We are here if getRenderNodeData created a new entry.
// Try to find the node in Arnold nodes on the case the node was
// created in the maya scene, and it was not exported to USD or
// Alembic.
// TODO: It's not an effective way. It's much better to export all
// the necessary nodes to the session layer. But it's much more
// complicated.
AtNode* shaderNode = AiNodeLookUpByName(shaderPath.GetText());
if (!shaderNode && isDisplacement)
{
// MTOA adds ".message" to the displacement nodes.
shaderPath = shaderPath.AppendProperty(TfToken("message"));
// Try again with a new name.
shaderNode = AiNodeLookUpByName(shaderPath.GetText());
}
if (shaderNode)
{
accessor->second = shaderNode;
}
}
// Read and release the accessor.
void* shaderData = accessor->second;
accessor.release();
if (shaderData)
{
std::string arrayName = isDisplacement ? "disp_map" : target;
AtArray* shaders = AiArrayAllocate(1, 1, AI_TYPE_NODE);
AiArraySetPtr(shaders, 0, shaderData);
AiNodeSetArray(node, arrayName.c_str(), shaders);
}
}
void* RendererPlugin::outputEmptyNode(const std::string& iNodeName) const
{
// Output a very small point that is visible only for volume rays
static const float points[] = {0.0f, 0.0f, 0.0f};
static const float radius[] = {1e-9f};
AtNode* node = AiNode("points");
AiNodeSetStr(node, "name", iNodeName.c_str());
AiNodeSetByte(node, "visibility", AI_RAY_VOLUME);
AiNodeSetByte(node, "sidedness", AI_RAY_UNDEFINED);
AiNodeSetArray(
node,
"points",
AiArrayConvert(
sizeof(points) / sizeof(points[0]) / 3, 1, AI_TYPE_VECTOR, points));
AiNodeSetArray(
node,
"radius",
AiArrayConvert(
sizeof(radius) / sizeof(radius[0]), 1, AI_TYPE_FLOAT, radius));
return node;
}
<|start_filename|>walter/maya/walterMtoaConnection/mtoaScene.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __MTOASCENE_H_
#define __MTOASCENE_H_
#include <translators/NodeTranslator.h>
#include "mtoaVersion.h"
#include <unordered_set>
typedef std::unordered_set<AtNode*> AtNodeSet;
// Since MTOA 1.4 files like CMayaScene, CArnoldSession, CRenderSession are no
// longer part of the API. But they are necessary to save Arnold shading
// network. This class contains all the communication with CMayaScene etc. In
// the case the MTOA is less than 1.4, we access CMayaScene directly. Otherwise,
// we are trying to load the symbols from the shared library and use them.
class MTOAScene {
public:
MTOAScene();
~MTOAScene();
// Export given plug to Arnold shading networks using MTOA. The root
// nodes are added to the AtNodeSet. If current MTOA is 2.1, `nodes` is
// never changed.
CNodeTranslator* exportNode(const MPlug& plug, AtNodeSet* nodes);
private:
void *fSession;
// Pointer to CMayaScene::End()
MStatus (*mEnd)();
// Pointer to
// CNodeTranslator* CArnoldSession::ExportNode(
// const MPlug& shaderOutputPlug,
// AtNodeSet* nodes=NULL,
// AOVSet* aovs=NULL,
// bool initOnly=false,
// int instanceNumber = -1,
// MStatus* stat=NULL);
// Available in MTOA 2.0
CNodeTranslator* (*mExportNode)(
void*, const MPlug&, AtNodeSet*, void*, bool, int, void*);
// Pointer to
// CNodeTranslator* CArnoldSession::ExportNode(
// const MPlug& shaderOutputPlug,
// bool initOnly,
// int instanceNumber,
// MStatus* stat)
// Available in MTOA 2.1
CNodeTranslator* (*mExportNodeA)(void*, const MPlug&, bool, int, void*);
};
#endif
<|start_filename|>walter/cmake/FindMaya.cmake<|end_filename|>
# - Maya finder module
# This module searches for a valid Maya instalation, including its devkit,
# libraries, executables and related paths (scripts).
#
# Useful environment variables:
# MAYA_LOCATION If defined in the shell environment, the contents
# of this variable will be used as the first search
# path for the Maya installation.
#
# Output variables:
# MAYA_FOUND Defined if a Maya installation has been detected
# MAYA_EXECUTABLE Path to Maya's executable
# MAYA_VERSION Version of Maya determined from MAYA_EXECUTABLE (20xx)
# MAYA_LIBRARIES List of all Maya libraries that are found
# MAYA_<lib>_FOUND Defined if <lib> has been found
# MAYA_<lib>_LIBRARY Path to <lib> library
# MAYA_INCLUDE_DIRS Path to the devkit's include directories
# MAYA_LIBRARY_DIRS Path to the library directory
# MAYA_PLUGIN_SUFFIX File extension for the maya plugin
# MAYA_QT_VERSION_SHORT Version of Qt used by Maya (e.g. 4.7)
# MAYA_QT_VERSION_LONG Full version of Qt used by Maya (e.g. 4.7.1)
#
# Deprecated output variables:
# MAYA_LIBRARY_DIR Superseded by MAYA_LIBRARY_DIRS
# MAYA_INCLUDE_DIR Superseded by MAYA_INCLUDE_DIRS
#
# Macros provided:
# MAYA_SET_PLUGIN_PROPERTIES Passed the target name, this sets up typical
# plugin properties like macro defines, prefixes,
# and suffixes.
#
# Naming conventions:
# Local variables of the form _maya_foo
# Input variables from CMake of the form Maya_FOO
# Output variables of the form MAYA_FOO
#
#=============================================================================
# Macros
#=============================================================================
# Macro for setting up typical plugin properties. These include:
# - OS-specific plugin suffix (.mll, .so, .bundle)
# - Removal of 'lib' prefix on osx/linux
# - OS-specific defines
# - Post-commnad for correcting Qt library linking on osx
# - Windows link flags for exporting initializePlugin/uninitializePlugin
macro(MAYA_SET_TRANSLATOR_PROPERTIES target)
set(_maya_DEFINES REQUIRE_IOSTREAM _BOOL)
if(APPLE)
set(_maya_DEFINES "${_maya_DEFINES}" _DARWIN MAC_PLUGIN OSMac_ OSMac_MachO)
if(QT_LIBRARIES)
set(_changes "")
foreach(_lib ${QT_LIBRARIES})
if("${_lib}" MATCHES ".*framework.*")
get_filename_component(_shortname ${_lib} NAME)
string(REPLACE ".framework" "" _shortname ${_shortname})
# FIXME: QT_LIBRARIES does not provide the entire path to the lib.
# it provides /usr/local/qt/4.7.2/lib/QtGui.framework
# but we need /usr/local/qt/4.7.2/lib/QtGui.framework/Versions/4/QtGui
# below is a hack, likely to break on other configurations
set(_changes ${_changes} "-change" "${_lib}/Versions/4/${_shortname}" "@executable_path/${_shortname}")
endif()
endforeach()
add_custom_command(TARGET ${target}
POST_BUILD
COMMAND install_name_tool ${_changes} $<TARGET_FILE:${target}>)
endif()
elseif(WIN32)
set(_maya_DEFINES "${_maya_DEFINES}" _AFXDLL _MBCS NT_PLUGIN)
else()
set(_maya_DEFINES "${_maya_DEFINES}" LINUX LINUX_64)
endif()
target_compile_definitions(${target} PUBLIC ${_maya_DEFINES})
target_include_directories(${target} PUBLIC ${MAYA_INCLUDE_DIRS})
endmacro(MAYA_SET_TRANSLATOR_PROPERTIES)
macro(MAYA_SET_PLUGIN_PROPERTIES target)
set_target_properties(${target} PROPERTIES
SUFFIX ${MAYA_PLUGIN_SUFFIX})
set(_maya_DEFINES REQUIRE_IOSTREAM _BOOL)
if(APPLE)
set(_maya_DEFINES "${_maya_DEFINES}" _DARWIN MAC_PLUGIN OSMac_ OSMac_MachO)
if(QT_LIBRARIES)
set(_changes "")
foreach(_lib ${QT_LIBRARIES})
if("${_lib}" MATCHES ".*framework.*")
get_filename_component(_shortname ${_lib} NAME)
string(REPLACE ".framework" "" _shortname ${_shortname})
# FIXME: QT_LIBRARIES does not provide the entire path to the lib.
# it provides /usr/local/qt/4.7.2/lib/QtGui.framework
# but we need /usr/local/qt/4.7.2/lib/QtGui.framework/Versions/4/QtGui
# below is a hack, likely to break on other configurations
set(_changes ${_changes} "-change" "${_lib}/Versions/4/${_shortname}" "@executable_path/${_shortname}")
endif()
endforeach()
add_custom_command(TARGET ${target}
POST_BUILD
COMMAND install_name_tool ${_changes} $<TARGET_FILE:${target}>)
endif()
elseif(WIN32)
set(_maya_DEFINES "${_maya_DEFINES}" _AFXDLL _MBCS NT_PLUGIN)
set_target_properties( ${target} PROPERTIES
LINK_FLAGS "/export:initializePlugin /export:uninitializePlugin")
else()
set(_maya_DEFINES "${_maya_DEFINES}" LINUX LINUX_64)
endif()
target_compile_definitions(${target} PUBLIC ${_maya_DEFINES})
target_include_directories(${target} PUBLIC ${MAYA_INCLUDE_DIRS})
endmacro(MAYA_SET_PLUGIN_PROPERTIES)
set(_maya_TEST_VERSIONS)
if(APPLE)
set(MAYA_PLUGIN_SUFFIX ".bundle")
elseif(WIN32)
set(MAYA_PLUGIN_SUFFIX ".mll")
else() #LINUX
set(MAYA_PLUGIN_SUFFIX ".so")
endif()
# generate list of versions to test
if(Maya_FIND_VERSION_EXACT)
list(APPEND _maya_TEST_VERSIONS "${Maya_FIND_VERSION}")
else()
# exact version not requested. we have some wiggle room
if(Maya_FIND_VERSION)
# loop through known versions and find anything >= requested
foreach(version ${_maya_KNOWN_VERSIONS})
if(NOT "${version}" VERSION_LESS "${Maya_FIND_VERSION}")
list(APPEND _maya_TEST_VERSIONS "${version}")
endif()
endforeach()
else()
# no version specified: test everything
set(_maya_TEST_VERSIONS ${_maya_KNOWN_VERSIONS})
endif()
endif()
# create empty list
set(_maya_TEST_PATHS)
# from version list, generate list of paths to test based on canonical locations
foreach(version ${_maya_TEST_VERSIONS})
if(APPLE)
list(APPEND _maya_TEST_PATHS "/Applications/Autodesk/maya${version}/Maya.app/Contents")
elseif(WIN32)
set(_maya_TEST_PATHS ${_maya_TEST_PATHS}
"$ENV{PROGRAMFILES}/Autodesk/Maya${version}-x64"
"$ENV{PROGRAMFILES}/Autodesk/Maya${version}"
"C:/Program Files/Autodesk/Maya${version}-x64"
"C:/Program Files/Autodesk/Maya${version}"
"C:/Program Files (x86)/Autodesk/Maya${version}")
else() #Linux
set(_maya_TEST_PATHS ${_maya_TEST_PATHS} ${MAYA_LOCATION})
# "/softwareLocal/maya/linux/Maya2016SP4/maya2016-x64")
endif()
endforeach(version)
# search for maya executable within the MAYA_LOCATION and PATH env vars and test paths
find_program(MAYA_EXECUTABLE maya
PATHS ${MAYA_LOCATION}/bin
DOC "Maya's executable path")
string(REGEX REPLACE "/bin/maya.*" "" MAYA_LOCATION "${MAYA_EXECUTABLE}")
string(REGEX MATCH "20[0-9][0-9]" MAYA_VERSION "${MAYA_LOCATION}")
if(Maya_FIND_VERSION)
# test that we've found a valid version
list(FIND _maya_TEST_VERSIONS ${MAYA_VERSION} _maya_FOUND_INDEX)
if(${_maya_FOUND_INDEX} EQUAL -1)
message(STATUS "Found Maya version ${MAYA_VERSION}, but requested at least ${Maya_FIND_VERSION}. Re-searching without environment variables...")
set(MAYA_LOCATION NOTFOUND)
# search again, but don't use environment variables
# (these should be only paths we constructed based on requested version)
find_path(MAYA_LOCATION maya
PATHS ${_maya_TEST_PATHS}
PATH_SUFFIXES bin
DOC "Maya's Base Directory"
NO_SYSTEM_ENVIRONMENT_PATH)
set(MAYA_EXECUTABLE "${MAYA_LOCATION}/bin/maya"
CACHE PATH "Maya's executable path")
string(REGEX MATCH "20[0-9][0-9]" MAYA_VERSION "${MAYA_LOCATION}")
#ELSE: error?
endif()
endif()
# NOTE: the MAYA_LOCATION environment variable is often misunderstood. On every OS it is expected to point
# directly above bin/maya. Relative paths from $MAYA_LOCATION to include, lib, and devkit directories vary depending on OS.
# We don't use environment variables below this point to lessen the risk of finding incompatible versions of
# libraries and includes (it could happen with highly non-standard configurations; i.e. maya libs in /usr/local/lib or on
# CMAKE_LIBRARY_PATH, CMAKE_INCLUDE_PATH, CMAKE_PREFIX_PATH).
# - If the maya executable is found in a standard location, or in $MAYA_LOCATION/bin or $PATH, and the
# includes and libs are in standard locations relative to the binary, they will be found
message(STATUS "Maya location: ${MAYA_LOCATION}")
find_path(MAYA_INCLUDE_DIRS maya/MFn.h
HINTS ${MAYA_LOCATION}
PATH_SUFFIXES
include # linux and windows
../../devkit/include # osx
devkit/include # linux
DOC "Maya's include path")
find_path(MAYA_LIBRARY_DIRS libOpenMaya.dylib libOpenMaya.so OpenMaya.lib
HINTS ${MAYA_LOCATION}
PATH_SUFFIXES
lib # linux and windows
MacOS # osx
DOC "Maya's library path")
# Set deprecated variables to avoid compatibility breaks
set(MAYA_INCLUDE_DIR ${MAYA_INCLUDE_DIRS})
set(MAYA_LIBRARY_DIR ${MAYA_LIBRARY_DIRS})
foreach(_maya_lib
OpenMaya
OpenMayaAnim
OpenMayaFX
OpenMayaRender
OpenMayaUI
Image
Foundation)
# cg
# cgGL
# HINTS is searched before PATHS, so preference is given to MAYA_LOCATION
# (set via MAYA_EXECUTABLE)
if(APPLE)
find_library(MAYA_${_maya_lib}_LIBRARY ${_maya_lib}
HINTS ${MAYA_LOCATION}
PATHS ${_maya_TEST_PATHS}
PATH_SUFFIXES MacOS
# This must be used or else Foundation.framework will be found instead of libFoundation
NO_CMAKE_SYSTEM_PATH
DOC "Maya's ${MAYA_LIB} library path")
else()
find_library(MAYA_${_maya_lib}_LIBRARY ${_maya_lib}
HINTS ${MAYA_LOCATION}
PATHS ${_maya_TEST_PATHS}
PATH_SUFFIXES lib # linux and windows
DOC "Maya's ${MAYA_LIB} library path")
endif()
list(APPEND MAYA_LIBRARIES ${MAYA_${_maya_lib}_LIBRARY})
endforeach()
find_path(MAYA_USER_DIR
NAMES ${MAYA_VERSION}-x64 ${MAYA_VERSION}
PATHS
$ENV{HOME}/Library/Preferences/Autodesk/maya # osx
$ENV{USERPROFILE}/Documents/maya # windows
$ENV{HOME}/maya # linux
DOC "Maya user home directory"
NO_SYSTEM_ENVIRONMENT_PATH)
# if (Maya_FOUND)
# if (NOT Maya_FIND_QUIETLY)
# message(STATUS "Maya version: ${Maya_MAJOR_VERSION}.${Maya_MINOR_VERSION}.${Maya_SUBMINOR_VERSION}")
# endif()
# if (NOT Maya_FIND_QUIETLY)
# message(STATUS "Found the following Maya libraries:")
# endif()
# foreach(COMPONENT ${Maya_FIND_COMPONENTS})
# string(TOUPPER ${COMPONENT} UPPERCOMPONENT)
# if(Maya_${UPPERCOMPONENT}_FOUND)
# if(NOT Maya_FIND_QUIETLY)
# message(STATUS " ${COMPONENT}")
# endif()
# set(Maya_LIBRARIES ${Maya_LIBRARIES} ${Maya_${UPPERCOMPONENT}_LIBRARY})
# endif()
# endforeach()
# else()
# if(Maya_FIND_REQUIRED)
# message(SEND_ERROR "Unable to find the requested Maya libraries.\n${Maya_ERROR_REASON}")
# endif()
# endif()
# Handles the QUIETLY and REQUIRED arguments and sets MAYA_FOUND to TRUE if
# all passed variables are TRUE
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Maya DEFAULT_MSG
MAYA_LIBRARIES MAYA_EXECUTABLE MAYA_INCLUDE_DIRS
MAYA_LIBRARY_DIRS MAYA_VERSION MAYA_PLUGIN_SUFFIX
MAYA_USER_DIR)
#
# Copyright 2012, <NAME>
#
# vfxcmake is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# vfxcmake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with vfxcmake. If not, see <http://www.gnu.org/licenses/>.
#
<|start_filename|>walter/maya/walterStandin/walterOverrideNode.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterOverrideNode.h"
#include <assert.h>
#include <maya/MFnDagNode.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MGlobal.h>
#include <maya/MMessage.h>
#include <maya/MNodeMessage.h>
MTypeId WalterOverride::mId(0x00128540);
// If a problem occurs, this function returns an empty string.
MString getNameFromObj(MObject obj)
{
MString nodeName;
// If this object is a MFnDagNode, we should store the dag name.
// Otherwise, use the MFnDependencyNode name.
if (obj.hasFn(MFn::kDagNode))
{
MFnDagNode dagNode(obj);
nodeName = dagNode.fullPathName();
}
else if (obj.hasFn(MFn::kDependencyNode))
{
MFnDependencyNode node(obj);
nodeName = node.name();
}
return nodeName;
}
WalterOverride::WalterOverride()
{
}
WalterOverride::~WalterOverride()
{
}
void* WalterOverride::creator()
{
return new WalterOverride();
}
MStatus WalterOverride::initialize()
{
return MS::kSuccess;
}
void WalterOverride::postConstructor()
{
MObject mobj = thisMObject();
MFnDependencyNode dep_node(mobj);
// Set the default node name.
MString defaultname = typeName() + "#";
// Save the digit in the node name.
if( isdigit( defaultname.asChar()[0] ) )
{
defaultname = "_" + defaultname;
}
dep_node.setName(defaultname);
// We are unable to call initialize MEL proc because the node is not
// initialized by maya proprly but we use "#" in the default node name, it
// means the name will be changed as soon as the node will be completely
// initialized. The DL_genericShadingNode::nameChanged() will immediately
// remove this callback.
MNodeMessage::addNameChangedCallback(mobj, nameChanged, nullptr);
}
void WalterOverride::nameChanged(MObject& node, void *data)
{
// We need this function only once, so immediately remove current callback.
MMessage::removeCallback(MMessage::currentCallbackId());
// Current node.
MString name = getNameFromObj(node);
// Call initialize python proc.
MString cmd =
"AEwalterOverrideTemplate.walterOverrideInitialize('" +
name +
"')";
MGlobal::executePythonCommandOnIdle(cmd);
}
<|start_filename|>walter/usd/walterUSDCommonUtils.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERUSDCOMMONUTILS_H__
#define __WALTERUSDCOMMONUTILS_H__
#include "pxr/usd/sdf/layer.h"
#include "pxr/usd/usd/stage.h"
#include <string>
#include <vector>
PXR_NAMESPACE_USING_DIRECTIVE
namespace WalterUSDCommonUtils
{
/**
* @brief Compose and open several usd layers.
*
* @param path One or several USD layers separated with ":" symbol.
*
* @return The pointer to the new layer.
*/
SdfLayerRefPtr getUSDLayer(const std::string& path);
/**
* @brief Compose and open several usd layers.
*
* @param paths One or several USD layes as a vector.
*
* @return The pointer to the new layer.
*/
SdfLayerRefPtr getUSDLayer(const std::vector<std::string>& paths);
/**
* @brief Creates or returns an anonymous layer that can be used to modify the
* stage.
*
* @param stage The stage to modify. The layer will be created on the front of
* this stage.
* @param name The name of the layer. If the stage already contains the layer
* with requeted name, this layer will be returned.
*
* @return The created or existed USD layer.
*/
SdfLayerRefPtr getAnonymousLayer(UsdStageRefPtr stage, const std::string& name);
/**
* @brief Gets or creates the variants layer and sets its content from external
* references (e.g Maya scene).
*
* @param stage The USD stage.
* @param variants The variants list (in a flat string).
*
* @return True if succeded, false otherwise.
*/
bool setUSDVariantsLayer(UsdStageRefPtr stage, const char* variants);
/**
* @brief Gets or creates the purpose layer and sets its content from external
* references (e.g Maya scene).
*
* @param stage The USD stage.
* @param purpose The purpose list (in a flat string).
*
* @return True if succeded, false otherwise.
*/
bool setUSDPurposeLayer(UsdStageRefPtr stage, const char* purpose);
/**
* @brief Gets or creates the visibility layer and sets its content from external
* references (e.g Maya scene).
*
* @param stage The USD stage.
* @param visibility The visibility list (in a flat string).
*
* @return True if succeded, false otherwise.
*/
bool setUSDVisibilityLayer(UsdStageRefPtr stage, const char* visibility);
/**
* @brief Constructs the variant layer.
*
* @param stage The USD stage.
*
* @return The variants list in a flat string.
*/
std::string getVariantsLayerAsText(UsdStageRefPtr stage);
/**
* @brief Constructs the visibility layer.
*
* @param stage The USD stage.
*
* @return The visibility list in a flat string.
*/
std::string getVisibilityLayerAsText(UsdStageRefPtr stage);
/**
* @brief Constructs the purpose layer.
*
* @param stage The USD stage.
*
* @return The purpose list in a flat string.
*/
std::string getPurposeLayerAsText(UsdStageRefPtr stage);
/**
* @brief Fills result with the names of the primitive children.
*
* @param stage The USD stage.
* @param primPath The primitive path (as string).
*
* @return The children names (as string array).
*/
std::vector<std::string> dirUSD(UsdStageRefPtr stage, const char* primPath);
/**
* @brief Fills result array with names/values of properties (USD attributes
* and/or relationships) of the primitive at path primPath.
*
* @param stage The USD stage.
* @param primPath The primitive path (as string).
* @param time The time.
* @param attributeOnly If true, only attributes properties (no relation-ship)
* will be extracted.
*
* @return The properties (as an array of json).
*/
std::vector<std::string> propertiesUSD(
UsdStageRefPtr stage,
const char* primPath,
double time,
bool attributeOnly = true);
/**
* @brief Fills result with all the USD variants of the stage.
*
* @param stage The USD stage.
* @param primPath The primitive path (as string).
*
* @return The variants list (as an array of json).
*/
std::vector<std::string> getVariantsUSD(
UsdStageRefPtr stage,
const char* primPath = "",
bool recursively = false);
/**
* @brief Sets the variants of the primitive at path primPath.
*
* @param stage The USD stage.
* @param primPath The primitive path (as string).
* @param variantName The variants name.
* @param variantSetName The variant set name.
*
*/
void setVariantUSD(
UsdStageRefPtr stage,
const char* primPath,
const char* variantName,
const char* variantSetName);
/**
* @brief Sets the variants of the primitive at path primPath.
*
* @param stage The USD stage.
* @param variantDefStr flat representation
* (primPath{variantSetName=variantName}).
*
*/
void setVariantUSD(UsdStageRefPtr stage, const char* variantDefStr);
/**
* @brief Gets the names/values of USD primVars attributes
* of the primitive at path primPath.
*
* @param stage The USD stage.
* @param primPath The primitive path (as an array of json).
* @param time The time.
*
* @return The properties (as string array).
*/
std::vector<std::string> primVarUSD(
UsdStageRefPtr stage,
const char* primPath,
double time);
/**
* @brief Checks that the prim at path is a USD pseudo root.
*
* @param stage The USD stage.
* @param primPath The primitive path.
*
* @return True if the prim at path is a pseudo-root, false otherwise.
*/
bool isPseudoRoot(
UsdStageRefPtr stage,
const char* primPath);
/**
* @brief Toggles the visibility state (show, hidden) of the prim.
*
* @param stage The USD stage.
* @param primPath The primitive path.
*
* @return True if the prim at path is visible, false otherwise.
*/
bool toggleVisibility(
UsdStageRefPtr stage,
const char* primPath);
/**
* @brief Sets the visibility state (show, hidden) of the prim.
*
* @param stage The USD stage.
* @param primPath The primitive path.
*
* @return True if the prim at path is visible, false otherwise.
*/
bool setVisibility(
UsdStageRefPtr stage,
const char* primPath,
bool visible);
/**
* @brief Checks if the prim at path is visible
*
* @param stage The USD stage.
* @param primPath The primitive path.
*
* @return True if the prim is visible, false otherwise.
*/
bool isVisible(
UsdStageRefPtr stage,
const char* primPath);
/**
* @brief Hides all the prims stage execpted the primitive at path.
*
* @param stage The USD stage.
* @param primPath The primitive path.
*
* @return True if the prim at path is visible, false otherwise.
*/
bool hideAllExceptedThis(
UsdStageRefPtr stage,
const char* primPath);
/**
* @brief Check that the regex expression matchs a least one USD prim path
* primitive at path primPath.
*
* @param stage The USD stage.
* @param expression The primitive path (as an array of json).
*
* @return True if there is a match, false otherwise.
*/
bool expressionIsMatching(
UsdStageRefPtr stage,
const char* expression);
/**
* @brief Gets the list of primitives matching the expression.
*
* @param stage The USD stage.
* @param expression A regex expression.
*
* @return A vector of USD prims.
*/
std::vector<UsdPrim> primsMatchingExpression(
UsdStageRefPtr stage,
const char* expression);
/**
* @brief Gets the list of primitives path matching the expression.
*
* @param stage The USD stage.
* @param expression A regex expression.
*
* @return A vector of USD prims path (string).
*/
std::vector<std::string> primPathsMatchingExpression(
UsdStageRefPtr stage,
const char* expression);
/**
* @brief Sets the prim purpose token (default, render, proxy, guide).
*
* @param stage The USD stage.
* @param primPath The primitive path.
* @param purpose The purpose token.
*
* @return The purpose token (as string)
*/
std::string setPurpose(
UsdStageRefPtr stage,
const char* primPath,
const char* purpose);
/**
* @brief Gets the prim purpose token.
*
* @param stage The USD stage.
* @param primPath The primitive path.
*
* @return The purpose token (as string)
*/
std::string purpose(
UsdStageRefPtr stage,
const char* primPath);
/**
* @brief Store information for a master primitive, like the name of the
* primitive it describe and the list of variant selection of it.
*/
struct MasterPrimInfo
{
std::string realName;
std::vector<std::string> variantsSelection;
bool isEmpty() { return realName == ""; }
};
typedef std::unordered_map<std::string, MasterPrimInfo> MastersInfoMap;
/**
* @brief Gets the binding between master primitive name and their
* information such that the name of the primitive it represents and the
* variants selection used to build this master prim.
*
* @param stage The USD stage.
*
* @return A map of master name/master information.
*/
MastersInfoMap getMastersInfo(UsdStageRefPtr stage);
/**
* @brief Get the list of variants selection for a given path.
*
* @param path The SdfPath on which to extract the list of variant selection.
*
* @return A list of variant selections (strings).
*/
std::vector<std::string> getVariantsSelection(const SdfPath& path);
} // namespace WalterUSDCommonUtils
#endif // __WALTERUSDCOMMONUTILS_H__
<|start_filename|>walter/usd/rdoCustomResource.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "rdoCustomResource.h"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <pxr/base/plug/plugin.h>
#include <pxr/base/tf/fileUtils.h>
#include <pxr/base/tf/token.h>
#include <pxr/usd/sdf/layer.h>
#include <string>
#include <unordered_map>
#include <fstream>
#include <sstream>
PXR_NAMESPACE_USING_DIRECTIVE
std::unordered_map<std::string, const char*> resource;
// Split the given path and return the vector of directories.
std::vector<std::string> splitPath(const boost::filesystem::path &src)
{
std::vector<std::string> elements;
for (const auto &p : src)
{
elements.push_back(p.c_str());
}
return elements;
}
void setResource(const char* filename, const char* contents)
{
std::vector<std::string> pathVect = splitPath(filename);
while (!pathVect.empty())
{
std::string joined = boost::algorithm::join(pathVect, "/");
resource[joined] = contents;
pathVect.erase(pathVect.begin());
}
}
const char* getResource(const char* filename)
{
std::vector<std::string> pathVect = splitPath(filename);
while (!pathVect.empty())
{
std::string joined = boost::algorithm::join(pathVect, "/");
auto it = resource.find(joined);
if (it != resource.end())
{
return it->second;
}
pathVect.erase(pathVect.begin());
}
return nullptr;
}
// USD overrides
extern "C"
TfToken _GetShaderPath(char const* shader)
{
return TfToken(shader);
}
extern "C"
std::istream* _GetFileStream(const char* filename)
{
// Try to search in the saved resources first.
const char* data = getResource(filename);
if (data)
{
return new std::istringstream(data);
}
return new std::ifstream(filename);
}
extern "C"
SdfLayerRefPtr _GetGeneratedSchema(const PlugPluginPtr &plugin)
{
// Look for generatedSchema in Resources.
const std::string filename = TfStringCatPaths(
plugin->GetResourcePath(),
"generatedSchema.usda");
const char* data = getResource(filename.c_str());
if (data)
{
SdfLayerRefPtr layer = SdfLayer::CreateAnonymous(filename);
if (layer->ImportFromString(data))
{
return layer;
}
}
return TfIsFile(filename) ? SdfLayer::OpenAsAnonymous(filename) : TfNullPtr;
}
<|start_filename|>walter/usd/tests/test_resources_GetShaderPaths.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
/*
Those tests check that we can load good tokens from the Walter resources when
calling the HdStPackage* functions.
To do that we are patching the Usd file 'package.cpp' by overriding _GetShaderPath().
*/
#include <pxr/imaging/hdSt/package.h>
#include <gtest/gtest.h>
PXR_NAMESPACE_USING_DIRECTIVE
TEST(test_resources_GetShaderPaths, fallbackSurface)
{
TfToken s = HdStPackageFallbackSurfaceShader();
EXPECT_EQ(s, "fallbackSurface.glslfx");
}
TEST(test_resources_getShaderPaths, ptexTexture)
{
TfToken s = HdStPackagePtexTextureShader();
EXPECT_EQ(s, "ptexTexture.glslfx");
}
TEST(test_resources_getShaderPaths, renderPassShader)
{
TfToken s = HdStPackageRenderPassShader();
EXPECT_EQ(s, "renderPassShader.glslfx");
}
TEST(test_resources_getShaderPaths, fallbackLightingShader)
{
TfToken s = HdStPackageFallbackLightingShader();
EXPECT_EQ(s, "fallbackLightingShader.glslfx");
}
TEST(test_resources_getShaderPaths, lightingIntegrationShader)
{
TfToken s = HdStPackageLightingIntegrationShader();
EXPECT_EQ(s, "lightingIntegrationShader.glslfx");
}
<|start_filename|>walter/arnold/procedural/index.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "index.h"
#include <boost/algorithm/string.hpp>
#include <boost/range/adaptor/reversed.hpp>
PXR_NAMESPACE_USING_DIRECTIVE
void RendererIndex::insertPrim(
const SdfPath& parentPath, const SdfPath& objectPath)
{
{
// Scope because we have another guard mHierarchyMap.
// TODO: Maybe concurrent_unordered_set is better?
FastMutexLock lock(mCachedObjectSetLock);
mCachedObjectSet.insert(objectPath);
}
ObjectMap::accessor it;
mHierarchyMap.insert(it, parentPath);
it->second.insert(objectPath);
}
bool RendererIndex::isProcessed(const SdfPath& path) const
{
FastMutexLock lock(mCachedObjectSetLock);
return mCachedObjectSet.find(path) != mCachedObjectSet.end();
}
int RendererIndex::getNumNodes(const SdfPath& path)
{
auto it = mNumNodes.find(path);
if (it != mNumNodes.end())
{
return it->second;
}
else
{
ObjectMap::const_accessor it;
if (!mHierarchyMap.find(it, path))
{
// Nothing is found.
return 0;
}
int numNodes = it->second.size();
mNumNodes.emplace(path, numNodes);
return numNodes;
}
}
void RendererIndex::insertNumNodes(const SdfPath& path, int numNodes)
{
mNumNodes.emplace(path, numNodes);
}
bool RendererIndex::isChildrenKnown(const SdfPath& path) const
{
ObjectMap::const_accessor it;
return mHierarchyMap.find(it, path);
}
bool RendererIndex::isParentKnown(
const SdfPath& root,
const SdfPath& path) const
{
ObjectMap::const_accessor it;
if (!mHierarchyMap.find(it, root))
{
return false;
}
for (SdfPath potentialParent: it->second)
{
if (path.HasPrefix(potentialParent))
{
return true;
}
}
return false;
}
bool RendererIndex::isAssignmentDone() const
{
return !mAssignments.empty();
}
bool RendererIndex::hasGlobalMaterials() const
{
SdfPath root("/");
SdfPath materials("/materials");
ObjectMap::const_accessor it;
return mHierarchyMap.find(it, root) || mHierarchyMap.find(it, materials);
}
const SdfPath* RendererIndex::getPath(
const SdfPath& parentPath, unsigned int i)const
{
ObjectMap::const_accessor it;
if (!mHierarchyMap.find(it, parentPath))
{
// Nothing is found.
return nullptr;
}
const ObjectSet& set = it->second;
if (i >= set.size())
{
// Out of range.
return nullptr;
}
return &(*std::next(set.begin(), i));
}
bool RendererIndex::getRenderNodeData(
const SdfPath& path,
RenderNodeMap::accessor& accessor)
{
return mRenderNodeMap.insert(accessor, path);
}
bool RendererIndex::getRenderNodeData(
const SdfPath& path,
RenderNodeMap::const_accessor& accessor)
{
return mRenderNodeMap.find(accessor, path);
}
void RendererIndex::insertExpression(
const SdfPath& expressionPrimPath,
const SdfPath& rootPath,
const std::string& expression,
const WalterExpression::AssignmentLayers& layers)
{
// The alembic can be loaded as an object. It means it's not in the root and
// we need to extend the expressions to the full path because we don't want
// to apply them to all the objects.
std::string fullExpression = rootPath.GetText();
// If the latest symbol is '/', remove it.
if (fullExpression[fullExpression.size()-1] == '/')
{
fullExpression = fullExpression.substr(0, fullExpression.size()-1);
}
// RND-555: Demangle the expression to convert special regex characters
fullExpression += WalterCommon::demangleString(
WalterCommon::convertRegex(expression));
// Iterate the layers.
for (auto& l : layers)
{
// "defaultRenderLayer"
TargetToObjShader& currentLayer = mAssignments[l.first];
for (auto& t : l.second)
{
// "shader"
const std::string& targetName = t.first;
// Filling mAssignments.
auto emplaceResult = currentLayer[targetName].emplace(
std::piecewise_construct,
std::forward_as_tuple(fullExpression),
std::forward_as_tuple(t.second));
if (!emplaceResult.second)
{
// The insertion only takes place if no other element in the
// container has a key equivalent to the one being emplaced.
// emplaceResult.second is false if the key already existed.
// Skip it.
continue;
}
// "/materials/aiStandard1"
SdfPath& material = emplaceResult.first->second;
// USD converts relative names to absolute names during composition.
// Make it relative back.
if (material.GetParentPath() == expressionPrimPath)
{
material = material.MakeRelativePath(expressionPrimPath);
}
// Material points to the UsdShadeMaterial. Arnold requires a
// shader. We need to find the shader and save it.
auto itT = mMaterials.find(material);
if (itT == mMaterials.end())
{
continue;
}
const WalterExpression::AssignmentTargets& matTarget = itT->second;
auto itS = matTarget.find(targetName);
if (itS == matTarget.end())
{
// A special case because a surface shader in Arnold is just
// "shader"
if (targetName != "shader" ||
(itS = matTarget.find("surface")) == matTarget.end() )
{
continue;
}
}
material = itS->second;
}
}
}
void RendererIndex::insertMaterial(
const SdfPath& material,
const std::string& target,
const SdfPath& shader)
{
mMaterials[material][target] = shader;
}
void RendererIndex::insertAttribute(
const SdfPath& iOverridePath,
const std::string& iAttributeName,
const RendererAttribute& iAttribute)
{
mAttributes[iOverridePath].emplace(iAttributeName, iAttribute);
}
SdfPath RendererIndex::getShaderAssignment(
const std::string& objectName,
const std::string& layer,
const std::string& target)const
{
// Looking for requested render layer
auto layerIt = mAssignments.find(layer);
if (layerIt == mAssignments.end())
{
return SdfPath();
}
// Looking for necessary target.
auto targetIt = layerIt->second.find(target);
if (targetIt == layerIt->second.end())
{
return SdfPath();
}
const ObjectToShader& objectList = targetIt->second;
const SdfPath* shader =
WalterCommon::resolveAssignment<SdfPath>(objectName, objectList);
if (!shader)
{
return SdfPath();
}
return *shader;
}
const NameToAttribute* RendererIndex::getAttributes(SdfPath iOverridePath) const
{
auto it = mAttributes.find(iOverridePath);
if (it == mAttributes.end())
{
return nullptr;
}
const NameToAttribute& attributes = it->second;
return &attributes;
}
const NameToAttribute* RendererIndex::getObjectAttribute(
const std::string& iVirtualObjectName,
const std::string& iLayer)
{
assert(!iVirtualObjectName.empty());
// First, try to find the current object in the cache.
ObjectAttrs::accessor accessor;
if (mObjectAttributes.find(accessor, iVirtualObjectName))
{
// Found!!!
return &accessor->second;
}
// TODO: It's not clear if `accessor` still locks this scope. It shouldn't.
// Get the name of the walterOverride.
SdfPath attributePath =
getShaderAssignment(iVirtualObjectName, iLayer, "attribute");
// Get the attributes from the walter override object.
const NameToAttribute* attributes = getAttributes(attributePath);
if (attributes)
{
// Create a list of attributes and copy everything from Walter Override.
mObjectAttributes.emplace(
accessor,
std::piecewise_construct,
std::forward_as_tuple(iVirtualObjectName),
std::forward_as_tuple(*attributes));
}
else
{
// Create a new empty list of attributes.
mObjectAttributes.emplace(
accessor,
std::piecewise_construct,
std::forward_as_tuple(iVirtualObjectName),
std::forward_as_tuple());
}
// Merge with the attributes of parent.
if (iVirtualObjectName != "/")
{
// Generate the name of the parent.
// TODO: We could cache even this.
std::string parentVirtualName;
size_t found = iVirtualObjectName.find_last_of('/');
if (found == 0)
{
// Special case if the parent is the root.
parentVirtualName = "/";
}
else if (found != std::string::npos)
{
parentVirtualName = iVirtualObjectName.substr(0, found);
}
if (!parentVirtualName.empty())
{
// Recursively get the attributes of the parent.
const NameToAttribute* parentAttributes =
getObjectAttribute(parentVirtualName, iLayer);
if (parentAttributes)
{
// Current attributes should be strong, the parent attributes
// should be weak.
// TODO: be careful. map::insert has an undefined behaviour.
// https://cplusplus.github.io/LWG/issue2844
// It's necessary to check it on all the new compilers.
accessor->second.insert(
parentAttributes->begin(), parentAttributes->end());
}
}
}
return &accessor->second;
}
const std::string& RendererIndex::getPrefixPath(
const std::string& iPrefix) const
{
static const std::string empty;
StringMap::const_accessor it;
if (!mPrefixPathsForProcedurals.find(it, iPrefix))
{
return empty;
}
return it->second;
}
bool RendererIndex::setPrefixPath(
const std::string& iPrefix,
const std::string& iPath)
{
return mPrefixPathsForProcedurals.emplace(
std::piecewise_construct,
std::forward_as_tuple(iPrefix),
std::forward_as_tuple(iPath));
}
<|start_filename|>walter/katana/WalterIn/walterUSDOpCaboose.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterUSDOpCaboose.h"
#include "schemas/volume.h"
#include "walterUSDOpEngine.h"
#include "walterUSDOpUtils.h"
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
#include <FnGeolib/op/FnGeolibOp.h>
#include <FnGeolibServices/FnXFormUtil.h>
#include <pxr/usd/usdGeom/curves.h>
#include <pxr/usd/usdGeom/mesh.h>
#include <pxr/usd/usdGeom/scope.h>
#include <pxr/usd/usdGeom/xform.h>
#include <pxr/usd/usdLux/light.h>
#include <pxr/usd/usdShade/connectableAPI.h>
#include <pxr/usd/usdShade/material.h>
#include <pxr/usd/usdShade/shader.h>
#include <usdKatana/utils.h>
#include <boost/algorithm/string.hpp>
#ifdef USE_OPENVDB
#include <openvdb/io/File.h>
#include <openvdb/openvdb.h>
#endif
namespace OpCabooseImpl
{
/**
* @brief Calls GroupBuilder::set. We need it to be able to std::bind set.
*
* @param ioGB GroupBuilder to call set().
* @param iPath First argument to set.
* @param iAttr Second argument to set.
*/
void setGroupBuilder(
void* ioGB,
const std::string& iPath,
const FnAttribute::Attribute& iAttr)
{
auto groupBuilder = reinterpret_cast<FnAttribute::GroupBuilder*>(ioGB);
groupBuilder->set(iPath, iAttr);
}
/**
* @brief Push USD array attribute to Katana. It extracts data from USD
* attribute, converts the USD data type to the type understandable by Katana,
* and sets Katana attribute.
*
* TODO: Can we use either PxrUsdKatanaUtils::ConvertVtValueToKatAttr or
* _ConvertGeomAttr instead?
*
* @param KatanaType Katana attribute type. Example FnAttribute::IntAttribute.
* @param UsdType The type of the single element of the USD array.
* @param TupleSize Katana tuple size. For float it's 1, for point it's 3.
* @param iAttr Attribute that will be passed to Katana.
* @param iName Katana name of the new attribute.
* @param iTime The sample times.
* @param oStaticGb Output group builder where the new attribute will be
* created.
*
* @return Number of the elements in the created Katana attribute.
*/
template <typename KatanaType, typename UsdType, unsigned int TupleSize = 1>
size_t attributeArrayToKatana(
UsdAttribute iAttr,
const char* iName,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb)
{
if (!iAttr.IsValid() || !iAttr.HasValue())
{
return 0;
}
// Number of motion keys.
size_t keys = iTime->size();
// The number of data items.
size_t size = 0;
// The data builder to combine animation samples. If there are no samples,
// it's not used.
FnAttribute::DataBuilder<KatanaType> dataBuilder;
for (auto time : iTime->samples())
{
VtArray<UsdType> array;
iAttr.Get(&array, iTime->current() + time);
if (array.empty())
{
continue;
}
// TODO: std::is_same<typename KatanaType::value_type, UsdType>::value
std::vector<typename KatanaType::value_type> value;
// TODO: It will not cast the type. If KatanaType and UsdType are
// different, it will produce wrong data.
size = array.size() * TupleSize;
auto dataBegin =
reinterpret_cast<typename KatanaType::value_type*>(array.data());
auto dataEnd = dataBegin + size;
value.reserve(size);
value.insert(value.end(), dataBegin, dataEnd);
if (keys == 1)
{
oStaticGb.set(
iName, KatanaType(&(value.front()), value.size(), TupleSize));
}
else
{
dataBuilder.set(value, time);
}
}
if (keys > 1)
{
oStaticGb.set(iName, dataBuilder.build());
}
return size;
}
/**
* @brief Convert USD interpolation to Katana scope.
*
* @param iInterpolation Interpolation
*
* @return Scope
*/
FnAttribute::StringAttribute interpolationToScope(const TfToken& iInterpolation)
{
static const FnAttribute::StringAttribute faceAttr("face");
static const FnAttribute::StringAttribute pointAttr("point");
static const FnAttribute::StringAttribute primAttr("primitive");
static const FnAttribute::StringAttribute vertexAttr("vertex");
if (iInterpolation == UsdGeomTokens->faceVarying)
{
return vertexAttr;
}
else if (iInterpolation == UsdGeomTokens->varying)
{
return pointAttr;
}
else if (iInterpolation == UsdGeomTokens->vertex)
{
// see below
return pointAttr;
}
else if (iInterpolation == UsdGeomTokens->uniform)
{
return faceAttr;
}
return primAttr;
}
/**
* @brief Converts USD role name to Katana type string.
*
* @param iRoleName USD role, like Point/Vector/Normal/Color
* @param iTypeStr It will be used if the role is unknown
* @param oInputTypeAttr Type name recognizable by Katana
* @param oElementSizeAttr Katana element's size.
*
* @return True if success.
*/
bool KTypeAndSizeFromUsdVec4(
TfToken const& iRoleName,
const char* iTypeStr,
FnAttribute::Attribute* oInputTypeAttr)
{
if (iRoleName == SdfValueRoleNames->Point)
{
*oInputTypeAttr = FnAttribute::StringAttribute("point4");
}
else if (iRoleName == SdfValueRoleNames->Vector)
{
*oInputTypeAttr = FnAttribute::StringAttribute("vector4");
}
else if (iRoleName == SdfValueRoleNames->Normal)
{
*oInputTypeAttr = FnAttribute::StringAttribute("normal4");
}
else if (iRoleName == SdfValueRoleNames->Color)
{
*oInputTypeAttr = FnAttribute::StringAttribute("color4");
}
else if (iRoleName.IsEmpty())
{
*oInputTypeAttr = FnKat::StringAttribute(iTypeStr);
}
else
{
return false;
}
return true;
}
/**
* @brief A simple utility to copy data from VtVec4fArray to vector.
*/
void ConvertArrayToVector(const VtVec4fArray& a, std::vector<float>* r)
{
r->resize(a.size() * 4);
size_t i = 0;
for (const auto& vec : a)
{
for (int c = 0; c < 4; c++)
{
(*r)[i++] = vec[c];
}
}
TF_VERIFY(i == r->size());
}
/**
* @brief As it's clear from the name it converts any VtValue to Katana
* attribute set. PxrUsdKatanaUtils::ConvertVtValueToKatCustomGeomAttr doesn't
* support all the types, and we need this function to have Point4.
*
* @param iVal Input VtValue
* @param iElementSize The size of an element
* @param iRoleName USD role, like Point/Vector/Normal/Color
* @param oValueAttr Katana value.
* @param oInputTypeAttr Type name recognizable by Katana
* @param oElementSizeAttr Katana element's size.
*/
void convertVtValueToKatCustomGeomAttr(
const VtValue& iVal,
int iElementSize,
const TfToken& iRoleName,
FnAttribute::Attribute* oValueAttr,
FnAttribute::Attribute* oInputTypeAttr,
FnAttribute::Attribute* oElementSizeAttr)
{
if (iVal.IsHolding<GfVec4f>())
{
if (KTypeAndSizeFromUsdVec4(iRoleName, "point4", oInputTypeAttr))
{
const GfVec4f rawVal = iVal.Get<GfVec4f>();
FnAttribute::FloatBuilder builder(/* tupleSize = */ 4);
std::vector<float> vec(rawVal.data(), rawVal.data() + 4);
builder.set(vec);
*oValueAttr = builder.build();
}
return;
}
if (iVal.IsHolding<VtArray<GfVec4f>>())
{
if (KTypeAndSizeFromUsdVec4(iRoleName, "float", oInputTypeAttr))
{
const VtArray<GfVec4f> rawVal = iVal.Get<VtArray<GfVec4f>>();
std::vector<float> vec;
ConvertArrayToVector(rawVal, &vec);
FnKat::FloatBuilder builder(/* tupleSize = */ 4);
builder.set(vec);
*oValueAttr = builder.build();
}
return;
}
if (iVal.IsHolding<VtArray<bool>>())
{
const VtArray<bool> rawVal = iVal.Get<VtArray<bool>>();
std::vector<int> vec(rawVal.size());
for (int i=0; i<rawVal.size(); ++i)
{
vec[i] = rawVal[i];
}
FnKat::IntBuilder builder(/* tupleSize = */ 1);
builder.set(vec);
*oValueAttr = builder.build();
return;
}
// else
PxrUsdKatanaUtils::ConvertVtValueToKatCustomGeomAttr(
iVal,
iElementSize,
iRoleName,
oValueAttr,
oInputTypeAttr,
oElementSizeAttr);
}
/**
* @brief Generates geometry arbitrary attribute for Katana.
*
* @param iVtValue The data of the attribute.
* @param vtIndices The indexes of the attribute. If this is not emply, the
* generated arbitrary attribute will be an indexed attribute.
* @param iElementSize The size of the element. For example it's 3 for point.
* @param iType USD type.
* @param iInterpolation USD interpolation. TODO: is it enough to use scope?
* @param iScopeAttr Katana scope.
*
* @return GroupAttribute that can be directly used as arbitrary attr.
*/
FnAttribute::Attribute convertVtValueToArbitrary(
const VtValue& iVtValue,
const VtIntArray& vtIndices,
int iElementSize,
const SdfValueTypeName& iType,
const TfToken& iInterpolation,
const FnAttribute::StringAttribute& iScopeAttr)
{
// Convert value to the required Katana attributes to describe it.
FnAttribute::Attribute valueAttr;
FnAttribute::Attribute inputTypeAttr;
FnAttribute::Attribute elementSizeAttr;
convertVtValueToKatCustomGeomAttr(
iVtValue,
iElementSize,
iType.GetRole(),
&valueAttr,
&inputTypeAttr,
&elementSizeAttr);
// Bundle them into a group attribute
FnAttribute::GroupBuilder attrBuilder;
attrBuilder.set("scope", iScopeAttr);
attrBuilder.set("inputType", inputTypeAttr);
if (elementSizeAttr.isValid())
{
attrBuilder.set("elementSize", elementSizeAttr);
}
std::string valueAttributeName;
if (!vtIndices.empty())
{
// If we have indexes, we need to output it as indexed attribute.
valueAttributeName = "indexedValue";
attrBuilder.set(
"index",
FnAttribute::IntAttribute(vtIndices.data(), vtIndices.size(), 1));
}
else
{
valueAttributeName = "value";
}
attrBuilder.set(valueAttributeName, valueAttr);
// Note that 'varying' vs 'vertex' require special handling, as in
// Katana they are both expressed as 'point' scope above. To get
// 'vertex' interpolation we must set an additional
// 'interpolationType' attribute. So we will flag that here.
const bool vertexInterpolationType =
(iInterpolation == UsdGeomTokens->vertex);
if (vertexInterpolationType)
{
attrBuilder.set(
"interpolationType", FnAttribute::StringAttribute("subdiv"));
}
return attrBuilder.build();
}
/**
* @brief Output the bound to the Katana group builder.
*
* @param iImageable The UsdGeomImageable with a bound.
* @param iTime The sample times.
* @param oStaticGb Output group builder where the new attribute will be
* created.
* @param isLocal Whether to return the local bound or the untransformed
* bound (default).
*/
void createBound(
const UsdGeomImageable& iImageable,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb,
bool isLocal=false)
{
// Get the bounding box.
GfBBox3d bbox;
// We need to combine all the bounding boxes of the all the motion
// samples.
bool bboxInitialized = false;
for (auto t : iTime->samples())
{
GfBBox3d current = isLocal
? iImageable.ComputeLocalBound(
t, UsdGeomTokens->default_, UsdGeomTokens->render)
: iImageable.ComputeUntransformedBound(
t, UsdGeomTokens->default_, UsdGeomTokens->render);
if (bboxInitialized)
{
bbox = GfBBox3d::Combine(bbox, current);
}
else
{
bbox = current;
bboxInitialized = true;
}
}
const GfRange3d& range = bbox.ComputeAlignedBox();
const GfVec3d& min = range.GetMin();
const GfVec3d& max = range.GetMax();
// Output to the group builder.
FnKat::DoubleBuilder builder(1);
builder.set({min[0], max[0], min[1], max[1], min[2], max[2]});
oStaticGb.set("bound", builder.build());
}
/**
* @brief Outputs the primvars of the object to the Katana group builder.
*
* @param iPrim The USD prim to output.
* @param iTime The sample times.
* @param oStaticGb Output group builder where the new attribute will be
* created.
*/
void cookGeomImageable(
const UsdPrim& iPrim,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb)
{
UsdGeomImageable imageable(iPrim);
const bool isCurve = iPrim.IsA<UsdGeomCurves>();
// Create primvars. We don't use PxrUsdKatanaGeomGetPrimvarGroup because it
// requires PxrUsdKatanaUsdInPrivateData and PxrUsdKatanaUsdInArgs. The next
// block is very close to PxrUsdKatanaUsdInPrivateData from readPrim.cpp
// from USD.
FnAttribute::GroupBuilder primvarsBuilder;
for (const UsdGeomPrimvar& primvar : imageable.GetPrimvars())
{
// Katana backends (such as KTOA) are not prepared to handle groups of
// primvars under geometry.arbitrary, which leaves us without a
// ready-made way to incorporate namespaced primvars like
// "primvars:skel:jointIndices". Until we untangle that, skip importing
// any namespaced primvars.
if (primvar.NameContainsNamespaces())
{
continue;
}
TfToken name;
TfToken interpolation;
SdfValueTypeName typeName;
int elementSize;
// GetDeclarationInfo inclues all namespaces other than "primvars:" in
// 'name'
primvar.GetDeclarationInfo(
&name, &typeName, &interpolation, &elementSize);
// Name: this will eventually need to know how to translate namespaces
std::string gdName = name;
// KTOA needs UV coordinates to be named "st".
if (gdName == "uv")
{
gdName = "st";
}
// Convert interpolation -> scope
FnAttribute::StringAttribute scopeAttr;
if (isCurve && interpolation == UsdGeomTokens->vertex)
{
// it's a curve, so "vertex" == "vertex"
scopeAttr = FnAttribute::StringAttribute("vertex");
}
else
{
scopeAttr = interpolationToScope(interpolation);
}
// Resolve the value
VtValue vtValue;
VtIntArray vtIndices;
if (interpolation == UsdGeomTokens->faceVarying && primvar.IsIndexed())
{
// It's an indexed value. We don't want to flatten it because it
// breaks subdivs.
if (!primvar.Get(&vtValue, iTime->current()))
{
continue;
}
if (!primvar.GetIndices(&vtIndices, iTime->current()))
{
continue;
}
}
else
{
// USD comments suggest using using the ComputeFlattened() API
// instead of Get even if they produce the same data.
if (!primvar.ComputeFlattened(&vtValue, iTime->current()))
{
continue;
}
}
primvarsBuilder.set(
gdName,
OpCabooseImpl::convertVtValueToArbitrary(
vtValue,
vtIndices,
elementSize,
typeName,
interpolation,
scopeAttr));
}
oStaticGb.set("geometry.arbitrary", primvarsBuilder.build());
// Purposes
UsdAttribute purpose = imageable.GetPurposeAttr();
TfToken purposeValue;
if (purpose.Get(&purposeValue))
{
if (purposeValue.GetString() == "proxy" ||
purposeValue.GetString() == "guide")
{
oStaticGb.set("visible", FnAttribute::IntAttribute(0));
}
// Note: purpose "render" is seen in viewport AND render for now.
// We could allow artists to have a control on that, for example with
// a check box on the Walter_In node to hide "render" primitives in the
// viewport. The code for that is the following:
// oStaticGb.set(
// "viewer.default.drawOptions.hide",
// FnAttribute::IntAttribute(1)
// );
}
}
/**
* @brief Outputs xform of the object to the Katana group builder.
*
* @param iPrim The USD prim to output.
* @param iTime The sample times.
* @param oStaticGb Output group builder where the new attribute will be
* created.
*/
void cookGeomXformable(
const UsdPrim& iPrim,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb)
{
UsdGeomXformable xformable(iPrim);
// This block closely matches to PxrUsdKatanaReadXformable() of
// readXformable.cpp.
// Get the ordered xform ops for the prim.
bool resetsXformStack;
std::vector<UsdGeomXformOp> orderedXformOps =
xformable.GetOrderedXformOps(&resetsXformStack);
FnAttribute::GroupBuilder gb;
// For each xform op, construct a matrix containing the
// transformation data for each time sample it has.
int opCount = 0;
for (const auto& xformOp : orderedXformOps)
{
FnAttribute::DoubleBuilder matBuilder(16);
for (auto time : iTime->samples())
{
GfMatrix4d mat = xformOp.GetOpTransform(iTime->current() + time);
// Convert to vector.
const double* matArray = mat.GetArray();
std::vector<double>& matVec = matBuilder.get(time);
matVec.resize(16);
for (int i = 0; i < 16; ++i)
{
matVec[i] = matArray[i];
}
}
gb.set("matrix" + std::to_string(opCount++), matBuilder.build());
}
// Only set an 'xform' attribute if xform ops were found.
//
if (!orderedXformOps.empty())
{
FnAttribute::GroupBuilder xformGb;
xformGb.setGroupInherit(false);
// Reset the location to the origin if the xform op
// requires the xform stack to be reset.
if (resetsXformStack)
{
xformGb.set("origin", FnAttribute::DoubleAttribute(1));
}
FnAttribute::DoubleAttribute matrixAttr =
FnGeolibServices::FnXFormUtil::CalcTransformMatrixAtExistingTimes(
gb.build())
.first;
xformGb.set("matrix", matrixAttr);
oStaticGb.set("xform", xformGb.build());
}
}
void cookGeomMesh(
const UsdPrim& iPrim,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb)
{
// Get mesh.
UsdGeomMesh mesh(iPrim);
oStaticGb.set("type", FnAttribute::StringAttribute("polymesh"));
// Eval vertex counts of faces.
VtIntArray numVertsArray;
mesh.GetFaceVertexCountsAttr().Get(&numVertsArray, iTime->current());
// Katana doesn't have "Face Vertex Counts". Instead, it has startIndex. We
// need to convert "Face Vertex Counts" to Katana's startIndex.
// FVC: [4, 4, 3, 4]
// startIndex: [0, 4, 8, 11, 15]
{
size_t numVertsArraySize = numVertsArray.size();
std::vector<int> startIndex;
startIndex.reserve(numVertsArraySize + 1);
startIndex.push_back(0);
for (size_t i = 0; i < numVertsArraySize; i++)
{
startIndex.push_back(startIndex[i] + numVertsArray[i]);
}
oStaticGb.set(
"geometry.poly.startIndex",
FnAttribute::IntAttribute(startIndex.data(), startIndex.size(), 1));
}
attributeArrayToKatana<FnAttribute::IntAttribute, int>(
mesh.GetFaceVertexIndicesAttr(),
"geometry.poly.vertexList",
iTime,
oStaticGb);
attributeArrayToKatana<FnAttribute::FloatAttribute, GfVec3f, 3>(
mesh.GetPointsAttr(), "geometry.point.P", iTime, oStaticGb);
attributeArrayToKatana<FnAttribute::FloatAttribute, GfVec3f, 3>(
mesh.GetNormalsAttr(), "geometry.vertex.N", iTime, oStaticGb);
}
void cookShadeShader(
const UsdPrim& iPrim,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb)
{
// TODO: Can we use _GatherShadingParameters although it's private?
// Get shader.
UsdShadeShader shader(iPrim);
FnAttribute::GroupBuilder parametersBuilder;
FnAttribute::GroupBuilder connectionsBuilder;
const std::string name = iPrim.GetName().GetString();
for (const UsdShadeInput& input : shader.GetInputs())
{
std::string inputName = input.GetBaseName();
// Convert USD namespaces to Arnold components. We need it because we
// did conversion from Arnold components to USD namespaces in Alembic to
// USD plugin.
std::replace(inputName.begin(), inputName.end(), ':', '.');
// Extract connection
UsdShadeConnectableAPI source;
TfToken outputName;
UsdShadeAttributeType sourceType;
if (UsdShadeConnectableAPI::GetConnectedSource(
input, &source, &outputName, &sourceType))
{
std::string outputNameStr = outputName.GetString();
if (outputNameStr != "out")
{
outputNameStr = "out." + outputNameStr;
}
connectionsBuilder.set(
inputName,
FnAttribute::StringAttribute(
outputNameStr + "@" + source.GetPath().GetName()));
}
// Extract value
UsdAttribute attr = input.GetAttr();
VtValue vtValue;
if (!attr.Get(&vtValue, iTime->current()))
{
continue;
}
parametersBuilder.set(
inputName,
PxrUsdKatanaUtils::ConvertVtValueToKatAttr(vtValue, true));
}
// Query shader type. It's "standard_surface"
static const TfToken typeToken("info:type");
TfToken type;
iPrim.GetAttribute(typeToken).Get(&type, iTime->current());
// Target is usually render name. "arnold"
static const TfToken targetToken("info:target");
TfToken target;
iPrim.GetAttribute(targetToken).Get(&target, iTime->current());
oStaticGb.set("name", FnAttribute::StringAttribute(name));
oStaticGb.set("srcName", FnAttribute::StringAttribute(name));
oStaticGb.set("type", FnAttribute::StringAttribute(type.GetString()));
oStaticGb.set("target", FnAttribute::StringAttribute(target.GetString()));
oStaticGb.set("parameters", parametersBuilder.build());
oStaticGb.set("connections", connectionsBuilder.build());
}
void cookShadeMaterial(
const UsdPrim& iPrim,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb)
{
FnAttribute::GroupBuilder nodesBuilder;
FnAttribute::GroupBuilder terminalsBuilder;
// Create the ports. Example: "arnoldSurface" and "arnoldSurfacePort"
// attributes
for (const UsdAttribute& attr : iPrim.GetAttributes())
{
if (!UsdShadeConnectableAPI::HasConnectedSource(attr))
{
continue;
}
// The name is "arnold:surface"
std::string name = attr.GetName();
std::vector<std::string> splitted;
boost::split(splitted, name, boost::is_any_of(":"));
if (splitted.size() < 2)
{
continue;
}
// Extract the render and the target.
std::string render = splitted[0];
std::string target = splitted[1];
// TODO: other renders?
if (render != "arnold")
{
continue;
}
// Get the connection using ConnectableAPI.
UsdShadeConnectableAPI connectableAPISource;
TfToken sourceName;
UsdShadeAttributeType sourceType;
if (!UsdShadeConnectableAPI::GetConnectedSource(
attr, &connectableAPISource, &sourceName, &sourceType))
{
// Should never happen because we already checked it.
assert(false);
}
// Title surface -> Surface
target[0] = toupper(target[0]);
terminalsBuilder.set(
render + target,
FnAttribute::StringAttribute(
connectableAPISource.GetPrim().GetName()));
terminalsBuilder.set(
render + target + "Port", FnAttribute::StringAttribute("out"));
}
// Iterate the shaders.
for (const UsdPrim& child : iPrim.GetDescendants())
{
W_DEBUG(
"Checking child %s %s",
child.GetTypeName().GetText(),
child.GetPath().GetText());
FnAttribute::GroupBuilder shadingNode;
if (child.IsA<UsdShadeShader>())
{
cookShadeShader(child, iTime, shadingNode);
}
nodesBuilder.set(child.GetName().GetString(), shadingNode.build());
}
static const FnAttribute::StringAttribute materialStrAttr("material");
static const FnAttribute::StringAttribute networkStrAttr("network");
oStaticGb.set("type", materialStrAttr);
oStaticGb.set("material.nodes", nodesBuilder.build());
oStaticGb.set("material.terminals", terminalsBuilder.build());
oStaticGb.set("material.style", networkStrAttr);
}
// The cooking of light is actually exactly the same thing as cooking a material
// network. The only difference is that the type of the location is 'light'.
void cookLight(
const UsdPrim& iPrim,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb)
{
cookShadeMaterial(iPrim, iTime, oStaticGb);
static const FnAttribute::StringAttribute lightStrAttr("light");
oStaticGb.set("type", lightStrAttr);
}
/**
* @brief Return assignment of the specified path
*
* @param iPath the path of the object.
* @param iTarget "shader", "displacement", "attribute".
* @param ioIndex
*
* @return the path to the material or walterOVerride object.
*/
SdfPath getAssignment(
const SdfPath& iPath,
const std::string& iTarget,
const OpIndex& iIndex,
bool checkParent = true)
{
const SdfPath assignmentPath =
iIndex.getMaterialAssignment(iPath, iTarget);
SdfPath parentAssignmentPath;
if (!iPath.IsRootPrimPath() && checkParent)
{
parentAssignmentPath =
iIndex.getMaterialAssignment(iPath.GetParentPath(), iTarget);
}
if (assignmentPath == parentAssignmentPath)
{
return SdfPath::EmptyPath();
}
return assignmentPath;
}
/**
* @brief Outputs material assign of the object to the Katana group builder.
*
* @param iPrim The USD prim to output.
* @param iPrivateData The object that is generated by us for each node we
* are going to produce.
* @param oStaticGb Output group builder where the new attribute will be
* created.
* @param isParentImageable Whether the parent prim is a UsdGeomImageable or
* not. If not, getAssignment won't check parent assignment for inheritance.
*/
void cookWalterAssignment(
const UsdPrim& iPrim,
const OpUtils::PrivateData* iPrivateData,
FnAttribute::GroupBuilder& oStaticGb,
bool isParentImageable)
{
OpUtils::TimePtr time = iPrivateData->time();
SdfPath path = iPrivateData->path();
OpIndex& index = iPrivateData->engine().index();
std::string masterName = iPrivateData->engine().getMasterName(iPrim);
static const std::string surfaceTarget = "shader";
static const std::string displacementTarget = "displacement";
static const std::string attributeTarget = "attribute";
// If masterName exists, it means that this prim is under a Master prim
// and we need to specify a path on which to get assignement.
// e.g.: if prim in Katana is located at /master_shape/cube, we need to
// look for assignment on /shape/cube in Usd.
if (masterName != "")
{
SdfPath primPath = iPrim.GetPrimPath();
SdfPath masterRoot = primPath.GetPrefixes().front();
std::string newPrimPath = primPath.GetString();
boost::replace_first(newPrimPath, masterRoot.GetName(), masterName);
path = SdfPath(newPrimPath);
}
// Shader assignment. First, we need to get the standard material
// binding. If it exists, it should win.
UsdRelationship binding = UsdShadeMaterial::GetBindingRel(iPrim);
SdfPath surfaceMaterialPath;
if (binding)
{
SdfPathVector targetPaths;
binding.GetForwardedTargets(&targetPaths);
if ((targetPaths.size() == 1) && targetPaths.front().IsPrimPath())
{
surfaceMaterialPath = targetPaths.front();
}
}
// If the standard binding doesn't exist, we need to evaluate our
// expressions.
if (surfaceMaterialPath.IsEmpty())
{
surfaceMaterialPath = OpCabooseImpl::getAssignment(
path,
surfaceTarget,
index,
isParentImageable
);
}
// TODO: it's necessary to figure out if we need to assign displacement
// if the standard binding exists. Now we do assign on the top of the
// standard binding.
const SdfPath displacementMaterialPath = OpCabooseImpl::getAssignment(
path,
displacementTarget,
index,
isParentImageable
);
if (!surfaceMaterialPath.IsEmpty() &&
!displacementMaterialPath.IsEmpty())
{
// We need to assign both surface and displacement. But in Katana
// there is only one material input. So we can't connect the
// material, we just output both surface and displacement to this
// current node and the shader is embedded.
// TODO: can we reuse GroupBuilder from the matrial we created
// previously?
FnAttribute::GroupBuilder materialBuilder;
OpCabooseImpl::cookShadeMaterial(
iPrim.GetStage()->GetPrimAtPath(surfaceMaterialPath),
time,
materialBuilder);
FnAttribute::GroupBuilder displacementBuilder;
OpCabooseImpl::cookShadeMaterial(
iPrim.GetStage()->GetPrimAtPath(displacementMaterialPath),
time,
displacementBuilder);
oStaticGb.deepUpdate(materialBuilder.build());
oStaticGb.deepUpdate(displacementBuilder.build());
}
else if (!surfaceMaterialPath.IsEmpty())
{
const std::string material =
iPrivateData->root() + surfaceMaterialPath.GetString();
oStaticGb.set(
"materialAssign", FnAttribute::StringAttribute(material));
}
else if (!displacementMaterialPath.IsEmpty())
{
const std::string material =
iPrivateData->root() + displacementMaterialPath.GetString();
oStaticGb.set(
"materialAssign", FnAttribute::StringAttribute(material));
}
// walterOverride attributes
const SdfPath attributePath = OpCabooseImpl::getAssignment(
path,
attributeTarget,
index,
isParentImageable
);
if (!attributePath.IsEmpty())
{
const OpIndex::NameToAttribute* attributes =
index.getAttributes(attributePath);
if (attributes)
{
FnAttribute::GroupBuilder attributesBld;
for (const auto& attr : *attributes)
{
attr.second->evaluate(&attributesBld);
}
oStaticGb.deepUpdate(attributesBld.build());
}
}
}
/**
* @brief Output WalterVolume schema to the Katana group builder.
*
* @param iPrim The USD prim to output.
* @param iTime The sample times.
* @param oStaticGb Output group builder where the new attribute will be
* created.
*/
void cookWalterVolume(
const UsdPrim& iPrim,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb)
{
static const FnAttribute::StringAttribute volumeStrAttr("volume");
static const FnAttribute::StringAttribute volumeplugStrAttr("volumeplugin");
static const FnAttribute::FloatAttribute stepSizeStrAttr(0.0f);
oStaticGb.set("type", volumeStrAttr);
oStaticGb.set("geometry.type", volumeplugStrAttr);
oStaticGb.set("geometry.step_size", stepSizeStrAttr);
oStaticGb.set("rendererProcedural.node", volumeStrAttr);
// The mapping from USD name to the Katana name.
static const std::unordered_map<std::string, std::string> attributeMap = {
{"filename", "rendererProcedural.args.filename"},
{"grids", "rendererProcedural.args.grids"},
{"stepScale", "rendererProcedural.args.step_scale"},
{"stepSize", "rendererProcedural.args.step_size"},
{"velocityFps", "rendererProcedural.args.velocity_fps"},
{"velocityOutlierThreshold",
"rendererProcedural.args.velocity_outlier_threshold"},
{"velocityScale", "rendererProcedural.args.velocity_scale"},
{"volumePadding", "rendererProcedural.args.volume_padding"}};
std::string filename;
// Iterate all the attributes.
for (const UsdAttribute& attr : iPrim.GetAttributes())
{
std::string baseName = attr.GetBaseName().GetString();
auto found = attributeMap.find(baseName);
if (found == attributeMap.end())
{
// If it is not in the map, we don't support it.
continue;
}
VtValue vtValue;
if (!attr.Get(&vtValue, iTime->current()))
{
continue;
}
if (baseName == "filename")
{
filename = vtValue.Get<std::string>();
}
oStaticGb.set(
found->second,
PxrUsdKatanaUtils::ConvertVtValueToKatAttr(vtValue, true));
}
#ifdef USE_OPENVDB
// Ass file doesn't contain the information about bounds. The only way to
// get it is open VDB file. Since we are going to read metadata only, it
// should be fast.
if (!filename.empty())
{
static std::atomic_bool sIsInitialized(false);
if (!sIsInitialized.load())
{
openvdb::initialize();
sIsInitialized = true;
}
// Trying to open OpenVDB to get the information about bounding box.
std::unique_ptr<openvdb::io::File> vdb(new openvdb::io::File(filename));
if (vdb->open())
{
openvdb::math::Vec3d bbMin =
openvdb::math::Vec3d(std::numeric_limits<double>::max());
openvdb::math::Vec3d bbMax =
openvdb::math::Vec3d(-std::numeric_limits<double>::max());
// Read the metadata of all the grids. It will not load the grid
// data.
openvdb::GridPtrVecPtr grids = vdb->readAllGridMetadata();
for (const auto& grid : *grids)
{
const openvdb::Vec3i& bbMinI = grid->metaValue<openvdb::Vec3i>(
openvdb::GridBase::META_FILE_BBOX_MIN);
const openvdb::Vec3i& bbMaxI = grid->metaValue<openvdb::Vec3i>(
openvdb::GridBase::META_FILE_BBOX_MAX);
// Intersect them.
bbMin = openvdb::math::minComponent(
bbMin, grid->indexToWorld(bbMinI));
bbMax = openvdb::math::maxComponent(
bbMax, grid->indexToWorld(bbMaxI));
}
// Output to Katana.
std::vector<double> bound = {bbMin.x(),
bbMax.x(),
bbMin.y(),
bbMax.y(),
bbMin.z(),
bbMax.z()};
FnKat::DoubleBuilder builder(1);
builder.set(bound);
oStaticGb.set("bound", builder.build());
}
}
#endif
}
void cookInstance(
const UsdPrim& iPrim,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb,
std::string instanceSourceLocation)
{
OpCabooseImpl::createBound(
UsdGeomImageable{iPrim}, iTime, oStaticGb, false/*isLocal*/);
oStaticGb.set("type", FnAttribute::StringAttribute("instance"));
oStaticGb.set(
"geometry.instanceSource",
FnAttribute::StringAttribute(instanceSourceLocation)
);
}
void cookAsRendererProcedural(
const UsdPrim& iPrim,
const OpUtils::TimePtr iTime,
FnAttribute::GroupBuilder& oStaticGb,
std::string engineIdentifier)
{
OpCabooseImpl::createBound(
UsdGeomImageable{iPrim}, iTime, oStaticGb, true/*isLocal*/);
oStaticGb.set(
"type", FnAttribute::StringAttribute("renderer procedural"));
oStaticGb.set(
"rendererProcedural.procedural",
FnAttribute::StringAttribute("walter"));
oStaticGb.set(
"rendererProcedural.node", FnAttribute::StringAttribute("walter"));
oStaticGb.set(
"rendererProcedural.args.filePaths",
FnAttribute::StringAttribute(engineIdentifier));
oStaticGb.set(
"rendererProcedural.args.objectPath",
FnAttribute::StringAttribute(iPrim.GetPath().GetString()));
oStaticGb.set(
"rendererProcedural.includeCameraInfo",
FnAttribute::StringAttribute("None"));
oStaticGb.set(
"rendererProcedural.args.__outputStyle",
FnAttribute::StringAttribute("typedArguments"));
oStaticGb.set(
"rendererProcedural.args.frame",
FnAttribute::FloatAttribute(iTime->current()));
}
void setAllAttrs(
Foundry::Katana::GeolibCookInterface& interface,
const FnAttribute::GroupAttribute& attrs)
{
for (int64_t i = 0; i < attrs.getNumberOfChildren(); ++i)
{
interface.setAttr(attrs.getChildName(i), attrs.getChildByIndex(i));
}
}
} // namespace OpCabooseImpl
void OpCaboose::ClientAttribute::evaluate(
OpCaboose::ClientAttribute::Carrier iCarrier) const
{
if (mFunction)
{
(*mFunction)(iCarrier);
}
}
bool OpCaboose::isSupported(const UsdPrim& iPrim)
{
// We check HasAuthoredTypeName because it's possible that the object
// doesn't have any type but it has children. We want to load children in
// this way.
return !iPrim.HasAuthoredTypeName() || iPrim.IsA<UsdGeomXform>() ||
iPrim.IsA<UsdGeomScope>() || iPrim.IsA<UsdGeomMesh>() ||
iPrim.IsA<UsdShadeMaterial>() || iPrim.IsA<WalterVolume>() ||
iPrim.IsA<UsdGeomPointInstancer>() || iPrim.IsA<UsdLuxLight>();
}
bool OpCaboose::skipChildren(const UsdPrim& iPrim)
{
return iPrim.IsA<UsdShadeMaterial>() || iPrim.IsA<UsdShadeShader>() ||
iPrim.IsA<UsdGeomPointInstancer>();
}
void OpCaboose::cook(
const UsdPrim& iPrim,
const OpUtils::PrivateData* iPrivateData,
void* ioClientData)
{
W_DEBUG("%s %s", iPrim.GetTypeName().GetText(), iPrim.GetPath().GetText());
assert(ioClientData);
auto interface =
reinterpret_cast<Foundry::Katana::GeolibCookInterface*>(ioClientData);
OpUtils::TimePtr time = iPrivateData->time();
const SdfPath& path = iPrivateData->path();
OpIndex& index = iPrivateData->engine().index();
bool isInstance = iPrim.IsInstance();
FnAttribute::GroupBuilder staticBld;
if (iPrim.IsA<UsdGeomImageable>() && iPrim.GetName() != "materials")
{
UsdGeomImageable imageable(iPrim);
if(imageable.ComputeVisibility() == TfToken("invisible"))
{
return;
}
OpCabooseImpl::cookGeomImageable(iPrim, time, staticBld);
// Cook Walter Assignment only for primitives that are not instances and
// not a group of instances.
// This test make sense as long as groups are homogeneous, i.e. they
// either contains only instances or only realy geometries but not both.
UsdPrimSiblingRange children = iPrim.GetChildren();
if (!isInstance && (children.empty() || !children.front().IsInstance()))
{
OpCabooseImpl::cookWalterAssignment(
iPrim,
iPrivateData,
staticBld,
iPrim.GetParent().IsA<UsdGeomImageable>()
);
}
}
if (iPrim.IsA<UsdGeomXformable>() && !isInstance)
{
// We shouldn't produce the transform for instances because we use the
// procedural to render them and the procedural will take care about the
// transforms.
OpCabooseImpl::cookGeomXformable(iPrim, time, staticBld);
}
if (iPrim.IsA<UsdGeomMesh>())
{
OpCabooseImpl::cookGeomMesh(iPrim, time, staticBld);
}
else if (iPrim.IsA<UsdShadeMaterial>())
{
OpCabooseImpl::cookShadeMaterial(iPrim, time, staticBld);
}
else if (iPrim.IsA<WalterVolume>())
{
OpCabooseImpl::cookWalterVolume(iPrim, time, staticBld);
}
else if (iPrim.IsA<UsdLuxLight>())
{
OpCabooseImpl::cookLight(iPrim, time, staticBld);
}
else if (iPrim.IsA<UsdGeomPointInstancer>())
{
OpCabooseImpl::cookAsRendererProcedural(
iPrim,
time,
staticBld,
iPrivateData->engine().getIdentifier()
);
}
else if (isInstance)
{
auto cookInstancesAttr = interface->getOpArg("cookInstances");
int cookInstances =
FnAttribute::IntAttribute(cookInstancesAttr).getValue(0, false);
// Cook instances as Katana instances.
// Note: Because of some bugs with the USD Arnold Procedural, instances are
// always expanded as Katana instances (cookInstances=True).
// cf. RND-661
if (cookInstances)
{
std::string masterName =
iPrivateData->engine().getKatMasterName(iPrim.GetMaster());
std::string katMasterLocation =
interface->getRootLocationPath() + "/" + masterName;
OpCabooseImpl::cookGeomXformable(iPrim, time, staticBld);
OpCabooseImpl::cookInstance(
iPrim,
time,
staticBld,
katMasterLocation
);
}
// Cook instances as renderer procedurals.
else
{
OpCabooseImpl::cookAsRendererProcedural(
iPrim,
time,
staticBld,
iPrivateData->engine().getIdentifier()
);
}
}
else if (iPrim.IsMaster())
{
staticBld.set("type", FnAttribute::StringAttribute("instance source"));
}
else
{
// Set the default node type. By default it's a group.
staticBld.set("type", FnAttribute::StringAttribute("group"));
}
OpCabooseImpl::setAllAttrs(*interface, staticBld.build());
// Check if we need to set Arnold defaults.
// TODO: We should do it on the root only.
FnAttribute::StringAttribute addDefaultAttrs =
interface->getOpArg("addDefaultAttrs");
if (addDefaultAttrs.getValue("Arnold", false) == "Arnold")
{
// We need smoothing because Arnold doesn't read normals it this
// attribute is off.
interface->setAttr(
"arnoldStatements.smoothing", FnAttribute::IntAttribute(1));
}
}
void OpCaboose::cookChild(
const UsdPrim& iPrim,
const OpUtils::PrivateData* iPrivateData,
void* ioClientData,
std::string iCustomName)
{
assert(ioClientData);
auto interface =
reinterpret_cast<Foundry::Katana::GeolibCookInterface*>(ioClientData);
FnAttribute::GroupAttribute childOpArgs = interface->getOpArg();
SdfPath path = iPrim.GetPath();
std::string name = (iCustomName != "")? iCustomName: path.GetName();
auto privateData = new OpUtils::PrivateData(
iPrivateData->engine(),
iPrivateData->root(),
path,
iPrivateData->time());
interface->createChild(
name,
"WalterInUSD",
childOpArgs,
Foundry::Katana::GeolibCookInterface::ResetRootFalse,
privateData,
OpUtils::PrivateData::kill);
}
OpCaboose::ClientAttributePtr OpCaboose::createClientAttribute(
const UsdAttribute& iAttr,
UsdTimeCode iTime)
{
VtValue vtValue;
if (!iAttr.Get(&vtValue, iTime))
{
return {};
}
std::string attributeName = iAttr.GetBaseName();
std::string attributeKatanaName =
OpUtils::getClientAttributeName(attributeName);
FnAttribute::Attribute attr;
if (!attributeKatanaName.empty())
{
// It's arnold attribute, and should be represented in Katana as a
// single atribute in arnoldStatements group.
attr = PxrUsdKatanaUtils::ConvertVtValueToKatAttr(vtValue, false);
}
else
{
// Since it doesn't have a special case name, it's a custom attribute.
// We need to create a special description in "geometry.arbitrary"
// group.
static const std::string arbitrary = "geometry.arbitrary.";
attributeKatanaName = arbitrary + iAttr.GetBaseName().GetString();
int elementSize = 1;
iAttr.GetMetadata(UsdGeomTokens->elementSize, &elementSize);
TfToken interpolation;
if (!iAttr.GetMetadata(UsdGeomTokens->interpolation, &interpolation))
{
interpolation = UsdGeomTokens->constant;
}
FnAttribute::StringAttribute scopeAttr =
OpCabooseImpl::interpolationToScope(interpolation);
VtIntArray vtIndices;
attr = OpCabooseImpl::convertVtValueToArbitrary(
vtValue,
vtIndices,
elementSize,
iAttr.GetTypeName(),
interpolation,
scopeAttr);
}
if (!attr.isValid())
{
return {};
}
auto function =
std::make_shared<OpCaboose::ClientAttribute::AttributeSetFn>(std::bind(
&OpCabooseImpl::setGroupBuilder,
std::placeholders::_1,
attributeKatanaName,
attr));
return std::make_shared<OpCaboose::ClientAttribute>(function);
}
<|start_filename|>walter/katana/WalterIn/ArbitraryGeomParamUtils.cpp<|end_filename|>
#include "ArbitraryGeomParamUtils.h"
#include "ArrayPropUtils.h"
#include <Alembic/AbcGeom/All.h>
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnDataBuilder.h>
namespace WalterIn
{
FnAttribute::StringAttribute getScopeAttribute(
Alembic::AbcGeom::GeometryScope scope)
{
switch (scope)
{
case Alembic::AbcGeom::kUniformScope:
return FnAttribute::StringAttribute("face");
case Alembic::AbcGeom::kVaryingScope:
return FnAttribute::StringAttribute("point");
case Alembic::AbcGeom::kVertexScope:
return FnAttribute::StringAttribute("point");
case Alembic::AbcGeom::kFacevaryingScope:
return FnAttribute::StringAttribute("vertex");
default:
return FnAttribute::StringAttribute("primitive");
}
}
std::string getInputType(const Alembic::Abc::PropertyHeader & iPropHeader)
{
std::string interp = iPropHeader.getMetaData().get("interpretation");
Alembic::Util::PlainOldDataType podType =
iPropHeader.getDataType().getPod();
Alembic::Util::uint8_t extent = iPropHeader.getDataType().getExtent();
if (podType == Alembic::Util::kBooleanPOD)
{
return "bool";
}
else if (podType == Alembic::Util::kFloat64POD ||
podType == Alembic::Util::kFloat32POD)
{
if (interp == "point" && extent == 3)
{
return "point3";
}
if (interp == "point" && extent == 4)
{
return "point4";
}
if (interp == "vector" && extent == 3)
{
return "vector3";
}
if (interp == "vector" && extent == 4)
{
return "vector4";
}
// a VERY special case (point2 on purpose)
if (interp == "vector" && extent == 2)
{
return "point2";
}
if (interp == "normal" && extent == 3)
{
return "normal3";
}
if (interp == "normal" && extent == 4)
{
return "normal4";
}
if (interp == "rgb" && extent == 3)
{
return "color3";
}
if (interp == "rgba" && extent == 4)
{
return "color4";
}
if (interp == "matrix" && extent == 9)
{
return "matrix9";
}
if (interp == "matrix" && extent == 16)
{
return "matrix16";
}
if (interp == "quat" && extent == 4)
{
return "point4";
}
}
return "";
}
// read iProp.prop into oGb
template <typename attrT, typename builderT>
void readAsExpandedProp(
IndexedGeomParamPair & iProp,
const OpArgs & iArgs,
FnAttribute::GroupBuilder & oGb)
{
size_t extent = iProp.prop.getDataType().getExtent();
int64_t tupleSize = extent;
builderT b(tupleSize);
Alembic::Abc::TimeSamplingPtr ts = iProp.prop.getTimeSampling();
SampleTimes sampleTimes;
iArgs.getRelevantSampleTimes(ts, iProp.prop.getNumSamples(), sampleTimes);
size_t numIndexed = 0;
Alembic::Util::Dimensions dims;
if (!sampleTimes.empty())
{
SampleTimes::iterator it = sampleTimes.begin();
iProp.indexed.getDimensions(dims, Alembic::Abc::ISampleSelector(*it));
numIndexed = dims.numPoints();
++it;
// make sure every sample we are using is the same size
bool sameSize = true;
for (; it != sampleTimes.end(); ++it)
{
iProp.indexed.getDimensions(dims,
Alembic::Abc::ISampleSelector(*it));
if (numIndexed != dims.numPoints())
{
sameSize = false;
break;
}
}
// not the same, use just a single time
if (!sameSize)
{
sampleTimes.clear();
sampleTimes.push_back(iArgs.getAbcFrameTime());
Alembic::Abc::ISampleSelector ss(*sampleTimes.begin());
iProp.indexed.getDimensions(dims, ss);
numIndexed = dims.numPoints();
}
}
for (SampleTimes::iterator it = sampleTimes.begin();
it != sampleTimes.end(); ++it)
{
std::vector<typename attrT::value_type> packedVals;
std::vector<Alembic::Util::uint32_t> indexedValue(numIndexed);
Alembic::Abc::ISampleSelector ss(*it);
iProp.prop.getDimensions(dims, ss);
size_t numVals = dims.numPoints();
packedVals.resize(extent * numVals);
if (numVals > 0)
{
iProp.prop.getAs(&packedVals.front(), iProp.asPod, ss);
}
if (numIndexed > 0)
{
iProp.indexed.getAs(&indexedValue.front(), ss);
}
// unroll it ourselves
std::vector<typename attrT::value_type> value;
value.resize(extent * indexedValue.size());
size_t packedSize = packedVals.size() / extent;
for (size_t i = 0; i < indexedValue.size(); ++i)
{
Alembic::Util::uint32_t curIndex = indexedValue[i];
if (indexedValue[i] < packedSize)
{
for (size_t j = 0; j < extent; ++j)
{
value[i*extent + j] = packedVals[curIndex * extent + j];
}
}
}
if (sampleTimes.size() == 1)
{
// hopefully this will use a fancy attr
if (value.empty())
{
typename attrT::value_type * nullPtr = NULL;
oGb.set(iProp.name, attrT(nullPtr, 0, tupleSize));
}
else
{
oGb.set(iProp.name, attrT(&value.front(), value.size(),
tupleSize));
}
}
else
{
b.set(value, iArgs.getRelativeSampleTime(*it));
}
}
if (sampleTimes.size() > 1)
{
oGb.set(iProp.name, b.build());
}
}
template <typename attrT, typename geomParamT>
void processArbitraryGeomParam(
Alembic::Abc::ICompoundProperty & iParent,
const Alembic::Abc::PropertyHeader & iPropHeader,
const std::string & iAttrName,
AbcCookPtr ioCook,
FnAttribute::GroupBuilder & oStaticGb,
Alembic::Abc::IUInt64ArrayProperty * iIdsProperty)
{
geomParamT param(iParent, iPropHeader.getName());
attrT a;
Alembic::Util::PlainOldDataType asPod = FnAttrTypeToPODType(
a.getKatAttributeType());
bool forceAsExpanded = (iAttrName.substr(0, 18) != "geometry.arbitrary");
// if a param has no samples, don't even bother creating it
if (param.getNumSamples() == 0)
{
return;
}
if (!forceAsExpanded)
{
oStaticGb.set(iAttrName + ".scope",
getScopeAttribute(Alembic::AbcGeom::GetGeometryScope(
iPropHeader.getMetaData())));
// Calculate the input type
// Notice that if param is an indexed parameter the input type has to
// be retrieved from the value property
const std::string inputType =
param.isIndexed()
? getInputType(param.getValueProperty().getHeader())
: getInputType(iPropHeader);
if (inputType != "")
{
oStaticGb.set(iAttrName + ".inputType",
FnAttribute::StringAttribute(inputType));
}
if (param.getArrayExtent() > 1)
{
int arrayExtent = (int) param.getArrayExtent();
oStaticGb.set(iAttrName + ".elementSize",
FnAttribute::IntAttribute(arrayExtent));
}
}
if (!param.isConstant())
{
if (param.isIndexed() && forceAsExpanded)
{
IndexedGeomParamPair valPair;
valPair.name = iAttrName;
valPair.prop = param.getValueProperty();
valPair.indexed = param.getIndexProperty();
valPair.asPod = asPod;
ioCook->forcedExpandProps.push_back(valPair);
// no reading to do, bail early
return;
}
// don't force expansion
else if (param.isIndexed())
{
if (!param.getValueProperty().isConstant())
{
ArrayProp item;
item.name = iAttrName + ".indexedValue";
item.prop = param.getValueProperty();
item.asPod = asPod;
ioCook->arrayProps.push_back(item);
}
if (!param.getIndexProperty().isConstant())
{
ArrayProp item;
item.name = iAttrName + ".index";
item.prop = param.getIndexProperty();
item.asPod = Alembic::Util::kInt32POD;
ioCook->arrayProps.push_back(item);
}
}
// not indexed!
else
{
ArrayProp item;
item.name = iAttrName;
if (!forceAsExpanded)
{
item.name += ".value";
}
item.prop = param.getValueProperty();
item.asPod = asPod;
ioCook->arrayProps.push_back(item);
}
}
std::string valueName = iAttrName;
OpArgs defaultArgs;
Alembic::Abc::IUInt32ArrayProperty indexProp = param.getIndexProperty();
if (indexProp.valid() && indexProp.isConstant() && !forceAsExpanded)
{
ArrayProp item;
item.name = iAttrName + ".index";
item.prop = indexProp;
item.asPod = Alembic::Util::kInt32POD;
arrayPropertyToAttr(item, defaultArgs, oStaticGb, iIdsProperty);
valueName += ".indexedValue";
}
else if (!forceAsExpanded)
{
valueName += ".value";
}
typename geomParamT::prop_type valueProp;
valueProp = param.getValueProperty();
if ((valueProp.valid() && valueProp.isConstant()) &&
(!forceAsExpanded || !param.isIndexed()))
{
ArrayProp item;
item.name = valueName;
item.prop = valueProp;
item.asPod = asPod;
arrayPropertyToAttr(item, defaultArgs, oStaticGb, iIdsProperty);
}
else if (forceAsExpanded && param.isConstant())
{
IndexedGeomParamPair valPair;
valPair.name = iAttrName;
valPair.prop = param.getValueProperty();
valPair.indexed = param.getIndexProperty();
valPair.asPod = asPod;
// NOTE: we don't support indexed params correlated by IDs (e.g. differing topology)
indexedParamToAttr(valPair, defaultArgs, oStaticGb);
}
}
void indexedParamToAttr(IndexedGeomParamPair & iProp,
const OpArgs & iArgs,
FnAttribute::GroupBuilder & oGb)
{
if (iProp.asPod == Alembic::Util::kFloat32POD)
{
readAsExpandedProp<FnAttribute::FloatAttribute,
FnAttribute::FloatBuilder>(
iProp, iArgs, oGb);
}
else if (iProp.asPod == Alembic::Util::kInt32POD)
{
readAsExpandedProp<FnAttribute::IntAttribute,
FnAttribute::IntBuilder>(
iProp, iArgs, oGb);
}
else if (iProp.asPod == Alembic::Util::kFloat64POD)
{
readAsExpandedProp<FnAttribute::DoubleAttribute,
FnAttribute::DoubleBuilder>(
iProp, iArgs, oGb);
}
else if (iProp.asPod == Alembic::Util::kStringPOD)
{
readAsExpandedProp<FnAttribute::StringAttribute,
FnAttribute::StringBuilder>(
iProp, iArgs, oGb);
}
}
void processArbitraryGeomParam( AbcCookPtr ioCook,
Alembic::Abc::ICompoundProperty & iParent,
const Alembic::AbcCoreAbstract::PropertyHeader & iPropHeader,
FnAttribute::GroupBuilder & oStaticGb,
const std::string & iAttrPath,
Alembic::Abc::IUInt64ArrayProperty * iIdsProperty )
{
if (Alembic::AbcGeom::IFloatGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::FloatAttribute, Alembic::AbcGeom::IFloatGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IDoubleGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::DoubleAttribute,
Alembic::AbcGeom::IDoubleGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IInt32GeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::IntAttribute, Alembic::AbcGeom::IInt32GeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IUInt32GeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::IntAttribute, Alembic::AbcGeom::IUInt32GeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IInt16GeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::IntAttribute, Alembic::AbcGeom::IInt16GeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IUInt16GeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::IntAttribute, Alembic::AbcGeom::IUInt16GeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::ICharGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::IntAttribute, Alembic::AbcGeom::ICharGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IUcharGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::IntAttribute, Alembic::AbcGeom::IUcharGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IBoolGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::IntAttribute, Alembic::AbcGeom::IBoolGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IStringGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::StringAttribute,
Alembic::AbcGeom::IStringGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IV2fGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::FloatAttribute, Alembic::AbcGeom::IV2fGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IV3dGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::DoubleAttribute, Alembic::AbcGeom::IV3dGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IV3fGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::FloatAttribute, Alembic::AbcGeom::IV3fGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IP3fGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::FloatAttribute, Alembic::AbcGeom::IP3fGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IP3dGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::DoubleAttribute, Alembic::AbcGeom::IP3dGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IN3fGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::FloatAttribute, Alembic::AbcGeom::IN3fGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IC3fGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::FloatAttribute, Alembic::AbcGeom::IC3fGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IC4fGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::FloatAttribute, Alembic::AbcGeom::IC4fGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IM44fGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::FloatAttribute, Alembic::AbcGeom::IM44fGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
else if (Alembic::AbcGeom::IQuatfGeomParam::matches(iPropHeader))
{
processArbitraryGeomParam<
FnAttribute::FloatAttribute, Alembic::AbcGeom::IQuatfGeomParam>(
iParent, iPropHeader, iAttrPath, ioCook, oStaticGb, iIdsProperty);
}
}
void processArbGeomParams( AbcCookPtr ioCook,
Alembic::Abc::ICompoundProperty & iParent,
FnAttribute::GroupBuilder & oStaticGb,
Alembic::Abc::v10::IUInt64ArrayProperty * iIdsProperty )
{
if (!iParent.valid())
{
return;
}
std::string attrPath = "geometry.arbitrary.";
for (size_t i = 0; i < iParent.getNumProperties(); ++i)
{
const Alembic::AbcCoreAbstract::PropertyHeader &propHeader =
iParent.getPropertyHeader(i);
processArbitraryGeomParam( ioCook, iParent, propHeader, oStaticGb,
attrPath + propHeader.getName(), iIdsProperty );
}
}
}
<|start_filename|>walter/usd/tests/test_regexEngine.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "PathUtil.h"
#include <gtest/gtest.h>
TEST(regexEngine, matchPattern)
{
EXPECT_EQ(WalterCommon::matchPattern("Boost Libraries", "\\w+\\s\\w+"), true);
}
TEST(regexEngine, mangleString)
{
auto demangled = WalterCommon::mangleString("/Hello /World");
EXPECT_EQ(demangled, "\\Hello \\World");
}
TEST(regexEngine, demangleString)
{
auto demangled = WalterCommon::demangleString("\\Hello \\World");
EXPECT_EQ(demangled, "/Hello /World");
}
TEST(regexEngine, convertRegex)
{
auto converted = WalterCommon::convertRegex("\\d \\D \\w \\W");
EXPECT_EQ(converted, "[0-9] [^0-9] [a-zA-Z0-9_] [^a-zA-Z0-9_]");
}
<|start_filename|>walter/katana/WalterIn/walterUSDOpDelegate.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __WALTERUSDOPDELEGATE_H_
#define __WALTERUSDOPDELEGATE_H_
#include <pxr/usd/usd/prim.h>
#include "walterUSDOpIndex.h"
PXR_NAMESPACE_USING_DIRECTIVE
/** @brief It's a set of utilities to fill the index. It's a class to be able to
* specify the methods as friends of OpIndex. */
class OpDelegate
{
public:
/**
* @brief populates the OpIndex with initial data. Usually it's a list of
* expressions.
*
* @param iRoot The root prim.
* @param oIndex The index to fill.
*/
static void populate(const UsdPrim& iRoot, OpIndex& oIndex);
};
#endif
<|start_filename|>vfx_platform_builder/Makefile<|end_filename|>
####################################################################
# Copyright 2018 <NAME>. All rights reserved.
# Makefile to build external libraries
#
# Usage:
# make
# or
# make MAKE_MODE=debug
#
################################################################################
# Directories
SOURCES_ROOT=/tmp/src
BUILD_ROOT=/tmp/build
PREFIX_ROOT=/tmp/lib
# Versions
ALEMBIC_VERSION := 1.7.1
BLOSC_VERSION := v1.14.0
BOOST_VERSION := 1_55_0
CMAKE_VERSION := 3.7.2
DC_VERSION := v1.1.5
EMBREE_VERSION := v2.17.1
GLEW_VERSION := 2.0.0
GLFW_VERSION := 3.2.1
GLUT_VERSION := 3.0.0
GOOGLETEST_VERSION := release-1.8.0
HDF5_VERSION := 1.8.10
ILMBASE_VERSION := 2.2.0
ISPC_VERSION := v1.9.1
JPEG_VERSION := 1.5.1
JSONCPP_VERSION := 1.8.0
LLVM_VERS := 3.9.0
MERCURIAL_VERSION := 4.1.1
OCIO_VERSION := v1.0.9
OIIO_VERSION := Release-1.8.6
OPENEXR_VERSION := 2.2.0
OPENSUBD_VERSION := v3_2_0
OPENVDB_VERSION := v5.0.0
OSL_VERSION := Release-1.8.12
PNG_VERSION := 1.6.34
PTEX_VERSION := v2.1.28
PYILMBASE_VERSION := v2.2.0
PYOPENGL_VERSION := 3.0.1b1
PYSIDETOOLS_VERSION := 0.2.15
PYSIDE_VERSION := 1.2.4
PYSTRING_VERSION := v1.1.3
PYTHON_VERSION := 2.7.12
QT_VERSION := 4.8.6
QT5BASE_VERSION := v5.9.2
SHIBOKEN_VERSION := 1.2.4
TBB_VERSION := 2017_20161128oss
TIFF_VERSION := 3.8.2
USD_VERSION := v0.8.5
ZLIB_VERSION := v1.2.11
# Set the package name for USD. It also sets the internal namespace for USD.
USD_PACKAGE_NAME := usd
MAKE_MODE := release
ifeq "$(MAKE_MODE)" "debug"
CMAKE_BUILD_TYPE := Debug
else
CMAKE_BUILD_TYPE := Release
endif
# Save the current directory
THIS_DIR := $(shell pwd)
# Stamp files that should indicate that the build is successfull
ALEMBIC_STAMP := $(PREFIX_ROOT)/built_alembic
BLOSC_STAMP := $(PREFIX_ROOT)/built_blosc
BOOST_STAMP := $(PREFIX_ROOT)/built_boost
CMAKE_STAMP := $(PREFIX_ROOT)/built_cmake
DC_STAMP := $(PREFIX_ROOT)/built_dc
EMBREE_STAMP := $(PREFIX_ROOT)/built_embree
GLEW_STAMP := $(PREFIX_ROOT)/built_glew
GLFW_STAMP := $(PREFIX_ROOT)/built_glfw
GLUT_STAMP := $(PREFIX_ROOT)/built_glut
GOOGLETEST_STAMP := $(PREFIX_ROOT)/built_googletest
HDF5_STAMP := $(PREFIX_ROOT)/built_hdf5
ILMBASE_STAMP := $(PREFIX_ROOT)/built_ilmbase
JPEG_STAMP := $(PREFIX_ROOT)/built_jpeg
JSONCPP_STAMP := $(PREFIX_ROOT)/built_jsoncpp
MERCURIAL_STAMP := $(PREFIX_ROOT)/built_mercural
OCIO_STAMP := $(PREFIX_ROOT)/built_ocio
OIIO_STAMP := $(PREFIX_ROOT)/built_oiio
OPENEXR_STAMP := $(PREFIX_ROOT)/built_openexr
OPENSUBD_STAMP := $(PREFIX_ROOT)/built_opensubd
OPENVDB_STAMP := $(PREFIX_ROOT)/built_openvdb
OSL_STAMP := $(PREFIX_ROOT)/built_osl
PNG_STAMP := $(PREFIX_ROOT)/built_png
PTEX_STAMP := $(PREFIX_ROOT)/built_ptex
PYILMBASE_STAMP := $(PREFIX_ROOT)/built_pyilmbase
PYOPENGL_STAMP := $(PREFIX_ROOT)/built_pyopengl
PYSIDE_STAMP := $(PREFIX_ROOT)/built_pyside
PYSIDETOOLS_STAMP := $(PREFIX_ROOT)/built_pysidetools
PYSTRING_STAMP := $(PREFIX_ROOT)/built_pystring
PYTHON_STAMP := $(PREFIX_ROOT)/built_python
QT_STAMP := $(PREFIX_ROOT)/built_qt
QT5BASE_STAMP := $(PREFIX_ROOT)/built_qt5base
SHIBOKEN_STAMP := $(PREFIX_ROOT)/built_shiboken
TBB_STAMP := $(PREFIX_ROOT)/built_tbb
TIFF_STAMP := $(PREFIX_ROOT)/built_tiff
USD_STAMP := $(PREFIX_ROOT)/built_$(USD_PACKAGE_NAME)
ZLIB_STAMP := $(PREFIX_ROOT)/built_zlib
ALEMBIC_SOURCE := git://github.com/alembic/alembic.git
BLOSC_SOURCE := git://github.com/Blosc/c-blosc.git
BOOST_SOURCE := http://sourceforge.net/projects/boost/files/boost/$(subst _,.,$(BOOST_VERSION))/boost_$(BOOST_VERSION).tar.gz
CMAKE_SOURCE := https://cmake.org/files/v$(word 1,$(subst ., ,$(CMAKE_VERSION))).$(word 2,$(subst ., ,$(CMAKE_VERSION)))/cmake-$(CMAKE_VERSION).tar.gz
DC_SOURCE := git://github.com/google/double-conversion.git
EMBREE_SOURCE := git@github.com:embree/embree.git
GLEW_SOURCE := https://sourceforge.net/projects/glew/files/glew/$(GLEW_VERSION)/glew-$(GLEW_VERSION).tgz
GLFW_SOURCE := git://github.com/glfw/glfw.git
GLUT_SOURCE := https://sourceforge.net/projects/freeglut/files/freeglut/$(GLUT_VERSION)/freeglut-$(GLUT_VERSION).tar.gz
GOOGLETEST_SOURCE := git://github.com/google/googletest.git
HDF5_SOURCE := https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-$(word 1,$(subst ., ,$(HDF5_VERSION))).$(word 2,$(subst ., ,$(HDF5_VERSION)))/hdf5-$(HDF5_VERSION)/src/hdf5-$(HDF5_VERSION).tar.gz
ILMBASE_SOURCE := http://download.savannah.nongnu.org/releases/openexr/ilmbase-$(ILMBASE_VERSION).tar.gz
JPEG_SOURCE := git://github.com/libjpeg-turbo/libjpeg-turbo.git
JSONCPP_SOURCE := git://github.com/open-source-parsers/jsoncpp.git
MERCURIAL_SOURCE := https://www.mercurial-scm.org/release/mercurial-$(MERCURIAL_VERSION).tar.gz
OCIO_SOURCE := git://github.com/imageworks/OpenColorIO.git
OIIO_SOURCE := git://github.com/OpenImageIO/oiio.git
OPENEXR_SOURCE := http://download.savannah.nongnu.org/releases/openexr/openexr-$(OPENEXR_VERSION).tar.gz
OPENSUBD_SOURCE := git://github.com/PixarAnimationStudios/OpenSubdiv.git
OPENVDB_SOURCE := git://github.com/dreamworksanimation/openvdb.git
OSL_SOURCE := git://github.com/imageworks/OpenShadingLanguage.git
PNG_SOURCE := https://sourceforge.net/projects/libpng/files/libpng16/$(PNG_VERSION)/libpng-$(PNG_VERSION).tar.gz
PTEX_SOURCE := git://github.com/wdas/ptex.git
PYILMBASE_SOURCE := git://github.com/openexr/openexr.git
PYOPENGL_SOURCE := https://downloads.sourceforge.net/project/pyopengl/PyOpenGL/$(PYOPENGL_VERSION)/PyOpenGL-$(PYOPENGL_VERSION).tar.gz
PYSIDE_SOURCE := <EMAIL>:pyside/PySide.git
PYSIDETOOLS_SOURCE := <EMAIL>:pyside/Tools.git
PYSTRING_SOURCE := git://github.com/imageworks/pystring.git
PYTHON_SOURCE := https://www.python.org/ftp/python/$(PYTHON_VERSION)/Python-$(PYTHON_VERSION).tgz
QT_SOURCE := http://mirror.csclub.uwaterloo.ca/qtproject/archive/qt/$(word 1,$(subst ., ,$(QT_VERSION))).$(word 2,$(subst ., ,$(QT_VERSION)))/$(QT_VERSION)/qt-everywhere-opensource-src-$(QT_VERSION).tar.gz
QT5BASE_SOURCE := <EMAIL>:qt/qtbase.git
SHIBOKEN_SOURCE := <EMAIL>:pyside/Shiboken.git
TBB_SOURCE := https://www.threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb$(TBB_VERSION)_src.tgz
TIFF_SOURCE := http://dl.maptools.org/dl/libtiff/tiff-$(TIFF_VERSION).tar.gz
USD_SOURCE := git://github.com/PixarAnimationStudios/USD
ZLIB_SOURCE := git://github.com/madler/zlib.git
ALEMBIC_FILE := $(SOURCES_ROOT)/$(notdir $(ALEMBIC_SOURCE))
BLOSC_FILE := $(SOURCES_ROOT)/$(notdir $(BLOSC_SOURCE))
BOOST_FILE := $(SOURCES_ROOT)/$(notdir $(BOOST_SOURCE))
CMAKE_FILE := $(SOURCES_ROOT)/$(notdir $(CMAKE_SOURCE))
DC_FILE := $(SOURCES_ROOT)/$(notdir $(DC_SOURCE))
EMBREE_FILE := $(SOURCES_ROOT)/$(notdir $(EMBREE_SOURCE))
GLEW_FILE := $(SOURCES_ROOT)/$(notdir $(GLEW_SOURCE))
GLFW_FILE := $(SOURCES_ROOT)/$(notdir $(GLFW_SOURCE))
GLUT_FILE := $(SOURCES_ROOT)/$(notdir $(GLUT_SOURCE))
GOOGLETEST_FILE := $(SOURCES_ROOT)/$(notdir $(GOOGLETEST_SOURCE))
HDF5_FILE := $(SOURCES_ROOT)/$(notdir $(HDF5_SOURCE))
ILMBASE_FILE := $(SOURCES_ROOT)/$(notdir $(ILMBASE_SOURCE))
JPEG_FILE := $(SOURCES_ROOT)/$(notdir $(JPEG_SOURCE))
JSONCPP_FILE := $(SOURCES_ROOT)/$(notdir $(JSONCPP_SOURCE))
MERCURIAL_FILE := $(SOURCES_ROOT)/$(notdir $(MERCURIAL_SOURCE))
OCIO_FILE := $(SOURCES_ROOT)/$(notdir $(OCIO_SOURCE))
OIIO_FILE := $(SOURCES_ROOT)/$(notdir $(OIIO_SOURCE))
OPENEXR_FILE := $(SOURCES_ROOT)/$(notdir $(OPENEXR_SOURCE))
OPENSUBD_FILE := $(SOURCES_ROOT)/$(notdir $(OPENSUBD_SOURCE))
OPENVDB_FILE := $(SOURCES_ROOT)/$(notdir $(OPENVDB_SOURCE))
OSL_FILE := $(SOURCES_ROOT)/$(notdir $(OSL_SOURCE))
PNG_FILE := $(SOURCES_ROOT)/$(notdir $(PNG_SOURCE))
PTEX_FILE := $(SOURCES_ROOT)/$(notdir $(PTEX_SOURCE))
PYILMBASE_FILE := $(SOURCES_ROOT)/$(notdir $(PYILMBASE_SOURCE))
PYOPENGL_FILE := $(SOURCES_ROOT)/$(notdir $(PYOPENGL_SOURCE))
PYSIDE_FILE := $(SOURCES_ROOT)/$(notdir $(PYSIDE_SOURCE))
PYSIDETOOLS_FILE := $(SOURCES_ROOT)/$(notdir $(PYSIDETOOLS_SOURCE))
PYSTRING_FILE := $(SOURCES_ROOT)/$(notdir $(PYSTRING_SOURCE))
PYTHON_FILE := $(SOURCES_ROOT)/$(notdir $(PYTHON_SOURCE))
QT_FILE := $(SOURCES_ROOT)/$(notdir $(QT_SOURCE))
QT5BASE_FILE := $(SOURCES_ROOT)/$(notdir $(QT5BASE_SOURCE))
SHIBOKEN_FILE := $(SOURCES_ROOT)/$(notdir $(SHIBOKEN_SOURCE))
TBB_FILE := $(SOURCES_ROOT)/$(notdir $(TBB_SOURCE))
TIFF_FILE := $(SOURCES_ROOT)/$(notdir $(TIFF_SOURCE))
USD_FILE := $(SOURCES_ROOT)/$(notdir $(USD_SOURCE))
ZLIB_FILE := $(SOURCES_ROOT)/$(notdir $(ZLIB_SOURCE))
# Number of processors
ifeq "$(OS)" "Darwin"
JOB_COUNT := $(shell sysctl -n machdep.cpu.thread_count)
endif
ifeq "$(OS)" "linux"
JOB_COUNT := $(shell cat /sys/devices/system/cpu/cpu*/topology/thread_siblings | wc -l)
endif
# DSO extension
DYNAMIC_EXT := .a
ifeq "$(BOOST_LINK)" "shared"
ifeq "$(OS)" "Darwin"
DYNAMIC_EXT := .dylib
endif
ifeq "$(OS)" "linux"
DYNAMIC_EXT := .so
endif
endif
# Compiler specific options.
# Try to use the compiler of devtoolset-2 first.
GCC_BIN_PATH := /opt/rh/devtoolset-2/root/usr/bin
ifeq ("$(wildcard $(GCC_BIN_PATH)/gcc)","")
GCC_BIN_PATH := /usr/bin
endif
AR := $(shell which ar)
AUTORECONF := $(shell which autoreconf)
CC := $(GCC_BIN_PATH)/gcc
CXX := $(GCC_BIN_PATH)/g++
LIBTOOL := $(shell which libtool)
MAKE := $(shell which make)
NASM := $(shell which nasm)
FLAGS := -fPIC
BOOST_LINK := static
PYTHON :=
HOUDINI_ROOT := ""
BUILD_HOUDINI_PLUGINS := ON
KATANA_ROOT := ""
BUILD_KATANA_PLUGINS := ON
MAYA_ROOT := ""
CLANG := $(PREFIX_ROOT)/llvm/bin/clang
ISPC := $(PREFIX_ROOT)/ispc/bin/ispc
BISON := $(PREFIX_ROOT)/bison/bin/bison
FLEX := $(PREFIX_ROOT)/flex/bin/flex
# Change tbb namespace. We need it to avoid conflicts with tbb already used in
# Maya.
ifeq "$(TBB_NAMESPACE)" ""
FLAGS += -Dtbb=rdotbb
else
ifneq "$(TBB_NAMESPACE)" "tbb"
FLAGS += -Dtbb=$(TBB_NAMESPACE)
endif
endif
ifeq "$(PYTHON)" ""
PYTHON_BIN := $(PREFIX_ROOT)/python/bin/python
PYTHON_VERSION_SHORT := $(word 1,$(subst ., ,$(PYTHON_VERSION))).$(word 2,$(subst ., ,$(PYTHON_VERSION)))
else
PYTHON_BIN := $(PYTHON)
PYTHON_VERSION_SHORT = 2.7
PYTHON_STAMP =
endif
PYTHON_ROOT := $(realpath $(dir $(PYTHON_BIN))/..)
ifeq "$(MAKE_MODE)" "debug"
FLAGS += -g
else
FLAGS += -O3
endif
ifeq "$(BOOST_VERSION)" "1_55_0"
ifeq "$(OS)" "Darwin"
# Fixed macOS compilation error for boost 1.55.0
# https://svn.boost.org/trac/boost/ticket/9610
FLAGS += -DBOOST_HAS_INT128=1
endif
endif
COMPILER_CONF :=\
CC="$(CC)" \
CXX="$(CXX)" \
CFLAGS="$(FLAGS)" \
CXXFLAGS="$(FLAGS)"
CMAKE := $(PREFIX_ROOT)/cmake/bin/cmake
COMMON_CMAKE_FLAGS :=\
-DCMAKE_BUILD_TYPE:STRING=$(CMAKE_BUILD_TYPE) \
-DCMAKE_CXX_COMPILER:STRING=$(CXX) \
-DCMAKE_CXX_FLAGS:STRING="$(FLAGS)" \
-DCMAKE_C_COMPILER:STRING=$(CC) \
-DCMAKE_C_FLAGS:STRING="$(FLAGS)" \
-DCMAKE_INSTALL_LIBDIR=lib \
-DCMAKE_INSTALL_RPATH_USE_LINK_PATH:BOOL=ON \
-DCMAKE_POSITION_INDEPENDENT_CODE:BOOL=ON \
-DCMAKE_SHARED_LINKER_FLAGS=-Wl,--no-undefined \
-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON
PYSIDE_CONF := \
PYTHONPATH=$(PREFIX_ROOT)/pyside/lib/python2.7/site-packages:$(PREFIX_ROOT)/shiboken/lib/python2.7/site-packages:$(PREFIX_ROOT)/pyopengl/lib/python2.7/site-packages
ALL_TARGETS :=\
$(ALEMBIC_STAMP) \
$(GOOGLETEST_STAMP) \
$(JSONCPP_STAMP) \
$(OIIO_STAMP) \
$(OPENVDB_STAMP) \
$(USD_STAMP)
manglevariable = `echo -e "void $(1)() {} " | $(CXX) -x c++ -S - -o- | grep "^_.*:$$" | sed -e 's/v:$$//' | sed -e 's/^_Z//'`
all: $(ALL_TARGETS)
# Shortcuts
alembic: $(ALEMBIC_STAMP)
blosc: $(BLOSC_STAMP)
boost: $(BOOST_STAMP)
cmake: $(CMAKE_STAMP)
doubleconversion: $(DC_STAMP)
embree: $(EMBREE_STAMP)
glew: $(GLEW_STAMP)
glfw: $(GLFW_STAMP)
glut: $(GLUT_STAMP)
googletest: $(GOOGLETEST_STAMP)
hdf5: $(HDF5_STAMP)
ilmbase: $(ILMBASE_STAMP)
ispc: $(ISPC)
jpeg: $(JPEG_STAMP)
jsoncpp: $(JSONCPP_STAMP)
llvm: $(CLANG)
mercurial: $(MERCURIAL_STAMP)
ocio: $(OCIO_STAMP)
oiio: $(OIIO_STAMP)
openexr: $(OPENEXR_STAMP)
opensubdiv: $(OPENSUBD_STAMP)
openvdb: $(OPENVDB_STAMP)
osl: $(OSL_STAMP)
png: $(PNG_STAMP)
ptex: $(PTEX_STAMP)
pyilmbase: $(PYILMBASE_STAMP)
pyopengl: $(PYOPENGL_STAMP)
pyside: $(PYSIDE_STAMP)
pysidetools: $(PYSIDETOOLS_STAMP)
pystring: $(PYSTRING_STAMP)
python: $(PYTHON_STAMP)
qt: $(QT_STAMP)
qt5: $(QT5BASE_STAMP)
shiboken: $(SHIBOKEN_STAMP)
tbb: $(TBB_STAMP)
tiff: $(TIFF_STAMP)
usd: $(USD_STAMP)
zlib: $(ZLIB_STAMP)
download : $(BOOST_FILE) $(CMAKE_FILE) $(ILMBASE_FILE) $(JPEG_FILE)/HEAD $(JSONCPP_FILE)/HEAD $(OCIO_FILE)/HEAD $(OIIO_FILE)/HEAD $(OPENEXR_FILE) $(PNG_FILE) $(PYSTRING_FILE)/HEAD $(PYTHON_FILE) $(TIFF_FILE) $(ZLIB_FILE)/HEAD
help:
@printf 'Automatic building system for external tools\n\n' ; \
printf 'Usage:\n\tmake\nor\n\tmake MAKE_MODE=debug\n\n' ; \
printf 'Options:\n' ; \
printf '\tCC\t\t: C copiler path\t: $(CC)\n' ; \
printf '\tCXX\t\t: C++ copiler path\t: $(CXX)\n' ; \
printf '\tMAKE_MODE\t: debug|release\t\t: $(MAKE_MODE)\n' ; \
printf '\tSOURCES_ROOT\t: Source directory\t: $(SOURCES_ROOT)\n' ; \
printf '\tBUILD_ROOT\t: Building directory\t: $(BUILD_ROOT)\n' ; \
printf '\tPREFIX_ROOT\t: Installation dir\t: $(PREFIX_ROOT)\n' ; \
printf '\nTo build Alembic or OIIO:\n\tmake\n\n' ; \
printf '\nTo build USD:\n\tmake BOOST_LINK=shared usd\n\n' ; \
printf 'CentOS packages to install:\n' ; \
printf 'nasm libXxf86vm-devel\n' ; \
printf '\nBuild everything with clang:\n' ; \
printf 'make PREFIX_ROOT=/tmp/tmplib llvm\n' ; \
printf 'make CC=/tmp/tmplib/llvm/bin/clang CXX=/tmp/tmplib/llvm/bin/clang++ llvm\n' ; \
printf 'make CC=/tmp/lib/llvm/bin/clang CXX=/tmp/lib/llvm/bin/clang++\n\n' ; \
printf '\nBuild PyAlembic:\n' ; \
printf 'make BOOST_NAMESPACE=rdoBoostAlembic BOOST_LINK=shared alembic\n\n' ; \
printf '\nBuild USD with custom namespace:\n' ; \
printf 'make USD_PACKAGE_NAME=usdProcedural\n\n' ;
# Download
$(ALEMBIC_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(ALEMBIC_FILE)... && \
git clone -q --bare $(ALEMBIC_SOURCE) $(ALEMBIC_FILE)
$(BLOSC_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(BLOSC_FILE)... && \
git clone -q --bare $(BLOSC_SOURCE) $(BLOSC_FILE)
$(BOOST_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(BOOST_FILE)... && \
curl -s -o $@ -L $(BOOST_SOURCE)
$(CMAKE_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(CMAKE_FILE)... && \
curl -s -o $@ -L $(CMAKE_SOURCE)
$(DC_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(DC_FILE)... && \
git clone -q --bare $(DC_SOURCE) $(DC_FILE)
$(EMBREE_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(EMBREE_FILE)... && \
git clone -q --bare $(EMBREE_SOURCE) $(EMBREE_FILE)
$(GLEW_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(GLEW_FILE)... && \
curl -s -o $@ -L $(GLEW_SOURCE)
$(GLFW_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(GLFW_FILE)... && \
git clone -q --bare $(GLFW_SOURCE) $(GLFW_FILE)
$(GLUT_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(GLUT_FILE)... && \
curl -s -o $@ -L $(GLUT_SOURCE)
$(GOOGLETEST_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(GOOGLETEST_FILE)... && \
git clone -q --bare $(GOOGLETEST_SOURCE) $(GOOGLETEST_FILE)
$(HDF5_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(HDF5_FILE)... && \
curl --tlsv1.2 -s -o $@ -L $(HDF5_SOURCE)
$(ILMBASE_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(ILMBASE_FILE)... && \
curl -s -o $@ -L $(ILMBASE_SOURCE)
$(JPEG_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(JPEG_FILE)... && \
git clone -q --bare $(JPEG_SOURCE) $(JPEG_FILE)
$(JSONCPP_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(JSONCPP_FILE)... && \
git clone -q --bare $(JSONCPP_SOURCE) $(JSONCPP_FILE)
$(MERCURIAL_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(MERCURIAL_FILE)... && \
curl -s -o $@ -L $(MERCURIAL_SOURCE)
$(OCIO_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(OCIO_FILE)... && \
git clone -q --bare $(OCIO_SOURCE) $(OCIO_FILE)
$(OIIO_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(OIIO_FILE)... && \
git clone -q --bare $(OIIO_SOURCE) $(OIIO_FILE)
$(OPENEXR_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(OPENEXR_FILE)... && \
curl -s -o $@ -L $(OPENEXR_SOURCE)
$(OPENSUBD_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(OPENSUBD_FILE)... && \
git clone -q --bare $(OPENSUBD_SOURCE) $(OPENSUBD_FILE)
$(OPENVDB_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(OPENVDB_FILE)... && \
git clone -q --bare $(OPENVDB_SOURCE) $(OPENVDB_FILE)
$(OSL_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(OSL_FILE)... && \
git clone -q --bare $(OSL_SOURCE) $(OSL_FILE)
$(PNG_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(PNG_FILE)... && \
curl -s -o $@ -L $(PNG_SOURCE)
$(PTEX_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(PTEX_FILE)... && \
git clone -q --bare $(PTEX_SOURCE) $(PTEX_FILE)
$(PYILMBASE_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(PYILMBASE_FILE)... && \
git clone -q --bare $(PYILMBASE_SOURCE) $(PYILMBASE_FILE)
$(PYOPENGL_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(PYOPENGL_FILE)... && \
curl --tlsv1.2 -s -o $@ -L $(PYOPENGL_SOURCE)
$(PYSIDE_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(PYSIDE_FILE)... && \
git clone -q --bare $(PYSIDE_SOURCE) $(PYSIDE_FILE)
$(PYSIDETOOLS_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(PYSIDETOOLS_FILE)... && \
git clone -q --bare $(PYSIDETOOLS_SOURCE) $(PYSIDETOOLS_FILE)
$(PYSTRING_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(PYSTRING_FILE)... && \
git clone -q --bare $(PYSTRING_SOURCE) $(PYSTRING_FILE)
$(PYTHON_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(PYTHON_FILE)... && \
curl -s -o $@ -L $(PYTHON_SOURCE)
$(QT_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(QT_FILE)... && \
curl -s -o $@ -L $(QT_SOURCE)
$(QT5BASE_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(QT5BASE_FILE)... && \
git clone -q --bare $(QT5BASE_SOURCE) $(QT5BASE_FILE)
$(SHIBOKEN_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(SHIBOKEN_FILE)... && \
git clone -q --bare $(SHIBOKEN_SOURCE) $(SHIBOKEN_FILE)
$(TBB_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(TBB_FILE)... && \
curl -s -o $@ -L $(TBB_SOURCE)
$(TIFF_FILE) :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(TIFF_FILE)... && \
curl -s -o $@ -L $(TIFF_SOURCE)
$(ZLIB_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(ZLIB_FILE)... && \
git clone -q --bare $(ZLIB_SOURCE) $(ZLIB_FILE)
$(USD_FILE)/HEAD :
@mkdir -p $(SOURCES_ROOT) && \
echo Downloading $(USD_FILE)... && \
git clone -q --bare $(USD_SOURCE) $(USD_FILE)
# Boost
ifeq "$(BOOST_VERSION)" "1_55_0"
BOOST_USERCONFIG := tools/build/v2/user-config.jam
else
BOOST_USERCONFIG := tools/build/src/user-config.jam
endif
BOOST_NAMESPACE := rdoBoost
ifeq "$(BOOST_LINK)" "shared"
USE_STATIC_BOOST := OFF
USE_SHARED_BOOST := ON
else
USE_STATIC_BOOST := ON
USE_SHARED_BOOST := OFF
PYILMBASE_STAMP :=
PYSIDETOOLS_STAMP :=
PYSIDE_STAMP :=
endif
$(BOOST_STAMP) : $(PYTHON_STAMP) $(BOOST_FILE)
@echo Building boost $(BOOST_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf boost_$(BOOST_VERSION) && \
rm -rf $(BOOST_NAMESPACE) && \
tar -xf $(SOURCES_ROOT)/boost_$(BOOST_VERSION).tar.gz && \
cd boost_$(BOOST_VERSION) && \
echo ">>>" Patching Boost. Regex crashed when defining the second time... && \
( printf "/static object_data/s/static object_data/object_data/\nw\nq" | ed -s boost/regex/pending/object_cache.hpp ) && \
mkdir -p $(PREFIX_ROOT) && \
$(COMPILER_CONF) TOOLSET=cc \
./bootstrap.sh > $(PREFIX_ROOT)/log_boost.txt 2>&1 && \
echo 'using gcc : 4.8 : "$(CXX)" ;' >> $(BOOST_USERCONFIG) && \
./b2 \
-j $(JOB_COUNT) \
tools/bcp >> $(PREFIX_ROOT)/log_boost.txt 2>&1 && \
mkdir ../$(BOOST_NAMESPACE) && \
dist/bin/bcp \
--namespace=$(BOOST_NAMESPACE) \
--namespace-alias \
build libs boost tools bootstrap.sh bootstrap.bat boostcpp.jam boost-build.jam \
$(BUILD_ROOT)/$(BOOST_NAMESPACE) >> $(PREFIX_ROOT)/log_boost.txt 2>&1 && \
cd ../$(BOOST_NAMESPACE) && \
$(COMPILER_CONF) TOOLSET=cc \
./bootstrap.sh \
--with-python-version=$(PYTHON_VERSION_SHORT) \
--with-python-root=$(PYTHON_ROOT) \
--with-python=$(PYTHON_BIN) \
--prefix=$(PREFIX_ROOT)/boost >> $(PREFIX_ROOT)/log_boost.txt 2>&1 && \
./b2 \
--layout=system \
--prefix=$(PREFIX_ROOT)/boost \
-j $(JOB_COUNT) \
-s NO_BZIP2=1 \
link=$(BOOST_LINK) \
threading=multi \
toolset=gcc-4.8 \
cxxflags="$(FLAGS)" cflags="$(FLAGS)" \
include=$(PYTHON_ROOT)/include/python$(PYTHON_VERSION_SHORT) \
$(MAKE_MODE) \
stage \
install >> $(PREFIX_ROOT)/log_boost.txt 2>&1 && \
cd .. && \
rm -rf boost_$(BOOST_VERSION) && \
rm -rf $(BOOST_NAMESPACE) && \
cd $(THIS_DIR) && \
echo $(BOOST_VERSION) > $@
# Alembic
# Edits:
# - Remove Werror, it fails the build.
$(ALEMBIC_STAMP) : $(BOOST_STAMP) $(CMAKE_STAMP) $(HDF5_STAMP) $(ILMBASE_STAMP) $(OPENEXR_STAMP) $(PYILMBASE_STAMP) $(ZLIB_STAMP) $(ALEMBIC_FILE)/HEAD
@echo Building Alembic $(ALEMBIC_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf alembic && \
git clone -q --no-checkout $(SOURCES_ROOT)/alembic.git alembic && \
cd alembic && \
git checkout -q $(ALEMBIC_VERSION) && \
git apply $(THIS_DIR)/patches/Alembic/0001-RodeoFX-modification-of-AbcConvert.patch && \
git apply $(THIS_DIR)/patches/Alembic/0002-RodeoFX-modification-of-AbcConvert.patch && \
git apply $(THIS_DIR)/patches/Alembic/0003-AbcExport-the-ability-to-set-metadata.patch && \
git apply $(THIS_DIR)/patches/Alembic/0004-AbcCoreLayer-merging-objects-with-different-names.patch && \
git apply $(THIS_DIR)/patches/Alembic/0005-AbcGeom-ability-to-add-replace-metadata-to-UVs.patch && \
git apply $(THIS_DIR)/patches/Alembic/0006-RodeoFX-modification-of-AbcConvert.patch && \
git apply $(THIS_DIR)/patches/Alembic/0007-RodeoFX-AbcConvert-replace-string-properties.patch && \
git apply $(THIS_DIR)/patches/Alembic/0008-RodeoFX-ability-to-change-property-name.patch && \
git apply $(THIS_DIR)/patches/Alembic/0009-RodeoFX-better-help-string.patch && \
git apply $(THIS_DIR)/patches/Alembic/0010-RodeoFX-ability-to-change-the-names-of-compounds.patch && \
( printf '/Werror/d\nw\nq' | ed -s CMakeLists.txt ) && \
( printf "/INSTALL/a\nFoundation.h\n.\nw\nq" | ed -s lib/Alembic/AbcCoreLayer/CMakeLists.txt ) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DALEMBIC_ILMBASE_LINK_STATIC:BOOL=ON \
-DALEMBIC_LIB_USES_BOOST:BOOL=ON \
-DALEMBIC_SHARED_LIBS:BOOL=OFF \
-DBOOST_ROOT:STRING=$(PREFIX_ROOT)/boost \
-DBUILD_SHARED_LIBS:BOOL=OFF \
-DBoost_NAMESPACE=$(BOOST_NAMESPACE) \
-DCMAKE_CXX_FLAGS="$(FLAGS) -fPIC -std=c++11" \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/alembic \
-DHDF5_ROOT=$(PREFIX_ROOT)/hdf5 \
-DILMBASE_ROOT=$(PREFIX_ROOT)/ilmbase \
-DMAYA_ROOT=$(MAYA_ROOT) \
-DPYILMBASE_ROOT:PATH=$(PREFIX_ROOT)/pyilmbase \
-DPYTHON_EXECUTABLE:FILEPATH=$(PYTHON_BIN) \
-DUSE_BOOSTREGEX:BOOL=ON \
-DUSE_HDF5:BOOL=ON \
-DUSE_MAYA:BOOL=ON \
-DUSE_PYALEMBIC:BOOL=$(USE_SHARED_BOOST) \
-DUSE_STATIC_BOOST:BOOL=$(USE_STATIC_BOOST) \
-DUSE_STATIC_HDF5:BOOL=ON \
-DUSE_TESTS:BOOL=OFF \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
. > $(PREFIX_ROOT)/log_alembic.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_alembic.txt 2>&1 && \
cd .. && \
rm -rf alembic && \
cd $(THIS_DIR) && \
echo $(ALEMBIC_VERSION) > $@
# BLOSC
$(BLOSC_STAMP) : $(CMAKE_STAMP) $(BLOSC_FILE)/HEAD
@echo Building Blosc $(BLOSC_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(BLOSC_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(BLOSC_FILE)) $(notdir $(basename $(BLOSC_FILE))) && \
cd $(notdir $(basename $(BLOSC_FILE))) && \
git checkout -q $(BLOSC_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBUILD_BENCHMARKS:BOOL=OFF \
-DBUILD_SHARED:BOOL=OFF \
-DBUILD_STATIC:BOOL=ON \
-DBUILD_TESTS:BOOL=OFF \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/blosc \
-DPREFER_EXTERNAL_ZLIB:BOOL=ON \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
. > $(PREFIX_ROOT)/log_blosc.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_blosc.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(BLOSC_FILE))) && \
cd $(THIS_DIR) && \
echo $(BLOSC_VERSION) > $@
# Bison
$(BISON) :
@echo Building Bison && \
$(MAKE) $(MAKE_OPTS) -C ./system \
BUILD_ROOT=$(BUILD_ROOT) \
CLANG=$(CLANG) \
CMAKE=$(CMAKE) \
CMAKE_BUILD_TYPE=$(CMAKE_BUILD_TYPE) \
COMMON_CMAKE_FLAGS='$(COMMON_CMAKE_FLAGS)' \
PREFIX_ROOT=$(PREFIX_ROOT) \
SOURCES_ROOT=$(SOURCES_ROOT) \
bison -j$(JOB_COUNT) > $(PREFIX_ROOT)/log_bison.txt 2>&1
# CMake
$(CMAKE_STAMP) : $(CMAKE_FILE)
@echo Building cmake $(CMAKE_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf cmake-$(CMAKE_VERSION) && \
tar -xf $(SOURCES_ROOT)/cmake-$(CMAKE_VERSION).tar.gz && \
cd cmake-$(CMAKE_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(COMPILER_CONF) \
./configure \
--prefix="$(PREFIX_ROOT)/cmake" \
--parallel=$(JOB_COUNT) \
--no-qt-gui \
--no-server \
--verbose > $(PREFIX_ROOT)/log_cmake.txt 2>&1 && \
$(MAKE) -j$(JOB_COUNT) \
MAKE_MODE=$(MAKE_MODE) \
install >> $(PREFIX_ROOT)/log_cmake.txt 2>&1 && \
cd .. && \
rm -rf cmake-$(CMAKE_VERSION) && \
cd $(THIS_DIR) && \
echo $(CMAKE_VERSION) > $@
# DoubleConversion
$(DC_STAMP) : $(CMAKE_STAMP) $(DC_FILE)/HEAD
@echo Building double-conversion $(DC_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(DC_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(DC_FILE)) $(notdir $(basename $(DC_FILE))) && \
cd $(notdir $(basename $(DC_FILE))) && \
git checkout -q $(DC_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/dc \
. > $(PREFIX_ROOT)/log_dc.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_dc.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(DC_FILE))) && \
cd $(THIS_DIR) && \
echo $(DC_VERSION) > $@
# DoubleConversion
$(EMBREE_STAMP) : $(CMAKE_STAMP) $(ISPC) $(GLUT_STAMP) $(EMBREE_FILE)/HEAD $(TBB_STAMP)
@echo Building embree $(EMBREE_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(EMBREE_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(EMBREE_FILE)) $(notdir $(basename $(EMBREE_FILE))) && \
cd $(notdir $(basename $(EMBREE_FILE))) && \
git checkout -q $(EMBREE_VERSION) && \
( printf '/ADD_EXECUTABLE/a\nfind_package(X11 REQUIRED)\n.\nw\nq' | ed -s common/cmake/tutorial.cmake ) && \
( printf '/TARGET_LINK_LIBRARIES/s/)/ \044{X11_LIBRARIES} Xxf86vm Xrandr)/\nw\nq' | ed -s common/cmake/tutorial.cmake ) && \
( printf '/TARGET_LINK_LIBRARIES.*ispc/s/)/ \044{X11_LIBRARIES} Xxf86vm Xrandr)/\nw\nq' | ed -s common/cmake/tutorial.cmake ) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/embree \
-DEMBREE_IGNORE_CMAKE_CXX_FLAGS:BOOL=OFF \
-DEMBREE_STATIC_LIB:BOOL=ON \
-DEMBREE_TUTORIALS:BOOL=ON \
-DGLUT_Xmu_LIBRARY= \
-DISPC_DIR_HINT=$(dir $(ISPC)) \
-DTBB_INCLUDE_DIR=$(PREFIX_ROOT)/tbb/include \
-DTBB_LIBRARY=$(PREFIX_ROOT)/tbb/lib/libtbb.a \
-DTBB_LIBRARY_MALLOC=$(PREFIX_ROOT)/tbb/lib/libtbb.a \
-D_GLUT_INC_DIR:PATH=$(PREFIX_ROOT)/glut/include \
-D_GLUT_glut_LIB_DIR:PATH=$(PREFIX_ROOT)/glut/lib \
. > $(PREFIX_ROOT)/log_embree.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_embree.txt 2>&1 && \
cp -rf *.a $(PREFIX_ROOT)/embree/lib && \
cd .. && \
rm -rf $(notdir $(basename $(EMBREE_FILE))) && \
cd $(THIS_DIR) && \
echo $(DC_VERSION) > $@
# Flex
$(FLEX) :
@echo Building Flex && \
$(MAKE) $(MAKE_OPTS) -C ./system \
BUILD_ROOT=$(BUILD_ROOT) \
CLANG=$(CLANG) \
CMAKE=$(CMAKE) \
CMAKE_BUILD_TYPE=$(CMAKE_BUILD_TYPE) \
COMMON_CMAKE_FLAGS='$(COMMON_CMAKE_FLAGS)' \
PREFIX_ROOT=$(PREFIX_ROOT) \
SOURCES_ROOT=$(SOURCES_ROOT) \
flex -j$(JOB_COUNT) > $(PREFIX_ROOT)/log_flex.txt 2>&1
# glew
# Edits:
# - define GLEW_STATIC
# link glewinfo and visualinfo statically
$(GLEW_STAMP) : $(CMAKE_STAMP) $(GLEW_FILE)
@echo Building glew $(GLEW_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(GLEW_FILE))) && \
tar zxf $(SOURCES_ROOT)/$(notdir $(GLEW_FILE)) && \
cd $(notdir $(basename $(GLEW_FILE))) && \
( printf "0a\n#define GLEW_STATIC\n.\nw\nq\n" | ed -s include/GL/glew.h ) && \
( printf "0a\n#define GLEW_STATIC\n.\nw\nq\n" | ed -s include/GL/wglew.h ) && \
( printf "/target_link_libraries.*glewinfo/s/glew)/glew_s)/\nw\nq" | ed -s build/cmake/CMakeLists.txt ) && \
( printf "/target_link_libraries.*visualinfo/s/glew)/glew_s)/\nw\nq" | ed -s build/cmake/CMakeLists.txt ) && \
( printf "/CMAKE_DEBUG_POSTFIX/d\nw\nq" | ed -s build/cmake/CMakeLists.txt ) && \
cd build && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/glew \
./cmake > $(PREFIX_ROOT)/log_glew.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_glew.txt 2>&1 && \
( ls -d -1 $(PREFIX_ROOT)/glew/lib/*GLEW* | grep -v -F .a | xargs rm ) && \
cd ../.. && \
rm -rf $(notdir $(basename $(GLEW_FILE))) && \
cd $(THIS_DIR) && \
echo $(GLEW_VERSION) > $@
# glfw
$(GLFW_STAMP) : $(CMAKE_STAMP) $(GLFW_FILE)/HEAD
@echo Building glfw $(GLFW_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(GLFW_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(GLFW_FILE)) $(notdir $(basename $(GLFW_FILE))) && \
cd $(notdir $(basename $(GLFW_FILE))) && \
git checkout -q $(GLFW_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DGLFW_BUILD_DOCS:BOOL=OFF \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/glfw \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
. > $(PREFIX_ROOT)/log_glfw.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_glfw.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(GLFW_FILE))) && \
cd $(THIS_DIR) && \
echo $(GLFW_VERSION) > $@
# glut
$(GLUT_STAMP) : $(CMAKE_STAMP) $(GLUT_FILE)
@echo Building glut $(GLUT_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(basename $(GLUT_FILE)))) && \
tar -xf $(SOURCES_ROOT)/$(notdir $(GLUT_FILE)) && \
cd $(notdir $(basename $(basename $(GLUT_FILE)))) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DFREEGLUT_BUILD_SHARED_LIBS:BOOL=OFF \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/glut \
. > $(PREFIX_ROOT)/log_glut.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_glut.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(basename $(GLUT_FILE)))) && \
cd $(THIS_DIR) && \
echo $(GLUT_VERSION) > $@
# Google Test
$(GOOGLETEST_STAMP) : $(CMAKE_STAMP) $(GOOGLETEST_FILE)/HEAD
@echo Building Google Test $(GOOGLETEST_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(GOOGLETEST_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(GOOGLETEST_FILE)) $(notdir $(basename $(GOOGLETEST_FILE))) && \
cd $(notdir $(basename $(GOOGLETEST_FILE))) && \
git checkout -q $(GOOGLETEST_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/googletest \
. > $(PREFIX_ROOT)/log_googletest.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_googletest.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(GOOGLETEST_FILE))) && \
cd $(THIS_DIR) && \
echo $(GOOGLETEST_VERSION) > $@
# HDF5
$(HDF5_STAMP) : $(CMAKE_STAMP) $(ZLIB_STAMP) $(HDF5_FILE)
@echo Building HDF5 $(HDF5_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf hdf5-$(HDF5_VERSION) && \
tar -xf $(SOURCES_ROOT)/hdf5-$(HDF5_VERSION).tar.gz && \
cd hdf5-$(HDF5_VERSION) && \
( test $$OS != linux || if [ -f release_docs/USING_CMake.txt ] ; then cp release_docs/USING_CMake.txt release_docs/Using_CMake.txt ; fi ) && \
( if [ ! -f release_docs/USING_CMake.txt ] ; then touch release_docs/USING_CMake.txt ; fi ) && \
( if [ ! -f release_docs/Using_CMake.txt ] ; then touch release_docs/Using_CMake.txt ; fi ) && \
mkdir build && cd build && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBUILD_SHARED_LIBS:BOOL=OFF \
-DBUILD_SHARED_LIBS:BOOL=OFF \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/hdf5 \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
-DZLIB_USE_EXTERNAL:BOOL=ON \
.. > $(PREFIX_ROOT)/log_hdf5.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_hdf5.txt 2>&1 && \
cd ../.. && \
rm -rf hdf5-$(HDF5_VERSION) && \
cd $(THIS_DIR) && \
echo $(HDF5_VERSION) > $@
# IlmBase
# Edits:
# - using the custom namespaces instead of Imath_2_2, Iex_2_2, IlmThread_2_2
$(ILMBASE_STAMP) : $(CMAKE_STAMP) $(ILMBASE_FILE)
@echo Building IlmBase $(ILMBASE_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf ilmbase-$(ILMBASE_VERSION) && \
tar -xf $(SOURCES_ROOT)/ilmbase-$(ILMBASE_VERSION).tar.gz && \
cd ilmbase-$(ILMBASE_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBUILD_SHARED_LIBS:BOOL=OFF \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/ilmbase \
-DNAMESPACE_VERSIONING:BOOL=ON \
. > $(PREFIX_ROOT)/log_ilmbase.txt 2>&1 && \
( printf '/IMATH_INTERNAL_NAMESPACE/s/Imath_2_2/rdoImath/\nw\nq' | ed -s config/IlmBaseConfig.h ) && \
( printf '/IEX_INTERNAL_NAMESPACE/s/Iex_2_2/rdoIex/\nw\nq' | ed -s config/IlmBaseConfig.h ) && \
( printf '/ILMTHREAD_INTERNAL_NAMESPACE/s/IlmThread_2_2/rdoIlmThread/\nw\nq' | ed -s config/IlmBaseConfig.h ) && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_ilmbase.txt 2>&1 && \
cd .. && \
rm -rf ilmbase-$(ILMBASE_VERSION) && \
cd $(THIS_DIR) && \
echo $(ILMBASE_VERSION) > $@
# ISPC
$(ISPC) : $(CMAKE_STAMP)
@echo Building ISPC $(ISPC_VERSION) && \
$(MAKE) $(MAKE_OPTS) -C ./system \
BUILD_ROOT=$(BUILD_ROOT) \
CLANG=$(CLANG) \
CMAKE=$(CMAKE) \
CMAKE_BUILD_TYPE=$(CMAKE_BUILD_TYPE) \
COMMON_CMAKE_FLAGS='$(COMMON_CMAKE_FLAGS)' \
ISPC=$(ISPC) \
ISPC_VERSION=$(ISPC_VERSION) \
LLVM_VERS=$(LLVM_VERS) \
PREFIX_ROOT=$(PREFIX_ROOT) \
PYTHON_BIN=$(PYTHON_BIN) \
SOURCES_ROOT=$(SOURCES_ROOT) \
ispc -j$(JOB_COUNT) > $(PREFIX_ROOT)/log_ispc.txt 2>&1
# jpeg
# Edits:
# - removed m4_argn which is available in the latest m4
$(JPEG_STAMP) : $(JPEG_FILE)/HEAD
@echo Building jpeg $(JPEG_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf jpeg && \
git clone -q --no-checkout $(SOURCES_ROOT)/libjpeg-turbo.git jpeg && \
cd jpeg && \
git checkout -q $(JPEG_VERSION) && \
( printf '/m4_define.*version_major/s/m4_argn(1,version_triplet)/1/\nw\nq' | ed -s configure.ac ) && \
( printf '/m4_define.*version_minor/s/m4_argn(2,version_triplet)/5/\nw\nq' | ed -s configure.ac ) && \
( printf '/m4_define.*version_revision/s/m4_argn(3,version_triplet)/1/\nw\nq' | ed -s configure.ac ) && \
mkdir -p $(PREFIX_ROOT) && \
$(AUTORECONF) -fiv > $(PREFIX_ROOT)/log_jpeg.txt 2>&1 && \
$(COMPILER_CONF) \
./configure \
--prefix="$(PREFIX_ROOT)/jpeg" \
--enable-shared=no >> $(PREFIX_ROOT)/log_jpeg.txt 2>&1 && \
$(MAKE) -j$(JOB_COUNT) \
MAKE_MODE=$(MAKE_MODE) \
install >> $(PREFIX_ROOT)/log_jpeg.txt 2>&1 && \
cd .. && \
rm -rf jpeg && \
cd $(THIS_DIR) && \
echo $(JPEG_VERSION) > $@
# jsoncpp
$(JSONCPP_STAMP) : $(CMAKE_STAMP) $(ZLIB_STAMP) $(JSONCPP_FILE)/HEAD
@echo Building jsoncpp $(JSONCPP_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf jsoncpp && \
git clone -q --no-checkout $(SOURCES_ROOT)/jsoncpp.git jsoncpp && \
cd jsoncpp && \
git checkout -q $(JSONCPP_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/jsoncpp \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
. > $(PREFIX_ROOT)/log_jsoncpp.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_jsoncpp.txt 2>&1 && \
cd .. && \
rm -rf jsoncpp && \
cd $(THIS_DIR) && \
echo $(JSONCPP_VERSION) > $@
# LLVM, clang
$(CLANG) : $(CMAKE_STAMP) $(PYTHON_STAMP)
@echo Building clang $(LLVM_VERS) && \
$(MAKE) $(MAKE_OPTS) -C ./system \
$(COMPILER_CONF) \
BUILD_ROOT=$(BUILD_ROOT) \
CLANG=$(CLANG) \
CMAKE=$(CMAKE) \
CMAKE_BUILD_TYPE=$(CMAKE_BUILD_TYPE) \
COMMON_CMAKE_FLAGS='$(COMMON_CMAKE_FLAGS)' \
LLVM_VERS=$(LLVM_VERS) \
PREFIX_ROOT=$(PREFIX_ROOT) \
PYTHON_BIN=$(PYTHON_BIN) \
SOURCES_ROOT=$(SOURCES_ROOT) \
llvm > $(PREFIX_ROOT)/log_llvm.txt 2>&1
# Mercurial
$(MERCURIAL_STAMP) : $(MERCURIAL_FILE) $(PYTHON_STAMP)
@echo Building mercurial $(MERCURIAL_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(basename $(MERCURIAL_FILE)))) && \
tar zxf $(SOURCES_ROOT)/$(notdir $(MERCURIAL_FILE)) && \
cd $(notdir $(basename $(basename $(MERCURIAL_FILE)))) && \
( printf "0c\n#!$(PYTHON_BIN)\n.\nw\nq" | ed -s hg ) && \
$(MAKE) $(COMPILER_CONF) -j$(JOB_COUNT) \
MAKE_MODE=$(MAKE_MODE) \
PYTHON=$(PYTHON_BIN) \
PREFIX=$(PREFIX_ROOT)/mercurial \
install-bin >> $(PREFIX_ROOT)/log_mercurial.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(basename $(MERCURIAL_FILE)))) && \
cd $(THIS_DIR) && \
echo $(MERCURIAL_VERSION) > $@
# OpenColorIO
$(OCIO_STAMP) : $(BOOST_STAMP) $(CMAKE_STAMP) $(OCIO_FILE)/HEAD
@echo Building OpenColorIO $(OCIO_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf ocio && \
git clone -q --no-checkout $(SOURCES_ROOT)/OpenColorIO.git ocio && \
cd ocio && \
git checkout -q $(OCIO_VERSION) && \
mkdir build && cd build && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBOOST_ROOT=$(PREFIX_ROOT)/boost \
-DBoost_NAMESPACE=$(BOOST_NAMESPACE) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/ocio \
-DOCIO_BUILD_APPS:BOOL=OFF \
-DOCIO_BUILD_PYGLUE:BOOL=OFF \
-DOCIO_BUILD_SHARED:BOOL=OFF \
-DOCIO_USE_BOOST_PTR:BOOL=ON \
.. > $(PREFIX_ROOT)/log_ocio.txt 2>&1 && \
PATH=$(dir $(CXX)):$(PATH) \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_ocio.txt 2>&1 && \
cp ext/dist/lib/lib* $(PREFIX_ROOT)/ocio/lib && \
cd ../.. && \
rm -rf ocio && \
cd $(THIS_DIR) && \
echo $(OCIO_VERSION) > $@
# OpenImageIO
# Edits:
# - Defining OIIO_STATIC_BUILD to avoid specifying it everywhere
# - Linking with tinyxml and yaml-cpp
# - std::locale segfault fix
# - Python module
$(OIIO_STAMP) : $(BOOST_STAMP) $(CMAKE_STAMP) $(GLEW_STAMP) $(ILMBASE_STAMP) $(JPEG_STAMP) $(OCIO_STAMP) $(OPENEXR_STAMP) $(PNG_STAMP) $(PTEX_STAMP) $(QT5BASE_STAMP) $(TIFF_STAMP) $(ZLIB_STAMP) $(OIIO_FILE)/HEAD
@echo Building OpenImageIO $(OIIO_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf oiio && \
git clone -q --no-checkout $(SOURCES_ROOT)/oiio.git oiio && \
cd oiio && \
git checkout -q $(OIIO_VERSION) && \
echo Patch to avoid defininig OIIO_STATIC_BUILD in all the packages... && \
( printf '\n#ifndef OIIO_STATIC_BUILD\n# define OIIO_STATIC_BUILD\n#endif\n' >> src/include/OpenImageIO/export.h ) && \
echo Patch to get tinyxml and yaml from OCIO... && \
( printf '/find_library.*tinyxml/s/)/ PATHS $$\{OCIO_PATH\}\/lib)/\nw\nq' | ed -s src/cmake/externalpackages.cmake ) && \
( printf '/find_library.*yaml-cpp/s/)/ PATHS $$\{OCIO_PATH\}\/lib)/\nw\nq' | ed -s src/cmake/externalpackages.cmake ) && \
( printf '/USE_PYTHON OFF/d\nw\nq' | ed -s src/cmake/compiler.cmake ) && \
( printf '/Boost_USE_STATIC_LIBS/d\nw\nq' | ed -s src/cmake/compiler.cmake ) && \
( printf '/Boost_USE_STATIC_LIBS/d\nw\nq' | ed -s src/cmake/compiler.cmake ) && \
( printf '/Boost_USE_STATIC_LIBS/d\nw\nq' | ed -s src/cmake/externalpackages.cmake ) && \
( printf '/CMAKE_FIND_LIBRARY_SUFFIXES .a/d\nw\nq' | ed -s src/cmake/compiler.cmake ) && \
echo Patch to link iv with static qt5... && \
( printf '/Qt5::Core/a\nlibxcb.so\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\nlibxcb-glx.so\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\nlibX11-xcb.so\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n\044{X11_Xi_LIB}\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n\044{X11_LIBRARIES}\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n$(PREFIX_ROOT)/qt5base/lib/libxcb-static.a\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n$(PREFIX_ROOT)/qt5base/lib/libqtpcre2.a\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n$(PREFIX_ROOT)/qt5base/lib/libqtharfbuzz.a\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n$(PREFIX_ROOT)/qt5base/lib/libqtfreetype.a\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n$(PREFIX_ROOT)/qt5base/lib/libQt5GlxSupport.a\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n$(PREFIX_ROOT)/qt5base/lib/libQt5FontDatabaseSupport.a\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n$(PREFIX_ROOT)/qt5base/lib/libQt5ServiceSupport.a\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n$(PREFIX_ROOT)/qt5base/lib/libQt5ThemeSupport.a\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n$(PREFIX_ROOT)/qt5base/lib/libQt5EventDispatcherSupport.a\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\n$(PREFIX_ROOT)/qt5base/lib/libQt5XcbQpa.a\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\nQt5::QXcbGlxIntegrationPlugin\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5::Core/a\nQt5::QXcbIntegrationPlugin\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '/Qt5_FOUND/a\nfind_package(X11 REQUIRED)\n.\nw\nq' | ed -s src/iv/CMakeLists.txt ) && \
( printf '\n#include <QtPlugin>\nQ_IMPORT_PLUGIN(QXcbIntegrationPlugin)' >> src/iv/ivmain.cpp ) && \
( printf '\nQ_IMPORT_PLUGIN(QXcbGlxIntegrationPlugin)' >> src/iv/ivmain.cpp ) && \
mkdir build && cd build && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBOOST_ROOT=$(PREFIX_ROOT)/boost \
-DBUILDSTATIC:BOOL=ON \
-DBoost_NAMESPACE=$(BOOST_NAMESPACE) \
-DBoost_USE_STATIC_LIBS:BOOL=$(USE_STATIC_BOOST) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/oiio \
-DGLEW_INCLUDES:PATH=$(PREFIX_ROOT)/glew/include/GL \
-DGLEW_LIBRARIES:PATH=$(PREFIX_ROOT)/glew/lib/libGLEW.a \
-DILMBASE_HOME=$(PREFIX_ROOT)/ilmbase \
-DJPEGTURBO_PATH=$(PREFIX_ROOT)/jpeg \
-DLINKSTATIC:BOOL=ON \
-DOCIO_PATH=$(PREFIX_ROOT)/ocio \
-DOIIO_BUILD_TESTS:BOOL=OFF \
-DOPENEXR_HOME=$(PREFIX_ROOT)/openexr \
-DPNG_LIBRARY=$(PREFIX_ROOT)/png/lib/libpng.a \
-DPNG_PNG_INCLUDE_DIR=$(PREFIX_ROOT)/png/include \
-DPTEX_LOCATION:PATH=$(PREFIX_ROOT)/ptex \
-DPYTHON_EXECUTABLE=$(PYTHON_BIN) \
-DTIFF_INCLUDE_DIR=$(PREFIX_ROOT)/tiff/include \
-DTIFF_LIBRARY=$(PREFIX_ROOT)/tiff/lib/libtiff.a \
-DUSE_FFMPEG:BOOL=OFF \
-DUSE_FREETYPE:BOOL=OFF \
-DUSE_GIF:BOOL=OFF \
-DQt5_DIR:PATH=$(PREFIX_ROOT)/qt5base/lib/cmake/Qt5 \
-DVERBOSE:BOOL=ON \
-DZLIB_ROOT=$(PREFIX_ROOT)/zlib \
.. > $(PREFIX_ROOT)/log_oiio.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_oiio.txt 2>&1 && \
cd ../.. && \
rm -rf oiio && \
cd $(THIS_DIR) && \
echo $(OIIO_VERSION) > $@
# OpenEXR
# Edits:
# - using the custom namespaces instead of Imf_2_2
# Patch:
# - Fixed linking problem of dwaLookups
$(OPENEXR_STAMP) : $(CMAKE_STAMP) $(ILMBASE_STAMP) $(ZLIB_STAMP) $(OPENEXR_FILE)
@echo Building OpenEXR $(OPENEXR_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf openexr-$(OPENEXR_VERSION) && \
tar -xf $(SOURCES_ROOT)/openexr-$(OPENEXR_VERSION).tar.gz && \
cd openexr-$(OPENEXR_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBUILD_SHARED_LIBS:BOOL=OFF \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/openexr \
-DILMBASE_PACKAGE_PREFIX:PATH=$(PREFIX_ROOT)/ilmbase \
-DNAMESPACE_VERSIONING:BOOL=ON \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
. > $(PREFIX_ROOT)/log_openexr.txt 2>&1 && \
( printf '/OPENEXR_IMF_INTERNAL_NAMESPACE Imf_2_2/s/Imf_2_2/rdoImf/\nw\nq' | ed -s config/OpenEXRConfig.h ) && \
( printf '/define.*INCLUDED_IMF_DWA_COMRESSOR_H/a\n#include <zlib.h>\n.\nw\nq' | ed -s IlmImf/ImfDwaCompressor.h ) && \
( printf '/define.*INCLUDED_IMF_ZIP_COMPRESSOR_H/a\n#include <zlib.h>\n.\nw\nq' | ed -s IlmImf/ImfZipCompressor.h ) && \
( printf '/define.*INCLUDED_IMF_COMPRESSION_H/a\n#include <zlib.h>\n.\nw\nq' | ed -s IlmImf/ImfCompression.h ) && \
( printf '/define.*INCLUDED_IMF_ZIP_H/a\n#include <zlib.h>\n.\nw\nq' | ed -s IlmImf/ImfZip.h ) && \
patch -N --no-backup-if-mismatch IlmImf/CMakeLists.txt $(THIS_DIR)/patches/OpenEXR/patch_openexr_cmakelists.diff && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_openexr.txt 2>&1 && \
cd .. && \
rm -rf openexr-$(OPENEXR_VERSION) && \
cp $(PREFIX_ROOT)/ilmbase/lib/*.a $(PREFIX_ROOT)/openexr/lib && \
cd $(THIS_DIR) && \
echo $(OPENEXR_VERSION) > $@
# OpenSubdiv
$(OPENSUBD_STAMP) : $(CMAKE_STAMP) $(GLEW_STAMP) $(GLFW_STAMP) $(PTEX_STAMP) $(PYTHON_STAMP) $(TBB_STAMP) $(ZLIB_STAMP) $(OPENSUBD_FILE)/HEAD
@echo Building OpenSubdiv $(OPENSUBD_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(OPENSUBD_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(OPENSUBD_FILE)) $(notdir $(basename $(OPENSUBD_FILE))) && \
cd $(notdir $(basename $(OPENSUBD_FILE))) && \
git checkout -q $(OPENSUBD_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
( printf "/osd_dynamic_cpu/s/osd_dynamic_cpu/osd_static_gpu/\nw\nq" | ed -s CMakeLists.txt ) && \
( printf "/osd_dynamic_gpu/s/osd_dynamic_gpu/osd_static_cpu/\nw\nq" | ed -s CMakeLists.txt ) && \
( printf "/if.*NOT.*NOT/s/(/( 0 AND /\nw\nq" | ed -s opensubdiv/CMakeLists.txt ) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/opensubdiv \
-DGLFW_LOCATION:PATH=$(PREFIX_ROOT)/glfw \
-DGLEW_LOCATION:PATH=$(PREFIX_ROOT)/glew \
-DNO_GLTESTS:BOOL=ON \
-DNO_TESTS:BOOL=ON \
-DNO_TUTORIALS:BOOL=ON \
-DPTEX_LOCATION:PATH=$(PREFIX_ROOT)/ptex \
-DPYTHON_EXECUTABLE=$(PYTHON_BIN) \
-DTBB_LOCATION:PATH=$(PREFIX_ROOT)/tbb \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
-DNO_OMP=1 \
. > $(PREFIX_ROOT)/log_opensubdiv.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_opensubdiv.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(OPENSUBD_FILE))) && \
cd $(THIS_DIR) && \
echo $(OPENSUBD_VERSION) > $@
# OpenVDB
$(OPENVDB_STAMP) : $(BLOSC_STAMP) $(BOOST_STAMP) $(CMAKE_STAMP) $(GLFW_STAMP) $(OPENEXR_STAMP) $(TBB_STAMP) $(OPENVDB_FILE)/HEAD
@echo Building OpenVDB $(OPENVDB_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(OPENVDB_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(OPENVDB_FILE)) $(notdir $(basename $(OPENVDB_FILE))) && \
cd $(notdir $(basename $(OPENVDB_FILE))) && \
git checkout -q $(OPENVDB_VERSION) && \
( printf "/define/a\n#define OPENVDB_STATICLIB\n.\nw\n" | ed -s openvdb/PlatformConfig.h ) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBLOSC_LOCATION=$(PREFIX_ROOT)/blosc \
-DBOOST_ROOT=$(PREFIX_ROOT)/boost \
-DBlosc_USE_STATIC_LIBS=ON \
-DBoost_NAMESPACE=$(BOOST_NAMESPACE) \
-DBoost_USE_STATIC_LIBS:BOOL=$(USE_STATIC_BOOST) \
-DCMAKE_CXX_FLAGS="$(FLAGS) -fPIC -std=c++11" \
-DCMAKE_EXE_LINKER_FLAGS="-ldl -pthread" \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/openvdb \
-DCMAKE_SHARED_LINKER_FLAGS="-Wl,--no-undefined -ldl -pthread" \
-DGLFW3_LOCATION=$(PREFIX_ROOT)/glfw \
-DGLFW3_USE_STATIC_LIBS:BOOL=ON \
-DILMBASE_LOCATION:PATH=$(PREFIX_ROOT)/ilmbase \
-DOPENEXR_LOCATION:PATH=$(PREFIX_ROOT)/openexr \
-DOPENVDB_BUILD_PYTHON_MODULE:BOOL=OFF \
-DOPENVDB_BUILD_UNITTESTS:BOOL=OFF \
-DOPENVDB_ENABLE_3_ABI_COMPATIBLE:BOOL=OFF \
-DTBB_LOCATION:PATH=$(PREFIX_ROOT)/tbb \
-DUSE_GLFW3:BOOL=ON \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
. > $(PREFIX_ROOT)/log_openvdb.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_openvdb.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(OPENVDB_FILE))) && \
rm $(PREFIX_ROOT)/openvdb/lib/*.so* && \
cd $(THIS_DIR) && \
echo $(OPENVDB_VERSION) > $@
# Open Shading Language
OSL_ADDITIONAL_LIBS := \
$(PREFIX_ROOT)/boost/lib/lib$(BOOST_NAMESPACE)_filesystem$(DYNAMIC_EXT) \
$(PREFIX_ROOT)/openexr/lib/libIlmImf-2_2.a \
$(PREFIX_ROOT)/openexr/lib/libImath-2_2.a \
$(PREFIX_ROOT)/openexr/lib/libIex-2_2.a \
$(PREFIX_ROOT)/openexr/lib/libHalf.a \
$(PREFIX_ROOT)/openexr/lib/libIlmThread-2_2.a \
$(PREFIX_ROOT)/png/lib/libpng.a \
$(PREFIX_ROOT)/jpeg/lib/libjpeg.a \
$(PREFIX_ROOT)/ptex/lib/libPtex.a \
$(PREFIX_ROOT)/tiff/lib/libtiff.a \
$(PREFIX_ROOT)/zlib/lib/libz.a
$(OSL_STAMP) : $(BISON) $(BOOST_STAMP) $(CLANG) $(CMAKE_STAMP) $(FLEX) $(OSL_FILE)/HEAD
@echo Building OSL $(OSL_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(OSL_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(OSL_FILE)) $(notdir $(basename $(OSL_FILE))) && \
cd $(notdir $(basename $(OSL_FILE))) && \
git checkout -q $(OSL_VERSION) && \
( printf '/VERSION_LESS/s/VERSION_LESS.*)/VERSION_LESS 3.8.0)/\nw\nq' | ed -s src/cmake/modules/FindLLVM.cmake ) && \
( printf '/LLVM.*REQUIRED/s/LLVM.*REQUIRED/LLVM REQUIRED/\nw\nq' | ed -s src/cmake/externalpackages.cmake ) && \
( printf '/oslexec/s/oslexec/oslexec oslcomp/\nw\nq' | ed -s src/osl.imageio/CMakeLists.txt ) && \
( for f in $(OSL_ADDITIONAL_LIBS); do ( printf "/OPENIMAGEIO_LIBRARY_DIRS.*OPENIMAGEIO_LIBRARY/a\nlist(APPEND OPENIMAGEIO_LIBRARY $$f)\n.\nw\nq" | ed -s src/cmake/modules/FindOpenImageIO.cmake ); done ) && \
mkdir -p build && cd build && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBISON_EXECUTABLE=$(BISON) \
-DBOOST_ROOT=$(PREFIX_ROOT)/boost \
-DBUILDSTATIC:BOOL=ON \
-DBoost_NAMESPACE=$(BOOST_NAMESPACE) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/osl \
-DFLEX_EXECUTABLE=$(FLEX) \
-DILMBASE_HOME=$(PREFIX_ROOT)/ilmbase \
-DLLVM_DIRECTORY=$(PREFIX_ROOT)/llvm \
-DLLVM_STATIC:BOOL=ON \
-DUSE_SIMD:BOOL=sse4.2 \
-DOPENEXR_HOME=$(PREFIX_ROOT)/openexr \
-DOPENIMAGEIOHOME=$(PREFIX_ROOT)/oiio \
-DOSL_BUILD_TESTS:BOOL=OFF \
.. > $(PREFIX_ROOT)/log_osl.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_osl.txt 2>&1 && \
cd ../.. && \
rm -rf $(notdir $(basename $(OSL_FILE))) && \
cd $(THIS_DIR) && \
echo $(OSL_VERSION) > $@
# png
$(PNG_STAMP) : $(CMAKE_STAMP) $(ZLIB_STAMP) $(PNG_FILE)
@echo Building png $(PNG_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(basename $(PNG_FILE)))) && \
tar zxf $(SOURCES_ROOT)/$(notdir $(PNG_FILE)) && \
cd $(notdir $(basename $(basename $(PNG_FILE)))) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DPNG_SHARED:BOOL=OFF \
-DPNG_PREFIX=rdoPNG \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/png \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
. > $(PREFIX_ROOT)/log_png.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_png.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(basename $(PNG_FILE)))) && \
cd $(THIS_DIR) && \
echo $(PNG_VERSION) > $@
# Ptex
$(PTEX_STAMP) : $(CMAKE_STAMP) $(ZLIB_STAMP) $(PTEX_FILE)/HEAD
@echo Building Ptex $(PTEX_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(PTEX_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(PTEX_FILE)) $(notdir $(basename $(PTEX_FILE))) && \
cd $(notdir $(basename $(PTEX_FILE))) && \
git checkout -q $(PTEX_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/ptex \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
. > $(PREFIX_ROOT)/log_ptex.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_ptex.txt 2>&1 && \
( ls -d -1 $(PREFIX_ROOT)/ptex/lib/* | grep -v -F .a | xargs rm ) && \
cd .. && \
rm -rf $(notdir $(basename $(PTEX_FILE))) && \
cd $(THIS_DIR) && \
echo $(PTEX_VERSION) > $@
# pyilmbase
$(PYILMBASE_STAMP) : $(BOOST_STAMP) $(CMAKE_STAMP) $(ILMBASE_STAMP) $(PYTHON_STAMP) $(PYILMBASE_FILE)/HEAD
@echo Building pyilmbase $(PYILMBASE_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(PYILMBASE_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(PYILMBASE_FILE)) $(notdir $(basename $(PYILMBASE_FILE))) && \
cd $(notdir $(basename $(PYILMBASE_FILE))) && \
git checkout -q $(PYILMBASE_VERSION) && \
cd PyIlmBase && \
( printf "/INCLUDE_DIRECTORIES/a\n\044{Boost_INCLUDE_DIR}\n.\nw\nq" | ed -s CMakeLists.txt ) && \
( printf "/FIND_PACKAGE.*Boost/a\nREQUIRED COMPONENTS python\n.\nw\nq" | ed -s CMakeLists.txt ) && \
( printf "\044a\nfile(GLOB MYHEADERS *.h)\ninstall(FILES \044{MYHEADERS} DESTINATION include/OpenEXR)\n.\nw\nq" | ed -s PyImath/CMakeLists.txt ) && \
( for i in `grep --include=\*.{cpp,h} -rl . -e "^namespace boost "`; do echo $$i; ( printf "/^namespace boost/s/namespace boost/namespace $(BOOST_NAMESPACE)/\nw\nq" | ed -s $$i ); done ) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBOOST_ROOT:PATH=$(PREFIX_ROOT)/boost \
-DBoost_NAMESPACE=$(BOOST_NAMESPACE) \
-DBoost_USE_STATIC_LIBS:BOOL=$(USE_STATIC_BOOST) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/pyilmbase \
-DCMAKE_INSTALL_RPATH=$(PREFIX_ROOT)/pyilmbase/lib \
-DILMBASE_PACKAGE_PREFIX=$(PREFIX_ROOT)/ilmbase \
-DPYTHON_EXECUTABLE=$(PYTHON_BIN) \
. > $(PREFIX_ROOT)/log_pyilmbase.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_pyilmbase.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(PYILMBASE_FILE))) && \
cd $(THIS_DIR) && \
echo $(PYILMBASE_VERSION) > $@
# PyOpenGL
$(PYOPENGL_STAMP) : $(PYTHON_STAMP) $(PYOPENGL_FILE)
@echo Building PyOpenGL $(PYOPENGL_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(basename $(PYOPENGL_FILE)))) && \
tar -xf $(SOURCES_ROOT)/$(notdir $(PYOPENGL_FILE)) && \
cd $(notdir $(basename $(basename $(PYOPENGL_FILE)))) && \
$(PYTHON_BIN) setup.py install --prefix=$(PREFIX_ROOT)/pyopengl > $(PREFIX_ROOT)/log_pyopengl.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(basename $(PYOPENGL_FILE)))) && \
cd $(THIS_DIR) && \
echo $(PYOPENGL_VERSION) > $@
# PySide
$(PYSIDE_STAMP) : $(CMAKE_STAMP) $(PYTHON_STAMP) $(QT_STAMP) $(SHIBOKEN_STAMP) $(PYSIDE_FILE)/HEAD
@echo Building PySide $(PYSIDE_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(PYSIDE_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(PYSIDE_FILE)) $(notdir $(basename $(PYSIDE_FILE))) && \
cd $(notdir $(basename $(PYSIDE_FILE))) && \
git checkout -q $(PYSIDE_VERSION) && \
mkdir -p build && cd build && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBUILD_TESTS:BOOL=OFF \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/pyside \
-DCMAKE_INSTALL_RPATH=$(PREFIX_ROOT)/pyside/lib \
-DPYTHON_EXECUTABLE=$(PYTHON_BIN) \
-DQT_QMAKE_EXECUTABLE:PATH=$(PREFIX_ROOT)/qt/bin/qmake \
-DShiboken_DIR=$(PREFIX_ROOT)/shiboken/lib/cmake/Shiboken-$(SHIBOKEN_VERSION) \
.. > $(PREFIX_ROOT)/log_pyside.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_pyside.txt 2>&1 && \
cd ../.. && \
rm -rf $(notdir $(basename $(PYSIDE_FILE))) && \
cd $(THIS_DIR) && \
echo $(PYSIDE_VERSION) > $@
# PySide Tools
$(PYSIDETOOLS_STAMP) : $(CMAKE_STAMP) $(PYSIDE_STAMP) $(PYTHON_STAMP) $(QT_STAMP) $(SHIBOKEN_STAMP) $(PYSIDETOOLS_FILE)/HEAD
@echo Building PySide Tools $(PYSIDETOOLS_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(PYSIDETOOLS_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(PYSIDETOOLS_FILE)) $(notdir $(basename $(PYSIDETOOLS_FILE))) && \
cd $(notdir $(basename $(PYSIDETOOLS_FILE))) && \
git checkout -q $(PYSIDETOOLS_VERSION) && \
mkdir -p build && cd build && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBUILD_TESTS:BOOL=OFF \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/pyside \
-DPySide_DIR=$(PREFIX_ROOT)/pyside/lib/cmake/PySide-$(PYSIDE_VERSION) \
-DQT_QMAKE_EXECUTABLE:PATH=$(PREFIX_ROOT)/qt/bin/qmake \
-DShiboken_DIR=$(PREFIX_ROOT)/shiboken/lib/cmake/Shiboken-$(SHIBOKEN_VERSION) \
.. > $(PREFIX_ROOT)/log_pysidetools.txt 2>&1 && \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_pysidetools.txt 2>&1 && \
cd ../.. && \
rm -rf $(notdir $(basename $(PYSIDETOOLS_FILE))) && \
cd $(THIS_DIR) && \
echo $(PYSIDETOOLS_VERSION) > $@
# pystring
$(PYSTRING_STAMP) : $(PYSTRING_FILE)/HEAD
@echo Building pystring $(PYSTRING_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf pystring && \
git clone -q --no-checkout $(SOURCES_ROOT)/pystring.git pystring && \
cd pystring && \
git checkout -q $(PYSTRING_VERSION) && \
mkdir -p $(PREFIX_ROOT)/pystring/lib && \
mkdir -p $(PREFIX_ROOT)/pystring/include && \
PATH=$(dir $(CXX)):$(PATH) \
$(MAKE) $(COMPILER_CONF) -j$(JOB_COUNT) \
MAKE_MODE=$(MAKE_MODE) \
LIBDIR=$(PREFIX_ROOT)/pystring/lib \
LIBTOOL=$(LIBTOOL) \
install > $(PREFIX_ROOT)/log_pystring.txt 2>&1 && \
cp pystring.h $(PREFIX_ROOT)/pystring/include && \
( ls -d -1 $(PREFIX_ROOT)/pystring/lib/* | grep -v -F .a | xargs rm ) && \
cd .. && \
rm -rf pystring && \
cd $(THIS_DIR) && \
echo $(PYSTRING_VERSION) > $@
# Python
# We have to run make && make install because target install fails in
# multithreaded mode in Python 2.6.6
# Edits:
# - Added RPATH, it allows to run python without setting LD_LIBRARY_PATH
ifeq "$(MAKE_MODE)" "debug"
PYTHON_EXTRA_OPT := --with-pydebug
endif
ifeq "$(OS)" "Darwin"
PYTHON_EXTRA_OPT += --enable-unicode=ucs2
endif
ifeq "$(OS)" "linux"
PYTHON_EXTRA_OPT += --enable-unicode=ucs4 --enable-shared
endif
$(PYTHON_STAMP) : $(PYTHON_FILE)
@echo Building python $(PYTHON_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf Python-$(PYTHON_VERSION) && \
tar zxf $(SOURCES_ROOT)/Python-$(PYTHON_VERSION).tgz && \
cd Python-$(PYTHON_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(COMPILER_CONF) \
./configure \
LDFLAGS=-Wl,-rpath,\''$$''$$'\'ORIGIN/../lib \
--prefix="$(PREFIX_ROOT)/python" \
$(PYTHON_EXTRA_OPT) > $(PREFIX_ROOT)/log_python.txt 2>&1 && \
$(MAKE) -j$(JOB_COUNT) \
MAKE_MODE=$(MAKE_MODE) >> $(PREFIX_ROOT)/log_python.txt 2>&1 && \
$(MAKE) \
MAKE_MODE=$(MAKE_MODE) \
install >> $(PREFIX_ROOT)/log_python.txt 2>&1 && \
cd .. && \
rm -rf Python-$(PYTHON_VERSION) && \
cd $(THIS_DIR) && \
echo $(PYTHON_VERSION) > $@
# Qt
$(QT_STAMP) : $(QT_FILE)
@echo Building Qt $(QT_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(basename $(QT_FILE)))) && \
tar zxf $(SOURCES_ROOT)/$(notdir $(QT_FILE)) && \
cd $(notdir $(basename $(basename $(QT_FILE)))) && \
echo QMAKE_CXX = $(CXX) >> mkspecs/linux-g++/qmake.conf && \
echo QMAKE_LINK = $(CXX) >> mkspecs/linux-g++/qmake.conf && \
echo QMAKE_CC = $(CC) >> mkspecs/linux-g++/qmake.conf && \
echo QMAKE_LINK_C = $(CC) >> mkspecs/linux-g++/qmake.conf && \
mkdir -p $(PREFIX_ROOT) && \
$(COMPILER_CONF) \
./configure \
-confirm-license \
-no-multimedia \
-no-webkit \
-nomake demos \
-nomake docs \
-nomake examples \
-nomake tests \
-opensource \
-prefix $(PREFIX_ROOT)/qt \
-shared > $(PREFIX_ROOT)/log_qt.txt 2>&1 && \
$(MAKE) -j$(JOB_COUNT) \
MAKE_MODE=$(MAKE_MODE) \
install >> $(PREFIX_ROOT)/log_qt.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(basename $(QT_FILE)))) && \
cd $(THIS_DIR) && \
echo $(QT_VERSION) > $@
# Qt 5
$(QT5BASE_STAMP) : $(QT5BASE_FILE)/HEAD
@echo Building Qt $(QT5BASE_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(QT5BASE_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(QT5BASE_FILE)) $(notdir $(basename $(QT5BASE_FILE))) && \
cd $(notdir $(basename $(QT5BASE_FILE))) && \
git checkout -q $(QT5BASE_VERSION) && \
echo QMAKE_CXX = $(CXX) >> mkspecs/linux-g++/qmake.conf && \
echo QMAKE_LINK = $(CXX) >> mkspecs/linux-g++/qmake.conf && \
echo QMAKE_CC = $(CC) >> mkspecs/linux-g++/qmake.conf && \
echo QMAKE_LINK_C = $(CC) >> mkspecs/linux-g++/qmake.conf && \
echo Patching Qt FreeType to don\'t use png... && \
( printf '/FT_CONFIG_OPTION_USE_PNG/d\nw\n' | ed -s src/3rdparty/freetype/freetype.pro ) && \
( printf '/libpng/d\nw\n' | ed -s src/3rdparty/freetype/freetype.pro ) && \
echo Patching Qt Platform Font Database to use fonts in /usr/share... && \
( printf '/location.*LibrariesPath.*fonts/c\nfontpath = QLatin1String("/usr/share/fonts");\n.\nw\n' | ed -s src/gui/text/qplatformfontdatabase.cpp ) && \
mkdir -p $(PREFIX_ROOT) && \
$(COMPILER_CONF) \
./configure \
-confirm-license \
-no-dbus \
-no-directfb \
-no-eglfs \
-no-gif \
-no-glib \
-no-icu \
-no-libjpeg \
-no-libpng \
-no-libproxy \
-no-linuxfb \
-no-openssl \
-no-securetransport \
-no-sql-mysql \
-no-sql-sqlite \
-no-zlib \
-nomake examples \
-nomake tests \
-opengl desktop \
-opensource \
-prefix $(PREFIX_ROOT)/qt5base \
-qt-freetype \
-qt-harfbuzz \
-qt-xcb \
-release \
-static > $(PREFIX_ROOT)/log_qt5base.txt 2>&1 && \
$(MAKE) -j$(JOB_COUNT) \
MAKE_MODE=$(MAKE_MODE) \
install >> $(PREFIX_ROOT)/log_qt5base.txt 2>&1 && \
cd .. && \
rm -rf $(notdir $(basename $(QT5BASE_FILE))) && \
cd $(THIS_DIR) && \
echo $(QT5BASE_VERSION) > $@
# Shiboken
$(SHIBOKEN_STAMP) : $(CMAKE_STAMP) $(PYTHON_STAMP) $(QT_STAMP) $(SHIBOKEN_FILE)/HEAD
@echo Building Shiboken $(SHIBOKEN_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(SHIBOKEN_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(SHIBOKEN_FILE)) $(notdir $(basename $(SHIBOKEN_FILE))) && \
cd $(notdir $(basename $(SHIBOKEN_FILE))) && \
git checkout -q $(SHIBOKEN_VERSION) && \
mkdir -p build && cd build && \
mkdir -p $(PREFIX_ROOT) && \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DBUILD_TESTS:BOOL=OFF \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/shiboken \
-DCMAKE_INSTALL_RPATH=$(PREFIX_ROOT)/shiboken/lib \
-DPYTHON_EXECUTABLE=$(PYTHON_BIN) \
-DQT_QMAKE_EXECUTABLE:PATH=$(PREFIX_ROOT)/qt/bin/qmake \
.. > $(PREFIX_ROOT)/log_shiboken.txt 2>&1 && \
LD_LIBRARY_PATH=$(PREFIX_ROOT)/qt/lib \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_shiboken.txt 2>&1 && \
cd ../.. && \
rm -rf $(notdir $(basename $(SHIBOKEN_FILE))) && \
cd $(THIS_DIR) && \
echo $(SHIBOKEN_VERSION) > $@
# tbb
# Edits:
# - Ability to use custom compiler, custom flags
# - Fixed bug with recognizing linux
$(TBB_STAMP) : $(TBB_FILE)
@echo Building tbb $(TBB_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf tbb$(TBB_VERSION) && \
tar zxf $(SOURCES_ROOT)/$(notdir $(TBB_FILE)) && \
cd tbb$(TBB_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
( printf "/CPLUS/s/g++/$(subst /,\/,$(CXX))/\nw\nq" | ed -s build/linux.gcc.inc ) && \
( printf "/CPLUS/s/g++/$(subst /,\/,$(CXX))/\nw\nq" | ed -s build/macos.gcc.inc ) && \
( printf "/CONLY/s/gcc/$(subst /,\/,$(CC))/\nw\nq" | ed -s build/linux.gcc.inc ) && \
( printf "/CONLY/s/gcc/$(subst /,\/,$(CC))/\nw\nq" | ed -s build/macos.gcc.inc ) && \
( printf "\044a\nCPLUS_FLAGS += $(FLAGS)\n.\nw\nq" | ed -s build/linux.gcc.inc ) && \
( printf "\044a\nCPLUS_FLAGS += $(FLAGS)\n.\nw\nq" | ed -s build/macos.gcc.inc ) && \
( printf "/ifeq.*OS.*Linux/i\nifeq (\044(OS), linux)\nexport tbb_os=linux\nendif\n.\nw\nq\n" | ed -s build/common.inc ) && \
$(MAKE) \
-C src \
tbb_$(MAKE_MODE) \
tbbmalloc_$(MAKE_MODE) \
compiler=gcc \
-j $(JOB_COUNT) > $(PREFIX_ROOT)/log_tbb.txt 2>&1 && \
mkdir -p $(PREFIX_ROOT)/tbb/include && \
cp -R include/tbb $(PREFIX_ROOT)/tbb/include && \
mkdir -p $(PREFIX_ROOT)/tbb/lib && \
$(AR) \
-rsc $(PREFIX_ROOT)/tbb/lib/libtbb.a \
build/*_$(MAKE_MODE)/*.o >> $(PREFIX_ROOT)/log_tbb.txt 2>&1 && \
cd .. && \
rm -rf tbb$(TBB_VERSION) && \
cd $(THIS_DIR) && \
echo $(TBB_VERSION) > $@
# libtiff
$(TIFF_STAMP) : $(ZLIB_STAMP) $(TIFF_FILE)
@echo Building tiff $(TIFF_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf tiff-$(TIFF_VERSION) && \
tar -xf $(SOURCES_ROOT)/tiff-$(TIFF_VERSION).tar.gz && \
cd tiff-$(TIFF_VERSION) && \
( printf "/inflateEnd.*()/d\nw\nq" | ed -s configure ) && \
( printf "/inflateEnd.*()/d\nw\nq" | ed -s configure ) && \
mkdir -p $(PREFIX_ROOT) && \
$(COMPILER_CONF) \
./configure \
--prefix=$(PREFIX_ROOT)/tiff \
--with-zlib-include-dir=$(PREFIX_ROOT)/zlib/include \
--with-zlib-lib-dir=$(PREFIX_ROOT)/zlib/lib \
--enable-shared=no > $(PREFIX_ROOT)/log_tiff.txt 2>&1 && \
$(MAKE) -j$(JOB_COUNT) \
MAKE_MODE=$(MAKE_MODE) \
install >> $(PREFIX_ROOT)/log_tiff.txt 2>&1 && \
cd .. && \
rm -rf tiff-$(TIFF_VERSION) && \
cd $(THIS_DIR) && \
echo $(TIFF_VERSION) > $@
# USD
# Edits:
# - FindOpenEXR: looking for static libHalf, use "-2_2" suffix to find other
# libraries.
# - headers: use rdoBoost namespace insted of boost.
# - FindOpenImageIO: link with static libraries.
# - Static linking of the usd libraries.
# - Set _ReadPlugInfoObject as a weak function. It allows to override it.
# - Suppress a message that load filed. We shouldn't load anything with static
# linking.
# - Change a key to store the plugins. It's necessary to use somthing unique
# since every plugin is in a single application.
# Right now we build dynamic USD because the static linking is not supported.
# Python is executed during building, so we need to provide proper
# LD_LIBRARY_PATH in linux. We don't have to do it on macOS because mac's python
# is linked statically.
OIIO_LIBS := \
$(PREFIX_ROOT)/openexr/lib/libIlmImf-2_2.a \
$(PREFIX_ROOT)/openexr/lib/libImath-2_2.a \
$(PREFIX_ROOT)/openexr/lib/libIex-2_2.a \
$(PREFIX_ROOT)/openexr/lib/libHalf.a \
$(PREFIX_ROOT)/openexr/lib/libIlmThread-2_2.a \
$(PREFIX_ROOT)/png/lib/libpng.a \
$(PREFIX_ROOT)/jpeg/lib/libjpeg.a \
$(PREFIX_ROOT)/ptex/lib/libPtex.a \
$(PREFIX_ROOT)/zlib/lib/libz.a \
$(PREFIX_ROOT)/tiff/lib/libtiff.a \
$(PREFIX_ROOT)/boost/lib/lib$(BOOST_NAMESPACE)_filesystem$(DYNAMIC_EXT) \
$(PREFIX_ROOT)/boost/lib/lib$(BOOST_NAMESPACE)_regex$(DYNAMIC_EXT) \
$(PREFIX_ROOT)/boost/lib/lib$(BOOST_NAMESPACE)_system$(DYNAMIC_EXT) \
$(PREFIX_ROOT)/boost/lib/lib$(BOOST_NAMESPACE)_thread$(DYNAMIC_EXT) \
$(PREFIX_ROOT)/boost/lib/lib$(BOOST_NAMESPACE)_chrono$(DYNAMIC_EXT) \
$(PREFIX_ROOT)/boost/lib/lib$(BOOST_NAMESPACE)_date_time$(DYNAMIC_EXT) \
$(PREFIX_ROOT)/boost/lib/lib$(BOOST_NAMESPACE)_atomic$(DYNAMIC_EXT) \
$(PREFIX_ROOT)/ocio/lib/libOpenColorIO.a \
$(PREFIX_ROOT)/ocio/lib/libtinyxml.a \
$(PREFIX_ROOT)/ocio/lib/libyaml-cpp.a
# Additional linux libs.
ifeq "$(OS)" "linux"
OIIO_LIBS += rt Xxf86vm Xrandr
endif
TBB_LIBRARY := $(PREFIX_ROOT)/tbb/lib
TBB_ROOT_DIR := $(PREFIX_ROOT)/tbb/include
ifeq "$(USE_STATIC_BOOST)" "ON"
BUILD_SHARED_LIBS := OFF
else
# If BUILD_SHARED_LIBS=ON, we force USD to build a single shared library (PXR_BUILD_MONOLITHIC=ON)
# This is needed because we link with a static TBB library even in shared mode as including static tbb
# in multiple usd shared libraries won't work!
# Using static tbb in the USD plugin is to avoid conflict with other tbb libraries from Maya, Houdini, etc...
BUILD_SHARED_LIBS := ON
endif
$(USD_STAMP) : $(ALEMBIC_STAMP) $(BOOST_STAMP) $(CMAKE_STAMP) $(DC_STAMP) $(EMBREE_STAMP) $(GLUT_STAMP) $(ILMBASE_STAMP) $(OIIO_STAMP) $(OPENEXR_STAMP) $(OPENSUBD_STAMP) $(PTEX_STAMP) $(PYOPENGL_STAMP) $(PYSIDE_STAMP) $(PYSIDETOOLS_STAMP) $(PYTHON_STAMP) $(TBB_STAMP) $(USD_FILE)/HEAD
@echo Building usd $(USD_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf $(notdir $(basename $(USD_FILE))) && \
git clone -q --no-checkout $(SOURCES_ROOT)/$(notdir $(USD_FILE)) $(notdir $(basename $(USD_FILE))) && \
cd $(notdir $(basename $(USD_FILE))) && \
git checkout -q $(USD_VERSION) && \
echo ">>>" Patching Alembic Reader for the materials support... && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0001-RDO-Added-ability-to-convert-Alembic-materials.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0002-RDO-Added-ability-to-output-Alembic-expressions-to-U.patch ) && \
( git am $(THIS_DIR)/patches/USD/0003-RDO-Don-t-collapse-the-hierarchy-of-Alembic.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0004-RDO-Output-all-the-material-parameters.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0005-RDO-USD-Alembic-add-userData-namespace.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0006-RDO-Houdini-Ability-to-import-all-the-objects.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0007-RDO-produce-doubleSided-property-in-Alembics.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0008-RDO-always-produce-xforms-in-alembics.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0009-RDO-flip-textures-to-display-in-Hydra-as-in-Arnold.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0010-RDO-Hydra-half-OpenEXR-support.patch ) && \
( git am $(THIS_DIR)/patches/USD/0011-RDO-Default-Resolver-Abc-Core-Layer-support.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0012-RDO-USD-Alembic-no-time-samples.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0013-RDO-USD-Alembic-Support-for-lights.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0014-RDO-USD-Alembic-using-indexed-UV.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0015-RDO-Integrate-embree-to-OpenGL.patch ) && \
( git am $(THIS_DIR)/patches/USD/0016-RDO-Added-virtual-method-ArResolver-Clear.patch ) && \
( test ! $(USE_STATIC_BOOST) == ON || git am $(THIS_DIR)/patches/USD/0017-RDO-Support-for-Arnold-components-in-shaders.patch ) && \
( git am $(THIS_DIR)/patches/USD/0018-RDO-the-ability-to-reference-a-root.patch ) && \
( git am $(THIS_DIR)/patches/USD/0019-RDO-USD-AlembicReader-Suppress-warnings.patch ) && \
( git am $(THIS_DIR)/patches/USD/0020-RDO-hdEngine-v0.8.5-broke-our-hdEmbree-plugin-when-used-.patch ) && \
( git am $(THIS_DIR)/patches/USD/0021-RDO-USD-Alembic-Fixed-texture-stretching-artifacts.patch ) && \
( printf "/find_library.*OPENEXR_.*_LIBRARY/a\nNAMES\n\044{OPENEXR_LIB}-2_2\n.\nw\nq" | ed -s cmake/modules/FindOpenEXR.cmake ) && \
( printf "/PATH_SUFFIXES/-a\n\"\044{OPENEXR_BASE_DIR}\"\n.\nw\nq" | ed -s cmake/modules/FindOpenEXR.cmake ) && \
( printf "/^namespace boost/s/namespace boost/namespace ${BOOST_NAMESPACE}/\nw\nq" | ed -s pxr/base/lib/tf/weakPtrFacade.h ) && \
( printf "/namespace boost/s/namespace boost/namespace ${BOOST_NAMESPACE}/\nw\nq" | ed -s third_party/houdini/lib/gusd/UT_Gf.h ) && \
( printf "/^namespace boost/s/namespace boost/namespace ${BOOST_NAMESPACE}/\nw\nq" | ed -s pxr/usd/lib/sdf/pySpec.h ) && \
( for i in `grep --include=\*.{cpp,h} -rl . -e "^namespace boost "`; do echo $$i; ( printf "/^namespace boost/s/namespace boost/namespace $(BOOST_NAMESPACE)/\nw\nq" | ed -s $$i ); done ) && \
( printf "/MAYA_LIBRARIES/a\n\044{X11_LIBRARIES}\n.\nw\nq" | ed -s third_party/maya/lib/pxrUsdMayaGL/CMakeLists.txt ) && \
( printf "/MAYA_INCLUDE_DIRS/a\n\044{GLUT_INCLUDE_DIR}\n.\nw\nq" | ed -s third_party/maya/lib/pxrUsdMayaGL/CMakeLists.txt ) && \
( printf "/OPENGL_gl_LIBRARY/a\n\044{X11_LIBRARIES}\n.\nw\nq" | ed -s pxr/imaging/lib/garch/CMakeLists.txt ) && \
( printf "/Unresolved_external_symbol_error_is_expected_Please_ignore/d\ni\nint Unresolved_external_symbol_error_is_expected_Please_ignore()\n{return 0;}\n.\nw\nq" | ed -s pxr/base/lib/plug/testenv/TestPlugDsoUnloadable.cpp ) && \
echo ">>>" Patching HDF5 support... && \
( printf "/HDF5/\n/COMPONENTS/\nd\nd\nd\nw\nq" | ed -s cmake/defaults/Packages.cmake ) && \
echo ">>>" Patching Maya finder... && \
( printf "/UNIX/\n/HINTS/\n-a\nPATH_SUFFIXES devkit\n.\nw\nq" | ed -s cmake/modules/FindMaya.cmake ) && \
echo ">>>" Adding static libraries to OIIO... && \
( for f in $(OIIO_LIBS); do ( printf "\044a\nlist(APPEND OIIO_LIBRARIES $$f)\n.\nw\nq" | ed -s cmake/modules/FindOpenImageIO.cmake ); done ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/pxr_shared_library/\n/SHARED/s/SHARED/STATIC/\nw\nq" | ed -s cmake/macros/Public.cmake ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/pxr_plugin/\n/SHARED/s/SHARED/STATIC/\nw\nq" | ed -s cmake/macros/Public.cmake ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/_ReadPlugInfoObject/-2a\nextern \"C\" __attribute__((weak))\n.\nw\nq" | ed -s pxr/base/lib/plug/info.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/PlugPlugin::_Load/\n/_handle/+1a\nif(0)\n.\nw\nq" | ed -s pxr/base/lib/plug/plugin.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/AppendPathList.*buildLocation/d\nw\nq" | ed -s pxr/base/lib/plug/initConfig.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/AppendPathList.*pluginBuildLocation/d\nw\nq" | ed -s pxr/base/lib/plug/initConfig.cpp ) && \
echo ">>>" Patching Alembic Reader for the AbcCoreLayer support... && \
( printf "/PXR_NAMESPACE_OPEN_SCOPE/-a\n#include <Alembic/AbcCoreFactory/IFactory.h>\n#include <boost/algorithm/string.hpp>\n.\nw\nq" | ed -s pxr/usd/plugin/usdAbc/alembicReader.cpp ) && \
( printf "/_ReaderContext::_OpenOgawa/\n/{/a\nstd::vector<std::string> archives;\nboost::split(archives, filePath, boost::is_any_of(\":\"));\n.\nw\nq" | ed -s pxr/usd/plugin/usdAbc/alembicReader.cpp ) && \
( printf "/_ReaderContext::_OpenOgawa/\n/\"Ogawa\"/a\nif (archives.size()>1) {\nAlembic::AbcCoreFactory::IFactory factory;\n*result = factory.getArchive(archives);\n} else\n.\nw\nq" | ed -s pxr/usd/plugin/usdAbc/alembicReader.cpp ) && \
echo ">>>" Patching Thread Limits for comatibility with MTOA... && \
( printf "/Work_GetConcurrencyLimitSetting/\n/{/\na\nreturn Work_NormalizeThreadCount(0);\n.\nw\nq" | ed -s pxr/base/lib/work/threadLimits.cpp ) && \
echo ">>>" Patching glf, hd, hdx to load built-in shaders... && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/GlfGLSLFX::_ProcessFile/--a\nextern \"C\" __attribute__((weak)) std::istream* _GetFileStream(const char* filename)\n.\nw\nq" | ed -s pxr/imaging/lib/glf/glslfx.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/GlfGLSLFX::_ProcessFile/--a\n{ return new std::ifstream(filename); }\n.\nw\nq" | ed -s pxr/imaging/lib/glf/glslfx.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/GlfGLSLFX::_ProcessFile/++d\nd\nd\nd\nd\nw\nq" | ed -s pxr/imaging/lib/glf/glslfx.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/_seenFiles.insert/a\nboost::scoped_ptr<istream> inputPtr(_GetFileStream(filePath.c_str()));\nreturn _ProcessInput(inputPtr.get(), context);\n.\nw\nq" | ed -s pxr/imaging/lib/glf/glslfx.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/_GetShaderPath/-d\n-a\nextern \"C\" __attribute__((weak)) TfToken\n.\nw\nq" | ed -s pxr/imaging/lib/glf/package.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/_GetShaderPath/-d\n-a\nextern \"C\" __attribute__((weak)) TfToken\n.\nw\nq" | ed -s pxr/imaging/lib/hdSt/package.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/_GetShaderPath/-d\n-a\nextern \"C\" __attribute__((weak)) TfToken\n.\nw\nq" | ed -s pxr/imaging/lib/hdx/package.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/_GetShaderPath/-d\n-a\nextern \"C\" __attribute__((weak)) TfToken\n.\nw\nq" | ed -s pxr/usdImaging/lib/usdImagingGL/package.cpp ) && \
echo ">>>" Patching schemaRegistry for ability to keep schemas in the binary... && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/_GetGeneratedSchema/-d\n-a\nextern \"C\" __attribute__((weak)) SdfLayerRefPtr\n.\nw\nq" | ed -s pxr/usd/lib/usd/schemaRegistry.cpp ) && \
echo ">>>" Turning off hdx conservative rasterization... && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/GL_NV_conservative_raster/a\nconvRstr = false;\n.\nw\nq" | ed -s pxr/imaging/lib/hdx/intersector.cpp ) && \
echo ">>>" Catmull-Clark is default subdivision scheme for all the alembics. It's temporary, while Hydra doesn't consider normals... && \
( printf "/UsdGeomTokens->subdivisionScheme/+2\ns/none/catmullClark/\nw\nq" | ed -s pxr/usd/plugin/usdAbc/alembicReader.cpp ) && \
echo ">>>" Patching bug in Katana linking... && \
( printf "/katanaAttrfncApi/a\nkatanaOpApi\nkatanaPluginApi\n.\nw\nq" | ed -s third_party/katana/lib/usdKatana/CMakeLists.txt ) && \
echo ">>>" Dont skip plugins when building static libraries... && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/Skipping plugin/\nd\nd\na\nset(args_TYPE \"STATIC\")\n.\nw\nq" | ed -s cmake/macros/Public.cmake ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/CMAKE_SHARED_LIBRARY_SUFFIX/s/CMAKE_SHARED_LIBRARY_SUFFIX/CMAKE_STATIC_LIBRARY_SUFFIX/\nw\nq" | ed -s cmake/macros/Public.cmake ) && \
echo ">>>" Patching Houdini plugin... && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/if(.*PXR_ENABLE_PYTHON_SUPPORT.*)/s/(.*)/(0)/\nw\nq" | ed -s CMakeLists.txt ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/if(.*PXR_ENABLE_PYTHON_SUPPORT.*)/s/(.*)/(0)/\nw\nq" | ed -s CMakeLists.txt ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/if(.*PXR_ENABLE_PYTHON_SUPPORT.*)/s/(.*)/(0)/\nw\nq" | ed -s CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/a\n$(PREFIX_ROOT)/boost/include\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/a\n$(PREFIX_ROOT)/boost/include\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniAPPS1.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniAPPS2.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniAPPS3.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniGEO.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniOP1.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniOP2.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniOP3.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniOPZ.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniPRM.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniRAY.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniUI.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniUT.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniAPPS1.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniAPPS2.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniAPPS3.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniGEO.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniOP1.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniOP2.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniOP3.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniOPZ.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniPRM.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniRAY.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniUI.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libHoudiniUT.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( test ! $(USE_STATIC_BOOST) == OFF || printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libhboost_system.so\n.\nw\nq" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( test ! $(USE_STATIC_BOOST) == OFF || printf "/INCLUDE_DIRS/-a\n\044{HOUDINI_LIB_DIRS}/libhboost_system.so\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "/INCLUDE_DIRS/-a\n$(PREFIX_ROOT)/boost/lib/lib$(BOOST_NAMESPACE)_filesystem$(DYNAMIC_EXT)\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "\044a\nfile(GLOB MYHEADERS *.h)\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( printf "\044a\ninstall(FILES \044{MYHEADERS} DESTINATION \044{PXR_INSTALL_SUBDIR}/include/OP_gusd)\n.\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/CMakeLists.txt ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/newDriverOperator/s/newDriverOperator/originalNewDriverOperator/\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/plugin.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/newSopOperator/s/newSopOperator/originalNewSopOperator/\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/plugin.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/newObjectOperator/s/newObjectOperator/originalNewObjectOperator/\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/plugin.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/newGeometryPrim/s/newGeometryPrim/originalNewGeometryPrim/\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/plugin.cpp ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/newGeometryIO/s/newGeometryIO/originalNewGeometryIO/\nw\nq" | ed -s third_party/houdini/plugin/OP_gusd/plugin.cpp ) && \
echo ">>>" Walter layers support in usdview... && \
( printf "/os.path.isfile.*usdFilePath/s/if /if 0 and /\nw\nq" | ed -s pxr/usdImaging/lib/usdviewq/appController.py ) && \
echo ">>>" Patching embree plugin... && \
( printf "/libembree.so/s/libembree.so/embree/\nw\nq" | ed -s cmake/modules/FindEmbree.cmake ) && \
( printf "/find_package_handle_standard_args/-a\nlist(APPEND EMBREE_LIBRARY $(PREFIX_ROOT)/embree/lib/libembree_avx.a)\n.\nw\nq" | ed -s cmake/modules/FindEmbree.cmake ) && \
( printf "/find_package_handle_standard_args/-a\nlist(APPEND EMBREE_LIBRARY $(PREFIX_ROOT)/embree/lib/libembree_avx2.a)\n.\nw\nq" | ed -s cmake/modules/FindEmbree.cmake ) && \
( printf "/find_package_handle_standard_args/-a\nlist(APPEND EMBREE_LIBRARY $(PREFIX_ROOT)/embree/lib/libembree_sse42.a)\n.\nw\nq" | ed -s cmake/modules/FindEmbree.cmake ) && \
( printf "/find_package_handle_standard_args/-a\nlist(APPEND EMBREE_LIBRARY $(PREFIX_ROOT)/embree/lib/liblexers.a)\n.\nw\nq" | ed -s cmake/modules/FindEmbree.cmake ) && \
( printf "/find_package_handle_standard_args/-a\nlist(APPEND EMBREE_LIBRARY $(PREFIX_ROOT)/embree/lib/libsimd.a)\n.\nw\nq" | ed -s cmake/modules/FindEmbree.cmake ) && \
( printf "/find_package_handle_standard_args/-a\nlist(APPEND EMBREE_LIBRARY $(PREFIX_ROOT)/embree/lib/libsys.a)\n.\nw\nq" | ed -s cmake/modules/FindEmbree.cmake ) && \
( printf "/find_package_handle_standard_args/-a\nlist(APPEND EMBREE_LIBRARY $(PREFIX_ROOT)/embree/lib/libtasking.a)\n.\nw\nq" | ed -s cmake/modules/FindEmbree.cmake ) && \
echo ">>>" Fixing bug with No module named PySide when opening Tree View in Houdini USD Import node... && \
( printf "/QtWidgets/d\na\ntry:\n\tfrom qt import QtWidgets\nexcept ImportError:\n\tpass\n.\nw\nq" | ed -s pxr/usdImaging/lib/usdviewq/__init__.py ) && \
( test ! $(USE_STATIC_BOOST) == ON || echo ">>>" Patching Houdini Mesh Wrapper to skip normals... ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/PUBLIC_CLASSES/a\nmeshWrapper\n.\nw\n" | ed -s third_party/houdini/lib/gusd/CMakeLists.txt ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/if.*(.*normalsAttr.HasAuthoredValueOpinion.*)/s/if.*(.*)/if(0)/\nw\n" | ed -s third_party/houdini/lib/gusd/meshWrapper.cpp ) && \
echo ">>>" Fixing bug with Katana plugin unresolved symbols... && \
( printf "/PYMODULE_CPPFILES/a\nwrapCache.cpp\n.\nw\n" | ed -s third_party/katana/lib/usdKatana/CMakeLists.txt ) && \
( test ! $(USE_STATIC_BOOST) == ON || echo ">>>" Patching hydra to not select children... ) && \
( test ! $(USE_STATIC_BOOST) == ON || printf "/UsdImagingDelegate::PopulateSelection/\n/} else {/s/else/else if(0)/\nw\n" | ed -s pxr/usdImaging/lib/usdImaging/delegate.cpp ) && \
mkdir -p build && cd build && \
mkdir -p $(PREFIX_ROOT) && \
$(PYSIDE_CONF) \
$(CMAKE) \
$(COMMON_CMAKE_FLAGS) \
-DALEMBIC_DIR=$(PREFIX_ROOT)/alembic \
-DBOOST_ROOT:STRING=$(PREFIX_ROOT)/boost \
-DBUILD_SHARED_LIBS:BOOL=$(BUILD_SHARED_LIBS) \
-DBoost_NAMESPACE=$(BOOST_NAMESPACE) \
-DCMAKE_INSTALL_PREFIX=$(PREFIX_ROOT)/$(USD_PACKAGE_NAME) \
-DDOUBLE_CONVERSION_INCLUDE_DIR:PATH=$(PREFIX_ROOT)/dc/include \
-DDOUBLE_CONVERSION_LIBRARY:PATH=$(PREFIX_ROOT)/dc/lib/libdouble-conversion.a \
-DEMBREE_LOCATION:PATH=$(PREFIX_ROOT)/embree \
-DGLEW_LOCATION:PATH=$(PREFIX_ROOT)/glew \
-DGLFW_LOCATION:PATH=$(PREFIX_ROOT)/glfw \
-DGLUT_Xmu_LIBRARY= \
-DHDF5_ROOT=$(PREFIX_ROOT)/hdf5 \
-DHOUDINI_ROOT:PATH=$(HOUDINI_ROOT) \
-DKATANA_API_LOCATION:PATH=$(KATANA_ROOT) \
-DMAYA_LOCATION:PATH=$(MAYA_ROOT) \
-DOIIO_LOCATION:PATH=$(PREFIX_ROOT)/oiio \
-DOPENEXR_BASE_DIR:PATH=$(PREFIX_ROOT)/ilmbase \
-DOPENEXR_LOCATION:PATH=$(PREFIX_ROOT)/openexr \
-DOPENSUBDIV_ROOT_DIR:PATH=$(PREFIX_ROOT)/opensubdiv \
-DPTEX_LOCATION:PATH=$(PREFIX_ROOT)/ptex \
-DPXR_BUILD_ALEMBIC_PLUGIN:BOOL=ON \
-DPXR_BUILD_EMBREE_PLUGIN:BOOL=ON \
-DPXR_BUILD_HOUDINI_PLUGIN:BOOL=$(BUILD_HOUDINI_PLUGINS) \
-DPXR_BUILD_IMAGING:BOOL=ON \
-DPXR_BUILD_KATANA_PLUGIN:BOOL=$(BUILD_KATANA_PLUGINS) \
-DPXR_INSTALL_LOCATION=$(PREFIX_ROOT)/$(USD_PACKAGE_NAME)/share/usd/plugins \
-DPXR_BUILD_MAYA_PLUGIN:BOOL=$(BUILD_SHARED_LIBS) \
-DPXR_BUILD_MONOLITHIC:BOOL=$(BUILD_SHARED_LIBS) \
-DPXR_BUILD_TESTS:BOOL=OFF \
-DPXR_ENABLE_PYTHON_SUPPORT:BOOL=$(BUILD_SHARED_LIBS) \
-DPXR_BUILD_USD_IMAGING:BOOL=ON \
-DPXR_ENABLE_HDF5_SUPPORT:BOOL=ON \
-DPXR_SET_INTERNAL_NAMESPACE=rdo$(USD_PACKAGE_NAME) \
-DPYSIDE_BIN_DIR=$(PREFIX_ROOT)/pyside/bin \
-DPYTHON_EXECUTABLE=$(PYTHON_BIN) \
-DTBB_LIBRARY=$(TBB_LIBRARY) \
-DTBB_ROOT_DIR=$(TBB_ROOT_DIR) \
-DZLIB_ROOT:PATH=$(PREFIX_ROOT)/zlib \
-D_GLUT_INC_DIR:PATH=$(PREFIX_ROOT)/glut/include \
-D_GLUT_glut_LIB_DIR:PATH=$(PREFIX_ROOT)/glut/lib \
.. > $(PREFIX_ROOT)/log_usd.txt 2>&1 && \
$(PYSIDE_CONF) \
$(CMAKE) \
--build . \
--target install \
--config $(CMAKE_BUILD_TYPE) \
-- -j $(JOB_COUNT) >> $(PREFIX_ROOT)/log_usd.txt 2>&1 && \
echo "USD source path: " $(USD_FILE) && \
cd ../.. && \
cd $(THIS_DIR) && \
echo $(USD_VERSION) > $@
# libz
$(ZLIB_STAMP) : $(ZLIB_FILE)/HEAD
@echo Building zlib $(ZLIB_VERSION) && \
mkdir -p $(BUILD_ROOT) && cd $(BUILD_ROOT) && \
rm -rf zlib && \
git clone -q --no-checkout $(SOURCES_ROOT)/zlib.git zlib && \
cd zlib && \
git checkout -q $(ZLIB_VERSION) && \
mkdir -p $(PREFIX_ROOT) && \
$(COMPILER_CONF) \
./configure \
--const \
--zprefix \
--prefix=$(PREFIX_ROOT)/zlib \
--static > $(PREFIX_ROOT)/log_zlib.txt 2>&1 && \
$(MAKE) -j$(JOB_COUNT) \
MAKE_MODE=$(MAKE_MODE) \
install >> $(PREFIX_ROOT)/log_zlib.txt 2>&1 && \
cd .. && \
rm -rf zlib && \
cd $(THIS_DIR) && \
echo $(ZLIB_VERSION) > $@
<|start_filename|>walter/katana/WalterIn/ArbitraryGeomParamUtils.h<|end_filename|>
#ifndef FnGeolibOp_WalterIn_ArbitraryGeomParamUtils_H
#define FnGeolibOp_WalterIn_ArbitraryGeomParamUtils_H
#include <Alembic/Abc/All.h>
#include <FnAttribute/FnGroupBuilder.h>
#include "AbcCook.h"
namespace WalterIn
{
void indexedParamToAttr(IndexedGeomParamPair & iProp,
const OpArgs & iArgs,
Foundry::Katana::GroupBuilder & oGb);
void processArbitraryGeomParam(AbcCookPtr ioCook,
Alembic::Abc::ICompoundProperty & iParent,
const Alembic::AbcCoreAbstract::PropertyHeader & iPropHeader,
Foundry::Katana::GroupBuilder & oStaticGb,
const std::string & iAttrPath,
Alembic::Abc::v10::IUInt64ArrayProperty * iIdsProperty = NULL);
void processArbGeomParams(AbcCookPtr ioCook,
Alembic::Abc::ICompoundProperty & iParent,
Foundry::Katana::GroupBuilder & oStaticGb,
Alembic::Abc::IUInt64ArrayProperty * iIdsProperty = NULL);
}
#endif
<|start_filename|>walter/houdini/src/UsdToGtPrim.h<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#ifndef __UsdToGtPrim_h__
#define __UsdToGtPrim_h__
#include <GT/GT_Handles.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/timeCode.h>
#include <gusd/purpose.h>
PXR_NAMESPACE_USING_DIRECTIVE
namespace WalterHoudini
{
/**
* @brief Copy data from a Usd Prim to a GT_Primitive.
*
* We put this function in a seperated compilation unit to clarify
* that it is the single point of contact with the Pixar Usd plugin for Houdini
* (as we are using its GusdPrimWrapper objects to extract Usd data).
*
* @param prim The source prim.
* @param time The time to get the data.
* @param purpose From which purpose you want to get the data.
*/
GT_PrimitiveHandle getGtPrimFromUsd(
const UsdPrim& prim,
const UsdTimeCode& time,
const GusdPurposeSet purpose = GUSD_PURPOSE_DEFAULT);
};
#endif
<|start_filename|>walter/usd/schemas/expression.cpp<|end_filename|>
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include ".//expression.h"
#include "pxr/usd/usd/schemaRegistry.h"
#include "pxr/usd/usd/typed.h"
#include "pxr/usd/sdf/types.h"
#include "pxr/usd/sdf/assetPath.h"
PXR_NAMESPACE_OPEN_SCOPE
// Register the schema with the TfType system.
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define<WalterExpression,
TfType::Bases< UsdTyped > >();
}
/* virtual */
WalterExpression::~WalterExpression()
{
}
/* static */
WalterExpression
WalterExpression::Get(const UsdStagePtr &stage, const SdfPath &path)
{
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return WalterExpression();
}
return WalterExpression(stage->GetPrimAtPath(path));
}
/* static */
const TfType &
WalterExpression::_GetStaticTfType()
{
static TfType tfType = TfType::Find<WalterExpression>();
return tfType;
}
/* static */
bool
WalterExpression::_IsTypedSchema()
{
static bool isTyped = _GetStaticTfType().IsA<UsdTyped>();
return isTyped;
}
/* virtual */
const TfType &
WalterExpression::_GetTfType() const
{
return _GetStaticTfType();
}
UsdAttribute
WalterExpression::GetExpressionAttr() const
{
return GetPrim().GetAttribute(WalterTokens->expression);
}
UsdAttribute
WalterExpression::CreateExpressionAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->expression,
SdfValueTypeNames->String,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
WalterExpression::GetGroupAttr() const
{
return GetPrim().GetAttribute(WalterTokens->group);
}
UsdAttribute
WalterExpression::CreateGroupAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(WalterTokens->group,
SdfValueTypeNames->String,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
namespace {
static inline TfTokenVector
_ConcatenateAttributeNames(const TfTokenVector& left,const TfTokenVector& right)
{
TfTokenVector result;
result.reserve(left.size() + right.size());
result.insert(result.end(), left.begin(), left.end());
result.insert(result.end(), right.begin(), right.end());
return result;
}
}
/*static*/
const TfTokenVector&
WalterExpression::GetSchemaAttributeNames(bool includeInherited)
{
static TfTokenVector localNames = {
WalterTokens->expression,
WalterTokens->group,
};
static TfTokenVector allNames =
_ConcatenateAttributeNames(
UsdTyped::GetSchemaAttributeNames(true),
localNames);
if (includeInherited)
return allNames;
else
return localNames;
}
PXR_NAMESPACE_CLOSE_SCOPE
// ===================================================================== //
// Feel free to add custom code below this line. It will be preserved by
// the code generator.
//
// Just remember to wrap code in the appropriate delimiters:
// 'PXR_NAMESPACE_OPEN_SCOPE', 'PXR_NAMESPACE_CLOSE_SCOPE'.
// ===================================================================== //
// --(BEGIN CUSTOM CODE)--
#include <boost/algorithm/string.hpp>
PXR_NAMESPACE_OPEN_SCOPE
std::string WalterExpression::GetExpression() const
{
std::string expression;
GetExpressionAttr().Get(&expression);
return expression;
}
void WalterExpression::SetExpression(const std::string& expression)
{
UsdAttribute expressionAttr = GetExpressionAttr();
if (!expressionAttr)
{
expressionAttr = CreateExpressionAttr();
}
expressionAttr.Set(expression);
}
WalterExpression::AssignmentLayers WalterExpression::GetLayers() const
{
AssignmentLayers layers;
// Iterate all the connections with the name starting with "assign:"
for (const UsdRelationship& relationship : GetPrim().GetRelationships())
{
// It should like this: "assign:defaultRenderLayer:shader"
const std::string name = relationship.GetName().GetText();
if (!boost::istarts_with(name, "assign:"))
{
continue;
}
std::vector<std::string> splitted;
boost::split(splitted, name, boost::is_any_of(":"));
if (splitted.size() != 3)
{
continue;
}
// Extract the render layer and the target.
const std::string layer = splitted[1];
const std::string target = splitted[2];
SdfPathVector shaders;
relationship.GetTargets(&shaders);
// We don't support multiple connections.
layers[layer][target] = shaders[0];
}
return layers;
}
void WalterExpression::SetConnection(
const std::string& layer,
const std::string& target,
const SdfPath& shader)
{
TfToken relName("assign:" + layer + ":" + target);
UsdRelationship rel = GetPrim().GetRelationship(relName);
if (!rel)
{
rel = GetPrim().CreateRelationship(relName, false);
}
rel.SetTargets(SdfPathVector{shader});
}
PXR_NAMESPACE_CLOSE_SCOPE
<|start_filename|>walter/maya/walterStandin/walterDrawOverride.cpp<|end_filename|>
// Copyright 2017 <NAME>. All rights reserved.
#include "walterDrawOverride.h"
#include <pxr/imaging/glf/glew.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usdGeom/imageable.h>
#include <pxr/usdImaging/usdImagingGL/gl.h>
#include "walterShapeNode.h"
#include "rdoProfiling.h"
#include <GL/gl.h>
#include <maya/MDrawContext.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MHWGeometryUtilities.h>
#include <maya/MUserData.h>
#include <maya/MGlobal.h>
#include <algorithm>
namespace WalterMaya {
PXR_NAMESPACE_USING_DIRECTIVE;
using namespace WalterMaya;
class DrawOverride::UserData : public MUserData
{
public:
UserData(ShapeNode* node) :
MUserData(false),
mShapeNode(node),
mIsSelected(false)
{
}
// Draw the stage.
void draw(const MHWRender::MDrawContext& context) const;
// Form USD Render Params.
void set(const MColor& wireframeColor, bool isSelected);
ShapeNode* node() const
{
return mShapeNode;
}
private:
ShapeNode* mShapeNode;
GfVec4f mWireframeColor;
bool mIsSelected;
};
void DrawOverride::UserData::draw(
const MHWRender::MDrawContext& context) const
{
RDOPROFILE("");
// Get USD stuff from the node.
UsdStageRefPtr stage = mShapeNode->getStage();
// TODO: const_cast is bad
UsdImagingGLSharedPtr renderer =
const_cast<ShapeNode*>(mShapeNode)->getRenderer();
if (!renderer || !stage)
{
return;
}
// We need to save the state of the bound program because Hydra doesn't
// restore it.
GLint lastProgram;
glGetIntegerv(GL_CURRENT_PROGRAM, &lastProgram);
// Get the matrices from the Maya context.
const MMatrix view =
context.getMatrix(MHWRender::MFrameContext::kWorldViewMtx);
const MMatrix projection =
context.getMatrix(MHWRender::MFrameContext::kProjectionMtx);
double viewData[4][4];
double projectionData[4][4];
view.get(viewData);
projection.get(projectionData);
// Get the Maya viewport.
int originX;
int originY;
int width;
int height;
context.getViewportDimensions(originX, originY, width, height);
const unsigned int displayStyle = context.getDisplayStyle();
const bool needWireframe =
!(displayStyle & MHWRender::MFrameContext::kBoundingBox) &&
(displayStyle & MHWRender::MFrameContext::kWireFrame || mIsSelected);
// Create render parameters. We can't define them as a member of UserData
// because Draw should be const.
UsdImagingGL::RenderParams params = mShapeNode->mParams;
// Frame number.
params.frame = UsdTimeCode(mShapeNode->time * getCurrentFPS());
params.highlight = mIsSelected;
params.wireframeColor = mWireframeColor;
if (needWireframe)
{
if (displayStyle & MHWRender::MFrameContext::kGouraudShaded)
{
params.drawMode = UsdImagingGLEngine::DRAW_WIREFRAME_ON_SURFACE;
}
else
{
params.drawMode = UsdImagingGLEngine::DRAW_WIREFRAME;
}
}
else
{
params.drawMode = UsdImagingGLEngine::DRAW_SHADED_SMOOTH;
}
GfMatrix4d viewMatrix(viewData);
GfMatrix4d projectionMatrix(projectionData);
// Put the camera and the viewport to the engine.
renderer->SetCameraState(
viewMatrix, projectionMatrix, GfVec4d(originX, originY, width, height));
// Lighting. We need to query lights of the scene and provide them to Hydra.
MStatus status;
// Take into account only the 8 lights supported by the basic OpenGL
// profile.
const unsigned int nbLights =
std::min(context.numberOfActiveLights(&status), 8u);
GlfSimpleLightVector lights;
if (nbLights > 0)
{
lights.reserve(nbLights);
for (unsigned int i = 0; i < nbLights; ++i)
{
MFloatPointArray positions;
MFloatVector direction;
float intensity;
MColor color;
bool hasDirection;
bool hasPosition;
status = context.getLightInformation(
i,
positions,
direction,
intensity,
color,
hasDirection,
hasPosition);
if (status != MStatus::kSuccess || !hasPosition)
{
continue;
}
color *= intensity;
GlfSimpleLight light;
light.SetAmbient(GfVec4f(0.0f, 0.0f, 0.0f, 0.0f));
light.SetDiffuse(GfVec4f(color[0], color[1], color[2], 1.0f));
light.SetPosition(GfVec4f(
positions[0][0], positions[0][1], positions[0][2], 1.0f));
lights.push_back(light);
}
}
if (lights.empty())
{
// There are no lights. We need to render something anyway, so put the
// light to the camera position.
GfVec3d translation = viewMatrix.GetInverse().ExtractTranslation();
GlfSimpleLight light;
light.SetAmbient(GfVec4f(0.0f, 0.0f, 0.0f, 0.0f));
light.SetPosition(
GfVec4f(translation[0], translation[1], translation[2], 1.0f));
lights.push_back(light);
}
if (!lights.empty())
{
static const GfVec4f ambient(0.01f, 0.01f, 0.01f, 1.0f);
static std::shared_ptr<GlfSimpleMaterial> material;
if(!material)
{
// Init only once.
material = std::make_shared<GlfSimpleMaterial>();
material->SetSpecular(GfVec4f(0.05f, 0.05f, 0.05f, 1.0f));
material->SetShininess(64.0);
}
renderer->SetLightingState(lights, *material, ambient);
}
{
RDOPROFILE("Render with Hydra");
renderer->Render(
stage->GetPrimAtPath(SdfPath::AbsoluteRootPath()), params);
}
// Restore the state of the GL_CURRENT_PROGRAM.
glUseProgram(lastProgram);
// Clear OpenGL errors. Because UsdImagingGL::TestIntersection prints them.
while (glGetError() != GL_NO_ERROR)
{
}
}
void DrawOverride::UserData::set(
const MColor& wireframeColor,
bool isSelected)
{
mWireframeColor =
GfVec4f(
wireframeColor[0],
wireframeColor[1],
wireframeColor[2],
1.0f);
mIsSelected = isSelected;
}
void DrawOverride::drawCb(
const MHWRender::MDrawContext& context,
const MUserData* userData)
{
const UserData* data = dynamic_cast<const UserData*>(userData);
if (data)
{
data->draw(context);
}
}
MHWRender::MPxDrawOverride* DrawOverride::creator(const MObject& obj)
{
return new DrawOverride(obj);
}
DrawOverride::DrawOverride(const MObject& obj) :
MPxDrawOverride(obj, &drawCb)
{}
DrawOverride::~DrawOverride()
{}
MHWRender::DrawAPI DrawOverride::supportedDrawAPIs() const
{
// This draw override supports only OpenGL.
return MHWRender::kOpenGL | MHWRender::kOpenGLCoreProfile;
}
bool DrawOverride::isBounded(
const MDagPath& /*objPath*/,
const MDagPath& /*cameraPath*/) const
{
return true;
}
MBoundingBox DrawOverride::boundingBox(
const MDagPath& objPath,
const MDagPath& cameraPath) const
{
// Extract the USD stuff.
MStatus status;
MFnDependencyNode node(objPath.node(), &status);
if (!status)
{
return MBoundingBox();
}
const ShapeNode* shapeNode = dynamic_cast<ShapeNode*>(node.userNode());
if (!shapeNode)
{
return MBoundingBox();
}
return shapeNode->boundingBox();
}
bool DrawOverride::disableInternalBoundingBoxDraw() const
{
// Always return true since we will perform custom bounding box drawing.
return true;
}
MUserData* DrawOverride::prepareForDraw(
const MDagPath& objPath,
const MDagPath& cameraPath,
const MHWRender::MFrameContext& frameContext,
MUserData* oldData)
{
RDOPROFILE("");
MObject object = objPath.node();
// Retrieve data cache (create if does not exist)
UserData* data = dynamic_cast<UserData*>(oldData);
if (!data)
{
// Get the real ShapeNode from the MObject.
MStatus status;
MFnDependencyNode node(object, &status);
if (status)
{
data = new UserData(
dynamic_cast<ShapeNode*>(node.userNode()));
}
}
if (data)
{
// Compute data.
const MColor wireframeColor =
MHWRender::MGeometryUtilities::wireframeColor(objPath);
const MHWRender::DisplayStatus displayStatus =
MHWRender::MGeometryUtilities::displayStatus(objPath);
const bool isSelected =
(displayStatus == MHWRender::kActive) ||
(displayStatus == MHWRender::kLead) ||
(displayStatus == MHWRender::kHilite);
const unsigned int displayStyle = frameContext.getDisplayStyle();
bool isTextured = displayStyle & MHWRender::MFrameContext::kTextured;
// Prepare USD
data->node()->updateUSDStage();
data->node()->updateTextures(
objPath.getDrawOverrideInfo().fEnableTexturing);
data->set(wireframeColor, isSelected);
}
return data;
}
#if MAYA_API_VERSION >= 201800
bool DrawOverride::wantUserSelection() const {
return true;
}
bool DrawOverride::refineSelectionPath(
const MSelectionInfo &selectInfo,
const MRenderItem &hitItem,
MDagPath &path,
MObject &components,
MSelectionMask &objectMask) {
return MPxDrawOverride::refineSelectionPath(
selectInfo, hitItem, path, components, objectMask);
}
bool DrawOverride::userSelect(
MSelectionInfo &selectInfo,
const MHWRender::MDrawContext &context,
MPoint &hitPoint,
const MUserData *data2) {
const UserData* data = dynamic_cast<const UserData*>(data2);
ShapeNode* node = data->node();
// Get USD stuff from the node.
UsdStageRefPtr stage = node->getStage();
UsdImagingGLSharedPtr renderer = node->getRenderer();
if (!renderer || !stage)
{
return false;
}
M3dView view = M3dView::active3dView();
GfMatrix4d viewMatrix;
GfMatrix4d projectionMatrix;
GLuint glHitRecord;
view.beginSelect(&glHitRecord, 1);
glGetDoublev(GL_MODELVIEW_MATRIX, viewMatrix.GetArray());
glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix.GetArray());
view.endSelect();
GfVec3d outHitPoint;
SdfPath outHitPrimPath;
UsdImagingGL::RenderParams params = node->mParams;
params.frame = UsdTimeCode(node->time * getCurrentFPS());
params.drawMode = UsdImagingGLEngine::DRAW_SHADED_SMOOTH;
bool didHit = renderer->TestIntersection(
viewMatrix,
projectionMatrix,
GfMatrix4d(1.0),
stage->GetPrimAtPath(SdfPath::AbsoluteRootPath()),
params,
&outHitPoint,
&outHitPrimPath);
// Sub-Selection
if (didHit)
{
UsdPrim prim;
// It can be an instance object. It's not allowed to get prim. We need
// to find the first valid prim.
while (true)
{
prim = stage->GetPrimAtPath(outHitPrimPath);
if (prim.IsValid())
{
break;
}
outHitPrimPath = outHitPrimPath.GetParentPath();
}
assert(prim.IsValid());
// Check the purpose of selected object.
if (prim.IsA<UsdGeomImageable>())
{
UsdGeomImageable imageable(prim);
if (imageable.ComputePurpose() == UsdGeomTokens->proxy)
{
// It's a proxy. Level up.
outHitPrimPath = outHitPrimPath.GetParentPath();
}
}
// If object was selected, set sub-selection.
node->setSubSelectedObjects(outHitPrimPath.GetText());
hitPoint = MPoint(outHitPoint[0], outHitPoint[1], outHitPoint[2]);
// Execute the callback to change the UI.
// selectPath() returns the tranform, multiPath() returns the shape.
// Form the MEL command. It looks like this:
// callbacks
// -executeCallbacks
// -hook walterPanelSelectionChanged
// "objectName" "subSelectedObject";
MString command =
"callbacks -executeCallbacks "
"-hook walterPanelSelectionChanged \"";
command += node->name();
command += "\" \"";
command += outHitPrimPath.GetText();
command += "\";";
MGlobal::executeCommandOnIdle(command);
}
else
{
// If object was not selected, clear sub-selection.
node->setSubSelectedObjects("");
}
return didHit;
}
#endif
}
| all-in-one-of/OpenWalter |
<|start_filename|>NAOFramework v 1.0/NAOHumanoid/src/com/aldebaran/demo/picture/Picture.java<|end_filename|>
package com.aldebaran.demo.picture;
import java.awt.image.BufferedImage;
public class Picture {
private BufferedImage image;
private String filename;
public Picture(BufferedImage image, String filename) {
this.image = image;
this.filename = filename;
}
public BufferedImage getImage() {
return this.image;
}
public String getFilename() {
return this.filename;
}
}
| ioNetrunner/NAO-Kinect-Teleoperation |
<|start_filename|>app/src/main/java/io/kuenzler/whatsappwebtogo/BlobDownloader.java<|end_filename|>
package io.kuenzler.whatsappwebtogo;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BlobDownloader {
private Context context;
public final static String JsInstance = "Downloader";
private static String lastDownloadBlob = "";
private static long lastDownloadTime = 0;
private final long sameFileDownloadTimeout = 100;
public BlobDownloader(Context context) {
this.context = context;
}
@JavascriptInterface
public void getBase64FromBlobData(String base64Data) throws IOException {
Log.d(WebviewActivity.DEBUG_TAG,"Download triggered "+ System.currentTimeMillis());
lastDownloadTime = System.currentTimeMillis();
if(System.currentTimeMillis() - lastDownloadTime < sameFileDownloadTimeout){
Log.d(WebviewActivity.DEBUG_TAG,"Download within sameFileDownloadTimeout");
if (lastDownloadBlob.equals(base64Data)) {
Log.d(WebviewActivity.DEBUG_TAG,"Blobs match, ignoring download");
} else {
Log.d(WebviewActivity.DEBUG_TAG,"Blobs do not match, downloading");
lastDownloadBlob = base64Data;
convertBase64StringToFileAndStoreIt(base64Data);
}
}
}
public static String getBase64StringFromBlobUrl(String blobUrl) {
if (blobUrl.startsWith("blob")) {
return "javascript: var xhr = new XMLHttpRequest();" +
"xhr.open('GET', '" + blobUrl + "', true);" +
"xhr.responseType = 'blob';" +
"xhr.onload = function(e) {" +
" if (this.status == 200) {" +
" var blobFile = this.response;" +
" var reader = new FileReader();" +
" reader.readAsDataURL(blobFile);" +
" reader.onloadend = function() {" +
" base64data = reader.result;" +
" "+JsInstance+".getBase64FromBlobData(base64data);" +
" }" +
" }" +
"};" +
"xhr.send();";
}
return "javascript: console.log('It is not a Blob URL');";
}
private void convertBase64StringToFileAndStoreIt(String base64File) throws IOException {
final int notificationId = (int) System.currentTimeMillis();
final String[] strings = base64File.split(",");
String extension = MimeTypes.lookupExt(strings[0]);
if (null == extension) {
extension = strings[0];
extension = "." + extension.substring(extension.indexOf('/') + 1, extension.indexOf(';'));
}
@SuppressLint("SimpleDateFormat") //SDF is just fine for filename
final String currentDateTime = new SimpleDateFormat("yyyyMMdd-hhmmss").format(new Date());
final String dlFileName = "WAWTG_" + currentDateTime + extension;
final File dlFilePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + dlFileName);
final byte[] fileAsBytes = Base64.decode(base64File.replaceFirst(strings[0], ""), 0);
final FileOutputStream os = new FileOutputStream(dlFilePath, false);
os.write(fileAsBytes);
os.flush();
if (dlFilePath.exists()) {
final Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
final Uri apkURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", dlFilePath);
intent.setDataAndType(apkURI, MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
final PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
final String notificationChannelId = "Downloads";
final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (null == notificationManager) {
return;
}
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, "name", NotificationManager.IMPORTANCE_LOW);
notification = new Notification.Builder(context, notificationChannelId)
.setContentText(String.format(context.getString(R.string.notification_text_saved_as), dlFileName))
.setContentTitle(context.getString(R.string.notification_title_tap_to_open))
.setContentIntent(pendingIntent)
.setChannelId(notificationChannelId)
.setSmallIcon(android.R.drawable.stat_notify_chat)
.build();
notificationManager.createNotificationChannel(notificationChannel);
} else {
notification = new NotificationCompat.Builder(context, notificationChannelId)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSmallIcon(android.R.drawable.stat_notify_chat)
.setContentIntent(pendingIntent)
.setContentTitle(String.format(context.getString(R.string.notification_text_saved_as), dlFileName))
.setContentText(context.getString(R.string.notification_title_tap_to_open))
.build();
}
notificationManager.notify(notificationId, notification);
Toast.makeText(context, R.string.toast_saved_to_downloads_folder, Toast.LENGTH_SHORT).show();
}
}
}
| benehmb/WhatsappWebToGo |
<|start_filename|>core/src/main/java/android/content/pm/IPackageInstallerCallback.java<|end_filename|>
package android.content.pm;
public interface IPackageInstallerCallback {
}
<|start_filename|>libkit/src/main/java/com/merxury/libkit/entity/ETrimMemoryLevel.kt<|end_filename|>
package com.merxury.libkit.entity
enum class ETrimMemoryLevel {
HIDDEN,
RUNNING_MODERATE,
BACKGROUND,
RUNNING_LOW,
MODERATE,
RUNNING_CRITICAL,
COMPLETE
}
<|start_filename|>app/src/main/java/com/merxury/blocker/util/ToastUtil.kt<|end_filename|>
package com.merxury.blocker.util
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.widget.Toast
import androidx.annotation.StringRes
import com.merxury.blocker.BlockerApplication
object ToastUtil {
private var toast: Toast? = null
private val handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
toast?.cancel()
val message = msg.obj as String
toast = Toast.makeText(BlockerApplication.context, message, msg.arg2)
toast?.show()
}
}
fun showToast(message: String, duration: Int) {
handler.sendMessage(handler.obtainMessage(0, 0, duration, message))
}
fun showToast(@StringRes msgId: Int, duration: Int) {
val message = BlockerApplication.context.getString(msgId)
handler.sendMessage(handler.obtainMessage(0, 0, duration, message))
}
fun showToast(message: String) {
if (!TextUtils.isEmpty(message)) {
showToast(message, Toast.LENGTH_SHORT)
}
}
}
<|start_filename|>core/src/main/java/android/content/pm/IPackageManager.java<|end_filename|>
package android.content.pm;
import android.content.ComponentName;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.RemoteException;
public interface IPackageManager extends IInterface {
IPackageInstaller getPackageInstaller()
throws RemoteException;
ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId)
throws RemoteException;
void setComponentEnabledSetting(ComponentName componentName, int newState, int flags, int userId)
throws RemoteException;
int getComponentEnabledSetting(ComponentName componentName, int userId)
throws RemoteException;
void setApplicationEnabledSetting(String packageName, int newState, int flags, int userId)
throws RemoteException;
int getApplicationEnabledSetting(String packageName, int userId)
throws RemoteException;
abstract class Stub extends Binder implements IPackageManager {
public static IPackageManager asInterface(IBinder obj) {
throw new UnsupportedOperationException();
}
}
}
<|start_filename|>ifw-api/src/main/java/com/merxury/ifw/entity/Service.java<|end_filename|>
package com.merxury.ifw.entity;
public class Service extends Component {
}
<|start_filename|>ifw-api/src/main/java/com/merxury/ifw/entity/ComponentType.java<|end_filename|>
package com.merxury.ifw.entity;
public enum ComponentType {
ACTIVITY,
BROADCAST,
SERVICE,
PROVIDER,
UNKNOWN
}
<|start_filename|>core/src/main/java/android/content/pm/IPackageInstaller.java<|end_filename|>
package android.content.pm;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.RemoteException;
import androidx.annotation.RequiresApi;
import java.util.List;
public interface IPackageInstaller extends IInterface {
int createSession(PackageInstaller.SessionParams params, String installerPackageName, int userId)
throws RemoteException;
void updateSessionAppIcon(int sessionId, Bitmap appIcon)
throws RemoteException;
void updateSessionAppLabel(int sessionId, String appLabel)
throws RemoteException;
void abandonSession(int sessionId)
throws RemoteException;
IPackageInstallerSession openSession(int sessionId)
throws RemoteException;
PackageInstaller.SessionInfo getSessionInfo(int sessionId)
throws RemoteException;
ParceledListSlice<PackageInstaller.SessionInfo> getAllSessions(int userId)
throws RemoteException;
ParceledListSlice<PackageInstaller.SessionInfo> getMySessions(String installerPackageName, int userId)
throws RemoteException;
@RequiresApi(29)
ParceledListSlice<PackageInstaller.SessionInfo> getStagedSessions()
throws RemoteException;
void registerCallback(IPackageInstallerCallback callback, int userId)
throws RemoteException;
void unregisterCallback(IPackageInstallerCallback callback)
throws RemoteException;
// removed from 26
void uninstall(String packageName, String callerPackageName, int flags,
IntentSender statusReceiver, int userId);
@RequiresApi(26)
void uninstall(VersionedPackage versionedPackage, String callerPackageName, int flags,
IntentSender statusReceiver, int userId)
throws RemoteException;
@RequiresApi(29)
void installExistingPackage(String packageName, int installFlags, int installReason,
IntentSender statusReceiver, int userId, List<String> whiteListedPermissions)
throws RemoteException;
void setPermissionsResult(int sessionId, boolean accepted)
throws RemoteException;
abstract class Stub extends Binder implements IPackageInstaller {
public static IPackageInstaller asInterface(IBinder binder) {
throw new UnsupportedOperationException();
}
}
}
<|start_filename|>ifw-api/src/main/java/com/merxury/ifw/entity/IntentFilter.java<|end_filename|>
package com.merxury.ifw.entity;
import org.simpleframework.xml.ElementList;
import java.util.List;
public class IntentFilter {
@ElementList(inline = true)
List<Action> actions;
public List<Action> getActions() {
return actions;
}
public void setActions(List<Action> actions) {
this.actions = actions;
}
}
<|start_filename|>libkit/src/main/java/com/merxury/libkit/exception/ProcessUnexpectedTerminateException.java<|end_filename|>
package com.merxury.libkit.exception;
/**
* Created by Mercury on 2018/1/1.
* ProcessUnexpectedTerminateException
*/
public class ProcessUnexpectedTerminateException extends Exception {
public ProcessUnexpectedTerminateException() {
super();
}
public ProcessUnexpectedTerminateException(String message) {
super(message);
}
public ProcessUnexpectedTerminateException(String message, Throwable cause) {
super(message, cause);
}
public ProcessUnexpectedTerminateException(Throwable cause) {
super(cause);
}
}
<|start_filename|>app/src/main/java/com/merxury/blocker/util/AppLauncher.kt<|end_filename|>
package com.merxury.blocker.util
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.widget.Toast
import com.merxury.blocker.R
object AppLauncher {
fun startApplication(context: Context, packageName: String) {
val intent = context.packageManager.getLaunchIntentForPackage(packageName)
if (intent == null) {
Toast.makeText(context, context.getString(R.string.app_cannot_start), Toast.LENGTH_SHORT).show()
return
}
Toast.makeText(context, context.getString(R.string.starting_application), Toast.LENGTH_SHORT).show()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
}
fun showApplicationDetails(context: Context, packageName: String) {
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
intent.data = Uri.fromParts("package", packageName, null)
context.startActivity(intent)
}
}
<|start_filename|>ifw-api/src/main/java/com/merxury/ifw/entity/Action.java<|end_filename|>
package com.merxury.ifw.entity;
import org.simpleframework.xml.Attribute;
public class Action {
@Attribute
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<|start_filename|>app/src/main/java/com/merxury/blocker/util/StringUtil.kt<|end_filename|>
package com.merxury.blocker.util
import java.io.PrintWriter
import java.io.StringWriter
object StringUtil {
@JvmStatic
fun getStackTrace(error: Throwable): String {
val errors = StringWriter()
error.printStackTrace(PrintWriter(errors))
return errors.toString()
}
}
<|start_filename|>ifw-api/src/main/java/com/merxury/ifw/entity/ComponentFilter.java<|end_filename|>
package com.merxury.ifw.entity;
import org.simpleframework.xml.Attribute;
public class ComponentFilter {
@Attribute
private String name;
public ComponentFilter() {
}
public ComponentFilter(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<|start_filename|>libkit/src/main/java/com/merxury/libkit/utils/ManagerUtils.kt<|end_filename|>
package com.merxury.libkit.utils
import android.annotation.TargetApi
import android.os.Build
import com.merxury.libkit.RootCommand
import com.merxury.libkit.entity.ETrimMemoryLevel
object ManagerUtils {
fun launchApplication(packageName: String) {
RootCommand.runBlockingCommand("monkey -p $packageName -c android.intent.category.LAUNCHER 1")
}
fun launchActivity(packageName: String, activityName: String) {
RootCommand.runBlockingCommand("am start -n $packageName/$activityName")
}
fun forceStop(packageName: String) {
RootCommand.runBlockingCommand("am force-stop $packageName")
}
fun startService(packageName: String, serviceName: String) {
RootCommand.runBlockingCommand("am startservice $packageName/$serviceName")
}
fun stopService(packageName: String, serviceName: String) {
RootCommand.runBlockingCommand("am stopservice $packageName/$serviceName")
}
fun disableApplication(packageName: String) {
RootCommand.runBlockingCommand("pm disable $packageName")
}
fun enableApplication(packageName: String) {
RootCommand.runBlockingCommand("pm enable $packageName")
}
fun clearData(packageName: String) {
RootCommand.runBlockingCommand("pm clear $packageName")
}
@TargetApi(Build.VERSION_CODES.M)
fun trimMemory(packageName: String, level: ETrimMemoryLevel) {
RootCommand.runBlockingCommand("am send-trim-memory $packageName ${level.name}")
}
}
<|start_filename|>ifw-api/src/main/java/com/merxury/ifw/entity/Broadcast.java<|end_filename|>
package com.merxury.ifw.entity;
public class Broadcast extends Component {
}
<|start_filename|>ifw-api/src/main/java/com/merxury/ifw/entity/Rules.java<|end_filename|>
package com.merxury.ifw.entity;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root(name = "rules")
public class Rules {
@Element(required = false)
private Activity activity;
@Element(required = false)
private Broadcast broadcast;
@Element(required = false)
private Service service;
public Activity getActivity() {
return activity;
}
public void setActivity(Activity activity) {
this.activity = activity;
}
public Broadcast getBroadcast() {
return broadcast;
}
public void setBroadcast(Broadcast broadcast) {
this.broadcast = broadcast;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
}
<|start_filename|>core/src/main/java/com/merxury/blocker/core/root/EControllerMethod.kt<|end_filename|>
package com.merxury.blocker.core.root
enum class EControllerMethod {
PM,
IFW,
SHIZUKU
}
<|start_filename|>ifw-api/src/main/java/com/merxury/ifw/entity/Activity.java<|end_filename|>
package com.merxury.ifw.entity;
public class Activity extends Component {
}
<|start_filename|>libkit/src/main/java/com/merxury/libkit/utils/PermissionUtils.kt<|end_filename|>
package com.merxury.libkit.utils
import com.topjohnwu.superuser.Shell
object PermissionUtils {
val isRootAvailable: Boolean
get() = Shell.rootAccess()
}
<|start_filename|>libkit/src/main/java/com/merxury/libkit/entity/ComponentInfo.kt<|end_filename|>
package com.merxury.libkit.entity
import android.content.pm.ComponentInfo
fun ComponentInfo.getSimpleName(): String {
return name.split(".").last()
}
| opensourcefuture/blocker |
<|start_filename|>src/Calendar.Plugin/Shared/Enums/EventIndicatorType.cs<|end_filename|>
namespace Xamarin.Plugin.Calendar.Enums
{
/// <summary>
/// Set type of event indicator on calendar
/// </summary>
public enum EventIndicatorType
{
/// <summary>
/// Set event indicator as dot bellow of date in calendar
/// </summary>
BottomDot,
/// <summary>
/// Set event indicator as dot on top of date in calendar
/// </summary>
TopDot,
/// <summary>
/// Set event indicator as colored background in calendar
/// </summary>
Background,
/// <summary>
/// Set event indicator as larger size colored background in calendar
/// </summary>
BackgroundFull,
}
}
| MintDevTeam/Xamarin.Plugin.Calendar |
<|start_filename|>vendor/github.com/casimir/xdg-go/xdg_linux.go<|end_filename|>
package xdg
import "os"
func DataHome() string {
return os.Getenv("HOME") + "/.local/share"
}
func ConfigHome() string {
return os.Getenv("HOME") + "/.config"
}
func CacheHome() string {
return os.Getenv("HOME") + "/.cache"
}
func DataDirs() []string {
// The specification gives a value with trailing slashes but only
// for this value. Seems odd enough to take the liberty of removing them.
return []string{"/usr/local/share", "/usr/share"}
}
func ConfigDirs() []string {
return []string{"/etc/xdg"}
}
<|start_filename|>vendor/github.com/casimir/xdg-go/xdg_darwin.go<|end_filename|>
package xdg
import "os"
func DataHome() string {
return os.Getenv("HOME") + "/Library"
}
func ConfigHome() string {
return os.Getenv("HOME") + "/Library/Preferences"
}
func CacheHome() string {
return os.Getenv("HOME") + "/Library/Caches"
}
func DataDirs() []string {
return []string{"/Library"}
}
func ConfigDirs() []string {
return []string{"/Library/Preferences", "/Library/Application Support"}
}
<|start_filename|>vendor/github.com/casimir/xdg-go/xdg.go<|end_filename|>
package xdg
import (
"os"
"path/filepath"
"strings"
)
// App is an aggregation of XDG information for a named application. Useful to
// propagate app configuration.
type App struct {
Name string
}
func (a App) path(envVar string, defaultFn func() string, file string) string {
base := os.Getenv(envVar)
if base == "" {
base = defaultFn()
}
return filepath.Join(base, a.Name, file)
}
// DataPath determines the full path of a data file.
func (a App) DataPath(file string) string {
return a.path("XDG_DATA_HOME", DataHome, file)
}
// ConfigPath determines the full path of a data file.
func (a App) ConfigPath(file string) string {
return a.path("XDG_CONFIG_HOME", ConfigHome, file)
}
// CachePath determines the full path of a cached file.
func (a App) CachePath(file string) string {
return a.path("XDG_CACHE_HOME", CacheHome, file)
}
func (a App) multiPaths(envVar string, defaultFn func() []string, file string) []string {
var bases []string
env := os.Getenv(envVar)
if env != "" {
bases = strings.Split(env, ":")
} else {
bases = defaultFn()
}
var dirs []string
for _, it := range bases {
dirs = append(dirs, filepath.Join(it, a.Name, file))
}
return dirs
}
// SystemDataPaths determines system-wide possible paths for a data file.
func (a App) SystemDataPaths(file string) []string {
return a.multiPaths("XDG_DATA_DIRS", DataDirs, file)
}
// SystemConfigPaths determines system-wide possible paths for a config file.
func (a App) SystemConfigPaths(file string) []string {
return a.multiPaths("XDG_CONFIG_DIRS", ConfigDirs, file)
}
var defaultApp App
// SetName for the default application. Used for package-wide functions.
func SetName(name string) {
defaultApp.Name = name
}
// DataPath determines the full path of a data file.
func DataPath(file string) string {
return defaultApp.DataPath(file)
}
// ConfigPath determines the full path of a data file.
func ConfigPath(file string) string {
return defaultApp.ConfigPath(file)
}
// CachePath determines the full path of a cached file.
func CachePath(file string) string {
return defaultApp.CachePath(file)
}
// SystemDataPaths determines system-wide possible paths for a data file.
func SystemDataPaths(file string) []string {
return defaultApp.SystemDataPaths(file)
}
// SystemConfigPaths determines system-wide possible paths for a config file.
func SystemConfigPaths(file string) []string {
return defaultApp.SystemConfigPaths(file)
}
<|start_filename|>vendor/github.com/casimir/xdg-go/xdg_windows.go<|end_filename|>
package xdg
import "os"
func DataHome() string {
return os.Getenv("APPDATA")
}
func ConfigHome() string {
return os.Getenv("APPDATA")
}
func CacheHome() string {
return os.Getenv("TEMP")
}
func DataDirs() []string {
return []string{os.Getenv("APPDATA"), os.Getenv("LOCALAPPDATA")}
}
func ConfigDirs() []string {
return []string{os.Getenv("APPDATA"), os.Getenv("LOCALAPPDATA")}
}
| br0xen/user-config |
<|start_filename|>popup/modules/screen.js<|end_filename|>
//
// Screen
// based on templates
//
window.Screen = (function () {
var $el = $('#screen'),
templates = null,
showCallbacks = {};
// template handler
function compileTemplate(source) {
return function (context) {
var html = source;
$.each(context, function (k, v) {
html = html.replace('{{' + k + '}}', v || '');
});
return html;
};
}
templates = {
settings: compileTemplate($('#settings-template').html()),
'report-issue': compileTemplate($('#report-issue-template').html())
};
return {
// show a specific template screen
// @param {String} name
show: function (name, context) {
$el.html(templates[name](context));
// handle callback
if (showCallbacks[name]) {
showCallbacks[name]($el);
}
// support autofocus inside templates
$el.find('[autofocus]').focus();
},
// callback for showing a specific screen
// @param {String} name
// @param {Function} callback run when it's shown
onShow: function (name, callback) {
showCallbacks[name] = callback;
}
}
}());
<|start_filename|>Makefile<|end_filename|>
# build latest zip release
# requires: npm install --global web-ext
build:
web-ext build --overwrite-dest
<|start_filename|>popup/modules/settings.js<|end_filename|>
//
// Settings storage
// e.g. for access token (used for auth to github api) & other settings
//
// ref https://developer.chrome.com/extensions/storage
//
window.Settings = (function () {
var cachedData = null,
secret = '';
function encrypt(data) {
return window.CryptoJS.AES.encrypt(JSON.stringify(data), secret).toString();
}
function decrypt(str) {
var data = window.CryptoJS.AES.decrypt(str.toString(), secret).toString(window.CryptoJS.enc.Utf8);
if (! data) return {};
return JSON.parse(data);
}
return {
// set encryption secret
setSecret: function (newSecret) {
secret = newSecret;
},
// get
// @param {Function} callback gets given the settings Object
get: function (callback) {
if (cachedData) {
callback(cachedData);
return;
}
chrome.storage.local.get(['settings'], function (result) {
if (! result.settings) {
callback(null);
return;
}
cachedData = decrypt(result.settings);
callback(cachedData);
});
},
// fast method to only check for cached version
getCached: function() {
return cachedData;
},
// set
// @param {Object} token
// @param {Function} callback when it's finished saving
set: function (settings, callback) {
cachedData = settings;
settings = encrypt(settings);
chrome.storage.local.set({ settings: settings }, function (result) {
callback();
});
}
}
}());
<|start_filename|>popup/app.css<|end_filename|>
* { margin: 0; padding: 0; }
body {
width: 300px;
padding: 10px;
}
body, input, select {
font: 14px/1.5 'Open Sans', sans-serif;
}
a {
text-decoration: underline;
color: lightseagreen;
cursor: pointer;
}
p {
margin-bottom: 15px;
}
label {
user-select: none;
}
input, select {
width: 100%;
padding: 4px;
box-sizing: border-box;
}
label.hidden-checkbox-label {
display: inline-block;
padding: 5px;
margin: 1px 0;
border: 1px solid #EEE;
}
label.hidden-checkbox-label:hover {
background-color: #EEE;
}
.hidden-checkbox {
display: none;
}
.hidden-checkbox:checked + label.hidden-checkbox-label {
background-color: lightseagreen;
color: #FFF;
}
<|start_filename|>popup/app.js<|end_filename|>
// When showing the settings screen
Screen.onShow('settings', function ($screen) {
// hook into save button click
$screen.on('submit', '#settings-form', function (e) {
e.preventDefault();
// save settings
var token = $screen.find('#token').val(),
org = $screen.find('#org').val();
Settings.set({ token: token, org: org }, function () {
// & switch to report-issue screen
Screen.show('report-issue');
});
});
});
// When showing the report-issue screen
Screen.onShow('report-issue', function ($screen) {
// get token
Settings.get(function (store) {
// lookup GitHub repos list
var gh = new GitHub({
token: store.token
});
var org = store.org ? gh.getOrganization(store.org) : gh.getUser();
(store.org ? org.getRepos : org.listRepos).call(org, function(err, repos) {
if (err) {
alert(err);
return;
}
var orgs = {};
repos.forEach(function (repo) {
var orgName = repo.owner.login;
orgs[orgName] = orgs[orgName] || [];
orgs[orgName].push(repo);
});
var list = Object.keys(orgs).map(function (org) {
var options = orgs[org].map(function (repo) {
return '<option value="' + repo.full_name + '">' + repo.name + '</option>';
});
return '<optgroup label="' + org + '">' + options.join('') + '</optgroup>';
});
$screen.find('#repo').html(list.join(''));
});
// projects only supported for org level
if (! store.org) {
$screen.find('#project-container').hide();
IssueForm.init($screen);
} else {
org.listProjects(function(err, projects) {
if (err) {
alert(err);
return;
}
var list = projects.map(function (project) {
return '<option value="' + store.org + '/' + project.number + '">' + project.name + '</option>';
});
$screen.find('#project').html('<option>~ optional ~</option>' + list);
IssueForm.init($screen);
});
}
// hookup config icon to switch to settings screen
$screen.on('click', '#settings-link', function (e) {
e.preventDefault();
Screen.show('settings', store);
});
// hook into submit button click
$screen.on('submit', '#report-issue-form', function (e) {
e.preventDefault();
// gather fields
var title = $screen.find('#title').val(),
repo = $screen.find('#repo').val(),
project = $screen.find('#project').val(),
added_url = $screen.find('#added_url').prop('checked'),
added_screenshot = $screen.find('#added_screenshot').prop('checked'),
added_debug = $screen.find('#added_debug').prop('checked'),
type_field = $screen.find('#type_field input[name="type"]:checked').val(),
body = '',
url = 'https://github.com/' + repo + '/issues/new?title=' + encodeURIComponent(title);
// build up extra params (ref https://help.github.com/articles/about-automation-for-issues-and-pull-requests-with-query-parameters/)
if (project) {
url += '&projects=' + encodeURIComponent(project);
}
// redirect to new issue page for given repo
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
// handle sending (delay until added additional data)
var sendToGitHub = function () {
if (body) {
url += '&body=' + encodeURIComponent(body);
}
chrome.tabs.create({
url: url
});
};
// add type/label + standard template ;D
if (type_field) {
url += '&labels=' + encodeURIComponent(type_field);
if (type_field=='bug') {
body += "### Issue description:\n";
body += "\n";
body += "As a User/Admin/Developer\n";
body += "When I <steps to reproduce>\n";
body += "Currently it <what happens currently>\n";
body += "While it should <what should happen>\n";
body += "Because <some business value>\n";
body += "\n\n";
}
else if (type_field=='enhancement') {
body += "### Story:\n";
body += "\n";
body += "As a User/Admin/Developer\n";
body += "I want <some software feature>\n";
body += "So that <some business value>\n";
body += "\n";
body += "### Requirements:\n";
body += "\n";
body += "- list them here\n";
body += "\n";
body += "### Tasks:\n";
body += "\n";
body += "- [ ] \n";
body += "- [ ] \n";
body += "- [ ] \n";
body += "\n\n";
}
}
// add url
if (added_url) {
body += "Reported from: " + tabs[0].url + "\n\n";
}
// add debug data
if (added_debug) {
body += "### Debug details: \n";
body += "User-agent: " + navigator.userAgent + "\n";
body += "Cookies: " + navigator.cookieEnabled + " (DNT: " + navigator.doNotTrack + ")\n";
body += "Date/time: " + Date() + "\n";
body += "\n";
}
// add screenshot link
if (added_screenshot) {
chrome.tabs.captureVisibleTab(function (imageUri) {
body += "### Screenshot:\n\n";
body += "<!-- drag in the screenshot file -->\n\n";
download(imageUri, 'screenshot.png');
setTimeout(sendToGitHub, 300); // small delay to allow download
});
} else {
sendToGitHub();
}
});
});
});
});
// Check if a token is saved yet & show either settings to set it or the report-issue screen
Settings.get(function (store) {
if (! store || ! store.token) {
Screen.show('settings', {
token: '',
org: ''
});
} else {
Screen.show('report-issue');
}
});
<|start_filename|>popup/modules/issue-form.js<|end_filename|>
//
// Issue Form
//
// Restores field state & watches for changes to save state
//
window.IssueForm = (function () {
var fields = {};
return {
init: function ($screen) {
chrome.storage.local.get(['fields'], function (result) {
// restore field state
if (result.fields) {
fields = JSON.parse(result.fields);
$screen.find('select').each(function () {
var $input = $(this),
val = fields[$input.attr('name')];
if (val != undefined) {
$input.val(val).trigger('change');
}
});
$screen.find('input[type="radio"]').each(function () {
var $input = $(this),
val = fields[$input.attr('name')];
if (val != undefined) {
$input.filter('#' + val).prop('checked', true);
}
});
}
// watch for field changes
$screen.find('select').on('change', function () {
var $input = $(this);
fields[$input.attr('name')] = $input.val();
chrome.storage.local.set({ fields: JSON.stringify(fields) });
});
$screen.find('input[type="radio"]').on('change', function () {
var $input = $(this);
fields[$input.attr('name')] = $input.attr('id');
chrome.storage.local.set({ fields: JSON.stringify(fields) });
});
});
}
}
}());
<|start_filename|>manifest.json<|end_filename|>
{
"manifest_version": 2,
"name": "Quick add issue to GitHub",
"description": "Open source browser extension/addon for adding issues to Github via a browser button.",
"version": "1.4",
"browser_action": {
"browser_style": true,
"default_icon": {
"48": "images/button-48.png",
"96": "images/button-96.png"
},
"default_popup": "popup/app.html"
},
"permissions": ["activeTab", "tabs", "storage", "<all_urls>"]
}
<|start_filename|>popup/modules/hidden-checkbox.js<|end_filename|>
//
// Handle accessability for our hidden checkboxs where only the label is shown
// We use tabindex on them so users can tab to them
// but we want users to be able to press enter or space to trigger a click
//
$('body').on('keypress', '.hidden-checkbox-label', function (e) {
var enterKeyCode = 13,
spaceKeyCode = 32;
console.log('Pressed: ', e.which);
if (e.which == enterKeyCode || e.which == spaceKeyCode) {
e.preventDefault();
$(this).click();
}
});
| stilliard/quick-add-github-issue-browser-extension |
<|start_filename|>ProgressButtonView/src/main/java/es/voghdev/progressbuttonview/ProgressImageButtonView.java<|end_filename|>
/*
* Copyright (C) 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.progressbuttonview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
public class ProgressImageButtonView extends ProgressButtonView {
ImageButton imageButton;
int buttonDrawableResId = NO_ID;
public ProgressImageButtonView(Context context) {
super(context);
}
public ProgressImageButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ProgressImageButtonView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected void bindViewListeners(View v) {
imageButton = (ImageButton) findViewById(R.id.progress_image_button_btn);
progressBar = (ProgressBar) findViewById(R.id.progress_image_button_progressBar);
}
@Override
protected void style(Button button, Context context, AttributeSet attrs, int defStyle) {
if (attrs != null) {
TypedArray a;
a = (defStyle >= 0)
?
context.obtainStyledAttributes(attrs, R.styleable.ProgressButtonView, defStyle, 0)
:
context.obtainStyledAttributes(attrs, R.styleable.ProgressButtonView);
int backgroundColor =
a.getColor(R.styleable.ProgressButtonView_backgroundColorResource,
NO_COLOR);
int drawableResId = a.getResourceId(R.styleable.ProgressButtonView_backgroundDrawable,
NO_DRAWABLE);
int src = a.getResourceId(R.styleable.ProgressButtonView_src,
NO_DRAWABLE);
boolean hideOnClick = a.getBoolean(R.styleable.ProgressButtonView_hideButtonWhileLoading, false);
float paddingRight = a.getDimension(R.styleable.ProgressButtonView_buttonPaddingRight, 8f);
float paddingLeft = a.getDimension(R.styleable.ProgressButtonView_buttonPaddingLeft, 8f);
float paddingTop = a.getDimension(R.styleable.ProgressButtonView_buttonPaddingTop, 0f);
float paddingBottom = a.getDimension(R.styleable.ProgressButtonView_buttonPaddingBottom, 0f);
if (backgroundColor != NO_COLOR) {
setBackgroundColor(backgroundColor);
}
this.hideButtonOnClick(hideOnClick);
if (drawableResId != NO_DRAWABLE) {
setBackground(ContextCompat.getDrawable(getContext(), drawableResId));
imageButton.setPadding((int) paddingLeft, (int) paddingTop, (int) paddingRight, (int) paddingBottom);
}
if (src != NO_DRAWABLE) {
buttonDrawableResId = src;
setImageDrawable(ContextCompat.getDrawable(getContext(), src));
imageButton.setPadding((int) paddingLeft, (int) paddingTop, (int) paddingRight, (int) paddingBottom);
}
// TODO remove inheritance
a.recycle();
}
}
public void setOnClickListener(OnClickListener l) {
imageButton.setOnClickListener(l);
}
public void setOnLongClickListener(OnLongClickListener l) {
imageButton.setOnLongClickListener(l);
}
public void setText(String text) {
/* Empty */
}
public void setText(int resId) {
/* Empty */
}
public void setTextColor(int color) {
/* Empty */
}
public void setTextSize(float textSize) {
/* Empty */
}
public void setBackground(Drawable background) {
if (Build.VERSION.SDK_INT >= 16 && button != null) {
imageButton.setBackground(background);
} else if (Build.VERSION.SDK_INT < 16 && button != null) {
imageButton.setBackgroundDrawable(background);
}
}
public void setImageDrawable(Drawable drawable) {
imageButton.setImageDrawable(drawable);
}
public void setImageBitmap(Bitmap bitmap) {
imageButton.setImageBitmap(bitmap);
}
public void setImageResource(int resId) {
imageButton.setImageResource(resId);
}
public void setImageAlpha(int alpha) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
imageButton.setImageAlpha(alpha);
}
}
public void setBackgroundResource(int resId) {
imageButton.setBackgroundResource(resId);
}
public void setBackgroundColor(int color) {
imageButton.setBackgroundColor(color);
}
@Override
protected int getLayoutId() {
return R.layout.view_progress_image_button;
}
public synchronized void showLoading() {
progressBar.setVisibility(ProgressBar.VISIBLE);
imageButton.setClickable(false);
if (hideButtonOnClick) {
imageButton.setVisibility(View.INVISIBLE);
} else {
int nullDrawable = 0; // TODO find a proper null
// TODO investigate about tinting icon like background color
setImageResource(nullDrawable);
}
loading = true;
}
public synchronized void hideLoading() {
progressBar.setVisibility(ProgressBar.GONE);
imageButton.setVisibility(View.VISIBLE);
imageButton.setClickable(true);
if (buttonDrawableResId != NO_ID) {
setImageResource(buttonDrawableResId);
}
loading = false;
}
}
<|start_filename|>sample/src/main/java/es/voghdev/progressbuttonview/sample/EfficientProgressButtonViewActivity.java<|end_filename|>
/*
* Copyright (C) 2016 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.progressbuttonview.sample;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import es.voghdev.progressbuttonview.ProgressButtonView;
public class EfficientProgressButtonViewActivity extends AppCompatActivity {
ProgressButtonView progressButtonView;
AlertDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_efficient_progress_button);
progressButtonView = (ProgressButtonView) findViewById(R.id.progressButtonView);
progressButtonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressButtonView.showLoading();
celebrateVisibilityAfterAFewMillisecs();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (dialog != null) {
dialog.cancel();
dialog = null;
}
}
private void celebrateVisibilityAfterAFewMillisecs() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
progressButtonView.hideLoading();
Toast.makeText(EfficientProgressButtonViewActivity.this,
"Wow. You're so efficient!", Toast.LENGTH_SHORT).show();
progressButtonView.setText("I'm still efficient");
showChangeTextDialog();
}
}, 1500);
}
private void showChangeTextDialog() {
dialog = new AlertDialog.Builder(this)
.setTitle("Change button text")
.setMessage("Do you want to change button text?")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
int color = ContextCompat.getColor(EfficientProgressButtonViewActivity.this, R.color.orange);
progressButtonView.setBackgroundColor(color);
progressButtonView.setText("Send");
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
dialog.show();
}
}
<|start_filename|>sample/src/main/java/es/voghdev/progressbuttonview/sample/CustomProgressBarActivity.java<|end_filename|>
/*
* Copyright (C) 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.progressbuttonview.sample;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import es.voghdev.progressbuttonview.ProgressButtonView;
public class CustomProgressBarActivity extends AppCompatActivity {
ProgressButtonView progressButtonView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_progress_bar);
progressButtonView = (ProgressButtonView) findViewById(R.id.progressButtonView);
progressButtonView.setIndeterminateDrawableColorFilter(0xFFFF00FF,
android.graphics.PorterDuff.Mode.MULTIPLY);
progressButtonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressButtonView.showLoading();
celebrateVisibilityAfterAFewMillisecs();
}
});
}
private void celebrateVisibilityAfterAFewMillisecs() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
progressButtonView.hideLoading();
Toast.makeText(CustomProgressBarActivity.this,
"Have you seen my cool ProgressBar drawable?", Toast.LENGTH_SHORT).show();
}
}, 1500);
}
}
<|start_filename|>sample/src/androidTest/java/es/voghdev/progressbuttonview/ProgressButtonViewLoadingMatcher.java<|end_filename|>
/*
* Copyright (C) 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.progressbuttonview;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
public class ProgressButtonViewLoadingMatcher extends BaseMatcher<ProgressButtonView> {
@Override
public boolean matches(Object item) {
ProgressButtonView pbv = (ProgressButtonView) item;
return pbv.isLoading();
}
@Override
public void describeTo(Description description) {
description.appendText("ProgressButtonView is displaying loading state");
}
}
<|start_filename|>ProgressButtonView/src/main/java/es/voghdev/progressbuttonview/ProgressButtonView.java<|end_filename|>
/*
* Copyright (C) 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.progressbuttonview;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
public class ProgressButtonView extends FrameLayout {
public static final int NO_DRAWABLE = -1;
public static final int NO_COLOR = -1;
public static final float DEFAULT_SIZE = 14f;
public static final String DEFAULT_TINT_MODE = "src_atop";
Button button;
ProgressBar progressBar;
int textColor;
boolean hideButtonOnClick = false;
boolean loading = false;
String buttonText = "";
public ProgressButtonView(Context context) {
super(context);
initViews();
style(button, context, null, -1);
}
public ProgressButtonView(Context context, AttributeSet attrs) {
super(context, attrs);
initViews();
style(button, context, attrs, -1);
}
public ProgressButtonView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initViews();
style(button, context, attrs, defStyle);
}
private void initViews() {
View v = inflate(getContext(), getLayoutId(), this);
bindViewListeners(v);
}
protected void bindViewListeners(View v) {
button = (Button) findViewById(R.id.progress_button_btn);
progressBar = (ProgressBar) findViewById(R.id.progress_button_progressBar);
}
protected int getLayoutId() {
return R.layout.view_progress_button;
}
public void setOnClickListener(OnClickListener l) {
button.setOnClickListener(l);
}
public void setOnLongClickListener(OnLongClickListener l) {
button.setOnLongClickListener(l);
}
public void setText(String text) {
buttonText = text;
button.setText(text);
}
public void setText(int resId) {
setText(getContext().getString(resId));
}
public CharSequence getText() {
return button.getText();
}
public void setTextColor(int color) {
button.setTextColor(color);
}
public void setTextSize(float textSize) {
button.setTextSize(textSize);
}
public void setEnabled(boolean enabled) {
button.setEnabled(enabled);
}
@SuppressWarnings("NewApi")
public void setIndeterminateTintMode(PorterDuff.Mode tintMode) {
progressBar.setIndeterminateTintMode(tintMode);
}
@SuppressWarnings("NewApi")
public void setIndeterminateDrawableTiled(Drawable d) {
progressBar.setIndeterminateDrawableTiled(d);
}
public void setIndeterminateDrawable(Drawable d) {
progressBar.setIndeterminateDrawable(d);
}
public void setIndeterminateDrawableColorFilter(int color, PorterDuff.Mode mode) {
progressBar.getIndeterminateDrawable().setColorFilter(color, mode);
}
public void setIndeterminateDrawableColorFilter(ColorFilter colorFilter) {
progressBar.getIndeterminateDrawable().setColorFilter(colorFilter);
}
@SuppressWarnings("NewApi")
public void setIndeterminateTintList(ColorStateList tint) {
progressBar.setIndeterminateTintList(tint);
}
public void setBackground(Drawable background) {
if (Build.VERSION.SDK_INT >= 16 && button != null) {
button.setBackground(background);
} else if (Build.VERSION.SDK_INT < 16 && button != null) {
button.setBackgroundDrawable(background);
}
}
@SuppressLint("NewApi")
public void setBackgroundTintList(ColorStateList tint) {
button.setBackgroundTintList(tint);
}
@SuppressLint("NewApi")
public void setBackgroundTintMode(PorterDuff.Mode mode) {
button.setBackgroundTintMode(mode);
}
public void setBackgroundResource(int resId) {
button.setBackgroundResource(resId);
}
public void setBackgroundColor(int color) {
button.setBackgroundColor(color);
}
public void setTypeface(Typeface tf) {
button.setTypeface(tf);
}
public void setTypeface(Typeface tf, int style) {
button.setTypeface(tf, style);
}
public void hideButtonOnClick(boolean hide) {
this.hideButtonOnClick = hide;
}
public void setAllCaps(boolean value) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
button.setAllCaps(value);
}
}
@SuppressWarnings("NewApi")
public synchronized void showLoading() {
boolean isColorDrawable = (button.getBackground() instanceof ColorDrawable);
if (isColorDrawable) {
ColorDrawable buttonColor = (ColorDrawable) button.getBackground();
button.setTextColor(buttonColor.getColor());
}
progressBar.setVisibility(ProgressBar.VISIBLE);
button.setClickable(false);
buttonText = button.getText().toString();
if (hideButtonOnClick) {
button.setVisibility(View.INVISIBLE);
} else {
button.setText(isColorDrawable
? buttonText
: buttonText.replaceAll(".", " "));
}
loading = true;
}
public synchronized void hideLoading() {
progressBar.setVisibility(ProgressBar.GONE);
button.setVisibility(View.VISIBLE);
button.setClickable(true);
if (buttonText.length() > 0) {
button.setText(buttonText);
}
setTextColor(textColor);
loading = false;
}
public synchronized boolean isLoading() {
return loading;
}
//region Styling methods
protected void style(Button button, Context context, AttributeSet attrs, int defStyle) {
if (attrs != null) {
TypedArray a;
a = (defStyle >= 0)
?
context.obtainStyledAttributes(attrs, R.styleable.ProgressButtonView, defStyle, 0)
:
context.obtainStyledAttributes(attrs, R.styleable.ProgressButtonView);
int textColor = a.getColor(R.styleable.ProgressButtonView_textColor,
ContextCompat.getColor(getContext(), android.R.color.white));
int backgroundColor =
a.getColor(R.styleable.ProgressButtonView_backgroundColorResource,
NO_COLOR);
String text = a.getString(R.styleable.ProgressButtonView_text);
int drawableResId = a.getResourceId(R.styleable.ProgressButtonView_backgroundDrawable,
NO_DRAWABLE);
boolean hideOnClick = a.getBoolean(R.styleable.ProgressButtonView_hideButtonWhileLoading, false);
float paddingRight = a.getDimension(R.styleable.ProgressButtonView_buttonPaddingRight, 8f);
float paddingLeft = a.getDimension(R.styleable.ProgressButtonView_buttonPaddingLeft, 8f);
float paddingTop = a.getDimension(R.styleable.ProgressButtonView_buttonPaddingTop, 0f);
float paddingBottom = a.getDimension(R.styleable.ProgressButtonView_buttonPaddingBottom, 0f);
float textSize = a.getDimension(R.styleable.ProgressButtonView_textSize, 14);
String tintMode = a.getString(R.styleable.ProgressButtonView_progressBarTintMode);
int tintColor = a.getColor(R.styleable.ProgressButtonView_progressBarTint, NO_COLOR);
boolean textAllCaps = a.getBoolean(R.styleable.ProgressButtonView_allCaps, true);
this.textColor = textColor;
setTextColor(textColor);
if (backgroundColor != NO_COLOR) {
setBackgroundColor(backgroundColor);
}
this.hideButtonOnClick(hideOnClick);
if (text != null) {
setText(text);
}
if (drawableResId != NO_DRAWABLE) {
setBackground(ContextCompat.getDrawable(getContext(), drawableResId));
button.setPadding((int) paddingLeft, (int) paddingTop, (int) paddingRight, (int) paddingBottom);
}
if (textSize != DEFAULT_SIZE) {
button.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
if (tintColor != NO_COLOR && tintMode == null) {
tintMode = DEFAULT_TINT_MODE.toUpperCase();
}
if (tintColor != NO_COLOR && tintMode != null) {
PorterDuff.Mode mode = PorterDuff.Mode.valueOf(tintMode.toUpperCase());
setIndeterminateDrawableColorFilter(tintColor, mode);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
button.setAllCaps(textAllCaps);
}
a.recycle();
}
}
//endregion
}
<|start_filename|>sample/src/main/java/es/voghdev/progressbuttonview/sample/SetTextIssueActivity.java<|end_filename|>
package es.voghdev.progressbuttonview.sample;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import es.voghdev.progressbuttonview.ProgressButtonView;
public class SetTextIssueActivity extends AppCompatActivity {
ProgressButtonView progressButtonView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressButtonView = (ProgressButtonView) findViewById(R.id.progressButtonView);
progressButtonView.setText("Text Before");
progressButtonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressButtonView.showLoading();
progressButtonView.setText("Text After");
progressButtonView.hideLoading();
}
});
}
}
<|start_filename|>sample/src/main/java/es/voghdev/progressbuttonview/sample/MainActivity.java<|end_filename|>
/*
* Copyright (C) 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.progressbuttonview.sample;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import es.voghdev.progressbuttonview.ProgressButtonView;
public class MainActivity extends AppCompatActivity {
ProgressButtonView progressButtonView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressButtonView = (ProgressButtonView) findViewById(R.id.progressButtonView);
progressButtonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressButtonView.showLoading();
sayHelloAfterAFewMillisecs();
}
});
}
private void sayHelloAfterAFewMillisecs() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
progressButtonView.hideLoading();
Toast.makeText(MainActivity.this,
R.string.progressButtonView_hello_response, Toast.LENGTH_SHORT).show();
}
}, 1500);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_sample2) {
Intent intent = new Intent(this, ViewWithWrongAttributesActivity.class);
startActivity(intent);
return false;
} else if (id == R.id.action_sample3) {
Intent intent = new Intent(this, ViewWithTwoBackgroundsActivity.class);
startActivity(intent);
return false;
} else if (id == R.id.action_sample4) {
Intent intent = new Intent(this, ImageButtonActivity.class);
startActivity(intent);
return false;
} else if (id == R.id.action_sample5) {
Intent intent = new Intent(this, CustomProgressBarActivity.class);
Intent intent2 = new Intent(this, CustomProgressBarXMLActivity.class);
startActivity(intent);
startActivity(intent2);
return false;
} else if (id == R.id.action_sample6) {
Intent intent = new Intent(this, ViewWithLowerCaseActivity.class);
startActivity(intent);
return false;
} else if (id == R.id.action_sample7) {
Intent intent = new Intent(this, WideProgressButtonViewActivity.class);
startActivity(intent);
return false;
}
return super.onOptionsItemSelected(item);
}
}
<|start_filename|>sample/src/androidTest/java/es/voghdev/progressbuttonview/ProgressButtonViewMatcher.java<|end_filename|>
package es.voghdev.progressbuttonview;
import androidx.test.espresso.ViewInteraction;
import androidx.test.espresso.matcher.BoundedMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static org.hamcrest.core.Is.is;
public class ProgressButtonViewMatcher {
public static ViewInteraction onLoadingProgressButtonView(boolean loading) {
return onView(isAssignableFrom(ProgressButtonView.class)).check(matches(isLoading(is(true))));
}
private static Matcher<Object> isLoading(final Matcher<Boolean> loadingMatcher) {
return new BoundedMatcher<Object, ProgressButtonView>(ProgressButtonView.class) {
@Override
public boolean matchesSafely(ProgressButtonView progressButtonView) {
return progressButtonView.isLoading();
}
@Override
public void describeTo(Description description) {
description.appendText(", which is loading");
}
};
}
}
<|start_filename|>sample/src/androidTest/java/es/voghdev/progressbuttonview/CustomProgressBarTest.java<|end_filename|>
/*
* Copyright (C) 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.voghdev.progressbuttonview;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import es.voghdev.progressbuttonview.sample.CustomProgressBarActivity;
import es.voghdev.progressbuttonview.sample.CustomProgressBarXMLActivity;
import es.voghdev.progressbuttonview.sample.R;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class CustomProgressBarTest {
@Rule
public ActivityTestRule<CustomProgressBarActivity> activityRule =
new ActivityTestRule<>(CustomProgressBarActivity.class, true, false);
@Rule
public ActivityTestRule<CustomProgressBarXMLActivity> activityXMLRule =
new ActivityTestRule<>(CustomProgressBarXMLActivity.class, true, false);
@Test
public void shouldDisplayAProgressButtonViewWithCustomProgressBarDrawable() {
startActivity();
onView(withId(R.id.progressButtonView)).check(matches(isDisplayed()));
onView(withId(R.id.progressButtonView)).perform(click());
onView(withText("I have a custom progressBar drawable")).check(matches(isDisplayed()));
}
@Test
public void shouldDisplayACustomProgressBarTintSetOnXML() throws Exception {
startXMLActivity();
onView(withId(R.id.progressButtonView)).check(matches(isDisplayed()));
onView(withId(R.id.progressButtonView)).perform(click());
onView(withText("My progressBar drawable is tinted on XML")).check(matches(isDisplayed()));
}
private CustomProgressBarActivity startActivity() {
return activityRule.launchActivity(null);
}
private CustomProgressBarXMLActivity startXMLActivity() {
return activityXMLRule.launchActivity(null);
}
} | voghDev/ProgressButtonView |
<|start_filename|>src/cpp/preface.cpp<|end_filename|>
#include <iostream>
int main() {
char tape[20000] = {0};
char *ptr = tape;
| 0paIescent/brainhug |
<|start_filename|>pkg/xtermjs/constants.go<|end_filename|>
package xtermjs
import "github.com/gorilla/websocket"
var WebsocketMessageType = map[int]string{
websocket.BinaryMessage: "binary",
websocket.TextMessage: "text",
websocket.CloseMessage: "close",
websocket.PingMessage: "ping",
websocket.PongMessage: "pong",
}
<|start_filename|>internal/log/log.go<|end_filename|>
package log
import (
"fmt"
"os"
"path"
"runtime"
"github.com/sirupsen/logrus"
)
var logger = logrus.New()
type Logger interface {
Trace(...interface{})
Tracef(string, ...interface{})
Debug(...interface{})
Debugf(string, ...interface{})
Info(...interface{})
Infof(string, ...interface{})
Warn(...interface{})
Warnf(string, ...interface{})
Error(...interface{})
Errorf(string, ...interface{})
}
// Log defines the function signature of the logger
type Log func(l ...interface{})
// Log defines the function signature of the logger when called with format parameters
type Logf func(s string, l ...interface{})
var WithField,
WithFields = logger.WithField,
logger.WithFields
// Trace logs at the Trace level
var Trace,
// Debug logs at the Debug level
Debug,
// Info logs at the Info level
Info,
// Warn logs at the Warn level
Warn,
// Error logs at the Error level
Error,
Print Log = logger.Trace,
logger.Debug,
logger.Info,
logger.Warn,
logger.Error,
func(l ...interface{}) {
fmt.Println(l...)
}
// Tracef logs at the trace level with formatting
var Tracef,
// Debugf logs at the debug level with formatting
Debugf,
// Infof logs at the info level with formatting
Infof,
// Warnf logs at the warn level with formatting
Warnf,
// Errorf logs at the error level with formatting
Errorf,
Printf Logf = logger.Tracef,
logger.Debugf,
logger.Infof,
logger.Warnf,
logger.Errorf,
func(s string, l ...interface{}) {
fmt.Printf(s, l...)
fmt.Printf("\n")
}
func Init(
logFormat Format,
logLevel Level,
) {
logger.SetLevel(LevelMap[logLevel])
logger.SetOutput(os.Stderr)
logger.SetReportCaller(true)
if logFormat == FormatJSON {
logger.SetFormatter(&logrus.JSONFormatter{
CallerPrettyfier: func(frame *runtime.Frame) (function string, file string) {
function = frame.Function
file = path.Base(frame.File)
return
},
DataKey: "@data",
TimestampFormat: "2006-01-02T15:04:05-0700",
FieldMap: logrus.FieldMap{
logrus.FieldKeyFile: "@file",
logrus.FieldKeyFunc: "@func",
logrus.FieldKeyLevel: "@level",
logrus.FieldKeyMsg: "@message",
logrus.FieldKeyTime: "@timestamp",
logrus.FieldKeyLogrusError: "@error",
},
})
return
}
logger.SetFormatter(&logrus.TextFormatter{
CallerPrettyfier: func(frame *runtime.Frame) (function string, file string) {
function = path.Base(frame.Function)
file = path.Base(frame.File)
return
},
TimestampFormat: "15:04:05",
DisableSorting: false,
FullTimestamp: true,
QuoteEmptyFields: true,
ForceQuote: true,
})
}
<|start_filename|>internal/log/constants.go<|end_filename|>
package log
import "github.com/sirupsen/logrus"
type Level string
const (
LevelTrace Level = "trace"
LevelDebug Level = "debug"
LevelInfo Level = "info"
LevelWarn Level = "warn"
LevelError Level = "error"
)
var ValidLevelStrings = []string{
string(LevelTrace),
string(LevelDebug),
string(LevelInfo),
string(LevelWarn),
string(LevelError),
}
var LevelMap = map[Level]logrus.Level{
LevelTrace: logrus.TraceLevel,
LevelDebug: logrus.DebugLevel,
LevelInfo: logrus.InfoLevel,
LevelWarn: logrus.WarnLevel,
LevelError: logrus.ErrorLevel,
}
type Format string
const (
FormatJSON Format = "json"
FormatText Format = "text"
)
var ValidFormatStrings = []string{
string(FormatJSON),
string(FormatText),
}
<|start_filename|>pkg/xtermjs/types.go<|end_filename|>
package xtermjs
import "fmt"
// TTYSize represents a JSON structure to be sent by the frontend
// xterm.js implementation to the xterm.js websocket handler
type TTYSize struct {
Cols uint16 `json:"cols"`
Rows uint16 `json:"rows"`
X uint16 `json:"x"`
Y uint16 `json:"y"`
}
// Logger is the logging interface used by the xterm.js handler
type Logger interface {
Trace(...interface{})
Tracef(string, ...interface{})
Debug(...interface{})
Debugf(string, ...interface{})
Info(...interface{})
Infof(string, ...interface{})
Warn(...interface{})
Warnf(string, ...interface{})
Error(...interface{})
Errorf(string, ...interface{})
}
type logger struct{}
func (l logger) Trace(i ...interface{}) { fmt.Println(append([]interface{}{"[trace] "}, i...)...) }
func (l logger) Tracef(s string, i ...interface{}) { fmt.Printf("[trace] "+s+"\n", i...) }
func (l logger) Debug(i ...interface{}) { fmt.Println(append([]interface{}{"[debug] "}, i...)...) }
func (l logger) Debugf(s string, i ...interface{}) { fmt.Printf("[debug] "+s+"\n", i...) }
func (l logger) Info(i ...interface{}) { fmt.Println(append([]interface{}{"[info] "}, i...)...) }
func (l logger) Infof(s string, i ...interface{}) { fmt.Printf("[info] "+s+"\n", i...) }
func (l logger) Warn(i ...interface{}) { fmt.Println(append([]interface{}{"[warn] "}, i...)...) }
func (l logger) Warnf(s string, i ...interface{}) { fmt.Printf("[warn] "+s+"\n", i...) }
func (l logger) Error(i ...interface{}) { fmt.Println(append([]interface{}{"[error] "}, i...)...) }
func (l logger) Errorf(s string, i ...interface{}) { fmt.Printf("[error] "+s+"\n", i...) }
var defaultLogger = logger{}
| nlepage/cloudshell |
<|start_filename|>package.json<|end_filename|>
{
"name": "ffmpeg-progress-wrapper",
"version": "2.0.0",
"description": "A simple wrapper that helps with determinng the progress of the ffmpeg conversion ",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"watch": "tsc --watch",
"build": "tsc",
"prepublishOnly": "tsc"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/legraphista/ffmpeg-progress-wrapper.git"
},
"engines": {
"node": ">=8.9.0"
},
"keywords": [
"ffmpeg",
"progress",
"wrapper",
"status",
"cli",
"ffmpeg-cli"
],
"author": "<NAME> <<EMAIL>> (http://my.corneroftheinternet.rocks/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/legraphista/ffmpeg-progress-wrapper/issues"
},
"homepage": "https://github.com/legraphista/ffmpeg-progress-wrapper#readme",
"dependencies": {
"@types/node": "^11.11.5",
"@types/pidusage": "^2.0.1",
"pidusage": "^2.0.17"
},
"devDependencies": {
"husky": "^4.2.5",
"source-map-support": "^0.5.19",
"typescript": "^3.3.4000"
},
"husky": {
"hooks": {
"pre-commit": "tsc"
}
}
}
| legraphista/ffmpeg-progress-wrapper |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.