repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
yldio/copilot
packages/cp-frontend/test/unit/state/selectors.js
6968
import { getInstanceStatuses, getInstancesActive, getInstancesHealthy, getService, processServices, processServicesForTopology } from '@state/selectors'; describe('Redux selectors and Apollo helpers', () => { describe('getInstanceStatuses', () => { it('gathers instance statuses correctly', () => { const service = { instances: [ { status: 'RUNNING' }, { status: 'RUNNING' }, { status: 'READY' }, { status: 'RUNNING' }, { status: 'INCOMPLETE' }, { status: 'READY' }, { status: 'OFFLINE' }, { status: 'STOPPED' }, { status: 'STOPPED' }, { status: 'RUNNING' } ] }; const expectedResult = [ { status: 'RUNNING', count: 4 }, { status: 'READY', count: 2 }, { status: 'INCOMPLETE', count: 1 }, { status: 'OFFLINE', count: 1 }, { status: 'STOPPED', count: 2 } ]; const result = getInstanceStatuses(service); expect(result).toEqual(expectedResult); }); it('does not throw a hissy fit if there are no instances', () => { const service = { instances: [] }; const expectedResult = []; const result = getInstanceStatuses(service); expect(result).toEqual(expectedResult); }); }); describe('getInstancesActive', () => { it("returns true if all instances' status is active", () => { const statuses = [ { status: 'RUNNING' }, { status: 'READY' }, { status: 'ACTIVE' }, { status: 'RUNNING' } ]; const expectedResult = true; const result = getInstancesActive(statuses); expect(result).toEqual(expectedResult); }); it("returns false if no instances' status is active", () => { const statuses = [ { status: 'STOPPING' }, { status: 'FAILED' }, { status: 'UNKNOWN' }, { status: 'STOPPED' } ]; const expectedResult = false; const result = getInstancesActive(statuses); expect(result).toEqual(expectedResult); }); it("returns true if some instances' status is active", () => { const statuses = [ { status: 'STOPPING' }, { status: 'FAILED' }, { status: 'ACTIVE' }, { status: 'RUNNING' } ]; const expectedResult = true; const result = getInstancesActive(statuses); expect(result).toEqual(expectedResult); }); }); describe('getInstancesHealthy', () => { it('returns the number of healthy instances correctly', () => { const instances = [ { healthy: 'HEALTHY' }, { healthy: 'UNHEALTHY' }, { healthy: 'MAINTENANCE' }, { healthy: 'UNKNOWN' }, { healthy: 'UNAVAILABLE' }, { healthy: 'HEALTHY' } ]; const expectedResult = { total: 6, healthy: 2 }; const result = getInstancesHealthy(instances); expect(result).toEqual(expectedResult); }); }); describe('getService', () => { it('returns the service decorated with details for display correctly', () => { const result = getService(nginxService, 0); expect(result).toEqual(nginxExpectedResult); }); it('returns the consul service decorated with details for display correctly', () => { const result = getService(consulService, 1); expect(result).toEqual(consulExpectedResult); }); }); describe('processServices', () => { it('returns the services decorated with details for display correctly', () => { const services = [nginxService, consulService]; const expectedResult = [nginxExpectedResult, consulExpectedResult]; const result = processServices(services); expect(result).toEqual(expectedResult); }); it('removes deleted services', () => { const services = [ { status: 'DELETED' } ]; const expectedResult = []; const result = processServices(services); expect(result).toEqual(expectedResult); }); }); describe('processServicesForTopology', () => { it('returns the services decorated with details for display correctly', () => { const services = [ { ...nginxService, id: 'nginx-service-0', connections: ['consul-service-0', 'consul-service-1'] }, { ...nginxService, id: 'nginx-service-1' }, { ...consulService, id: 'consul-service-0', connections: ['consul-service-1'] }, { ...consulService, id: 'consul-service-1' } ]; const expectedResult = [ { ...nginxExpectedResult, id: 'nginx-service-0', connections: ['consul-service-0', 'consul-service-1'], connected: true, index: 0 }, { ...nginxExpectedResult, id: 'nginx-service-1', connected: false, index: 1 }, { ...consulExpectedResult, id: 'consul-service-0', connections: ['consul-service-1'], connected: true, index: 2 }, { ...consulExpectedResult, id: 'consul-service-1', connected: true, index: 3 } ]; const result = processServicesForTopology(services); expect(result).toEqual(expectedResult); }); }); }); const nginxService = { instances: [ { status: 'RUNNING', healthy: 'HEALTHY' }, { status: 'RUNNING', healthy: 'HEALTHY' }, { status: 'READY', healthy: 'HEALTHY' }, { status: 'RUNNING', healthy: 'UNHEALTHY' }, { status: 'INCOMPLETE', healthy: 'UNKNOWN' }, { status: 'READY', healthy: 'HEALTHY' }, { status: 'OFFLINE', healthy: 'UNAVAILABLE' }, { status: 'STOPPED', healthy: 'UNAVAILABLE' }, { status: 'STOPPED', healthy: 'UNAVAILABLE' }, { status: 'RUNNING', healthy: 'HEALTHY' } ], status: 'ACTIVE', slug: 'nginx' }; const nginxExpectedResult = { ...nginxService, instanceStatuses: [ { status: 'RUNNING', count: 4 }, { status: 'READY', count: 2 }, { status: 'INCOMPLETE', count: 1 }, { status: 'OFFLINE', count: 1 }, { status: 'STOPPED', count: 2 } ], instancesActive: true, instancesHealthy: { total: 10, healthy: 5 }, transitionalStatus: false, isConsul: false, index: 0 }; const consulService = { instances: [ { status: 'RUNNING', healthy: 'HEALTHY' }, { status: 'READY', healthy: 'HEALTHY' }, { status: 'PROVISIONING', healthy: 'UNKNOWN' } ], status: 'PROVISIONING', slug: 'consul' }; const consulExpectedResult = { ...consulService, instanceStatuses: [ { status: 'RUNNING', count: 1 }, { status: 'READY', count: 1 }, { status: 'PROVISIONING', count: 1 } ], instancesActive: true, instancesHealthy: { total: 3, healthy: 2 }, transitionalStatus: true, isConsul: true, index: 1 };
mpl-2.0
ewah/consul-template
dependency/file.go
2509
package dependency import ( "errors" "fmt" "io/ioutil" "log" "os" "sync" "time" ) // File represents a local file dependency. type File struct { sync.Mutex mutex sync.RWMutex rawKey string lastStat os.FileInfo stopped bool stopCh chan struct{} } // Fetch retrieves this dependency and returns the result or any errors that // occur in the process. func (d *File) Fetch(clients *ClientSet, opts *QueryOptions) (interface{}, *ResponseMetadata, error) { d.Lock() if d.stopped { defer d.Unlock() return nil, nil, ErrStopped } d.Unlock() var err error var newStat os.FileInfo var data []byte dataCh := make(chan struct{}) go func() { log.Printf("[DEBUG] (%s) querying file", d.Display()) newStat, err = d.watch() close(dataCh) }() select { case <-d.stopCh: return nil, nil, ErrStopped case <-dataCh: } if err != nil { return nil, nil, fmt.Errorf("file: error watching: %s", err) } d.mutex.Lock() defer d.mutex.Unlock() d.lastStat = newStat if data, err = ioutil.ReadFile(d.rawKey); err == nil { return respWithMetadata(string(data)) } return nil, nil, fmt.Errorf("file: error reading: %s", err) } // CanShare returns a boolean if this dependency is shareable. func (d *File) CanShare() bool { return false } // HashCode returns a unique identifier. func (d *File) HashCode() string { return fmt.Sprintf("StoreKeyPrefix|%s", d.rawKey) } // Display prints the human-friendly output. func (d *File) Display() string { return fmt.Sprintf(`"file(%s)"`, d.rawKey) } // Stop halts the dependency's fetch function. func (d *File) Stop() { d.Lock() defer d.Unlock() if !d.stopped { close(d.stopCh) d.stopped = true } } // watch watchers the file for changes func (d *File) watch() (os.FileInfo, error) { for { stat, err := os.Stat(d.rawKey) if err != nil { return nil, err } changed := func(d *File, stat os.FileInfo) bool { d.mutex.RLock() defer d.mutex.RUnlock() if d.lastStat == nil { return true } if d.lastStat.Size() != stat.Size() { return true } if d.lastStat.ModTime() != stat.ModTime() { return true } return false }(d, stat) if changed { return stat, nil } time.Sleep(3 * time.Second) } } // ParseFile creates a file dependency from the given path. func ParseFile(s string) (*File, error) { if len(s) == 0 { return nil, errors.New("cannot specify empty file dependency") } kd := &File{ rawKey: s, stopCh: make(chan struct{}), } return kd, nil }
mpl-2.0
pryorda/terraform
vendor/github.com/tombuildsstuff/giovanni/storage/2018-11-09/blob/blobs/snapshot.go
5939
package blobs import ( "context" "fmt" "net/http" "strings" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) type SnapshotInput struct { // The ID of the Lease // This must be specified if a Lease is present on the Blob, else a 403 is returned LeaseID *string // MetaData is a user-defined name-value pair associated with the blob. // If no name-value pairs are specified, the operation will copy the base blob metadata to the snapshot. // If one or more name-value pairs are specified, the snapshot is created with the specified metadata, // and metadata is not copied from the base blob. MetaData map[string]string // A DateTime value which will only snapshot the blob if it has been modified since the specified date/time // If the base blob has not been modified, the Blob service returns status code 412 (Precondition Failed). IfModifiedSince *string // A DateTime value which will only snapshot the blob if it has not been modified since the specified date/time // If the base blob has been modified, the Blob service returns status code 412 (Precondition Failed). IfUnmodifiedSince *string // An ETag value to snapshot the blob only if its ETag value matches the value specified. // If the values do not match, the Blob service returns status code 412 (Precondition Failed). IfMatch *string // An ETag value for this conditional header to snapshot the blob only if its ETag value // does not match the value specified. // If the values are identical, the Blob service returns status code 412 (Precondition Failed). IfNoneMatch *string } type SnapshotResult struct { autorest.Response // The ETag of the snapshot ETag string // A DateTime value that uniquely identifies the snapshot. // The value of this header indicates the snapshot version, // and may be used in subsequent requests to access the snapshot. SnapshotDateTime string } // Snapshot captures a Snapshot of a given Blob func (client Client) Snapshot(ctx context.Context, accountName, containerName, blobName string, input SnapshotInput) (result SnapshotResult, err error) { if accountName == "" { return result, validation.NewError("blobs.Client", "Snapshot", "`accountName` cannot be an empty string.") } if containerName == "" { return result, validation.NewError("blobs.Client", "Snapshot", "`containerName` cannot be an empty string.") } if strings.ToLower(containerName) != containerName { return result, validation.NewError("blobs.Client", "Snapshot", "`containerName` must be a lower-cased string.") } if blobName == "" { return result, validation.NewError("blobs.Client", "Snapshot", "`blobName` cannot be an empty string.") } if err := metadata.Validate(input.MetaData); err != nil { return result, validation.NewError("blobs.Client", "Snapshot", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) } req, err := client.SnapshotPreparer(ctx, accountName, containerName, blobName, input) if err != nil { err = autorest.NewErrorWithError(err, "blobs.Client", "Snapshot", nil, "Failure preparing request") return } resp, err := client.SnapshotSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "blobs.Client", "Snapshot", resp, "Failure sending request") return } result, err = client.SnapshotResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "blobs.Client", "Snapshot", resp, "Failure responding to request") return } return } // SnapshotPreparer prepares the Snapshot request. func (client Client) SnapshotPreparer(ctx context.Context, accountName, containerName, blobName string, input SnapshotInput) (*http.Request, error) { pathParameters := map[string]interface{}{ "containerName": autorest.Encode("path", containerName), "blobName": autorest.Encode("path", blobName), } queryParameters := map[string]interface{}{ "comp": autorest.Encode("query", "snapshot"), } headers := map[string]interface{}{ "x-ms-version": APIVersion, } if input.LeaseID != nil { headers["x-ms-lease-id"] = *input.LeaseID } if input.IfModifiedSince != nil { headers["If-Modified-Since"] = *input.IfModifiedSince } if input.IfUnmodifiedSince != nil { headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince } if input.IfMatch != nil { headers["If-Match"] = *input.IfMatch } if input.IfNoneMatch != nil { headers["If-None-Match"] = *input.IfNoneMatch } headers = metadata.SetIntoHeaders(headers, input.MetaData) preparer := autorest.CreatePreparer( autorest.AsPut(), autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), autorest.WithQueryParameters(queryParameters), autorest.WithHeaders(headers)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // SnapshotSender sends the Snapshot request. The method will close the // http.Response Body if it receives an error. func (client Client) SnapshotSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // SnapshotResponder handles the response to the Snapshot request. The method always // closes the http.Response Body. func (client Client) SnapshotResponder(resp *http.Response) (result SnapshotResult, err error) { if resp != nil && resp.Header != nil { result.ETag = resp.Header.Get("ETag") result.SnapshotDateTime = resp.Header.Get("x-ms-snapshot") } err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusCreated), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
mpl-2.0
Bhamni/openmrs-core
api/src/test/java/org/openmrs/cohort/CohortUtilTest.java
3251
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.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://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.cohort; import static org.junit.Assert.assertEquals; import java.util.Date; import java.util.List; import org.junit.Test; import org.openmrs.api.PatientSetService; import org.openmrs.api.context.Context; import org.openmrs.reporting.PatientCharacteristicFilter; import org.openmrs.reporting.PatientSearch; import org.openmrs.reporting.PatientSearchReportObject; import org.openmrs.reporting.ProgramStatePatientFilter; import org.openmrs.test.BaseContextSensitiveTest; import org.openmrs.test.Verifies; /** * Tests methods in the {@link CohortUtil} class. */ public class CohortUtilTest extends BaseContextSensitiveTest { /** * @see {@link CohortUtil#parse(String)} */ @Test @Verifies(value = "should parse specification with and in it", method = "parse(String)") public void parse_shouldParseSpecificationWithAndInIt() throws Exception { // sets up the database { // Create a search called "Male" PatientSearch ps = PatientSearch.createFilterSearch(PatientCharacteristicFilter.class); ps.addArgument("gender", "m", String.class); Context.getReportObjectService().saveReportObject(new PatientSearchReportObject("Male", ps)); } { // Create a search called "EnrolledOnDate" with one parameter called untilDate PatientSearch ps = PatientSearch.createFilterSearch(ProgramStatePatientFilter.class); //ps.addArgument("program", Context.getProgramWorkflowService().getProgram("HIV PROGRAM").getProgramId().toString(), Integer.class); ps.addArgument("untilDate", "${date}", Date.class); Context.getReportObjectService().saveReportObject(new PatientSearchReportObject("EnrolledOnDate", ps)); } // TODO this is the actual test. Move the above logic into a dbunit xml file or use the standard xml run by BaseContextSensitiveTest PatientSearch ps = (PatientSearch) CohortUtil.parse("[Male] and [EnrolledOnDate|untilDate=${report.startDate}]"); List<Object> list = ps.getParsedComposition(); { PatientSearch test = (PatientSearch) list.get(0); assertEquals(test.getFilterClass(), PatientCharacteristicFilter.class); assertEquals(test.getArguments().iterator().next().getValue(), "m"); assertEquals(test.getArguments().size(), 1); } assertEquals(list.get(1), PatientSetService.BooleanOperator.AND); { PatientSearch test = (PatientSearch) list.get(2); assertEquals(test.getFilterClass(), ProgramStatePatientFilter.class); assertEquals(test.getArguments().iterator().next().getValue(), "${date}"); assertEquals(test.getArgumentValue("untilDate"), "${report.startDate}"); assertEquals(test.getArguments().size(), 1); } } }
mpl-2.0
ricardclau/packer
vendor/github.com/yandex-cloud/go-sdk/gen/mdb/mongodb/cluster.go
17021
// Code generated by sdkgen. DO NOT EDIT. //nolint package mongodb import ( "context" "google.golang.org/grpc" mongodb "github.com/yandex-cloud/go-genproto/yandex/cloud/mdb/mongodb/v1" "github.com/yandex-cloud/go-genproto/yandex/cloud/operation" ) //revive:disable // ClusterServiceClient is a mongodb.ClusterServiceClient with // lazy GRPC connection initialization. type ClusterServiceClient struct { getConn func(ctx context.Context) (*grpc.ClientConn, error) } // AddHosts implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) AddHosts(ctx context.Context, in *mongodb.AddClusterHostsRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).AddHosts(ctx, in, opts...) } // AddShard implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) AddShard(ctx context.Context, in *mongodb.AddClusterShardRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).AddShard(ctx, in, opts...) } // Backup implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) Backup(ctx context.Context, in *mongodb.BackupClusterRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).Backup(ctx, in, opts...) } // Create implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) Create(ctx context.Context, in *mongodb.CreateClusterRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).Create(ctx, in, opts...) } // Delete implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) Delete(ctx context.Context, in *mongodb.DeleteClusterRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).Delete(ctx, in, opts...) } // DeleteHosts implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) DeleteHosts(ctx context.Context, in *mongodb.DeleteClusterHostsRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).DeleteHosts(ctx, in, opts...) } // DeleteShard implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) DeleteShard(ctx context.Context, in *mongodb.DeleteClusterShardRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).DeleteShard(ctx, in, opts...) } // EnableSharding implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) EnableSharding(ctx context.Context, in *mongodb.EnableClusterShardingRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).EnableSharding(ctx, in, opts...) } // Get implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) Get(ctx context.Context, in *mongodb.GetClusterRequest, opts ...grpc.CallOption) (*mongodb.Cluster, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).Get(ctx, in, opts...) } // GetShard implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) GetShard(ctx context.Context, in *mongodb.GetClusterShardRequest, opts ...grpc.CallOption) (*mongodb.Shard, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).GetShard(ctx, in, opts...) } // List implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) List(ctx context.Context, in *mongodb.ListClustersRequest, opts ...grpc.CallOption) (*mongodb.ListClustersResponse, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).List(ctx, in, opts...) } type ClusterIterator struct { ctx context.Context opts []grpc.CallOption err error started bool client *ClusterServiceClient request *mongodb.ListClustersRequest items []*mongodb.Cluster } func (c *ClusterServiceClient) ClusterIterator(ctx context.Context, folderId string, opts ...grpc.CallOption) *ClusterIterator { return &ClusterIterator{ ctx: ctx, opts: opts, client: c, request: &mongodb.ListClustersRequest{ FolderId: folderId, PageSize: 1000, }, } } func (it *ClusterIterator) Next() bool { if it.err != nil { return false } if len(it.items) > 1 { it.items[0] = nil it.items = it.items[1:] return true } it.items = nil // consume last item, if any if it.started && it.request.PageToken == "" { return false } it.started = true response, err := it.client.List(it.ctx, it.request, it.opts...) it.err = err if err != nil { return false } it.items = response.Clusters it.request.PageToken = response.NextPageToken return len(it.items) > 0 } func (it *ClusterIterator) Value() *mongodb.Cluster { if len(it.items) == 0 { panic("calling Value on empty iterator") } return it.items[0] } func (it *ClusterIterator) Error() error { return it.err } // ListBackups implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) ListBackups(ctx context.Context, in *mongodb.ListClusterBackupsRequest, opts ...grpc.CallOption) (*mongodb.ListClusterBackupsResponse, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).ListBackups(ctx, in, opts...) } type ClusterBackupsIterator struct { ctx context.Context opts []grpc.CallOption err error started bool client *ClusterServiceClient request *mongodb.ListClusterBackupsRequest items []*mongodb.Backup } func (c *ClusterServiceClient) ClusterBackupsIterator(ctx context.Context, clusterId string, opts ...grpc.CallOption) *ClusterBackupsIterator { return &ClusterBackupsIterator{ ctx: ctx, opts: opts, client: c, request: &mongodb.ListClusterBackupsRequest{ ClusterId: clusterId, PageSize: 1000, }, } } func (it *ClusterBackupsIterator) Next() bool { if it.err != nil { return false } if len(it.items) > 1 { it.items[0] = nil it.items = it.items[1:] return true } it.items = nil // consume last item, if any if it.started && it.request.PageToken == "" { return false } it.started = true response, err := it.client.ListBackups(it.ctx, it.request, it.opts...) it.err = err if err != nil { return false } it.items = response.Backups it.request.PageToken = response.NextPageToken return len(it.items) > 0 } func (it *ClusterBackupsIterator) Value() *mongodb.Backup { if len(it.items) == 0 { panic("calling Value on empty iterator") } return it.items[0] } func (it *ClusterBackupsIterator) Error() error { return it.err } // ListHosts implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) ListHosts(ctx context.Context, in *mongodb.ListClusterHostsRequest, opts ...grpc.CallOption) (*mongodb.ListClusterHostsResponse, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).ListHosts(ctx, in, opts...) } type ClusterHostsIterator struct { ctx context.Context opts []grpc.CallOption err error started bool client *ClusterServiceClient request *mongodb.ListClusterHostsRequest items []*mongodb.Host } func (c *ClusterServiceClient) ClusterHostsIterator(ctx context.Context, clusterId string, opts ...grpc.CallOption) *ClusterHostsIterator { return &ClusterHostsIterator{ ctx: ctx, opts: opts, client: c, request: &mongodb.ListClusterHostsRequest{ ClusterId: clusterId, PageSize: 1000, }, } } func (it *ClusterHostsIterator) Next() bool { if it.err != nil { return false } if len(it.items) > 1 { it.items[0] = nil it.items = it.items[1:] return true } it.items = nil // consume last item, if any if it.started && it.request.PageToken == "" { return false } it.started = true response, err := it.client.ListHosts(it.ctx, it.request, it.opts...) it.err = err if err != nil { return false } it.items = response.Hosts it.request.PageToken = response.NextPageToken return len(it.items) > 0 } func (it *ClusterHostsIterator) Value() *mongodb.Host { if len(it.items) == 0 { panic("calling Value on empty iterator") } return it.items[0] } func (it *ClusterHostsIterator) Error() error { return it.err } // ListLogs implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) ListLogs(ctx context.Context, in *mongodb.ListClusterLogsRequest, opts ...grpc.CallOption) (*mongodb.ListClusterLogsResponse, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).ListLogs(ctx, in, opts...) } type ClusterLogsIterator struct { ctx context.Context opts []grpc.CallOption err error started bool client *ClusterServiceClient request *mongodb.ListClusterLogsRequest items []*mongodb.LogRecord } func (c *ClusterServiceClient) ClusterLogsIterator(ctx context.Context, clusterId string, opts ...grpc.CallOption) *ClusterLogsIterator { return &ClusterLogsIterator{ ctx: ctx, opts: opts, client: c, request: &mongodb.ListClusterLogsRequest{ ClusterId: clusterId, PageSize: 1000, }, } } func (it *ClusterLogsIterator) Next() bool { if it.err != nil { return false } if len(it.items) > 1 { it.items[0] = nil it.items = it.items[1:] return true } it.items = nil // consume last item, if any if it.started && it.request.PageToken == "" { return false } it.started = true response, err := it.client.ListLogs(it.ctx, it.request, it.opts...) it.err = err if err != nil { return false } it.items = response.Logs it.request.PageToken = response.NextPageToken return len(it.items) > 0 } func (it *ClusterLogsIterator) Value() *mongodb.LogRecord { if len(it.items) == 0 { panic("calling Value on empty iterator") } return it.items[0] } func (it *ClusterLogsIterator) Error() error { return it.err } // ListOperations implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) ListOperations(ctx context.Context, in *mongodb.ListClusterOperationsRequest, opts ...grpc.CallOption) (*mongodb.ListClusterOperationsResponse, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).ListOperations(ctx, in, opts...) } type ClusterOperationsIterator struct { ctx context.Context opts []grpc.CallOption err error started bool client *ClusterServiceClient request *mongodb.ListClusterOperationsRequest items []*operation.Operation } func (c *ClusterServiceClient) ClusterOperationsIterator(ctx context.Context, clusterId string, opts ...grpc.CallOption) *ClusterOperationsIterator { return &ClusterOperationsIterator{ ctx: ctx, opts: opts, client: c, request: &mongodb.ListClusterOperationsRequest{ ClusterId: clusterId, PageSize: 1000, }, } } func (it *ClusterOperationsIterator) Next() bool { if it.err != nil { return false } if len(it.items) > 1 { it.items[0] = nil it.items = it.items[1:] return true } it.items = nil // consume last item, if any if it.started && it.request.PageToken == "" { return false } it.started = true response, err := it.client.ListOperations(it.ctx, it.request, it.opts...) it.err = err if err != nil { return false } it.items = response.Operations it.request.PageToken = response.NextPageToken return len(it.items) > 0 } func (it *ClusterOperationsIterator) Value() *operation.Operation { if len(it.items) == 0 { panic("calling Value on empty iterator") } return it.items[0] } func (it *ClusterOperationsIterator) Error() error { return it.err } // ListShards implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) ListShards(ctx context.Context, in *mongodb.ListClusterShardsRequest, opts ...grpc.CallOption) (*mongodb.ListClusterShardsResponse, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).ListShards(ctx, in, opts...) } type ClusterShardsIterator struct { ctx context.Context opts []grpc.CallOption err error started bool client *ClusterServiceClient request *mongodb.ListClusterShardsRequest items []*mongodb.Shard } func (c *ClusterServiceClient) ClusterShardsIterator(ctx context.Context, clusterId string, opts ...grpc.CallOption) *ClusterShardsIterator { return &ClusterShardsIterator{ ctx: ctx, opts: opts, client: c, request: &mongodb.ListClusterShardsRequest{ ClusterId: clusterId, PageSize: 1000, }, } } func (it *ClusterShardsIterator) Next() bool { if it.err != nil { return false } if len(it.items) > 1 { it.items[0] = nil it.items = it.items[1:] return true } it.items = nil // consume last item, if any if it.started && it.request.PageToken == "" { return false } it.started = true response, err := it.client.ListShards(it.ctx, it.request, it.opts...) it.err = err if err != nil { return false } it.items = response.Shards it.request.PageToken = response.NextPageToken return len(it.items) > 0 } func (it *ClusterShardsIterator) Value() *mongodb.Shard { if len(it.items) == 0 { panic("calling Value on empty iterator") } return it.items[0] } func (it *ClusterShardsIterator) Error() error { return it.err } // Move implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) Move(ctx context.Context, in *mongodb.MoveClusterRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).Move(ctx, in, opts...) } // RescheduleMaintenance implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) RescheduleMaintenance(ctx context.Context, in *mongodb.RescheduleMaintenanceRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).RescheduleMaintenance(ctx, in, opts...) } // ResetupHosts implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) ResetupHosts(ctx context.Context, in *mongodb.ResetupHostsRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).ResetupHosts(ctx, in, opts...) } // RestartHosts implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) RestartHosts(ctx context.Context, in *mongodb.RestartHostsRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).RestartHosts(ctx, in, opts...) } // Restore implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) Restore(ctx context.Context, in *mongodb.RestoreClusterRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).Restore(ctx, in, opts...) } // Start implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) Start(ctx context.Context, in *mongodb.StartClusterRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).Start(ctx, in, opts...) } // Stop implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) Stop(ctx context.Context, in *mongodb.StopClusterRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).Stop(ctx, in, opts...) } // StreamLogs implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) StreamLogs(ctx context.Context, in *mongodb.StreamClusterLogsRequest, opts ...grpc.CallOption) (mongodb.ClusterService_StreamLogsClient, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).StreamLogs(ctx, in, opts...) } // Update implements mongodb.ClusterServiceClient func (c *ClusterServiceClient) Update(ctx context.Context, in *mongodb.UpdateClusterRequest, opts ...grpc.CallOption) (*operation.Operation, error) { conn, err := c.getConn(ctx) if err != nil { return nil, err } return mongodb.NewClusterServiceClient(conn).Update(ctx, in, opts...) }
mpl-2.0
MozillaOnline/pc-sync-gaia-app
pcsyncclient/js/fromgaia/gallery_config.js
873
// // This file is automatically generated: DO NOT EDIT. // To change these values, create a camera.json file in the // distribution directory with content like this: // // { // "maxImagePixelSize": 6000000, // "maxSnapshotPixelSize": 4000000 } // } // // Optionally, you can also define variables to specify the // minimum EXIF preview size that will be displayed as a // full-screen preview by adding a property like this: // // "requiredEXIFPreviewSize": { "width": 640, "height": 480} // // If you do not specify this property then EXIF previews will only // be used if they are big enough to fill the screen in either // width or height in both landscape and portrait mode. // var CONFIG_MAX_IMAGE_PIXEL_SIZE = 5242880; var CONFIG_MAX_SNAPSHOT_PIXEL_SIZE = 5242880; var CONFIG_REQUIRED_EXIF_PREVIEW_WIDTH = 0; var CONFIG_REQUIRED_EXIF_PREVIEW_HEIGHT = 0;
mpl-2.0
powsybl/powsybl-core
commons/src/test/java/com/powsybl/commons/plugins/PluginInfoTest.java
2340
/** * Copyright (c) 2018, RTE (http://www.rte-france.com) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.powsybl.commons.plugins; import com.powsybl.commons.util.ServiceLoaderCache; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.junit.Assert.*; /** * @author Christian Biasuzzi <[email protected]> */ public class PluginInfoTest { private PluginInfo<A> pluginInfo; @Before public void setUp() { pluginInfo = Plugins.getPluginInfoByName(PluginInfoA.PLUGIN_NAME); } @Test public void testPlugins() { assertEquals(1, Plugins.getPluginInfos().stream().map(PluginInfo::getPluginName).filter(PluginInfoA.PLUGIN_NAME::equals).count()); } @Test public void testPluginExist() { assertNotNull(pluginInfo); assertNotNull(pluginInfo.toString()); } @Test public void testPluginDetails() { new ServiceLoaderCache<>(A.class).getServices().forEach(a -> assertNotNull(pluginInfo.getId(a)) ); } @Test public void testPluginNotExist() { assertNull(Plugins.getPluginInfoByName("DOES_NOT_EXIST")); } @Test public void testGetPluginImplementationsIds() { List<String> testPluginsIds = Arrays.asList("A1", "A2"); Collection<String> pluginImplementationsIds = Plugins.getPluginImplementationsIds(pluginInfo); assertEquals(testPluginsIds.size(), pluginImplementationsIds.size()); assertTrue(pluginImplementationsIds.containsAll(testPluginsIds)); } @Test public void testGetPluginInfoId() { A1 a1 = new A1(); A2 a2 = new A2(); assertEquals("A1", pluginInfo.getId(a1)); assertEquals("A2", pluginInfo.getId(a2)); } @Test public void testGetPluginInfoIdDefault() { PluginInfo<B> pluginInfoB = Plugins.getPluginInfoByName(PluginInfoB.PLUGIN_NAME); B b1 = () -> "B1"; String bPluginID = pluginInfoB.getId(b1); assertNotEquals("B1", bPluginID); assertEquals(b1.getClass().getName(), bPluginID); } }
mpl-2.0
oracle/terraform-provider-baremetal
vendor/github.com/oracle/oci-go-sdk/v46/databasemigration/job_output_summary.go
817
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Database Migration API // // Use the Oracle Cloud Infrastructure Database Migration APIs to perform database migration operations. // package databasemigration import ( "github.com/oracle/oci-go-sdk/v46/common" ) // JobOutputSummary Job output summary line. type JobOutputSummary struct { // Job output line. Message *string `mandatory:"true" json:"message"` } func (m JobOutputSummary) String() string { return common.PointerString(m) }
mpl-2.0
mozilla/advocacy.mozilla.org
src/components/open-web-fellows/apply.js
853
var React = require(`react`); var HeroUnit = require(`../hero-unit.js`); var Router = require(`react-router`); var Link = Router.Link; module.exports = React.createClass({ PropTypes: { headline: React.PropTypes.string, description: React.PropTypes.string, cta: React.PropTypes.shape({ label: React.PropTypes.string, link: React.PropTypes.string }) }, render: function() { let cta = ( <div> <a href={this.props.cta.link} className="button">{this.props.cta.label}</a> </div> ) return ( <div className="apply"> <HeroUnit className="apply-hero-unit" image="/assets/apply.jpg"> <h2>{this.props.title}</h2> <div className="horizontal-rule"></div> <h4>{this.props.description}</h4> {cta} </HeroUnit> </div> ); } });
mpl-2.0
moovweb/tritium
parser/parser_test.go
158
package parser import ( "os" . "testing" ) func TestParseRun(t *T) { wd, _ := os.Getwd() ParseFile(wd, "scripts", "two.ts", false, make([]string, 0)) }
mpl-2.0
Vild/TrigonOverthrow
src/world/system/bossaisystem.hpp
559
#pragma once #include "system.hpp" #include "../component/bossaicomponent.hpp" class BossAISystem : public System { public: BossAISystem(); virtual ~BossAISystem(); void update(World& world, float delta) final; void registerImGui() final; inline std::string name() final { return "BossAISystem"; } void setCentre(glm::vec3 centre) { _centre = centre; } private: bool _walkToMiddle; void _doPhase(Entity* boss, float delta); void _moveMiddle(Entity* boss); glm::vec3 _calculateForceDirection(float time); glm::vec3 _centre; float _walkDistance; };
mpl-2.0
graimundo/basic-plugin
src/pt/webdetails/basic/plugin/BasicPluginContentGenerator.java
3862
/*! * Copyright 2002 - 2015 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package pt.webdetails.basic.plugin; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.platform.api.engine.IParameterProvider; import org.pentaho.platform.api.repository2.unified.IUnifiedRepository; import org.pentaho.platform.api.repository2.unified.RepositoryFile; import org.pentaho.platform.api.repository2.unified.data.simple.SimpleRepositoryFileData; import org.pentaho.platform.engine.services.solution.BaseContentGenerator; import org.pentaho.platform.util.messages.LocaleHelper; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLDecoder; public class BasicPluginContentGenerator extends BaseContentGenerator { protected static Log logger = LogFactory.getLog( BasicPluginContentGenerator.class ); private static final String PATH_PARAMETER_ID = "path"; private IUnifiedRepository repository; public BasicPluginContentGenerator( IUnifiedRepository repository ){ setRepository( repository ); } @Override public Log getLogger() { return logger; } @Override public void createContent() throws Exception { info( "createContent()" ); IParameterProvider pathParams = parameterProviders.get( PATH_PARAMETER_ID ); RepositoryFile file; String urlEncodedFilePath; if( pathParams != null && !StringUtils.isEmpty( ( urlEncodedFilePath = pathParams.getStringParameter( Constants.JaxRs.PATH, null ) ) ) ) { String filePath = URLDecoder.decode( urlEncodedFilePath, LocaleHelper.UTF_8 ); getResponse().setContentType( Constants.MIME_TEXT_PLAIN ); getResponse().setHeader( "Cache-Control", "no-cache" ); if ( ( file = getRepository().getFile( filePath ) ) == null ) { throw new WebApplicationException( Response.Status.NOT_FOUND ); } InputStream content = null; try { SimpleRepositoryFileData data = getRepository().getDataForRead( file.getId(), SimpleRepositoryFileData.class ); writeOutAndFlush( getResponse().getOutputStream(), data.getInputStream() ); } finally { IOUtils.closeQuietly( content ); } } } public IUnifiedRepository getRepository() { return repository; } public void setRepository( IUnifiedRepository repository ) { this.repository = repository; } protected HttpServletResponse getResponse(){ return ( HttpServletResponse ) parameterProviders.get( PATH_PARAMETER_ID ).getParameter( "httpresponse" ); } private void writeOutAndFlush( OutputStream out, InputStream data ) { writeOut( out, data ); flush( out ); } private void writeOut( OutputStream out, InputStream data ){ try { IOUtils.copy( data, out ); } catch (IOException ex){ getLogger().error( ex ); } } private void flush( OutputStream out ) { try { if ( out != null ) { out.flush(); } } catch ( IOException ex ) { getLogger().error( ex ); } } }
mpl-2.0
Topl/Project-Bifrost
src/main/scala/bifrost/transaction/bifrostTransaction/ProgramCreation.scala
8850
package bifrost.transaction.bifrostTransaction import java.util.UUID import bifrost.program.ExecutionBuilder import bifrost.crypto.hash.FastCryptographicHash import BifrostTransaction.Nonce import bifrost.transaction.account.PublicKeyNoncedBox import bifrost.transaction.box.proposition.{ProofOfKnowledgeProposition, PublicKey25519Proposition} import bifrost.transaction.box.{BifrostBox, BoxUnlocker, CodeBox, ExecutionBox, PolyBox, StateBox} import bifrost.transaction.proof.Signature25519 import bifrost.transaction.serialization.ProgramCreationCompanion import bifrost.transaction.state.PrivateKey25519 import bifrost.transaction.serialization.ExecutionBuilderCompanion import com.google.common.primitives.{Bytes, Ints, Longs} import io.circe.syntax._ import io.circe.{Decoder, HCursor, Json} import scorex.crypto.encode.Base58 import scala.util.Try /** * * @param executionBuilder the ExecutionBuilder object containing the terms for the proposed program * @param readOnlyStateBoxes a list of StateBoxes to be used in evaluating the program, but never mutated * beyond the context of the evaluation * @param preInvestmentBoxes a list of box nonces corresponding to the PolyBoxes to be used to fund the investment * @param owner the public key used to sign and create newboxes * @param signatures a mapping specifying the signatures by each public key for this transaction * @param preFeeBoxes a mapping specifying box nonces and amounts corresponding to the PolyBoxes to be used to * pay fees for each party contributing fees * @param fees a mapping specifying the amount each party is contributing to the fees * @param timestamp the timestamp of this transaction */ case class ProgramCreation(executionBuilder: ExecutionBuilder, readOnlyStateBoxes: Seq[UUID], preInvestmentBoxes: IndexedSeq[(Nonce, Long)], owner: PublicKey25519Proposition, signatures: Map[PublicKey25519Proposition, Signature25519], preFeeBoxes: Map[PublicKey25519Proposition, IndexedSeq[(Nonce, Long)]], fees: Map[PublicKey25519Proposition, Long], timestamp: Long, data: String) extends ProgramTransaction { override type M = ProgramCreation // lazy val proposition = MofNProposition(1, parties.map(_._1.pubKeyBytes).toSet) lazy val investmentBoxIds: IndexedSeq[Array[Byte]] = preInvestmentBoxes.map(n => { PublicKeyNoncedBox.idFromBox(owner, n._1)}) lazy val boxIdsToOpen: IndexedSeq[Array[Byte]] = investmentBoxIds ++ feeBoxIdKeyPairs.map(_._1) override lazy val unlockers: Traversable[BoxUnlocker[ProofOfKnowledgeProposition[PrivateKey25519]]] = investmentBoxIds .map(id => new BoxUnlocker[PublicKey25519Proposition] { override val closedBoxId: Array[Byte] = id override val boxKey: Signature25519 = signatures(owner) } ) ++ feeBoxUnlockers lazy val hashNoNonces = FastCryptographicHash( ExecutionBuilderCompanion.toBytes(executionBuilder) ++ owner.pubKeyBytes ++ unlockers.map(_.closedBoxId).foldLeft(Array[Byte]())(_ ++ _) ++ //boxIdsToOpen.foldLeft(Array[Byte]())(_ ++ _) ++ fees.foldLeft(Array[Byte]())((a, b) => a ++ b._1.pubKeyBytes ++ Longs.toByteArray(b._2))) lazy val newStateBoxes: Traversable[StateBox] = { val stateNonce = ProgramTransaction.nonceFromDigest( FastCryptographicHash("stateBox".getBytes ++ executionBuilder.core.variables.noSpaces.getBytes ++ hashNoNonces ++ Ints.toByteArray(0)) ) val stateBox = StateBox(owner, stateNonce, UUID.nameUUIDFromBytes(StateBox.idFromBox(owner, stateNonce)), executionBuilder.core.variables) IndexedSeq(stateBox) } override lazy val newBoxes: Traversable[BifrostBox] = { val digest = FastCryptographicHash(owner.pubKeyBytes ++ hashNoNonces) val nonce = ProgramTransaction.nonceFromDigest(digest) val boxValue: Json = Map( "owner" -> Base58.encode(owner.pubKeyBytes).asJson, "executionBuilder" -> executionBuilder.json, "lastUpdated" -> timestamp.asJson ).asJson val availableBoxes: Set[(Nonce, Long)] = (preFeeBoxes(owner) ++ preInvestmentBoxes).toSet val canSend = availableBoxes.map(_._2).sum val leftOver: Long = canSend - fees(owner) val investorNonce = ProgramTransaction.nonceFromDigest( FastCryptographicHash("ProgramCreation".getBytes ++ owner.pubKeyBytes ++ hashNoNonces ++ Ints.toByteArray(0)) ) val codeNonce = ProgramTransaction.nonceFromDigest( FastCryptographicHash("codeBox".getBytes ++ executionBuilder.core.code.values.foldLeft(Array[Byte]())((a,b) => a ++ b.getBytes()) ++ hashNoNonces ++ Ints.toByteArray(0)) ) val execNonce = ProgramTransaction.nonceFromDigest( FastCryptographicHash("executionBuilder".getBytes ++ hashNoNonces ++ Ints.toByteArray(0)) ) val stateNonce = ProgramTransaction.nonceFromDigest( FastCryptographicHash("stateBox".getBytes ++ executionBuilder.core.variables.noSpaces.getBytes ++ hashNoNonces ++ Ints.toByteArray(0)) ) val stateBox = StateBox(owner, stateNonce, UUID.nameUUIDFromBytes(StateBox.idFromBox(owner, stateNonce)),executionBuilder.core.variables) val codeBox = CodeBox(owner, codeNonce, UUID.nameUUIDFromBytes(CodeBox.idFromBox(owner, codeNonce)), executionBuilder.core.code.values.toSeq, executionBuilder.core.interface) val stateUUIDs: Seq[UUID] = Seq(UUID.nameUUIDFromBytes(stateBox.id)) ++ readOnlyStateBoxes val executionBox = ExecutionBox(owner, execNonce, UUID.nameUUIDFromBytes(ExecutionBox.idFromBox(owner, execNonce)), stateUUIDs, Seq(codeBox.id)) val investorDeductedBoxes: PolyBox = PolyBox(owner, investorNonce, leftOver) IndexedSeq(executionBox, stateBox, codeBox) :+ investorDeductedBoxes // nonInvestorDeductedBoxes } lazy val json: Json = (commonJson.asObject.get.toMap ++ Map( "preInvestmentBoxes" -> preInvestmentBoxes.map(_.asJson).asJson, "executionBuilder" -> executionBuilder.json, "newBoxes" -> newBoxes.map(_.json).asJson, "data" -> data.asJson )).asJson override lazy val serializer = ProgramCreationCompanion // println("BifrostTransaction") //println(ExecutionBuilderCompanion.toBytes(executionBuilder).mkString("")) //println(parties.toSeq.sortBy(_._1.pubKeyBytes.toString).foldLeft(Array[Byte]())((a, b) => a ++ b._1.pubKeyBytes).mkString("")) // println(investmentBoxIds.foldLeft(Array[Byte]())(_ ++ _).mkString("")) // println(preInvestmentBoxes) //println(feeBoxIdKeyPairs.map(_._1).foldLeft(Array[Byte]())(_ ++ _).mkString("")) override lazy val messageToSign: Array[Byte] = Bytes.concat( ExecutionBuilderCompanion.toBytes(executionBuilder), owner.pubKeyBytes, unlockers.toArray.flatMap(_.closedBoxId), data.getBytes //boxIdsToOpen.foldLeft(Array[Byte]())(_ ++ _) ) override def toString: String = s"ProgramCreation(${json.noSpaces})" } object ProgramCreation { def validate(tx: ProgramCreation): Try[Unit] = Try { val outcome = ExecutionBuilder.validate(tx.executionBuilder) require(outcome.isSuccess) require(tx.signatures(tx.owner).isValid(tx.owner, tx.messageToSign), "Not all signatures were valid") }.flatMap(_ => ProgramTransaction.commonValidation(tx)) implicit val decodeProgramCreation: Decoder[ProgramCreation] = (c: HCursor) => for { executionBuilder <- c.downField("executionBuilder").as[ExecutionBuilder] readOnlyStateBoxes <- c.downField("readOnlyStateBoxes").as[Seq[UUID]] preInvestmentBoxes <- c.downField("preInvestmentBoxes").as[IndexedSeq[(Nonce, Long)]] rawOwner <- c.downField("owner").as[String] rawSignatures <- c.downField("signatures").as[Map[String, String]] rawPreFeeBoxes <- c.downField("preFeeBoxes").as[Map[String, IndexedSeq[(Long, Long)]]] rawFees <- c.downField("fees").as[Map[String, Long]] timestamp <- c.downField("timestamp").as[Long] data <- c.downField("data").as[String] } yield { val commonArgs = ProgramTransaction.commonDecode(rawOwner, rawSignatures, rawPreFeeBoxes, rawFees) ProgramCreation(executionBuilder, readOnlyStateBoxes, preInvestmentBoxes, commonArgs._1, commonArgs._2, commonArgs._3, commonArgs._4, timestamp, data) } }
mpl-2.0
peyuco08/gulp-easy
build/assets/js/carrousel.js
2318
$(function(){ $('#slides').slides({ preload: true, generateNextPrev: true }); }); $(document).ready(function() { /* pag 1 */ $("#paginador-carrusel .pagUno .botones .next").click(function(e) { e.preventDefault() $("#paginador-carrusel .cont-carrousel").animate({left: "-670px"}, "fast"); $("#paginador-carrusel .pasos-paginas .on").animate({width: "70px"}, "slow"); }); /* fin pag 1 */ /* pag 2 */ $("#paginador-carrusel .pagDos .botones .next").click(function(e) { e.preventDefault() $("#paginador-carrusel .cont-carrousel").animate({left: "-1340px"}, "fast"); $("#paginador-carrusel .pasos-paginas .on").animate({width: "140px"}, "slow"); }); $("#paginador-carrusel .pagDos .botones .prev").click(function(e) { e.preventDefault() $("#paginador-carrusel .cont-carrousel").animate({left: "0"}, "fast"); $("#paginador-carrusel .pasos-paginas .on").animate({width: "0"}, "slow"); }); /* fin pag 2 */ /* pag 3 */ $("#paginador-carrusel .pagTres .botones .next").click(function(e) { e.preventDefault() $("#paginador-carrusel .cont-carrousel").animate({left: "-2010px"}, "fast"); $("#paginador-carrusel .pasos-paginas .on").animate({width: "210px"}, "slow"); }); $("#paginador-carrusel .pagTres .botones .prev").click(function(e) { e.preventDefault() $("#paginador-carrusel .cont-carrousel").animate({left: "-670px"}, "fast"); $("#paginador-carrusel .pasos-paginas .on").animate({width: "70px"}, "slow"); }); /* fin pag 3 */ /* pag 4 */ $("#paginador-carrusel .pagCuatro .botones .next").click(function(e) { e.preventDefault() $("#paginador-carrusel .cont-carrousel").animate({left: "-2680px"}, "fast"); $("#paginador-carrusel .pasos-paginas .on").animate({width: "300px"}, "slow"); }); $("#paginador-carrusel .pagCuatro .botones .prev").click(function(e) { e.preventDefault() $("#paginador-carrusel .cont-carrousel").animate({left: "-1340px"}, "fast"); $("#paginador-carrusel .pasos-paginas .on").animate({width: "140px"}, "slow"); }); /* fin pag 4 */ /* pag 5 */ $("#paginador-carrusel .pagCinco .botones .prev").click(function(e) { e.preventDefault() $("#paginador-carrusel .cont-carrousel").animate({left: "-2010px"}, "fast"); $("#paginador-carrusel .pasos-paginas .on").animate({width: "210px"}, "slow"); }); });
mpl-2.0
mozilla/kanbanzilla
test/spec/controllers/header.js
518
'use strict'; describe('Controller: HeaderCtrl', function () { // load the controller's module beforeEach(module('kanbanzillaApp')); var HeaderCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); HeaderCtrl = $controller('HeaderCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
mpl-2.0
hooklift/gowsdl
soap/soap_test.go
25327
package soap import ( "bytes" "context" "encoding/xml" "fmt" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/stretchr/testify/assert" ) type Ping struct { XMLName xml.Name `xml:"http://example.com/service.xsd Ping"` Request *PingRequest `xml:"request,omitempty"` } type PingRequest struct { // XMLName xml.Name `xml:"http://example.com/service.xsd PingRequest"` Message string `xml:"Message,omitempty"` Attachment *Binary `xml:"Attachment,omitempty"` } type PingResponse struct { XMLName xml.Name `xml:"http://example.com/service.xsd PingResponse"` PingResult *PingReply `xml:"PingResult,omitempty"` } type PingReply struct { // XMLName xml.Name `xml:"http://example.com/service.xsd PingReply"` Message string `xml:"Message,omitempty"` Attachment []byte `xml:"Attachment,omitempty"` } type AttachmentRequest struct { XMLName xml.Name `xml:"http://example.com/service.xsd attachmentRequest"` Name string `xml:"name,omitempty"` ContentID string `xml:"contentID,omitempty"` } func TestClient_Call(t *testing.T) { var pingRequest = new(Ping) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { xml.NewDecoder(r.Body).Decode(pingRequest) rsp := `<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <PingResponse xmlns="http://example.com/service.xsd"> <PingResult> <Message>Pong hi</Message> </PingResult> </PingResponse> </soap:Body> </soap:Envelope>` w.Write([]byte(rsp)) })) defer ts.Close() client := NewClient(ts.URL) req := &Ping{Request: &PingRequest{Message: "Hi"}} reply := &PingResponse{} if err := client.Call("GetData", req, reply); err != nil { t.Fatalf("couln't call service: %v", err) } wantedMsg := "Pong hi" if reply.PingResult.Message != wantedMsg { t.Errorf("got msg %s wanted %s", reply.PingResult.Message, wantedMsg) } } func TestClient_Send_Correct_Headers(t *testing.T) { tests := []struct { action string reqHeaders map[string]string expectedHeaders map[string]string }{ // default case when no custom headers are set { "GetTrade", map[string]string{}, map[string]string{ "User-Agent": "gowsdl/0.1", "SOAPAction": "GetTrade", "Content-Type": "text/xml; charset=\"utf-8\"", }, }, // override default User-Agent { "SaveTrade", map[string]string{"User-Agent": "soap/0.1"}, map[string]string{ "User-Agent": "soap/0.1", "SOAPAction": "SaveTrade", }, }, // override default Content-Type { "SaveTrade", map[string]string{"Content-Type": "text/xml; charset=\"utf-16\""}, map[string]string{"Content-Type": "text/xml; charset=\"utf-16\""}, }, } var gotHeaders http.Header ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotHeaders = r.Header })) defer ts.Close() for _, test := range tests { client := NewClient(ts.URL, WithHTTPHeaders(test.reqHeaders)) req := struct{}{} reply := struct{}{} client.Call(test.action, req, reply) for k, v := range test.expectedHeaders { h := gotHeaders.Get(k) if h != v { t.Errorf("got %s wanted %s", h, v) } } } } func TestClient_Attachments_WithAttachmentResponse(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for k, v := range r.Header { w.Header().Set(k, v[0]) } bodyBuf, _ := ioutil.ReadAll(r.Body) _, err := w.Write(bodyBuf) if err != nil { panic(err) } })) defer ts.Close() // GIVEN firstAtt := MIMEMultipartAttachment{ Name: "First_Attachment", Data: []byte(`foobar`), } secondAtt := MIMEMultipartAttachment{ Name: "Second_Attachment", Data: []byte(`tl;tr`), } client := NewClient(ts.URL, WithMIMEMultipartAttachments()) client.AddMIMEMultipartAttachment(firstAtt) client.AddMIMEMultipartAttachment(secondAtt) req := &AttachmentRequest{ Name: "UploadMyFilePlease", ContentID: "First_Attachment", } reply := new(AttachmentRequest) retAttachments := make([]MIMEMultipartAttachment, 0) // WHEN if err := client.CallContextWithAttachmentsAndFaultDetail(context.TODO(), "''", req, reply, nil, &retAttachments); err != nil { t.Fatalf("couln't call service: %v", err) } // THEN assert.Equal(t, req.ContentID, reply.ContentID) assert.Len(t, retAttachments, 2) assert.Equal(t, retAttachments[0], firstAtt) assert.Equal(t, retAttachments[1], secondAtt) } func TestClient_MTOM(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for k, v := range r.Header { w.Header().Set(k, v[0]) } bodyBuf, _ := ioutil.ReadAll(r.Body) w.Write(bodyBuf) })) defer ts.Close() client := NewClient(ts.URL, WithMTOM()) req := &PingRequest{Attachment: NewBinary([]byte("Attached data")).SetContentType("text/plain")} reply := &PingRequest{} if err := client.Call("GetData", req, reply); err != nil { t.Fatalf("couln't call service: %v", err) } if !bytes.Equal(reply.Attachment.Bytes(), req.Attachment.Bytes()) { t.Errorf("got %s wanted %s", reply.Attachment.Bytes(), req.Attachment.Bytes()) } if reply.Attachment.ContentType() != req.Attachment.ContentType() { t.Errorf("got %s wanted %s", reply.Attachment.Bytes(), req.Attachment.ContentType()) } } type SimpleNode struct { Detail string `xml:"Detail,omitempty"` Num float64 `xml:"Num,omitempty"` Nested *SimpleNode `xml:"Nested,omitempty"` } func (s SimpleNode) ErrorString() string { var sb strings.Builder sb.WriteString(fmt.Sprintf("%.2f: %s", s.Num, s.Detail)) if s.Nested != nil { sb.WriteString("\n" + s.Nested.ErrorString()) } return sb.String() } func (s SimpleNode) HasData() bool { return true } type Wrapper struct { Item interface{} `xml:"SimpleNode"` hasData bool } func (w *Wrapper) HasData() bool { return w.hasData } func (w *Wrapper) ErrorString() string { switch w.Item.(type) { case FaultError: return w.Item.(FaultError).ErrorString() } return "default error" } func Test_SimpleNode(t *testing.T) { input := `<SimpleNode> <Name>SimpleNode</Name> <Detail>detail message</Detail> <Num>6.005</Num> </SimpleNode>` decoder := xml.NewDecoder(strings.NewReader(input)) var simple interface{} simple = &SimpleNode{} if err := decoder.Decode(&simple); err != nil { t.Fatalf("error decoding: %v", err) } assert.EqualValues(t, &SimpleNode{ Detail: "detail message", Num: 6.005, }, simple) } func Test_Client_FaultDefault(t *testing.T) { tests := []struct { name string hasData bool wantErrString string fault interface{} emptyFault interface{} }{ { name: "Empty-WithFault", wantErrString: "default error", hasData: true, }, { name: "Empty-NoFaultDetail", wantErrString: "Custom error message.", hasData: false, }, { name: "SimpleNode", wantErrString: "7.70: detail message", hasData: true, fault: &SimpleNode{ Detail: "detail message", Num: 7.7, }, emptyFault: &SimpleNode{}, }, { name: "ArrayOfNode", wantErrString: "default error", hasData: true, fault: &[]SimpleNode{ { Detail: "detail message-1", Num: 7.7, }, { Detail: "detail message-2", Num: 7.8, }, }, emptyFault: &[]SimpleNode{}, }, { name: "NestedNode", wantErrString: "0.00: detail-1\n" + "0.00: nested-2", hasData: true, fault: &SimpleNode{ Detail: "detail-1", Num: .003, Nested: &SimpleNode{ Detail: "nested-2", Num: .004, }, }, emptyFault: &SimpleNode{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { data, err := xml.MarshalIndent(tt.fault, "\t\t\t\t", "\t") if err != nil { t.Fatalf("Failed to encode input as XML: %v", err) } var pingRequest = new(Ping) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { xml.NewDecoder(r.Body).Decode(pingRequest) rsp := fmt.Sprintf(` <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <soap:Fault> <faultcode>soap:Server</faultcode> <faultstring>Custom error message.</faultstring> <detail> %v </detail> </soap:Fault> </soap:Body> </soap:Envelope>`, string(data)) w.Write([]byte(rsp)) })) defer ts.Close() faultErrString := tt.wantErrString client := NewClient(ts.URL) req := &Ping{Request: &PingRequest{Message: "Hi"}} var reply PingResponse fault := Wrapper{ Item: tt.emptyFault, hasData: tt.hasData, } if err := client.CallWithFaultDetail("GetData", req, &reply, &fault); err != nil { assert.EqualError(t, err, faultErrString) assert.EqualValues(t, tt.fault, fault.Item) } else { t.Fatalf("call to ping() should have failed, but succeeded.") } }) } } // TestXsdDateTime checks the marshalled xsd datetime func TestXsdDateTime(t *testing.T) { type TestDateTime struct { XMLName xml.Name `xml:"TestDateTime"` Datetime XSDDateTime } type TestAttrDateTime struct { XMLName xml.Name `xml:"TestAttrDateTime"` Datetime XSDDateTime `xml:"Datetime,attr"` } // test marshalling { // without nanosecond testDateTime := TestDateTime{ Datetime: CreateXsdDateTime(time.Date(1951, time.October, 22, 1, 2, 3, 0, time.FixedZone("UTC-8", -8*60*60)), true), } if output, err := xml.MarshalIndent(testDateTime, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestDateTime><Datetime>1951-10-22T01:02:03-08:00</Datetime></TestDateTime>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } { // with nanosecond testDateTime := TestDateTime{ Datetime: CreateXsdDateTime(time.Date(1951, time.October, 22, 1, 2, 3, 4, time.FixedZone("UTC-8", -8*60*60)), true), } if output, err := xml.MarshalIndent(testDateTime, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestDateTime><Datetime>1951-10-22T01:02:03.000000004-08:00</Datetime></TestDateTime>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } // test marshalling of UTC { testDateTime := TestDateTime{ Datetime: CreateXsdDateTime(time.Date(1951, time.October, 22, 1, 2, 3, 4, time.UTC), true), } if output, err := xml.MarshalIndent(testDateTime, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestDateTime><Datetime>1951-10-22T01:02:03.000000004Z</Datetime></TestDateTime>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } // test marshalling of XsdDateTime without TZ { testDateTime := TestDateTime{ Datetime: CreateXsdDateTime(time.Date(1951, time.October, 22, 1, 2, 3, 4, time.UTC), false), } if output, err := xml.MarshalIndent(testDateTime, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestDateTime><Datetime>1951-10-22T01:02:03.000000004</Datetime></TestDateTime>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } // test marshalling as attribute { testDateTime := TestAttrDateTime{ Datetime: CreateXsdDateTime(time.Date(1951, time.October, 22, 1, 2, 3, 4, time.UTC), true), } if output, err := xml.MarshalIndent(testDateTime, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestAttrDateTime Datetime=\"1951-10-22T01:02:03.000000004Z\"></TestAttrDateTime>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } // test unmarshalling { dateTimes := map[string]time.Time{ "<TestDateTime><Datetime>1951-10-22T01:02:03.000000004-08:00</Datetime></TestDateTime>": time.Date(1951, time.October, 22, 1, 2, 3, 4, time.FixedZone("-0800", -8*60*60)), "<TestDateTime><Datetime>1951-10-22T01:02:03Z</Datetime></TestDateTime>": time.Date(1951, time.October, 22, 1, 2, 3, 0, time.UTC), "<TestDateTime><Datetime>1951-10-22T01:02:03</Datetime></TestDateTime>": time.Date(1951, time.October, 22, 1, 2, 3, 0, time.Local), } for dateTimeStr, dateTimeObj := range dateTimes { parsedDt := TestDateTime{} if err := xml.Unmarshal([]byte(dateTimeStr), &parsedDt); err != nil { t.Error(err) } else { if !parsedDt.Datetime.ToGoTime().Equal(dateTimeObj) { t.Errorf("Got: %#v\nExpected: %#v", parsedDt.Datetime.ToGoTime(), dateTimeObj) } } } } // test unmarshalling as attribute { dateTimes := map[string]time.Time{ "<TestAttrDateTime Datetime=\"1951-10-22T01:02:03.000000004-08:00\"></TestAttrDateTime>": time.Date(1951, time.October, 22, 1, 2, 3, 4, time.FixedZone("-0800", -8*60*60)), "<TestAttrDateTime Datetime=\"1951-10-22T01:02:03Z\"></TestAttrDateTime>": time.Date(1951, time.October, 22, 1, 2, 3, 0, time.UTC), "<TestAttrDateTime Datetime=\"1951-10-22T01:02:03\"></TestAttrDateTime>": time.Date(1951, time.October, 22, 1, 2, 3, 0, time.Local), } for dateTimeStr, dateTimeObj := range dateTimes { parsedDt := TestAttrDateTime{} if err := xml.Unmarshal([]byte(dateTimeStr), &parsedDt); err != nil { t.Error(err) } else { if !parsedDt.Datetime.ToGoTime().Equal(dateTimeObj) { t.Errorf("Got: %#v\nExpected: %#v", parsedDt.Datetime.ToGoTime(), dateTimeObj) } } } } } // TestXsdDateTime checks the marshalled xsd datetime func TestXsdDate(t *testing.T) { type TestDate struct { XMLName xml.Name `xml:"TestDate"` Date XSDDate } type TestAttrDate struct { XMLName xml.Name `xml:"TestAttrDate"` Date XSDDate `xml:"Date,attr"` } // test marshalling { testDate := TestDate{ Date: CreateXsdDate(time.Date(1951, time.October, 22, 0, 0, 0, 0, time.FixedZone("UTC-8", -8*60*60)), false), } if output, err := xml.MarshalIndent(testDate, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestDate><Date>1951-10-22</Date></TestDate>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } // test marshalling { testDate := TestDate{ Date: CreateXsdDate(time.Date(1951, time.October, 22, 0, 0, 0, 0, time.FixedZone("UTC-8", -8*60*60)), true), } if output, err := xml.MarshalIndent(testDate, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestDate><Date>1951-10-22-08:00</Date></TestDate>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } // test marshalling of UTC { testDate := TestDate{ Date: CreateXsdDate(time.Date(1951, time.October, 22, 0, 0, 0, 0, time.UTC), true), } if output, err := xml.MarshalIndent(testDate, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestDate><Date>1951-10-22Z</Date></TestDate>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } // test marshalling as attribute { testDate := TestAttrDate{ Date: CreateXsdDate(time.Date(1951, time.October, 22, 0, 0, 0, 0, time.UTC), true), } if output, err := xml.MarshalIndent(testDate, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestAttrDate Date=\"1951-10-22Z\"></TestAttrDate>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } // test unmarshalling { dates := map[string]time.Time{ "<TestDate><Date>1951-10-22</Date></TestDate>": time.Date(1951, time.October, 22, 0, 0, 0, 0, time.Local), "<TestDate><Date>1951-10-22Z</Date></TestDate>": time.Date(1951, time.October, 22, 0, 0, 0, 0, time.UTC), "<TestDate><Date>1951-10-22-08:00</Date></TestDate>": time.Date(1951, time.October, 22, 0, 0, 0, 0, time.FixedZone("UTC-8", -8*60*60)), } for dateStr, dateObj := range dates { parsedDate := TestDate{} if err := xml.Unmarshal([]byte(dateStr), &parsedDate); err != nil { t.Error(dateStr, err) } else { if !parsedDate.Date.ToGoTime().Equal(dateObj) { t.Errorf("Got: %#v\nExpected: %#v", parsedDate.Date.ToGoTime(), dateObj) } } } } // test unmarshalling as attribute { dates := map[string]time.Time{ "<TestAttrDate Date=\"1951-10-22\"></TestAttrDate>": time.Date(1951, time.October, 22, 0, 0, 0, 0, time.Local), "<TestAttrDate Date=\"1951-10-22Z\"></TestAttrDate>": time.Date(1951, time.October, 22, 0, 0, 0, 0, time.UTC), "<TestAttrDate Date=\"1951-10-22-08:00\"></TestAttrDate>": time.Date(1951, time.October, 22, 0, 0, 0, 0, time.FixedZone("UTC-8", -8*60*60)), } for dateStr, dateObj := range dates { parsedDate := TestAttrDate{} if err := xml.Unmarshal([]byte(dateStr), &parsedDate); err != nil { t.Error(dateStr, err) } else { if !parsedDate.Date.ToGoTime().Equal(dateObj) { t.Errorf("Got: %#v\nExpected: %#v", parsedDate.Date.ToGoTime(), dateObj) } } } } } // TestXsdTime checks the marshalled xsd datetime func TestXsdTime(t *testing.T) { type TestTime struct { XMLName xml.Name `xml:"TestTime"` Time XSDTime } type TestAttrTime struct { XMLName xml.Name `xml:"TestAttrTime"` Time XSDTime `xml:"Time,attr"` } // test marshalling { testTime := TestTime{ Time: CreateXsdTime(12, 13, 14, 4, time.FixedZone("Test", -19800)), } if output, err := xml.MarshalIndent(testTime, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestTime><Time>12:13:14.000000004-05:30</Time></TestTime>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } { testTime := TestTime{ Time: CreateXsdTime(12, 13, 14, 0, time.FixedZone("UTC-8", -8*60*60)), } if output, err := xml.MarshalIndent(testTime, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestTime><Time>12:13:14-08:00</Time></TestTime>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } { testTime := TestTime{ Time: CreateXsdTime(12, 13, 14, 0, nil), } if output, err := xml.MarshalIndent(testTime, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestTime><Time>12:13:14</Time></TestTime>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } // test marshalling as attribute { testTime := TestAttrTime{ Time: CreateXsdTime(12, 13, 14, 4, time.FixedZone("Test", -19800)), } if output, err := xml.MarshalIndent(testTime, "", ""); err != nil { t.Error(err) } else { outputstr := string(output) expected := "<TestAttrTime Time=\"12:13:14.000000004-05:30\"></TestAttrTime>" if outputstr != expected { t.Errorf("Got: %v\nExpected: %v", outputstr, expected) } } } // test unmarshalling without TZ { timeStr := "<TestTime><Time>12:13:14.000000004</Time></TestTime>" parsedTime := TestTime{} if err := xml.Unmarshal([]byte(timeStr), &parsedTime); err != nil { t.Error(err) } else { if parsedTime.Time.Hour() != 12 { t.Errorf("Got hour %#v\nExpected: %#v", parsedTime.Time.Hour(), 12) } if parsedTime.Time.Minute() != 13 { t.Errorf("Got minute %#v\nExpected: %#v", parsedTime.Time.Minute(), 13) } if parsedTime.Time.Second() != 14 { t.Errorf("Got second %#v\nExpected: %#v", parsedTime.Time.Second(), 14) } if parsedTime.Time.Nanosecond() != 4 { t.Errorf("Got nsec %#v\nExpected: %#v", parsedTime.Time.Nanosecond(), 4) } if parsedTime.Time.Location() != nil { t.Errorf("Got location %v\nExpected: Nil/Undetermined", parsedTime.Time.Location().String()) } } } // test unmarshalling with UTC { timeStr := "<TestTime><Time>12:13:14Z</Time></TestTime>" parsedTime := TestTime{} if err := xml.Unmarshal([]byte(timeStr), &parsedTime); err != nil { t.Error(err) } else { if parsedTime.Time.Hour() != 12 { t.Errorf("Got hour %#v\nExpected: %#v", parsedTime.Time.Hour(), 12) } if parsedTime.Time.Minute() != 13 { t.Errorf("Got minute %#v\nExpected: %#v", parsedTime.Time.Minute(), 13) } if parsedTime.Time.Second() != 14 { t.Errorf("Got second %#v\nExpected: %#v", parsedTime.Time.Second(), 14) } if parsedTime.Time.Nanosecond() != 0 { t.Errorf("Got nsec %#v\nExpected: %#v", parsedTime.Time.Nanosecond(), 0) } if parsedTime.Time.Location().String() != "UTC" { t.Errorf("Got location %v\nExpected: UTC", parsedTime.Time.Location().String()) } } } // test unmarshalling with non-UTC Tz { timeStr := "<TestTime><Time>12:13:14-08:00</Time></TestTime>" parsedTime := TestTime{} if err := xml.Unmarshal([]byte(timeStr), &parsedTime); err != nil { t.Error(err) } else { if parsedTime.Time.Hour() != 12 { t.Errorf("Got hour %#v\nExpected: %#v", parsedTime.Time.Hour(), 12) } if parsedTime.Time.Minute() != 13 { t.Errorf("Got minute %#v\nExpected: %#v", parsedTime.Time.Minute(), 13) } if parsedTime.Time.Second() != 14 { t.Errorf("Got second %#v\nExpected: %#v", parsedTime.Time.Second(), 14) } if parsedTime.Time.Nanosecond() != 0 { t.Errorf("Got nsec %#v\nExpected: %#v", parsedTime.Time.Nanosecond(), 0) } _, tzOffset := parsedTime.Time.innerTime.Zone() if tzOffset != -8*3600 { t.Errorf("Got location offset %v\nExpected: %v", tzOffset, -8*3600) } } } // test unmarshalling as attribute { timeStr := "<TestAttrTime Time=\"12:13:14Z\"></TestAttrTime>" parsedTime := TestAttrTime{} if err := xml.Unmarshal([]byte(timeStr), &parsedTime); err != nil { t.Error(err) } else { if parsedTime.Time.Hour() != 12 { t.Errorf("Got hour %#v\nExpected: %#v", parsedTime.Time.Hour(), 12) } if parsedTime.Time.Minute() != 13 { t.Errorf("Got minute %#v\nExpected: %#v", parsedTime.Time.Minute(), 13) } if parsedTime.Time.Second() != 14 { t.Errorf("Got second %#v\nExpected: %#v", parsedTime.Time.Second(), 14) } if parsedTime.Time.Nanosecond() != 0 { t.Errorf("Got nsec %#v\nExpected: %#v", parsedTime.Time.Nanosecond(), 0) } if parsedTime.Time.Location().String() != "UTC" { t.Errorf("Got location %v\nExpected: UTC", parsedTime.Time.Location().String()) } } } } func TestHTTPError(t *testing.T) { type httpErrorTest struct { name string responseCode int responseBody string wantErr bool wantErrMsg string } tests := []httpErrorTest{ { name: "should error if server returns 500", responseCode: http.StatusInternalServerError, responseBody: "internal server error", wantErr: true, wantErrMsg: "HTTP Status 500: internal server error", }, { name: "should error if server returns 403", responseCode: http.StatusForbidden, responseBody: "forbidden", wantErr: true, wantErrMsg: "HTTP Status 403: forbidden", }, { name: "should not error if server returns 200", responseCode: http.StatusOK, responseBody: `<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <PingResponse xmlns="http://example.com/service.xsd"> <PingResult> <Message>Pong hi</Message> </PingResult> </PingResponse> </soap:Body> </soap:Envelope>`, wantErr: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(test.responseCode) w.Write([]byte(test.responseBody)) })) defer ts.Close() client := NewClient(ts.URL) gotErr := client.Call("GetData", &Ping{}, &PingResponse{}) if test.wantErr { if gotErr == nil { t.Fatalf("Expected an error from call. Received none") } requestError, ok := gotErr.(*HTTPError) if !ok { t.Fatalf("Expected a HTTPError. Received: %s", gotErr.Error()) } if requestError.StatusCode != test.responseCode { t.Fatalf("Unexpected StatusCode. Got %d", requestError.StatusCode) } if string(requestError.ResponseBody) != test.responseBody { t.Fatalf("Unexpected ResponseBody. Got %s", requestError.ResponseBody) } if requestError.Error() != test.wantErrMsg { t.Fatalf("Unexpected Error message. Got %s", requestError.Error()) } } else if gotErr != nil { t.Fatalf("Expected no error from call. Received: %s", gotErr.Error()) } }) } }
mpl-2.0
cstipkovic/spidermonkey-research
js/src/jit-test/tests/wasm/spec/exports.wast.js
145
// |jit-test| test-also-wasm-baseline // TODO: real memory exports. quit(); var importedArgs = ['exports.wast']; load(scriptdir + '../spec.js');
mpl-2.0
CalebSLane/openelisglobal-core
app/src/us/mn/state/health/lims/testconfiguration/action/TestSectionTestAssignUpdate.java
4219
/* * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations under * the License. * * The Original Code is OpenELIS code. * * Copyright (C) ITECH, University of Washington, Seattle WA. All Rights Reserved. */ package us.mn.state.health.lims.testconfiguration.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.validator.DynaValidatorForm; import org.hibernate.HibernateException; import org.hibernate.Transaction; import us.mn.state.health.lims.common.action.BaseAction; import us.mn.state.health.lims.common.services.DisplayListService; import us.mn.state.health.lims.common.services.TestSectionService; import us.mn.state.health.lims.common.services.TestService; import us.mn.state.health.lims.common.util.validator.GenericValidator; import us.mn.state.health.lims.hibernate.HibernateUtil; import us.mn.state.health.lims.test.daoimpl.TestDAOImpl; import us.mn.state.health.lims.test.daoimpl.TestSectionDAOImpl; import us.mn.state.health.lims.test.valueholder.Test; import us.mn.state.health.lims.test.valueholder.TestSection; public class TestSectionTestAssignUpdate extends BaseAction { @Override protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm dynaForm = (DynaValidatorForm)form; String testId = dynaForm.getString("testId"); String testSectionId = dynaForm.getString("testSectionId"); String deactivateTestSectionId = dynaForm.getString("deactivateTestSectionId"); boolean updateTestSection = false; String currentUser = getSysUserId(request); Test test = new TestService(testId).getTest(); TestSection testSection = new TestSectionService(testSectionId).getTestSection(); TestSection deActivateTestSection = null; test.setTestSection(testSection); test.setSysUserId(currentUser); //This covers the case that they are moving the test to the same test section they are moving it from if(testSectionId.equals(deactivateTestSectionId)){ return mapping.findForward(FWD_SUCCESS); } if( "N".equals(testSection.getIsActive())){ testSection.setIsActive("Y"); testSection.setSysUserId(currentUser); updateTestSection = true; } if( !GenericValidator.isBlankOrNull(deactivateTestSectionId) ){ deActivateTestSection = new TestSectionService(deactivateTestSectionId).getTestSection(); deActivateTestSection.setIsActive("N"); deActivateTestSection.setSysUserId(currentUser); } Transaction tx = HibernateUtil.getSession().beginTransaction(); try { new TestDAOImpl().updateData(test); if(updateTestSection){ new TestSectionDAOImpl().updateData(testSection); } if( deActivateTestSection != null){ new TestSectionDAOImpl().updateData(deActivateTestSection); } tx.commit(); } catch (HibernateException e) { tx.rollback(); } finally { HibernateUtil.closeSession(); } DisplayListService.refreshList(DisplayListService.ListType.TEST_SECTION); DisplayListService.refreshList(DisplayListService.ListType.TEST_SECTION_INACTIVE); return mapping.findForward(FWD_SUCCESS); } @Override protected String getPageTitleKey() { return null; } @Override protected String getPageSubtitleKey() { return null; } }
mpl-2.0
logicmonitor/k8s-argus
vendor/github.com/logicmonitor/lm-sdk-go/client/lm/patch_device_parameters.go
8596
// Code generated by go-swagger; DO NOT EDIT. package lm // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/logicmonitor/lm-sdk-go/models" ) // NewPatchDeviceParams creates a new PatchDeviceParams object, // with the default timeout for this client. // // Default values are not hydrated, since defaults are normally applied by the API server side. // // To enforce default values in parameter, use SetDefaults or WithDefaults. func NewPatchDeviceParams() *PatchDeviceParams { return &PatchDeviceParams{ timeout: cr.DefaultTimeout, } } // NewPatchDeviceParamsWithTimeout creates a new PatchDeviceParams object // with the ability to set a timeout on a request. func NewPatchDeviceParamsWithTimeout(timeout time.Duration) *PatchDeviceParams { return &PatchDeviceParams{ timeout: timeout, } } // NewPatchDeviceParamsWithContext creates a new PatchDeviceParams object // with the ability to set a context for a request. func NewPatchDeviceParamsWithContext(ctx context.Context) *PatchDeviceParams { return &PatchDeviceParams{ Context: ctx, } } // NewPatchDeviceParamsWithHTTPClient creates a new PatchDeviceParams object // with the ability to set a custom HTTPClient for a request. func NewPatchDeviceParamsWithHTTPClient(client *http.Client) *PatchDeviceParams { return &PatchDeviceParams{ HTTPClient: client, } } /* PatchDeviceParams contains all the parameters to send to the API endpoint for the patch device operation. Typically these are written to a http.Request. */ type PatchDeviceParams struct { // PatchFields. PatchFields *string // UserAgent. // // Default: "Logicmonitor/SDK: Argus Dist-v1.0.0-argus1" UserAgent *string // Body. Body *models.Device // End. // // Format: int64 End *int64 // ID. // // Format: int32 ID int32 // NetflowFilter. NetflowFilter *string // OpType. // // Default: "refresh" OpType *string // Start. // // Format: int64 Start *int64 timeout time.Duration Context context.Context HTTPClient *http.Client } // WithDefaults hydrates default values in the patch device params (not the query body). // // All values with no default are reset to their zero value. func (o *PatchDeviceParams) WithDefaults() *PatchDeviceParams { o.SetDefaults() return o } // SetDefaults hydrates default values in the patch device params (not the query body). // // All values with no default are reset to their zero value. func (o *PatchDeviceParams) SetDefaults() { var ( userAgentDefault = string("Logicmonitor/SDK: Argus Dist-v1.0.0-argus1") opTypeDefault = string("refresh") ) val := PatchDeviceParams{ UserAgent: &userAgentDefault, OpType: &opTypeDefault, } val.timeout = o.timeout val.Context = o.Context val.HTTPClient = o.HTTPClient *o = val } // WithTimeout adds the timeout to the patch device params func (o *PatchDeviceParams) WithTimeout(timeout time.Duration) *PatchDeviceParams { o.SetTimeout(timeout) return o } // SetTimeout adds the timeout to the patch device params func (o *PatchDeviceParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } // WithContext adds the context to the patch device params func (o *PatchDeviceParams) WithContext(ctx context.Context) *PatchDeviceParams { o.SetContext(ctx) return o } // SetContext adds the context to the patch device params func (o *PatchDeviceParams) SetContext(ctx context.Context) { o.Context = ctx } // WithHTTPClient adds the HTTPClient to the patch device params func (o *PatchDeviceParams) WithHTTPClient(client *http.Client) *PatchDeviceParams { o.SetHTTPClient(client) return o } // SetHTTPClient adds the HTTPClient to the patch device params func (o *PatchDeviceParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } // WithPatchFields adds the patchFields to the patch device params func (o *PatchDeviceParams) WithPatchFields(patchFields *string) *PatchDeviceParams { o.SetPatchFields(patchFields) return o } // SetPatchFields adds the patchFields to the patch device params func (o *PatchDeviceParams) SetPatchFields(patchFields *string) { o.PatchFields = patchFields } // WithUserAgent adds the userAgent to the patch device params func (o *PatchDeviceParams) WithUserAgent(userAgent *string) *PatchDeviceParams { o.SetUserAgent(userAgent) return o } // SetUserAgent adds the userAgent to the patch device params func (o *PatchDeviceParams) SetUserAgent(userAgent *string) { o.UserAgent = userAgent } // WithBody adds the body to the patch device params func (o *PatchDeviceParams) WithBody(body *models.Device) *PatchDeviceParams { o.SetBody(body) return o } // SetBody adds the body to the patch device params func (o *PatchDeviceParams) SetBody(body *models.Device) { o.Body = body } // WithEnd adds the end to the patch device params func (o *PatchDeviceParams) WithEnd(end *int64) *PatchDeviceParams { o.SetEnd(end) return o } // SetEnd adds the end to the patch device params func (o *PatchDeviceParams) SetEnd(end *int64) { o.End = end } // WithID adds the id to the patch device params func (o *PatchDeviceParams) WithID(id int32) *PatchDeviceParams { o.SetID(id) return o } // SetID adds the id to the patch device params func (o *PatchDeviceParams) SetID(id int32) { o.ID = id } // WithNetflowFilter adds the netflowFilter to the patch device params func (o *PatchDeviceParams) WithNetflowFilter(netflowFilter *string) *PatchDeviceParams { o.SetNetflowFilter(netflowFilter) return o } // SetNetflowFilter adds the netflowFilter to the patch device params func (o *PatchDeviceParams) SetNetflowFilter(netflowFilter *string) { o.NetflowFilter = netflowFilter } // WithOpType adds the opType to the patch device params func (o *PatchDeviceParams) WithOpType(opType *string) *PatchDeviceParams { o.SetOpType(opType) return o } // SetOpType adds the opType to the patch device params func (o *PatchDeviceParams) SetOpType(opType *string) { o.OpType = opType } // WithStart adds the start to the patch device params func (o *PatchDeviceParams) WithStart(start *int64) *PatchDeviceParams { o.SetStart(start) return o } // SetStart adds the start to the patch device params func (o *PatchDeviceParams) SetStart(start *int64) { o.Start = start } // WriteToRequest writes these params to a swagger request func (o *PatchDeviceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if o.PatchFields != nil { // query param PatchFields var qrPatchFields string if o.PatchFields != nil { qrPatchFields = *o.PatchFields } qPatchFields := qrPatchFields if qPatchFields != "" { if err := r.SetQueryParam("PatchFields", qPatchFields); err != nil { return err } } } if o.UserAgent != nil { // header param User-Agent if err := r.SetHeaderParam("User-Agent", *o.UserAgent); err != nil { return err } } if o.Body != nil { if err := r.SetBodyParam(o.Body); err != nil { return err } } if o.End != nil { // query param end var qrEnd int64 if o.End != nil { qrEnd = *o.End } qEnd := swag.FormatInt64(qrEnd) if qEnd != "" { if err := r.SetQueryParam("end", qEnd); err != nil { return err } } } // path param id if err := r.SetPathParam("id", swag.FormatInt32(o.ID)); err != nil { return err } if o.NetflowFilter != nil { // query param netflowFilter var qrNetflowFilter string if o.NetflowFilter != nil { qrNetflowFilter = *o.NetflowFilter } qNetflowFilter := qrNetflowFilter if qNetflowFilter != "" { if err := r.SetQueryParam("netflowFilter", qNetflowFilter); err != nil { return err } } } if o.OpType != nil { // query param opType var qrOpType string if o.OpType != nil { qrOpType = *o.OpType } qOpType := qrOpType if qOpType != "" { if err := r.SetQueryParam("opType", qOpType); err != nil { return err } } } if o.Start != nil { // query param start var qrStart int64 if o.Start != nil { qrStart = *o.Start } qStart := swag.FormatInt64(qrStart) if qStart != "" { if err := r.SetQueryParam("start", qStart); err != nil { return err } } } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
mpl-2.0
cstipkovic/spidermonkey-research
js/src/jsapi-tests/testArrayBuffer.cpp
5161
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: */ #include "jsfriendapi.h" #include "jsapi-tests/tests.h" BEGIN_TEST(testArrayBuffer_bug720949_steal) { static const unsigned NUM_TEST_BUFFERS = 2; static const unsigned MAGIC_VALUE_1 = 3; static const unsigned MAGIC_VALUE_2 = 17; JS::RootedObject buf_len1(cx), buf_len200(cx); JS::RootedObject tarray_len1(cx), tarray_len200(cx); uint32_t sizes[NUM_TEST_BUFFERS] = { sizeof(uint32_t), 200 * sizeof(uint32_t) }; JS::HandleObject testBuf[NUM_TEST_BUFFERS] = { buf_len1, buf_len200 }; JS::HandleObject testArray[NUM_TEST_BUFFERS] = { tarray_len1, tarray_len200 }; // Single-element ArrayBuffer (uses fixed slots for storage) CHECK(buf_len1 = JS_NewArrayBuffer(cx, sizes[0])); CHECK(tarray_len1 = JS_NewInt32ArrayWithBuffer(cx, testBuf[0], 0, -1)); JS_SetElement(cx, testArray[0], 0, MAGIC_VALUE_1); // Many-element ArrayBuffer (uses dynamic storage) CHECK(buf_len200 = JS_NewArrayBuffer(cx, 200 * sizeof(uint32_t))); CHECK(tarray_len200 = JS_NewInt32ArrayWithBuffer(cx, testBuf[1], 0, -1)); for (unsigned i = 0; i < NUM_TEST_BUFFERS; i++) { JS::HandleObject obj = testBuf[i]; JS::HandleObject view = testArray[i]; uint32_t size = sizes[i]; JS::RootedValue v(cx); // Byte lengths should all agree CHECK(JS_IsArrayBufferObject(obj)); CHECK_EQUAL(JS_GetArrayBufferByteLength(obj), size); JS_GetProperty(cx, obj, "byteLength", &v); CHECK(v.isInt32(size)); JS_GetProperty(cx, view, "byteLength", &v); CHECK(v.isInt32(size)); // Modifying the underlying data should update the value returned through the view { JS::AutoCheckCannotGC nogc; bool sharedDummy; uint8_t* data = JS_GetArrayBufferData(obj, &sharedDummy, nogc); CHECK(data != nullptr); *reinterpret_cast<uint32_t*>(data) = MAGIC_VALUE_2; } CHECK(JS_GetElement(cx, view, 0, &v)); CHECK(v.isInt32(MAGIC_VALUE_2)); // Steal the contents void* contents = JS_StealArrayBufferContents(cx, obj); CHECK(contents != nullptr); CHECK(JS_IsDetachedArrayBufferObject(obj)); // Transfer to a new ArrayBuffer JS::RootedObject dst(cx, JS_NewArrayBufferWithContents(cx, size, contents)); CHECK(JS_IsArrayBufferObject(dst)); { JS::AutoCheckCannotGC nogc; bool sharedDummy; (void) JS_GetArrayBufferData(obj, &sharedDummy, nogc); } JS::RootedObject dstview(cx, JS_NewInt32ArrayWithBuffer(cx, dst, 0, -1)); CHECK(dstview != nullptr); CHECK_EQUAL(JS_GetArrayBufferByteLength(dst), size); { JS::AutoCheckCannotGC nogc; bool sharedDummy; uint8_t* data = JS_GetArrayBufferData(dst, &sharedDummy, nogc); CHECK(data != nullptr); CHECK_EQUAL(*reinterpret_cast<uint32_t*>(data), MAGIC_VALUE_2); } CHECK(JS_GetElement(cx, dstview, 0, &v)); CHECK(v.isInt32(MAGIC_VALUE_2)); } return true; } END_TEST(testArrayBuffer_bug720949_steal) // Varying number of views of a buffer, to test the detachment weak pointers BEGIN_TEST(testArrayBuffer_bug720949_viewList) { JS::RootedObject buffer(cx); // No views buffer = JS_NewArrayBuffer(cx, 2000); buffer = nullptr; GC(cx); // One view. { buffer = JS_NewArrayBuffer(cx, 2000); JS::RootedObject view(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 0, -1)); void* contents = JS_StealArrayBufferContents(cx, buffer); CHECK(contents != nullptr); JS_free(nullptr, contents); GC(cx); CHECK(hasDetachedBuffer(view)); CHECK(JS_IsDetachedArrayBufferObject(buffer)); view = nullptr; GC(cx); buffer = nullptr; GC(cx); } // Two views { buffer = JS_NewArrayBuffer(cx, 2000); JS::RootedObject view1(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 0, -1)); JS::RootedObject view2(cx, JS_NewUint8ArrayWithBuffer(cx, buffer, 1, 200)); // Remove, re-add a view view2 = nullptr; GC(cx); view2 = JS_NewUint8ArrayWithBuffer(cx, buffer, 1, 200); // Detach void* contents = JS_StealArrayBufferContents(cx, buffer); CHECK(contents != nullptr); JS_free(nullptr, contents); CHECK(hasDetachedBuffer(view1)); CHECK(hasDetachedBuffer(view2)); CHECK(JS_IsDetachedArrayBufferObject(buffer)); view1 = nullptr; GC(cx); view2 = nullptr; GC(cx); buffer = nullptr; GC(cx); } return true; } static void GC(JSContext* cx) { JS_GC(cx); JS_GC(cx); // Trigger another to wait for background finalization to end } bool hasDetachedBuffer(JS::HandleObject obj) { JS::RootedValue v(cx); return JS_GetProperty(cx, obj, "byteLength", &v) && v.toInt32() == 0; } END_TEST(testArrayBuffer_bug720949_viewList)
mpl-2.0
joyent/manta-nfs
server.js
15007
// Copyright 2014 Joyent, Inc. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. var fs = require('fs'); var os = require('os'); var path = require('path'); var util = require('util'); var userid = require('userid'); var assert = require('assert-plus'); var bunyan = require('bunyan'); var clone = require('clone'); var dashdash = require('dashdash'); var LRU = require('lru-cache'); var nfs = require('nfs'); var rpc = require('oncrpc'); var mantafs = require('mantafs'); var vasync = require('vasync'); var app = require('./lib'); // uid/gid for 'nobody' on non-windows systems var uid = 0; var gid = 0; var os_platform; ///--- Globals var LOG = app.bunyan.createLogger(); var OPTIONS_PARSER = dashdash.createParser({ options: [ { names: ['file', 'f'], type: 'string', help: 'configuration file to use', helpArg: 'FILE' }, { names: ['debug', 'd'], type: 'bool', help: 'turn on debug bunyan logging' }, { names: ['verbose', 'v'], type: 'bool', help: 'turn on verbose bunyan logging' } ] }); ///--- Functions function usage(msg) { var help = OPTIONS_PARSER.help({ includeEnv: true }).trimRight(); if (msg) console.error(util.format.apply(util, arguments)); console.error('usage: nfsd [OPTIONS]\noptions:\n' + help); process.exit(msg ? 1 : 0); } function configure() { var opts; try { opts = OPTIONS_PARSER.parse(process.argv); } catch (e) { usage(e.message); } if (opts.verbose) { LOG = LOG.child({ level: 'trace', src: true }); } else if (opts.debug) { LOG = LOG.child({ level: 'debug', src: true }); } else { LOG = LOG.child({ level: 'info', src: true }); } if (opts.help) usage(); var cfg; if (opts.file) { try { cfg = JSON.parse(fs.readFileSync(opts.file, 'utf8')); } catch (e) { usage('unable to load %s:\n%s\n', opts.file, e.toString()); } } else { cfg = {}; } // If no config, let createMantaClient handle setup using env if (!cfg.manta) cfg.manta = {}; if (cfg.database) { assert.object(cfg.database, 'config.database'); } else { cfg.database = {}; } // default local cache config values if any are not provided if (!cfg.database.location) cfg.database.location = '/var/tmp/mfsdb'; if (!cfg.database.sizeMB) cfg.database.sizeMB = 5120; if (!cfg.database.ttl) cfg.database.ttl = 43200; if (!cfg.database.wbtime) cfg.database.wbtime = 60; if (!cfg.database.num_par) cfg.database.num_par = 2; if (cfg.portmap) { assert.object(cfg.portmap, 'config.portmap'); // Normally only define this section if setting // 'usehost': 1 } else { // our built-in portmapper just hardcodes the standard info cfg.portmap = { 'port': 111, 'mappings': { 'mountd': [ { 'prog': 100005, 'vers': 3, 'prot': 6, 'port': 1892 }, { 'prog': 100005, 'vers': 1, 'prot': 6, 'port': 1892 }], 'nfsd': [ { 'prog': 100003, 'vers': 3, 'prot': 6, 'port': 2049 }], 'portmapd': [ { 'prog': 100000, 'vers': 2, 'prot': 6, 'port': 111 }] } }; } // Can set 'address' to enable the mountd server to listen on an IP address // other than the loopback. // Can define hosts_allow and hosts_deny to list the addresses of hosts // which can/cannot mount. e.g. // 'hosts_allow': { // '192.168.0.10': {}, // '192.168.0.11': {} // }, // 'hosts_deny': { // '192.168.0.12': {}, // '192.168.0.13': {} // } // Can set exports if you want to limit what parts of the manta namespace // can be mounted: // 'exports': { // '/user/stor/project': {}, // '/user/public': {} // } cfg.mount = cfg.mount || {}; assert.object(cfg.mount, 'config.mount'); // Can set uid and gid to specify the uid/gid for 'nobody' on the client. // If not provided, the server's values for 'nobody' will be used. if (!cfg.nfs) { var t_uid; var t_gid; try { t_uid = convert_neg_id(userid.uid('nobody')); } catch (e1) { t_uid = 65534; } try { t_gid = convert_neg_id(userid.gid('nobody')); } catch (e1) { // Linux uses 'nogroup' instead of 'nobody' try { t_gid = convert_neg_id(userid.gid('nogroup')); } catch (e2) { t_gid = t_uid; } } cfg.nfs = { 'uid': t_uid, 'gid': t_gid }; } assert.object(cfg.nfs, 'config.nfs'); cfg.nfs.fd_cache = cfg.nfs.fd_cache || { max: 10000, ttl: 60 }; cfg.nfs.hosts_allow = cfg.mount.hosts_allow; cfg.nfs.hosts_deny = cfg.mount.hosts_deny; cfg.log = LOG; cfg.manta.log = LOG; cfg.mount.log = LOG; cfg.nfs.log = LOG; cfg.portmap.log = LOG; cfg.manta = app.createMantaClient(cfg.manta); cfg.mount.manta = cfg.manta; cfg.nfs.manta = cfg.manta; return (cfg); } function step_down() { try { process.setgid(gid); process.setuid(uid); LOG.info('server now running as \'nobody\''); } catch (e) { LOG.fatal(e, 'unable to setuid/setgid to nobody'); process.exit(1); } } // Runs the mountd and nfsd servers. Called once we're registered with the // system's portmapper or once we've started our own portmapper. function run_servers(log, cfg_mount, cfg_nfs) { var barrier = vasync.barrier(); var mountd = app.createMountServer(cfg_mount); var nfsd = app.createNfsServer(cfg_nfs); barrier.on('drain', function onRunning() { var ma = mountd.address(); var na = nfsd.address(); log.info('mountd: listening on: tcp://%s:%d', ma.address, ma.port); log.info('nfsd: listening on: tcp://%s:%d', na.address, na.port); if (uid !== 0) { // On non-windows machines we run as 'nobody'. // On sunos we have to wait until after we're listening on the nfs // port since the user 'nobody' will not have the sys_nfs priv. // On darwin 'nobody' is -2 and we error setting the uid/gid to a // negative number, so use the symbolic name. if (os_platform === 'darwin') { gid = uid = 'nobody'; } step_down(); } }); mountd.on('error', function (e) { if (e.code == 'EADDRINUSE') { log.fatal('mountd already running, exiting.'); } else { log.fatal(e, 'unable to run the mountd'); } process.exit(1); }); nfsd.on('error', function (e) { if (e.code == 'EADDRINUSE') { log.fatal('nfsd already running, exiting.'); } else { log.fatal(e, 'unable to run the nfsd'); } process.exit(1); }); barrier.start('mount'); mountd.listen(cfg_mount.port || 1892, cfg_mount.address || '127.0.0.1', barrier.done.bind(barrier, 'mount')); // nfsd needs to listen on the same IP as configured for the mountd barrier.start('nfs'); nfsd.listen(cfg_nfs.port || 2049, cfg_mount.address || '127.0.0.1', barrier.done.bind(barrier, 'nfs')); } // Darwin uses negative numbers for 'nobody' but these get pulled out as a // large non-negative number. Convert to twos-complement. function convert_neg_id(id) { if (id > 0x7fffffff) return (-(~id + 1)); else return (id); } ///--- Mainline (function main() { var cfg = configure(); var log = cfg.log; os_platform = os.platform(); if (os_platform !== 'win32' && os_platform !== 'darwin') { uid = convert_neg_id(userid.uid('nobody')); try { gid = convert_neg_id(userid.gid('nobody')); } catch (e1) { // Linux uses 'nogroup' instead of 'nobody' try { gid = convert_neg_id(userid.gid('nogroup')); } catch (e2) { gid = uid; } } } var mfs = mantafs.createClient({ log: log.child({component: 'MantaFs'}, true), manta: cfg.manta, path: cfg.database.location, sizeMB: cfg.database.sizeMB, ttl: cfg.database.ttl, wbtime: cfg.database.wbtime, num_par: cfg.database.num_par, uid: cfg.nfs.uid || uid, gid: cfg.nfs.gid || gid }); // must always use the system's portmapper on sunos if (os_platform === 'sunos') cfg.portmap.usehost = true; cfg.mount.fs = mfs; cfg.nfs.fs = mfs; cfg.nfs.fd_cache = LRU({ dispose: function cache_close_fd(k, v) { mfs.close(v.fd, function on_close(err) { if (err) log.debug(err, 'failed to close(fd=%d) for %s', v.fd, k); }); }, max: cfg.nfs.fd_cache.max, maxAge: cfg.nfs.fd_cache.ttl * 1000 // 1m TTL }); cfg.nfs.cachepath = cfg.database.location; // used by fsstat log.info('configuration: %s', util.inspect(cfg)); var mntmapping = { prog: 100005, vers: 3, prot: 6, port: 1892 }; var nfsmapping = { prog: 100003, vers: 3, prot: 6, port: 2049 }; function cleanup() { mfs.shutdown(function (err) { if (err) { log.warn(err, 'mantafs shutdown error'); } if (cfg.portmap.usehost) { var pmapclient = app.createPortmapClient(cfg.portmap); pmapclient.once('connect', function () { pmapclient.unset(mntmapping, function (err1) { if (err1) { log.warn(err1, 'unregistering mountd from the portmapper'); } pmapclient.unset(nfsmapping, function (err2) { if (err2) { log.warn(err2, 'unregistering nfsd from the portmapper'); } log.info('Shutdown complete, exiting.'); process.exit(0); }); }); }); } else { log.info('Shutdown complete, exiting.'); process.exit(0); } }); } process.on('SIGTERM', function () { log.info('Got SIGTERM, shutting down.'); cleanup(); }); process.on('SIGINT', function () { log.info('Got SIGINT, shutting down.'); cleanup(); }); mfs.once('error', function (err) { log.fatal(err, 'unable to initialize mantafs cache'); process.exit(1); }); mfs.once('ready', function () { // Cache exists now, ensure cache dir modes are more secure fs.chmodSync(mfs.cache.location, 0700); fs.chmodSync(path.join(mfs.cache.location, 'fscache'), 0700); fs.chmodSync(path.join(mfs.cache.location, 'mantafs.db'), 0600); if (uid !== 0) { // On non-windows machines we run as 'nobody'. Tighten up now. fs.chownSync(mfs.cache.location, uid, gid); fs.chownSync(path.join(mfs.cache.location, 'fscache'), uid, gid); fs.chownSync(path.join(mfs.cache.location, 'mantafs.db'), uid, gid); } // the portmapper needs to listen on all addresses, unlike our mountd // and nfsd which only listen on localhost by default for some basic // security cfg.portmap.address = cfg.portmap.address || '0.0.0.0'; cfg.portmap.port = cfg.portmap.port || 111; // Use the system's portmapper function register_with_pmap() { // The Linux portmapper normally rejects requests that are not // made to the loopback address. cfg.portmap.url = util.format('udp://127.0.0.1:%d', cfg.portmap.port); var pmapclient = app.createPortmapClient(cfg.portmap); pmapclient.on('error', function (e) { log.fatal(e, 'unable to connect to the system`s portmapper'); process.exit(1); }); pmapclient.once('connect', function () { pmapclient.set(mntmapping, function (err1) { if (err1) { log.fatal(err1, 'unable to register mountd with the portmapper'); process.exit(1); } pmapclient.set(nfsmapping, function (err2) { if (err2) { log.fatal(err2, 'unable to register nfsd with the portmapper'); process.exit(1); } pmapclient.close(); run_servers(cfg.log, cfg.mount, cfg.nfs); }); }); }); } if (cfg.portmap.usehost) { register_with_pmap(); } else { // Here we run our own portmapper var pmapd = app.createPortmapServer(cfg.portmap); pmapd.on('error', function (e) { if (e.code == 'EADDRINUSE') { log.info('Portmapper running, registering there...'); cfg.portmap.usehost = 1; register_with_pmap(); } else { log.fatal(e, 'unable to run the portmapper'); process.exit(1); } }); pmapd.listen(cfg.portmap.port, cfg.portmap.address, function () { run_servers(cfg.log, cfg.mount, cfg.nfs); }); } }); })();
mpl-2.0
UK992/servo
tests/wpt/web-platform-tests/fetch/cross-origin-resource-policy/fetch.https.any.js
3087
// META: global=window,worker // META: script=/common/get-host-info.sub.js const host = get_host_info(); const path = "/fetch/cross-origin-resource-policy/"; const localBaseURL = host.HTTPS_ORIGIN + path; const notSameSiteBaseURL = host.HTTPS_NOTSAMESITE_ORIGIN + path; promise_test(async () => { const response = await fetch("./resources/hello.py?corp=same-origin"); assert_equals(await response.text(), "hello"); }, "Same-origin fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header."); promise_test(async () => { const response = await fetch("./resources/hello.py?corp=same-site"); assert_equals(await response.text(), "hello"); }, "Same-origin fetch with a 'Cross-Origin-Resource-Policy: same-site' response header."); promise_test(async (test) => { const response = await fetch(notSameSiteBaseURL + "resources/hello.py?corp=same-origin"); assert_equals(await response.text(), "hello"); }, "Cross-origin cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header."); promise_test(async (test) => { const response = await fetch(notSameSiteBaseURL + "resources/hello.py?corp=same-site"); assert_equals(await response.text(), "hello"); }, "Cross-origin cors fetch with a 'Cross-Origin-Resource-Policy: same-site' response header."); promise_test((test) => { const remoteURL = notSameSiteBaseURL + "resources/hello.py?corp=same-origin"; return promise_rejects_js(test, TypeError, fetch(remoteURL, { mode : "no-cors" })); }, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header."); promise_test((test) => { const remoteURL = notSameSiteBaseURL + "resources/hello.py?corp=same-site"; return promise_rejects_js(test, TypeError, fetch(remoteURL, { mode: "no-cors" })); }, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-site' response header."); promise_test((test) => { const finalURL = notSameSiteBaseURL + "resources/hello.py?corp=same-origin"; return promise_rejects_js(test, TypeError, fetch("resources/redirect.py?redirectTo=" + encodeURIComponent(finalURL), { mode: "no-cors" })); }, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header after a redirection."); promise_test((test) => { const finalURL = localBaseURL + "resources/hello.py?corp=same-origin"; return fetch(notSameSiteBaseURL + "resources/redirect.py?redirectTo=" + encodeURIComponent(finalURL), { mode: "no-cors" }); }, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' response header after a cross-origin redirection."); promise_test(async (test) => { const finalURL = localBaseURL + "resources/hello.py?corp=same-origin"; await fetch(finalURL, { mode: "no-cors" }); return promise_rejects_js(test, TypeError, fetch(notSameSiteBaseURL + "resources/redirect.py?corp=same-origin&redirectTo=" + encodeURIComponent(finalURL), { mode: "no-cors" })); }, "Cross-origin no-cors fetch with a 'Cross-Origin-Resource-Policy: same-origin' redirect response header.");
mpl-2.0
Yukarumya/Yukarum-Redfoxes
dom/system/gonk/tests/test_ril_worker_ssn.js
3032
/* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this); function run_test() { run_next_test(); } add_test(function test_notification() { let workerHelper = newInterceptWorker(); let worker = workerHelper.worker; let context = worker.ContextPool._contexts[0]; function Call(callIndex, number) { this.callIndex = callIndex; this.number = number; } Call.prototype = { // Should use CALL_STATE_ACTIVE. // Any new outgoing call (state = dialing or alerting) will be drop if there // is no pending outgoing call created before. state: CALL_STATE_ACTIVE, //callIndex: 0, toa: 0, isMpty: false, isMT: false, als: 0, isVoice: true, isVoicePrivacy: false, //number: null, numberPresentation: 0, name: null, namePresentation: 0, uusInfo: null }; let oneCall = { 0: new Call(0, '00000') }; let twoCalls = { 0: new Call(0, '00000'), 1: new Call(1, '11111') }; function testNotification(calls, code, number, resultNotification) { let testInfo = {calls: calls, code: code, number: number, resultNotification: resultNotification}; do_print('Test case info: ' + JSON.stringify(testInfo)); // Set current calls. context.RIL.sendChromeMessage({ rilMessageType: "currentCalls", calls: calls }); let notificationInfo = { notificationType: 1, // MT code: code, index: 0, type: 0, number: number }; context.RIL._processSuppSvcNotification(notificationInfo); let postedMessage = workerHelper.postedMessage; equal(postedMessage.rilMessageType, 'suppSvcNotification'); equal(postedMessage.number, number); equal(postedMessage.notification, resultNotification); // Clear all existed calls. context.RIL.sendChromeMessage({ rilMessageType: "currentCalls", calls: {} }); } testNotification(oneCall, SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD, null, GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD); testNotification(oneCall, SUPP_SVC_NOTIFICATION_CODE2_RETRIEVED, null, GECKO_SUPP_SVC_NOTIFICATION_REMOTE_RESUMED); testNotification(twoCalls, SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD, null, GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD); testNotification(twoCalls, SUPP_SVC_NOTIFICATION_CODE2_RETRIEVED, null, GECKO_SUPP_SVC_NOTIFICATION_REMOTE_RESUMED); testNotification(twoCalls, SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD, '00000', GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD); testNotification(twoCalls, SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD, '11111', GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD); testNotification(twoCalls, SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD, '22222', GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD); run_next_test(); });
mpl-2.0
Sparfel/iTop-s-Portal
public/setup/scripts/testWebSrv.php
4394
<?php defined('__DIR__') || define('__DIR__', dirname(__FILE__)); defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(__DIR__ . '/../../../application')); $checklist = array(); include_once __DIR__ . '/../class/Check.php'; $check = new Check(); $check->check(); //$check->checkCfg(2); echo '<div id="progress"style="width:300px;border:1px solid #ccc;"></div>'; echo '<div id="informationdb" style="width"></div>'; include_once __DIR__ . '/../../../library/Centurion/Config/Directory.php'; include_once __DIR__ . '/../../../library/Centurion/Iterator/Directory.php'; include_once __DIR__ . '/../../../library/Zend/Config/Ini.php'; //$config = Centurion_Config_Directory::loadConfig(__DIR__ . '/../../../application/configs', getenv('APPLICATION_ENV')); $config = Centurion_Config_Directory::loadConfig(__DIR__ . '/../../../application/configs', 'production'); include_once __DIR__ . '/../../../library/Zend/Application/Resource/Db.php'; include_once __DIR__ . '/../../../library/Zend/Db.php'; $AWebSrvParam = Array(); for ($noItop = 1; $noItop <=2; $noItop++) { //error_log('iTop n°'.$noItop); $AWebSrvParam[$noItop]['protocol'] =$config['itop'.$noItop]['url']['protocol']; $AWebSrvParam[$noItop]['adress'] = $config['itop'.$noItop]['url']['adress']; $AWebSrvParam[$noItop]['username'] = $config['itop'.$noItop]['webservice']['user']; $AWebSrvParam[$noItop]['password'] = $config['itop'.$noItop]['webservice']['pwd']; $AWebSrvParam[$noItop]['url'] = $AWebSrvParam[$noItop]['protocol'].'://'.$AWebSrvParam[$noItop]['adress'].'/webservices/rest.php?version=1.0'; } $success = true; $total = count($AWebSrvParam); $i = 0; foreach($AWebSrvParam as $webSrv) { $aData = array('operation' => 'list_operations'); $aPostData = array( 'auth_user' => $webSrv['username'], 'auth_pwd' => $webSrv['password'], 'json_data' => json_encode($aData), ); try { $curl = curl_init(); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($aPostData)); curl_setopt($curl, CURLOPT_URL, $webSrv['url']); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_VERBOSE, true); $percent = intval($i/$total * 100)."%"; $sResult = curl_exec($curl); $aResult = @json_decode($sResult, true /* bAssoc */); if ($aResult == null) { $Ares[$i] = 'error'; $success = false; } else { if ($aResult['code'] == 0) { $Ares[$i] = 'ok'; $success = false; } else { $Ares[$i] = 'error'; $success = false; } } echo '<script language="javascript"> document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background:url(\'./images/orange-progress.gif\') repeat; height:10px;\">&nbsp;</div>"; document.getElementById("informationdb").innerHTML="<p>Database import in progress : '.$percent.' completed.</p>"; </script>'; $i++; } catch (Exception $e) { //throw $e; error_log($e->getCode().' - '.$e->getMessage()); $Ares[$i] = 'error'; $success= false; $next_step = false; //break; } } //Finalize to 100% and show the result if ($success) { $percent = '100%'; echo '<script language="javascript"> document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd; \">&nbsp;</div>"; document.getElementById("informationdb").innerHTML="<p>'.$percent.' completed.</p>"; document.getElementById("display_import").style = "hidden"; </script></p>'; $next_step = true; } else //One or more Webservice are not OK { if (!(isset($msg))) { $msg =''; $no = 1; $webSrvPb = 0; foreach($Ares as $res) { if ($res == 'ok') { $msg .= '<li class="tipsyauto" title="WebService n°'.$no.'"> <span class="ui-icon ui-icon-bluelight ui-icon-check"></span> The Webservice '.$no.' is OK </li>'; } else { $msg .= '<li class="red tipsyauto" title="WebService n°'.$no.'"> <span class="ui-icon ui-icon-red ui-icon-alert"></span> The Webservice '.$no.' is not OK </li>'; $webSrvPb++; } $no++; } if ($webSrvPb == count($Ares)) { $next_step = false;} else {$next_step = true;} // if only one Webservice is Ok, we allow to get further } $res = array('msg' =>$msg,'next_step' => $next_step); echo 'ERROR'.json_encode($res); } ?>
agpl-3.0
o2oa/o2oa
o2server/x_processplatform_assemble_surface/src/main/java/com/x/processplatform/assemble/surface/jaxrs/serialnumber/SerialNumberAction.java
6107
package com.x.processplatform.assemble.surface.jaxrs.serialnumber; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import com.google.gson.JsonElement; import com.x.base.core.project.annotation.JaxrsDescribe; import com.x.base.core.project.annotation.JaxrsMethodDescribe; import com.x.base.core.project.annotation.JaxrsParameterDescribe; import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.base.core.project.http.HttpMediaType; import com.x.base.core.project.jaxrs.ResponseFactory; import com.x.base.core.project.jaxrs.StandardJaxrsAction; import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; @Path("serialnumber") @JaxrsDescribe("流水号操作") public class SerialNumberAction extends StandardJaxrsAction { private static Logger logger = LoggerFactory.getLogger(SerialNumberAction.class); @JaxrsMethodDescribe(value = "列示指定应用的所有SerialNumber对象.", action = ActionList.class) @GET @Path("list/application/{applicationFlag}") @Produces(HttpMediaType.APPLICATION_JSON_UTF_8) @Consumes(MediaType.APPLICATION_JSON) public void list(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request, @JaxrsParameterDescribe("应用标识") @PathParam("applicationFlag") String applicationFlag) { ActionResult<List<ActionList.Wo>> result = new ActionResult<>(); EffectivePerson effectivePerson = this.effectivePerson(request); try { result = new ActionList().execute(effectivePerson, applicationFlag); } catch (Exception e) { logger.error(e, effectivePerson, request, null); result.error(e); } asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result)); } @JaxrsMethodDescribe(value = "获取SerialNumber内容,", action = ActionGet.class) @GET @Path("{id}") @Produces(HttpMediaType.APPLICATION_JSON_UTF_8) @Consumes(MediaType.APPLICATION_JSON) public void get(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request, @JaxrsParameterDescribe("标识") @PathParam("id") String id) { ActionResult<ActionGet.Wo> result = new ActionResult<>(); EffectivePerson effectivePerson = this.effectivePerson(request); try { result = new ActionGet().execute(effectivePerson, id); } catch (Exception e) { logger.error(e, effectivePerson, request, null); result.error(e); } asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result)); } @JaxrsMethodDescribe(value = "更新SerialNumber内容.", action = ActionUpdate.class) @PUT @Path("{id}") @Produces(HttpMediaType.APPLICATION_JSON_UTF_8) @Consumes(MediaType.APPLICATION_JSON) public void update(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request, @JaxrsParameterDescribe("标识") @PathParam("id") String id, JsonElement jsonElement) { ActionResult<ActionUpdate.Wo> result = new ActionResult<>(); EffectivePerson effectivePerson = this.effectivePerson(request); try { result = new ActionUpdate().execute(effectivePerson, id, jsonElement); } catch (Exception e) { logger.error(e, effectivePerson, request, null); result.error(e); } asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result, jsonElement)); } @JaxrsMethodDescribe(value = "Mock Post To Put.", action = ActionUpdate.class) @POST @Path("{id}/mockputtopost") @Produces(HttpMediaType.APPLICATION_JSON_UTF_8) @Consumes(MediaType.APPLICATION_JSON) public void updateMockPutToPost(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request, @JaxrsParameterDescribe("标识") @PathParam("id") String id, JsonElement jsonElement) { ActionResult<ActionUpdate.Wo> result = new ActionResult<>(); EffectivePerson effectivePerson = this.effectivePerson(request); try { result = new ActionUpdate().execute(effectivePerson, id, jsonElement); } catch (Exception e) { logger.error(e, effectivePerson, request, null); result.error(e); } asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result, jsonElement)); } @JaxrsMethodDescribe(value = "删除SerialNumber内容.", action = ActionRemove.class) @DELETE @Path("{id}") @Produces(HttpMediaType.APPLICATION_JSON_UTF_8) @Consumes(MediaType.APPLICATION_JSON) public void delete(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request, @JaxrsParameterDescribe("标识") @PathParam("id") String id) { ActionResult<ActionRemove.Wo> result = new ActionResult<>(); EffectivePerson effectivePerson = this.effectivePerson(request); try { result = new ActionRemove().execute(effectivePerson, id); } catch (Exception e) { logger.error(e, effectivePerson, request, null); result.error(e); } asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result)); } @JaxrsMethodDescribe(value = "Mock Get To Delete.", action = ActionRemove.class) @GET @Path("{id}/mockdeletetoget") @Produces(HttpMediaType.APPLICATION_JSON_UTF_8) @Consumes(MediaType.APPLICATION_JSON) public void deleteMockDeleteToGet(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request, @JaxrsParameterDescribe("标识") @PathParam("id") String id) { ActionResult<ActionRemove.Wo> result = new ActionResult<>(); EffectivePerson effectivePerson = this.effectivePerson(request); try { result = new ActionRemove().execute(effectivePerson, id); } catch (Exception e) { logger.error(e, effectivePerson, request, null); result.error(e); } asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result)); } }
agpl-3.0
daqingyun/probdata
src/fastprof/fastprof.cpp
5958
/*************************************************************************** * FastProf: A Stochastic Approximation-based Transport Profiler * All rights reserved - Daqing Yun <[email protected]> ***************************************************************************/ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> #include "fastprof.h" int f_ctrl_default(struct fastprof_ctrl * ctrl) { ctrl->role = F_UNKNOWN; memset(ctrl->local_ip, 0, F_HOSTADDR_LEN); memset(ctrl->remote_ip, 0, F_HOSTADDR_LEN); ctrl->tcp_port = -1; ctrl->udt_port = -1; ctrl->bw_bps = -1.0; ctrl->rtt_ms = -1.0; ctrl->mss = -1; ctrl->A_val = -1.0; ctrl->a_val = -1.0; ctrl->a_scale = 1.0; ctrl->c_val = -1.0; ctrl->c_scale = 1.0; ctrl->alpha = -1.0; ctrl->gamma = -1.0; ctrl->pgr = -1.0; ctrl->impeded_limit = -1; ctrl->max_limit = -1; ctrl->duration = F_DEFAULT_DURATION; return 0; } int f_ctrl_set_addr(struct fastprof_ctrl* ctrl, char* addr) { memcpy(ctrl->remote_ip, addr, strlen(addr)); ctrl->remote_ip[strlen(addr)] = '\0'; return 0; } double f_perturb() { return ( ( (double)rand() / (double)RAND_MAX ) > 0.5 ? (1.0) : (-1.0) ); } double f_round(double x) { return (floor( ((double)(x)) + 0.5 )); } double f_rand(int x, int y) { return (double)( (rand() % (y - x + 1)) + x ); } int f_get_currtime_str(char* tm_str) { time_t t; struct tm currtime; t = time(NULL); currtime = *localtime(&t); sprintf(tm_str, "%02d:%02d:%d:%02d:%02d:%02d", currtime.tm_mon + 1, currtime.tm_mday, currtime.tm_year + 1900, currtime.tm_hour, currtime.tm_min, currtime.tm_sec); return 0; } int f_m2m_db_search(FILE* f, struct mem_record* record_max, struct fastprof_ctrl* ctrl) { struct stat st = {0}; int ret = 0; char filename[128]; char readline[512]; struct mem_record record_tmp; if (stat(F_DEFAULT_M2M_FOLDER, &st) == -1) { mkdir(F_DEFAULT_M2M_FOLDER, 0700); F_LOG(F_HINT, "profile folder <%s> created", F_DEFAULT_M2M_FOLDER); return -1; } else { F_LOG(F_HINT, "profile folder <%s> exists", F_DEFAULT_M2M_FOLDER); } if (!f) { sprintf(filename, "%s/%s_%s.PROF", F_DEFAULT_M2M_FOLDER, ctrl->local_ip, ctrl->remote_ip); F_LOG(F_PERF, " FILE: %s", filename); f = fopen(filename, "a+"); if (f == NULL) { printf("file open error\n"); return -1; } } record_max->average_perf = -1.0; while (!feof(f)) { memset(readline, '\0', 512); // memset(&record_tmp, '\0', sizeof(struct mem_record)); fgets(readline, 512, f); if (readline[0] == '\n' || readline[0] == '\t' || readline[0] == ' ' || readline[0] == '\0' || readline[0] == '#') { continue; } ret = sscanf(readline, MEM_RECORD_FORMAT_LABEL, (record_tmp.src_ip), (record_tmp.dst_ip), (record_tmp.curr_time), (record_tmp.protocol_name), (record_tmp.toolkit_name), &(record_tmp.num_streams), &(record_tmp.mss_size), &(record_tmp.buffer_size), (record_tmp.buffer_size_unit), &(record_tmp.block_size), (record_tmp.block_size_unit), &(record_tmp.duration), (record_tmp.duration_unit), &(record_tmp.trans_size), (record_tmp.trans_size_unit), &(record_tmp.average_perf), (record_tmp.average_perf_unit)); if (ret != MEM_RECORD_NUM_ELEMENTS) { F_LOG(F_HINT, "parsing error - %d elements are captured", ret); return -1; } if (record_tmp.average_perf > record_max->average_perf) { memcpy(record_max, &record_tmp, sizeof(struct mem_record)); } } if (record_max->average_perf < 0) { return -1; } fclose(f); return 0; } int f_print_m2m_record(struct mem_record *record) { F_LOG(F_PERF, " SrcIP: %s\n" " DstIP: %s\n" " Time: %s\n" " Protocol: %s\n" " Toolkit: %s\n" " Stream#: %d\n" " MSS(PktSize): %d\n" " BufferSize: %d%s\n" " BlockSize: %d%s\n" " Duration: %d%s\n" " TransferSize: %lld%s\n" " AvgPerf: %lf%s", record->src_ip, record->dst_ip, record->curr_time, record->protocol_name, record->toolkit_name, record->num_streams, record->mss_size, record->buffer_size, record->buffer_size_unit, record->block_size, record->block_size_unit, record->duration, record->duration_unit, record->trans_size, record->trans_size_unit, record->average_perf, record->average_perf_unit); return 0; } double f_estimate_rtt(char* hostaddr) { unsigned int ret = -1; double min_rtt_ms = -1.0; double avg_rtt_ms = -1.0; double max_rtt_ms = -1.0; double mdev_rtt_ms = -1.0; char format_cmd[128]; std::string output_str; FILE * stream; const int max_buffer = 512; char buffer[max_buffer]; sprintf(format_cmd, "/bin/ping -w 6 -c 5 %s", hostaddr); std::string cmd(format_cmd); cmd.append(" 2>&1"); stream = popen(cmd.c_str(), "r"); if (stream) { while (!feof(stream)) { if (fgets(buffer, max_buffer, stream) != NULL) { output_str.append(buffer); } } pclose(stream); } else { return -1.0; } // now parsing the output if ((unsigned int)(ret = output_str.find(std::string("mdev"), 0)) == std::string::npos) { return -1; } else { // printf("%s\n", output_str.c_str()); // printf("%s\n", output_str.substr(ret, std::string::npos).c_str()); // mdev = 0.030/0.043/0.066/0.014 ms sscanf(output_str.substr(ret, std::string::npos).c_str(), "mdev = %lf/%lf/%lf/%lf ms", &min_rtt_ms, &avg_rtt_ms, &max_rtt_ms, &mdev_rtt_ms); } return avg_rtt_ms; }
agpl-3.0
fayazkhan/secret-diary
diary/cli.py
2293
# secret-diary: A secure diary app # Copyright (C) 2016 Fayaz Yusuf Khan # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # 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 Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Fayaz's diary. Usage: diary show <file> diary write <file> [--message=<message>] [--create] diary server <file> Options: -h --help Show this screen. --version Show version. -m MESSAGE --message=MESSAGE Message to add. -c --create Create tables if they don't exist. """ from getpass import getpass import sys import arrow from docopt import docopt from diary import ( application_factory, Base, create_entry, create_database_session, Entry) def main(): arguments = docopt(__doc__, version="Fayaz's diary 2.0") file = arguments['<file>'] password = getpass(prompt='Database password: ') session = create_database_session(file, password) if arguments['show']: show(session) elif arguments['write']: if arguments['--create']: Base.metadata.create_all(bind=session) if arguments['--message']: create_entry(session, message=arguments['--message']) else: write_from_buffer(session, sys.stdin) elif arguments['server']: app = application_factory() app.run() def write_from_buffer(session, buffer): entry = create_entry(session) for line in buffer: entry.content += line entry.updated = arrow.utcnow() session.commit() def show(session): for entry in session.query(Entry): display_row(entry.updated.humanize(), entry.content) def display_row(time, text): print(time, text)
agpl-3.0
oeoeaio/openfoodnetwork
spec/controllers/spree/admin/reports_controller_spec.rb
12354
require 'spec_helper' describe Spree::Admin::ReportsController, type: :controller do # Given two distributors and two suppliers let(:bill_address) { create(:address) } let(:ship_address) { create(:address) } let(:instructions) { "pick up on thursday please" } let(:coordinator1) { create(:distributor_enterprise) } let(:coordinator2) { create(:distributor_enterprise) } let(:supplier1) { create(:supplier_enterprise) } let(:supplier2) { create(:supplier_enterprise) } let(:supplier3) { create(:supplier_enterprise) } let(:distributor1) { create(:distributor_enterprise) } let(:distributor2) { create(:distributor_enterprise) } let(:distributor3) { create(:distributor_enterprise) } let(:product1) { create(:product, price: 12.34, distributors: [distributor1], supplier: supplier1) } let(:product2) { create(:product, price: 23.45, distributors: [distributor2], supplier: supplier2) } let(:product3) { create(:product, price: 34.56, distributors: [distributor3], supplier: supplier3) } # Given two order cycles with both distributors let(:ocA) { create(:simple_order_cycle, coordinator: coordinator1, distributors: [distributor1, distributor2], suppliers: [supplier1, supplier2, supplier3], variants: [product1.master, product3.master]) } let(:ocB) { create(:simple_order_cycle, coordinator: coordinator2, distributors: [distributor1, distributor2], suppliers: [supplier1, supplier2, supplier3], variants: [product2.master]) } # orderA1 can only be accessed by supplier1, supplier3 and distributor1 let(:orderA1) do order = create(:order, distributor: distributor1, bill_address: bill_address, ship_address: ship_address, special_instructions: instructions, order_cycle: ocA) order.line_items << create(:line_item, variant: product1.master) order.line_items << create(:line_item, variant: product3.master) order.finalize! order.save order end # orderA2 can only be accessed by supplier2 and distributor2 let(:orderA2) do order = create(:order, distributor: distributor2, bill_address: bill_address, ship_address: ship_address, special_instructions: instructions, order_cycle: ocA) order.line_items << create(:line_item, variant: product2.master) order.finalize! order.save order end # orderB1 can only be accessed by supplier1, supplier3 and distributor1 let(:orderB1) do order = create(:order, distributor: distributor1, bill_address: bill_address, ship_address: ship_address, special_instructions: instructions, order_cycle: ocB) order.line_items << create(:line_item, variant: product1.master) order.line_items << create(:line_item, variant: product3.master) order.finalize! order.save order end # orderB2 can only be accessed by supplier2 and distributor2 let(:orderB2) do order = create(:order, distributor: distributor2, bill_address: bill_address, ship_address: ship_address, special_instructions: instructions, order_cycle: ocB) order.line_items << create(:line_item, variant: product2.master) order.finalize! order.save order end # Results let(:resulting_orders_prelim) { assigns(:report).search.result } let(:resulting_orders) { assigns(:report).table_items.map(&:order) } let(:resulting_products) { assigns(:report).table_items.map(&:product) } # As manager of a coordinator (coordinator1) context "Coordinator Enterprise User" do let!(:present_objects) { [orderA1, orderA2, orderB1, orderB2] } before { login_as_enterprise_user [coordinator1] } describe 'Orders & Fulfillment' do it "shows all orders in order cycles I coordinate" do spree_post :orders_and_fulfillment, {q: {}} expect(resulting_orders).to include orderA1, orderA2 expect(resulting_orders).not_to include orderB1, orderB2 end end end # As a Distributor Enterprise user for distributor1 context "Distributor Enterprise User" do before { login_as_enterprise_user [distributor1] } describe 'Orders and Distributors' do let!(:present_objects) { [orderA1, orderA2, orderB1, orderB2] } it "only shows orders that I have access to" do spree_post :orders_and_distributors expect(assigns(:search).result).to include(orderA1, orderB1) expect(assigns(:search).result).not_to include(orderA2) expect(assigns(:search).result).not_to include(orderB2) end end describe 'Bulk Coop' do let!(:present_objects) { [orderA1, orderA2, orderB1, orderB2] } it "only shows orders that I have access to" do spree_post :bulk_coop, {q: {}} expect(resulting_orders).to include(orderA1, orderB1) expect(resulting_orders).not_to include(orderA2) expect(resulting_orders).not_to include(orderB2) end end describe 'Payments' do let!(:present_objects) { [orderA1, orderA2, orderB1, orderB2] } it "only shows orders that I have access to" do spree_post :payments expect(resulting_orders_prelim).to include(orderA1, orderB1) expect(resulting_orders_prelim).not_to include(orderA2) expect(resulting_orders_prelim).not_to include(orderB2) end end describe 'Orders & Fulfillment' do context "with four orders" do let!(:present_objects) { [orderA1, orderA2, orderB1, orderB2] } it "only shows orders that I distribute" do spree_post :orders_and_fulfillment, {q: {}} expect(resulting_orders).to include orderA1, orderB1 expect(resulting_orders).not_to include orderA2, orderB2 end end context "with two orders" do let!(:present_objects) { [orderA1, orderB1] } it "only shows the selected order cycle" do spree_post :orders_and_fulfillment, q: {order_cycle_id_in: [ocA.id.to_s]} expect(resulting_orders).to include(orderA1) expect(resulting_orders).not_to include(orderB1) end end end end # As a Supplier Enterprise user for supplier1 context "Supplier" do before { login_as_enterprise_user [supplier1] } describe 'index' do it "loads reports relevant to producers" do spree_get :index report_types = assigns(:reports).keys expect(report_types).to include "orders_and_fulfillment", "products_and_inventory", "packing" # and others expect(report_types).to_not include "sales_tax" end end describe 'Bulk Coop' do context "where I have granted P-OC to the distributor" do let!(:present_objects) { [orderA1, orderA2] } before do create(:enterprise_relationship, parent: supplier1, child: distributor1, permissions_list: [:add_to_order_cycle]) end it "only shows product line items that I am supplying" do spree_post :bulk_coop, {q: {}} expect(resulting_products).to include product1 expect(resulting_products).not_to include product2, product3 end end context "where I have not granted P-OC to the distributor" do it "shows product line items that I am supplying" do spree_post :bulk_coop expect(resulting_products).not_to include product1, product2, product3 end end end describe 'Orders & Fulfillment' do let!(:present_objects) { [orderA1, orderA2] } context "where I have granted P-OC to the distributor" do before do create(:enterprise_relationship, parent: supplier1, child: distributor1, permissions_list: [:add_to_order_cycle]) end it "only shows product line items that I am supplying" do spree_post :orders_and_fulfillment, {q: {}} expect(resulting_products).to include product1 expect(resulting_products).not_to include product2, product3 end it "only shows the selected order cycle" do spree_post :orders_and_fulfillment, q: {order_cycle_id_eq: ocA.id} expect(resulting_orders_prelim).to include(orderA1) expect(resulting_orders_prelim).not_to include(orderB1) end end context "where I have not granted P-OC to the distributor" do it "does not show me line_items I supply" do spree_post :orders_and_fulfillment expect(resulting_products).not_to include product1, product2, product3 end end end end context "Products & Inventory" do before { login_as_admin } context "with distributors and suppliers" do let(:distributors) { [coordinator1, distributor1, distributor2] } let(:suppliers) { [supplier1, supplier2] } let!(:present_objects) { [distributors, suppliers] } it "should build distributors for the current user" do spree_get :products_and_inventory expect(assigns(:distributors)).to match_array distributors end it "builds suppliers for the current user" do spree_get :products_and_inventory expect(assigns(:suppliers)).to match_array suppliers end end context "with order cycles" do let!(:order_cycles) { [ocA, ocB] } it "builds order cycles for the current user" do spree_get :products_and_inventory expect(assigns(:order_cycles)).to match_array order_cycles end end it "assigns report types" do spree_get :products_and_inventory expect(assigns(:report_types)).to eq(subject.report_types[:products_and_inventory]) end it "creates a ProductAndInventoryReport" do expect(OpenFoodNetwork::ProductsAndInventoryReport).to receive(:new) .with(@admin_user, {"test" => "foo", "controller" => "spree/admin/reports", "action" => "products_and_inventory"}, false) .and_return(report = double(:report)) allow(report).to receive(:header).and_return [] allow(report).to receive(:table).and_return [] spree_get :products_and_inventory, test: "foo" expect(assigns(:report)).to eq(report) end end context "My Customers" do before { login_as_admin } it "should have report types for customers" do expect(subject.report_types[:customers]).to eq([ ["Mailing List", :mailing_list], ["Addresses", :addresses] ]) end context "with distributors and suppliers" do let(:distributors) { [coordinator1, distributor1, distributor2] } let(:suppliers) { [supplier1, supplier2] } let!(:present_objects) { [distributors, suppliers] } it "should build distributors for the current user" do spree_get :customers expect(assigns(:distributors)).to match_array distributors end it "builds suppliers for the current user" do spree_get :customers expect(assigns(:suppliers)).to match_array suppliers end end context "with order cycles" do let!(:order_cycles) { [ocA, ocB] } it "builds order cycles for the current user" do spree_get :customers expect(assigns(:order_cycles)).to match_array order_cycles end end it "assigns report types" do spree_get :customers expect(assigns(:report_types)).to eq(subject.report_types[:customers]) end it "creates a CustomersReport" do expect(OpenFoodNetwork::CustomersReport).to receive(:new) .with(@admin_user, {"test" => "foo", "controller" => "spree/admin/reports", "action" => "customers"}, false) .and_return(report = double(:report)) allow(report).to receive(:header).and_return [] allow(report).to receive(:table).and_return [] spree_get :customers, test: "foo" expect(assigns(:report)).to eq(report) end end context "Admin" do before { login_as_admin } describe "users_and_enterprises" do let!(:present_objects) { [coordinator1] } it "shows report search forms" do spree_get :users_and_enterprises expect(assigns(:report).table).to eq [] end it "shows report data" do spree_post :users_and_enterprises, {q: {}} expect(assigns(:report).table.empty?).to be false end end describe "sales_tax" do it "shows report search forms" do spree_get :sales_tax expect(assigns(:report).table).to eq [] end end end end
agpl-3.0
qliavi/asteroids
run/js/Particle.js
1076
function Particle (x, y, speedX, speedY, radius) { var randomAngle = Math.random() * Math.PI * 2, multiplier = 0.008 * radius x += Math.cos(randomAngle) * multiplier y += Math.sin(randomAngle) * multiplier var randomAngle = Math.random() * Math.PI * 2, multiplier = 0.0017 * Math.pow(radius, 0.2) speedX += Math.cos(randomAngle) * multiplier, speedY += Math.sin(randomAngle) * multiplier var maxLife = Math.ceil(radius * 20), life = maxLife, fadeLife = Math.ceil(life / 3) radius *= 0.0015 return { paint: function (c, scale) { c.save() c.translate(x * scale, y * scale) if (life < fadeLife) c.globalAlpha = life / fadeLife c.beginPath() c.arc(0, 0, radius * scale * life / maxLife, 0, Math.PI * 2) c.fillStyle = '#fff' c.fill() c.restore() }, tick: function () { x += speedX y += speedY life-- return life }, } }
agpl-3.0
stratosphereips/Manati
manati/analysis_sessions/models/base.py
688
# Copyright (C) 2016-2018 Stratosphere Lab # This file is part of ManaTI Project - https://stratosphereips.org # See the file 'docs/LICENSE' for copying permission. # Created by Raul B. Netto <[email protected]> on 8/25/18. from django.db import models from model_utils.fields import AutoCreatedField, AutoLastModifiedField from django.utils.translation import ugettext_lazy as _ class TimeStampedModel(models.Model): """ An abstract base class model that provides self-updating ``created`` and ``modified`` fields. """ created_at = AutoCreatedField(_('created_at')) updated_at = AutoLastModifiedField(_('updated_at')) class Meta: abstract = True
agpl-3.0
UM-USElab/gradecraft-development
app/controllers/api/rubrics_controller.rb
321
class API::RubricsController < ApplicationController # GET api/rubric/:id def show @rubric = Rubric.find params[:id] @criteria = @rubric.criteria.ordered.includes(:levels) @levels = Level.where(criterion_id: @criteria.pluck(:id)).order("criterion_id").order("points").order("sort_order") end end
agpl-3.0
Tatwi/legend-of-hondo
MMOCoreORB/bin/scripts/object/tangible/lair/base/poi_all_lair_nest_large_evil_fire_green.lua
2363
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --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 Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_lair_base_poi_all_lair_nest_large_evil_fire_green = object_tangible_lair_base_shared_poi_all_lair_nest_large_evil_fire_green:new { objectMenuComponent = "LairMenuComponent", } ObjectTemplates:addTemplate(object_tangible_lair_base_poi_all_lair_nest_large_evil_fire_green, "object/tangible/lair/base/poi_all_lair_nest_large_evil_fire_green.iff")
agpl-3.0
sakukode/owncloud-custom
100
OC.L10N.register( "core", { "Password" : "Passcode" }, "nplurals=2; plural=(n != 1);");
agpl-3.0
vvfosprojects/sovvf
src/backend/SO115App.ApiGac/Models/MezzoDTO.cs
2492
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SO115App.ApiGac.Models { public class MezzoDTO { /// <summary> /// Codice del mezzo /// </summary> public string Codice { get; set; } /// <summary> /// Codice del radio trasmittente /// </summary> public string IdRadio { get; set; } /// <summary> /// Codice della sim per il sistema di tracking /// </summary> public string ICCID { get; set; } /// <summary> /// Descrizione del mezzo /// </summary> public string Descrizione { get; set; } /// <summary> /// Genere del mezzo /// </summary> public string Genere { get; set; } /// <summary> /// Stato del mezzo /// </summary> public Movimentazione Movimentazione { get; set; } /// <summary> /// Appartenenza del mezzo /// </summary> public int Appartenenza { get; set; } /// <summary> /// Indica il distaccamento del mezzo /// </summary> public Sede Distaccamento { get; set; } /// <summary> /// Descrizione dell'appartenenza del mezzo /// </summary> public string DescrizioneAppartenenza { get; set; } /// <summary> /// Descrizione dello stato del mezzo /// </summary> public string DescrizioneStato { get; set; } /// <summary> /// Stato efficenza del mezzo /// </summary> public int StatoEfficenza { get; set; } /// <summary> /// Descrizione dello Stato efficenza del mezzo /// </summary> public string DescrizioneStatoEfficenza { get; set; } /// <summary> /// Indica il livello del carburante del mezzo /// </summary> public int LivelloCarburante { get; set; } /// <summary> /// descrive il livello del carburante del mezzo /// </summary> public string DescrizioneLivelloCarburante { get; set; } /// <summary> /// Indica il livello dell'estinguente del mezzo /// </summary> public int LivelloEstinguente { get; set; } /// <summary> /// descrive il livello dell'estinguente del mezzo /// </summary> public string DescrizioneLivelloEstinguente { get; set; } } }
agpl-3.0
HoBu4eK/easypcfix
includes/classes/PHPFusion/Errors.php
25777
<?php namespace PHPFusion; use PHPFusion\Database\DatabaseFactory; class Errors { private static $instances = array(); public $no_notice = 0; public $compressed = 0; private $error_status = ''; private $posted_error_id = ''; private $delete_status = ''; private $rows = 0; private $rowstart = ''; private $error_id = ''; private $errors = array(); private $new_errors = array(); private $locale = array(); public static function getInstance($key = 'default') { if (!isset(self::$instances[$key])) { self::$instances[$key] = new static(); } return self::$instances[$key]; } public function __construct() { if (empty($this->locale)) { global $locale; include LOCALE.LOCALESET."admin/errors.php"; include LOCALE.LOCALESET."errors.php"; $this->locale += $locale; } $this->error_status = filter_input(INPUT_POST, 'error_status', FILTER_VALIDATE_INT, array('min_range' => 0, 'max_range' => 2)); $this->posted_error_id = filter_input(INPUT_POST, 'error_id', FILTER_VALIDATE_INT); $this->delete_status = filter_input(INPUT_POST, 'delete_status', FILTER_VALIDATE_INT, array('min_range' => 0, 'max_range' => 2)); $this->rowstart = filter_input(INPUT_GET, 'rowstart', FILTER_VALIDATE_INT) ? : 0; $this->error_id = filter_input(INPUT_GET, 'error_id', FILTER_VALIDATE_INT); if (isnum($this->error_status) && $this->posted_error_id) { dbquery("UPDATE ".DB_ERRORS." SET error_status='".$this->error_status."' WHERE error_id='".$this->posted_error_id."'"); redirect(FUSION_REQUEST); } if (isset($_POST['delete_entries']) && isnum($this->delete_status)) { dbquery("DELETE FROM ".DB_ERRORS." WHERE error_status='".$_POST['delete_status']."'"); $source_redirection_path = preg_replace("~".fusion_get_settings("site_path")."~","",FUSION_REQUEST,1); redirect(fusion_get_settings("siteurl").$source_redirection_path); } $result = dbquery("SELECT * FROM ".DB_ERRORS." ORDER BY error_timestamp DESC LIMIT ".$this->rowstart.",20"); while ($data = dbarray($result)) { $this->errors[$data['error_id']] = $data; } $this->rows = $this->errors ? dbcount('(error_id)', DB_ERRORS) : 0; } /** * Custom error handler for PHP processor * @param $error_level * @param $error_message * @param $error_file * @param $error_line * @param $error_context */ public function setError($error_level, $error_message, $error_file, $error_line, $error_context) { global $userdata; $showLiveError = TRUE; // directly show error - push to another instance $data = array(); $db = DatabaseFactory::getConnection(); $result = $db->query( "SELECT error_id, error_status FROM ".DB_ERRORS." WHERE error_message = :message AND error_file = :file AND error_line = :line AND error_status != '1' AND error_page = :page ORDER BY error_timestamp DESC LIMIT 1", array( ':message' => $error_message, ':file' => $error_file, ':page' => FUSION_REQUEST, ':line' => $error_line, )); if ($db->countRows($result) == 0) { $db->query("INSERT INTO ".DB_ERRORS." ( error_level, error_message, error_file, error_line, error_page, error_user_level, error_user_ip, error_user_ip_type, error_status, error_timestamp ) VALUES ( :level, :message, :file, :line, :page, '".$userdata['user_level']."', '".USER_IP."', '".USER_IP_TYPE."', '0', '".time()."' )", array( ':level' => $error_level, ':message' => $error_message, ':file' => $error_file, ':page' => FUSION_REQUEST, ':line' => $error_line, )); $errorId = $db->getLastId(); } else { $data = $db->fetchAssoc($result); $errorId = $data['error_id']; if ($data['error_status'] == 2) { $showLiveError = FALSE; } } if ($showLiveError) { $this->new_errors[$errorId] = array( "error_id" => $errorId, "error_level" => $error_level, "error_file" => $error_file, "error_line" => $error_line, "error_page" => FUSION_REQUEST, "error_message" => $error_message, "error_timestamp" => time(), "error_status" => 0, ); } } /** * Administration Console */ public function display_administration() { global $aidlink; $locale = $this->locale; define("NO_DEBUGGER", TRUE); $_GET['rowstart'] = isset($_GET['rowstart']) && isnum($_GET['rowstart']) ? $_GET['rowstart'] : 0; $tab_title['title'][0] = 'Errors'; $tab_title['id'][0] = 'errors-list'; $tab_title['icon'][0] = 'fa fa-bug m-r-10'; if ($this->error_id) { $tab_title['title'][1] = 'Error File'; $tab_title['id'][1] = 'error-file'; $tab_title['icon'][1] = 'fa fa-medkit m-r-10'; $tab_title['title'][2] = 'Source File'; $tab_title['id'][2] = 'src-file'; $tab_title['icon'][2] = 'fa fa-stethoscope m-r-10'; } $tab_active = tab_active($tab_title, $this->error_id ? 1 : 0); add_breadcrumb(array('link'=>ADMIN."errors.php".$aidlink, 'title'=>$locale['400'])); opentable($locale['400']); echo opentab($tab_title, $tab_active, 'error_tab'); echo opentabbody($tab_title['title'][0], $tab_title['id'][0], $tab_active); ?> <div class='m-t-20'><?php echo $this->getErrorLogs(); ?></div> <?php echo closetabbody(); if ($this->error_id) { // dump 1 and 2 add_to_head("<link rel='stylesheet' href='".THEMES."templates/errors.css' type='text/css' media='all' />"); define('no_debugger', 1); $data = dbarray(dbquery("SELECT * FROM ".DB_ERRORS." WHERE error_id='".$this->error_id."' LIMIT 1")); if (!$data) redirect(FUSION_SELF.$aidlink); $thisFileContent = is_file($data['error_file']) ? file($data['error_file']) : array(); $line_start = max($data['error_line']-10, 1); $line_end = min($data['error_line']+10, count($thisFileContent)); $output = implode("", array_slice($thisFileContent, $line_start-1, $line_end-$line_start+1)); $pageFilePath = BASEDIR.$data['error_page']; $pageContent = is_file($pageFilePath) ? file_get_contents($pageFilePath) : ''; add_to_jquery(" $('#error_status_sel').bind('change', function(e) { this.form.submit(); }); "); echo opentabbody($tab_title['title'][1], $tab_title['id'][1], $tab_active); ?> <div class='m-t-20'> <h2><?php echo $data['error_message'] ?></h2> <h3 style='border-bottom:0;' class='display-inline'><label class='label label-success'><?php echo $locale['415']." ".number_format($data['error_line']); ?></label> </h3> <div class='display-inline text-lighter'><strong><?php echo $locale['419'] ?></strong> -- <?php echo self::getMaxFolders(stripslashes($data['error_file']), 3); ?></div> <div class='m-t-10'> <div class='display-inline-block m-r-20'><i class='fa fa-file-code-o m-r-10'></i><strong class='m-r-10'><?php echo $locale['411'] ?></strong> -- <a href='<?php echo FUSION_SELF.$aidlink."&amp;rowstart=".$_GET['rowstart']."&amp;error_id=".$data['error_id'] ?>#page' title='<?php echo $data['error_page'] ?>'> <?php echo self::getMaxFolders($data['error_page'], 3); ?></a> </div> <span class='text-lighter'>generated by</span> <div class='alert alert-info display-inline-block p-t-0 p-b-0 text-smaller'> <strong><?php echo $locale['412']."-".$locale['416'] ?> <?php echo $data['error_user_level']; ?> -- <?php echo $locale['417']." ".$data['error_user_ip'] ?></strong> </div> <span class='text-lighter'><?php echo lcfirst($locale['on']) ?></span> <div class='alert alert-info display-inline-block p-t-0 p-b-0 text-smaller'><strong class='m-r-10'><?php echo showdate("longdate", $data['error_timestamp']) ?></strong></div> </div> <div class='m-t-10 display-inline-block' style='width:300px'> <?php echo openform('logform', 'post', FUSION_SELF.$aidlink."&amp;rowstart=".$_GET['rowstart']."&amp;error_id=".$data['error_id']."#file", array('max_tokens' => 1)); echo form_hidden('error_id', '', $data['error_id']); echo form_select('error_status', $locale['mark_as'], $data['error_status'], array("inline" => TRUE, "options" => self::get_logTypes())); echo closeform(); ?> </div> </div> <div class='m-t-10'> <?php openside('') ?> <table class='table table-responsive'> <tr> <td colspan='4' class='tbl2'><strong><?php echo $locale['421'] ?></strong> (<?php echo $locale['415']." ".$line_start." - ".$line_end ?>) </td> </tr> <tr> <td colspan='4'><?php echo self::printCode($output, $line_start, $data['error_line'], array('time' => $data['error_timestamp'], 'text' => $data['error_message'])) ?></td> </tr> </table> <?php closeside() ?> </div> <?php echo closetabbody(); echo opentabbody($tab_title['title'][2], $tab_title['id'][2], $tab_active); ?> <div class='m-t-10'> <?php openside('') ?> <table class='table table-responsive'> <tr> <td class='tbl2'><a name='page'></a> <strong><?php echo $locale['411'] ?> : <?php echo self::getMaxFolders($data['error_page'], 3) ?></strong> </td> </tr> <tr> <td><?php echo self::printCode($pageContent, "1") ?></td> </tr> </table> <?php closeside() ?> </div> <?php echo closetabbody(); } echo closetab(); closetable(); } /** Use this function to show error logs */ public function showFooterErrors() { $locale = $this->locale; $html = ""; if (iADMIN && checkrights("ERRO") && (count($this->errors) || count($this->new_errors)) && !defined("NO_DEBUGGER")) { global $aidlink; $html = "<i class='fa fa-bug fa-lg'></i></button><strong>\n"; $html .= str_replace(array("[ERROR_LOG_URL]", "[/ERROR_LOG_URL]"), array( "<a id='footer_debug' href='".ADMIN."errors.php".$aidlink."'>", "</a>" ), $locale['err_101']); $html .= "</strong><span class='badge m-l-10'>L: ".count($this->errors)."</span>\n"; $html .= "<span class='badge m-l-10'>N: ".count($this->new_errors)."</span>\n"; $cHtml = openmodal('tbody', 'Error Console', array('class' => 'modal-lg modal-center zindex-boost', 'button_id' => 'footer_debug')); $cHtml .= $this->getErrorLogs(); $cHtml .= closemodal(); add_to_footer($cHtml); } return $html; } /** * Displays error logs HTML * @return string */ private function getErrorLogs() { global $aidlink; $locale = $this->locale; $html = openform('error_logform', 'post', FUSION_REQUEST, array("class" => "text-center well m-t-5 m-b-5")); $html .= "<div class='display-inline-block text-right m-r-10'>".$locale['440']."</div>\n"; $html .= "<div class='display-inline-block'>\n"; $html .= form_select('delete_status', "", "", array("allowclear" => TRUE, "options" => self::get_logTypes(), "class"=>"m-b-10", "inline"=>TRUE)). form_button('delete_entries', $locale['453'], $locale['453'], array('class' => 'm-l-10 btn-primary')); $html .= "</div>\n"; $html .= closeform(); if (!empty($this->errors) or !empty($this->new_errors)) { $html .= "<a name='top'></a>\n"; $html .= "<table class='table table-responsive center'>"; $html .= "<tr>"; $html .= "<th class='col-xs-5'>".$locale['410']."</th>"; $html .= "<th>Options</th>"; $html .= "<th>".$locale['454']."</th>"; $html .= "<th class='col-xs-4'>".$locale['414']."</th>\n"; $html .= "</tr>\n"; if (!empty($this->errors)) { foreach ($this->errors as $i => $data) { $link = FUSION_SELF.$aidlink."&amp;rowstart=".$this->rowstart."&amp;error_id=".$data['error_id']."#file"; $file = $data['error_file']; $link_title = $this->getMaxFolders($data['error_file'], 2); $html .= "<tr id='rmd-".$data['error_id']."'>"; $html .= "<td>"; $html .= "<a href='".$link."' title='".$file."'>".$link_title."</a><br/>\n"; $html .= "<i>".$data['error_page']."</i><br/>\n"; $html .= "<small>".$data['error_message']."</small><br/>"; $html .= "<strong>".$locale['415']." ".$data['error_line']."</strong><br/>\n"; $html .= "<small>".timer($data['error_timestamp'])."</small>\n"; $html .= "</td><td>".$this->getGitsrc($data['error_file'], $data['error_line'])."</td>\n"; $html .= "<td>".$this->get_errorTypes($data['error_level'])."</td>\n"; $html .= "<td id='ecmd_".$data['error_id']."' style='white-space:nowrap;'>\n"; $html .= "<a data-id='".$data['error_id']."' data-type='0' class='btn ".($data['error_status'] == 0 ? 'active' : '')." e_status_0 button btn-default move_error_log'>\n"; $html .= $locale['450']."</a>\n"; $html .= "<a data-id='".$data['error_id']."' data-type='1' class='btn ".($data['error_status'] == 1 ? 'active' : '')." e_status_1 button btn-default move_error_log'>\n"; $html .= $locale['451']."</a>\n"; $html .= "<a data-id='".$data['error_id']."' data-type='2' class='btn ".($data['error_status'] == 2 ? 'active' : '')." e_status_2 button btn-default move_error_log'>\n"; $html .= $locale['452']."</a>\n"; $html .= "<a data-id='".$data['error_id']."' data-type='999' class='btn e_status_999 button btn-default move_error_log'>\n"; $html .= $locale['delete']."</a>\n"; } } if (!empty($this->new_errors)) { foreach ($this->new_errors as $i => $data) { $link = FUSION_SELF.$aidlink."&amp;rowstart=".$this->rowstart."&amp;error_id=".$data['error_id']."#file"; $file = stripslashes($data['error_file']); $link_title = $this->getMaxFolders($data['error_file'], 2); $html .= "<tr id='rmd-".$data['error_id']."'>"; $html .= "<td>"; $html .= "<a href='".$link."' title='".$file."'>".$link_title."</a><br/>\n"; $html .= "<code class='error_page'>".$data['error_page']."</code><br/>\n"; $html .= "<small>".$data['error_message']."</small><br/>"; $html .= "<strong>".$locale['415']." ".$data['error_line']."</strong><br/>\n"; $html .= "<small>".timer($data['error_timestamp'])."</small>\n"; $html .= "</td><td>".$this->getGitsrc($data['error_file'], $data['error_line'])."</td>\n"; $html .= "<td><label class='label label-success'>".$locale['450']."</label> ".$this->get_errorTypes($data['error_level'])."</td>\n"; $html .= "<td id='ecmd_".$data['error_id']."' style='white-space:nowrap;'>\n"; $html .= "<a data-id='".$data['error_id']."' data-type='0' class='btn ".($data['error_status'] == 0 ? 'active' : '')." e_status_0 button btn-default move_error_log'>\n"; $html .= $locale['450']."</a>\n"; $html .= "<a data-id='".$data['error_id']."' data-type='1' class='btn ".($data['error_status'] == 1 ? 'active' : '')." e_status_1 button btn-default move_error_log'>\n"; $html .= $locale['451']."</a>\n"; $html .= "<a data-id='".$data['error_id']."' data-type='2' class='btn ".($data['error_status'] == 2 ? 'active' : '')." e_status_2 button btn-default move_error_log'>\n"; $html .= $locale['452']."</a>\n"; $html .= "<a data-id='".$data['error_id']."' data-type='999' class='btn e_status_999 button btn-default move_error_log'>\n"; $html .= $locale['delete']."</a>\n"; } } $html .= "</table>\n"; if ($this->rows > 20) { $html .= "<div class='m-t-10 text-center'>\n"; $html .= makepagenav($this->rowstart, 20, $this->rows, 3, ADMIN."errors.php".$aidlink."&amp;"); $html .= "</div>\n"; } } else { $html .= "<div class='text-center well'>".$locale['418']."</div>\n"; } $this->errorjs(); return $html; } private static function errorjs() { global $aidlink; if (checkrights("ERRO") || !defined("iAUTH") || !isset($_GET['aid']) || $_GET['aid'] == iAUTH) { // Show the "Apply"-button only when javascript is disabled" add_to_jquery(" $('a#footer_debug').bind('click', function(e) { e.preventDefault(); }); $('.change_status').hide(); $('a[href=#top]').click(function(){ jQuery('html, body').animate({scrollTop:0}, 'slow'); return false; }); $('.move_error_log').bind('click', function() { var form = $('#error_logform'); var data = { 'aidlink' : '".$aidlink."', 'error_id' : $(this).data('id'), 'error_type' : $(this).data('type') }; var sendData = form.serialize() + '&' + $.param(data); $.ajax({ url: '".ADMIN."includes/error_logs_updater.php', dataType: 'json', method : 'GET', type: 'json', data: sendData, success: function(e) { //console.log(e); if (e.status == 'OK') { var target_group_add = $('tr#rmd-'+e.fusion_error_id+' > td > a.e_status_'+ e.to); var target_group_remove = $('tr#rmd-'+e.fusion_error_id+' > td > a.e_status_'+ e.from) target_group_add.addClass('active'); target_group_remove.removeClass('active'); } else if (e.status == 'RMD') { $('tr#rmd-'+e.fusion_error_id).html(''); } }, error : function(e) { console.log('fail'); } }); }); "); } } private static function get_errorTypes($type) { $locale = ''; include LOCALE.LOCALESET."errors.php"; $error_types = array(1 => array("E_ERROR", $locale['E_ERROR']), 2 => array("E_WARNING", $locale['E_WARNING']), 4 => array("E_PARSE", $locale['E_PARSE']), 8 => array("E_NOTICE", $locale['E_NOTICE']), 16 => array("E_CORE_ERROR", $locale['E_CORE_ERROR']), 32 => array("E_CORE_WARNING", $locale['E_CORE_WARNING']), 64 => array("E_COMPILE_ERROR", $locale['E_COMPILE_ERROR']), 128 => array("E_COMPILE_WARNING", $locale['E_COMPILE_WARNING']), 256 => array("E_USER_ERROR", $locale['E_USER_ERROR']), 512 => array("E_USER_WARNING", $locale['E_USER_WARNING']), 1024 => array("E_USER_NOTICE", $locale['E_USER_NOTICE']), 2047 => array("E_ALL", $locale['E_ALL']), 2048 => array("E_STRICT", $locale['E_STRICT'])); if (isset($error_types[$type])) return $error_types[$type][1]; return FALSE; } private static function getMaxFolders($url, $level = 2) { $return = ""; $tmpUrlArr = explode("/", $url); if (count($tmpUrlArr) > $level) { $tmpUrlArr = array_reverse($tmpUrlArr); for ($i = 0; $i < $level; $i++) { $return = $tmpUrlArr[$i].($i > 0 ? "/".$return : ""); } } else { $return = implode("/", $tmpUrlArr); } return $return; } private static function get_logTypes() { global $locale; return array('0' => $locale['450'], '1' => $locale['451'], '2' => $locale['452']); } private static function printCode($source_code, $starting_line, $error_line = "", array $error_message = array()) { global $locale; if (is_array($source_code)) { return FALSE; } $error_message = array('time' => !empty($error_message['time']) ? $error_message['time'] : time(), 'text' => !empty($error_message['text']) ? $error_message['text'] : $locale['na'],); $source_code = explode("\n", str_replace(array("\r\n", "\r"), "\n", $source_code)); $line_count = $starting_line; $formatted_code = ""; $error_message = "<div class='panel panel-default m-10'><div class='panel-heading'><i class='fa fa-bug'></i> Line ".$error_line." -- ".timer($error_message['time'])."</div><div class='panel-body strong required'>".$error_message['text']."</div>\n"; foreach ($source_code as $code_line) { $code_line = self::codeWrap($code_line, 145); $line_class = ($line_count == $error_line ? "err_tbl-error-line" : "err_tbl1"); $formatted_code .= "<tr>\n<td class='err_tbl2' style='text-align:right;width:1%;'>".$line_count."</td>\n"; if (preg_match('#<\?(php)?[^[:graph:]]#', $code_line)) { $formatted_code .= "<td class='".$line_class."'>".str_replace(array('<code>', '</code>'), '', highlight_string($code_line, TRUE))."</td>\n</tr>\n"; } else { $formatted_code .= "<td class='".$line_class."'>".preg_replace('#(&lt;\?php&nbsp;)+#', '', str_replace(array('<code>', '</code>'), '', highlight_string('<?php '.$code_line, TRUE)))." </td>\n</tr>\n"; if ($line_count == $error_line) { $formatted_code .= "<tr>\n<td colspan='2'>".$error_message."</td></tr>\n"; } } $line_count++; } return "<table class='err_tbl-border center' cellspacing='0' cellpadding='0'>".$formatted_code."</table>"; } private static function codeWrap($code, $maxLength = 150) { $lines = explode("\n", $code); $count = count($lines); for ($i = 0; $i < $count; ++$i) { preg_match('`^\s*`', $code, $matches); $lines[$i] = wordwrap($lines[$i], $maxLength, "\n$matches[0]\t", TRUE); } return implode("\n", $lines); } public static function getGitsrc($file, $line_number) { $repository_address = "https://github.com/php-fusion/PHP-Fusion/tree/"; $version = 9.01; $file_path = substr(str_replace('\\', '/', $file), strlen(FUSION_ROOT_DIR)); return "<a class='btn btn-default' href='".$repository_address.$version."/".$file_path."#L".$line_number."' target='new_window'><i class='fa fa-git'></i></a>"; } }
agpl-3.0
afterlogic/webmail-lite
libraries/afterlogic/common/net/protocols/poppassd.php
2576
<?php /* * Copyright 2004-2017, AfterLogic Corp. * Licensed under AGPLv3 license or AfterLogic license * if commercial version of the product was purchased. * See the LICENSE file for a full license statement. */ CApi::Inc('common.net.abstract'); /** * @package Api * @subpackage Net */ class CApiPoppassdProtocol extends CApiNetAbstract { /** * @return bool */ public function Connect() { $bResult = false; if (parent::Connect()) { $bResult = $this->CheckResponse($this->GetNextLine(), 0); } return $bResult; } /** * @param string $sLogin * @param string $sPassword * @return bool */ public function Login($sLogin, $sPassword) { return $this->SendCommand('user '.$sLogin, array(), 1) && $this->SendCommand('pass '.$sPassword, array($sPassword), 1); } /** * @param string $sLogin * @param string $sPassword * @return bool */ public function ConnectAndLogin($sLogin, $sPassword) { return $this->Connect() && $this->Login($sLogin, $sPassword); } /** * @return bool */ public function Disconnect() { return parent::Disconnect(); } /** * @return bool */ public function Logout() { return $this->SendCommand('quit', array(), 0); } /** * @return bool */ public function LogoutAndDisconnect() { return $this->Logout() && $this->Disconnect(); } /** * @param string $sNewPassword * @return bool */ public function NewPass($sNewPassword) { return $this->SendCommand('newpass '.$sNewPassword, array($sNewPassword), 0); } /** * @param string $sCmd * @return bool */ public function SendLine($sCmd) { return $this->WriteLine($sCmd); } /** * @param string $sCmd * @param array $aHideValues = array() * @param int $iCheckType = 0 * @return bool */ public function SendCommand($sCmd, $aHideValues = array(), $iCheckType = 0) { if ($this->WriteLine($sCmd, $aHideValues)) { return $this->CheckResponse($this->GetNextLine(), $iCheckType); } return false; } /** * @return string */ public function GetNextLine() { return $this->ReadLine(); } /** * @param string $sResponse * @param int $iCheckType = 0 * @return bool */ public function CheckResponse($sResponse, $iCheckType = 0) { switch ($iCheckType) { case 0: return (bool) preg_match('/^2\d\d/', $sResponse); break; case 1: return (bool) preg_match('/^[23]\d\d/', $sResponse); break; } return false; } }
agpl-3.0
sakukode/owncloud-custom
apps/files/js/newfilemenu.js
6593
/* * Copyright (c) 2014 * * This file is licensed under the Affero General Public License version 3 * or later. * * See the COPYING-README file. * */ /* global Files */ (function() { var TEMPLATE_MENU = '<ul>' + '<li>' + '<label for="file_upload_start" class="menuitem" data-action="upload" title="{{uploadMaxHumanFilesize}}"><span class="svg icon icon-upload"></span><span class="displayname">{{uploadLabel}}</span></label>' + '</li>' + '{{#each items}}' + '<li>' + '<a href="#" class="menuitem" data-templatename="{{templateName}}" data-filetype="{{fileType}}" data-action="{{id}}"><span class="icon {{iconClass}} svg"></span><span class="displayname">{{displayName}}</span></a>' + '</li>' + '{{/each}}' + '</ul>'; var TEMPLATE_FILENAME_FORM = '<form class="filenameform">' + '<label class="hidden-visually" for="{{cid}}-input-{{fileType}}">{{fileName}}</label>' + '<input id="{{cid}}-input-{{fileType}}" type="text" value="{{fileName}}">' + '</form>'; /** * Construct a new NewFileMenu instance * @constructs NewFileMenu * * @memberof OCA.Files */ var NewFileMenu = OC.Backbone.View.extend({ tagName: 'div', className: 'newFileMenu popovermenu bubble hidden open menu', events: { 'click .menuitem': '_onClickAction' }, /** * @type OCA.Files.FileList */ fileList: null, initialize: function(options) { var self = this; var $uploadEl = $('#file_upload_start'); if ($uploadEl.length) { $uploadEl.on('fileuploadstart', function() { self.trigger('actionPerformed', 'upload'); }); } else { console.warn('Missing upload element "file_upload_start"'); } this.fileList = options && options.fileList; this._menuItems = [{ id: 'folder', displayName: t('files', 'Folder'), templateName: t('files', 'New folder'), iconClass: 'icon-folder', fileType: 'folder', actionHandler: function(name) { self.fileList.createDirectory(name); } }]; OC.Plugins.attach('OCA.Files.NewFileMenu', this); }, template: function(data) { if (!OCA.Files.NewFileMenu._TEMPLATE) { OCA.Files.NewFileMenu._TEMPLATE = Handlebars.compile(TEMPLATE_MENU); } return OCA.Files.NewFileMenu._TEMPLATE(data); }, /** * Event handler whenever an action has been clicked within the menu * * @param {Object} event event object */ _onClickAction: function(event) { var $target = $(event.target); if (!$target.hasClass('menuitem')) { $target = $target.closest('.menuitem'); } var action = $target.attr('data-action'); // note: clicking the upload label will automatically // set the focus on the "file_upload_start" hidden field // which itself triggers the upload dialog. // Currently the upload logic is still in file-upload.js and filelist.js if (action === 'upload') { OC.hideMenus(); } else { event.preventDefault(); this.$el.find('.menuitem.active').removeClass('active'); $target.addClass('active'); this._promptFileName($target); } }, _promptFileName: function($target) { var self = this; if (!OCA.Files.NewFileMenu._TEMPLATE_FORM) { OCA.Files.NewFileMenu._TEMPLATE_FORM = Handlebars.compile(TEMPLATE_FILENAME_FORM); } if ($target.find('form').length) { $target.find('input').focus(); return; } // discard other forms this.$el.find('form').remove(); this.$el.find('.displayname').removeClass('hidden'); $target.find('.displayname').addClass('hidden'); var newName = $target.attr('data-templatename'); var fileType = $target.attr('data-filetype'); var $form = $(OCA.Files.NewFileMenu._TEMPLATE_FORM({ fileName: newName, cid: this.cid, fileType: fileType })); //this.trigger('actionPerformed', action); $target.append($form); // here comes the OLD code var $input = $form.find('input'); var lastPos; var checkInput = function () { var filename = $input.val(); try { if (!Files.isFileNameValid(filename)) { // Files.isFileNameValid(filename) throws an exception itself } else if (self.fileList.inList(filename)) { throw t('files', '{newname} already exists', {newname: filename}); } else { return true; } } catch (error) { $input.attr('title', error); $input.tooltip({placement: 'right', trigger: 'manual'}); $input.tooltip('show'); $input.addClass('error'); } return false; }; // verify filename on typing $input.keyup(function() { if (checkInput()) { $input.tooltip('hide'); $input.removeClass('error'); } }); $input.focus(); // pre select name up to the extension lastPos = newName.lastIndexOf('.'); if (lastPos === -1) { lastPos = newName.length; } $input.selectRange(0, lastPos); $form.submit(function(event) { event.stopPropagation(); event.preventDefault(); if (checkInput()) { var newname = $input.val(); /* Find the right actionHandler that should be called. * Actions is retrieved by using `actionSpec.id` */ action = _.filter(self._menuItems, function(item) { return item.id == $target.attr('data-action'); }).pop(); action.actionHandler(newname); $form.remove(); $target.find('.displayname').removeClass('hidden'); OC.hideMenus(); } }); }, /** * Add a new item menu entry in the “New” file menu (in * last position). By clicking on the item, the * `actionHandler` function is called. * * @param {Object} actionSpec item’s properties */ addMenuEntry: function(actionSpec) { this._menuItems.push({ id: actionSpec.id, displayName: actionSpec.displayName, templateName: actionSpec.templateName, iconClass: actionSpec.iconClass, fileType: actionSpec.fileType, actionHandler: actionSpec.actionHandler, }); }, /** * Renders the menu with the currently set items */ render: function() { this.$el.html(this.template({ uploadMaxHumanFileSize: 'TODO', uploadLabel: t('files', 'Upload'), items: this._menuItems })); OC.Util.scaleFixForIE8(this.$('.svg')); }, /** * Displays the menu under the given element * * @param {Object} $target target element */ showAt: function($target) { this.render(); var targetOffset = $target.offset(); this.$el.css({ left: targetOffset.left, top: targetOffset.top + $target.height() }); this.$el.removeClass('hidden'); OC.showMenu(null, this.$el); } }); OCA.Files.NewFileMenu = NewFileMenu; })();
agpl-3.0
OpusVL/odoo
addons/base_action_rule/__openerp__.py
1943
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Automated Action Rules', 'version': '1.0', 'category': 'Sales Management', 'description': """ This module allows to implement action rules for any object. ============================================================ Use automated actions to automatically trigger actions for various screens. **Example:** A lead created by a specific user may be automatically set to a specific sales team, or an opportunity which still has status pending after 14 days might trigger an automatic reminder email. """, 'author': 'OpenERP SA', 'website': 'https://www.odoo.com', 'depends': ['base', 'resource', 'mail'], 'data': [ 'base_action_rule_data.xml', 'base_action_rule_view.xml', 'security/ir.model.access.csv', ], 'demo': [], 'installable': True, 'auto_install': False, 'images': ['images/base_action_rule1.jpeg','images/base_action_rule2.jpeg','images/base_action_rule3.jpeg'], }
agpl-3.0
nonblocking/cliwix
cliwix-webapp/src/main/scala/at/nonblocking/cliwix/webapp/LoginController.scala
2605
/* * Copyright (c) 2014-2016 * nonblocking.at gmbh [http://www.nonblocking.at] * * This file is part of Cliwix. * * Cliwix is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package at.nonblocking.cliwix.webapp import java.io.Serializable import java.security.SecureRandom import javax.inject.Inject import javax.servlet.http.HttpServletRequest import com.typesafe.scalalogging.slf4j.LazyLogging import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.{RequestBody, RequestMethod, RequestMapping} import scala.beans.BeanProperty @Controller class LoginController extends ControllerDefaults with LazyLogging { @BeanProperty @Inject var cliwixCoreHolder: CliwixCoreHolder = _ var random = new SecureRandom() @RequestMapping(value = Array("/services/login"), method = Array(RequestMethod.POST)) def login(request: HttpServletRequest, @RequestBody loginData: LoginData): LoginResult = { val succeeded = if (loginData.getUsername != null && loginData.getPassword != null) { this.cliwixCoreHolder.getCliwix.getLiferayAuthenticator.login(loginData.getUsername, loginData.getPassword) } else { false } val result = new LoginResult result.setSucceeded(succeeded) if (!succeeded) { result.setErrorMessage("Invalid username or password!") } else { val user = new User(loginData.username) logger.info("User login successful: {}", user) storeUser(request, user) } result } @RequestMapping(value = Array("/services/logout"), method = Array(RequestMethod.GET)) def logout(request: HttpServletRequest): Unit = { storeUser(request, null) request.getSession.invalidate() } } class LoginData extends Serializable { @BeanProperty var username: String = _ @BeanProperty var password: String = _ } class LoginResult extends Serializable { @BeanProperty var succeeded: Boolean = _ @BeanProperty var errorMessage: String = _ }
agpl-3.0
napramirez/jPOS
jpos/src/test/java/org/jpos/util/NameRegistrarTest.java
4261
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2013 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.util; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.After; import org.junit.Before; import org.junit.Test; public class NameRegistrarTest { private static final boolean WITH_DETAIL = true; @Before public void onSetup() { NameRegistrar.register("test1", "testValue1"); NameRegistrar.register("test2", "testValue2"); } @After public void tearDown() { NameRegistrar.unregister("test1"); NameRegistrar.unregister("test2"); } @Test public void testDumpWithoutDetail() throws Throwable { ByteArrayOutputStream out = new ByteArrayOutputStream(); NameRegistrar.getInstance().dump(new PrintStream(out), ">"); assertThat( out.toString(), allOf(containsString("name-registrar:" + System.getProperty("line.separator")), containsString("test1"), containsString("test2"))); } @Test public void testDumpWithDetail() throws Throwable { ByteArrayOutputStream out = new ByteArrayOutputStream(); NameRegistrar.getInstance().dump(new PrintStream(out), "+", WITH_DETAIL); assertThat( out.toString(), allOf(containsString("name-registrar:" + System.getProperty("line.separator")), containsString("test1"), containsString("test2"))); } @Test public void testGetInstance() throws Throwable { NameRegistrar result = NameRegistrar.getInstance(); assertThat(result, is(sameInstance(NameRegistrar.getInstance()))); } @Test public void testGet() throws Exception { String value = (String) NameRegistrar.get("test1"); assertThat(value, is("testValue1")); } @Test(expected = NameRegistrar.NotFoundException.class) public void testGetThrowsNotFoundException() throws Throwable { NameRegistrar.get("NonexistentKey"); } @Test public void testGetIfExists() throws Throwable { String value = (String) NameRegistrar.getIfExists("test2"); assertThat(value, is("testValue2")); } @Test public void testGetIfExistsWithNotFoundKey() throws Exception { String value = (String) NameRegistrar.getIfExists("NonexistentKey"); assertThat(value, is(nullValue())); } @Test(expected = NameRegistrar.NotFoundException.class) public void testUnregister() throws Exception { NameRegistrar.register("test3", "someTest3Value"); assertThat((String) NameRegistrar.get("test3"), is("someTest3Value")); NameRegistrar.unregister("test3"); NameRegistrar.get("test3"); } @Test public void testUnregisterUnknownKeyDoesNotThrowException() throws Exception { NameRegistrar.unregister("unknownKey"); } @Test public void testNotFoundExceptionConstructor1() throws Throwable { NameRegistrar.NotFoundException notFoundException = new NameRegistrar.NotFoundException("testNotFoundExceptionDetail"); assertEquals("notFoundException.getMessage()", "testNotFoundExceptionDetail", notFoundException.getMessage()); } }
agpl-3.0
Sparfel/iTop-s-Portal
library/Zend/Pdf/Resource/Font/Type0.php
9585
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Pdf * @subpackage Fonts * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** Internally used classes */ //$1 'Zend/Pdf/Element/Array.php'; //$1 'Zend/Pdf/Element/Name.php'; /** Zend_Pdf_Resource_Font */ //$1 'Zend/Pdf/Resource/Font.php'; /** * Adobe PDF composite fonts implementation * * A composite font is one whose glyphs are obtained from other fonts or from fontlike * objects called CIDFonts ({@link Zend_Pdf_Resource_Font_CidFont}), organized hierarchically. * In PDF, a composite font is represented by a font dictionary whose Subtype value is Type0; * this is also called a Type 0 font (the Type 0 font at the top level of the hierarchy is the * root font). * * In PDF, a Type 0 font is a CID-keyed font. * * CID-keyed fonts provide effective method to operate with multi-byte character encodings. * * The CID-keyed font architecture specifies the external representation of certain font programs, * called CMap and CIDFont files, along with some conventions for combining and using those files. * * A CID-keyed font is the combination of a CMap with one or more CIDFonts, simple fonts, * or composite fonts containing glyph descriptions. * * The term 'CID-keyed font' reflects the fact that CID (character identifier) numbers * are used to index and access the glyph descriptions in the font. * * * Font objects should be normally be obtained from the factory methods * {@link Zend_Pdf_Font::fontWithName} and {@link Zend_Pdf_Font::fontWithPath}. * * @package Zend_Pdf * @subpackage Fonts * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Pdf_Resource_Font_Type0 extends Zend_Pdf_Resource_Font { /** * Descendant CIDFont * * @var Zend_Pdf_Resource_Font_CidFont */ private $_descendantFont; /** * Generate ToUnicode character map data * * @return string */ static private function getToUnicodeCMapData() { return '/CIDInit /ProcSet findresource begin ' . "\n" . '12 dict begin ' . "\n" . 'begincmap ' . "\n" . '/CIDSystemInfo ' . "\n" . '<</Registry (Adobe) ' . "\n" . '/Ordering (UCS) ' . "\n" . '/Supplement 0' . "\n" . '>> def' . "\n" . '/CMapName /Adobe-Identity-UCS def ' . "\n" . '/CMapType 2 def ' . "\n" . '1 begincodespacerange' . "\n" . '<0000> <FFFF> ' . "\n" . 'endcodespacerange ' . "\n" . '1 beginbfrange ' . "\n" . '<0000> <FFFF> <0000> ' . "\n" . 'endbfrange ' . "\n" . 'endcmap ' . "\n" . 'CMapName currentdict /CMap defineresource pop ' . "\n" . 'end ' . 'end '; } /** * Object constructor * */ public function __construct(Zend_Pdf_Resource_Font_CidFont $descendantFont) { parent::__construct(); $this->_objectFactory->attach($descendantFont->getFactory()); $this->_fontType = Zend_Pdf_Font::TYPE_TYPE_0; $this->_descendantFont = $descendantFont; $this->_fontNames = $descendantFont->getFontNames(); $this->_isBold = $descendantFont->isBold(); $this->_isItalic = $descendantFont->isItalic(); $this->_isMonospaced = $descendantFont->isMonospace(); $this->_underlinePosition = $descendantFont->getUnderlinePosition(); $this->_underlineThickness = $descendantFont->getUnderlineThickness(); $this->_strikePosition = $descendantFont->getStrikePosition(); $this->_strikeThickness = $descendantFont->getStrikeThickness(); $this->_unitsPerEm = $descendantFont->getUnitsPerEm(); $this->_ascent = $descendantFont->getAscent(); $this->_descent = $descendantFont->getDescent(); $this->_lineGap = $descendantFont->getLineGap(); $this->_resource->Subtype = new Zend_Pdf_Element_Name('Type0'); $this->_resource->BaseFont = new Zend_Pdf_Element_Name($descendantFont->getResource()->BaseFont->value); $this->_resource->DescendantFonts = new Zend_Pdf_Element_Array(array( $descendantFont->getResource() )); $this->_resource->Encoding = new Zend_Pdf_Element_Name('Identity-H'); $toUnicode = $this->_objectFactory->newStreamObject(self::getToUnicodeCMapData()); $this->_resource->ToUnicode = $toUnicode; } /** * Returns an array of glyph numbers corresponding to the Unicode characters. * * Zend_Pdf uses 'Identity-H' encoding for Type 0 fonts. * So we don't need to perform any conversion * * See also {@link glyphNumberForCharacter()}. * * @param array $characterCodes Array of Unicode character codes (code points). * @return array Array of glyph numbers. */ public function glyphNumbersForCharacters($characterCodes) { return $characterCodes; } /** * Returns the glyph number corresponding to the Unicode character. * * Zend_Pdf uses 'Identity-H' encoding for Type 0 fonts. * So we don't need to perform any conversion * * @param integer $characterCode Unicode character code (code point). * @return integer Glyph number. */ public function glyphNumberForCharacter($characterCode) { return $characterCode; } /** * Returns a number between 0 and 1 inclusive that indicates the percentage * of characters in the string which are covered by glyphs in this font. * * Since no one font will contain glyphs for the entire Unicode character * range, this method can be used to help locate a suitable font when the * actual contents of the string are not known. * * Note that some fonts lie about the characters they support. Additionally, * fonts don't usually contain glyphs for control characters such as tabs * and line breaks, so it is rare that you will get back a full 1.0 score. * The resulting value should be considered informational only. * * @param string $string * @param string $charEncoding (optional) Character encoding of source text. * If omitted, uses 'current locale'. * @return float */ public function getCoveredPercentage($string, $charEncoding = '') { return $this->_descendantFont->getCoveredPercentage($string, $charEncoding); } /** * Returns the widths of the glyphs. * * The widths are expressed in the font's glyph space. You are responsible * for converting to user space as necessary. See {@link unitsPerEm()}. * * Throws an exception if the glyph number is out of range. * * See also {@link widthForGlyph()}. * * @param array &$glyphNumbers Array of glyph numbers. * @return array Array of glyph widths (integers). * @throws Zend_Pdf_Exception */ public function widthsForGlyphs($glyphNumbers) { return $this->_descendantFont->widthsForChars($glyphNumbers); } /** * Returns the width of the glyph. * * Like {@link widthsForGlyphs()} but used for one glyph at a time. * * @param integer $glyphNumber * @return integer * @throws Zend_Pdf_Exception */ public function widthForGlyph($glyphNumber) { return $this->_descendantFont->widthForChar($glyphNumber); } /** * Convert string to the font encoding. * * The method is used to prepare string for text drawing operators * * @param string $string * @param string $charEncoding Character encoding of source text. * @return string */ public function encodeString($string, $charEncoding) { return iconv($charEncoding, 'UTF-16BE', $string); } /** * Convert string from the font encoding. * * The method is used to convert strings retrieved from existing content streams * * @param string $string * @param string $charEncoding Character encoding of resulting text. * @return string */ public function decodeString($string, $charEncoding) { return iconv('UTF-16BE', $charEncoding, $string); } }
agpl-3.0
gtank/Gadgetbridge
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/receivers/GBMusicControlReceiver.java
2670
package nodomain.freeyourgadget.gadgetbridge.service.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.os.SystemClock; import android.view.KeyEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventMusicControl; public class GBMusicControlReceiver extends BroadcastReceiver { private static final Logger LOG = LoggerFactory.getLogger(GBMusicControlReceiver.class); public static final String ACTION_MUSICCONTROL = "nodomain.freeyourgadget.gadgetbridge.musiccontrol"; @Override public void onReceive(Context context, Intent intent) { GBDeviceEventMusicControl.Event musicCmd = GBDeviceEventMusicControl.Event.values()[intent.getIntExtra("event", 0)]; int keyCode = -1; int volumeAdjust = AudioManager.ADJUST_LOWER; switch (musicCmd) { case NEXT: keyCode = KeyEvent.KEYCODE_MEDIA_NEXT; break; case PREVIOUS: keyCode = KeyEvent.KEYCODE_MEDIA_PREVIOUS; break; case PLAY: keyCode = KeyEvent.KEYCODE_MEDIA_PLAY; break; case PAUSE: keyCode = KeyEvent.KEYCODE_MEDIA_PAUSE; break; case PLAYPAUSE: keyCode = KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE; break; case VOLUMEUP: // change default and fall through, :P volumeAdjust = AudioManager.ADJUST_RAISE; case VOLUMEDOWN: AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, volumeAdjust, 0); break; default: return; } if (keyCode != -1) { long eventtime = SystemClock.uptimeMillis(); Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, keyCode, 0); downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent); context.sendOrderedBroadcast(downIntent, null); Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, keyCode, 0); upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent); context.sendOrderedBroadcast(upIntent, null); } } }
agpl-3.0
cm-is-dog/rapidminer-studio-core
report/html/com/rapidminer/operator/learner/associations/AssociationRules.js
1238
var clover = new Object(); // JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]} clover.pageData = {"classes":[{"el":136,"id":46052,"methods":[{"el":55,"sc":2,"sl":53},{"el":65,"sc":2,"sl":63},{"el":69,"sc":2,"sl":67},{"el":73,"sc":2,"sl":71},{"el":77,"sc":2,"sl":75},{"el":81,"sc":2,"sl":79},{"el":86,"sc":2,"sl":83},{"el":95,"sc":2,"sl":92},{"el":117,"sc":2,"sl":104},{"el":122,"sc":2,"sl":119},{"el":135,"sc":2,"sl":124}],"name":"AssociationRules","sl":37}]} // JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...}; clover.testTargets = {} // JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]}; clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
agpl-3.0
KWZwickau/KREDA-Sphere
Sphere/Client/Component/Parameter/Repository/Icon/HomeIcon.php
490
<?php namespace KREDA\Sphere\Client\Component\Parameter\Repository\Icon; use KREDA\Sphere\Client\Component\IParameterInterface; use KREDA\Sphere\Client\Component\Parameter\Repository\AbstractIcon; /** * Class HomeIcon * * @package KREDA\Sphere\Client\Component\Parameter\Repository\Icon */ class HomeIcon extends AbstractIcon implements IParameterInterface { /** * */ public function __construct() { $this->setValue( AbstractIcon::ICON_HOME ); } }
agpl-3.0
devsarr/ONLYOFFICE-OnlineEditors
OfficeWeb/sdk/Word/Editor/GraphicObjects/States.js
276061
/* * (c) Copyright Ascensio System SIA 2010-2014 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, * EU, LV-1021. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ var STATES_ID_NULL = 0; var STATES_ID_PRE_CHANGE_ADJ = 1; var STATES_ID_PRE_MOVE = 2; var STATES_ID_PRE_MOVE_INLINE_OBJECT = 3; var STATES_ID_PRE_ROTATE = 4; var STATES_ID_PRE_RESIZE = 5; var STATES_ID_CHANGE_ADJ = 6; var STATES_ID_MOVE = 7; var STATES_ID_START_ADD_NEW_SHAPE = 8; var STATES_ID_START_TRACK_NEW_SHAPE = 9; var STATES_ID_TRACK_NEW_SHAPE = 9; var STATES_ID_ROTATE = 16; var STATES_ID_RESIZE = 17; var STATES_ID_GROUP = 18; var STATES_ID_TEXT_ADD = 19; var STATES_ID_PRE_CHANGE_ADJ_GROUPED = 20; var STATES_ID_CHANGE_ADJ_GROUPED = 21; var STATES_ID_TEXT_ADD_IN_GROUP = 22; var STATES_ID_START_CHANGE_WRAP = 23; var STATES_ID_PRE_CHANGE_WRAP = 24; var STATES_ID_PRE_CHANGE_WRAP_ADD = 25; var STATES_ID_PRE_CHANGE_WRAP_CONTOUR = 25; var STATES_ID_SPLINE_BEZIER = 32; var STATES_ID_SPLINE_BEZIER33 = 33; var STATES_ID_SPLINE_BEZIER2 = 34; var STATES_ID_SPLINE_BEZIER3 = 35; var STATES_ID_SPLINE_BEZIER4 = 36; var STATES_ID_SPLINE_BEZIER5 = 37; var STATES_ID_MOVE_INLINE_OBJECT = 38; var STATES_ID_NULL_HF = 39; var STATES_ID_START_ADD_TEXT_RECT = 40; var STATES_ID_START_TRACK_TEXT_RECT = 41; var STATES_ID_TRACK_TEXT_RECT = 48; var STATES_ID_PRE_RESIZE_GROUPED = 49; var STATES_ID_RESIZE_GROUPED = 50; var STATES_ID_PRE_MOVE_IN_GROUP = 51; var STATES_ID_MOVE_IN_GROUP = 52; var STATES_ID_PRE_ROTATE_IN_GROUP = 53; var STATES_ID_ROTATE_IN_GROUP = 54; var STATES_ID_PRE_CH_ADJ_IN_GROUP = 55; var STATES_ID_CH_ADJ_IN_GROUP = 56; var STATES_ID_PRE_RESIZE_IN_GROUP = 57; var STATES_ID_RESIZE_IN_GROUP = 64; var STATES_ID_PRE_ROTATE_IN_GROUP2 = 65; var STATES_ID_ROTATE_IN_GROUP2 = 66; var STATES_ID_CHART = 67; var STATES_ID_CHART_TITLE_TEXT = 68; var STATES_ID_PRE_MOVE_CHART_TITLE = 69; var STATES_ID_MOVE_CHART_TITLE = 70; var STATES_ID_PRE_MOVE_CHART_TITLE_GROUP = 71; var STATES_ID_MOVE_CHART_TITLE_GROUP = 72; var STATES_ID_CHART_GROUP = 73; var STATES_ID_CHART_TITLE_TEXT_GROUP = 80; var SNAP_DISTANCE = 1.27; function handleSelectedObjects(graphicObjects, e, x, y, pageIndex) { var _common_selection_array = graphicObjects.selectionInfo.selectionArray; if (_common_selection_array.length > 0) { if (_common_selection_array.length === 1) { var _selected_gr_object = _common_selection_array[0]; var _translated_x; var _translated_y; if (_selected_gr_object.selectStartPage !== pageIndex) { var _translated_point = graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, _selected_gr_object.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var _hit_to_adj = _selected_gr_object.hitToAdj(_translated_x, _translated_y); if (_hit_to_adj.hit === true) { graphicObjects.majorGraphicObject = _selected_gr_object; graphicObjects.arrPreTrackObjects = []; if (_hit_to_adj.adjPolarFlag === true) { graphicObjects.arrPreTrackObjects.push(new CTrackPolarAdjObject(_selected_gr_object.GraphicObj, _hit_to_adj.adjNum, _selected_gr_object.pageIndex)); } else { graphicObjects.arrPreTrackObjects.push(new CTrackXYAdjObject(_selected_gr_object.GraphicObj, _hit_to_adj.adjNum, _selected_gr_object.pageIndex)); } graphicObjects.changeCurrentState(new PreChangeAdjState(graphicObjects)); return true; } } for (var _index = _common_selection_array.length - 1; _index > -1; --_index) { var _cur_selected_gr_object = _common_selection_array[_index]; if (_cur_selected_gr_object.pageIndex !== pageIndex) { _translated_point = graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, _cur_selected_gr_object.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var _hit_to_handle = _cur_selected_gr_object.hitToHandle(_translated_x, _translated_y); if (_hit_to_handle.hit === true) { graphicObjects.majorGraphicObject = _cur_selected_gr_object; graphicObjects.arrPreTrackObjects.length = 0; if (_hit_to_handle.handleRotate === false) { var _card_direction = _cur_selected_gr_object.numberToCardDirection(_hit_to_handle.handleNum); for (var _selected_index = 0; _selected_index < _common_selection_array.length; ++_selected_index) { graphicObjects.arrPreTrackObjects.push(new CTrackHandleObject(_common_selection_array[_selected_index], _card_direction, _common_selection_array[_selected_index].pageIndex)); } graphicObjects.changeCurrentState(new PreResizeState(graphicObjects, _hit_to_handle.handleNum)); return true; } else { if (!_cur_selected_gr_object.canRotate()) { return false; } for (_selected_index = 0; _selected_index < _common_selection_array.length; ++_selected_index) { if (_common_selection_array[_selected_index].canRotate()) { break; } } if (_selected_index === _common_selection_array.length) { return false; } for (_selected_index = 0; _selected_index < _common_selection_array.length; ++_selected_index) { if (_common_selection_array[_selected_index].canRotate()) { graphicObjects.arrPreTrackObjects.push(new CTrackRotateObject(_common_selection_array[_selected_index], _common_selection_array[_selected_index].pageIndex)); } } graphicObjects.changeCurrentState(new PreRotateState(graphicObjects)); return true; } } } } return false; } function handleSelectedObjectsCursorType(graphicObjects, e, x, y, pageIndex) { var _common_selection_array = graphicObjects.selectionInfo.selectionArray; if (_common_selection_array.length > 0) { if (_common_selection_array.length === 1) { var _selected_gr_object = _common_selection_array[0]; var _translated_x; var _translated_y; if (_selected_gr_object.selectStartPage !== pageIndex) { var _translated_point = graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, _selected_gr_object.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var _hit_to_adj = _selected_gr_object.hitToAdj(_translated_x, _translated_y); if (_hit_to_adj.hit === true) { graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; } } for (var _index = _common_selection_array.length - 1; _index > -1; --_index) { var _cur_selected_gr_object = _common_selection_array[_index]; if (_cur_selected_gr_object.pageIndex !== pageIndex) { _translated_point = graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, _cur_selected_gr_object.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var _hit_to_handle = _cur_selected_gr_object.hitToHandle(_translated_x, _translated_y); if (_hit_to_handle.hit === true) { graphicObjects.majorGraphicObject = _cur_selected_gr_object; graphicObjects.arrPreTrackObjects.length = 0; if (_hit_to_handle.handleRotate === false) { var _card_direction = _cur_selected_gr_object.numberToCardDirection(_hit_to_handle.handleNum); graphicObjects.drawingDocument.SetCursorType(CURSOR_TYPES_BY_CARD_DIRECTION[_card_direction]); return true; } else { graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; } } } } return false; } function handleFloatShapeImage(drawing, graphicObjects, e, x, y, pageIndex, handleState) { var _hit = drawing.hit(x, y); var _hit_to_path = drawing.hitToPath(x, y); var b_hit_to_text = drawing.hitToTextRect(x, y); var _common_selection_array = graphicObjects.selectionInfo.selectionArray; if ((_hit && !b_hit_to_text) || _hit_to_path) { handleHitNoText(drawing, graphicObjects, e, x, y, pageIndex, handleState); return true; } else { if (b_hit_to_text) { for (var _sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; _common_selection_array.push(drawing); drawing.select(pageIndex); var arr_inline_objects = drawing.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { if (cur_inline_object.selected === false) { for (_sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; cur_inline_object.select(pageIndex); _common_selection_array.push(cur_inline_object); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, cur_inline_object.Get_Id(), false, false)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { if (cur_inline_object.selected === false) { cur_inline_object.select(pageIndex); _common_selection_array.push(cur_inline_object); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, cur_inline_object.Get_Id(), false, false)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } } editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return true; } } drawing.selectionSetStart(x, y, e); graphicObjects.changeCurrentState(new TextAddState(graphicObjects, drawing)); if (e.ClickCount <= 1) { graphicObjects.updateSelectionState(); } return true; } } return false; } function handleFloatGroup(drawing, graphicObjects, e, x, y, pageIndex, handleState) { var _hit = drawing.hit(x, y); var _hit_to_path = drawing.hitToPath(x, y); var _hit_to_text_rect = drawing.hitToTextRect(x, y); var b_hit_to_text = _hit_to_text_rect.hit; var _common_selection_array = graphicObjects.selectionInfo.selectionArray; if ((_hit && !b_hit_to_text) || _hit_to_path) { handleHitNoText(drawing, graphicObjects, e, x, y, pageIndex, handleState); return true; } else { if (b_hit_to_text) { for (var _sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; _common_selection_array.push(drawing); drawing.select(pageIndex); var sp = drawing.GraphicObj.spTree[_hit_to_text_rect.num]; if (typeof sp.getArrContentDrawingObjects === "function") { var arr_inline_objects = sp.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { if (cur_inline_object.selected === false) { for (_sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; cur_inline_object.select(pageIndex); _common_selection_array.push(cur_inline_object); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, cur_inline_object.Get_Id(), false, false)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { if (cur_inline_object.selected === false) { cur_inline_object.select(pageIndex); _common_selection_array.push(cur_inline_object); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, cur_inline_object.Get_Id(), false, false)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } } editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return true; } } } sp.selectionSetStart(x, y, e); sp.select(pageIndex); drawing.GraphicObj.selectionInfo.selectionArray.push(sp); graphicObjects.changeCurrentState(new TextAddInGroup(graphicObjects, sp, drawing.GraphicObj)); if (e.ClickCount <= 1) { graphicObjects.updateSelectionState(); } editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return true; } } return false; } function handleFloatObjects(drawingArray, graphicObjects, e, x, y, pageIndex, handleState) { for (var _object_index = drawingArray.length - 1; _object_index > -1; --_object_index) { var _current_graphic_object = drawingArray[_object_index]; if (_current_graphic_object.GraphicObj instanceof WordShape || _current_graphic_object.GraphicObj instanceof WordImage) { if (handleFloatShapeImage(_current_graphic_object, graphicObjects, e, x, y, pageIndex, handleState)) { return true; } } else { if (_current_graphic_object.GraphicObj instanceof WordGroupShapes) { if (handleFloatGroup(_current_graphic_object, graphicObjects, e, x, y, pageIndex, handleState)) { return true; } } else { if (typeof CChartAsGroup != "undefined" && _current_graphic_object.GraphicObj instanceof CChartAsGroup) { if (handleChart(_current_graphic_object, graphicObjects, x, y, e, pageIndex)) { return true; } } } } } return false; } function handleHitNoText(drawing, graphicObjects, e, x, y, pageIndex, handleState) { var _common_selection_array = graphicObjects.selectionInfo.selectionArray; graphicObjects.majorGraphicObject = drawing; if (! (e.CtrlKey || e.ShiftKey)) { if (drawing.selected === false) { for (var _sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; drawing.select(pageIndex); _common_selection_array.push(drawing); editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); _common_selection_array.sort(ComparisonByZIndex); graphicObjects.arrPreTrackObjects.length = 0; graphicObjects.arrPreTrackObjects[0] = new CTrackMoveObject(drawing, drawing.absOffsetX - x, drawing.absOffsetY - y, graphicObjects, pageIndex); if (_common_selection_array.length === 1) { var pre_track = _common_selection_array[0]; pre_track.calculateOffset(); var boundsOffX = pre_track.absOffsetX - pre_track.boundsOffsetX; var boundsOffY = pre_track.absOffsetY - pre_track.boundsOffsetY; handleState.anchorPos = pre_track.Get_AnchorPos(); handleState.anchorPos.Page = pageIndex; } graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); graphicObjects.changeCurrentState(new PreMoveState(graphicObjects, false, false)); return; } else { graphicObjects.arrPreTrackObjects.length = 0; for (_sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { if (_common_selection_array[_sel_index].pageIndex === pageIndex) { drawing = _common_selection_array[_sel_index]; graphicObjects.arrPreTrackObjects.push(new CTrackMoveObject(drawing, drawing.absOffsetX - x, drawing.absOffsetY - y, graphicObjects, pageIndex)); } } if (_common_selection_array.length === 1) { var pre_track = _common_selection_array[0]; pre_track.calculateOffset(); var boundsOffX = pre_track.absOffsetX - pre_track.boundsOffsetX; var boundsOffY = pre_track.absOffsetY - pre_track.boundsOffsetY; handleState.anchorPos = pre_track.Get_AnchorPos(); handleState.anchorPos.Page = pageIndex; handleState.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } graphicObjects.changeCurrentState(new PreMoveState(graphicObjects, false, true)); return; } } else { if ((_common_selection_array.length > 0 && _common_selection_array[0].Is_Inline())) { return; } if (drawing.selected === false) { drawing.select(pageIndex); _common_selection_array.push(drawing); _common_selection_array.sort(ComparisonByZIndex); editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); } graphicObjects.arrPreTrackObjects.length = 0; for (_sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { if (_common_selection_array[_sel_index].pageIndex === pageIndex) { drawing = _common_selection_array[_sel_index]; graphicObjects.arrPreTrackObjects.push(new CTrackMoveObject(drawing, drawing.absOffsetX - x, drawing.absOffsetY - y, graphicObjects, pageIndex)); } } if (_common_selection_array.length === 1) { var pre_track = _common_selection_array[0]; pre_track.calculateOffset(); var boundsOffX = pre_track.absOffsetX - pre_track.boundsOffsetX; var boundsOffY = pre_track.absOffsetY - pre_track.boundsOffsetY; handleState.anchorPos = pre_track.Get_AnchorPos(); handleState.anchorPos.Page = pageIndex; } graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); graphicObjects.changeCurrentState(new PreMoveState(graphicObjects, true, false)); return; } } function handleInlineShapeImage(drawing, graphicObjects, e, x, y, pageIndex, handleState) { var _common_selection_array = graphicObjects.selectionInfo.selectionArray; var _hit = drawing.hit(x, y); var _hit_to_path = drawing.hitToPath(x, y); var b_hit_to_text = drawing.hitToTextRect(x, y); if ((_hit && !b_hit_to_text) || _hit_to_path) { handleInlineHitNoText(drawing, graphicObjects, e, x, y, pageIndex, handleState); return true; } else { if (b_hit_to_text) { for (var _sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; drawing.select(pageIndex); _common_selection_array.push(drawing); var arr_inline_objects = drawing.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { if (cur_inline_object.selected === false) { for (_sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; cur_inline_object.select(pageIndex); _common_selection_array.push(cur_inline_object); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, cur_inline_object.Get_Id(), false, false)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { if (cur_inline_object.selected === false) { cur_inline_object.select(pageIndex); _common_selection_array.push(cur_inline_object); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, cur_inline_object.Get_Id(), false, false)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } } editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return true; } } drawing.selectionSetStart(x, y, e); graphicObjects.changeCurrentState(new TextAddState(graphicObjects, drawing)); if (e.ClickCount <= 1) { graphicObjects.updateSelectionState(); } editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return true; } } return false; } function handleInlineGroup(drawing, graphicObjects, e, x, y, pageIndex, handleState) { var _common_selection_array = graphicObjects.selectionInfo.selectionArray; var _hit = drawing.hit(x, y); var _hit_to_path = drawing.hitToPath(x, y); var _hit_to_text_rect = drawing.hitToTextRect(x, y); var b_hit_to_text = _hit_to_text_rect.hit; if ((_hit && !b_hit_to_text) || _hit_to_path) { handleInlineHitNoText(drawing, graphicObjects, e, x, y, pageIndex, handleState); return true; } else { if (b_hit_to_text) { for (var _sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; drawing.select(pageIndex); _common_selection_array.push(drawing); var sp = drawing.GraphicObj.spTree[_hit_to_text_rect.num]; if (typeof sp.getArrContentDrawingObjects === "function") { var arr_inline_objects = sp.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { if (cur_inline_object.selected === false) { for (_sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; cur_inline_object.select(pageIndex); _common_selection_array.push(cur_inline_object); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, cur_inline_object.Get_Id(), false, false)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { if (cur_inline_object.selected === false) { cur_inline_object.select(pageIndex); _common_selection_array.push(cur_inline_object); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, cur_inline_object.Get_Id(), false, false)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } } editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return true; } } } sp.selectionSetStart(x, y, e); sp.select(pageIndex); drawing.GraphicObj.selectionInfo.selectionArray.push(sp); graphicObjects.changeCurrentState(new TextAddInGroup(graphicObjects, sp, drawing.GraphicObj)); if (e.ClickCount <= 1) { graphicObjects.updateSelectionState(); } editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return true; } } return false; } function handleInlineHitNoText(drawing, graphicObjects, e, x, y, pageIndex, handleState) { var _common_selection_array = graphicObjects.selectionInfo.selectionArray; graphicObjects.majorGraphicObject = drawing; if (! (e.CtrlKey || e.ShiftKey)) { var b_sel = drawing.selected; if (drawing.selected === false) { for (_sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; drawing.select(pageIndex); _common_selection_array.push(drawing); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, drawing.Get_Id(), false, b_sel)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return; } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === drawing) { b_sel = drawing.selected; if (drawing.selected === false) { drawing.select(pageIndex); _common_selection_array.push(drawing); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, drawing.Get_Id(), false, b_sel)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return; } } function handleInlineObjects(inlineObjects, graphicObjects, e, x, y, pageIndex, handleState) { for (_object_index = inlineObjects.length - 1; _object_index > -1; --_object_index) { var _current_graphic_object = inlineObjects[_object_index]; if (!_current_graphic_object.isShapeChild()) { if (_current_graphic_object.GraphicObj instanceof WordShape || _current_graphic_object.GraphicObj instanceof WordImage) { if (handleInlineShapeImage(_current_graphic_object, graphicObjects, e, x, y, pageIndex, handleState)) { return true; } } else { if (_current_graphic_object.GraphicObj instanceof WordGroupShapes) { if (handleInlineGroup(_current_graphic_object, graphicObjects, e, x, y, pageIndex, handleState)) { return true; } } else { if (typeof CChartAsGroup != "undefined" && _current_graphic_object.GraphicObj instanceof CChartAsGroup) { if (handleChart(_current_graphic_object, graphicObjects, x, y, e, pageIndex) === true) { return true; } } } } } } return false; } function handleChart(paraDrawing, graphicObjects, x, y, e, pageIndex) { var chart = paraDrawing.GraphicObj; var titles = []; if (! (e.CtrlKey || e.ShiftKey)) { if (isRealObject(chart.chartTitle)) { titles.push(chart.chartTitle); } if (isRealObject(chart.hAxisTitle)) { titles.push(chart.hAxisTitle); } if (isRealObject(chart.vAxisTitle)) { titles.push(chart.vAxisTitle); } for (var i = 0; i < titles.length; ++i) { var cur_title = titles[i]; var hit = cur_title.hit(x, y); var hit_in_text_rect = cur_title.hitInTextRect(x, y); if (chart.selected) { if (!cur_title.selected && hit && !hit_in_text_rect) { var selected_objects = graphicObjects.selectionInfo.selectionArray; for (var j = 0; j < selected_objects.length; ++j) { selected_objects[j].deselect(); } selected_objects.length = 0; paraDrawing.select(pageIndex); selected_objects.push(paraDrawing); for (var j = 0; j < titles.length; ++j) { if (titles[j]) { titles[j].deselect(); } } cur_title.select(pageIndex); graphicObjects.arrPreTrackObjects.push(new MoveTitleInChart(cur_title)); graphicObjects.changeCurrentState(new PreMoveChartTitleState(graphicObjects, cur_title, paraDrawing, x, y, pageIndex)); editor.WordControl.m_oLogicDocument.Document_UpdateSelectionState(); editor.WordControl.OnUpdateOverlay(); return true; } else { if (hit_in_text_rect) { var selected_objects = graphicObjects.selectionInfo.selectionArray; for (var j = 0; j < selected_objects.length; ++j) { selected_objects[j].deselect(); } selected_objects.length = 0; for (var j = 0; j < titles.length; ++j) { if (titles[j]) { titles[j].deselect(); } } paraDrawing.select(pageIndex); cur_title.select(pageIndex); graphicObjects.selectionInfo.selectionArray.push(paraDrawing); graphicObjects.changeCurrentState(new TextAddInChartTitle(graphicObjects, paraDrawing, cur_title)); cur_title.selectionSetStart(e, x, y, pageIndex); if (e.ClickCount < 2) { graphicObjects.updateSelectionState(); } return true; } else { if (hit) { graphicObjects.arrPreTrackObjects.push(new MoveTitleInChart(cur_title)); graphicObjects.changeCurrentState(new PreMoveChartTitleState(graphicObjects, cur_title, paraDrawing, x, y, pageIndex)); editor.WordControl.m_oLogicDocument.Document_UpdateSelectionState(); editor.WordControl.OnUpdateOverlay(); return true; } } } } else { if (hit && !hit_in_text_rect) { var selected_objects = graphicObjects.selectionInfo.selectionArray; for (var j = 0; j < selected_objects.length; ++j) { selected_objects[j].deselect(); } selected_objects.length = 0; for (var j = 0; j < titles.length; ++j) { if (titles[j]) { titles[j].deselect(); } } paraDrawing.select(pageIndex); cur_title.select(pageIndex); graphicObjects.selectionInfo.selectionArray.push(paraDrawing); graphicObjects.arrPreTrackObjects.push(new MoveTitleInChart(cur_title)); graphicObjects.changeCurrentState(new PreMoveChartTitleState(graphicObjects, cur_title, paraDrawing, x, y, pageIndex)); editor.WordControl.m_oLogicDocument.Document_UpdateSelectionState(); editor.WordControl.OnUpdateOverlay(); return true; } else { if (hit_in_text_rect) { var selected_objects = graphicObjects.selectionInfo.selectionArray; for (var j = 0; j < selected_objects.length; ++j) { selected_objects[j].deselect(); } selected_objects.length = 0; for (var j = 0; j < titles.length; ++j) { if (titles[j]) { titles[j].deselect(); } } paraDrawing.select(pageIndex); cur_title.select(pageIndex); graphicObjects.selectionInfo.selectionArray.push(paraDrawing); graphicObjects.changeCurrentState(new TextAddInChartTitle(graphicObjects, paraDrawing, cur_title)); cur_title.selectionSetStart(e, x, y, pageIndex); graphicObjects.updateSelectionState(); editor.WordControl.OnUpdateOverlay(); return true; } } } } } if (!chart.parent.Is_Inline()) { var _hit = chart.hit(x, y); var _hit_to_path = hit; var b_hit_to_text = false; var _common_selection_array = graphicObjects.selectionInfo.selectionArray; if ((_hit && !b_hit_to_text) || _hit_to_path) { graphicObjects.majorGraphicObject = chart.parent; if (! (e.CtrlKey || e.ShiftKey)) { if (chart.selected === false) { for (var _sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; chart.select(pageIndex); _common_selection_array.push(paraDrawing); editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); _common_selection_array.sort(ComparisonByZIndex); graphicObjects.arrPreTrackObjects.length = 0; graphicObjects.arrPreTrackObjects[0] = new CTrackMoveObject(chart.parent, chart.absOffsetX - x, chart.absOffsetY - y, graphicObjects, pageIndex); if (_common_selection_array.length === 1) { var pre_track = _common_selection_array[0]; pre_track.calculateOffset(); var boundsOffX = pre_track.absOffsetX - pre_track.boundsOffsetX; var boundsOffY = pre_track.absOffsetY - pre_track.boundsOffsetY; graphicObjects.curState.anchorPos = pre_track.Get_AnchorPos(); graphicObjects.curState.anchorPos.Page = pageIndex; } graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); graphicObjects.changeCurrentState(new PreMoveState(graphicObjects, false, false)); return true; } else { graphicObjects.arrPreTrackObjects.length = 0; for (_sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { if (_common_selection_array[_sel_index].pageIndex === pageIndex) { _common_selection_array[_sel_index]; graphicObjects.arrPreTrackObjects.push(new CTrackMoveObject(_common_selection_array[_sel_index], _common_selection_array[_sel_index].absOffsetX - x, _common_selection_array[_sel_index].absOffsetY - y, graphicObjects, pageIndex)); } } if (_common_selection_array.length === 1) { var pre_track = _common_selection_array[0]; pre_track.calculateOffset(); var boundsOffX = pre_track.absOffsetX - pre_track.boundsOffsetX; var boundsOffY = pre_track.absOffsetY - pre_track.boundsOffsetY; graphicObjects.curState.anchorPos = pre_track.Get_AnchorPos(); graphicObjects.curState.anchorPos.Page = pageIndex; graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } graphicObjects.changeCurrentState(new PreMoveState(graphicObjects, false, true)); return true; } } else { if ((_common_selection_array.length > 0 && _common_selection_array[0].Is_Inline())) { return true; } if (chart.parent.selected === false) { chart.parent.select(pageIndex); _common_selection_array.push(chart.parent); _common_selection_array.sort(ComparisonByZIndex); editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); } graphicObjects.arrPreTrackObjects.length = 0; for (_sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { if (_common_selection_array[_sel_index].pageIndex === pageIndex) { chart = _common_selection_array[_sel_index]; graphicObjects.arrPreTrackObjects.push(new CTrackMoveObject(chart, chart.absOffsetX - x, chart.absOffsetY - y, graphicObjects, pageIndex)); } } if (_common_selection_array.length === 1) { var pre_track = _common_selection_array[0]; pre_track.calculateOffset(); var boundsOffX = pre_track.absOffsetX - pre_track.boundsOffsetX; var boundsOffY = pre_track.absOffsetY - pre_track.boundsOffsetY; graphicObjects.curState.anchorPos = pre_track.Get_AnchorPos(); graphicObjects.curState.anchorPos.Page = pageIndex; } graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); graphicObjects.changeCurrentState(new PreMoveState(graphicObjects, true, false)); return true; } } } else { _hit = chart.parent.hit(x, y); if (_hit) { var _common_selection_array = graphicObjects.selectionInfo.selectionArray; var _current_graphic_object = paraDrawing; graphicObjects.majorGraphicObject = chart.parent; if (! (e.CtrlKey || e.ShiftKey)) { var b_sel = _current_graphic_object.selected; if (_current_graphic_object.selected === false) { for (_sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; _current_graphic_object.select(pageIndex); _common_selection_array.push(_current_graphic_object); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, _current_graphic_object.Get_Id(), false, b_sel)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return true; } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === _current_graphic_object) { b_sel = _current_graphic_object.selected; if (_current_graphic_object.selected === false) { _current_graphic_object.select(pageIndex); _common_selection_array.push(_current_graphic_object); } graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, _current_graphic_object.Get_Id(), false, b_sel)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } editor.asc_fireCallback("asc_canGroup", graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", graphicObjects.canUnGroup()); return true; } } } return false; } function handleSelectedObjectsGroup(graphicObjects, group, e, x, y, pageIndex, handleState) { var t_x, t_y; if (group.pageIndex === pageIndex || graphicObjects.document.CurPos.Type === docpostype_HdrFtr) { t_x = x; t_y = y; } else { var t_p = graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, group.pageIndex); t_x = t_p.X; t_y = t_p.Y; } var s_arr = group.selectionInfo.selectionArray; if (s_arr.length > 0) { if (s_arr.length === 1) { if (typeof s_arr[0].hitToAdj === "function") { var hit = s_arr[0].hitToAdj(t_x, t_y); if (hit.hit) { graphicObjects.arrPreTrackObjects.length = 0; if (!hit.adjPolarFlag) { graphicObjects.arrPreTrackObjects.push(new CTrackXYAdjObject(s_arr[0], hit.adjNum, group.pageIndex)); } else { graphicObjects.arrPreTrackObjects.push(new CTrackPolarAdjObject(s_arr[0], hit.adjNum, group.pageIndex)); } graphicObjects.changeCurrentState(new PreChangeAdjInGroup(graphicObjects, group)); return true; } } } for (var i = s_arr.length - 1; i > -1; --i) { if (typeof s_arr[i].hitToHandle === "function") { hit = s_arr[i].hitToHandle(t_x, t_y); if (hit.hit) { graphicObjects.arrPreTrackObjects.length = 0; if (!hit.handleRotate) { var card_dir = s_arr[i].numberToCardDirection(hit.handleNum); for (var j = 0; j < s_arr.length; ++j) { var handle_num = s_arr[j].cardDirectionToNumber(card_dir); graphicObjects.arrPreTrackObjects.push(new ShapeForResizeInGroup2(s_arr[j], handle_num)); } graphicObjects.changeCurrentState(new PreResizeInGroup(graphicObjects, group, s_arr[i], handle_num)); } else { if (!s_arr[i].canRotate()) { return false; } for (var _selected_index = 0; _selected_index < s_arr.length; ++_selected_index) { if (s_arr[_selected_index].canRotate()) { break; } } if (_selected_index === s_arr.length) { return false; } for (j = 0; j < s_arr.length; ++j) { graphicObjects.arrPreTrackObjects.push(new ShapeForRotateInGroup(s_arr[j])); } graphicObjects.changeCurrentState(new PreRotateInGroup(graphicObjects, group, s_arr[i])); } return true; } } } } hit = group.hitToHandle(t_x, t_y); if (hit.hit) { for (i = 0; i < group.selectionInfo.selectionArray.length; ++i) { group.selectionInfo.selectionArray[i].deselect(); } group.selectionInfo.selectionArray.length = 0; graphicObjects.majorGraphicObject = group.parent; graphicObjects.arrPreTrackObjects.length = 0; if (hit.handleRotate === false) { var _card_direction = group.numberToCardDirection(hit.handleNum); graphicObjects.arrPreTrackObjects.push(new CTrackHandleObject(group.parent, _card_direction, group.pageIndex)); graphicObjects.changeCurrentState(new PreResizeState(graphicObjects, hit.handleNum)); } else { if (!group.canRotate()) { return false; } graphicObjects.arrPreTrackObjects.push(new CTrackRotateObject(group.parent, group.pageIndex)); graphicObjects.changeCurrentState(new PreRotateState(graphicObjects)); } return true; } return false; } function handleSelectedObjectsGroupCursorType(graphicObjects, group, e, x, y, pageIndex, handleState) { var t_x, t_y; if (group.pageIndex === pageIndex || graphicObjects.document.CurPos.Type === docpostype_HdrFtr) { t_x = x; t_y = y; } else { var t_p = graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, group.pageIndex); t_x = t_p.X; t_y = t_p.Y; } var s_arr = group.selectionInfo.selectionArray; if (s_arr.length > 0) { if (s_arr.length === 1) { if (typeof s_arr[0].hitToAdj === "function") { var hit = s_arr[0].hitToAdj(t_x, t_y); if (hit.hit) { graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; } } } for (var i = s_arr.length - 1; i > -1; --i) { if (typeof s_arr[i].hitToHandle === "function") { hit = s_arr[i].hitToHandle(t_x, t_y); if (hit.hit) { graphicObjects.arrPreTrackObjects.length = 0; if (!hit.handleRotate) { var card_dir = s_arr[i].numberToCardDirection(hit.handleNum); graphicObjects.drawingDocument.SetCursorType(CURSOR_TYPES_BY_CARD_DIRECTION[card_dir]); } else { graphicObjects.drawingDocument.SetCursorType("crosshair"); } return true; } } } } hit = group.hitToHandle(t_x, t_y); if (hit.hit) { if (hit.handleRotate === false) { var _card_direction = group.numberToCardDirection(hit.handleNum); graphicObjects.drawingDocument.SetCursorType(CURSOR_TYPES_BY_CARD_DIRECTION[_card_direction]); } else { if (!group.canRotate()) { return false; } graphicObjects.drawingDocument.SetCursorType("crosshair"); } return true; } return false; } function handleFloatShapeImageCursorType(drawing, graphicObjects, e, x, y, pageIndex, handleState) { var _hit = drawing.hit(x, y); var _hit_to_path = drawing.hitToPath(x, y); var b_hit_to_text = drawing.hitToTextRect(x, y); if ((_hit && !b_hit_to_text) || _hit_to_path) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } else { if (b_hit_to_text) { var arr_inline_objects = drawing.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } } drawing.GraphicObj.updateCursorType(e, x, y, pageIndex); return true; } } return false; } function handleFloatGroupCursorType(drawing, graphicObjects, e, x, y, pageIndex, handleState) { var _hit = drawing.hit(x, y); var _hit_to_path = drawing.hitToPath(x, y); var _hit_to_text_rect = drawing.hitToTextRect(x, y); var b_hit_to_text = _hit_to_text_rect.hit; if ((_hit && !b_hit_to_text) || _hit_to_path) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } else { if (b_hit_to_text) { var sp = drawing.GraphicObj.spTree[_hit_to_text_rect.num]; if (typeof sp.getArrContentDrawingObjects === "function") { var arr_inline_objects = sp.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; var _hit = cur_inline_object.hit(x, y); if (_hit) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } } } sp.updateCursorType(e, x, y, pageIndex); return true; } } return false; } function handleFloatObjectsCursorType(drawingArray, graphicObjects, e, x, y, pageIndex, handleState) { for (var _object_index = drawingArray.length - 1; _object_index > -1; --_object_index) { var _current_graphic_object = drawingArray[_object_index]; if (_current_graphic_object.GraphicObj instanceof WordShape || _current_graphic_object.GraphicObj instanceof WordImage) { if (handleFloatShapeImageCursorType(_current_graphic_object, graphicObjects, e, x, y, pageIndex, handleState)) { return true; } } else { if (_current_graphic_object.GraphicObj instanceof WordGroupShapes) { if (handleFloatGroupCursorType(_current_graphic_object, graphicObjects, e, x, y, pageIndex, handleState)) { return true; } } else { if (typeof CChartAsGroup != "undefined" && _current_graphic_object.GraphicObj instanceof CChartAsGroup) { if (handleChartCursorType(_current_graphic_object, graphicObjects, x, y, e, pageIndex)) { return true; } } } } } return false; } function handleChartCursorType(paraDrawing, graphicObjects, x, y, e, pageIndex) { var chart = paraDrawing.GraphicObj; var titles = []; if (isRealObject(chart.chartTitle)) { titles.push(chart.chartTitle); } if (isRealObject(chart.hAxisTitle)) { titles.push(chart.hAxisTitle); } if (isRealObject(chart.vAxisTitle)) { titles.push(chart.vAxisTitle); } for (var i = 0; i < titles.length; ++i) { var cur_title = titles[i]; var hit = cur_title.hit(x, y); var hit_in_text_rect = cur_title.hitInTextRect(x, y); if (chart.selected) { if (!cur_title.selected && hit && !hit_in_text_rect) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } else { if (hit_in_text_rect) { cur_title.updateCursorType(e, x, y, pageIndex); return true; } else { if (hit) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } } } } else { if (hit && !hit_in_text_rect) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } else { if (hit_in_text_rect) { cur_title.updateCursorType(e, x, y, pageIndex); return true; } } } } if (!chart.parent.Is_Inline()) { var _hit = chart.hit(x, y); var _hit_to_path = hit; var _hit_to_text_rect = false; var b_hit_to_text = false; var _common_selection_array = graphicObjects.selectionInfo.selectionArray; if ((_hit && !b_hit_to_text) || _hit_to_path) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } } else { _hit = chart.parent.hit(x, y); if (_hit) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } } return false; } function handleInlineShapeImageCursorType(drawing, graphicObjects, e, x, y, pageIndex, handleState) { var _common_selection_array = graphicObjects.selectionInfo.selectionArray; var _hit = drawing.hit(x, y); var _hit_to_path = drawing.hitToPath(x, y); var b_hit_to_text = drawing.hitToTextRect(x, y); if ((_hit && !b_hit_to_text) || _hit_to_path) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } else { if (b_hit_to_text) { var arr_inline_objects = drawing.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; var _hit = cur_inline_object.hit(x, y); if (_hit) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } } drawing.GraphicObj.updateCursorType(e, x, y, pageIndex); return true; } } return false; } function handleInlineGroupCursorType(drawing, graphicObjects, e, x, y, pageIndex, handleState) { var _hit = drawing.hit(x, y); var _hit_to_path = drawing.hitToPath(x, y); var _hit_to_text_rect = drawing.hitToTextRect(x, y); var b_hit_to_text = _hit_to_text_rect.hit; if ((_hit && !b_hit_to_text) || _hit_to_path) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } else { if (b_hit_to_text) { var sp = drawing.GraphicObj.spTree[_hit_to_text_rect.num]; if (typeof sp.getArrContentDrawingObjects === "function") { var arr_inline_objects = sp.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; var _hit = cur_inline_object.hit(x, y); if (_hit) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } } } sp.updateCursorType(e, x, y, pageIndex); return true; } } return false; } function handleInlineObjectsCursorType(inlineObjects, graphicObjects, e, x, y, pageIndex, handleState) { for (var _object_index = inlineObjects.length - 1; _object_index > -1; --_object_index) { var _current_graphic_object = inlineObjects[_object_index]; if (!_current_graphic_object.isShapeChild()) { if (_current_graphic_object.GraphicObj instanceof WordShape || _current_graphic_object.GraphicObj instanceof WordImage) { if (handleInlineShapeImageCursorType(_current_graphic_object, graphicObjects, e, x, y, pageIndex, handleState)) { return true; } } else { if (_current_graphic_object.GraphicObj instanceof WordGroupShapes) { if (handleInlineGroupCursorType(_current_graphic_object, graphicObjects, e, x, y, pageIndex, handleState)) { return true; } } else { if (typeof CChartAsGroup != "undefined" && _current_graphic_object.GraphicObj instanceof CChartAsGroup) { if (handleChartCursorType(_current_graphic_object, graphicObjects, x, y, e, pageIndex) === true) { return true; } } } } } } return false; } function handleMouseDownNullState(graphicObjects, e, x, y, pageIndex, state) { graphicObjects.setStartTrackPos(x, y, pageIndex); var _graphic_pages = graphicObjects.graphicPages; var _common_selection_array = graphicObjects.selectionInfo.selectionArray; if (handleSelectedObjects(graphicObjects, e, x, y, pageIndex)) { return true; } var _cur_page = _graphic_pages[pageIndex]; var beforeTextArray = _cur_page.beforeTextObjects; if (handleFloatObjects(beforeTextArray, graphicObjects, e, x, y, pageIndex, state)) { return true; } var inline_objects = _cur_page.inlineObjects; if (handleInlineObjects(inline_objects, graphicObjects, e, x, y, pageIndex, state)) { return true; } var wrapping_array = _cur_page.wrappingObjects; if (handleFloatObjects(wrapping_array, graphicObjects, e, x, y, pageIndex, state)) { return true; } var behind_array = _cur_page.behindDocObjects; if (handleFloatObjects(behind_array, graphicObjects, e, x, y, pageIndex, state)) { return true; } for (var _sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); graphicObjects.updateSelectionState(); return false; } function handleMouseDownNullStateCursorType(graphicObjects, e, x, y, pageIndex, bTextFlag, state) { var _graphic_pages = graphicObjects.graphicPages; var _common_selection_array = graphicObjects.selectionInfo.selectionArray; if (handleSelectedObjectsCursorType(graphicObjects, e, x, y, pageIndex)) { return true; } var _cur_page = _graphic_pages[pageIndex]; var beforeTextArray = _cur_page.beforeTextObjects; if (handleFloatObjectsCursorType(beforeTextArray, graphicObjects, e, x, y, pageIndex, state)) { return true; } var inline_objects = _cur_page.inlineObjects; if (handleInlineObjectsCursorType(inline_objects, graphicObjects, e, x, y, pageIndex, state)) { return true; } if (!bTextFlag) { var wrapping_array = _cur_page.wrappingObjects; if (handleFloatObjectsCursorType(wrapping_array, graphicObjects, e, x, y, pageIndex, state)) { return true; } var behind_array = _cur_page.behindDocObjects; if (handleFloatObjectsCursorType(behind_array, graphicObjects, e, x, y, pageIndex, state)) { return true; } } return false; } function handleShapeImageGroup(drawing, group, graphicObjects, e, x, y, pageIndex, state) { var hit = drawing.hit(x, y); var hit_path = drawing.hitToPath(x, y); var hit_text = drawing.hitToTextRect(x, y); var _group_selection_array = group.selectionInfo.selectionArray; if ((hit && !hit_text) || hit_path) { if (! (e.CtrlKey || e.ShiftKey)) { if (drawing.selected === false) { for (var _sel_index = 0; _sel_index < _group_selection_array.length; ++_sel_index) { _group_selection_array[_sel_index].deselect(); } _group_selection_array.length = 0; drawing.select(pageIndex); _group_selection_array.push(drawing); graphicObjects.arrPreTrackObjects.length = 0; graphicObjects.arrPreTrackObjects[0] = new MoveTrackInGroup(drawing); graphicObjects.changeCurrentState(new PreMoveInGroup(graphicObjects, group, false, false, x, y)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } else { graphicObjects.arrPreTrackObjects.length = 0; for (_sel_index = 0; _sel_index < _group_selection_array.length; ++_sel_index) { graphicObjects.arrPreTrackObjects.push(new MoveTrackInGroup(_group_selection_array[_sel_index])); } graphicObjects.changeCurrentState(new PreMoveInGroup(graphicObjects, group, false, true, x, y)); if (typeof CChartAsGroup != "undefined" && drawing instanceof CChartAsGroup) { var selected_title = drawing.getSelectedTitle(); if (selected_title) { selected_title.deselect(); } graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } } return true; } else { if (drawing.selected === false) { drawing.select(pageIndex); _group_selection_array.push(drawing); _group_selection_array.sort(ComparisonByZIndexSimple); } graphicObjects.arrPreTrackObjects.length = 0; for (_sel_index = 0; _sel_index < _group_selection_array.length; ++_sel_index) { var _current_graphic_object = _group_selection_array[_sel_index]; graphicObjects.arrPreTrackObjects.push(new MoveTrackInGroup(_current_graphic_object)); } graphicObjects.changeCurrentState(new PreMoveInGroup(graphicObjects, group, false, true, x, y)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); return true; } } else { if (hit_text) { var arr_inline_objects = drawing.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; var _hit = cur_inline_object.hit(x, y); if (_hit) { graphicObjects.majorGraphicObject = cur_inline_object; for (var j = 0; j < _group_selection_array.length; ++j) { _group_selection_array[j].deselect(); } _group_selection_array.length = 0; group.deselect(); graphicObjects.selectionInfo.selectionArray.length = 0; graphicObjects.selectionInfo.selectionArray.push(cur_inline_object); graphicObjects.changeCurrentState(new PreMoveInlineObject(graphicObjects, cur_inline_object.Get_Id(), false, false)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); return true; } } for (var gr_sel_index = 0; gr_sel_index < _group_selection_array.length; ++gr_sel_index) { _group_selection_array[gr_sel_index].deselect(); } _group_selection_array.length = 0; drawing.selectionSetStart(x, y, e); drawing.select(pageIndex); _group_selection_array.push(drawing); graphicObjects.changeCurrentState(new TextAddInGroup(graphicObjects, drawing, group)); if (e.ClickCount <= 1) { graphicObjects.updateSelectionState(); } return true; } } return false; } function handleShapeImageGroupCursorType(drawing, group, graphicObjects, e, x, y, pageIndex, state) { var hit = drawing.hit(x, y); var hit_path = drawing.hitToPath(x, y); var hit_text = drawing.hitToTextRect(x, y); if ((hit && !hit_text) || hit_path) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } else { if (hit_text) { var arr_inline_objects = drawing.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; var _hit = cur_inline_object.hit(x, y); if (_hit) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } } drawing.updateCursorType(e, x, y, pageIndex); return true; } } return false; } function handleChartGroup(drawing, group, graphicObjects, e, x, y, pageIndex, state) { var chart = drawing; var titles = []; if (isRealObject(chart.chartTitle)) { titles.push(chart.chartTitle); } if (isRealObject(chart.hAxisTitle)) { titles.push(chart.hAxisTitle); } if (isRealObject(chart.vAxisTitle)) { titles.push(chart.vAxisTitle); } var group_selected_objects = group.selectionInfo.selectionArray; if (! (e.CtrlKey || e.ShiftKey)) { for (var i = 0; i < titles.length; ++i) { var cur_title = titles[i]; var hit = cur_title.hit(x, y); var hit_in_text_rect = cur_title.hitInTextRect(x, y); if (chart.selected) { if (!cur_title.selected && hit && !hit_in_text_rect) { for (var j = 0; j < group_selected_objects.length; ++j) { group_selected_objects[j].deselect(); } group_selected_objects.length = 0; for (var j = 0; j < titles.length; ++j) { if (titles[j]) { titles[j].deselect(); } } chart.select(pageIndex); group_selected_objects.push(chart); cur_title.select(pageIndex); graphicObjects.arrPreTrackObjects.push(new MoveTitleInChart(cur_title)); graphicObjects.changeCurrentState(new PreMoveChartTitleGroupState(graphicObjects, group.parent, cur_title, chart, x, y, pageIndex)); editor.WordControl.m_oLogicDocument.Document_UpdateSelectionState(); editor.WordControl.OnUpdateOverlay(); return true; } else { if (hit_in_text_rect) { for (var j = 0; j < group_selected_objects.length; ++j) { group_selected_objects[j].deselect(); } group_selected_objects.length = 0; for (var j = 0; j < titles.length; ++j) { if (titles[j]) { titles[j].deselect(); } } chart.select(pageIndex); cur_title.select(pageIndex); group.selectionInfo.selectionArray.push(chart); graphicObjects.changeCurrentState(new TextAddInChartTitleGroup(graphicObjects, group.parent, chart, cur_title)); cur_title.selectionSetStart(e, x, y, pageIndex); if (e.ClickCount < 2) { graphicObjects.updateSelectionState(); } editor.WordControl.OnUpdateOverlay(); return true; } else { if (hit) { graphicObjects.arrPreTrackObjects.push(new MoveTitleInChart(cur_title)); graphicObjects.changeCurrentState(new PreMoveChartTitleGroupState(graphicObjects, group.parent, cur_title, chart, x, y, pageIndex)); editor.WordControl.m_oLogicDocument.Document_UpdateSelectionState(); return true; } } } } else { if (hit && !hit_in_text_rect) { for (var j = 0; j < group_selected_objects.length; ++j) { group_selected_objects[j].deselect(); } group_selected_objects.length = 0; for (var j = 0; j < titles.length; ++j) { if (titles[j]) { titles[j].deselect(); } } chart.select(pageIndex); cur_title.select(pageIndex); group.selectionInfo.selectionArray.push(chart); graphicObjects.arrPreTrackObjects.push(new MoveTitleInChart(cur_title)); graphicObjects.changeCurrentState(new PreMoveChartTitleGroupState(graphicObjects, group.parent, cur_title, chart, x, y, pageIndex)); editor.WordControl.m_oLogicDocument.Document_UpdateSelectionState(); editor.WordControl.OnUpdateOverlay(); return true; } else { if (hit_in_text_rect) { for (var j = 0; j < group_selected_objects.length; ++j) { group_selected_objects[j].deselect(); } group_selected_objects.length = 0; for (var j = 0; j < titles.length; ++j) { if (titles[j]) { titles[j].deselect(); } } chart.select(pageIndex); cur_title.select(pageIndex); group.selectionInfo.selectionArray.push(chart); graphicObjects.changeCurrentState(new TextAddInChartTitleGroup(graphicObjects, group.parent, chart, cur_title)); cur_title.selectionSetStart(e, x, y, pageIndex); graphicObjects.updateSelectionState(); editor.WordControl.OnUpdateOverlay(); return true; } } } } } return handleShapeImageGroup(drawing, group, graphicObjects, e, x, y, pageIndex, state); } function handleChartGroupCursorType(drawing, group, graphicObjects, e, x, y, pageIndex, state) { var chart = drawing; var titles = []; if (isRealObject(chart.chartTitle)) { titles.push(chart.chartTitle); } if (isRealObject(chart.hAxisTitle)) { titles.push(chart.hAxisTitle); } if (isRealObject(chart.vAxisTitle)) { titles.push(chart.vAxisTitle); } var group_selected_objects = group.selectionInfo.selectionArray; if (! (e.CtrlKey || e.ShiftKey)) { for (var i = 0; i < titles.length; ++i) { var cur_title = titles[i]; var hit = cur_title.hit(x, y); var hit_in_text_rect = cur_title.hitInTextRect(x, y); if (chart.selected) { if (!cur_title.selected && hit && !hit_in_text_rect) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } else { if (hit_in_text_rect) { cur_title.updateCursorType(e, x, y, pageIndex); return true; } else { if (hit) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } } } } else { if (hit && !hit_in_text_rect) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } else { if (hit_in_text_rect) { cur_title.updateCursorType(e, x, y, pageIndex); return true; } } } } } return handleShapeImageGroupCursorType(drawing, group, graphicObjects, e, x, y, pageIndex, state); } function handleCurrentGroup(drawing, graphicObjects, e, x, y, pageIndex, state) { var group = drawing.GraphicObj; var sp_tree = group.getSpTree2(); for (var j = sp_tree.length - 1; j > -1; --j) { var cur_sp = sp_tree[j]; if (cur_sp instanceof WordShape || cur_sp instanceof WordImage) { if (handleShapeImageGroup(cur_sp, group, graphicObjects, e, x, y, pageIndex, state)) { return true; } } else { if (typeof CChartAsGroup != "undefined" && cur_sp instanceof CChartAsGroup) { if (handleChartGroup(cur_sp, group, graphicObjects, e, x, y, pageIndex, state)) { return true; } } } } if (group.hitInBox(x, y)) { for (var r = 0; r < group.selectionInfo.selectionArray.length; ++r) { group.selectionInfo.selectionArray[r].deselect(); } group.selectionInfo.selectionArray.length = 0; graphicObjects.arrPreTrackObjects.length = 0; graphicObjects.arrPreTrackObjects[0] = new CTrackMoveObject(group.parent, group.parent.absOffsetX - x, group.parent.absOffsetY - y, graphicObjects, pageIndex); graphicObjects.changeCurrentState(new PreMoveState(graphicObjects, false, false)); graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); return true; } return false; } function handleCurrentGroupCursorType(drawing, graphicObjects, e, x, y, pageIndex, state) { var group = drawing.GraphicObj; var sp_tree = group.getSpTree2(); for (var j = sp_tree.length - 1; j > -1; --j) { var cur_sp = sp_tree[j]; if (cur_sp instanceof WordShape || cur_sp instanceof WordImage) { if (handleShapeImageGroupCursorType(cur_sp, group, graphicObjects, e, x, y, pageIndex, state)) { return true; } } else { if (typeof CChartAsGroup != "undefined" && cur_sp instanceof CChartAsGroup) { if (handleChartGroupCursorType(cur_sp, group, graphicObjects, e, x, y, pageIndex, state)) { return true; } } } } if (group.hitInBox(x, y)) { graphicObjects.drawingDocument.SetCursorType("move"); return true; } return false; } function handleFloatObjectsGroupState(drawingArray, graphicObjects, e, x, y, pageIndex, state) { var group = state.group; for (var i = drawingArray.length - 1; i > -1; --i) { var _cur_object = drawingArray[i]; if (_cur_object !== group.parent) { if (_cur_object.GraphicObj instanceof WordShape || _cur_object instanceof WordImage) { if (handleFloatShapeImage(_cur_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } else { if (typeof CChartAsGroup != "undefined" && _cur_object.GraphicObj instanceof CChartAsGroup) { if (handleChart(_cur_object, graphicObjects, x, y, e, pageIndex)) { return true; } } else { if (_cur_object.GraphicObj instanceof WordGroupShapes) { if (handleFloatGroup(_cur_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } } } } else { if (handleCurrentGroup(_cur_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } } return false; } function handleFloatObjectsGroupStateCursorType(drawingArray, graphicObjects, e, x, y, pageIndex, state) { var group = state.group; for (var i = drawingArray.length - 1; i > -1; --i) { var _cur_object = drawingArray[i]; if (_cur_object !== group.parent) { if (_cur_object.GraphicObj instanceof WordShape || _cur_object instanceof WordImage) { if (handleFloatShapeImageCursorType(_cur_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } else { if (typeof CChartAsGroup != "undefined" && _cur_object.GraphicObj instanceof CChartAsGroup) { if (handleChartCursorType(_cur_object, graphicObjects, x, y, e, pageIndex)) { return true; } } else { if (_cur_object.GraphicObj instanceof WordGroupShapes) { if (handleFloatGroupCursorType(_cur_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } } } } else { if (handleCurrentGroupCursorType(_cur_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } } return false; } function handleInlineObjectsGroupState(drawingArray, graphicObjects, e, x, y, pageIndex, state) { for (var i = drawingArray.length - 1; i > -1; --i) { var _current_graphic_object = drawingArray[i]; if (_current_graphic_object !== state.groupWordGO && !_current_graphic_object.isShapeChild()) { if (_current_graphic_object.GraphicObj instanceof WordShape || _current_graphic_object.GraphicObj instanceof WordImage) { if (handleInlineShapeImage(_current_graphic_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } else { if (typeof CChartAsGroup != "undefined" && _current_graphic_object.GraphicObj instanceof CChartAsGroup) { if (handleChart(_current_graphic_object, graphicObjects, x, y, e, pageIndex)) { return true; } } else { if (_current_graphic_object instanceof WordGroupShapes) { if (handleInlineGroup(_current_graphic_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } } } } else { if (handleCurrentGroup(_current_graphic_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } } return false; } function handleInlineObjectsGroupStateCursorType(drawingArray, graphicObjects, e, x, y, pageIndex, state) { for (var i = drawingArray.length - 1; i > -1; --i) { var _current_graphic_object = drawingArray[i]; if (_current_graphic_object !== state.groupWordGO && !_current_graphic_object.isShapeChild()) { if (_current_graphic_object.GraphicObj instanceof WordShape || _current_graphic_object.GraphicObj instanceof WordImage) { if (handleInlineShapeImageCursorType(_current_graphic_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } else { if (typeof CChartAsGroup != "undefined" && _current_graphic_object.GraphicObj instanceof CChartAsGroup) { if (handleChartCursorType(_current_graphic_object, graphicObjects, x, y, e, pageIndex)) { return true; } } else { if (_current_graphic_object instanceof WordGroupShapes) { if (handleInlineGroupCursorType(_current_graphic_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } } } } else { if (handleCurrentGroupCursorType(_current_graphic_object, graphicObjects, e, x, y, pageIndex, state)) { return true; } } } return false; } function handleGroupState(graphicObjects, group, e, x, y, pageIndex, state) { var before_arr, inline_arr, wrap_arr, behind_arr; if (graphicObjects.document.CurPos.Type !== docpostype_HdrFtr) { before_arr = graphicObjects.graphicPages[pageIndex].beforeTextObjects; inline_arr = graphicObjects.graphicPages[pageIndex].inlineObjects; wrap_arr = graphicObjects.graphicPages[pageIndex].wrappingObjects; behind_arr = graphicObjects.graphicPages[pageIndex].behindDocObjects; } else { var hdr_ftr; if (pageIndex === 0) { hdr_ftr = graphicObjects.firstPage; } else { if (pageIndex % 2 === 1) { hdr_ftr = graphicObjects.evenPage; } else { hdr_ftr = graphicObjects.oddPage; } } if (isRealObject(hdr_ftr)) { before_arr = hdr_ftr.beforeTextArray; inline_arr = hdr_ftr.inlineArray; wrap_arr = hdr_ftr.wrappingArray; behind_arr = hdr_ftr.behindDocArray; } } if (handleSelectedObjectsGroup(graphicObjects, group, e, x, y, pageIndex, state)) { return; } if (handleFloatObjectsGroupState(before_arr, graphicObjects, e, x, y, pageIndex, state)) { return; } if (handleInlineObjectsGroupState(inline_arr, graphicObjects, e, x, y, pageIndex, state)) { return; } if (handleFloatObjectsGroupState(wrap_arr, graphicObjects, e, x, y, pageIndex, state)) { return; } if (handleFloatObjectsGroupState(behind_arr, graphicObjects, e, x, y, pageIndex, state)) { return; } var gr_sel_arr = group.selectionInfo.selectionArray; for (var i = 0; i < gr_sel_arr.length; ++i) { gr_sel_arr[i].deselect(); } gr_sel_arr.length = 0; group.parent.deselect(); graphicObjects.selectionInfo.selectionArray.length = 0; graphicObjects.changeCurrentState(new NullState(graphicObjects)); graphicObjects.curState.updateAnchorPos(); } function handleGroupStateCursorType(graphicObjects, group, e, x, y, pageIndex, state, textFlag) { var before_arr, inline_arr, wrap_arr, behind_arr; if (graphicObjects.document.CurPos.Type !== docpostype_HdrFtr) { before_arr = graphicObjects.graphicPages[pageIndex].beforeTextObjects; inline_arr = graphicObjects.graphicPages[pageIndex].inlineObjects; wrap_arr = graphicObjects.graphicPages[pageIndex].wrappingObjects; behind_arr = graphicObjects.graphicPages[pageIndex].behindDocObjects; } else { var hdr_ftr; if (pageIndex === 0) { hdr_ftr = graphicObjects.firstPage; } else { if (pageIndex % 2 === 1) { hdr_ftr = graphicObjects.evenPage; } else { hdr_ftr = graphicObjects.oddPage; } } if (isRealObject(hdr_ftr)) { before_arr = hdr_ftr.beforeTextArray; inline_arr = hdr_ftr.inlineArray; wrap_arr = hdr_ftr.wrappingArray; behind_arr = hdr_ftr.behindDocArray; } } if (handleSelectedObjectsGroupCursorType(graphicObjects, group, e, x, y, pageIndex, state)) { return true; } if (handleFloatObjectsGroupStateCursorType(before_arr, graphicObjects, e, x, y, pageIndex, state)) { return true; } if (handleInlineObjectsGroupStateCursorType(inline_arr, graphicObjects, e, x, y, pageIndex, state)) { return true; } if (!textFlag) { if (handleFloatObjectsGroupStateCursorType(wrap_arr, graphicObjects, e, x, y, pageIndex, state)) { return true; } if (handleFloatObjectsGroupStateCursorType(behind_arr, graphicObjects, e, x, y, pageIndex, state)) { return true; } } return false; } function NullState(graphicObjects) { this.id = STATES_ID_NULL; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) { if (this.graphicObjects.document.CurPos.Type === docpostype_HdrFtr) { this.graphicObjects.changeCurrentState(new NullStateHeaderFooter(this.graphicObjects)); this.graphicObjects.curState.OnMouseDown(e, x, y, pageIndex); return; } handleMouseDownNullState(this.graphicObjects, e, x, y, pageIndex, this); }; this.OnMouseMove = function (e, x, y, pageIndex) {}; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) { if (this.graphicObjects.document.CurPos.Type === docpostype_HdrFtr) { var hdr_ftr_state = new NullStateHeaderFooter(this.graphicObjects); return hdr_ftr_state.updateCursorType(pageIndex, x, y, e, bTextFlag); } return handleMouseDownNullStateCursorType(this.graphicObjects, e, x, y, pageIndex, bTextFlag, this); }; this.updateAnchorPos = function () { if (isRealObject(this.graphicObjects.selectionInfo) && isRealObject(this.graphicObjects.selectionInfo.selectionArray)) { var selection_array = this.graphicObjects.selectionInfo.selectionArray; if (selection_array.length === 1 && !selection_array[0].Is_Inline()) { this.anchorPos = selection_array[0].Get_AnchorPos(); this.anchorPos.Page = selection_array[0].getPageIndex(); } else { delete this.anchorPos; } } }; } function NullStateHeaderFooter(graphicObjects) { this.id = STATES_ID_NULL_HF; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) { var bFirst = (0 === pageIndex ? true : false); var bEven = (pageIndex % 2 === 1 ? true : false); var graphicObjects = this.graphicObjects; var hdr_footer_objects; if (bFirst) { hdr_footer_objects = this.graphicObjects.firstPage; } else { if (bEven) { hdr_footer_objects = this.graphicObjects.evenPage; } else { hdr_footer_objects = this.graphicObjects.oddPage; } } graphicObjects.setStartTrackPos(x, y, pageIndex); var _graphic_pages = graphicObjects.graphicPages; var _common_selection_array = graphicObjects.selectionInfo.selectionArray; var state = this; if (handleSelectedObjects(graphicObjects, e, x, y, pageIndex)) { return true; } var _cur_page = _graphic_pages[pageIndex]; var beforeTextArray = hdr_footer_objects.beforeTextArray; if (handleFloatObjects(beforeTextArray, graphicObjects, e, x, y, pageIndex, state)) { return true; } var inline_objects = hdr_footer_objects.inlineArray; if (handleInlineObjects(inline_objects, graphicObjects, e, x, y, pageIndex, state)) { return true; } var wrapping_array = hdr_footer_objects.wrappingArray; if (handleFloatObjects(wrapping_array, graphicObjects, e, x, y, pageIndex, state)) { return true; } var behind_array = hdr_footer_objects.behindDocArray; if (handleFloatObjects(behind_array, graphicObjects, e, x, y, pageIndex, state)) { return true; } for (var _sel_index = 0; _sel_index < _common_selection_array.length; ++_sel_index) { _common_selection_array[_sel_index].deselect(); } _common_selection_array.length = 0; graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); graphicObjects.updateSelectionState(); return false; }; this.OnMouseMove = function (e, x, y, pageIndex) {}; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) { var _graphic_pages = this.graphicObjects.graphicPages; var _common_selection_array = this.graphicObjects.selectionInfo.selectionArray; if (_common_selection_array.length > 0) { if (_common_selection_array.length === 1) { var _selected_gr_object = _common_selection_array[0]; var _translated_x; var _translated_y; if (isRealObject(_selected_gr_object) && isRealObject(_selected_gr_object.GraphicObj) && _selected_gr_object.GraphicObj.selectStartPage !== pageIndex) { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, _selected_gr_object.GraphicObj.selectStartPage); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var _hit_to_adj = _selected_gr_object.hitToAdj(_translated_x, _translated_y); if (_hit_to_adj.hit === true) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; } } for (var _index = _common_selection_array.length - 1; _index > -1; --_index) { var _cur_selected_gr_object = _common_selection_array[_index]; if (isRealObject(_cur_selected_gr_object) && isRealObject(_cur_selected_gr_object.GraphicObj) && _cur_selected_gr_object.GraphicObj.selectStartPage !== pageIndex) { _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, _cur_selected_gr_object.GraphicObj.selectStartPage); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var _hit_to_handle = _cur_selected_gr_object.hitToHandle(_translated_x, _translated_y); if (_hit_to_handle.hit === true) { this.graphicObjects.majorGraphicObject = _cur_selected_gr_object; this.graphicObjects.arrPreTrackObjects.length = 0; if (_hit_to_handle.handleRotate === false) { this.graphicObjects.drawingDocument.SetCursorType(_cur_selected_gr_object.getCursorTypeByNum(_hit_to_handle.handleNum)); } else { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); } return true; } } } var hdr_footer_objects; var bFirst = (0 === pageIndex ? true : false); var bEven = (pageIndex % 2 === 1 ? true : false); if (bFirst) { hdr_footer_objects = this.graphicObjects.firstPage; } else { if (bEven) { hdr_footer_objects = this.graphicObjects.evenPage; } else { hdr_footer_objects = this.graphicObjects.oddPage; } } if (!isRealObject(hdr_footer_objects)) { return false; } var beforeTextArray = hdr_footer_objects.beforeTextArray; for (var _object_index = beforeTextArray.length - 1; _object_index > -1; --_object_index) { var _current_graphic_object = beforeTextArray[_object_index]; var _hit = _current_graphic_object.hit(x, y); var _hit_to_path = _current_graphic_object.hitToPath(x, y); var _hit_to_text_rect = _current_graphic_object.hitToTextRect(x, y); var b_hit_to_text = _current_graphic_object.isGroup() ? _hit_to_text_rect.hit : _hit_to_text_rect; if ((_hit && !b_hit_to_text) || _hit_to_path) { this.graphicObjects.majorGraphicObject = _current_graphic_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if ((_common_selection_array.length > 0 && _common_selection_array[0].Is_Inline())) { this.graphicObjects.drawingDocument.SetCursorType("default"); } else { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } else { if (b_hit_to_text) { if (!_current_graphic_object.isGroup()) { var arr_inline_objects = _current_graphic_object.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { this.graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } } var tmp2 = global_MatrixTransformer.Invert(_current_graphic_object.GraphicObj.transformText); var Xt = tmp2.TransformPointX(x, y); var Yt = tmp2.TransformPointY(x, y); _current_graphic_object.GraphicObj.textBoxContent.Update_CursorType(Xt, Yt, pageIndex); } else { var obj = _current_graphic_object.GraphicObj.spTree[_hit_to_text_rect.num]; if (typeof obj.getArrContentDrawingObjects === "function") { arr_inline_objects = obj.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { this.graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } } } tmp2 = global_MatrixTransformer.Invert(obj.transformText); Xt = tmp2.TransformPointX(x, y); Yt = tmp2.TransformPointY(x, y); obj.textBoxContent.Update_CursorType(Xt, Yt, pageIndex); } return true; } } } var inline_objects = hdr_footer_objects.inlineArray; for (_object_index = inline_objects.length - 1; _object_index > -1; --_object_index) { _current_graphic_object = inline_objects[_object_index]; if (!_current_graphic_object.isShapeChild()) { _hit = _current_graphic_object.hit(x, y); _hit_to_path = _current_graphic_object.hitToPath(x, y); _hit_to_text_rect = _current_graphic_object.hitToTextRect(x, y); b_hit_to_text = _current_graphic_object.isGroup() ? _hit_to_text_rect.hit : _hit_to_text_rect; if ((_hit && !b_hit_to_text) || _hit_to_path) { this.graphicObjects.majorGraphicObject = _current_graphic_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === _current_graphic_object) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { this.graphicObjects.drawingDocument.SetCursorType("default"); } } return true; } else { if (b_hit_to_text) { if (!_current_graphic_object.isGroup()) { var arr_inline_objects = _current_graphic_object.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { this.graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } } var tmp2 = global_MatrixTransformer.Invert(_current_graphic_object.GraphicObj.transformText); var Xt = tmp2.TransformPointX(x, y); var Yt = tmp2.TransformPointY(x, y); _current_graphic_object.GraphicObj.textBoxContent.Update_CursorType(Xt, Yt, pageIndex); } else { var obj = _current_graphic_object.GraphicObj.spTree[_hit_to_text_rect.num]; if (typeof obj.getArrContentDrawingObjects === "function") { arr_inline_objects = obj.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { this.graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } } } tmp2 = global_MatrixTransformer.Invert(obj.transformText); Xt = tmp2.TransformPointX(x, y); Yt = tmp2.TransformPointY(x, y); obj.textBoxContent.Update_CursorType(Xt, Yt, pageIndex); } return true; } } } } if (!bTextFlag) { var wrapping_array = hdr_footer_objects.wrappingArray; for (var _object_index = wrapping_array.length - 1; _object_index > -1; --_object_index) { var _current_graphic_object = wrapping_array[_object_index]; var _hit = _current_graphic_object.hit(x, y); var _hit_to_path = _current_graphic_object.hitToPath(x, y); var _hit_to_text_rect = _current_graphic_object.hitToTextRect(x, y); var b_hit_to_text = _current_graphic_object.isGroup() ? _hit_to_text_rect.hit : _hit_to_text_rect; if ((_hit && !b_hit_to_text) || _hit_to_path) { this.graphicObjects.majorGraphicObject = _current_graphic_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if ((_common_selection_array.length > 0 && _common_selection_array[0].Is_Inline())) { this.graphicObjects.drawingDocument.SetCursorType("default"); } else { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } else { if (b_hit_to_text) { if (!_current_graphic_object.isGroup()) { var arr_inline_objects = _current_graphic_object.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { this.graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } } var tmp2 = global_MatrixTransformer.Invert(_current_graphic_object.GraphicObj.transformText); var Xt = tmp2.TransformPointX(x, y); var Yt = tmp2.TransformPointY(x, y); _current_graphic_object.GraphicObj.textBoxContent.Update_CursorType(Xt, Yt, pageIndex); } else { var obj = _current_graphic_object.GraphicObj.spTree[_hit_to_text_rect.num]; if (typeof obj.getArrContentDrawingObjects === "function") { arr_inline_objects = obj.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { this.graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } } } tmp2 = global_MatrixTransformer.Invert(obj.transformText); Xt = tmp2.TransformPointX(x, y); Yt = tmp2.TransformPointY(x, y); obj.textBoxContent.Update_CursorType(Xt, Yt, pageIndex); } return true; } } } var behind_array = hdr_footer_objects.behindDocArray; for (var _object_index = behind_array.length - 1; _object_index > -1; --_object_index) { var _current_graphic_object = behind_array[_object_index]; var _hit = _current_graphic_object.hit(x, y); var _hit_to_path = _current_graphic_object.hitToPath(x, y); var _hit_to_text_rect = _current_graphic_object.hitToTextRect(x, y); var b_hit_to_text = _current_graphic_object.isGroup() ? _hit_to_text_rect.hit : _hit_to_text_rect; if ((_hit && !b_hit_to_text) || _hit_to_path) { this.graphicObjects.majorGraphicObject = _current_graphic_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if ((_common_selection_array.length > 0 && _common_selection_array[0].Is_Inline())) { this.graphicObjects.drawingDocument.SetCursorType("default"); } else { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } else { if (b_hit_to_text) { if (!_current_graphic_object.isGroup()) { var arr_inline_objects = _current_graphic_object.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { this.graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } } var tmp2 = global_MatrixTransformer.Invert(_current_graphic_object.GraphicObj.transformText); var Xt = tmp2.TransformPointX(x, y); var Yt = tmp2.TransformPointY(x, y); _current_graphic_object.GraphicObj.textBoxContent.Update_CursorType(Xt, Yt, pageIndex); } else { var obj = _current_graphic_object.GraphicObj.spTree[_hit_to_text_rect.num]; if (typeof obj.getArrContentDrawingObjects === "function") { arr_inline_objects = obj.getArrContentDrawingObjects(); for (var inline_index = 0; inline_index < arr_inline_objects.length; ++inline_index) { var cur_inline_object = arr_inline_objects[inline_index]; _hit = cur_inline_object.hit(x, y); if (_hit) { this.graphicObjects.majorGraphicObject = cur_inline_object; if (! (e.CtrlKey || e.ShiftKey)) { this.graphicObjects.drawingDocument.SetCursorType("move"); } else { if (_common_selection_array.length === 0 || _common_selection_array.length === 1 && _common_selection_array[0] === cur_inline_object) { this.graphicObjects.drawingDocument.SetCursorType("move"); } } return true; } } } tmp2 = global_MatrixTransformer.Invert(obj.transformText); Xt = tmp2.TransformPointX(x, y); Yt = tmp2.TransformPointY(x, y); obj.textBoxContent.Update_CursorType(Xt, Yt, pageIndex); } return true; } } } } return false; }; } function ChartState(graphicObjects, chart) { this.id = STATES_ID_CHART; this.graphicObjects = graphicObjects; this.chart = chart; this.headerFooterState = new NullStateHeaderFooter(this.graphicObjects); this.OnMouseDown = function (e, x, y, pageIndex) { if (this.graphicObjects.document.CurPos.Type === docpostype_HdrFtr) { this.headerFooterState.OnMouseDown(e, x, y, pageIndex); } else { handleMouseDownNullState(this.graphicObjects, e, x, y, pageIndex, this); } }; this.OnMouseMove = function (e, x, y, pageIndex) {}; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) { if (this.graphicObjects.document.CurPos.Type === docpostype_HdrFtr) { var hdr_ftr_state = new NullStateHeaderFooter(this.graphicObjects); return hdr_ftr_state.updateCursorType(pageIndex, x, y, e, bTextFlag); } return handleMouseDownNullStateCursorType(this.graphicObjects, e, x, y, pageIndex, bTextFlag, this); }; } function TextAddInChartTitle(graphicObjects, chart, title) { this.id = STATES_ID_CHART_TITLE_TEXT; this.graphicObjects = graphicObjects; this.chart = chart; this.title = title; this.chartState = new ChartState(graphicObjects, chart); this.OnMouseDown = function (e, x, y, pageIndex) { this.chartState.OnMouseDown(e, x, y, pageIndex); if (this.graphicObjects.curState.id !== STATES_ID_CHART_TITLE_TEXT || this.graphicObjects.curState.title !== this.title) { this.chart.GraphicObj.recalculate(); this.graphicObjects.updateCharts(); } }; this.OnMouseMove = function (e, x, y, pageIndex) { if (e.IsLocked) { this.title.selectionSetEnd(e, x, y, pageIndex); this.graphicObjects.updateSelectionState(); } }; this.OnMouseUp = function (e, x, y, pageIndex) { this.title.selectionSetEnd(e, x, y, pageIndex); this.graphicObjects.updateSelectionState(); }; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) { return this.chartState.updateCursorType(pageIndex, x, y, e, bTextFlag); }; } function TextAddInChartTitleGroup(graphicObjects, group, chart, title) { this.id = STATES_ID_CHART_TITLE_TEXT_GROUP; this.graphicObjects = graphicObjects; this.chart = chart; this.title = title; this.group = group; this.textObject = title; this.groupWordGO = group.GraphicObj; this.chartGroupState = new ChartGroupState(graphicObjects, group, chart); this.OnMouseDown = function (e, x, y, pageIndex) { this.chartGroupState.OnMouseDown(e, x, y, pageIndex); }; this.OnMouseMove = function (e, x, y, pageIndex) { if (e.IsLocked) { this.title.selectionSetEnd(e, x, y, pageIndex); this.title.updateSelectionState(editor.WordControl.m_oDrawingDocument); } }; this.OnMouseUp = function (e, x, y, pageIndex) { this.title.selectionSetEnd(e, x, y, pageIndex); this.title.updateSelectionState(editor.WordControl.m_oDrawingDocument); }; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) { return this.chartGroupState.updateCursorType(pageIndex, x, y, e, bTextFlag); }; } function ChartGroupState(graphicObjects, group, chart) { this.id = STATES_ID_CHART_GROUP; this.graphicObjects = graphicObjects; this.chart = chart; this.group = group; this.groupState = new GroupState(this.graphicObjects, this.group); this.OnMouseDown = function (e, x, y, pageIndex) { this.groupState.OnMouseDown(e, x, y, pageIndex); }; this.OnMouseMove = function (e, x, y, pageIndex) { if (e.IsLocked) { this.title.selectionSetEnd(e, x, y, pageIndex); this.graphicObjects.updateSelectionState(); } }; this.OnMouseUp = function (e, x, y, pageIndex) { this.title.selectionSetEnd(e, x, y, pageIndex); this.graphicObjects.updateSelectionState(); }; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) { return this.groupState.updateCursorType(pageIndex, x, y, e, bTextFlag); }; } function PreMoveChartTitleGroupState(graphicObjects, group, title, chart, startX, startY, startPageIndex) { this.id = STATES_ID_PRE_MOVE_CHART_TITLE_GROUP; this.graphicObjects = graphicObjects; this.group = group; this.title = title; this.chart = chart; this.startX = startX; this.startY = startY; this.startPageIndex = startPageIndex; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { if (x === this.startX && y === this.startY && this.startPageIndex === pageIndex) { return; } this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new MoveChartTitleGroupState(this.graphicObjects, this.group, this.title, this.chart, this.startX, this.startY, this.startPageIndex)); }; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) {}; } function MoveChartTitleGroupState(graphicObjects, group, title, chart, startX, startY, startPageIndex) { this.id = STATES_ID_MOVE_CHART_TITLE_GROUP; this.graphicObjects = graphicObjects; this.group = group; this.title = title; this.chart = chart; this.startX = startX; this.startY = startY; this.startPageIndex = startPageIndex; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var tx, ty; if (pageIndex === this.startPageIndex) { tx = x; ty = y; } else { var tp = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.startPageIndex); tx = tp.X; ty = tp.Y; } var dx = tx - this.startX; var dy = ty - this.startY; this.graphicObjects.arrTrackObjects[0].track(dx, dy, pageIndex); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var doc = editor.WordControl.m_oLogicDocument; if (false === editor.isViewMode && false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.group.Parent, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); this.graphicObjects.arrTrackObjects[0].trackEnd(); this.graphicObjects.drawingDocument.OnRecalculatePage(this.startPageIndex, this.graphicObjects.document.Pages[this.startPageIndex]); this.graphicObjects.drawingDocument.OnEndRecalculate(false, false); } this.graphicObjects.arrTrackObjects = []; this.graphicObjects.changeCurrentState(new ChartGroupState(this.graphicObjects, this.group, this.chart)); editor.WordControl.OnUpdateOverlay(); }; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) {}; } function PreMoveChartTitleState(graphicObjects, title, chart, startX, startY, startPageIndex) { this.id = STATES_ID_PRE_MOVE_CHART_TITLE; this.graphicObjects = graphicObjects; this.title = title; this.chart = chart; this.startX = startX; this.startY = startY; this.startPageIndex = startPageIndex; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { if (x === this.startX && y === this.startY && this.startPageIndex === pageIndex) { return; } this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new MoveChartTitleState(this.graphicObjects, this.title, this.chart, this.startX, this.startY, this.startPageIndex)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new ChartState(this.graphicObjects, this.chart)); }; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) { return false; }; } function MoveChartTitleState(graphicObjects, title, chart, startX, startY, startPageIndex) { this.id = STATES_ID_MOVE_CHART_TITLE; this.graphicObjects = graphicObjects; this.title = title; this.chart = chart; this.startX = startX; this.startY = startY; this.startPageIndex = startPageIndex; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var tx, ty; if (pageIndex === this.startPageIndex) { tx = x; ty = y; } else { var tp = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.startPageIndex); tx = tp.X; ty = tp.Y; } var dx = tx - this.startX; var dy = ty - this.startY; this.graphicObjects.arrTrackObjects[0].track(dx, dy, pageIndex); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var doc = editor.WordControl.m_oLogicDocument; if (false === editor.isViewMode && false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.chart.Parent, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); this.graphicObjects.arrTrackObjects[0].trackEnd(); this.graphicObjects.drawingDocument.OnRecalculatePage(this.startPageIndex, this.graphicObjects.document.Pages[this.startPageIndex]); this.graphicObjects.drawingDocument.OnEndRecalculate(false, false); } this.graphicObjects.arrTrackObjects = []; this.graphicObjects.changeCurrentState(new ChartState(this.graphicObjects, this.chart)); editor.WordControl.OnUpdateOverlay(); }; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) { return false; }; } function PreMoveInlineObject(graphicObjects, objectId, ctrlShiftFlag, bSelectedMajorObject) { this.id = STATES_ID_PRE_MOVE_INLINE_OBJECT; this.graphicObjects = graphicObjects; this.ctrlShiftFlag = ctrlShiftFlag; this.bSelectedMajorObjected = bSelectedMajorObject; this.objectId = objectId; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; var _track_objects = this.graphicObjects.arrTrackObjects; var _object_index = 0; var _object_count = _track_objects.length; for (; _object_index < _object_count; ++_object_index) { _track_objects[_object_index].init(); } var object = this.graphicObjects.getObjectById(objectId); object.calculateOffset(); this.graphicObjects.changeCurrentState(new MoveInlineObject(this.graphicObjects, this.objectId)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.arrTrackObjects = []; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); if (this.ctrlShiftFlag === false) { if (e.ClickCount > 1) { var gr_obj = this.graphicObjects.majorGraphicObject; } } if (this.ctrlShiftFlag === true) { if (this.bSelectedMajorObjected === true) { var _selection_array = this.graphicObjects.selectionInfo.selectionArray; for (var _sel_index = 0; _sel_index < _selection_array.length; ++_sel_index) { if (_selection_array[_sel_index] === this.graphicObjects.majorGraphicObject) { _selection_array.splice(_sel_index, 1); this.graphicObjects.sortSelectionArray(); this.graphicObjects.majorGraphicObject.deselect(); } } } } else { if (this.bSelectedMajorObjected === true && this.graphicObjects.majorGraphicObject.isGroup() && e.Button !== 2) { this.graphicObjects.changeCurrentState(new GroupState(graphicObjects, this.graphicObjects.majorGraphicObject)); this.graphicObjects.OnMouseDown(e, x, y, pageIndex); this.graphicObjects.OnMouseUp(e, x, y, pageIndex); } } }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("move"); return true; }; } function MoveInlineObject(graphicObjects, objectId) { this.id = STATES_ID_MOVE_INLINE_OBJECT; this.graphicObjects = graphicObjects; this.objectId = objectId; this.object = this.graphicObjects.getObjectById(objectId); this.InlinePos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, this.graphicObjects.startTrackPos.x, this.graphicObjects.startTrackPos.y); this.InlinePos.Page = this.graphicObjects.startTrackPos.pageIndex; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.InlinePos = this.graphicObjects.document.Get_NearestPos(pageIndex, x, y, false, this.object); this.InlinePos.Page = pageIndex; this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var graphicObject = this.graphicObjects.getObjectById(this.objectId); if (graphicObject !== null) { if (!e.CtrlKey) { graphicObject.OnEnd_MoveInline(this.InlinePos); } else { var doc = this.graphicObjects.document; if (false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.InlinePos.Paragraph, CheckType: changestype_Paragraph_Content }) && false === editor.isViewMode) { History.Create_NewPoint(); var para_drawing = graphicObject.copy(); para_drawing.Add_ToDocument(this.InlinePos, true); } } } this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("default"); return true; }; } function StateAddArrows(graphicObjects, beginArrow, endArrow) { this.graphicObjects = graphicObjects; this.beginArrow = beginArrow; this.endArrow = endArrow; this.currentPreset = graphicObjects.currentPreset; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) {}; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function StartAddNewShape(graphicObjects) { this.id = STATES_ID_START_ADD_NEW_SHAPE; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) { this.graphicObjects.setStartTrackPos(x, y, pageIndex); this.graphicObjects.changeCurrentState(new StartTrackNewShape(this.graphicObjects)); }; this.OnMouseMove = function (e, x, y, pageIndex) {}; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function StartAddNewArrow(graphicObjects, beginArrow, endArrow) { this.id = STATES_ID_START_ADD_NEW_SHAPE; this.graphicObjects = graphicObjects; this.beginArrow = beginArrow; this.endArrow = endArrow; this.OnMouseDown = function (e, x, y, pageIndex) { this.graphicObjects.setStartTrackPos(x, y, pageIndex); this.graphicObjects.changeCurrentState(new StartTrackNewShape(this.graphicObjects, this.beginArrow, this.endArrow)); }; this.OnMouseMove = function (e, x, y, pageIndex) {}; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function StartTrackNewShape(graphicObjects, beginArrow, endArrow) { this.id = STATES_ID_START_TRACK_NEW_SHAPE; this.graphicObjects = graphicObjects; this.beginArrow = beginArrow; this.endArrow = endArrow; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _translated_x; var _translated_y; if (pageIndex !== this.graphicObjects.startTrackPos.pageIndex) { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var pen = new CLn(); pen.Fill = new CUniFill(); pen.Fill.fill = new CSolidFill(); pen.Fill.fill.color.color = new CSchemeColor(); pen.Fill.calculate(this.graphicObjects.document.theme, this.graphicObjects.document.clrSchemeMap, { R: 0, G: 0, B: 0, A: 255 }); if (this.beginArrow) { pen.headEnd = new EndArrow(); pen.headEnd.type = LineEndType.Arrow; pen.headEnd.w = LineEndSize.Mid; pen.headEnd.len = LineEndSize.Mid; } if (this.endArrow) { pen.tailEnd = new EndArrow(); pen.tailEnd.type = LineEndType.Arrow; pen.tailEnd.w = LineEndSize.Mid; pen.tailEnd.len = LineEndSize.Mid; } var brush = new CUniFill(); brush.fill = new CSolidFill(); brush.fill.color.color = new CSchemeColor(); brush.calculate(this.graphicObjects.document.theme, this.graphicObjects.document.clrSchemeMap, { R: 0, G: 0, B: 0, A: 255 }); var _track_new_shape_obj = new CTrackNewObject2(this.graphicObjects.currentPresetGeom, pen, brush, this.graphicObjects.startTrackPos.x, this.graphicObjects.startTrackPos.y, this.graphicObjects.startTrackPos.pageIndex); this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.arrTrackObjects.push(_track_new_shape_obj); _track_new_shape_obj.init(_translated_x, _translated_y); _track_new_shape_obj.modify(_translated_x, _translated_y, e.CtrlKey, e.ShiftKey); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); this.graphicObjects.changeCurrentState(new TrackNewShape(this.graphicObjects, this.beginArrow, this.endArrow)); }; this.OnMouseUp = function (e, x, y, pageIndex) { var _start_track_pos = this.graphicObjects.startTrackPos; var _offset_x = _start_track_pos.x; var _offset_y = _start_track_pos.y; var _ext_x; var _ext_y; if (typeof SHAPE_ASPECTS[this.graphicObjects.currentPresetGeom] === "number") { var _aspect = SHAPE_ASPECTS[this.graphicObjects.currentPresetGeom]; if (_aspect >= 1) { _ext_y = 25.4; _ext_x = _ext_y * _aspect; } else { _ext_x = 25.4; _ext_y = _ext_x / _aspect; } } else { _ext_x = 25.4; _ext_y = 25.4; } var Drawing = new ParaDrawing(_ext_x, _ext_y, null, this.graphicObjects.drawingDocument, this.graphicObjects.document, this.graphicObjects.document); Drawing.Set_DrawingType(drawing_Anchor); var shape = new WordShape(Drawing, this.graphicObjects.document, this.graphicObjects.drawingDocument, null); Drawing.Set_GraphicObject(shape); Drawing.Set_WrappingType(WRAPPING_TYPE_NONE); Drawing.Set_Distance(3.2, 0, 3.2, 0); shape.init(this.graphicObjects.currentPresetGeom, _offset_x, _offset_y, _ext_x, _ext_y, false, false, false, false); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, x, y, true, Drawing); if (near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content }) && false === editor.isViewMode) { History.Create_NewPoint(); var Drawing = new ParaDrawing(_ext_x, _ext_y, null, this.graphicObjects.drawingDocument, this.graphicObjects.document, this.graphicObjects.document); Drawing.Set_DrawingType(drawing_Anchor); var shape = new WordShape(Drawing, this.graphicObjects.document, this.graphicObjects.drawingDocument, null); Drawing.Set_GraphicObject(shape); Drawing.Set_WrappingType(WRAPPING_TYPE_NONE); Drawing.Set_Distance(3.2, 0, 3.2, 0); shape.init(this.graphicObjects.currentPresetGeom, _offset_x, _offset_y, _ext_x, _ext_y, false, false, false, false); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; Drawing.Set_XYForAdd(_offset_x, _offset_y, near_pos, this.graphicObjects.startTrackPos.pageIndex); Drawing.Add_ToDocument(near_pos); this.graphicObjects.resetSelection(); Drawing.select(pageIndex); this.graphicObjects.selectionInfo.selectionArray.push(Drawing); } editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); editor.asc_fireCallback("asc_canGroup", this.graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", this.graphicObjects.canUnGroup()); }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function TrackNewShape(graphicObjects, beginArrow, endArrow) { this.id = STATES_ID_TRACK_NEW_SHAPE; this.graphicObjects = graphicObjects; this.beginArrow = beginArrow; this.endArrow = endArrow; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _translated_x; var _translated_y; if (pageIndex !== this.graphicObjects.startTrackPos.pageIndex) { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } this.graphicObjects.arrTrackObjects[0].modify(_translated_x, _translated_y, e.CtrlKey, e.ShiftKey); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var track_obj = this.graphicObjects.arrTrackObjects[0]; var object_bounds = track_obj.getBounds(); var Drawing = new ParaDrawing(track_obj.extX, track_obj.extY, null, this.graphicObjects.drawingDocument, this.graphicObjects.document, this.graphicObjects.document); Drawing.Set_DrawingType(drawing_Anchor); var shape = new WordShape(Drawing, this.graphicObjects.document, this.graphicObjects.drawingDocument, null); Drawing.Set_GraphicObject(shape); Drawing.Set_WrappingType(WRAPPING_TYPE_NONE); Drawing.Set_Distance(3.2, 0, 3.2, 0); shape.init(track_obj.presetGeom, track_obj.posX, track_obj.posY, track_obj.extX, track_obj.extY, track_obj.flipH, track_obj.flipV, this.beginArrow, this.endArrow); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, object_bounds.l, object_bounds.t, true, Drawing); if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var Drawing = new ParaDrawing(track_obj.extX, track_obj.extY, null, this.graphicObjects.drawingDocument, this.graphicObjects.document, this.graphicObjects.document); Drawing.Set_DrawingType(drawing_Anchor); var shape = new WordShape(Drawing, this.graphicObjects.document, this.graphicObjects.drawingDocument, null); Drawing.Set_GraphicObject(shape); Drawing.Set_WrappingType(WRAPPING_TYPE_NONE); Drawing.Set_Distance(3.2, 0, 3.2, 0); shape.init(track_obj.presetGeom, track_obj.posX, track_obj.posY, track_obj.extX, track_obj.extY, track_obj.flipH, track_obj.flipV, this.beginArrow, this.endArrow); this.graphicObjects.arrTrackObjects[0].endTrack(); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; Drawing.Set_XYForAdd(track_obj.posX, track_obj.posY, near_pos, this.graphicObjects.startTrackPos.pageIndex); Drawing.Add_ToDocument(near_pos); this.graphicObjects.resetSelection(); Drawing.select(this.graphicObjects.startTrackPos.pageIndex); this.graphicObjects.selectionInfo.selectionArray.push(Drawing); } editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); editor.asc_fireCallback("asc_canGroup", this.graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", this.graphicObjects.canUnGroup()); }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function StartAddTextRect(graphicObjects) { this.id = STATES_ID_START_ADD_TEXT_RECT; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) { this.graphicObjects.setStartTrackPos(x, y, pageIndex); this.graphicObjects.changeCurrentState(new StartTrackTextRect(this.graphicObjects)); }; this.OnMouseMove = function (e, x, y, pageIndex) {}; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function StartTrackTextRect(graphicObjects) { this.id = STATES_ID_START_TRACK_TEXT_RECT; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _translated_x; var _translated_y; if (pageIndex !== this.graphicObjects.startTrackPos.pageIndex) { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var pen = new CLn(); pen.w = 6350; pen.Fill = new CUniFill(); pen.Fill.fill = new CSolidFill(); pen.Fill.fill.color.color = new CPrstColor(); pen.Fill.fill.color.color.id = "black"; pen.Fill.calculate(this.graphicObjects.document.theme, this.graphicObjects.document.clrSchemeMap, { R: 0, G: 0, B: 0, A: 255 }); var brush = new CUniFill(); brush.fill = new CSolidFill(); brush.fill.color.color = new CSchemeColor(); brush.fill.color.color.id = 12; brush.calculate(this.graphicObjects.document.theme, this.graphicObjects.document.clrSchemeMap, { R: 0, G: 0, B: 0, A: 255 }); var _track_new_shape_obj = new CTrackNewObject2("rect", pen, brush, this.graphicObjects.startTrackPos.x, this.graphicObjects.startTrackPos.y, this.graphicObjects.startTrackPos.pageIndex); this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.arrTrackObjects.push(_track_new_shape_obj); _track_new_shape_obj.init(_translated_x, _translated_y); _track_new_shape_obj.modify(_translated_x, _translated_y, e.CtrlKey, e.ShiftKey); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); this.graphicObjects.changeCurrentState(new TrackTextRect(this.graphicObjects)); }; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function TrackTextRect(graphicObjects) { this.id = STATES_ID_TRACK_TEXT_RECT; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _translated_x; var _translated_y; if (pageIndex !== this.graphicObjects.startTrackPos.pageIndex) { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } this.graphicObjects.arrTrackObjects[0].modify(_translated_x, _translated_y, e.CtrlKey, e.ShiftKey); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var track_obj = this.graphicObjects.arrTrackObjects[0]; var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, track_obj.posX, track_obj.posY, true, null); if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); this.graphicObjects.arrTrackObjects[0].endTrack(); track_obj = this.graphicObjects.arrTrackObjects[0]; var Drawing = new ParaDrawing(track_obj.extX, track_obj.extY, null, this.graphicObjects.drawingDocument, this.graphicObjects.document, this.graphicObjects.document); Drawing.Set_DrawingType(drawing_Anchor); var shape = new WordShape(Drawing, this.graphicObjects.document, this.graphicObjects.drawingDocument, null); Drawing.Set_GraphicObject(shape); Drawing.Set_WrappingType(WRAPPING_TYPE_NONE); Drawing.Set_Distance(3.2, 0, 3.2, 0); shape.init2(track_obj.presetGeom, track_obj.posX, track_obj.posY, track_obj.extX, track_obj.extY, track_obj.flipH, track_obj.flipV, false, false); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; Drawing.Set_XYForAdd(track_obj.posX, track_obj.posY, near_pos, this.graphicObjects.startTrackPos.pageIndex); Drawing.Add_ToDocument(near_pos); this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.resetSelection(); Drawing.select(this.graphicObjects.startTrackPos.pageIndex); this.graphicObjects.selectionInfo.selectionArray.push(Drawing); editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); Drawing.selectionSetStart(0, 0, e); Drawing.selectionSetEnd(0, 0, e); this.graphicObjects.changeCurrentState(new TextAddState(this.graphicObjects, Drawing)); this.graphicObjects.updateSelectionState(); return; } editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); editor.asc_fireCallback("asc_canGroup", this.graphicObjects.canGroup()); editor.asc_fireCallback("asc_canUnGroup", this.graphicObjects.canUnGroup()); }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function PreChangeAdjState(graphicObjects) { this.id = STATES_ID_PRE_CHANGE_ADJ; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new ChangeAdjState(this.graphicObjects)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function PreMoveState(graphicObjects, ctrlShiftFlag, bSelectedMajorObject) { this.id = STATES_ID_PRE_MOVE; this.graphicObjects = graphicObjects; this.ctrlShiftFlag = ctrlShiftFlag; this.bSelectedMajorObjected = bSelectedMajorObject; var _common_selection_array = this.graphicObjects.selectionInfo.selectionArray; if (_common_selection_array.length === 1) { var pre_track = _common_selection_array[0]; pre_track.calculateOffset(); this.anchorPos = pre_track.Get_AnchorPos(); this.anchorPos.Page = this.graphicObjects.startTrackPos.pageIndex; } this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { if (this.graphicObjects.startTrackPos.x === x && this.graphicObjects.startTrackPos.y === y && this.graphicObjects.startTrackPos.pageIndex === pageIndex) { return; } this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; var _track_objects = this.graphicObjects.arrTrackObjects; var _object_index = 0; var _object_count = _track_objects.length; for (; _object_index < _object_count; ++_object_index) { _track_objects[_object_index].init(); } this.graphicObjects.changeCurrentState(new MoveState(this.graphicObjects)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); if (this.ctrlShiftFlag === false) { if (e.ClickCount > 1) { var gr_obj = this.graphicObjects.majorGraphicObject; } } if (this.ctrlShiftFlag === true) { if (this.bSelectedMajorObjected === true) { var _selection_array = this.graphicObjects.selectionInfo.selectionArray; for (var _sel_index = 0; _sel_index < _selection_array.length; ++_sel_index) { if (_selection_array[_sel_index] === this.graphicObjects.majorGraphicObject) { _selection_array.splice(_sel_index, 1); this.graphicObjects.sortSelectionArray(); this.graphicObjects.majorGraphicObject.deselect(); } } } } else { if (this.bSelectedMajorObjected === true && this.graphicObjects.majorGraphicObject.isGroup() && e.Button !== 2) { this.graphicObjects.changeCurrentState(new GroupState(graphicObjects, this.graphicObjects.majorGraphicObject)); this.graphicObjects.OnMouseDown(e, x, y, pageIndex); this.graphicObjects.OnMouseUp(e, x, y, pageIndex); } } this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("move"); return true; }; } function PreRotateState(graphicObjects) { this.id = STATES_ID_PRE_ROTATE; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; var _track_objects = this.graphicObjects.arrTrackObjects; var _track_object_index; var _track_object_count = _track_objects.length; for (_track_object_index = 0; _track_object_index < _track_object_count; ++_track_object_index) { _track_objects[_track_object_index].init(); } this.graphicObjects.changeCurrentState(new RotateState(this.graphicObjects)); this.graphicObjects.OnMouseMove(e, x, y, pageIndex); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function RotateState(graphicObjects) { this.id = STATES_ID_ROTATE; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _translated_x; var _translated_y; var object_page_index; if (isRealObject(this.graphicObjects.majorGraphicObject) && isRealObject(this.graphicObjects.majorGraphicObject.Parent) && isRealObject(this.graphicObjects.majorGraphicObject.Parent.Parent) && typeof this.graphicObjects.majorGraphicObject.Parent.Parent.Is_HdrFtr === "function" && this.graphicObjects.majorGraphicObject.Parent.Parent.Is_HdrFtr()) { if (isRealObject(this.graphicObjects.majorGraphicObject.GraphicObj) && typeof this.graphicObjects.majorGraphicObject.GraphicObj.selectStartPage === "number" && this.graphicObjects.majorGraphicObject.GraphicObj.selectStartPage !== -1) { object_page_index = this.graphicObjects.majorGraphicObject.GraphicObj.selectStartPage; } else { if (isRealObject(this.graphicObjects.majorGraphicObject)) { object_page_index = this.graphicObjects.majorGraphicObject.pageIndex; } else { object_page_index = pageIndex; } } } else { if (isRealObject(this.graphicObjects.majorGraphicObject)) { object_page_index = this.graphicObjects.majorGraphicObject.pageIndex; } else { object_page_index = pageIndex; } } if (pageIndex !== object_page_index) { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, object_page_index); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var _angle = this.graphicObjects.majorGraphicObject.getAngle(_translated_x, _translated_y); var _track_object_index; var _track_objects = this.graphicObjects.arrTrackObjects; var _track_objects_count = _track_objects.length; for (_track_object_index = 0; _track_object_index < _track_objects_count; ++_track_object_index) { _track_objects[_track_object_index].modify(_angle, e.ShiftKey); } this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var tracks = this.graphicObjects.arrTrackObjects; if (tracks.length > 0) { History.Create_NewPoint(); var doc = this.graphicObjects.document; var para_drawing, bounds; if (tracks[0].originalGraphicObject.Is_Inline()) { if (false === editor.isViewMode && doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: tracks[0].originalGraphicObject.Parent, CheckType: changestype_Paragraph_Content }) === false) { tracks[0].trackEnd(); para_drawing = tracks[0].originalGraphicObject; bounds = para_drawing.getBounds(); para_drawing.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } } else { var b_recalc = false; var n_pos; for (var i = 0; i < tracks.length; ++i) { var cur_track = tracks[i]; para_drawing = cur_track.originalGraphicObject; if (false === editor.isViewMode && doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: para_drawing.Parent, CheckType: changestype_Paragraph_Content }) === false) { cur_track.trackEnd(); bounds = para_drawing.getBounds(); n_pos = para_drawing.Parent.Get_NearestPos(para_drawing.pageIndex, para_drawing.absOffsetX, para_drawing.absOffsetY, true, para_drawing); para_drawing.OnEnd_ChangeFlow(para_drawing.absOffsetX, para_drawing.absOffsetY, para_drawing.pageIndex, bounds.r - bounds.l, bounds.b - bounds.t, n_pos, true, false); b_recalc = true; } } if (b_recalc) { doc.Recalculate(); } } tracks.length = 0; } this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function PreResizeState(graphicObjects, majorHandleNum) { this.id = STATES_ID_PRE_RESIZE; this.graphicObjects = graphicObjects; this.majorHandleNum = majorHandleNum; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; var _track_objects = this.graphicObjects.arrTrackObjects; var _object_index; var _objects_count = _track_objects.length; for (_object_index = 0; _object_index < _objects_count; ++_object_index) { _track_objects[_object_index].init(); } this.graphicObjects.changeCurrentState(new ResizeState(this.graphicObjects, this.majorHandleNum)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function ChangeAdjState(graphicObjects) { this.id = STATES_ID_CHANGE_ADJ; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _transformed_x; var _transformed_y; var object_page_index; if (this.graphicObjects.majorGraphicObject.Parent.Parent.Is_HdrFtr(false)) { object_page_index = this.graphicObjects.majorGraphicObject.GraphicObj.selectStartPage; } else { object_page_index = this.graphicObjects.majorGraphicObject.pageIndex; } if (pageIndex !== object_page_index) { var _transformed_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, object_page_index); _transformed_x = _transformed_point.X; _transformed_y = _transformed_point.Y; } else { _transformed_x = x; _transformed_y = y; } this.graphicObjects.arrTrackObjects[0].track(_transformed_x, _transformed_y); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp2 = function (e, x, y, pageIndex) { var near_pos = null; var bounds33 = this.graphicObjects.arrTrackObjects[0].getBounds(); near_pos = this.graphicObjects.document.Get_NearestPos(pageIndex, bounds33.l, bounds33.t, true, this.graphicObjects.majorGraphicObject); if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); this.graphicObjects.arrTrackObjects[0].trackEnd(); if (this.graphicObjects.arrTrackObjects[0].originalShape.group == null) { var graphic_object = this.graphicObjects.arrTrackObjects[0].originalShape.parent; if (graphic_object.Is_Inline()) { var bounds = graphic_object.getBounds(); graphic_object.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } else { graphic_object.calculateOffset(); var pos_x = graphic_object.absOffsetX - graphic_object.boundsOffsetX; var pos_y = graphic_object.absOffsetY - graphic_object.boundsOffsetY; bounds = graphic_object.getBounds(); var W = bounds.r - bounds.l; var H = bounds.b - bounds.t; var near_pos = this.graphicObjects.document.Get_NearestPos(graphic_object.pageIndex, bounds.l, bounds.t, true, graphic_object); graphic_object.OnEnd_ChangeFlow(pos_x, pos_y, graphic_object.pageIndex, W, H, near_pos, !graphic_object.Is_Inline(), true); } } else { var main_group = this.graphicObjects.arrTrackObjects[0].originalShape.mainGroup; graphic_object = main_group.parent; if (graphic_object.Is_Inline()) { bounds = graphic_object.getBounds(); graphic_object.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } else { graphic_object.calculateOffset(); pos_x = graphic_object.absOffsetX - graphic_object.boundsOffsetX; pos_y = graphic_object.absOffsetY - graphic_object.boundsOffsetY; bounds = graphic_object.getBounds(); W = bounds.r - bounds.l; H = bounds.b - bounds.t; near_pos = this.graphicObjects.document.Get_NearestPos(graphic_object.pageIndex, bounds.l, bounds.t, true, graphic_object); graphic_object.OnEnd_ChangeFlow(pos_x, pos_y, graphic_object.pageIndex, W, H, near_pos, !graphic_object.Is_Inline(), true); } } } this.graphicObjects.arrTrackObjects = []; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var doc = this.graphicObjects.document; var track = this.graphicObjects.arrTrackObjects[0]; if (isRealObject(track)) { var shape = track.originalShape; var para_drawing = track.originalShape.parent; if (false === editor.isViewMode && false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: para_drawing.Parent, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); track.trackEnd(); var bounds = para_drawing.getBounds(); if (para_drawing.Is_Inline()) { para_drawing.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } else { var bounds_rect = para_drawing.getBoundsRect(); var nearest_pos = para_drawing.Parent.Get_NearestPos(para_drawing.pageIndex, bounds_rect.l, bounds_rect.t, true, para_drawing); para_drawing.OnEnd_ChangeFlow(para_drawing.absOffsetX, para_drawing.absOffsetY, para_drawing.pageIndex, bounds.r - bounds.l, bounds.t - bounds.b, nearest_pos, true, true); } } } this.graphicObjects.arrTrackObjects = []; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function MoveState(graphicObjects) { this.id = STATES_ID_MOVE; this.graphicObjects = graphicObjects; var major_object = this.graphicObjects.majorGraphicObject; major_object.calculateOffset(); this.boundsOffX = major_object.absOffsetX - major_object.boundsOffsetX - this.graphicObjects.startTrackPos.x; this.boundsOffY = major_object.absOffsetY - major_object.boundsOffsetY - this.graphicObjects.startTrackPos.y; this.anchorPos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, this.boundsOffX + this.graphicObjects.startTrackPos.x, this.boundsOffY + this.graphicObjects.startTrackPos.y); this.anchorPos.Page = this.graphicObjects.startTrackPos.pageIndex; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _arr_track_objects = this.graphicObjects.arrTrackObjects; var _objects_count = _arr_track_objects.length; var _object_index; var result_x, result_y; if (!e.ShiftKey) { result_x = x; result_y = y; } else { var abs_dist_x = Math.abs(this.graphicObjects.startTrackPos.x - x); var abs_dist_y = Math.abs(this.graphicObjects.startTrackPos.y - y); if (abs_dist_x > abs_dist_y) { result_x = x; result_y = this.graphicObjects.startTrackPos.y; } else { result_x = this.graphicObjects.startTrackPos.x; result_y = y; } } var tr_to_start_page_x; var tr_to_start_page_y; if (pageIndex === this.graphicObjects.startTrackPos.pageIndex) { tr_to_start_page_x = x; tr_to_start_page_y = y; } else { var tr_to_start_page = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); tr_to_start_page_x = tr_to_start_page.X; tr_to_start_page_y = tr_to_start_page.Y; } var startPage = this.graphicObjects.graphicPages[this.graphicObjects.startTrackPos.pageIndex]; var startPos = this.graphicObjects.startTrackPos; var startBeforeArr = startPage.beforeTextObjects; var startWrapArr = startPage.wrappingObjects; var startInlineArr = startPage.inlineObjects; var startBehindArr = startPage.behindDocObjects; var min_dx = null, min_dy = null; var dx, dy; var snap_x = null, snap_y = null; var snapHorArray = [], snapVerArray = []; snapHorArray.push(X_Left_Field); snapHorArray.push(X_Right_Field); snapHorArray.push(Page_Width / 2); snapVerArray.push(Y_Top_Field); snapVerArray.push(Y_Bottom_Field); snapVerArray.push(Page_Height / 2); if (result_x === this.graphicObjects.startTrackPos.x) { min_dx = 0; } else { for (var track_index = 0; track_index < _arr_track_objects.length; ++track_index) { var cur_track_original_shape = _arr_track_objects[track_index].originalGraphicObject; var trackSnapArrayX = cur_track_original_shape.snapArrayX; var curDX = result_x - startPos.x; for (snap_index = 0; snap_index < trackSnapArrayX.length; ++snap_index) { var snap_obj = GetMinSnapDistanceXObjectByArrays(trackSnapArrayX[snap_index] + curDX, snapHorArray); if (isRealObject(snap_obj)) { dx = snap_obj.dist; if (dx !== null) { if (min_dx === null) { min_dx = dx; snap_x = snap_obj.pos; } else { if (Math.abs(min_dx) > Math.abs(dx)) { min_dx = dx; snap_x = snap_obj.pos; } } } } } if (startBeforeArr.length > 0) { for (var snap_index = 0; snap_index < trackSnapArrayX.length; ++snap_index) { var snap_obj = GetMinSnapDistanceXObject(trackSnapArrayX[snap_index] + curDX, startBeforeArr); if (isRealObject(snap_obj)) { dx = snap_obj.dist; if (dx !== null) { if (min_dx === null) { snap_x = snap_obj.pos; min_dx = dx; } else { if (Math.abs(min_dx) > Math.abs(dx)) { min_dx = dx; snap_x = snap_obj.pos; } } } } } } if (startWrapArr.length > 0) { for (snap_index = 0; snap_index < trackSnapArrayX.length; ++snap_index) { var snap_obj = GetMinSnapDistanceXObject(trackSnapArrayX[snap_index] + curDX, startWrapArr); if (isRealObject(snap_obj)) { dx = snap_obj.dist; if (dx !== null) { if (min_dx === null) { min_dx = dx; snap_x = snap_obj.pos; } else { if (Math.abs(min_dx) > Math.abs(dx)) { min_dx = dx; snap_x = snap_obj.pos; } } } } } } if (startInlineArr.length > 0) { for (snap_index = 0; snap_index < trackSnapArrayX.length; ++snap_index) { var snap_obj = GetMinSnapDistanceXObject(trackSnapArrayX[snap_index] + curDX, startInlineArr); if (isRealObject(snap_obj)) { dx = snap_obj.dist; if (dx !== null) { if (min_dx === null) { min_dx = dx; snap_x = snap_obj.pos; } else { if (Math.abs(min_dx) > Math.abs(dx)) { min_dx = dx; snap_x = snap_obj.pos; } } } } } } if (startBehindArr.length > 0) { for (snap_index = 0; snap_index < trackSnapArrayX.length; ++snap_index) { var snap_obj = GetMinSnapDistanceXObject(trackSnapArrayX[snap_index] + curDX, startBehindArr); if (isRealObject(snap_obj)) { dx = snap_obj.dist; if (dx !== null) { if (min_dx === null) { min_dx = dx; snap_x = snap_obj.pos; } else { if (Math.abs(min_dx) > Math.abs(dx)) { min_dx = dx; snap_x = snap_obj.pos; } } } } } } } } if (result_y === this.graphicObjects.startTrackPos.y) { min_dy = 0; } else { for (track_index = 0; track_index < _arr_track_objects.length; ++track_index) { cur_track_original_shape = _arr_track_objects[track_index].originalGraphicObject; var trackSnapArrayY = cur_track_original_shape.snapArrayY; var curDY = result_y - startPos.y; for (snap_index = 0; snap_index < trackSnapArrayY.length; ++snap_index) { var snap_obj = GetMinSnapDistanceYObjectByArrays(trackSnapArrayY[snap_index] + curDY, snapVerArray); if (isRealObject(snap_obj)) { dy = snap_obj.dist; if (dy !== null) { if (min_dy === null) { min_dy = dy; snap_y = snap_obj.pos; } else { if (Math.abs(min_dy) > Math.abs(dy)) { min_dy = dy; snap_y = snap_obj.pos; } } } } } if (startBeforeArr.length > 0) { for (snap_index = 0; snap_index < trackSnapArrayY.length; ++snap_index) { var snap_obj = GetMinSnapDistanceYObject(trackSnapArrayY[snap_index] + curDY, startBeforeArr); if (isRealObject(snap_obj)) { dy = snap_obj.dist; if (dy !== null) { if (min_dy === null) { min_dy = dy; snap_y = snap_obj.pos; } else { if (Math.abs(min_dy) > Math.abs(dy)) { min_dy = dy; snap_y = snap_obj.pos; } } } } } } if (startWrapArr.length) { for (snap_index = 0; snap_index < trackSnapArrayY.length; ++snap_index) { var snap_obj = GetMinSnapDistanceYObject(trackSnapArrayY[snap_index] + curDY, startWrapArr); if (isRealObject(snap_obj)) { dy = snap_obj.dist; if (dy !== null) { if (min_dy === null) { min_dy = dy; snap_y = snap_obj.pos; } else { if (Math.abs(min_dy) > Math.abs(dy)) { min_dy = dy; snap_y = snap_obj.pos; } } } } } } if (startInlineArr.length > 0) { for (snap_index = 0; snap_index < trackSnapArrayY.length; ++snap_index) { var snap_obj = GetMinSnapDistanceYObject(trackSnapArrayY[snap_index] + curDY, startInlineArr); if (isRealObject(snap_obj)) { dy = snap_obj.dist; if (dy !== null) { if (min_dy === null) { min_dy = dy; snap_y = snap_obj.pos; } else { if (Math.abs(min_dy) > Math.abs(dy)) { min_dy = dy; snap_y = snap_obj.pos; } } } } } } if (startBehindArr.length > 0) { for (snap_index = 0; snap_index < trackSnapArrayY.length; ++snap_index) { var snap_obj = GetMinSnapDistanceYObject(trackSnapArrayY[snap_index] + curDY, startBehindArr); if (isRealObject(snap_obj)) { dy = snap_obj.dist; if (dy !== null) { if (min_dy === null) { min_dy = dy; snap_y = snap_obj.pos; } else { if (Math.abs(min_dy) > Math.abs(dy)) { min_dy = dy; snap_y = snap_obj.pos; } } } } } } } } if (min_dx === null || Math.abs(min_dx) > SNAP_DISTANCE) { min_dx = 0; } else { if (isRealNumber(snap_x)) { editor.WordControl.m_oDrawingDocument.DrawVerAnchor(pageIndex, snap_x); } } if (min_dy === null || Math.abs(min_dy) > SNAP_DISTANCE) { min_dy = 0; } else { if (isRealNumber(snap_y)) { editor.WordControl.m_oDrawingDocument.DrawHorAnchor(pageIndex, snap_y); } } for (_object_index = 0; _object_index < _objects_count; ++_object_index) { _arr_track_objects[_object_index].track(result_x + min_dx, result_y + min_dy, pageIndex); } this.anchorPos = this.graphicObjects.document.Get_NearestPos(pageIndex, this.boundsOffX + x, this.boundsOffY + y, true, this.graphicObjects.majorGraphicObject); this.anchorPos.Page = pageIndex; this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var tracks = this.graphicObjects.arrTrackObjects; if (tracks.length > 0) { History.Create_NewPoint(); var doc = this.graphicObjects.document; var b_recalculate = false; var gr_obj; for (var i = 0; i < tracks.length; ++i) { var cur_track = tracks[i]; var bounds = cur_track.getBoundsRect(); var near_pos = doc.Get_NearestPos(cur_track.trackGraphicObject.pageIndex, bounds.l, bounds.t, true, cur_track.originalGraphicObject); near_pos.Page = cur_track.trackGraphicObject.pageIndex; if (false === editor.isViewMode && false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { b_recalculate = true; cur_track.trackEnd(e, pageIndex); gr_obj = cur_track.originalGraphicObject; bounds = gr_obj.getBounds(); cur_track.originalGraphicObject.OnEnd_ChangeFlow(gr_obj.absOffsetX, gr_obj.absOffsetY, cur_track.trackGraphicObject.pageIndex, bounds.r - bounds.l, bounds.b - bounds.t, near_pos, true, false); } } if (b_recalculate) { doc.Recalculate(); } } tracks.length = 0; this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("move"); return true; }; } function ResizeState(graphicObjects, majorHandleNum) { this.id = STATES_ID_RESIZE; this.majorHandleNum = majorHandleNum; this.graphicObjects = graphicObjects; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _translated_x; var _translated_y; var object_page_index; var major_object = this.graphicObjects.majorGraphicObject; if (major_object.Parent.Parent.Is_HdrFtr(false)) { object_page_index = major_object.GraphicObj.selectStartPage; } else { object_page_index = this.graphicObjects.majorGraphicObject.pageIndex; } if (pageIndex !== object_page_index) { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, object_page_index); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var graphic_page = this.graphicObjects.graphicPages[object_page_index]; var min_dx = null, min_dy = null; var dx, dy; var gr_arr = graphic_page.beforeTextObjects; for (var i = 0; i < gr_arr.length; ++i) { var snap_arr_x = gr_arr[i].snapArrayX; var snap_arr_y = gr_arr[i].snapArrayY; for (var j = 0, count = snap_arr_x.length; j < count; ++j) { dx = snap_arr_x[j] - _translated_x; if (min_dx === null) { min_dx = dx; } else { if (Math.abs(dx) < Math.abs(min_dx)) { min_dx = dx; } } } count = snap_arr_y.length; for (j = 0; j < count; ++j) { dy = snap_arr_y[j] - _translated_y; if (min_dy === null) { min_dy = dy; } else { if (Math.abs(min_dy) > Math.abs(dy)) { min_dy = dy; } } } } gr_arr = graphic_page.wrappingObjects; for (i = 0; i < gr_arr.length; ++i) { snap_arr_x = gr_arr[i].snapArrayX; snap_arr_y = gr_arr[i].snapArrayY; for (j = 0, count = snap_arr_x.length; j < count; ++j) { dx = snap_arr_x[j] - _translated_x; if (min_dx === null) { min_dx = dx; } else { if (Math.abs(dx) < Math.abs(min_dx)) { min_dx = dx; } } } count = snap_arr_y.length; for (j = 0; j < count; ++j) { dy = snap_arr_y[j] - _translated_y; if (min_dy === null) { min_dy = dy; } else { if (Math.abs(min_dy) > Math.abs(dy)) { min_dy = dy; } } } } gr_arr = graphic_page.inlineObjects; for (i = 0; i < gr_arr.length; ++i) { snap_arr_x = gr_arr[i].snapArrayX; snap_arr_y = gr_arr[i].snapArrayY; for (j = 0, count = snap_arr_x.length; j < count; ++j) { dx = snap_arr_x[j] - _translated_x; if (min_dx === null) { min_dx = dx; } else { if (Math.abs(dx) < Math.abs(min_dx)) { min_dx = dx; } } } count = snap_arr_y.length; for (j = 0; j < count; ++j) { dy = snap_arr_y[j] - _translated_y; if (min_dy === null) { min_dy = dy; } else { if (Math.abs(min_dy) > Math.abs(dy)) { min_dy = dy; } } } } gr_arr = graphic_page.behindDocObjects; for (i = 0; i < gr_arr.length; ++i) { snap_arr_x = gr_arr[i].snapArrayX; snap_arr_y = gr_arr[i].snapArrayY; for (j = 0, count = snap_arr_x.length; j < count; ++j) { dx = snap_arr_x[j] - _translated_x; if (min_dx === null) { min_dx = dx; } else { if (dx < min_dx) { min_dx = dx; } } } count = snap_arr_y.length; for (j = 0; j < count; ++j) { dy = snap_arr_y[j] - _translated_y; if (min_dy === null) { min_dy = dy; } else { if (Math.abs(min_dy) > Math.abs(dy)) { min_dy = dy; } } } } if (min_dx === null) { min_dx = 0; } else { if (Math.abs(min_dx) > SNAP_DISTANCE) { min_dx = 0; } } if (min_dy === null) { min_dy = 0; } else { if (Math.abs(min_dy) > SNAP_DISTANCE) { min_dy = 0; } } var _resize_coefficients = this.graphicObjects.majorGraphicObject.getResizeCoefficients(this.majorHandleNum, _translated_x + min_dx, _translated_y + min_dy); var _arr_track_objects = this.graphicObjects.arrTrackObjects; var _objects_count = _arr_track_objects.length; var _object_index; for (_object_index = 0; _object_index < _objects_count; ++_object_index) { _arr_track_objects[_object_index].track(_resize_coefficients.kd1, _resize_coefficients.kd2, e); } this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp2 = function (e, x, y, pageIndex) { History.Create_NewPoint(); var _translated_x; var _translated_y; if (pageIndex !== this.graphicObjects.majorGraphicObject.pageIndex) { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.majorGraphicObject.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var _resize_coefficients = this.graphicObjects.majorGraphicObject.getResizeCoefficients(this.majorHandleNum, _translated_x, _translated_y); var _arr_track_objects = this.graphicObjects.arrTrackObjects; var _objects_count = _arr_track_objects.length; var _object_index; for (var i = 0; i < _objects_count; ++i) { if (_arr_track_objects[i].originalGraphicObject === this.graphicObjects.majorGraphicObject) { var bounds33 = _arr_track_objects[i].getBounds(); near_pos = this.graphicObjects.document.Get_NearestPos(pageIndex, bounds33.l, bounds33.t, true, this.graphicObjects.majorGraphicObject); } } if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { for (_object_index = 0; _object_index < _objects_count; ++_object_index) { _arr_track_objects[_object_index].trackEnd(); } if (_arr_track_objects[0].originalGraphicObject.Is_Inline()) { var bounds = _arr_track_objects[0].originalGraphicObject.getBounds(); _arr_track_objects[0].originalGraphicObject.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); this.graphicObjects.arrTrackObjects = []; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); return; } else { var bounds_2 = this.graphicObjects.majorGraphicObject.getBounds(); var near_pos = this.graphicObjects.document.Get_NearestPos(pageIndex, bounds_2.l, bounds_2.t, true, this.graphicObjects.majorGraphicObject); for (var i = 0; i < _arr_track_objects.length; ++i) { var or_gr_obj = _arr_track_objects[i].originalGraphicObject; or_gr_obj.calculateOffset(); var pos_x = or_gr_obj.absOffsetX - or_gr_obj.boundsOffsetX; var pos_y = or_gr_obj.absOffsetY - or_gr_obj.boundsOffsetY; bounds_2 = or_gr_obj.getBounds(); var W = bounds_2.r - bounds_2.l; var H = bounds_2.b - bounds_2.t; or_gr_obj.OnEnd_ChangeFlow(pos_x, pos_y, or_gr_obj.pageIndex, W, H, near_pos, _arr_track_objects[i].trackGraphicObject.boolChangePos, i == _arr_track_objects.length - 1); } } } this.graphicObjects.arrTrackObjects = []; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var tracks = this.graphicObjects.arrTrackObjects; if (tracks.length > 0) { History.Create_NewPoint(); var para_drawing; var doc = this.graphicObjects.document; var bounds; if (tracks[0].originalGraphicObject.Is_Inline()) { para_drawing = tracks[0].originalGraphicObject; var paragraph = null; if (!para_drawing.isShapeChild()) { paragraph = para_drawing.Parent; } else { var parent_shape = para_drawing.getParentShape(); if (!parent_shape.group) { paragraph = parent_shape.parent.Parent; } else { main_group = parent_shape.getMainGroup(); if (isRealObject(main_group)) { paragraph = main_group.parent.Parent; } else { paragraph = para_drawing.Parent; } } } if (false === editor.isViewMode && false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: paragraph, CheckType: changestype_Paragraph_Content })) { tracks[0].trackEnd(); bounds = para_drawing.getBounds(); para_drawing.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } } else { var b_recalculate = false; for (var i = 0; i < tracks.length; ++i) { var track = tracks[i]; para_drawing = track.originalGraphicObject; var bounds_rect = track.getBoundsRect(); var nearest_pos = doc.Get_NearestPos(para_drawing.pageIndex, bounds_rect.l, bounds_rect.t, true, para_drawing); if (false === editor.isViewMode && false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_Drawing_Props, Element: nearest_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { b_recalculate = true; track.trackEnd(); bounds = para_drawing.getBounds(); para_drawing.OnEnd_ChangeFlow(para_drawing.absOffsetX, para_drawing.absOffsetY, para_drawing.pageIndex, bounds.r - bounds.l, bounds.b - bounds.t, nearest_pos, true, false); } } if (b_recalculate) { doc.Recalculate(); } } } this.graphicObjects.arrTrackObjects = []; this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.updateCursorType = function (pageIndex, x, y) { this.graphicObjects.drawingDocument.SetCursorType("crosshair"); return true; }; } function TextAddState(graphicObjects, textObject) { this.id = STATES_ID_TEXT_ADD; this.graphicObjects = graphicObjects; this.textObject = textObject; this.nullState = new NullState(graphicObjects); this.OnMouseDown = function (e, x, y, pageIndex) { this.textObject.selectionRemove(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.OnMouseDown(e, x, y, pageIndex); if (this.graphicObjects.curState.id !== STATES_ID_TEXT_ADD || this.graphicObjects.curState.id !== STATES_ID_TEXT_ADD_IN_GROUP) { this.graphicObjects.drawingDocument.UpdateTargetTransform(new CMatrix()); } }; this.OnMouseMove = function (e, x, y, pageIndex) { if (e.IsLocked) { var page_index; if (isRealObject(this.textObject.Parent) && isRealObject(this.textObject.Parent.Parent) && this.textObject.Parent.Parent.Is_HdrFtr()) { page_index = this.textObject.GraphicObj.selectStartPage; } else { page_index = this.textObject.pageIndex; } var tx, ty; if (pageIndex === page_index) { tx = x; ty = y; } else { var tp = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, page_index); tx = tp.X; ty = tp.Y; } this.textObject.selectionSetEnd(tx, ty, e, page_index); this.graphicObjects.updateSelectionState(); } }; this.OnMouseUp = function (e, x, y, pageIndex) { var page_index; if (isRealObject(this.textObject.Parent) && isRealObject(this.textObject.Parent.Parent) && this.textObject.Parent.Parent.Is_HdrFtr()) { page_index = this.textObject.GraphicObj.selectStartPage; } else { page_index = this.textObject.pageIndex; } var tx, ty; if (pageIndex === page_index) { tx = x; ty = y; } else { var tp = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, page_index); tx = tp.X; ty = tp.Y; } this.textObject.selectionSetEnd(tx, ty, e, page_index); this.graphicObjects.updateSelectionState(); }; this.updateCursorType = function (pageIndex, x, y, e, textFlag) { return this.nullState.updateCursorType(pageIndex, x, y, e, textFlag); }; } function TextAddInGroup(graphicObjects, textObject, group) { this.id = STATES_ID_TEXT_ADD_IN_GROUP; this.graphicObjects = graphicObjects; this.textObject = textObject; this.group = group; this.groupState = new GroupState(this.graphicObjects, group.parent); this.OnMouseDown = function (e, x, y, pageIndex) { this.textObject.selectionRemove(); this.graphicObjects.changeCurrentState(new GroupState(graphicObjects, this.group.parent)); this.graphicObjects.OnMouseDown(e, x, y, pageIndex); }; this.OnMouseMove = function (e, x, y, pageIndex) { if (e.IsLocked) { var page_index; if (isRealObject(this.group.parent.Parent) && isRealObject(this.group.parent.Parent.Parent) && this.group.parent.Parent.Parent.Is_HdrFtr()) { page_index = this.group.selectStartPage; } else { page_index = this.group.parent.pageIndex; } var tx, ty; if (pageIndex === page_index) { tx = x; ty = y; } else { var tp = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, page_index); tx = tp.X; ty = tp.Y; } this.textObject.selectionSetEnd(tx, ty, e, page_index); this.graphicObjects.updateSelectionState(); } }; this.OnMouseUp = function (e, x, y, pageIndex) { this.textObject.selectionSetEnd(x, y, e, pageIndex); this.graphicObjects.updateSelectionState(); }; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) { return this.groupState.updateCursorType(pageIndex, x, y, e, bTextFlag); }; } function GroupState(graphicObjects, group) { this.id = STATES_ID_GROUP; this.graphicObjects = graphicObjects; this.groupWordGO = group; this.group = group.GraphicObj; this.groupInvertMatrix = global_MatrixTransformer.Invert(this.group.transform); this.OnMouseDown = function (e, x, y, pageIndex) { handleGroupState(this.graphicObjects, this.group, e, x, y, pageIndex, this); }; this.OnMouseMove = function (e, x, y, pageIndex) {}; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y, e, bTextFlag) { return handleGroupStateCursorType(this.graphicObjects, this.group, e, x, y, pageIndex, this, bTextFlag); }; } function PreChangeAdjInGroup(graphicObjects, group) { this.id = STATES_ID_PRE_CH_ADJ_IN_GROUP; this.graphicObjects = graphicObjects; this.group = group; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new ChangeAdjInGroup(this.graphicObjects, this.group)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); }; this.updateCursorType = function () {}; } function ChangeAdjInGroup(graphicObjects, group) { this.id = STATES_ID_CH_ADJ_IN_GROUP; this.graphicObjects = graphicObjects; this.group = group; this.track = this.graphicObjects.arrTrackObjects[0]; this.invertMatrix = global_MatrixTransformer.Invert(this.track.originalShape.group.transform); this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var t_x, t_y; if (pageIndex === this.group.pageIndex) { t_x = this.invertMatrix.TransformPointX(x, y); t_y = this.invertMatrix.TransformPointY(x, y); } else { var t_p = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.group.pageIndex); t_x = this.invertMatrix.TransformPointX(t_p.X, t_p.Y); t_y = this.invertMatrix.TransformPointY(t_p.X, t_p.Y); } this.track.track(t_x, t_y); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var doc = this.graphicObjects.document; if (false === editor.isViewMode && false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.group.parent.Parent, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); this.track.trackEnd(); var bounds = this.group.parent.getBounds(); if (this.group.parent.Is_Inline()) { this.group.parent.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } else { var near_pos = this.group.parent.Parent.Get_NearestPos(this.group.pageIndex, this.group.absOffsetX, this.group.absOffsetY, true, this.group.parent); this.group.parent.OnEnd_ChangeFlow(this.group.absOffsetX, this.group.absOffsetY, this.group.pageIndex, bounds.r - bounds.l, bounds.b - bounds.t, null, true, true); } } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.updateCursorType = function () {}; } function PreResizeInGroup(graphicObjects, group, majorObject, majorHandleNum) { this.id = STATES_ID_PRE_RESIZE_IN_GROUP; this.graphicObjects = graphicObjects; this.group = group; this.majorObject = majorObject; this.majorHandleNum = majorHandleNum; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new ResizeInGroup(this.graphicObjects, this.group, this.majorObject, this.majorHandleNum)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); }; this.updateCursorType = function () { return false; }; } function ResizeInGroup(graphicObjects, group, majorObject, majorHandleNum) { this.id = STATES_ID_RESIZE_IN_GROUP; this.graphicObjects = graphicObjects; this.group = group; this.majorObject = majorObject; this.majorHandleNum = majorHandleNum; this.inv = global_MatrixTransformer.Invert(this.majorObject.group.transform); this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var t_x, t_y; if (pageIndex === this.group.pageIndex) { t_x = this.inv.TransformPointX(x, y); t_y = this.inv.TransformPointY(x, y); } else { var t_p = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.group.pageIndex); t_x = this.inv.TransformPointX(t_p.X, t_p.Y); t_y = this.inv.TransformPointY(t_p.X, t_p.Y); } var _resize_coefficients = this.majorObject.getResizeCoefficients(this.majorHandleNum, t_x, t_y); var _arr_track_objects = this.graphicObjects.arrTrackObjects; var _objects_count = _arr_track_objects.length; var _object_index; if (!e.CtrlKey) { for (_object_index = 0; _object_index < _objects_count; ++_object_index) { _arr_track_objects[_object_index].resize(_resize_coefficients.kd1, _resize_coefficients.kd2, e.ShiftKey); } } else { for (_object_index = 0; _object_index < _objects_count; ++_object_index) { _arr_track_objects[_object_index].resizeRelativeCenter(_resize_coefficients.kd1, _resize_coefficients.kd2, e.ShiftKey); } } this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var doc = this.graphicObjects.document; if (false === editor.isViewMode && false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.group.parent.Parent, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var tracks = this.graphicObjects.arrTrackObjects; for (var i = 0; i < tracks.length; ++i) { tracks[i].endTrack(); } this.group.updateSizes(); this.group.recalculate(); var bounds = this.group.parent.getBounds(); if (this.group.parent.Is_Inline()) { this.group.parent.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } else { var near_pos = this.group.parent.Parent.Get_NearestPos(this.group.pageIndex, this.group.absOffsetX, this.group.absOffsetY, true, this.group.parent); this.group.parent.OnEnd_ChangeFlow(this.group.absOffsetX, this.group.absOffsetY, this.group.pageIndex, bounds.r - bounds.l, bounds.b - bounds.t, null, true, true); } } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); }; this.updateCursorType = function () { return false; }; } function PreRotateInGroup(graphicObjects, group, majorObject) { this.id = STATES_ID_PRE_ROTATE_IN_GROUP2; this.graphicObjects = graphicObjects; this.group = group; this.majorObject = majorObject; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new RotateInGroup(this.graphicObjects, this.group, this.majorObject)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); }; this.updateCursorType = function () { return false; }; } function RotateInGroup(graphicObjects, group, majorObject) { this.id = STATES_ID_ROTATE_IN_GROUP2; this.graphicObjects = graphicObjects; this.group = group; this.majorObject = majorObject; this.inv = global_MatrixTransformer.Invert(majorObject.group.transform); this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var t_x, t_y; if (pageIndex === this.group.pageIndex) { t_x = this.inv.TransformPointX(x, y); t_y = this.inv.TransformPointY(x, y); } else { var t_p = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.group.pageIndex); t_x = this.inv.TransformPointX(t_p.X, t_p.Y); t_y = this.inv.TransformPointY(t_p.X, t_p.Y); } var angle = this.majorObject.getAngle(t_x, t_y); var tracks = this.graphicObjects.arrTrackObjects; for (var i = 0; i < tracks.length; ++i) { tracks[i].track(angle, e.ShiftKey); } this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var doc = this.graphicObjects.document; if (false === editor.isViewMode && false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.group.parent.Parent, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var tracks = this.graphicObjects.arrTrackObjects; for (var i = 0; i < tracks.length; ++i) { tracks[i].trackEnd(); } this.group.updateSizes(); this.group.recalculate(); var bounds = this.group.parent.getBounds(); if (this.group.parent.Is_Inline()) { this.group.parent.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } else { var near_pos = this.group.parent.Parent.Get_NearestPos(this.group.pageIndex, this.group.absOffsetX, this.group.absOffsetY, true, this.group.parent); this.group.parent.OnEnd_ChangeFlow(this.group.absOffsetX, this.group.absOffsetY, this.group.pageIndex, bounds.r - bounds.l, bounds.b - bounds.t, null, true, true); } } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.updateCursorType = function () { return false; }; } function PreResizeGroupedShapes(graphicObjects, group, majorObject, majorObjectHandleNum) { this.id = STATES_ID_PRE_RESIZE_GROUPED; this.graphicObjects = graphicObjects; this.group = group; this.majorObject = majorObject; this.majorHandleNum = majorObjectHandleNum; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; var _track_objects = this.graphicObjects.arrTrackObjects; var _object_index; var _objects_count = _track_objects.length; for (_object_index = 0; _object_index < _objects_count; ++_object_index) { _track_objects[_object_index].init(); } this.graphicObjects.changeCurrentState(new ResizeGroupedShapes(this.graphicObjects, this.group, this.majorObject, majorObjectHandleNum)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function ResizeGroupedShapes(graphicObjects, group, majorObject, majorObjectHandleNum) { this.id = STATES_ID_RESIZE_GROUPED; this.graphicObjects = graphicObjects; this.group = group; this.majorObject = majorObject; this.majorHandleNum = majorObjectHandleNum; this.invertGroupMatrix = global_MatrixTransformer.Invert(this.group.transform); this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _translated_x; var _translated_y; if (pageIndex !== this.group.pageIndex) { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.group.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var _translated_to_group_x = this.invertGroupMatrix.TransformPointX(_translated_x, _translated_y); var _translated_to_group_y = this.invertGroupMatrix.TransformPointY(_translated_x, _translated_y); var _resize_coefficients = this.majorObject.getResizeCoefficients(this.majorHandleNum, _translated_to_group_x, _translated_to_group_y); var _arr_track_objects = this.graphicObjects.arrTrackObjects; var _objects_count = _arr_track_objects.length; var _object_index; for (_object_index = 0; _object_index < _objects_count; ++_object_index) { _arr_track_objects[_object_index].track(_resize_coefficients.kd1, _resize_coefficients.kd2, e); } this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { if (false === editor.isViewMode && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.group.parent.Parent, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var _arr_track_objects = this.graphicObjects.arrTrackObjects; var _objects_count = _arr_track_objects.length; var _object_index; for (_object_index = 0; _object_index < _objects_count; ++_object_index) { _arr_track_objects[_object_index].trackEnd(); } this.group.recalculateAfterInternalResize(); History.Add(this.group, { Type: historyitem_InternalChanges }); var bounds = this.group.parent.getBounds(); if (this.group.parent.Is_Inline()) { this.group.parent.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } else { var bounds = this.group.parent.getBounds(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.group.parent.getPageIndex(), bounds.l, bounds.t, true, this.group.parent); this.group.parent.OnEnd_ChangeFlow(this.group.absOffsetX, this.group.absOffsetY, this.group.parent.getPageIndex(), bounds.r - bounds.l, bounds.b - bounds.t, near_pos, true, true); } this.graphicObjects.arrTrackObjects = []; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); } }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function PreMoveInGroup(graphicObjects, group, ctrlShift, bSelectedMajorObject, startX, startY) { this.id = STATES_ID_PRE_MOVE_IN_GROUP; this.graphicObjects = graphicObjects; this.group = group; this.ctrlShiftFlag = ctrlShift; this.bSelectedMajorObjected = bSelectedMajorObject; this.startX = startX; this.startY = startY; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new MoveInGroup(this.graphicObjects, this.group, this.startX, this.startY)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects.length = 0; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function MoveInGroup(graphicObjects, group, startX, startY) { this.id = STATES_ID_MOVE_IN_GROUP; this.graphicObjects = graphicObjects; this.group = group; this.invertGroupMatrix = global_MatrixTransformer.Invert(this.group.getTransformMatrix()); this.startX = startX; this.startY = startY; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var t_x, t_y; if (pageIndex === this.group.pageIndex) { t_x = x; t_y = y; } else { var t_p = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.group.pageIndex); t_x = t_p.X; t_y = t_p.Y; } var _track_objects = this.graphicObjects.arrTrackObjects; for (var _index = 0; _index < _track_objects.length; ++_index) { _track_objects[_index].track(this.startX, this.startY, t_x, t_y); } this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var doc = this.graphicObjects.document; var _track_objects = this.graphicObjects.arrTrackObjects; for (var _index = 0; _index < _track_objects.length; ++_index) { _track_objects[_index].track(this.startX, this.startY, x, y); } if (false === editor.isViewMode && false === doc.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.group.parent.Parent, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var tracks = this.graphicObjects.arrTrackObjects; for (var i = 0; i < tracks.length; ++i) { tracks[i].trackEnd(e); } this.group.updateSizes(); this.group.recalculate(); var bounds = this.group.parent.getBounds(); if (this.group.parent.Is_Inline()) { this.group.parent.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } else { var near_pos = this.group.parent.Parent.Get_NearestPos(this.group.pageIndex, this.group.absOffsetX, this.group.absOffsetY, true, this.group.parent); this.group.parent.OnEnd_ChangeFlow(this.group.absOffsetX, this.group.absOffsetY, this.group.pageIndex, bounds.r - bounds.l, bounds.b - bounds.t, near_pos, true, true); } } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function PreRotateInGroupState(graphicObjects, group, majorObject) { this.id = STATES_ID_PRE_ROTATE_IN_GROUP; this.graphicObjects = graphicObjects; this.group = group; this.majorObject = majorObject; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects = this.graphicObjects.arrPreTrackObjects; this.graphicObjects.arrPreTrackObjects = []; var _track_objects = this.graphicObjects.arrTrackObjects; var _track_object_index; var _track_object_count = _track_objects.length; for (_track_object_index = 0; _track_object_index < _track_object_count; ++_track_object_index) { _track_objects[_track_object_index].init(); } this.graphicObjects.changeCurrentState(new RotateInGroupState(this.graphicObjects, this.group, this.majorObject)); this.graphicObjects.OnMouseMove(e, x, y, pageIndex); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.arrPreTrackObjects = []; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function RotateInGroupState(graphicObjects, group, majorObject) { this.id = STATES_ID_ROTATE_IN_GROUP; this.group = group; this.majorObject = majorObject; this.graphicObjects = graphicObjects; this.invertGroupTransfrom = global_MatrixTransformer.Invert(this.group.transform); this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _translated_x; var _translated_y; if (pageIndex !== this.group.pageIndex) { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.group.pageIndex); _translated_x = _translated_point.X; _translated_y = _translated_point.Y; } else { _translated_x = x; _translated_y = y; } var _transformed_to_group_x = this.invertGroupTransfrom.TransformPointX(_translated_x, _translated_y); var _transformed_to_group_y = this.invertGroupTransfrom.TransformPointY(_translated_x, _translated_y); var _angle = this.majorObject.getAngle(_transformed_to_group_x, _transformed_to_group_y); var _track_object_index; var _track_objects = this.graphicObjects.arrTrackObjects; var _track_objects_count = _track_objects.length; for (_track_object_index = 0; _track_object_index < _track_objects_count; ++_track_object_index) { _track_objects[_track_object_index].modify(_angle, e.ShiftKey); } this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { if (false === editor.isViewMode && false === this.graphicObject.document.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.group.parent.Parent, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var _track_object_index; var _track_objects = this.graphicObjects.arrTrackObjects; var _track_objects_count = _track_objects.length; for (_track_object_index = 0; _track_object_index < _track_objects_count; ++_track_object_index) { _track_objects[_track_object_index].trackEnd(); } this.group.startCalculateAfterInternalResize(); var bounds = this.group.parent.getBounds(); this.graphicObjects.arrTrackObjects = []; this.graphicObjects.changeCurrentState(new GroupState(this.graphicObjects, this.group.parent)); if (this.group.parent.Is_Inline()) { this.group.parent.OnEnd_ResizeInline(bounds.r - bounds.l, bounds.b - bounds.t); } else { var bounds = this.group.parent.getBounds(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.group.parent.getPageIndex(), bounds.l, bounds.t, true, this.group.parent); this.group.parent.OnEnd_ChangeFlow(this.group.absOffsetX, this.group.absOffsetY, this.group.parent.getPageIndex(), bounds.r - bounds.l, bounds.b - bounds.t, near_pos, true, true); } } this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function StartChangeWrapContourState(graphicObjects, wordGraphicObject) { this.id = STATES_ID_START_CHANGE_WRAP; this.graphicObjects = graphicObjects; this.wordGraphicObject = wordGraphicObject; this.OnMouseDown = function (e, x, y, pageIndex) { var object_page_x, object_page_y; if (this.wordGraphicObject.pageIndex === pageIndex) { object_page_x = x; object_page_y = y; } else { var _translated_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.wordGraphicObject.pageIndex); object_page_x = _translated_point.X; object_page_y = _translated_point.Y; } var hit_to_wrap_polygon = this.wordGraphicObject.hitToWrapPolygonPoint(object_page_x, object_page_y); if (hit_to_wrap_polygon.hit === true) { if (hit_to_wrap_polygon.hitType === WRAP_HIT_TYPE_POINT) { if (!e.CtrlKey) { this.graphicObjects.changeCurrentState(new PreChangeWrapContour(this.graphicObjects, this.wordGraphicObject, hit_to_wrap_polygon.pointNum)); } else { if (false === editor.isViewMode && this.wordGraphicObject.wrappingPolygon.arrPoints.length > 3 && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.wordGraphicObject.Parent, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var wrap_polygon = this.wordGraphicObject.wrappingPolygon; var data = {}; data.Type = historyitem_ChangePolygon; data.oldEdited = wrap_polygon.edited; data.oldRelArr = []; for (var i = 0; i < wrap_polygon.relativeArrPoints.length; ++i) { data.oldRelArr[i] = { x: wrap_polygon.relativeArrPoints[i].x, y: wrap_polygon.relativeArrPoints[i].y }; } wrap_polygon.edited = true; wrap_polygon.arrPoints.splice(hit_to_wrap_polygon.pointNum, 1); wrap_polygon.calculateAbsToRel(this.wordGraphicObject.getTransformMatrix()); data.newRelArr = []; for (i = 0; i < wrap_polygon.relativeArrPoints.length; ++i) { data.newRelArr[i] = { x: wrap_polygon.relativeArrPoints[i].x, y: wrap_polygon.relativeArrPoints[i].y }; } History.Add(wrap_polygon, data); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); this.graphicObjects.document.Recalculate(); this.graphicObjects.drawingDocument.OnRecalculatePage(this.wordGraphicObject.pageIndex, this.graphicObjects.document.Pages[this.wordGraphicObject.pageIndex]); } } } else { if (false === editor.isViewMode && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.wordGraphicObject.Parent, CheckType: changestype_Paragraph_Content })) { this.graphicObjects.changeCurrentState(new PreChangeWrapContourAddPoint(this.graphicObjects, this.wordGraphicObject, hit_to_wrap_polygon.pointNum1, hit_to_wrap_polygon.pointNum2, object_page_x, object_page_y)); } } } else { this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.OnMouseDown(e, x, y, pageIndex); } }; this.OnMouseMove = function (e, x, y, pageIndex) {}; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function PreChangeWrapContour(graphicObjects, wordGraphicObject, pointNum) { this.id = STATES_ID_PRE_CHANGE_WRAP; this.graphicObjects = graphicObjects; this.wordGraphicObject = wordGraphicObject; this.pointNum = pointNum; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.arrTrackObjects.push(new CTrackWrapPolygon(this.wordGraphicObject.wrappingPolygon, this.pointNum)); this.graphicObjects.changeCurrentState(new ChangeWrapContour(this.graphicObjects, this.wordGraphicObject, true)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.changeCurrentState(new StartChangeWrapContourState(this.graphicObjects, this.wordGraphicObject)); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function PreChangeWrapContourAddPoint(graphicObjects, wordGraphicObject, pointNum1, pointNum2, startX, startY) { this.id = STATES_ID_PRE_CHANGE_WRAP_ADD; this.graphicObjects = graphicObjects; this.wordGraphicObject = wordGraphicObject; this.pointNum1 = pointNum1; this.pointNum2 = pointNum2; this.startX = startX; this.startY = startY; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { History.Create_NewPoint(); var wrap_polygon = this.wordGraphicObject.wrappingPolygon; var data = {}; data.Type = historyitem_ChangePolygon; data.oldEdited = wrap_polygon.edited; data.oldRelArr = []; for (var i = 0; i < wrap_polygon.relativeArrPoints.length; ++i) { data.oldRelArr[i] = { x: wrap_polygon.relativeArrPoints[i].x, y: wrap_polygon.relativeArrPoints[i].y }; } this.wordGraphicObject.wrappingPolygon.arrPoints.splice(this.pointNum2, 0, { x: this.startX, y: this.startY }); this.wordGraphicObject.wrappingPolygon.calculateAbsToRel(this.wordGraphicObject.getTransformMatrix()); data.newRelArr = []; for (i = 0; i < wrap_polygon.relativeArrPoints.length; ++i) { data.newRelArr[i] = { x: wrap_polygon.relativeArrPoints[i].x, y: wrap_polygon.relativeArrPoints[i].y }; } History.Add(wrap_polygon, data); this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.arrTrackObjects.push(new CTrackWrapPolygon(this.wordGraphicObject.wrappingPolygon, this.pointNum2)); this.graphicObjects.changeCurrentState(new ChangeWrapContour(this.graphicObjects, this.wordGraphicObject, false)); }; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.changeCurrentState(new StartChangeWrapContourState(this.graphicObjects, this.wordGraphicObject)); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function ChangeWrapContour(graphicObjects, wordGraphicObject, bHistoryNewPoint) { this.id = STATES_ID_PRE_CHANGE_WRAP_CONTOUR; this.graphicObjects = graphicObjects; this.wordGraphicObject = wordGraphicObject; this.bHistoryNewPoint = bHistoryNewPoint; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var tr_x, tr_y; if (pageIndex === this.wordGraphicObject.pageIndex) { tr_x = x; tr_y = y; } else { var tr_p = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.wordGraphicObject.pageIndex); tr_x = tr_p.X; tr_y = tr_p.Y; } this.graphicObjects.arrTrackObjects[0].track(tr_x, tr_y); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { var bEndTrack = this.bHistoryNewPoint && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_Drawing_Props, { Type: changestype_2_Element_and_Type, Element: this.wordGraphicObject.Parent, CheckType: changestype_Paragraph_Content }) || !this.bHistoryNewPoint; if (bEndTrack) { if (this.bHistoryNewPoint) { History.Create_NewPoint(); } this.graphicObjects.arrTrackObjects[0].trackEnd(); } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.changeCurrentState(new StartChangeWrapContourState(this.graphicObjects, this.wordGraphicObject)); if (bEndTrack) { this.graphicObjects.document.Recalculate(); } this.graphicObjects.drawingDocument.OnRecalculatePage(this.wordGraphicObject.pageIndex, this.graphicObjects.document.Pages[this.wordGraphicObject.pageIndex]); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function SplineBezierState(graphicObjects) { this.id = STATES_ID_SPLINE_BEZIER; this.graphicObjects = graphicObjects; this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) { this.graphicObjects.startTrackPos = { x: x, y: y, pageIndex: pageIndex }; this.graphicObjects.spline = new Spline(pageIndex, this.graphicObjects.document); this.graphicObjects.spline.path.push(new SplineCommandMoveTo(x, y)); this.graphicObjects.changeCurrentState(new SplineBezierState33(this.graphicObjects, x, y)); var sel_arr = this.graphicObjects.selectionInfo.selectionArray; for (var i = 0; i < sel_arr.length; ++i) { sel_arr[i].deselect(); } sel_arr.length = 0; this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseMove = function (e, X, Y, pageIndex) {}; this.OnMouseUp = function (e, X, Y, pageIndex) { this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function SplineBezierState33(graphicObjects, startX, startY) { this.id = STATES_ID_SPLINE_BEZIER33; this.graphicObjects = graphicObjects; this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var startPos = this.graphicObjects.startTrackPos; if (startPos.x === x && startPos.y === y && startPos.pageIndex === pageIndex) { return; } var tr_x, tr_y; if (pageIndex === startPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, startPos.pageIndex); tr_x = tr_point.X; tr_y = tr_point.Y; } this.graphicObjects.spline.path.push(new SplineCommandLineTo(tr_x, tr_y)); this.graphicObjects.changeCurrentState(new SplineBezierState2(this.graphicObjects)); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function SplineBezierState2(graphicObjects) { this.id = STATES_ID_SPLINE_BEZIER2; this.graphicObjects = graphicObjects; this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) { if (e.ClickCount >= 2) { var lt = this.graphicObjects.spline.getLeftTopPoint(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, lt.x, lt.y, true, null); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var _new_word_graphic_object = this.graphicObjects.spline.createShape(this.graphicObjects.document); _new_word_graphic_object.select(this.graphicObjects.startTrackPos.pageIndex); this.graphicObjects.selectionInfo.selectionArray.push(_new_word_graphic_object); _new_word_graphic_object.recalculateWrapPolygon(); _new_word_graphic_object.Set_DrawingType(drawing_Anchor); _new_word_graphic_object.Set_WrappingType(WRAPPING_TYPE_NONE); _new_word_graphic_object.Set_XYForAdd(_new_word_graphic_object.absOffsetX, _new_word_graphic_object.absOffsetY, near_pos, this.graphicObjects.startTrackPos.pageIndex); _new_word_graphic_object.Add_ToDocument(near_pos); } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.spline = null; editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); } }; this.OnMouseMove = function (e, x, y, pageIndex) { var startPos = this.graphicObjects.startTrackPos; var tr_x, tr_y; if (pageIndex === startPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, startPos.pageIndex); tr_x = tr_point.X; tr_y = tr_point.Y; } this.graphicObjects.spline.path[1].changePoint(tr_x, tr_y); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { if (e.ClickCount < 2) { var tr_x, tr_y; if (pageIndex === this.graphicObjects.startTrackPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); tr_x = tr_point.x; tr_y = tr_point.y; } this.graphicObjects.changeCurrentState(new SplineBezierState3(this.graphicObjects, tr_x, tr_y)); } }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function SplineBezierState3(graphicObjects, startX, startY) { this.id = STATES_ID_SPLINE_BEZIER3; this.graphicObjects = graphicObjects; this.startX = startX; this.startY = startY; this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) { if (e.ClickCount >= 2) { var lt = this.graphicObjects.spline.getLeftTopPoint(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, lt.x, lt.y, true, null); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var _new_word_graphic_object = this.graphicObjects.spline.createShape(this.graphicObjects.document); _new_word_graphic_object.select(this.graphicObjects.startTrackPos.pageIndex); this.graphicObjects.selectionInfo.selectionArray.push(_new_word_graphic_object); _new_word_graphic_object.recalculateWrapPolygon(); _new_word_graphic_object.Set_DrawingType(drawing_Anchor); _new_word_graphic_object.Set_WrappingType(WRAPPING_TYPE_NONE); _new_word_graphic_object.Set_XYForAdd(_new_word_graphic_object.absOffsetX, _new_word_graphic_object.absOffsetY, near_pos, near_pos.Page); _new_word_graphic_object.Add_ToDocument(near_pos); } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.spline = null; editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); } }; this.OnMouseMove = function (e, x, y, pageIndex) { if (x === this.startX && y === this.startY && pageIndex === this.graphicObjects.startTrackPos.pageIndex) { return; } var tr_x, tr_y; if (pageIndex === this.graphicObjects.startTrackPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); tr_x = tr_point.X; tr_y = tr_point.Y; } var x0, y0, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6; var spline = this.graphicObjects.spline; x0 = spline.path[0].x; y0 = spline.path[0].y; x3 = spline.path[1].x; y3 = spline.path[1].y; x6 = tr_x; y6 = tr_y; var vx = (x6 - x0) / 6; var vy = (y6 - y0) / 6; x2 = x3 - vx; y2 = y3 - vy; x4 = x3 + vx; y4 = y3 + vy; x1 = (x0 + x2) * 0.5; y1 = (y0 + y2) * 0.5; x5 = (x4 + x6) * 0.5; y5 = (y4 + y6) * 0.5; spline.path.length = 1; spline.path.push(new SplineCommandBezier(x1, y1, x2, y2, x3, y3)); spline.path.push(new SplineCommandBezier(x4, y4, x5, y5, x6, y6)); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); this.graphicObjects.changeCurrentState(new SplineBezierState4(this.graphicObjects)); }; this.OnMouseUp = function (e, x, y, pageIndex) { if (e.ClickCount >= 2) { var lt = this.graphicObjects.spline.getLeftTopPoint(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, lt.x, lt.y, true, null); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var _new_word_graphic_object = this.graphicObjects.spline.createShape(this.graphicObjects.document); _new_word_graphic_object.select(this.graphicObjects.startTrackPos.pageIndex); this.graphicObjects.selectionInfo.selectionArray.push(_new_word_graphic_object); _new_word_graphic_object.recalculateWrapPolygon(); _new_word_graphic_object.Set_DrawingType(drawing_Anchor); _new_word_graphic_object.Set_WrappingType(WRAPPING_TYPE_NONE); _new_word_graphic_object.Set_XYForAdd(_new_word_graphic_object.absOffsetX, _new_word_graphic_object.absOffsetY, near_pos, near_pos.Page); _new_word_graphic_object.Add_ToDocument(near_pos); } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.spline = null; editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); } }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function SplineBezierState4(graphicObjects) { this.id = STATES_ID_SPLINE_BEZIER4; this.graphicObjects = graphicObjects; this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) { if (e.ClickCount >= 2) { var lt = this.graphicObjects.spline.getLeftTopPoint(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, lt.x, lt.y, true, null); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; if (near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { var _new_word_graphic_object = this.graphicObjects.spline.createShape(this.graphicObjects.document); _new_word_graphic_object.select(this.graphicObjects.startTrackPos.pageIndex); this.graphicObjects.selectionInfo.selectionArray.push(_new_word_graphic_object); _new_word_graphic_object.recalculateWrapPolygon(); _new_word_graphic_object.Set_DrawingType(drawing_Anchor); _new_word_graphic_object.Set_WrappingType(WRAPPING_TYPE_NONE); _new_word_graphic_object.Set_XYForAdd(_new_word_graphic_object.absOffsetX, _new_word_graphic_object.absOffsetY, near_pos, this.graphicObjects.startTrackPos.pageIndex); _new_word_graphic_object.Add_ToDocument(near_pos); } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.spline = null; editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); } }; this.OnMouseMove = function (e, x, y, pageIndex) { var spline = this.graphicObjects.spline; var lastCommand = spline.path[spline.path.length - 1]; var preLastCommand = spline.path[spline.path.length - 2]; var x0, y0, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6; if (spline.path[spline.path.length - 3].id == 0) { x0 = spline.path[spline.path.length - 3].x; y0 = spline.path[spline.path.length - 3].y; } else { x0 = spline.path[spline.path.length - 3].x3; y0 = spline.path[spline.path.length - 3].y3; } x3 = preLastCommand.x3; y3 = preLastCommand.y3; var tr_x, tr_y; if (pageIndex === this.graphicObjects.startTrackPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); tr_x = tr_point.X; tr_y = tr_point.Y; } x6 = tr_x; y6 = tr_y; var vx = (x6 - x0) / 6; var vy = (y6 - y0) / 6; x2 = x3 - vx; y2 = y3 - vy; x4 = x3 + vx; y4 = y3 + vy; x5 = (x4 + x6) * 0.5; y5 = (y4 + y6) * 0.5; if (spline.path[spline.path.length - 3].id == 0) { preLastCommand.x1 = (x0 + x2) * 0.5; preLastCommand.y1 = (y0 + y2) * 0.5; } preLastCommand.x2 = x2; preLastCommand.y2 = y2; preLastCommand.x3 = x3; preLastCommand.y3 = y3; lastCommand.x1 = x4; lastCommand.y1 = y4; lastCommand.x2 = x5; lastCommand.y2 = y5; lastCommand.x3 = x6; lastCommand.y3 = y6; this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { if (e.ClickCount < 2) { var tr_x, tr_y; if (pageIndex === this.graphicObjects.startTrackPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); tr_x = tr_point.X; tr_y = tr_point.Y; } this.graphicObjects.changeCurrentState(new SplineBezierState5(graphicObjects, tr_x, tr_y)); } }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function SplineBezierState5(graphicObjects, startX, startY) { this.id = STATES_ID_SPLINE_BEZIER5; this.graphicObjects = graphicObjects; this.startX = startX; this.startY = startY; this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) { if (e.ClickCount >= 2) { var lt = this.graphicObjects.spline.getLeftTopPoint(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, lt.x, lt.y, true, null); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var _new_word_graphic_object = this.graphicObjects.spline.createShape(this.graphicObjects.document); _new_word_graphic_object.select(this.graphicObjects.startTrackPos.pageIndex); this.graphicObjects.selectionInfo.selectionArray.push(_new_word_graphic_object); _new_word_graphic_object.recalculateWrapPolygon(); _new_word_graphic_object.Set_DrawingType(drawing_Anchor); _new_word_graphic_object.Set_WrappingType(WRAPPING_TYPE_NONE); _new_word_graphic_object.Set_XYForAdd(_new_word_graphic_object.absOffsetX, _new_word_graphic_object.absOffsetY, near_pos, this.graphicObjects.startTrackPos.pageIndex); _new_word_graphic_object.Add_ToDocument(near_pos); } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.spline = null; editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); } }; this.OnMouseMove = function (e, x, y, pageIndex) { if (x === this.startX && y === this.startY && pageIndex === this.graphicObjects.startTrackPos.pageIndex) { return; } var spline = this.graphicObjects.spline; var lastCommand = spline.path[spline.path.length - 1]; var x0, y0, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6; if (spline.path[spline.path.length - 2].id == 0) { x0 = spline.path[spline.path.length - 2].x; y0 = spline.path[spline.path.length - 2].y; } else { x0 = spline.path[spline.path.length - 2].x3; y0 = spline.path[spline.path.length - 2].y3; } x3 = lastCommand.x3; y3 = lastCommand.y3; var tr_x, tr_y; if (pageIndex === this.graphicObjects.startTrackPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); tr_x = tr_point.X; tr_y = tr_point.Y; } x6 = tr_x; y6 = tr_y; var vx = (x6 - x0) / 6; var vy = (y6 - y0) / 6; x2 = x3 - vx; y2 = y3 - vy; x1 = (x2 + x1) * 0.5; y1 = (y2 + y1) * 0.5; x4 = x3 + vx; y4 = y3 + vy; x5 = (x4 + x6) * 0.5; y5 = (y4 + y6) * 0.5; if (spline.path[spline.path.length - 2].id == 0) { lastCommand.x1 = x1; lastCommand.y1 = y1; } lastCommand.x2 = x2; lastCommand.y2 = y2; spline.path.push(new SplineCommandBezier(x4, y4, x5, y5, x6, y6)); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); this.graphicObjects.changeCurrentState(new SplineBezierState4(this.graphicObjects)); }; this.OnMouseUp = function (e, x, y, pageIndex) { if (e.ClickCount >= 2) { var lt = this.graphicObjects.spline.getLeftTopPoint(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, lt.x, lt.y, true, null); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var _new_word_graphic_object = this.graphicObjects.spline.createShape(this.graphicObjects.document); _new_word_graphic_object.select(this.graphicObjects.startTrackPos.pageIndex); this.graphicObjects.selectionInfo.selectionArray.push(_new_word_graphic_object); _new_word_graphic_object.recalculateWrapPolygon(); _new_word_graphic_object.Set_DrawingType(drawing_Anchor); _new_word_graphic_object.Set_WrappingType(WRAPPING_TYPE_NONE); _new_word_graphic_object.Set_XYForAdd(_new_word_graphic_object.absOffsetX, _new_word_graphic_object.absOffsetY, near_pos, this.graphicObjects.startTrackPos.pageIndex); _new_word_graphic_object.Add_ToDocument(near_pos); } this.graphicObjects.arrTrackObjects.length = 0; this.graphicObjects.spline = null; editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); } }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function PolyLineAddState(graphicObjects) { this.graphicObjects = graphicObjects; this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) { this.graphicObjects.startTrackPos = { x: x, y: y, pageIndex: pageIndex }; this.graphicObjects.polyline = new PolyLine(this.graphicObjects.document, pageIndex); this.graphicObjects.polyline.arrPoint.push({ x: x, y: y }); var sel_arr = this.graphicObjects.selectionInfo.selectionArray; for (var i = 0; i < sel_arr.length; ++i) { sel_arr[i].deselect(); } sel_arr.length = 0; this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); var _min_distance = this.graphicObjects.drawingDocument.GetMMPerDot(1); this.graphicObjects.changeCurrentState(new PolyLineAddState2(this.graphicObjects, _min_distance)); }; this.OnMouseMove = function (e, x, y, pageIndex) {}; this.OnMouseUp = function (e, x, y, pageIndex) { this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.polyline = null; }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function PolyLineAddState2(graphicObjects, minDistance) { this.graphicObjects = graphicObjects; this.minDistance = minDistance; this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) {}; this.OnMouseMove = function (e, x, y, pageIndex) { var _last_point = this.graphicObjects.polyline.arrPoint[this.graphicObjects.polyline.arrPoint.length - 1]; var tr_x, tr_y; if (pageIndex === this.graphicObjects.startTrackPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); tr_x = tr_point.X; tr_y = tr_point.Y; } var dx = tr_x - _last_point.x; var dy = tr_y - _last_point.y; if (Math.sqrt(dx * dx + dy * dy) >= this.minDistance) { this.graphicObjects.polyline.arrPoint.push({ x: tr_x, y: tr_y }); this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); } }; this.OnMouseUp = function (e, x, y, pageIndex) { if (this.graphicObjects.polyline.arrPoint.length > 1) { var lt = this.graphicObjects.polyline.getLeftTopPoint(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, lt.x, lt.y); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var _new_word_graphic_object = this.graphicObjects.polyline.createShape(this.graphicObjects.document); this.graphicObjects.arrTrackObjects.length = 0; _new_word_graphic_object.select(this.graphicObjects.startTrackPos.pageIndex); _new_word_graphic_object.recalculateWrapPolygon(); this.graphicObjects.selectionInfo.selectionArray.push(_new_word_graphic_object); _new_word_graphic_object.Set_DrawingType(drawing_Anchor); _new_word_graphic_object.Set_WrappingType(WRAPPING_TYPE_NONE); _new_word_graphic_object.Set_XYForAdd(_new_word_graphic_object.absOffsetX, _new_word_graphic_object.absOffsetY, near_pos, this.graphicObjects.startTrackPos.pageIndex); _new_word_graphic_object.Add_ToDocument(near_pos); } editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.polyline = null; } else { this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.drawingDocument.OnRecalculatePage(this.graphicObjects.startTrackPos.pageIndex, this.graphicObjects.document.Pages[this.graphicObjects.startTrackPos.pageIndex]); this.graphicObjects.polyline = null; } }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function AddPolyLine2State(graphicObjects) { this.graphicObjects = graphicObjects; this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) { this.graphicObjects.startTrackPos = { x: x, y: y, pageIndex: pageIndex }; var sel_arr = this.graphicObjects.selectionInfo.selectionArray; for (var sel_index = 0; sel_index < sel_arr.length; ++sel_index) { sel_arr[sel_index].deselect(); } sel_arr.length = 0; this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); this.graphicObjects.polyline = new PolyLine(this.graphicObjects.document, pageIndex); this.graphicObjects.polyline.arrPoint.push({ x: x, y: y }); this.graphicObjects.changeCurrentState(new AddPolyLine2State2(this.graphicObjects, x, y)); }; this.OnMouseMove = function (AutoShapes, e, X, Y) {}; this.OnMouseUp = function (AutoShapes, e, X, Y) {}; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function AddPolyLine2State2(graphicObjects, x, y) { this.graphicObjects = graphicObjects; this.X = x; this.Y = y; this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) { if (e.ClickCount > 1) { this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.polyline = null; } }; this.OnMouseMove = function (e, x, y, pageIndex) { if (this.X !== x || this.Y !== y || this.graphicObjects.startTrackPos.pageIndex !== pageIndex) { var tr_x, tr_y; if (pageIndex === this.graphicObjects.startTrackPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); tr_x = tr_point.X; tr_y = tr_point.Y; } this.graphicObjects.polyline.arrPoint.push({ x: tr_x, y: tr_y }); this.graphicObjects.changeCurrentState(new AddPolyLine2State3(this.graphicObjects)); } }; this.OnMouseUp = function (e, x, y, pageIndex) {}; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function AddPolyLine2State3(graphicObjects) { this.graphicObjects = graphicObjects; this.minSize = graphicObjects.drawingDocument.GetMMPerDot(1); this.polylineFlag = true; this.OnMouseDown = function (e, x, y, pageIndex) { var tr_x, tr_y; if (pageIndex === this.graphicObjects.startTrackPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); tr_x = tr_point.X; tr_y = tr_point.Y; } this.graphicObjects.polyline.arrPoint.push({ x: tr_x, y: tr_y }); if (e.ClickCount > 1) { var lt = this.graphicObjects.polyline.getLeftTopPoint(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, lt.x, lt.y); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var _new_word_graphic_object = this.graphicObjects.polyline.createShape(this.graphicObjects.document); this.graphicObjects.arrTrackObjects.length = 0; _new_word_graphic_object.select(this.graphicObjects.startTrackPos.pageIndex); _new_word_graphic_object.recalculateWrapPolygon(); this.graphicObjects.selectionInfo.selectionArray.push(_new_word_graphic_object); _new_word_graphic_object.Set_DrawingType(drawing_Anchor); _new_word_graphic_object.Set_WrappingType(WRAPPING_TYPE_NONE); _new_word_graphic_object.Set_XYForAdd(_new_word_graphic_object.absOffsetX, _new_word_graphic_object.absOffsetY, near_pos, this.graphicObjects.startTrackPos.pageIndex); _new_word_graphic_object.Add_ToDocument(near_pos); } editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.polyline = null; } }; this.OnMouseMove = function (e, x, y, pageIndex) { var tr_x, tr_y; if (pageIndex === this.graphicObjects.startTrackPos.pageIndex) { tr_x = x; tr_y = y; } else { var tr_point = this.graphicObjects.drawingDocument.ConvertCoordsToAnotherPage(x, y, pageIndex, this.graphicObjects.startTrackPos.pageIndex); tr_x = tr_point.X; tr_y = tr_point.Y; } if (!e.IsLocked) { this.graphicObjects.polyline.arrPoint[this.graphicObjects.polyline.arrPoint.length - 1] = { x: tr_x, y: tr_y }; } else { var _last_point = this.graphicObjects.polyline.arrPoint[this.graphicObjects.polyline.arrPoint.length - 1]; var dx = tr_x - _last_point.x; var dy = tr_y - _last_point.y; if (Math.sqrt(dx * dx + dy * dy) >= this.minSize) { this.graphicObjects.polyline.arrPoint.push({ x: tr_x, y: tr_y }); } } this.graphicObjects.drawingDocument.m_oWordControl.OnUpdateOverlay(); }; this.OnMouseUp = function (e, x, y, pageIndex) { if (e.ClickCount > 1) { var lt = this.graphicObjects.polyline.getLeftTopPoint(); var near_pos = this.graphicObjects.document.Get_NearestPos(this.graphicObjects.startTrackPos.pageIndex, lt.x, lt.y); near_pos.Page = this.graphicObjects.startTrackPos.pageIndex; if (false === editor.isViewMode && near_pos != null && false === this.graphicObjects.document.Document_Is_SelectionLocked(changestype_None, { Type: changestype_2_Element_and_Type, Element: near_pos.Paragraph, CheckType: changestype_Paragraph_Content })) { History.Create_NewPoint(); var _new_word_graphic_object = this.graphicObjects.polyline.createShape(this.graphicObjects.document); this.graphicObjects.arrTrackObjects.length = 0; _new_word_graphic_object.select(this.graphicObjects.startTrackPos.pageIndex); _new_word_graphic_object.recalculateWrapPolygon(); this.graphicObjects.selectionInfo.selectionArray.push(_new_word_graphic_object); _new_word_graphic_object.Set_DrawingType(drawing_Anchor); _new_word_graphic_object.Set_WrappingType(WRAPPING_TYPE_NONE); _new_word_graphic_object.Set_XYForAdd(_new_word_graphic_object.absOffsetX, _new_word_graphic_object.absOffsetY, near_pos, this.graphicObjects.startTrackPos.pageIndex); _new_word_graphic_object.Add_ToDocument(near_pos); } editor.sync_StartAddShapeCallback(false); editor.sync_EndAddShape(); this.graphicObjects.changeCurrentState(new NullState(this.graphicObjects)); this.graphicObjects.curState.updateAnchorPos(); this.graphicObjects.polyline = null; } }; this.updateCursorType = function (pageIndex, x, y) { return false; }; } function GetMinSnapDistanceX(pointX, arrGrObjects) { var min_dx = null; for (var i = 0; i < arrGrObjects.length; ++i) { var cur_snap_arr_x = arrGrObjects[i].snapArrayX; var count = cur_snap_arr_x.length; for (var snap_index = 0; snap_index < count; ++snap_index) { var dx = cur_snap_arr_x[snap_index] - pointX; if (min_dx === null) { min_dx = dx; } else { if (Math.abs(dx) < Math.abs(min_dx)) { min_dx = dx; } } } } return min_dx; } function GetMinSnapDistanceY(pointY, arrGrObjects) { var min_dy = null; for (var i = 0; i < arrGrObjects.length; ++i) { var cur_snap_arr_y = arrGrObjects[i].snapArrayY; var count = cur_snap_arr_y.length; for (var snap_index = 0; snap_index < count; ++snap_index) { var dy = cur_snap_arr_y[snap_index] - pointY; if (min_dy === null) { min_dy = dy; } else { if (Math.abs(dy) < Math.abs(min_dy)) { min_dy = dy; } } } } return min_dy; } function GetMinSnapDistanceXObject(pointX, arrGrObjects) { var min_dx = null; var ret = null; for (var i = 0; i < arrGrObjects.length; ++i) { var cur_snap_arr_x = arrGrObjects[i].snapArrayX; var count = cur_snap_arr_x.length; for (var snap_index = 0; snap_index < count; ++snap_index) { var dx = cur_snap_arr_x[snap_index] - pointX; if (min_dx === null) { ret = { dist: dx, pos: cur_snap_arr_x[snap_index] }; min_dx = dx; } else { if (Math.abs(dx) < Math.abs(min_dx)) { min_dx = dx; ret = { dist: dx, pos: cur_snap_arr_x[snap_index] }; } } } } return ret; } function GetMinSnapDistanceYObject(pointY, arrGrObjects) { var min_dy = null; var ret = null; for (var i = 0; i < arrGrObjects.length; ++i) { var cur_snap_arr_y = arrGrObjects[i].snapArrayY; var count = cur_snap_arr_y.length; for (var snap_index = 0; snap_index < count; ++snap_index) { var dy = cur_snap_arr_y[snap_index] - pointY; if (min_dy === null) { min_dy = dy; ret = { dist: dy, pos: cur_snap_arr_y[snap_index] }; } else { if (Math.abs(dy) < Math.abs(min_dy)) { min_dy = dy; ret = { dist: dy, pos: cur_snap_arr_y[snap_index] }; } } } } return ret; } function GetMinSnapDistanceXObjectByArrays(pointX, snapArrayX) { var min_dx = null; var ret = null; var cur_snap_arr_x = snapArrayX; var count = cur_snap_arr_x.length; for (var snap_index = 0; snap_index < count; ++snap_index) { var dx = cur_snap_arr_x[snap_index] - pointX; if (min_dx === null) { ret = { dist: dx, pos: cur_snap_arr_x[snap_index] }; min_dx = dx; } else { if (Math.abs(dx) < Math.abs(min_dx)) { min_dx = dx; ret = { dist: dx, pos: cur_snap_arr_x[snap_index] }; } } } return ret; } function GetMinSnapDistanceYObjectByArrays(pointY, snapArrayY) { var min_dy = null; var ret = null; var cur_snap_arr_y = snapArrayY; var count = cur_snap_arr_y.length; for (var snap_index = 0; snap_index < count; ++snap_index) { var dy = cur_snap_arr_y[snap_index] - pointY; if (min_dy === null) { min_dy = dy; ret = { dist: dy, pos: cur_snap_arr_y[snap_index] }; } else { if (Math.abs(dy) < Math.abs(min_dy)) { min_dy = dy; ret = { dist: dy, pos: cur_snap_arr_y[snap_index] }; } } } return ret; }
agpl-3.0
uroni/urbackup_backend
fileservplugin/FileMetadataPipe.cpp
35854
/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "FileMetadataPipe.h" #include "../common/data.h" #include <assert.h> #include "../Interface/Server.h" #include "../stringtools.h" #include "../urbackupcommon/os_functions.h" #include "IFileServ.h" #include <cstring> #include "FileServ.h" #include "PipeSessions.h" #include "../common/adler32.h" #include <limits.h> #ifndef _WIN32 #include <sys/types.h> #ifndef __FreeBSD__ #include <sys/xattr.h> #else #include <sys/extattr.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #endif #if defined(__APPLE__) #define llistxattr(path, list, size) listxattr(path, list, size, XATTR_NOFOLLOW) #define lgetxattr(path, name, value, size) getxattr(path, name, value, size, 0, XATTR_NOFOLLOW) #define stat64 stat #define lstat64 lstat #endif #if defined(__FreeBSD__) #define llistxattr(path, list, size) extattr_list_link(path, EXTATTR_NAMESPACE_USER, list, size) #define lgetxattr(path, name, value, size) extattr_get_link(path, EXTATTR_NAMESPACE_USER, name, value, size) #define stat64 stat #define lstat64 lstat #endif const size_t metadata_id_size = 4+4+8+4; FileMetadataPipe::FileMetadataPipe( IPipe* pipe, const std::string& cmd ) : PipeFileBase(cmd), pipe(pipe), #ifdef _WIN32 hFile(INVALID_HANDLE_VALUE), backup_read_state(-1), #else backup_state(BackupState_StatInit), #endif metadata_state(MetadataState_Wait), errpipe(Server->createMemoryPipe()) { metadata_buffer.resize(4096); init(); } FileMetadataPipe::FileMetadataPipe() : PipeFileBase(std::string()), pipe(nullptr), #ifdef _WIN32 hFile(INVALID_HANDLE_VALUE), backup_read_state(-1), #else backup_state(BackupState_StatInit), #endif metadata_state(MetadataState_Wait), errpipe(Server->createMemoryPipe()) { metadata_buffer.resize(4096); } FileMetadataPipe::~FileMetadataPipe() { assert(token_callback.get() == nullptr); } bool FileMetadataPipe::getExitCode( int& exit_code ) { exit_code = 0; return true; } bool FileMetadataPipe::readStdoutIntoBuffer( char* buf, size_t buf_avail, size_t& read_bytes ) { if (token_callback.get() == nullptr) { token_callback.reset(FileServ::newTokenCallback()); } if(buf_avail==0) { read_bytes = 0; return true; } if(metadata_state==MetadataState_FnSize) { read_bytes = (std::min)(buf_avail, sizeof(unsigned int) - fn_off); unsigned int fn_size = little_endian(static_cast<unsigned int>(public_fn.size())); fn_size = little_endian(fn_size); memcpy(buf, reinterpret_cast<char*>(&fn_size) + fn_off, read_bytes); curr_checksum = urb_adler32(curr_checksum, reinterpret_cast<char*>(&fn_size) + fn_off, static_cast<_u32>(read_bytes)); fn_off+=read_bytes; if(fn_off==sizeof(unsigned int)) { fn_off=0; metadata_state = MetadataState_Fn; } return true; } else if(metadata_state==MetadataState_Fn) { read_bytes = (std::min)(buf_avail, public_fn.size()- fn_off); memcpy(buf, public_fn.data()+fn_off, read_bytes); curr_checksum = urb_adler32(curr_checksum, public_fn.data()+fn_off, static_cast<_u32>(read_bytes)); fn_off+=read_bytes; if(fn_off==public_fn.size()) { fn_off=0; metadata_state = MetadataState_FnChecksum; } return true; } else if(metadata_state==MetadataState_FnChecksum) { read_bytes = (std::min)(buf_avail, sizeof(unsigned int) - fn_off); unsigned int endian_curr_checksum = little_endian(curr_checksum); memcpy(buf, reinterpret_cast<char*>(&endian_curr_checksum) + fn_off, read_bytes); fn_off+=read_bytes; if(fn_off==sizeof(unsigned int)) { metadata_buffer_size = 0; metadata_buffer_off = 0; curr_checksum = urb_adler32(0, nullptr, 0); if(callback==nullptr) { metadata_state = MetadataState_Common; } else { if(!metadata_file->Seek(metadata_file_off)) { std::string msg = "Error seeking to metadata in \"" + metadata_file->getFilename() + "\""; Server->Log(msg, LL_ERROR); errpipe->Write(msg); read_bytes=0; metadata_file.reset(); PipeSessions::fileMetadataDone(public_fn.substr(1), server_token, active_gen); metadata_state = MetadataState_Wait; return false; } metadata_state = MetadataState_File; } } return true; } else if(metadata_state == MetadataState_Common) { if(metadata_buffer_size==0) { SFile file_meta = getFileMetadata(os_file_prefix(local_fn)); if(file_meta.name.empty()) { Server->Log("Error getting metadata (created and last modified time) of "+local_fn, LL_ERROR); } CWData meta_data; meta_data.addChar(1); #ifdef _WIN32 meta_data.addVarInt(file_meta.created); #else meta_data.addVarInt(0); #endif meta_data.addVarInt(file_meta.last_modified); meta_data.addVarInt(file_meta.accessed); meta_data.addVarInt(folder_items); meta_data.addVarInt(metadata_id); if(token_callback.get()!=nullptr) { meta_data.addString(token_callback->getFileTokens(local_fn)); } else { meta_data.addString(""); } size_t meta_size = meta_data.getDataSize() + 2 * sizeof(unsigned int); if(meta_size>20*1024*1024) { Server->Log("File metadata of " + local_fn + " too large (" + convert((size_t)meta_data.getDataSize()) + ")", LL_ERROR); return false; } else if (meta_size > metadata_buffer.size()) { metadata_buffer.resize(meta_size); } unsigned int data_size = little_endian(static_cast<unsigned int>(meta_data.getDataSize())); memcpy(metadata_buffer.data(), &data_size, sizeof(data_size)); memcpy(metadata_buffer.data()+sizeof(unsigned int), meta_data.getDataPtr(), meta_data.getDataSize()); metadata_buffer_size = meta_data.getDataSize()+sizeof(unsigned int); curr_checksum = urb_adler32(curr_checksum, metadata_buffer.data(), static_cast<_u32>(metadata_buffer_size)); unsigned int endian_curr_checksum = little_endian(curr_checksum); memcpy(metadata_buffer.data()+metadata_buffer_size, &endian_curr_checksum, sizeof(endian_curr_checksum)); metadata_buffer_size+=sizeof(endian_curr_checksum); } if (metadata_buffer_size - metadata_buffer_off>0) { read_bytes = (std::min)(metadata_buffer_size - metadata_buffer_off, buf_avail); memcpy(buf, metadata_buffer.data() + metadata_buffer_off, read_bytes); metadata_buffer_off += read_bytes; } if (metadata_buffer_size - metadata_buffer_off == 0) { metadata_buffer_size = 0; metadata_buffer_off = 0; curr_checksum = urb_adler32(0, nullptr, 0); metadata_state = MetadataState_Os; } return true; } else if(metadata_state == MetadataState_Os) { bool b = transmitCurrMetadata(buf, buf_avail, read_bytes); if(read_bytes>0) { curr_checksum = urb_adler32(curr_checksum, buf, static_cast<_u32>(read_bytes)); } if(!b) { fn_off=0; metadata_state = MetadataState_OsChecksum; #ifndef _WIN32 backup_state=BackupState_StatInit; #else hFile = INVALID_HANDLE_VALUE; backup_read_state = -1; #endif } return true; } else if(metadata_state == MetadataState_OsChecksum) { read_bytes = (std::min)(buf_avail, sizeof(unsigned int) - fn_off); unsigned int endian_curr_checksum = little_endian(curr_checksum); memcpy(buf, reinterpret_cast<char*>(&endian_curr_checksum) + fn_off, read_bytes); fn_off+=read_bytes; if(fn_off==sizeof(unsigned int)) { PipeSessions::fileMetadataDone(public_fn.substr(1), server_token, active_gen); metadata_state = MetadataState_Wait; } return true; } else if(metadata_state == MetadataState_File) { read_bytes = static_cast<size_t>((std::min)(static_cast<int64>(buf_avail), metadata_file_size)); if(read_bytes==0) { metadata_state = MetadataState_FileChecksum; return true; } _u32 read = metadata_file->Read(buf, static_cast<_u32>(read_bytes)); if(read!=read_bytes) { std::string msg; Server->Log(msg, LL_ERROR); errpipe->Write(msg); memset(buf + read, 0, read_bytes - read); } curr_checksum = urb_adler32(curr_checksum, buf, static_cast<_u32>(read_bytes)); metadata_file_size-=read_bytes; if(read_bytes<buf_avail) { fn_off=0; metadata_state = MetadataState_File; } return true; } else if(metadata_state == MetadataState_FileChecksum) { read_bytes = (std::min)(buf_avail, sizeof(unsigned int) - fn_off); unsigned int endian_curr_checksum = little_endian(curr_checksum); memcpy(buf, reinterpret_cast<char*>(&endian_curr_checksum) + fn_off, read_bytes); fn_off+=read_bytes; if(fn_off==sizeof(unsigned int)) { metadata_file.reset(); PipeSessions::fileMetadataDone(public_fn.substr(1), server_token, active_gen); metadata_state = MetadataState_Wait; } return true; } else if (metadata_state == MetadataState_Raw) { if (raw_metadata.size() - metadata_buffer_off > 0) { read_bytes = (std::min)(raw_metadata.size() - metadata_buffer_off, buf_avail); memcpy(buf, raw_metadata.data() + metadata_buffer_off, read_bytes); metadata_buffer_off += read_bytes; } if (raw_metadata.size() - metadata_buffer_off == 0) { PipeSessions::fileMetadataDone(public_fn.substr(1), server_token, active_gen); metadata_state = MetadataState_Wait; } return true; } else if (metadata_state == MetadataState_RawFileFnSize) { read_bytes = (std::min)(buf_avail, sizeof(unsigned int) - fn_off); unsigned int fn_size = little_endian(static_cast<unsigned int>(public_fn.size())); fn_size = little_endian(fn_size); memcpy(buf, reinterpret_cast<char*>(&fn_size) + fn_off, read_bytes); curr_checksum = urb_adler32(curr_checksum, reinterpret_cast<char*>(&fn_size) + fn_off, static_cast<_u32>(read_bytes)); fn_off += read_bytes; if (fn_off == sizeof(unsigned int)) { fn_off = 0; metadata_state = MetadataState_RawFileFn; } return true; } else if (metadata_state == MetadataState_RawFileFn) { read_bytes = (std::min)(buf_avail, public_fn.size() - fn_off); memcpy(buf, public_fn.data() + fn_off, read_bytes); curr_checksum = urb_adler32(curr_checksum, public_fn.data() + fn_off, static_cast<_u32>(read_bytes)); fn_off += read_bytes; if (fn_off == public_fn.size()) { fn_off = 0; metadata_state = MetadataState_RawFileFnChecksum; } return true; } else if (metadata_state == MetadataState_RawFileFnChecksum) { read_bytes = (std::min)(buf_avail, sizeof(unsigned int) - fn_off); unsigned int endian_curr_checksum = little_endian(curr_checksum); memcpy(buf, reinterpret_cast<char*>(&endian_curr_checksum) + fn_off, read_bytes); fn_off += read_bytes; if (fn_off == sizeof(unsigned int)) { int64* datasize = reinterpret_cast<int64*>(metadata_buffer.data()); metadata_file_size = transmit_file->Size(); metadata_file_off = 0; *datasize = little_endian(metadata_file_size); metadata_buffer_size = sizeof(int64); metadata_buffer_off = 0; metadata_state = MetadataState_RawFileDataSize; } return true; } else if (metadata_state == MetadataState_RawFileDataSize) { if (metadata_buffer_size - metadata_buffer_off>0) { read_bytes = (std::min)(metadata_buffer_size - metadata_buffer_off, buf_avail); memcpy(buf, metadata_buffer.data() + metadata_buffer_off, read_bytes); metadata_buffer_off += read_bytes; } if (metadata_buffer_size - metadata_buffer_off == 0) { metadata_buffer_size = 0; metadata_buffer_off = 0; curr_checksum = urb_adler32(0, nullptr, 0); metadata_state = MetadataState_RawFileData; sha512_init(&transmit_file_ctx); } return true; } else if (metadata_state == MetadataState_RawFileData) { _u32 max_read = static_cast<_u32>((std::min)(metadata_file_size-metadata_file_off, (std::min)((int64)32768, static_cast<int64>(buf_avail)))); bool has_read_error = false; read_bytes = transmit_file->Read(metadata_file_off, buf, max_read, &has_read_error); sha512_update(&transmit_file_ctx, reinterpret_cast<unsigned char*>(buf), static_cast<_u32>(read_bytes)); if (has_read_error) { Server->Log("Error reading from file " + transmit_file->getFilename() + ". " + os_last_error_str(), LL_WARNING); return false; } metadata_file_off += read_bytes; if (metadata_file_off == metadata_file_size) { metadata_state = MetadataState_RawFileDataChecksum; sha512_final(&transmit_file_ctx, reinterpret_cast<unsigned char*>(metadata_buffer.data())); metadata_buffer_size = SHA512_DIGEST_SIZE; metadata_buffer_off = 0; } return true; } else if (metadata_state == MetadataState_RawFileDataChecksum) { if (metadata_buffer_size - metadata_buffer_off>0) { read_bytes = (std::min)(metadata_buffer_size - metadata_buffer_off, buf_avail); memcpy(buf, metadata_buffer.data() + metadata_buffer_off, read_bytes); metadata_buffer_off += read_bytes; } if (metadata_buffer_size - metadata_buffer_off == 0) { transmit_wait_pipe->Write(std::string()); transmit_wait_pipe = nullptr; transmit_file = nullptr; PipeSessions::fileMetadataDone(public_fn.substr(1), server_token, active_gen); metadata_state = MetadataState_Wait; } return true; } while(true) { std::string msg; size_t r = pipe->Read(&msg, 60000); if(r==0) { if(pipe->hasError()) { read_bytes = 0; return false; } else { *buf = ID_METADATA_NOP; read_bytes = 1; return true; } } else { CRData msg_data(&msg); char id; if (msg_data.getChar(&id)) { if (id == METADATA_PIPE_SEND_FILE && msg_data.getStr(&public_fn) && msg_data.getStr(&local_fn) && msg_data.getInt64(&folder_items) && msg_data.getInt64(&metadata_id) && msg_data.getStr(&server_token) && msg_data.getInt64(&active_gen)) { assert(!public_fn.empty() || !local_fn.empty()); if (std::find(last_public_fns.begin(), last_public_fns.end(), public_fn) != last_public_fns.end()) { PipeSessions::fileMetadataDone(public_fn, server_token, active_gen); *buf = ID_METADATA_NOP; read_bytes = 1; return true; } last_public_fns.push_back(public_fn); if (last_public_fns.size() > 10) { last_public_fns.pop_front(); } int file_type_flags = os_get_file_type(os_file_prefix(local_fn)); if (file_type_flags == 0) { Server->Log("Error getting file type of " + local_fn+". "+os_last_error_str(), LL_ERROR); *buf = ID_METADATA_NOP; read_bytes = 1; PipeSessions::fileMetadataDone(public_fn, server_token, active_gen); return true; } if (!msg_data.getVoidPtr(reinterpret_cast<void**>(&callback))) { callback = nullptr; } if (callback==nullptr && !openFileHandle() ) { Server->Log("Error opening file handle to " + local_fn+". "+os_last_error_str(), LL_ERROR); *buf = ID_METADATA_NOP; read_bytes = 1; PipeSessions::fileMetadataDone(public_fn, server_token, active_gen); return true; } std::string file_type; if ((file_type_flags & EFileType_Directory) && (file_type_flags & EFileType_Symlink)) { file_type = "l"; } else if (file_type_flags & EFileType_Directory) { file_type = "d"; } else { file_type = "f"; } public_fn = file_type + public_fn; metadata_state = MetadataState_FnSize; *buf = ID_METADATA_V1; read_bytes = 1; fn_off = 0; curr_checksum = urb_adler32(0, nullptr, 0); if(callback!=nullptr) { std::string orig_path; _u32 version = 0; metadata_file.reset(callback->getMetadata(public_fn, &orig_path, &metadata_file_off, &metadata_file_size, &version, false)); if (metadata_file.get() == nullptr) { Server->Log("Error opening metadata file for \"" + public_fn + "\"", LL_ERROR); errpipe->Write("Error opening metadata file for \"" + public_fn + "\""); *buf = ID_METADATA_NOP; read_bytes = 1; metadata_state = MetadataState_Wait; PipeSessions::fileMetadataDone(public_fn.substr(1), server_token, active_gen); return true; } if (version != 0) { *buf = version; } public_fn = file_type + orig_path; } return true; } else if (id == METADATA_PIPE_SEND_RAW && msg_data.getStr(&public_fn) && msg_data.getStr(&raw_metadata) && msg_data.getStr(&server_token) && msg_data.getInt64(&active_gen)) { metadata_state = MetadataState_Raw; metadata_buffer_off = 0; return readStdoutIntoBuffer(buf, buf_avail, read_bytes); } else if (id == METADATA_PIPE_SEND_RAW_FILEDATA && msg_data.getStr(&public_fn) && msg_data.getVoidPtr(reinterpret_cast<void**>(&transmit_file)) && msg_data.getVoidPtr(reinterpret_cast<void**>(&transmit_wait_pipe)) && msg_data.getStr(&server_token) && msg_data.getInt64(&active_gen) ) { metadata_state = MetadataState_RawFileFnSize; *buf = ID_RAW_FILE; read_bytes = 1; fn_off = 0; curr_checksum = urb_adler32(0, nullptr, 0); return true; } else if (id == METADATA_PIPE_EXIT) { errpipe->shutdown(); read_bytes = 0; return false; } else { Server->Log("Unknown metadata pipe id: " + convert((int)id), LL_ERROR); assert(false); return false; } } else { Server->Log("Cannot get metadata pipe id", LL_ERROR); assert(false); return false; } } } } void FileMetadataPipe::finishStdout() { token_callback.reset(); } bool FileMetadataPipe::readStderrIntoBuffer( char* buf, size_t buf_avail, size_t& read_bytes ) { while(true) { if(stderr_buf.size()>0) { read_bytes = (std::min)(buf_avail, stderr_buf.size()); memcpy(buf, stderr_buf.data(), read_bytes); stderr_buf.erase(0, read_bytes); return true; } if(errpipe->Read(&stderr_buf)==0) { if(errpipe->hasError()) { return false; } } } } void FileMetadataPipe::cleanupOnForceShutdown() { if (metadata_state != MetadataState_Wait) { PipeSessions::fileMetadataDone(public_fn.substr(1), server_token, active_gen); } metadata_file.reset(); #ifdef _WIN32 if (hFile != INVALID_HANDLE_VALUE) { if (backup_read_context != NULL) { BackupRead(hFile, NULL, 0, NULL, TRUE, TRUE, &backup_read_context); backup_read_context = NULL; } CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; } #endif while (true) { std::string msg; size_t r = pipe->Read(&msg, 0); if (r == 0) { break; } CRData msg_data(&msg); char id; if (msg_data.getChar(&id)) { if (id == METADATA_PIPE_SEND_FILE && msg_data.getStr(&public_fn) && msg_data.getStr(&local_fn) && msg_data.getInt64(&folder_items) && msg_data.getInt64(&metadata_id) && msg_data.getStr(&server_token) && msg_data.getInt64(&active_gen) ) { PipeSessions::fileMetadataDone(public_fn, server_token, active_gen); } else if (id == METADATA_PIPE_SEND_RAW && msg_data.getStr(&public_fn) && msg_data.getStr(&raw_metadata) && msg_data.getStr(&server_token) && msg_data.getInt64(&active_gen)) { PipeSessions::fileMetadataDone(public_fn.substr(1), server_token, active_gen); } else if (id == METADATA_PIPE_SEND_RAW_FILEDATA && msg_data.getStr(&public_fn) && msg_data.getVoidPtr(reinterpret_cast<void**>(&transmit_file)) && msg_data.getVoidPtr(reinterpret_cast<void**>(&transmit_wait_pipe)) && msg_data.getStr(&server_token) && msg_data.getInt64(&active_gen)) { PipeSessions::fileMetadataDone(public_fn.substr(1), server_token, active_gen); } } } } void FileMetadataPipe::forceExitWait() { CWData data; data.addChar(METADATA_PIPE_EXIT); pipe->Write(data.getDataPtr(), data.getDataSize()); errpipe->shutdown(); waitForExit(); } IPipe* FileMetadataPipe::getErrPipe() { return errpipe.get(); } bool FileMetadataPipe::openOsMetadataFile(const std::string& fn) { local_fn = fn; return openFileHandle(); } bool FileMetadataPipe::readCurrOsMetadata(char* buf, size_t buf_avail, size_t& read_bytes) { return transmitCurrMetadata(buf, buf_avail, read_bytes); } #ifdef _WIN32 bool FileMetadataPipe::transmitCurrMetadata( char* buf, size_t buf_avail, size_t& read_bytes ) { if(metadata_buffer_size-metadata_buffer_off>0) { read_bytes = (std::min)(metadata_buffer_size-metadata_buffer_off, buf_avail); memcpy(buf, metadata_buffer.data()+metadata_buffer_off, read_bytes); metadata_buffer_off+=read_bytes; return true; } if(backup_read_state==-1) { if(hFile==INVALID_HANDLE_VALUE) { errpipe->Write("Error opening file \""+local_fn+"\" to read metadata. Last error: "+convert((int)GetLastError())+"\n"); return false; } backup_read_state = 0; backup_read_context=NULL; FILE_BASIC_INFO file_information; if(GetFileInformationByHandleEx(hFile, FileBasicInfo, &file_information, sizeof(file_information))==FALSE) { errpipe->Write("Error getting file attributes of \""+local_fn+"\". Last error: "+convert((int)GetLastError())+"\n"); return false; } CWData data; data.addChar(1); data.addUInt(file_information.FileAttributes); data.addVarInt(file_information.CreationTime.QuadPart); data.addVarInt(file_information.LastAccessTime.QuadPart); data.addVarInt(file_information.LastWriteTime.QuadPart); data.addVarInt(file_information.ChangeTime.QuadPart); _u32 data_size = little_endian(static_cast<_u32>(data.getDataSize())); memcpy(metadata_buffer.data(), &data_size, sizeof(data_size)); memcpy(metadata_buffer.data()+sizeof(data_size), data.getDataPtr(), data.getDataSize()); metadata_buffer_size = data.getDataSize()+sizeof(data_size); metadata_buffer_off=0; return transmitCurrMetadata(buf, buf_avail, read_bytes); } if(backup_read_state==0) { DWORD total_read = 0; DWORD read; BOOL b = BackupRead(hFile, reinterpret_cast<LPBYTE>(metadata_buffer.data()+1), metadata_id_size, &read, FALSE, TRUE, &backup_read_context); if(b==FALSE) { errpipe->Write("Error getting metadata of file \""+local_fn+"\". Last error: "+convert((int)GetLastError())+"\n"); *buf = 0; read_bytes = 1; return false; } if(read==0) { BackupRead(hFile, NULL, 0, NULL, TRUE, TRUE, &backup_read_context); backup_read_context=NULL; CloseHandle(hFile); hFile = INVALID_HANDLE_VALUE; backup_read_state = -1; *buf=0; read_bytes = 1; return false; } if(read!=metadata_id_size) { errpipe->Write("Error getting metadata stream structure.\n"); *buf=0; read_bytes = 1; return false; } total_read += read; metadata_buffer[0]=1; WIN32_STREAM_ID* curr_stream = reinterpret_cast<WIN32_STREAM_ID*>(metadata_buffer.data()+1); if(curr_stream->dwStreamNameSize>0) { if (3 + read + curr_stream->dwStreamNameSize > metadata_buffer.size()) { metadata_buffer.resize(3 + read + curr_stream->dwStreamNameSize); } b = BackupRead(hFile, reinterpret_cast<LPBYTE>(metadata_buffer.data()+1) + read, curr_stream->dwStreamNameSize, &read, FALSE, TRUE, &backup_read_context); if(b==FALSE) { errpipe->Write("Error getting metadata of file \""+local_fn+"\" (2). Last error: "+convert((int)GetLastError())+"\n"); *buf=0; read_bytes = 1; return false; } if(read!=curr_stream->dwStreamNameSize) { errpipe->Write("Error getting metadata stream structure (name).\n"); *buf=0; read_bytes = 1; return false; } curr_stream->cStreamName[curr_stream->dwStreamNameSize/sizeof(WCHAR)] = 0; total_read += read; stream_name = Server->ConvertFromWchar(curr_stream->cStreamName); } else { stream_name.clear(); } if(curr_stream->dwStreamId==BACKUP_DATA || curr_stream->dwStreamId==BACKUP_SPARSE_BLOCK) { //skip LARGE_INTEGER seeked; DWORD high_seeked; b = BackupSeek(hFile, curr_stream->Size.LowPart, curr_stream->Size.HighPart, &seeked.LowPart, &high_seeked, &backup_read_context); seeked.HighPart = high_seeked; if(b==FALSE) { errpipe->Write("Error skipping data stream of file \""+local_fn+"\" (1). Last error: "+convert((int)GetLastError())+"\n"); *buf=0; read_bytes = 1; return false; } if(seeked.QuadPart!=curr_stream->Size.QuadPart) { errpipe->Write("Error skipping data stream of file \""+local_fn+"\" (2). Last error: "+convert((int)GetLastError())+"\n"); *buf=0; read_bytes = 1; return false; } return transmitCurrMetadata(buf, buf_avail, read_bytes); } if (curr_stream->Size.QuadPart > 0) { backup_read_state = 1; curr_stream_size = curr_stream->Size; } metadata_buffer_size = total_read + 1; metadata_buffer_off = 0; curr_pos = 0; return transmitCurrMetadata(buf, buf_avail, read_bytes); } else if(backup_read_state==1) { DWORD toread = static_cast<DWORD>((std::min)(curr_stream_size.QuadPart-curr_pos, static_cast<int64>(buf_avail))); DWORD read; BOOL b = BackupRead(hFile, reinterpret_cast<LPBYTE>(buf), toread, &read, FALSE, TRUE, &backup_read_context); if(b==FALSE) { errpipe->Write("Error reading metadata stream \""+stream_name+"\" of file \""+local_fn+"\". Last error: "+convert((int)GetLastError())+"\n"); memset(buf, 0, toread); } read_bytes = read; curr_pos+=read; assert(curr_pos <= curr_stream_size.QuadPart); if(curr_pos==curr_stream_size.QuadPart) { backup_read_state = 0; } return true; } return false; } bool FileMetadataPipe::openFileHandle() { backup_read_context = NULL; hFile = CreateFileW(Server->ConvertToWchar(os_file_prefix(local_fn)).c_str(), GENERIC_READ | ACCESS_SYSTEM_SECURITY | READ_CONTROL, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_OPEN_REPARSE_POINT, NULL); backup_read_state = -1; if (hFile == INVALID_HANDLE_VALUE && next(local_fn, 0, "\\\\?\\UNC\\")) { hFile = CreateFileW(Server->ConvertToWchar(os_file_prefix(local_fn)).c_str(), GENERIC_READ| READ_CONTROL, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_OPEN_REPARSE_POINT, NULL); } return hFile != INVALID_HANDLE_VALUE; } #else //_WIN32 void serialize_stat_buf(const struct stat64& buf, const std::string& symlink_target, CWData& data) { data.addChar(1); data.addVarInt(buf.st_dev); data.addVarInt(buf.st_mode); data.addVarInt(buf.st_uid); data.addVarInt(buf.st_gid); data.addVarInt(buf.st_rdev); #if defined(__APPLE__) || defined(__FreeBSD__) data.addVarInt(buf.st_atimespec.tv_sec); data.addUInt(buf.st_atimespec.tv_nsec); data.addVarInt(buf.st_mtimespec.tv_sec); data.addUInt(buf.st_mtimespec.tv_nsec); data.addVarInt(buf.st_ctimespec.tv_sec); data.addUInt(buf.st_ctimespec.tv_nsec); data.addVarInt(buf.st_flags); #else data.addVarInt(buf.st_atime); data.addUInt(buf.st_atim.tv_nsec); data.addVarInt(buf.st_mtime); data.addUInt(buf.st_mtim.tv_nsec); data.addVarInt(buf.st_ctime); data.addUInt(buf.st_ctim.tv_nsec); data.addVarInt(0); #endif data.addString(symlink_target); } namespace { bool get_xattr_keys(const std::string& fn, std::vector<std::string>& keys) { ssize_t mult = 1; while(true) { ssize_t bufsize; bufsize = llistxattr(fn.c_str(), nullptr, 0); if(bufsize==-1) { if (errno == EOPNOTSUPP) { return true; } #ifdef __APPLE__ if (errno == EPERM) { //fs object does not support extended attributes return true; } #endif Server->Log("Error getting extended attribute list of file "+fn+" errno: "+convert(errno), LL_ERROR); return false; } std::string buf; buf.resize(bufsize*mult); bufsize = llistxattr(fn.c_str(), &buf[0], buf.size()); if(bufsize==-1 && errno==ERANGE) { ++mult; if (mult >= 10) { Server->Log("Error getting extended attribute list of file " + fn + " errno: " + convert(errno) + " (3)", LL_ERROR); return false; } Server->Log("Extended attribute list size increased. Retrying...", LL_DEBUG); continue; } if(bufsize==-1) { Server->Log("Error getting extended attribute list of file "+fn+" errno: "+convert(errno)+" (2)", LL_ERROR); return false; } Tokenize(buf, keys, std::string(1, '\0')); for(size_t i=0;i<keys.size();) { if (keys[i].empty() || keys[i].size()>=UINT_MAX) { keys.erase(keys.begin() + i); continue; } unsigned int ksize = static_cast<unsigned int>(keys[i].size()); ksize = little_endian(ksize); keys[i].insert(0, reinterpret_cast<char*>(&ksize), sizeof(ksize)); ++i; } return true; } } bool get_xattr(const std::string& fn, const std::string& key, std::string& value) { while(true) { ssize_t bufsize; bufsize = lgetxattr(fn.c_str(), key.c_str()+sizeof(unsigned int), nullptr, 0); if(bufsize==-1) { Server->Log("Error getting extended attribute \""+key+"\" of file \""+fn+"\" errno: "+convert(errno), LL_ERROR); return false; } value.resize(bufsize+sizeof(_u32)); bufsize = lgetxattr(fn.c_str(), key.c_str()+sizeof(unsigned int), &value[sizeof(_u32)], value.size()-sizeof(_u32)); if(bufsize==-1 && errno==ERANGE) { Server->Log("Extended attribute size increased. Retrying...", LL_DEBUG); continue; } if(bufsize==-1) { Server->Log("Error getting extended attribute \""+key+"\" of file \""+fn+"\" errno: "+convert(errno)+" (2)", LL_ERROR); return false; } if(bufsize<value.size()-sizeof(_u32)) { value.resize(bufsize+sizeof(_u32)); } _u32 vsize=static_cast<_u32>(bufsize); vsize=little_endian(vsize); memcpy(&value[0], &vsize, sizeof(vsize)); return true; } } } bool FileMetadataPipe::transmitCurrMetadata(char* buf, size_t buf_avail, size_t& read_bytes) { if(backup_state==BackupState_StatInit) { CWData data; struct stat64 statbuf; int rc = lstat64(local_fn.c_str(), &statbuf); if(rc!=0) { Server->Log("Error with lstat of "+local_fn+" errorcode: "+convert(errno), LL_ERROR); return false; } std::string symlink_target; if (S_ISLNK(statbuf.st_mode)) { if (!os_get_symlink_target(local_fn, symlink_target)) { Server->Log("Error getting symlink target of " + local_fn + " errorcode: " + convert(errno), LL_ERROR); return false; } } serialize_stat_buf(statbuf, symlink_target, data); if(data.getDataSize()+sizeof(_u32)>metadata_buffer.size()) { Server->Log("File metadata of "+local_fn+" too large ("+convert((size_t)data.getDataSize()+sizeof(_u32))+")", LL_ERROR); return false; } _u32 metadata_size = little_endian(static_cast<_u32>(data.getDataSize())); memcpy(metadata_buffer.data(), &metadata_size, sizeof(_u32)); memcpy(metadata_buffer.data()+sizeof(_u32), data.getDataPtr(), data.getDataSize()); metadata_buffer_size=data.getDataSize()+sizeof(_u32); metadata_buffer_off=0; backup_state=BackupState_Stat; return transmitCurrMetadata(buf, buf_avail, read_bytes); } else if(backup_state==BackupState_Stat) { if(metadata_buffer_size-metadata_buffer_off>0) { read_bytes = (std::min)(metadata_buffer_size-metadata_buffer_off, buf_avail); memcpy(buf, metadata_buffer.data()+metadata_buffer_off, read_bytes); metadata_buffer_off+=read_bytes; } if(metadata_buffer_size-metadata_buffer_off==0) { backup_state=BackupState_EAttrInit; } return true; } else if(backup_state==BackupState_EAttrInit) { eattr_keys.clear(); if(!get_xattr_keys(local_fn, eattr_keys)) { return false; } CWData data; data.addInt64(eattr_keys.size()); memcpy(metadata_buffer.data(), data.getDataPtr(), data.getDataSize()); metadata_buffer_size=data.getDataSize(); metadata_buffer_off=0; backup_state=BackupState_EAttr; return transmitCurrMetadata(buf, buf_avail, read_bytes); } else if(backup_state==BackupState_EAttr) { if(metadata_buffer_size-metadata_buffer_off>0) { read_bytes = (std::min)(metadata_buffer_size-metadata_buffer_off, buf_avail); memcpy(buf, metadata_buffer.data()+metadata_buffer_off, read_bytes); metadata_buffer_off+=read_bytes; } if(metadata_buffer_size-metadata_buffer_off==0) { if(!eattr_keys.empty()) { eattr_idx=0; backup_state=BackupState_EAttr_Vals_Key; eattr_key_off=0; } else { return false; } } return true; } else if(backup_state==BackupState_EAttr_Vals_Key) { if(eattr_keys[eattr_idx].size()-eattr_key_off>0) { read_bytes = (std::min)(eattr_keys[eattr_idx].size()-eattr_key_off, buf_avail); memcpy(buf, eattr_keys[eattr_idx].c_str()+eattr_key_off, read_bytes); eattr_key_off+=read_bytes; } if(eattr_keys[eattr_idx].size()-eattr_key_off==0) { if(!get_xattr(local_fn, eattr_keys[eattr_idx], eattr_val)) { eattr_val.resize(sizeof(_u32)); unsigned int umax = UINT_MAX; memcpy(&eattr_val[0], &umax, sizeof(umax)); } backup_state = BackupState_EAttr_Vals_Val; eattr_val_off=0; } return true; } else if (backup_state == BackupState_EAttr_Vals_Val) { if (eattr_val.size() - eattr_val_off > 0) { read_bytes = (std::min)(eattr_val.size() - eattr_val_off, buf_avail); memcpy(buf, eattr_val.data() + eattr_val_off, read_bytes); eattr_val_off += read_bytes; } if (eattr_val.size() - eattr_val_off == 0) { if (eattr_idx + 1 < eattr_keys.size()) { ++eattr_idx; backup_state = BackupState_EAttr_Vals_Key; eattr_key_off = 0; } else { //finished return false; } } return true; } return false; } bool FileMetadataPipe::openFileHandle() { return true; } #endif //_WIN32
agpl-3.0
kkmsc17/smes
xnes/snes9x/filter/blit.cpp
24061
/*********************************************************************************** Snes9x - Portable Super Nintendo Entertainment System (TM) emulator. (c) Copyright 1996 - 2002 Gary Henderson ([email protected]), Jerremy Koot ([email protected]) (c) Copyright 2002 - 2004 Matthew Kendora (c) Copyright 2002 - 2005 Peter Bortas ([email protected]) (c) Copyright 2004 - 2005 Joel Yliluoma (http://iki.fi/bisqwit/) (c) Copyright 2001 - 2006 John Weidman ([email protected]) (c) Copyright 2002 - 2006 funkyass ([email protected]), Kris Bleakley ([email protected]) (c) Copyright 2002 - 2010 Brad Jorsch ([email protected]), Nach ([email protected]), (c) Copyright 2002 - 2011 zones ([email protected]) (c) Copyright 2006 - 2007 nitsuja (c) Copyright 2009 - 2011 BearOso, OV2 BS-X C emulator code (c) Copyright 2005 - 2006 Dreamer Nom, zones C4 x86 assembler and some C emulation code (c) Copyright 2000 - 2003 _Demo_ ([email protected]), Nach, zsKnight ([email protected]) C4 C++ code (c) Copyright 2003 - 2006 Brad Jorsch, Nach DSP-1 emulator code (c) Copyright 1998 - 2006 _Demo_, Andreas Naive ([email protected]), Gary Henderson, Ivar ([email protected]), John Weidman, Kris Bleakley, Matthew Kendora, Nach, neviksti ([email protected]) DSP-2 emulator code (c) Copyright 2003 John Weidman, Kris Bleakley, Lord Nightmare ([email protected]), Matthew Kendora, neviksti DSP-3 emulator code (c) Copyright 2003 - 2006 John Weidman, Kris Bleakley, Lancer, z80 gaiden DSP-4 emulator code (c) Copyright 2004 - 2006 Dreamer Nom, John Weidman, Kris Bleakley, Nach, z80 gaiden OBC1 emulator code (c) Copyright 2001 - 2004 zsKnight, pagefault ([email protected]), Kris Bleakley Ported from x86 assembler to C by sanmaiwashi SPC7110 and RTC C++ emulator code used in 1.39-1.51 (c) Copyright 2002 Matthew Kendora with research by zsKnight, John Weidman, Dark Force SPC7110 and RTC C++ emulator code used in 1.52+ (c) Copyright 2009 byuu, neviksti S-DD1 C emulator code (c) Copyright 2003 Brad Jorsch with research by Andreas Naive, John Weidman S-RTC C emulator code (c) Copyright 2001 - 2006 byuu, John Weidman ST010 C++ emulator code (c) Copyright 2003 Feather, John Weidman, Kris Bleakley, Matthew Kendora Super FX x86 assembler emulator code (c) Copyright 1998 - 2003 _Demo_, pagefault, zsKnight Super FX C emulator code (c) Copyright 1997 - 1999 Ivar, Gary Henderson, John Weidman Sound emulator code used in 1.5-1.51 (c) Copyright 1998 - 2003 Brad Martin (c) Copyright 1998 - 2006 Charles Bilyue' Sound emulator code used in 1.52+ (c) Copyright 2004 - 2007 Shay Green ([email protected]) SH assembler code partly based on x86 assembler code (c) Copyright 2002 - 2004 Marcus Comstedt ([email protected]) 2xSaI filter (c) Copyright 1999 - 2001 Derek Liauw Kie Fa HQ2x, HQ3x, HQ4x filters (c) Copyright 2003 Maxim Stepin ([email protected]) NTSC filter (c) Copyright 2006 - 2007 Shay Green GTK+ GUI code (c) Copyright 2004 - 2011 BearOso Win32 GUI code (c) Copyright 2003 - 2006 blip, funkyass, Matthew Kendora, Nach, nitsuja (c) Copyright 2009 - 2011 OV2 Mac OS GUI code (c) Copyright 1998 - 2001 John Stiles (c) Copyright 2001 - 2011 zones Specific ports contains the works of other authors. See headers in individual files. Snes9x homepage: http://www.snes9x.com/ Permission to use, copy, modify and/or distribute Snes9x in both binary and source form, for non-commercial purposes, is hereby granted without fee, providing that this license information and copyright notice appear with all copies and any derived work. This software is provided 'as-is', without any express or implied warranty. In no event shall the authors be held liable for any damages arising from the use of this software or it's derivatives. Snes9x is freeware for PERSONAL USE only. Commercial users should seek permission of the copyright holders first. Commercial use includes, but is not limited to, charging money for Snes9x or software derived from Snes9x, including Snes9x or derivatives in commercial game bundles, and/or using Snes9x as a promotion for your commercial product. The copyright holders request that bug fixes and improvements to the code should be forwarded to them so everyone can benefit from the modifications in future versions. Super NES and Super Nintendo Entertainment System are trademarks of Nintendo Co., Limited and its subsidiary companies. ***********************************************************************************/ #include "snes9x.h" #include "blit.h" #define ALL_COLOR_MASK (FIRST_COLOR_MASK | SECOND_COLOR_MASK | THIRD_COLOR_MASK) #ifdef GFX_MULTI_FORMAT static uint16 lowPixelMask = 0, qlowPixelMask = 0, highBitsMask = 0; static uint32 colorMask = 0; #else #define lowPixelMask (RGB_LOW_BITS_MASK) #define qlowPixelMask ((RGB_HI_BITS_MASK >> 3) | TWO_LOW_BITS_MASK) #define highBitsMask (ALL_COLOR_MASK & RGB_REMOVE_LOW_BITS_MASK) #define colorMask \ (((~RGB_HI_BITS_MASK & ALL_COLOR_MASK) << 16) | \ (~RGB_HI_BITS_MASK & ALL_COLOR_MASK)) #endif static snes_ntsc_t *ntsc = NULL; static uint8 *XDelta = NULL; bool8 S9xBlitFilterInit(void) { XDelta = new uint8[SNES_WIDTH * SNES_HEIGHT_EXTENDED * 4]; if (!XDelta) return (FALSE); S9xBlitClearDelta(); #ifdef GFX_MULTI_FORMAT lowPixelMask = RGB_LOW_BITS_MASK; qlowPixelMask = (RGB_HI_BITS_MASK >> 3) | TWO_LOW_BITS_MASK; highBitsMask = ALL_COLOR_MASK & RGB_REMOVE_LOW_BITS_MASK; colorMask = ((~RGB_HI_BITS_MASK & ALL_COLOR_MASK) << 16) | (~RGB_HI_BITS_MASK & ALL_COLOR_MASK); #endif return (TRUE); } void S9xBlitFilterDeinit(void) { if (XDelta) { delete[] XDelta; XDelta = NULL; } } void S9xBlitClearDelta(void) { uint32 *d = (uint32 *)XDelta; for (int y = 0; y < SNES_HEIGHT_EXTENDED; y++) for (int x = 0; x < SNES_WIDTH; x++) *d++ = 0x80008000; } bool8 S9xBlitNTSCFilterInit(void) { ntsc = (snes_ntsc_t *)malloc(sizeof(snes_ntsc_t)); if (!ntsc) return (FALSE); snes_ntsc_init(ntsc, &snes_ntsc_composite); return (TRUE); } void S9xBlitNTSCFilterDeinit(void) { if (ntsc) { free(ntsc); ntsc = NULL; } } void S9xBlitNTSCFilterSet(const snes_ntsc_setup_t *setup) { snes_ntsc_init(ntsc, setup); } void S9xBlitPixSimple1x1(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { width <<= 1; for (; height; height--) { memcpy(dstPtr, srcPtr, width); srcPtr += srcRowBytes; dstPtr += dstRowBytes; } } void S9xBlitPixSimple1x2(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { width <<= 1; for (; height; height--) { memcpy(dstPtr, srcPtr, width); dstPtr += dstRowBytes; memcpy(dstPtr, srcPtr, width); srcPtr += srcRowBytes; dstPtr += dstRowBytes; } } void S9xBlitPixSimple2x1(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { for (; height; height--) { uint16 *dP = (uint16 *)dstPtr, *bP = (uint16 *)srcPtr; for (int i = 0; i < (width >> 1); i++) { *dP++ = *bP; *dP++ = *bP++; *dP++ = *bP; *dP++ = *bP++; } srcPtr += srcRowBytes; dstPtr += dstRowBytes; } } void S9xBlitPixSimple2x2(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { uint8 *dstPtr2 = dstPtr + dstRowBytes, *deltaPtr = XDelta; dstRowBytes <<= 1; for (; height; height--) { uint32 *dP1 = (uint32 *)dstPtr, *dP2 = (uint32 *)dstPtr2, *bP = (uint32 *)srcPtr, *xP = (uint32 *)deltaPtr; uint32 currentPixel, lastPixel, currentPixA, currentPixB, colorA, colorB; for (int i = 0; i < (width >> 1); i++) { currentPixel = *bP; lastPixel = *xP; if (currentPixel != lastPixel) { #ifdef MSB_FIRST colorA = (currentPixel >> 16) & 0xFFFF; colorB = (currentPixel)&0xFFFF; #else colorA = (currentPixel)&0xFFFF; colorB = (currentPixel >> 16) & 0xFFFF; #endif currentPixA = (colorA << 16) | colorA; currentPixB = (colorB << 16) | colorB; dP1[0] = currentPixA; dP1[1] = currentPixB; dP2[0] = currentPixA; dP2[1] = currentPixB; *xP = *bP; } bP++; xP++; dP1 += 2; dP2 += 2; } srcPtr += srcRowBytes; deltaPtr += srcRowBytes; dstPtr += dstRowBytes; dstPtr2 += dstRowBytes; } } void S9xBlitPixBlend1x1(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { for (; height; height--) { uint16 *dP = (uint16 *)dstPtr, *bP = (uint16 *)srcPtr; uint16 prev, curr; prev = *bP; for (int i = 0; i < (width >> 1); i++) { curr = *bP++; *dP++ = (prev & curr) + (((prev ^ curr) & highBitsMask) >> 1); prev = curr; curr = *bP++; *dP++ = (prev & curr) + (((prev ^ curr) & highBitsMask) >> 1); prev = curr; } srcPtr += srcRowBytes; dstPtr += dstRowBytes; } } void S9xBlitPixBlend2x1(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { for (; height; height--) { uint16 *dP = (uint16 *)dstPtr, *bP = (uint16 *)srcPtr; uint16 prev, curr; prev = *bP; for (int i = 0; i < (width >> 1); i++) { curr = *bP++; *dP++ = (prev & curr) + (((prev ^ curr) & highBitsMask) >> 1); *dP++ = curr; prev = curr; curr = *bP++; *dP++ = (prev & curr) + (((prev ^ curr) & highBitsMask) >> 1); *dP++ = curr; prev = curr; } srcPtr += srcRowBytes; dstPtr += dstRowBytes; } } void S9xBlitPixTV1x2(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { uint8 *dstPtr2 = dstPtr + dstRowBytes; dstRowBytes <<= 1; for (; height; height--) { uint32 *dP1 = (uint32 *)dstPtr, *dP2 = (uint32 *)dstPtr2, *bP = (uint32 *)srcPtr; uint32 product, darkened; for (int i = 0; i < (width >> 1); i++) { product = *dP1++ = *bP++; darkened = (product = (product >> 1) & colorMask); darkened += (product = (product >> 1) & colorMask); *dP2++ = darkened; } srcPtr += srcRowBytes; dstPtr += dstRowBytes; dstPtr2 += dstRowBytes; } } void S9xBlitPixTV2x2(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { uint8 *dstPtr2 = dstPtr + dstRowBytes, *deltaPtr = XDelta; dstRowBytes <<= 1; for (; height; height--) { uint32 *dP1 = (uint32 *)dstPtr, *dP2 = (uint32 *)dstPtr2, *bP = (uint32 *)srcPtr, *xP = (uint32 *)deltaPtr; uint32 currentPixel, nextPixel, currentDelta, nextDelta, colorA, colorB, product, darkened; for (int i = 0; i < (width >> 1) - 1; i++) { currentPixel = *bP; currentDelta = *xP; nextPixel = *(bP + 1); nextDelta = *(xP + 1); if ((currentPixel != currentDelta) || (nextPixel != nextDelta)) { *xP = *bP; #ifdef MSB_FIRST colorA = (currentPixel >> 16) & 0xFFFF; colorB = (currentPixel)&0xFFFF; #else colorA = (currentPixel)&0xFFFF; colorB = (currentPixel >> 16) & 0xFFFF; #endif #ifdef MSB_FIRST *dP1 = product = (colorA << 16) | ((((colorA >> 1) & colorMask) + ((colorB >> 1) & colorMask) + (colorA & colorB & lowPixelMask))); #else *dP1 = product = (colorA) | ((((colorA >> 1) & colorMask) + ((colorB >> 1) & colorMask) + (colorA & colorB & lowPixelMask)) << 16); #endif darkened = (product = ((product >> 1) & colorMask)); darkened += (product = ((product >> 1) & colorMask)); darkened += (product >> 1) & colorMask; *dP2 = darkened; #ifdef MSB_FIRST colorA = (nextPixel >> 16) & 0xFFFF; #else colorA = (nextPixel)&0xFFFF; #endif #ifdef MSB_FIRST *(dP1 + 1) = product = (colorB << 16) | ((((colorA >> 1) & colorMask) + ((colorB >> 1) & colorMask) + (colorA & colorB & lowPixelMask))); #else *(dP1 + 1) = product = (colorB) | ((((colorA >> 1) & colorMask) + ((colorB >> 1) & colorMask) + (colorA & colorB & lowPixelMask)) << 16); #endif darkened = (product = ((product >> 1) & colorMask)); darkened += (product = ((product >> 1) & colorMask)); darkened += (product >> 1) & colorMask; *(dP2 + 1) = darkened; } bP++; xP++; dP1 += 2; dP2 += 2; } // Last 2 Pixels currentPixel = *bP; currentDelta = *xP; if (currentPixel != currentDelta) { *xP = *bP; #ifdef MSB_FIRST colorA = (currentPixel >> 16) & 0xFFFF; colorB = (currentPixel)&0xFFFF; #else colorA = (currentPixel)&0xFFFF; colorB = (currentPixel >> 16) & 0xFFFF; #endif #ifdef MSB_FIRST *dP1 = product = (colorA << 16) | ((((colorA >> 1) & colorMask) + ((colorB >> 1) & colorMask) + (colorA & colorB & lowPixelMask))); #else *dP1 = product = (colorA) | ((((colorA >> 1) & colorMask) + ((colorB >> 1) & colorMask) + (colorA & colorB & lowPixelMask)) << 16); #endif darkened = (product = ((product >> 1) & colorMask)); darkened += (product = ((product >> 1) & colorMask)); darkened += (product >> 1) & colorMask; *dP2 = darkened; *(dP1 + 1) = product = (colorB << 16) | colorB; darkened = (product = ((product >> 1) & colorMask)); darkened += (product = ((product >> 1) & colorMask)); darkened += (product >> 1) & colorMask; *(dP2 + 1) = darkened; } srcPtr += srcRowBytes; deltaPtr += srcRowBytes; dstPtr += dstRowBytes; dstPtr2 += dstRowBytes; } } void S9xBlitPixMixedTV1x2(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { uint8 *dstPtr2 = dstPtr + dstRowBytes, *srcPtr2 = srcPtr + srcRowBytes; dstRowBytes <<= 1; for (; height > 1; height--) { uint16 *dP1 = (uint16 *)dstPtr, *dP2 = (uint16 *)dstPtr2, *bP1 = (uint16 *)srcPtr, *bP2 = (uint16 *)srcPtr2; uint16 prev, next, mixed; for (int i = 0; i < width; i++) { prev = *bP1++; next = *bP2++; mixed = prev + next + ((prev ^ next) & lowPixelMask); *dP1++ = prev; *dP2++ = (mixed >> 1) - (mixed >> 4 & qlowPixelMask); } srcPtr += srcRowBytes; srcPtr2 += srcRowBytes; dstPtr += dstRowBytes; dstPtr2 += dstRowBytes; } // Last 1 line uint16 *dP1 = (uint16 *)dstPtr, *dP2 = (uint16 *)dstPtr2, *bP1 = (uint16 *)srcPtr; uint16 prev, mixed; for (int i = 0; i < width; i++) { prev = *bP1++; mixed = prev + ((prev ^ 0) & lowPixelMask); *dP1++ = prev; *dP2++ = (mixed >> 1) - (mixed >> 4 & qlowPixelMask); } } void S9xBlitPixSmooth2x2(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { uint8 *dstPtr2 = dstPtr + dstRowBytes, *deltaPtr = XDelta; uint32 lastLinePix[SNES_WIDTH << 1]; uint8 lastLineChg[SNES_WIDTH >> 1]; int lineBytes = width << 1; dstRowBytes <<= 1; memset(lastLinePix, 0, sizeof(lastLinePix)); memset(lastLineChg, 0, sizeof(lastLineChg)); for (; height; height--) { uint32 *dP1 = (uint32 *)dstPtr, *dP2 = (uint32 *)dstPtr2, *bP = (uint32 *)srcPtr, *xP = (uint32 *)deltaPtr; uint32 *lL = lastLinePix; uint8 *lC = lastLineChg; uint32 currentPixel, nextPixel, currentDelta, nextDelta, lastPix, lastChg, thisChg, currentPixA, currentPixB, colorA, colorB, colorC; uint16 savePixel; savePixel = *(uint16 *)(srcPtr + lineBytes); *(uint16 *)(srcPtr + lineBytes) = *(uint16 *)(srcPtr + lineBytes - 2); *(uint32 *)(deltaPtr + lineBytes) = *(uint32 *)(srcPtr + lineBytes); nextPixel = *bP++; nextDelta = *xP++; for (int i = 0; i < (width >> 1); i++) { currentPixel = nextPixel; currentDelta = nextDelta; nextPixel = *bP++; nextDelta = *xP++; lastChg = *lC; thisChg = (nextPixel - nextDelta) | (currentPixel - currentDelta); #ifdef MSB_FIRST colorA = (currentPixel >> 16) & 0xFFFF; colorB = (currentPixel)&0xFFFF; colorC = (nextPixel >> 16) & 0xFFFF; currentPixA = (colorA << 16) | ((((colorA >> 1) & colorMask) + ((colorB >> 1) & colorMask) + (colorA & colorB & lowPixelMask))); currentPixB = (colorB << 16) | ((((colorC >> 1) & colorMask) + ((colorB >> 1) & colorMask) + (colorC & colorB & lowPixelMask))); #else colorA = (currentPixel)&0xFFFF; colorB = (currentPixel >> 16) & 0xFFFF; colorC = (nextPixel)&0xFFFF; currentPixA = (colorA) | ((((colorA >> 1) & colorMask) + ((colorB >> 1) & colorMask) + (colorA & colorB & lowPixelMask)) << 16); currentPixB = (colorB) | ((((colorC >> 1) & colorMask) + ((colorB >> 1) & colorMask) + (colorC & colorB & lowPixelMask)) << 16); #endif if (thisChg | lastChg) { xP[-2] = currentPixel; lastPix = lL[0]; dP1[0] = ((currentPixA >> 1) & colorMask) + ((lastPix >> 1) & colorMask) + (currentPixA & lastPix & lowPixelMask); dP2[0] = currentPixA; lL[0] = currentPixA; lastPix = lL[1]; dP1[1] = ((currentPixB >> 1) & colorMask) + ((lastPix >> 1) & colorMask) + (currentPixB & lastPix & lowPixelMask); dP2[1] = currentPixB; lL[1] = currentPixB; *lC++ = (thisChg != 0); } else { lL[0] = currentPixA; lL[1] = currentPixB; *lC++ = 0; } lL += 2; dP2 += 2; dP1 += 2; } *(uint16 *)(srcPtr + lineBytes) = savePixel; srcPtr += srcRowBytes; deltaPtr += srcRowBytes; dstPtr += dstRowBytes; dstPtr2 += dstRowBytes; } } void S9xBlitPixSuper2xSaI16(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { Super2xSaI(srcPtr, srcRowBytes, dstPtr, dstRowBytes, width, height); } void S9xBlitPix2xSaI16(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { _2xSaI(srcPtr, srcRowBytes, dstPtr, dstRowBytes, width, height); } void S9xBlitPixSuperEagle16(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { SuperEagle(srcPtr, srcRowBytes, dstPtr, dstRowBytes, width, height); } void S9xBlitPixEPX16(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { EPX_16(srcPtr, srcRowBytes, dstPtr, dstRowBytes, width, height); } void S9xBlitPixHQ2x16(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { HQ2X_16(srcPtr, srcRowBytes, dstPtr, dstRowBytes, width, height); } void S9xBlitPixHQ3x16(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { HQ3X_16(srcPtr, srcRowBytes, dstPtr, dstRowBytes, width, height); } void S9xBlitPixHQ4x16(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { HQ4X_16(srcPtr, srcRowBytes, dstPtr, dstRowBytes, width, height); } void S9xBlitPixNTSC16(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { snes_ntsc_blit(ntsc, (SNES_NTSC_IN_T const *)srcPtr, srcRowBytes >> 1, 0, width, height, dstPtr, dstRowBytes); } void S9xBlitPixHiResNTSC16(uint8 *srcPtr, int srcRowBytes, uint8 *dstPtr, int dstRowBytes, int width, int height) { snes_ntsc_blit_hires(ntsc, (SNES_NTSC_IN_T const *)srcPtr, srcRowBytes >> 1, 0, width, height, dstPtr, dstRowBytes); }
agpl-3.0
diqube/diqube
diqube-ui/src/main/java/org/diqube/ui/websocket/result/analysis/AnalysisRefJsonResult.java
1601
/** * diqube: Distributed Query Base. * * Copyright (C) 2015 Bastian Gloeckle * * This file is part of diqube. * * diqube is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.diqube.ui.websocket.result.analysis; import org.diqube.build.mojo.TypeScriptProperty; import org.diqube.ui.websocket.result.JsonResult; import org.diqube.ui.websocket.result.JsonResultDataType; import com.fasterxml.jackson.annotation.JsonProperty; /** * Basic information about an available analysis. * * @author Bastian Gloeckle */ @JsonResultDataType(AnalysisRefJsonResult.TYPE) public class AnalysisRefJsonResult implements JsonResult { @TypeScriptProperty public static final String TYPE = "analysisRef"; @JsonProperty @TypeScriptProperty public String name; @JsonProperty @TypeScriptProperty public String id; // for tests only public AnalysisRefJsonResult() { } public AnalysisRefJsonResult(String name, String id) { this.name = name; this.id = id; } }
agpl-3.0
robmyers/the_colour_of
config/routes.rb
2087
ActionController::Routing::Routes.draw do |map| map.resources :colours map.resources :palettes map.resources :sources map.resources :sources map.resources :categories # The priority is based upon order of creation: first created -> highest priority. # Sample of regular route: # map.connect 'products/:id', :controller => 'catalog', :action => 'view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # map.resources :products # Sample resource route with options: # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } # Sample resource route with sub-resources: # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller # Sample resource route with more complex sub-resources # map.resources :products do |products| # products.resources :comments # products.resources :sales, :collection => { :recent => :get } # end # Sample resource route within a namespace: # map.namespace :admin do |admin| # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) # admin.resources :products # end # You can have the root of your site routed with map.root -- just remember to delete public/index.html. # map.root :controller => "welcome" map.root :controller => "categories" # See how all your routes lay out with "rake routes" # Install the default routes as the lowest priority. # Note: These default routes make all actions in every controller accessible via GET requests. You should # consider removing or commenting them out if you're using named routes and resources. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end
agpl-3.0
gabrys/wikidot
web/files--common/modules/js/managesite/ManageSiteTemplatesModule.js
3903
/* * Wikidot - free wiki collaboration software * Copyright (c) 2008, Wikidot Inc. * * Code licensed under the GNU Affero General Public * License version 3 or later. * * For more information about licensing visit: * http://www.wikidot.org/license */ WIKIDOT.modules.ManagerSiteTemplatesModule = {}; WIKIDOT.modules.ManagerSiteTemplatesModule.vars = { currentCategory: null } WIKIDOT.modules.ManagerSiteTemplatesModule.listeners = { categoryChange: function(e){ // update template info var categoryId = $("sm-template-cats").value; var category = WIKIDOT.modules.ManagerSiteModule.utils.getCategoryById(categoryId); WIKIDOT.modules.ManagerSiteTemplatesModule.vars.currentCategory = category; var value = category['template_id']; if(value == null){ $("sm-templates-list").value = ""; } else { $("sm-templates-list").value=value; } WIKIDOT.modules.ManagerSiteTemplatesModule.utils.updateTemplatePreview(); }, templateChange: function(e){ // save changes to the array var categoryId = $("sm-template-cats").value; var category = WIKIDOT.modules.ManagerSiteModule.utils.getCategoryById(categoryId); if(this.value == ""){ category['template_id'] = null; } else { category['template_id'] = this.value; } WIKIDOT.modules.ManagerSiteTemplatesModule.utils.updateTemplatePreview(); }, cancel: function(e){ WIKIDOT.modules.ManagerSiteModule.utils.loadModule('sm-welcome'); }, save: function(e){ // ok, do it the easy way: serialize categories using the JSON method var categories = WIKIDOT.modules.ManagerSiteModule.vars.categories; var serialized = JSON.stringify(categories); var parms = new Object(); parms['categories'] = serialized; parms['action'] = "ManageSiteAction"; parms['event'] = "saveTemplates"; OZONE.ajax.requestModule("Empty", parms, WIKIDOT.modules.ManagerSiteTemplatesModule.callbacks.save); var w = new OZONE.dialogs.WaitBox(); w.content = "Saving changes..."; w.show(); } } WIKIDOT.modules.ManagerSiteTemplatesModule.callbacks = { cancel: function(response){ OZONE.utils.setInnerHTMLContent("site-manager", response.body); }, save: function(r){ if(!WIKIDOT.utils.handleError(r)) {return;} var w = new OZONE.dialogs.SuccessBox(); w.content ="Changes saved."; w.show(); } } WIKIDOT.modules.ManagerSiteTemplatesModule.utils = { updateTemplatePreview: function(){ // apart from just updating the preview also show/hide extra textarea // for custom licenses var category = WIKIDOT.modules.ManagerSiteTemplatesModule.vars.currentCategory; var templateId = $("sm-templates-list").value; // let us assume that "other" has id = 11. bleeeeh // now enable or disable preview // first hide all previews var div = $("sm-template-preview"); if(templateId==""){ div.style.display = "none"; return; } else { div.style.display = "block"; } var pres = div.getElementsByTagName("div"); for(var i = 0; i< pres.length; i++){ pres[i].style.display = "none"; } // now show the chosen one var pre = $("sm-template-preview-"+templateId); pre.style.display = "block"; return; } } WIKIDOT.modules.ManagerSiteTemplatesModule.init = function(){ YAHOO.util.Event.addListener("sm-template-cats", "change", WIKIDOT.modules.ManagerSiteTemplatesModule.listeners.categoryChange); YAHOO.util.Event.addListener("sm-templates-list", "change", WIKIDOT.modules.ManagerSiteTemplatesModule.listeners.templateChange); YAHOO.util.Event.addListener("sm-templates-cancel", "click", WIKIDOT.modules.ManagerSiteTemplatesModule.listeners.cancel); YAHOO.util.Event.addListener("sm-templates-save", "click", WIKIDOT.modules.ManagerSiteTemplatesModule.listeners.save); // init categories info if($("sm-template-cats")){ WIKIDOT.modules.ManagerSiteTemplatesModule.listeners.categoryChange(null); } } WIKIDOT.modules.ManagerSiteTemplatesModule.init();
agpl-3.0
ttiurani/extendedmind
backend/src/test/scala/org/extendedmind/security/test/TokenSpec.scala
2684
/** * Copyright (c) 2013-2016 Extended Mind Technologies Oy * * This file is part of Extended Mind. * * Extended Mind is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.extendedmind.security.test import org.extendedmind.test.SpraySpecBase import org.extendedmind.security.defaults._ import org.extendedmind.security.AES import java.util.UUID import org.extendedmind.security.Token import org.extendedmind._ import org.extendedmind.Response._ class TokenSpec extends SpraySpecBase{ def configurations = EmptyTestConfiguration describe("Token class"){ it("should encode and decode Tokens"){ val testUUID = UUID.randomUUID() val testToken = Token(testUUID, 1L) val stringToken = Token.encryptToken(testToken) assert(stringToken.length() === 44) // Decrypt and verify val decryptedToken = Token.decryptToken(stringToken) decryptedToken match{ case Right(token) => { assert(token.userUUID.getMostSignificantBits() === testToken.userUUID.getMostSignificantBits()) assert(token.userUUID.getLeastSignificantBits() === testToken.userUUID.getLeastSignificantBits()) assert(token.accessKey === testToken.accessKey) } case Left(e) => fail(e.toString) } } it("should fail to decode invalid token"){ val decryptedToken = Token.decryptToken("ejsoP4lbqEwn2J+gabrKMeWBwQOxYR4QyujwFBNhOR4=") decryptedToken match{ case Right(token) => fail("Should have failed with CRC check") case Left(e) => assert(e(0) === ResponseContent(INVALID_PARAMETER, ERR_BASE_INVALID_CRC, "Token CRC Check failed")) } } it("should fail to decode too short token"){ val decryptedToken = Token.decryptToken("MjsoP4lbqEwn2J+gabrKMeWBwQOxYR4QyujwFBNhOR4") decryptedToken match{ case Right(token) => fail("Should have failed with invalid lenght token") case Left(e) => assert(e(0) === ResponseContent(INVALID_PARAMETER, ERR_BASE_INVALID_TOKEN_LENGTH, "Invalid string token length, should be 44")) } } } }
agpl-3.0
VonIobro/ab-web
app/components/Modal/Container.js
1120
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { DialogTransitionGroup } from './DialogTransitionGroup'; import { ContainerTransitionGroup } from './ContainerTransitionGroup'; const Wrapper = styled.div` position: fixed; top: 0; left: 0; bottom: 0; right: 0; `; const Background = styled.div` position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0.85; transition: opacity 0.3s; background-color: rgb(24, 39, 56); `; const Modals = styled.div` position: absolute; top: 0; left: 0; overflow-y: auto; width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; opacity: 1; transition: opacity 0.3s; `; const ModalContainer = ({ children, ...props }) => ( <ContainerTransitionGroup component={Wrapper} {...props}> <Background /> <DialogTransitionGroup component={Modals}> {children} </DialogTransitionGroup> </ContainerTransitionGroup> ); ModalContainer.propTypes = { children: PropTypes.any, }; export default ModalContainer;
agpl-3.0
mysociety/fixmytransport
lib/patches/babosa_trailing_hyphens_patch.rb
1008
# encoding: utf-8 # Patch to prevent slugs being generated that end with a hyphen module Babosa class Identifier # Normalize the string for use as a URL slug. Note that in this context, # +normalize+ means, strip, remove non-letters/numbers, downcasing, # truncating to 255 bytes and converting whitespace to dashes. # @param Options # @return String def normalize!(options = nil) # Handle deprecated usage if options == true warn "#normalize! now takes a hash of options rather than a boolean" options = default_normalize_options.merge(:to_ascii => true) else options = default_normalize_options.merge(options || {}) end if options[:transliterate] transliterate!(*options[:transliterations]) end to_ascii! if options[:to_ascii] clean! word_chars! clean! downcase! truncate_bytes!(options[:max_length]) clean! with_separators!(options[:separator]) end end end
agpl-3.0
lansingcodelab/www
app/async_fetcher/app/sources/lessons-started.js
1460
import Rx from 'rx' import githubClientFactory from '../apis/github-client-factory' export default (token, query) => { const GithubClient = githubClientFactory(token) return Rx.Observable.create((observer) => { GithubClient.repos.getAll({ // https://developer.github.com/v3/repos/#parameters visibility: 'public', type: 'owner', sort: 'updated', direction: 'desc', per_page: 100, }, (error, repos) => { if (error) throw error repos // Only get the repos we want .filter((repo) => { // A single project if (query.single) { return repo.name === `codelab-${query.single}` // An exclusive list of projects } else if (query.only) { const keys = query.only.split(',') return keys.some((key) => repo.name === `codelab-${key}`) // An exclusive list of projects } else if (query.keys) { const keys = query.keys.split(',') return keys.some((key) => repo.name === `codelab-${key}`) // All Code Lab projects } return repo.name.match(/^codelab-/) }) // Push a formatted object to the observable array .forEach((repo) => { observer.onNext({ name: repo.name, owner: repo.owner.login, status: 'started', }) }) observer.onCompleted() }) }) }
agpl-3.0
disorganizer/brig
vendor/gx/ipfs/QmZHU2gx42NPTYXzw6pJkuX6xCE7bKECp6e8QcPdoLx8sx/protobuf/protoc-gen-go/generator/name_test.go
3979
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2013 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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 Google Inc. 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 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. package generator import ( "testing" "gx/ipfs/QmZHU2gx42NPTYXzw6pJkuX6xCE7bKECp6e8QcPdoLx8sx/protobuf/protoc-gen-go/descriptor" ) func TestCamelCase(t *testing.T) { tests := []struct { in, want string }{ {"one", "One"}, {"one_two", "OneTwo"}, {"_my_field_name_2", "XMyFieldName_2"}, {"Something_Capped", "Something_Capped"}, {"my_Name", "My_Name"}, {"OneTwo", "OneTwo"}, {"_", "X"}, {"_a_", "XA_"}, } for _, tc := range tests { if got := CamelCase(tc.in); got != tc.want { t.Errorf("CamelCase(%q) = %q, want %q", tc.in, got, tc.want) } } } func TestGoPackageOption(t *testing.T) { tests := []struct { in string impPath GoImportPath pkg GoPackageName ok bool }{ {"", "", "", false}, {"foo", "", "foo", true}, {"github.com/golang/bar", "github.com/golang/bar", "bar", true}, {"github.com/golang/bar;baz", "github.com/golang/bar", "baz", true}, } for _, tc := range tests { d := &FileDescriptor{ FileDescriptorProto: &descriptor.FileDescriptorProto{ Options: &descriptor.FileOptions{ GoPackage: &tc.in, }, }, } impPath, pkg, ok := d.goPackageOption() if impPath != tc.impPath || pkg != tc.pkg || ok != tc.ok { t.Errorf("go_package = %q => (%q, %q, %t), want (%q, %q, %t)", tc.in, impPath, pkg, ok, tc.impPath, tc.pkg, tc.ok) } } } func TestUnescape(t *testing.T) { tests := []struct { in string out string }{ // successful cases, including all kinds of escapes {"", ""}, {"foo bar baz frob nitz", "foo bar baz frob nitz"}, {`\000\001\002\003\004\005\006\007`, string([]byte{0, 1, 2, 3, 4, 5, 6, 7})}, {`\a\b\f\n\r\t\v\\\?\'\"`, string([]byte{'\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '?', '\'', '"'})}, {`\x10\x20\x30\x40\x50\x60\x70\x80`, string([]byte{16, 32, 48, 64, 80, 96, 112, 128})}, // variable length octal escapes {`\0\018\222\377\3\04\005\6\07`, string([]byte{0, 1, '8', 0222, 255, 3, 4, 5, 6, 7})}, // malformed escape sequences left as is {"foo \\g bar", "foo \\g bar"}, {"foo \\xg0 bar", "foo \\xg0 bar"}, {"\\", "\\"}, {"\\x", "\\x"}, {"\\xf", "\\xf"}, {"\\777", "\\777"}, // overflows byte } for _, tc := range tests { s := unescape(tc.in) if s != tc.out { t.Errorf("doUnescape(%q) = %q; should have been %q", tc.in, s, tc.out) } } }
agpl-3.0
nccgroup/pip3line
defaultplugins/baseplugins/fixprotocol.cpp
3746
/** Released as open source by NCC Group Plc - http://www.nccgroup.com/ Developed by Gabriel Caudrelier, gabriel dot caudrelier at nccgroup dot com https://github.com/nccgroup/pip3line Released under AGPL see LICENSE for more information **/ #include "fixprotocol.h" #include <QXmlQuery> #include <QXmlResultItems> #include <QTextStream> #include <QFile> const QString FixProtocol::id = "Fix Protocol parser"; FixProtocol::FixProtocol() { QTextStream cout(stdout); QFile referenceFile; referenceFile.setFileName(":/definitions/FIX44.xml"); if (!referenceFile.open(QIODevice::ReadOnly)) { cout << tr("Error while opening the reference file:\n %1").arg(referenceFile.errorString()) << endl; } query.setFocus(&referenceFile); referenceFile.close(); } FixProtocol::~FixProtocol() { } QString FixProtocol::name() const { return id; } QString FixProtocol::description() const { return tr("Parse/unpack a FIX 4.4 stream"); } void FixProtocol::transform(const QByteArray &input, QByteArray &output) { QList<QByteArray> fields = input.split(0x01); for (int i = 0; i < fields.size(); i++) { output.append(translateField(fields.at(i))); if (!output.isEmpty()) output.append('\n'); } } bool FixProtocol::isTwoWays() { return false; } QString FixProtocol::help() const { QString help; help.append("<p>Financial Information eXchange (FIX) protocol parser</p><p>This transformation will parse a raw (binary) FIX transaction, also resolving fields' name and value when possible</p><p>Currently only supporting FIX 4.4.<br>Test data are needed to enable support for other versions.</p>"); return help; } QByteArray FixProtocol::translateField(QByteArray val) { QByteArray ret; if (val.isEmpty()) return ret; bool ok = false; int fieldNum = 0; QList<QByteArray> list = val.split('='); if (list.size() != 2) { emit error(tr("Invalid pair:").append(val),id); return ret; } fieldNum = list.at(0).toInt(&ok); if (!ok) { emit error(tr("Error while parsing the field number value: %1").arg(QString(list.at(0))),id); return ret; } query.bindVariable("field",QVariant(fieldNum)); query.bindVariable("val",QVariant(QString(list.at(1)))); query.setQuery("/fix/fields/field[@number=$field]/@name/string()"); if (!query.isValid()) { emit error(tr("Invalid XPATH query"),id); return ret; } QStringList qout; if (!query.evaluateTo(&qout)) { emit error(tr("Error while evaluating xmlQuery with %1").arg(QString(val)),id); } if (qout.size() < 1) { emit error(tr("Unknown field number:").append(fieldNum),id); ret.append(val); return ret; } else if (qout.size() > 1) { emit warning(tr("Strange, found multiple value for field number %1 (taking the first one)").arg(fieldNum),id); } ret.append(qout.at(0)).append('(').append(list.at(0)).append(')').append(" = "); query.setQuery("/fix/fields/field[@number=$field]/value[@enum=$val]/@description/string()"); if (!query.isValid()) { emit error(tr("Invalid XPATH query"),id); return ret.append(list.at(1)); } qout.clear(); if (!query.evaluateTo(&qout)) { emit error(tr("Error while evaluating xmlQuery (2) with %1").arg(QString(val)),id); } if (qout.size() < 1) { ret.append(list.at(1)); return ret; } else if (qout.size() > 1) { emit warning(tr("Strange, found multiple value for field value %1 (taking the first one)").arg(QString(list.at(1))),id); } ret.append(qout.at(0)).append('(').append(list.at(1)).append(')'); return ret; }
agpl-3.0
jpretori/SoaringCoach
src/test/java/soaringcoach/CircleTestFacade.java
2054
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * SoaringCoach is a tool for analysing IGC files produced by modern FAI * flight recorder devices, and providing the pilot with useful feedback * on how effectively they are flying. * Copyright (C) 2017 Johan Pretorius * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * The author can be contacted via email at [email protected], or * by paper mail by addressing as follows: * Johan Pretorius * PO Box 990 * Durbanville * Cape Town * 7551 * South Africa * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package soaringcoach; import java.util.Date; import soaringcoach.FlightAnalyser.FlightMode; import soaringcoach.analysis.GNSSPoint; public class CircleTestFacade extends Circle { public CircleTestFacade( Date timestamp, long duration, double circle_start_latitude, double circle_start_longitude, double circle_drift_bearing) { super(timestamp, duration, circle_start_latitude, circle_start_longitude); } public CircleTestFacade(GNSSPoint p1, GNSSPoint p2, FlightMode mode) { super(p1, p2, mode); } public CircleTestFacade(GNSSPoint p1, GNSSPoint p2, CircleTestFacade c) { super(p1, p2, c); } public boolean detectCircleCompleted(GNSSPoint p) { return super.detectCircleCompleted(p); } }
agpl-3.0
cinquin/mutinack
src/uk/org/cinquin/mutinack/misc_util/SettableInteger.java
1773
/** * Mutinack mutation detection program. * Copyright (C) 2014-2016 Olivier Cinquin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, version 3. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.org.cinquin.mutinack.misc_util; import java.io.Serializable; public class SettableInteger implements Serializable { private static final long serialVersionUID = 8580008588332408546L; private int value; private boolean initialized; public SettableInteger(int value) { initialized = true; this.value = value; } public SettableInteger() { initialized = false; } private void checkInitialized() { if (!initialized) { throw new IllegalStateException("Not initialized"); } } public final int get() { checkInitialized(); return value; } public final void set(int value) { initialized = true; this.value = value; } public final void set(SettableInteger i) { initialized = true; set(i.value); } public final int incrementAndGet() { checkInitialized(); return ++value; } public final int addAndGet(int i) { checkInitialized(); value += i; return value; } public int getAndIncrement() { checkInitialized(); return value++; } @Override public String toString() { return Integer.toString(value); } }
agpl-3.0
henrik-muehe/ira
js/block.js
1632
/* IRA - Interactive Relational Algebra Tool Copyright (C) 2010-2012 Henrik Mühe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ function Block() { this.kind = Block; this.children = []; this.getChildren = function() { return this.children; } this.setChildren = function(c) { this.children = c; } this.copy = function() { throw "Kann abstrakte Klasse Block nicht kopieren."; } this.resetBlockIds = function() { if (!this.blockId) { this.blockId = ++blockid; this.getChildren().each(function(c) { c.resetBlockIds(); }); } } this.findChild = function(id) { if (this.blockId == id) { return this; } else { var result = null; this.getChildren().each(function(c) { var f = c.findChild(id); if (f != null) { result = f; } }); return result; } } }
agpl-3.0
quikkian-ua-devops/will-financials
kfs-ar/src/main/java/org/kuali/kfs/module/ar/document/validation/event/CashControlDetailEventBase.java
3198
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.ar.document.validation.event; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.kuali.kfs.krad.document.Document; import org.kuali.kfs.krad.rules.rule.event.KualiDocumentEventBase; import org.kuali.kfs.krad.util.ObjectUtils; import org.kuali.kfs.module.ar.businessobject.CashControlDetail; public abstract class CashControlDetailEventBase extends KualiDocumentEventBase implements CashControlDetailEvent { private static final Logger LOG = Logger.getLogger(CashControlDetailEventBase.class); private final CashControlDetail cashControlDetail; /** * Initializes fields common to all subclasses * * @param description * @param errorPathPrefix * @param document * @param check */ public CashControlDetailEventBase(String description, String errorPathPrefix, Document document, CashControlDetail cashControlDetail) { super(description, errorPathPrefix, document); // by doing a deep copy, we are ensuring that the business rule class can't update // the original object by reference this.cashControlDetail = (CashControlDetail) ObjectUtils.deepCopy(cashControlDetail); logEvent(); } /** * @see org.kuali.kfs.module.ar.document.validation.event.CustomerInvoiceDetailEvent#getCustomerInvoiceDetail() */ public CashControlDetail getCashControlDetail() { return cashControlDetail; } /** * @see org.kuali.rice.krad.rule.event.KualiDocumentEvent#validate() */ public void validate() { super.validate(); if (getCashControlDetail() == null) { throw new IllegalArgumentException("invalid (null) cash control detail"); } } /** * Logs the event type and some information about the associated accountingLine */ private void logEvent() { StringBuffer logMessage = new StringBuffer(StringUtils.substringAfterLast(this.getClass().getName(), ".")); logMessage.append(" with "); // vary logging detail as needed if (cashControlDetail == null) { logMessage.append("null cashControlDetail"); } else { logMessage.append(" cashControlDetail# "); logMessage.append(cashControlDetail.getDocumentNumber()); } LOG.debug(logMessage); } }
agpl-3.0
thinkdry/blank-application
spec/models/users_containers_spec.rb
1896
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe UsersContainer do fixtures :users_containers def users_containers UsersContainer.new end def users_containers_attributes { :containerable_id => 1, :containerable_type => 'Workspace', :user_id => 21, :role_id => 14 } end before(:each) do @users_containers = users_containers end it "should be valid" do @users_containers.attributes = users_containers_attributes @users_containers.should be_valid end it "should require user, container, role" do @users_containers.attributes = users_containers_attributes.except(:user_id, :containerable_id, :containerable_type, :role_id) @users_containers.should have(1).error_on(:user_id) @users_containers.should have(1).error_on(:containerable_id) @users_containers.should have(1).error_on(:containerable_type) @users_containers.should have(1).error_on(:role_id) end it "should validate uniqueness of user for given container" do @users_containers.attributes = users_containers_attributes @users_containers.user_id = 1 @users_containers.should have(1).error_on(:user_id) end it "should belong to user" do UsersContainer.reflect_on_association(:user).to_hash.should == { :class_name => 'User', :options => {}, :macro => :belongs_to } end it "should belong to containerable and be polymorphic" do UsersContainer.reflect_on_association(:containerable).to_hash.should == { :class_name => 'Containerable', :options => {:foreign_type => "containerable_type", :polymorphic=>true }, :macro => :belongs_to } end it "should belong to role" do UsersContainer.reflect_on_association(:role).to_hash.should == { :class_name => 'Role', :options => {}, :macro => :belongs_to } end end
agpl-3.0
Bernie-2016/ground-control
src/frontend/components/forms/GCPhoneField.js
677
import React from 'react'; import {TextField} from 'material-ui'; import {BernieText} from '../styles/bernie-css'; import GCFormField from './GCFormField'; import phoneFormatter from 'phone-formatter'; export default class GCPhoneField extends GCFormField { render() { return <TextField {...this.props} value={this.props.value ? phoneFormatter.format(this.props.value, '(NNN) NNN-NNNN') : ''} floatingLabelText={this.floatingLabelText()} errorStyle={BernieText.inputError} hintText={this.props.label} onChange={(event) => { let val = event.target.value.replace(/\D/g,'') this.props.onChange(val) }} /> } }
agpl-3.0
arkivverket/arkade5
src/Arkivverket.Arkade.Core.Tests/Testing/Noark5/N5_35_NumberOfCasePartsTests.cs
10449
using System.Collections.Generic; using System.Linq; using Arkivverket.Arkade.Core.Base; using Arkivverket.Arkade.Core.Testing; using Arkivverket.Arkade.Core.Testing.Noark5; using FluentAssertions; using Xunit; namespace Arkivverket.Arkade.Core.Tests.Testing.Noark5 { public class N5_35_NumberOfCasePartsTests : LanguageDependentTest { const string TestDataDirectory = "TestData\\Noark5\\Small"; const string TestDataDirectoryV5_5 = "TestData\\Noark5\\Version5_5"; [Fact] public void NumberOfCasePartsIsOne() { Archive testArchive = TestUtil.CreateArchiveExtraction(TestDataDirectory); XmlElementHelper helper = new XmlElementHelper() .Add("arkiv", new XmlElementHelper() .Add("arkivdel", new XmlElementHelper() .Add("systemID", "archivePartSystemId_1") .Add("tittel", "archivePartTitle_1") .Add("klassifikasjonssystem", new XmlElementHelper() .Add("klasse", new XmlElementHelper() .Add("mappe", new XmlElementHelper() .Add("registrering", new XmlElementHelper() .Add("sakspart", new XmlElementHelper() .Add("sakspartID", "Sakspart1")))))))); TestRun testRun = helper.RunEventsOnTest(new N5_35_NumberOfCaseParts(testArchive)); testRun.TestResults.TestsResults.First().Message.Should().Be("Totalt: 1"); testRun.TestResults.GetNumberOfResults().Should().Be(1); } [Fact] public void NumberOfCasePartsIsOnePerArchivePart() { Archive testArchive = TestUtil.CreateArchiveExtraction(TestDataDirectory); XmlElementHelper helper = new XmlElementHelper() .Add("arkiv", new XmlElementHelper() .Add("arkivdel", new XmlElementHelper() .Add("systemID", "someSystemId_1") .Add("tittel", "someTitle_1") .Add("klassifikasjonssystem", new XmlElementHelper() .Add("klasse", new XmlElementHelper() .Add("mappe", new XmlElementHelper() .Add("registrering", new XmlElementHelper() .Add("sakspart", new XmlElementHelper() .Add("sakspartID", "Sakspart1"))))))) .Add("arkivdel", new XmlElementHelper() .Add("systemID", "someSystemId_2") .Add("tittel", "someTitle_2") .Add("klassifikasjonssystem", new XmlElementHelper() .Add("klasse", new XmlElementHelper() .Add("mappe", new XmlElementHelper() .Add("registrering", new XmlElementHelper() .Add("systemID", "journpost57d6608569ed33.70652483")))))) .Add("arkivdel", new XmlElementHelper() .Add("systemID", "someSystemId_3") .Add("tittel", "someTitle_3") .Add("klassifikasjonssystem", new XmlElementHelper() .Add("klasse", new XmlElementHelper() .Add("mappe", new XmlElementHelper() .Add("registrering", new XmlElementHelper() .Add("sakspart", new XmlElementHelper() .Add("sakspartID", "Sakspart1"))))))) ); TestRun testRun = helper.RunEventsOnTest(new N5_35_NumberOfCaseParts(testArchive)); List<TestResult> testResults = testRun.TestResults.TestsResults; testResults[0].Message.Should().Be("Totalt: 2"); testResults[1].Message.Should().Be("Arkivdel (systemID, tittel): someSystemId_1, someTitle_1: 1"); testResults[2].Message.Should().Be("Arkivdel (systemID, tittel): someSystemId_2, someTitle_2: 0"); testResults[3].Message.Should().Be("Arkivdel (systemID, tittel): someSystemId_3, someTitle_3: 1"); testRun.TestResults.GetNumberOfResults().Should().Be(4); } [Fact] public void NumberOfCasePartsIsZero() { Archive testArchive = TestUtil.CreateArchiveExtraction(TestDataDirectory); XmlElementHelper helper = new XmlElementHelper() .Add("arkiv", new XmlElementHelper() .Add("arkivdel", new XmlElementHelper() .Add("systemID", "archivePartSystemId_1") .Add("tittel", "archivePartTitle_1") .Add("klassifikasjonssystem", new XmlElementHelper() .Add("klasse", new XmlElementHelper() .Add("mappe", new XmlElementHelper() .Add("registrering", new XmlElementHelper())))))); TestRun testRun = helper.RunEventsOnTest(new N5_35_NumberOfCaseParts(testArchive)); testRun.TestResults.TestsResults.First().Message.Should().Be("Totalt: 0"); testRun.TestResults.GetNumberOfResults().Should().Be(1); } [Fact] public void NumberOfCasePartsIsOneNoark5_5() { Archive testArchive = TestUtil.CreateArchiveExtractionV5_5(TestDataDirectoryV5_5); XmlElementHelper helper = new XmlElementHelper() .Add("arkiv", new XmlElementHelper() .Add("arkivdel", new XmlElementHelper() .Add("systemID", "someSystemId_1") .Add("tittel", "someTitle_1") .Add("klassifikasjonssystem", new XmlElementHelper() .Add("klasse", new XmlElementHelper() .Add("mappe", new XmlElementHelper() .Add("registrering", new XmlElementHelper() .Add("part", new XmlElementHelper() .Add("sakspartID", "Sakspart1")))))))); TestRun testRun = helper.RunEventsOnTest(new N5_35_NumberOfCaseParts(testArchive)); testRun.TestResults.TestsResults[0].Message.Should().Be("Totalt: 1"); testRun.TestResults.GetNumberOfResults().Should().Be(1); } [Fact] public void NumberOfCasePartsIsOnePerArchivePartNoark5_5() { Archive testArchive = TestUtil.CreateArchiveExtractionV5_5(TestDataDirectoryV5_5); XmlElementHelper helper = new XmlElementHelper() .Add("arkiv", new XmlElementHelper() .Add("arkivdel", new XmlElementHelper() .Add("systemID", "someSystemId_1") .Add("tittel", "someTitle_1") .Add("klassifikasjonssystem", new XmlElementHelper() .Add("klasse", new XmlElementHelper() .Add("mappe", new XmlElementHelper() .Add("registrering", new XmlElementHelper() .Add("part", new XmlElementHelper() .Add("sakspartID", "Sakspart1"))))))) .Add("arkivdel", new XmlElementHelper() .Add("systemID", "someSystemId_2") .Add("tittel", "someTitle_2") .Add("klassifikasjonssystem", new XmlElementHelper() .Add("klasse", new XmlElementHelper() .Add("mappe", new XmlElementHelper() .Add("registrering", new XmlElementHelper() .Add("systemID", "journpost57d6608569ed33.70652483")))))) .Add("arkivdel", new XmlElementHelper() .Add("systemID", "someSystemId_3") .Add("tittel", "someTitle_3") .Add("klassifikasjonssystem", new XmlElementHelper() .Add("klasse", new XmlElementHelper() .Add("mappe", new XmlElementHelper() .Add("registrering", new XmlElementHelper() .Add("part", new XmlElementHelper() .Add("sakspartID", "Sakspart1"))))))) ); TestRun testRun = helper.RunEventsOnTest(new N5_35_NumberOfCaseParts(testArchive)); List<TestResult> testResults = testRun.TestResults.TestsResults; testResults[0].Message.Should().Be("Totalt: 2"); testResults[1].Message.Should().Be("Arkivdel (systemID, tittel): someSystemId_1, someTitle_1: 1"); testResults[2].Message.Should().Be("Arkivdel (systemID, tittel): someSystemId_2, someTitle_2: 0"); testResults[3].Message.Should().Be("Arkivdel (systemID, tittel): someSystemId_3, someTitle_3: 1"); testRun.TestResults.GetNumberOfResults().Should().Be(4); } [Fact] public void NumberOfCasePartsIsZeroNoark5_5() { Archive testArchive = TestUtil.CreateArchiveExtractionV5_5(TestDataDirectoryV5_5); XmlElementHelper helper = new XmlElementHelper() .Add("arkiv", new XmlElementHelper() .Add("arkivdel", new XmlElementHelper() .Add("systemID", "someSystemId_1") .Add("tittel", "someTitle_1") .Add("klassifikasjonssystem", new XmlElementHelper() .Add("klasse", new XmlElementHelper() .Add("mappe", new XmlElementHelper() .Add("registrering", new XmlElementHelper())))))); TestRun testRun = helper.RunEventsOnTest(new N5_35_NumberOfCaseParts(testArchive)); testRun.TestResults.TestsResults[0].Message.Should().Be("Totalt: 0"); testRun.TestResults.GetNumberOfResults().Should().Be(1); } } }
agpl-3.0
jhuymaier/zurmo
app/protected/modules/tasks/data/TasksDemoDataMaker.php
5610
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2013 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address [email protected]. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2013. All rights reserved". ********************************************************************************/ /** * Class that builds demo tasks. */ class TasksDemoDataMaker extends DemoDataMaker { protected $ratioToLoad = 3; /** * @return array */ public static function getDependencies() { return array('opportunities'); } /** * @param DemoDataHelper $demoDataHelper */ public function makeAll(& $demoDataHelper) { assert('$demoDataHelper instanceof DemoDataHelper'); assert('$demoDataHelper->isSetRange("User")'); assert('$demoDataHelper->isSetRange("Opportunity")'); $tasks = array(); for ($i = 0; $i < $this->resolveQuantityToLoad(); $i++) { $task = new Task(); $opportunity = $demoDataHelper->getRandomByModelName('Opportunity'); $task->owner = $opportunity->owner; $task->completed = false; if ($i%2 == 0) { $task->status = Task::STATUS_NEW; } elseif ($i%3 == 0) { $task->status = Task::STATUS_IN_PROGRESS; } elseif ($i%5 == 0) { $task->status = Task::STATUS_COMPLETED; } $task->activityItems->add($opportunity); $task->activityItems->add($opportunity->contacts[0]); $task->activityItems->add($opportunity->account); //Notification subscriber $notificationSubscriber = new NotificationSubscriber(); $notificationSubscriber->person = $demoDataHelper->getRandomByModelName('User'); $notificationSubscriber->hasReadLatest = false; $task->notificationSubscribers->add($notificationSubscriber); $this->populateModel($task); $saved = $task->save(); assert('$saved'); $tasks[] = $task->id; } $demoDataHelper->setRangeByModelName('Task', $tasks[0], $tasks[count($tasks)-1]); } /** * Populates model * @param Task $model */ public function populateModel(& $model) { assert('$model instanceof Task'); parent::populateModel($model); $taskRandomData = ZurmoRandomDataUtil:: getRandomDataByModuleAndModelClassNames('TasksModule', 'Task'); $name = RandomDataUtil::getRandomValueFromArray($taskRandomData['names']); if (intval($model->status) == Task::STATUS_COMPLETED) { $dueTimeStamp = time() - (mt_rand(1, 50) * 60 * 60 * 24); $completedDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime( $dueTimeStamp + (mt_rand(1, 24) * 15)); $model->completedDateTime = $completedDateTime; $model->completed = true; } else { $dueTimeStamp = time() + (mt_rand(1, 200) * 60 * 60 * 24); } $dueDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime($dueTimeStamp); $model->name = $name; $model->dueDateTime = $dueDateTime; } } ?>
agpl-3.0
wapolinar/SOGoICSTool
sogoTool/src/main/java/de/apolinarski/tool/sogo/Utils.java
1529
package de.apolinarski.tool.sogo; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class Utils { private static final String FIRST_STRING_PART="http://127.0.0.1:20000/SOGo/so/"; private static final String SECOND_STRING_PART="/Calendar/"; private static final String LAST_STRING_PART="/reload"; private static final String HTTP_HEADER_FIELD="x-webobjects-remote-user"; public static void callCurl(SOGoUser user) { StringBuilder sb=new StringBuilder(); sb.append(FIRST_STRING_PART); sb.append(user.getName()); sb.append(SECOND_STRING_PART); final String urlFirstPart=sb.toString(); user.getCalendarIds().parallelStream() .forEach((calendarId) -> { StringBuilder lambdaSB=new StringBuilder(urlFirstPart.length()+LAST_STRING_PART.length()+calendarId.length()); lambdaSB.append(urlFirstPart); lambdaSB.append(calendarId); lambdaSB.append(LAST_STRING_PART); try { URL url=new URL(lambdaSB.toString()); HttpURLConnection connection=(HttpURLConnection) url.openConnection(); connection.setRequestProperty(HTTP_HEADER_FIELD, user.getName()); connection.connect(); if(connection.getResponseCode()!=200) { System.err.println("Could not reload calendar for user: "+user.getName()+" Error: "+connection.getResponseMessage()); } } catch(IOException e) { System.err.println("Could not establish connection to SOGo for user: "+user.getName()+" Error: "+e.getMessage()); } }); } }
agpl-3.0
carbn/huonot-uutiset
huonotuutiset/templatetags/extras.py
463
from django import template register = template.Library() # from http://stackoverflow.com/questions/19268727/django-how-to-get-the-name-of-the-template-being-rendered @register.simple_tag def active_page(request, view_name): from django.core.urlresolvers import resolve, Resolver404 if not request: return "" try: return "active" if resolve(request.path_info).url_name == view_name else "" except Resolver404: return ""
agpl-3.0
avcsa/openepg
client/src/main.js
62
var App = require('./app'); var epg = new App(); epg.start();
agpl-3.0
colares/touke-flow
Packages/Framework/TYPO3.Fluid/Classes/TYPO3/Fluid/Core/Parser/SyntaxTree/ViewHelperNode.php
4900
<?php namespace TYPO3\Fluid\Core\Parser\SyntaxTree; /* * * This script belongs to the TYPO3 Flow package "Fluid". * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ use TYPO3\Flow\Annotations as Flow; use TYPO3\Flow\Object\DependencyInjection\DependencyProxy; /** * Node which will call a ViewHelper associated with this node. * */ class ViewHelperNode extends \TYPO3\Fluid\Core\Parser\SyntaxTree\AbstractNode { /** * Class name of view helper * @var string */ protected $viewHelperClassName; /** * Arguments of view helper - References to RootNodes. * @var array */ protected $arguments = array(); /** * The ViewHelper associated with this node * @var \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper */ protected $uninitializedViewHelper = NULL; /** * A mapping RenderingContext -> ViewHelper to only re-initialize ViewHelpers * when a context change occurs. * @var \SplObjectStorage */ protected $viewHelpersByContext = NULL; /** * Constructor. * * @param \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper $viewHelper The view helper * @param array $arguments Arguments of view helper - each value is a RootNode. */ public function __construct(\TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper $viewHelper, array $arguments) { $this->uninitializedViewHelper = $viewHelper; $this->viewHelpersByContext = new \SplObjectStorage(); $this->arguments = $arguments; $this->viewHelperClassName = ($this->uninitializedViewHelper instanceof DependencyProxy) ? $this->uninitializedViewHelper->_getClassName() : get_class($this->uninitializedViewHelper); } /** * Returns the attached (but still uninitialized) ViewHelper for this ViewHelperNode. * We need this method because sometimes Interceptors need to ask some information from the ViewHelper. * * @return \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper the attached ViewHelper, if it is initialized */ public function getUninitializedViewHelper() { return $this->uninitializedViewHelper; } /** * Get class name of view helper * * @return string Class Name of associated view helper */ public function getViewHelperClassName() { return $this->viewHelperClassName; } /** * INTERNAL - only needed for compiling templates * * @return array * @Flow\Internal */ public function getArguments() { return $this->arguments; } /** * Call the view helper associated with this object. * * First, it evaluates the arguments of the view helper. * * If the view helper implements \TYPO3\Fluid\Core\ViewHelper\Facets\ChildNodeAccessInterface, * it calls setChildNodes(array childNodes) on the view helper. * * Afterwards, checks that the view helper did not leave a variable lying around. * * @param \TYPO3\Fluid\Core\Rendering\RenderingContextInterface $renderingContext * @return object evaluated node after the view helper has been called. */ public function evaluate(\TYPO3\Fluid\Core\Rendering\RenderingContextInterface $renderingContext) { if ($this->viewHelpersByContext->contains($renderingContext)) { $viewHelper = $this->viewHelpersByContext[$renderingContext]; $viewHelper->resetState(); } else { $viewHelper = clone $this->uninitializedViewHelper; $this->viewHelpersByContext->attach($renderingContext, $viewHelper); } $evaluatedArguments = array(); if (count($viewHelper->prepareArguments())) { foreach ($viewHelper->prepareArguments() as $argumentName => $argumentDefinition) { if (isset($this->arguments[$argumentName])) { $argumentValue = $this->arguments[$argumentName]; $evaluatedArguments[$argumentName] = $argumentValue->evaluate($renderingContext); } else { $evaluatedArguments[$argumentName] = $argumentDefinition->getDefaultValue(); } } } $viewHelper->setArguments($evaluatedArguments); $viewHelper->setViewHelperNode($this); $viewHelper->setRenderingContext($renderingContext); if ($viewHelper instanceof \TYPO3\Fluid\Core\ViewHelper\Facets\ChildNodeAccessInterface) { $viewHelper->setChildNodes($this->childNodes); } $output = $viewHelper->initializeArgumentsAndRender(); return $output; } /** * Clean up for serializing. * * @return array */ public function __sleep() { return array('viewHelperClassName', 'arguments', 'childNodes'); } } ?>
agpl-3.0
ralfbecher/neo4j-extensions
neo4j-extensions-java/src/main/java/org/neo4j/extensions/java/plugins/GetAll.java
1798
package org.neo4j.extensions.java.plugins; import java.util.ArrayList; import java.util.List; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; import org.neo4j.server.plugins.Description; import org.neo4j.server.plugins.Name; import org.neo4j.server.plugins.PluginTarget; import org.neo4j.server.plugins.ServerPlugin; import org.neo4j.server.plugins.Source; import org.neo4j.tooling.GlobalGraphOperations; /** * @author bradnussbaum * @since 2014-05-25 */ @Description("An extension to the Neo4j Server for getting all nodes or relationships") public class GetAll extends ServerPlugin { @Name("get_all_nodes") @Description("Get all nodes from the Neo4j graph database") @PluginTarget(GraphDatabaseService.class) public Iterable<Node> getAllNodes( @Source GraphDatabaseService graphDb ) { ArrayList<Node> nodes = new ArrayList<>(); try ( Transaction tx = graphDb.beginTx() ) { for ( Node node : GlobalGraphOperations.at( graphDb ).getAllNodes() ) { nodes.add( node ); } tx.success(); } return nodes; } @Description("Get all relationships from the Neo4j graph database") @PluginTarget(GraphDatabaseService.class) public Iterable<Relationship> getAllRelationships( @Source GraphDatabaseService graphDb ) { List<Relationship> rels = new ArrayList<>(); try ( Transaction tx = graphDb.beginTx() ) { for ( Relationship rel : GlobalGraphOperations.at( graphDb ).getAllRelationships() ) { rels.add( rel ); } tx.success(); } return rels; } }
agpl-3.0
rajeshrhino/uk.co.vedaconsulting.membershipchurnchart
api/v3/Membershipchurnchart.php
536
<?php /** * Membershipchurnchart prepare churn table API * * @param array $params * @return array API result descriptor * @see civicrm_api3_create_success * @see civicrm_api3_create_error * @throws API_Exception */ function civicrm_api3_membershipchurnchart_preparechurntable($params) { // Prepare renewal dates CRM_Membershipchurnchart_Utils::prepareChurnTable(); $returnValues = array(); // Return success return civicrm_api3_create_success($returnValues, $params, 'Membershipchurnchart', 'Preparechurntable'); }
agpl-3.0
JanMarvin/rstudio
src/cpp/core/http/Response.cpp
24639
/* * Response.cpp * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/http/Response.hpp> #include <algorithm> #include <gsl/gsl> #include <boost/regex.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/trim.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/asio/buffer.hpp> #include <core/http/URL.hpp> #include <core/http/Util.hpp> #include <core/http/Cookie.hpp> #include <core/Hash.hpp> #include <core/RegexUtils.hpp> #include <core/FileSerializer.hpp> #ifndef _WIN32 #include "zlib.h" #endif namespace rstudio { namespace core { namespace http { namespace { #define kGzipWindow 31 #define kDeflateWindow 15 #define kDefaultMemoryUsage 8 std::shared_ptr<StreamBuffer> makePaddingBuffer(size_t numPadding) { // create a padding buffer char* buffer = new char[numPadding]; std::fill_n(buffer, numPadding, '0'); return std::make_shared<StreamBuffer>(buffer, numPadding); } class FileStreamResponse : public StreamResponse { friend class ZlibCompressionStreamResponse; public: FileStreamResponse(const FilePath& file, std::streamsize bufferSize, bool padding) : file_(file), bufferSize_(bufferSize), padding_(padding), totalRead_(0) { } virtual ~FileStreamResponse() { } Error initialize() { return file_.openForRead(fileStream_); } std::shared_ptr<StreamBuffer> nextBuffer() { // create buffer to hold the file data char* buffer = new char[bufferSize_]; // read next chunk of data fileStream_->read(buffer, bufferSize_); uint64_t read = fileStream_->gcount(); totalRead_ += read; fileStream_->seekg(totalRead_); if (read == 0) { delete [] buffer; // incomplete read, likely end-of-file reached if ((totalRead_ < 1024) && padding_) { // no data read and we need to pad return makePaddingBuffer(1024 - totalRead_); } else { // no data read and no need for pad - return empty buffer return std::shared_ptr<StreamBuffer>(); } } // return buffer representing the data with how much we actually read return std::make_shared<StreamBuffer>(buffer, read); } private: FilePath file_; std::shared_ptr<std::istream> fileStream_; std::streamsize bufferSize_; bool padding_; uint64_t totalRead_; }; enum class CompressionType { Gzip, Deflate }; #ifndef _WIN32 // we currently do not support direct usage of zlib on windows class ZlibCompressionStreamResponse : public StreamResponse { public: ZlibCompressionStreamResponse(const boost::shared_ptr<FileStreamResponse>& fileStream, std::streamsize bufferSize, CompressionType compressionType) : fileStream_(fileStream), bufferSize_(bufferSize), compressionType_(compressionType), finished_(false) { } virtual ~ZlibCompressionStreamResponse() { } static void freeStream(z_stream* pStream) { (void)deflateEnd(pStream); delete pStream; } Error initialize() { Error error = fileStream_->initialize(); if (error) return error; // initialize zlib stream zStream_.reset(new z_stream(), ZlibCompressionStreamResponse::freeStream); zStream_->zalloc = Z_NULL; zStream_->zfree = Z_NULL; zStream_->opaque = Z_NULL; int res = deflateInit2(zStream_.get(), Z_BEST_COMPRESSION, Z_DEFLATED, (compressionType_ == CompressionType::Gzip) ? kGzipWindow : kDeflateWindow, kDefaultMemoryUsage, Z_DEFAULT_STRATEGY); if (res != Z_OK) return systemError(res, "ZLib initialization error", ERROR_LOCATION); return Success(); } std::shared_ptr<StreamBuffer> nextBuffer() { if (finished_) return std::shared_ptr<StreamBuffer>(); uint64_t written = 0; int flush = Z_NO_FLUSH; int res = 0; // create a new output buffer to hold output generated by zlib char* buffer = new char[bufferSize_]; zStream_->avail_out = bufferSize_; zStream_->next_out = reinterpret_cast<unsigned char*>(buffer); do { // check to see if the last file buffer was fully consumed by zlib // if not, we need to keep using it std::shared_ptr<StreamBuffer> fileBuffer; if (fileBuffer_) { fileBuffer = fileBuffer_; fileBuffer_.reset(); // no change to avail_in or next_in as this is persisted by zlib // when reusing the input buffer } else { // the buffer was fully consumed last time, so get the next // bytes from the file fileBuffer = fileStream_->nextBuffer(); if (!fileBuffer) { // no more file bytes - signal to zlib that we are done processing zStream_->avail_in = 0; flush = Z_FINISH; } else { // tell zlib about the new input buffer zStream_->avail_in = fileBuffer->size; zStream_->next_in = reinterpret_cast<unsigned char*>(fileBuffer->data); } } // compress the file bytes res = deflate(zStream_.get(), flush); if (res == Z_STREAM_ERROR) { LOG_ERROR_MESSAGE("Could not compress file " + fileStream_->file_.getAbsolutePath() + " - zlib stream error"); delete [] buffer; return std::shared_ptr<StreamBuffer>(); } written = bufferSize_ - zStream_->avail_out; if (zStream_->avail_in != 0) { // the input data has not been fully processed // process it on the next call to this method fileBuffer_ = fileBuffer; } // if no data written, zlib isn't ready to give us data // keep processing new input data until zlib gives us some output } while (written == 0); if (res == Z_STREAM_END) finished_ = true; return std::make_shared<StreamBuffer>(buffer, written); } private: boost::shared_ptr<FileStreamResponse> fileStream_; std::streamsize bufferSize_; CompressionType compressionType_; boost::shared_ptr<struct z_stream_s> zStream_; std::shared_ptr<StreamBuffer> fileBuffer_; bool finished_; }; #endif } // anonymous namespace Response::Response() : Message(), statusCode_(status::Ok) { } const std::string& Response::statusMessage() const { ensureStatusMessage(); return statusMessage_; } void Response::setStatusMessage(const std::string& statusMessage) { statusMessage_ = statusMessage; } std::string Response::contentEncoding() const { return headerValue("Content-Encoding"); } void Response::setContentEncoding(const std::string& encoding) { setHeader("Content-Encoding", encoding); } void Response::setCacheWithRevalidationHeaders() { setHeader("Expires", http::util::httpDate()); setHeader("Cache-Control", "public, max-age=0, must-revalidate"); } void Response::setCacheForeverHeaders(bool publicAccessiblity) { // set Expires header using namespace boost::posix_time; time_duration yearDuration = hours(365 * 24); ptime expireTime = second_clock::universal_time() + yearDuration; setHeader("Expires", http::util::httpDate(expireTime)); // set Cache-Control header auto durationSeconds = yearDuration.total_seconds(); std::string accessibility = publicAccessiblity ? "public" : "private"; std::string cacheControl(accessibility + ", max-age=" + safe_convert::numberToString(durationSeconds)); setHeader("Cache-Control", cacheControl); } void Response::setCacheForeverHeaders() { setCacheForeverHeaders(true); } void Response::setPrivateCacheForeverHeaders() { // NOTE: the Google article referenced above indicates that for the // private scenario you should set the Expires header in the past so // that HTTP 1.0 proxies never cache it. Unfortuantely when running // against localhost in Firefox we observed that this prevented Firefox // from caching. setCacheForeverHeaders(false); } // WARNING: This appears to break IE8 if Content-Disposition: attachment void Response::setNoCacheHeaders() { setHeader("Expires", "Fri, 01 Jan 1990 00:00:00 GMT"); setHeader("Pragma", "no-cache"); setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); } void Response::setFrameOptionHeaders(const std::string& options) { std::string option; if (options.empty() || options == "none") { // the default is to deny all framing option = "DENY"; } else if (options == "same") { // this special string indicates that framing is permissible on the same // domain option = "SAMEORIGIN"; } else { // the special string "any" means any origin if (options != "any") { option = "ALLOW-FROM " + options; // Chrome and Safari ignore ALLOW-FROM so also emit Content-Security-Policy // https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Defending_with_X-Frame-Options_Response_Headers std::string optionCSP = "frame-ancestors "; optionCSP += options; setHeader("Content-Security-Policy", optionCSP); } } // multiple space-separated domains not supported by X-Frame-Options, so if // there's a space, don't set the header (modern browsers will use the // previously-set Content-Security-Policy) if (!option.empty() && boost::algorithm::trim_copy(options).find_first_of(' ') == std::string::npos) setHeader("X-Frame-Options", option); } // mark this request's user agent compatibility void Response::setBrowserCompatible(const Request& request) { if (boost::algorithm::contains(request.userAgent(), "Trident")) setHeader("X-UA-Compatible", "IE=edge"); } void Response::addCookie(const Cookie& cookie) { addHeader("Set-Cookie", cookie.cookieHeaderValue()); // some browsers may swallow a cookie with SameSite=None // so create an additional legacy cookie without SameSite // which would be swalllowed by a standard-conforming browser if (cookie.sameSite() == Cookie::SameSite::None) { Cookie legacyCookie = cookie; legacyCookie.setName(legacyCookie.name() + kLegacyCookieSuffix); legacyCookie.setSameSite(Cookie::SameSite::Undefined); addHeader("Set-Cookie", legacyCookie.cookieHeaderValue()); } } Headers Response::getCookies(const std::vector<std::string>& names /*= {}*/) const { http::Headers headers; for (const http::Header& header : headers_) { if (header.name == "Set-Cookie") { if (names.empty()) { headers.push_back(header); } else { for (const std::string& name : names) { if (boost::algorithm::starts_with(header.value, name)) headers.push_back(header); else if (boost::algorithm::starts_with(header.value, name + kLegacyCookieSuffix)) headers.push_back(header); } } } } return headers; } void Response::clearCookies() { for (auto iter = headers_.begin(); iter != headers_.end();) { if (iter->name == "Set-Cookie") iter = headers_.erase(iter); else ++iter; } } Error Response::setBody(const std::string& content) { std::istringstream is(content); return setBody(is); } Error Response::setCacheableBody(const FilePath& filePath, const Request& request) { std::string content; Error error = core::readStringFromFile(filePath, &content); if (error) return error; return setCacheableBody(content, request); } void Response::setDynamicHtml(const std::string& html, const Request& request) { // dynamic html setContentType("text/html"); setNoCacheHeaders(); // gzip if possible if (request.acceptsEncoding(kGzipEncoding)) setContentEncoding(kGzipEncoding); // set body setBody(html); } void Response::setRangeableFile(const FilePath& filePath, const Request& request) { // read the file in from disk std::string contents; Error error = core::readStringFromFile(filePath, &contents); if (error) { setError(error); return; } setRangeableFile(contents, filePath.getMimeContentType(), request); } void Response::setRangeableFile(const std::string& contents, const std::string& mimeType, const Request& request) { // set content type setContentType(mimeType); // parse the range field std::string range = request.headerValue("Range"); boost::regex re("bytes=(\\d*)\\-(\\d*)"); boost::smatch match; if (regex_utils::match(range, match, re)) { // specify partial content setStatusCode(http::status::PartialContent); // determine the byte range const size_t kNone = -1; size_t begin = safe_convert::stringTo<size_t>(match[1], kNone); size_t end = safe_convert::stringTo<size_t>(match[2], kNone); size_t total = contents.length(); if (end == kNone) { end = total-1; } if (begin == kNone) { begin = total - end; end = total-1; } // set the byte range addHeader("Accept-Ranges", "bytes"); boost::format fmt("bytes %1%-%2%/%3%"); std::string range = boost::str(fmt % begin % end % contents.length()); addHeader("Content-Range", range); // always attempt gzip if (request.acceptsEncoding(http::kGzipEncoding)) setContentEncoding(http::kGzipEncoding); // set body if (begin == 0 && end == (contents.length()-1)) setBody(contents); else setBody(contents.substr(begin, end-begin+1)); } else { setStatusCode(http::status::RangeNotSatisfiable); boost::format fmt("bytes */%1%"); std::string range = boost::str(fmt % contents.length()); addHeader("Content-Range", range); } } void Response::setBodyUnencoded(const std::string& body) { removeHeader("Content-Encoding"); body_ = body; setContentLength(gsl::narrow_cast<int>(body_.length())); } void Response::setError(int statusCode, const std::string& message) { setStatusCode(statusCode); removeCachingHeaders(); setContentType("text/html"); setBodyUnencoded(string_utils::htmlEscape(message)); } void Response::setNotFoundError(const http::Request& request) { if (notFoundHandler_) { notFoundHandler_(request, this); return; } else setError(http::status::NotFound, request.uri() + " not found"); } void Response::setNotFoundError(const std::string& uri, const http::Request& request) { // the file this is missing is derived from details in the request, // and is not simply the request uri itself // as this is a special and rare case, do not attempt to handle it with the // not found handler, and simply note which uri was not found setError(http::status::NotFound, uri + " not found"); } void Response::setError(const Error& error) { setError(status::InternalServerError, error.getMessage()); } namespace { // only take up to the first newline to prevent http response split std::string safeLocation(const std::string& location) { std::vector<std::string> lines; boost::algorithm::split(lines, location, boost::algorithm::is_any_of("\r\n")); return lines.size() > 0 ? lines[0] : ""; } } // anonymous namespace void Response::setMovedPermanently(const http::Request& request, const std::string& location) { std::string path = URL(location).protocol() != "" ? location : request.rootPath() + '/' + safeLocation(location); std::string uri = URL::complete(request.baseUri(), path); setError(http::status::MovedPermanently, uri); setHeader("Location", uri); } void Response::setMovedTemporarily(const http::Request& request, const std::string& location) { std::string path = URL(location).protocol() != "" ? location : request.rootPath() + '/' + safeLocation(location); std::string uri = URL::complete(request.baseUri(), path); setError(http::status::MovedTemporarily, uri); setHeader("Location", uri); } void Response::resetMembers() { statusCode_ = status::Ok; statusCodeStr_.clear(); statusMessage_.clear(); } void Response::removeCachingHeaders() { removeHeader("Expires"); removeHeader("Pragma"); removeHeader("Cache-Control"); removeHeader("Last-Modified"); removeHeader("ETag"); } std::string Response::eTagForContent(const std::string& content) { return core::hash::crc32Hash(content); } void Response::appendFirstLineBuffers( std::vector<boost::asio::const_buffer>& buffers) const { // create status code string (needs to be a member so memory is still valid // for use of buffers) std::ostringstream statusCodeStream; statusCodeStream << statusCode_; statusCodeStr_ = statusCodeStream.str(); // status line appendHttpVersionBuffers(buffers); appendSpaceBuffer(buffers); buffers.push_back(boost::asio::buffer(statusCodeStr_)); appendSpaceBuffer(buffers); ensureStatusMessage(); buffers.push_back(boost::asio::buffer(statusMessage_)); } namespace status { namespace Message { const char * const SwitchingProtocols = "SwitchingProtocols"; const char * const Ok = "OK"; const char * const Created = "Created"; const char * const PartialContent = "Partial Content"; const char * const MovedPermanently = "Moved Permanently"; const char * const MovedTemporarily = "Moved Temporarily"; const char * const TooManyRedirects = "Too Many Redirects"; const char * const SeeOther = "See Other"; const char * const NotModified = "Not Modified"; const char * const BadRequest = "Bad Request"; const char * const Unauthorized = "Unauthorized"; const char * const Forbidden = "Forbidden"; const char * const NotFound = "Not Found"; const char * const MethodNotAllowed = "Method Not Allowed"; const char * const RangeNotSatisfiable = "Range Not Satisfyable"; const char * const InternalServerError = "Internal Server Error"; const char * const NotImplemented = "Not Implemented"; const char * const BadGateway = "Bad Gateway"; const char * const ServiceUnavailable = "Service Unavailable"; const char * const GatewayTimeout = "Gateway Timeout"; } // namespace Message } // namespace status void Response::ensureStatusMessage() const { if ( statusMessage_.empty() ) { using namespace status; switch(statusCode_) { case SwitchingProtocols: statusMessage_ = status::Message::SwitchingProtocols; break; case Ok: statusMessage_ = status::Message::Ok; break; case Created: statusMessage_ = status::Message::Created; break; case PartialContent: statusMessage_ = status::Message::PartialContent; break; case MovedPermanently: statusMessage_ = status::Message::MovedPermanently; break; case MovedTemporarily: statusMessage_ = status::Message::MovedTemporarily; break; case TooManyRedirects: statusMessage_ = status::Message::TooManyRedirects; break; case SeeOther: statusMessage_ = status::Message::SeeOther; break; case NotModified: statusMessage_ = status::Message::NotModified; break; case BadRequest: statusMessage_ = status::Message::BadRequest; break; case Unauthorized: statusMessage_ = status::Message::Unauthorized; break; case Forbidden: statusMessage_ = status::Message::Forbidden; break; case NotFound: statusMessage_ = status::Message::NotFound; break; case MethodNotAllowed: statusMessage_ = status::Message::MethodNotAllowed; break; case RangeNotSatisfiable: statusMessage_ = status::Message::RangeNotSatisfiable; break; case InternalServerError: statusMessage_ = status::Message::InternalServerError; break; case NotImplemented: statusMessage_ = status::Message::NotImplemented; break; case BadGateway: statusMessage_ = status::Message::BadGateway; break; case ServiceUnavailable: statusMessage_ = status::Message::ServiceUnavailable; break; case GatewayTimeout: statusMessage_ = status::Message::GatewayTimeout; break; } } } std::ostream& operator << (std::ostream& stream, const Response& r) { // output status line stream << "HTTP/" << r.httpVersionMajor() << "." << r.httpVersionMinor() << " " << r.statusCode() << " " << r.statusMessage() << std::endl; // output headers and body const Message& m = r; stream << m; return stream; } void Response::setStreamFile(const FilePath& filePath, const Request& request, std::streamsize buffSize) { std::string contentType = filePath.getMimeContentType("application/octet-stream"); setContentType(contentType); // if content type indicates compression, do not compress it again // Firefox is unable to handle this case, so we specifically guard against it bool compress = (contentType != "application/x-gzip" && contentType != "application/zip" && contentType != "application/x-bzip" && contentType != "application/x-bzip2" && contentType != "application/x-tar"); boost::optional<CompressionType> compressionType; #ifndef _WIN32 // gzip if possible (never on win32) // we prefer the inferior gzip to deflate // because older browsers (like IE11) claim to support // deflate but in actuality cannot handle it! if (request.acceptsEncoding(kGzipEncoding) && compress) { setContentEncoding(kGzipEncoding); compressionType = CompressionType::Gzip; } else if (request.acceptsEncoding(kDeflateEncoding) && compress) { setContentEncoding(kDeflateEncoding); compressionType = CompressionType::Deflate; } #endif // streaming will be performed via chunked encoding setHeader(kTransferEncoding, kChunkedTransferEncoding); boost::shared_ptr<FileStreamResponse> fileStream( new FileStreamResponse(filePath, buffSize, usePadding(request, filePath))); #ifndef _WIN32 if (compressionType) { streamResponse_.reset( new ZlibCompressionStreamResponse(fileStream, buffSize, compressionType.get())); } else { streamResponse_ = fileStream; } #else streamResponse_ = fileStream; #endif Error error = streamResponse_->initialize(); if (error) setError(status::InternalServerError, error.getMessage()); } } // namespacc http } // namespace core } // namespace rstudio
agpl-3.0
skyrossm/SkyMod
src/main/java/com/skyrossm/skymod/handler/FuelHandler.java
483
package com.skyrossm.skymod.handler; import com.skyrossm.skymod.init.ModItems; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.IFuelHandler; public class FuelHandler implements IFuelHandler { @Override public int getBurnTime(ItemStack fuel){ if(fuel.getItem() == ModItems.itemCoalClump){ return 12800; } if(fuel.getItem() == ModItems.itemMagicDust){ return 1024; } return 0; } }
agpl-3.0
c2corg/camptocamp.org
plugins/sfFeed2Plugin/lib/sfFeed.class.php
6577
<?php /* * This file is part of the sfFeed2 package. * (c) 2004-2006 Fabien Potencier <[email protected]> * (c) 2004-2007 Francois Zaninotto <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * sfFeed. * * based on feedgenerator.py from django project * * @package sfFeed2 * @author Fabien Potencier <[email protected]> * @author Francois Zaninotto <[email protected]> */ class sfFeed { protected $items = array(), $title, $link, $description, $language = 'en', $authorEmail, $authorName, $authorLink, $subtitle, $categories = array(), $feedUrl, $encoding = 'UTF-8'; public function construct($feed_array = array()) { if($feed_array) { $this->initialize($feed_array); } } /** * Defines the feed properties, based on an associative array * * @param array an associative array of feed parameters * * @return sfFeed the current sfFeed object */ public function initialize($feed_array) { $this->setItems(isset($feed_array['items']) ? $feed_array['items'] : ''); $this->setTitle(isset($feed_array['title']) ? $feed_array['title'] : ''); $this->setLink(isset($feed_array['link']) ? $feed_array['link'] : ''); $this->setDescription(isset($feed_array['description']) ? $feed_array['description'] : ''); $this->setLanguage(isset($feed_array['language']) ? $feed_array['language'] : $this->language); $this->setAuthorEmail(isset($feed_array['authorEmail']) ? $feed_array['authorEmail'] : ''); $this->setAuthorName(isset($feed_array['authorName']) ? $feed_array['authorName'] : ''); $this->setAuthorLink(isset($feed_array['authorLink']) ? $feed_array['authorLink'] : ''); $this->setSubtitle(isset($feed_array['subtitle']) ? $feed_array['subtitle'] : ''); $this->setCategories(isset($feed_array['categories']) ? $feed_array['categories'] : ''); $this->setFeedUrl(isset($feed_array['feedUrl']) ? $feed_array['feedUrl'] : ''); $this->setEncoding(isset($feed_array['encoding']) ? $feed_array['encoding'] : $this->encoding); return $this; } /** * Retrieves the feed items * * @return array an array of sfFeedItem objects */ public function getItems() { return $this->items; } /** * Defines the items of the feed * Caution: in previous versions, this method used to accept all kinds of objects. * Now only objects of class sfFeedItem are allowed. * * @param array an array of sfFeedItem objects * * @return sfFeed the current sfFeed object */ public function setItems($items = array()) { $this->items = array(); $this->addItems($items); return $this; } /** * Adds one item to the feed * * @param sfFeedItem an item object * * @return sfFeed the current sfFeed object */ public function addItem($item) { if (!($item instanceof sfFeedItem)) { // the object is of the wrong class $error = 'Parameter of addItem() is not of class sfFeedItem'; throw new Exception($error); } $item->setFeed($this); $this->items[] = $item; return $this; } /** * Adds several items to the feed * * @param array an array of sfFeedItem objects * * @return sfFeed the current sfFeed object */ public function addItems($items) { if(is_array($items)) { foreach($items as $item) { $this->addItem($item); } } return $this; } /** * Adds one item to the feed, based on an associative array * * @param array an associative array * * @return sfFeed the current sfFeed object */ public function addItemFromArray($item_array) { $this->items[] = new sfFeedItem($item_array); return $this; } /** * Removes the last items of the feed * so that the total number doesn't bypass the limit defined as a parameter * * @param integer the maximum number of items * * @return sfFeed the current sfFeed object */ public function keepOnlyItems($count = 10) { if($count < count($this->items)) { $this->items = array_slice($this->items, 0, $count); } return $this; } public function setTitle ($title) { $this->title = $title; } public function getTitle () { return $this->title; } public function setLink ($link) { $this->link = $link; } public function getLink () { return $this->link; } public function setDescription ($description) { $this->description = $description; } public function getDescription () { return $this->description; } public function setLanguage ($language) { $this->language = $language; } public function getLanguage () { return $this->language; } public function setAuthorEmail ($authorEmail) { $this->authorEmail = $authorEmail; } public function getAuthorEmail () { return $this->authorEmail; } public function setAuthorName ($authorName) { $this->authorName = $authorName; } public function getAuthorName () { return $this->authorName; } public function setAuthorLink ($authorLink) { $this->authorLink = $authorLink; } public function getAuthorLink () { return $this->authorLink; } public function setSubtitle ($subtitle) { $this->subtitle = $subtitle; } public function getSubtitle () { return $this->subtitle; } public function setCategories ($categories) { $this->categories = $categories; } public function getCategories () { return $this->categories; } public function setFeedUrl ($feedUrl) { $this->feedUrl = $feedUrl; } public function getFeedUrl () { return $this->feedUrl; } public function getEncoding() { return $this->encoding; } public function setEncoding($encoding) { $this->encoding = $encoding; } public function getLatestPostDate() { $updates = array(); foreach ($this->getItems() as $item) { if ($item->getPubdate()) { $updates[] = $item->getPubdate(); } } if ($updates) { sort($updates); return array_pop($updates); } else { return time(); } } public function asXml() { throw new sfException('You must use newInstance to get a real feed.'); } } ?>
agpl-3.0
shoaib-fazal16/yourown
custom/Extension/modules/AOS_Products/Ext/Layoutdefs/yo_sales_aos_products_AOS_Products.php
593
<?php // created: 2015-03-23 15:31:08 $layout_defs["AOS_Products"]["subpanel_setup"]['yo_sales_aos_products'] = array ( 'order' => 100, 'module' => 'yo_Sales', 'subpanel_name' => 'default', 'sort_order' => 'asc', 'sort_by' => 'id', 'title_key' => 'LBL_YO_SALES_AOS_PRODUCTS_FROM_YO_SALES_TITLE', 'get_subpanel_data' => 'yo_sales_aos_products', 'top_buttons' => array ( 0 => array ( 'widget_class' => 'SubPanelTopButtonQuickCreate', ), 1 => array ( 'widget_class' => 'SubPanelTopSelectButton', 'mode' => 'MultiSelect', ), ), );
agpl-3.0
elijh/crabgrass-core
app/controllers/avatars_controller.rb
923
## ## Avatars are the little icons used for users and groups. ## ## This controller is in charge of showing them. See me/avatars or groups/avatars ## for editing them. ## class AvatarsController < ApplicationController # always enable cache, even in dev mode. def self.perform_caching; true; end def perform_caching; true; end caches_page :show def show @image = Avatar.find_by_id params[:id] if @image.nil? size = Avatar.pixels(params[:size]) size.sub!(/^\d*x/,'') filename = "#{File.dirname(__FILE__)}/../../public/images/default/#{size}.jpg" send_data(IO.read(filename), :type => 'image/jpeg', :disposition => 'inline') else content_type = 'image/jpeg' data = @image.resize(params[:size], content_type); response.headers['Cache-Control'] = 'public, max-age=86400' send_data data, :type => content_type, :disposition => 'inline' end end end
agpl-3.0
rhosocial/yii2-assets
JqueryWidgetAsset.php
685
<?php /** * _ __ __ _____ _____ ___ ____ _____ * | | / // // ___//_ _// || __||_ _| * | |/ // /(__ ) / / / /| || | | | * |___//_//____/ /_/ /_/ |_||_| |_| * @link https://vistart.me/ * @copyright Copyright (c) 2016 - 2017 vistart * @license https://vistart.me/license/ */ namespace rhosocial\assets; use yii\web\AssetBundle; /** * Class JqueryWidgetAsset * @package rhosocial\assets * @version 1.0 * @author vistart <[email protected]> */ class JqueryWidgetAsset extends AssetBundle { /** * @inheritdoc */ public $sourcePath = '@bower/jquery-ui'; /** * @inheritdoc */ public $js = ['ui/minified/widget.min.js']; }
agpl-3.0
faradayio/earth
spec/earth/locality/padd_spec.rb
799
require 'spec_helper' require 'earth/locality/petroleum_administration_for_defense_district' describe PetroleumAdministrationForDefenseDistrict do let(:padd) { PetroleumAdministrationForDefenseDistrict } describe '#name' do it 'describes a PADD that is a district' do test = padd.new(:district_code => 1, :district_name => 'East Coast') test.name.should == 'PAD District 1 (East Coast)' end it 'describes a PADD that is a subdistric' do test = padd.new(:district_code => 1, :district_name => 'East Coast', :subdistrict_code => 'A', :subdistrict_name => 'New England') test.name.should == 'PAD District 1 (East Coast) Subdistrict 1A (New England)' end end describe 'Sanity check', :sanity => true do it { padd.count.should == 7 } end end
agpl-3.0
naturdrogerie/plentymarkets-shopware-connector
Components/Soap/Models/PlentySoapRequest/SetItemsCategories.php
1500
<?php /** * plentymarkets shopware connector * Copyright © 2013-2014 plentymarkets GmbH * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License, supplemented by an additional * permission, and of our proprietary license can be found * in the LICENSE file you have received along with this program. * * 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 Affero General Public License for more details. * * "plentymarkets" is a registered trademark of plentymarkets GmbH. * "shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, titles and interests in the * above trademarks remain entirely with the trademark owners. * * @copyright Copyright (c) 2014, plentymarkets GmbH (http://www.plentymarkets.com) * @author Daniel Bächtle <[email protected]> */ /** * I am a generated class and am required for communicating with plentymarkets. */ class PlentySoapRequest_SetItemsCategories { /** * @var int */ public $CallItemsLimit; /** * @var ArrayOfPlentysoapobject_setitemscategories */ public $ItemsList; }
agpl-3.0
theoo/circl
db/migrate/20141012174951_add_dates_to_product_items.rb
352
class AddDatesToProductItems < ActiveRecord::Migration def change add_column :affairs_products_programs, :confirmed_at, :datetime, default: nil add_column :affairs_products_programs, :delivery_at, :datetime, default: nil add_index :affairs_products_programs, :confirmed_at add_index :affairs_products_programs, :delivery_at end end
agpl-3.0
blocktrail/blocktrail-wallet
src/js/controllers/PromoControllers.js
5535
angular.module('blocktrail.wallet') .controller('PromoCodeRedeemCtrl', function($scope, $rootScope, $state, $stateParams, $btBackButtonDelegate, $q, $log, $cordovaToast, $ionicLoading, QR, $timeout, walletsManagerService, trackingService) { $scope.appControl = { working: false, showMessage: false }; $scope.promoCodeInput = { code: $stateParams.code || null, //promo code address: null, //redemption address uuid: device.uuid, //unique device id //nocommit platform: $rootScope.isIOS && "iOS" || "Android", version: $rootScope.appVersion }; $scope.message = { title: "", title_class: "", body: "", body_class: "" }; $scope.scanQr = function() { $ionicLoading.show({template: "<div>{{ 'LOADING' | translate }}...</div>", hideOnStateChange: true}); // wait for transition, then open the scanner and begin scanning $timeout(function() { QR.scan( function(result) { $log.debug('scan done', result); $ionicLoading.hide(); // parse result for address and value var elm = angular.element('<a>').attr('href', result )[0]; $log.debug(elm.protocol, elm.pathname, elm.search, elm.hostname); if (result.toLowerCase() === "cancelled") { $state.go('wallet.summary'); } else if (elm.protocol === 'btccomwallet:') { var reg = new RegExp(/btccomwallet:\/\/promocode\?code=(.+)/); var res = result.match(reg); $scope.promoCodeInput.code = res[1]; } }, function(error) { $log.error(error); $log.error("Scanning failed: " + error); $ionicLoading.hide(); $cordovaToast.showLongTop("Scanning failed: " + error); } ); }, 350); }; $scope.showMessage = function() { $scope.appControl.showMessage = true; //set alternative back button function (just fires once) $btBackButtonDelegate.setBackButton(function() { $timeout(function() { $scope.dismissMessage(); }); }, true); $btBackButtonDelegate.setHardwareBackButton(function() { $timeout(function() { $scope.dismissMessage(); }); }, true); }; $scope.dismissMessage = function() { $scope.appControl.showMessage = false; //reset back button functionality $btBackButtonDelegate.setBackButton($btBackButtonDelegate._default); $btBackButtonDelegate.setHardwareBackButton($btBackButtonDelegate._default); }; $scope.resetMessage = function() { $scope.message = { title: "", title_class: "", body: "", body_class: "" }; }; $scope.confirmInput = function() { if ($scope.appControl.working) { return false; } //validate and cleanup if (!$scope.promoCodeInput.code) { $scope.message = {title: 'ERROR_TITLE_2', title_class: 'text-bad', body: 'MSG_MISSING_PROMO_CODE'}; return false; } //generate redemption address then send promo code $scope.message = {title: 'CHECKING', title_class: 'text-neutral', body: ''}; $scope.appControl.working = true; $scope.showMessage(); $q.when($scope.promoCodeInput.address || walletsManagerService.getActiveWallet().getNewAddress()) .then(function(address) { $scope.promoCodeInput.address = address; trackingService.trackEvent(trackingService.EVENTS.PROMO_ATTEMPT); return walletsManagerService.getActiveSdk().redeemPromoCode($scope.promoCodeInput); }) .then(function(result) { trackingService.trackEvent(trackingService.EVENTS.PROMO_REDEEM); $timeout(function(){ $scope.dismissMessage(); $timeout(function(){ $scope.message = {title: 'THANKS_1', title_class: 'text-good', body: result.msg}; $scope.promoCodeInput.code = ''; $scope.appControl.working = false; }, 400); }, 200); }) .catch(function(err) { $timeout(function(){ $scope.dismissMessage(); $timeout(function(){ $scope.message = {title: 'SORRY', title_class: 'text-bad', body: err.message || err}; $scope.appControl.working = false; }, 400); }, 200); }); }; } );
agpl-3.0
GTAUN/wl-chat-channel
src/main/java/net/gtaun/wl/chat/event/ChatChannelPlayerJoinEvent.java
1126
/** * WL Chat Channel Plugin * Copyright (C) 2013 MK124 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.gtaun.wl.chat.event; import net.gtaun.shoebill.object.Player; import net.gtaun.wl.chat.ChatChannel; /** * 聊天频道玩家加入事件。 * * @author MK124 */ public class ChatChannelPlayerJoinEvent extends ChatChannelPlayerEvent { public ChatChannelPlayerJoinEvent(ChatChannel channel, Player player) { super(channel, player); } }
agpl-3.0
Rovanion/Yaws
lib/libAuth.php
4278
<?php require_once '../lib/settings.php'; session_start(); $loggedIn = checkLogin(); //$loggedIn is true if the user is logged in, else false function makeMySQLConnection(){ //Connects to MySQL at localhost with username and password from ../lib/settings.php mysql_connect('localhost', DatabaseUserName, DatabasePassword) or die('MySQL connection failed. You must enter your password in ../lib/settings.php accordingly to your setup. Either that or your database just broke.'. mysql_error()); if(!mysql_select_db(Database)){ //The database defined in ../lib/settings.php is selected, else created. $sql = "CREATE DATABASE `".Database."`"; mysql_query($sql) or die('Selecting the database '. Database. ' failed and subsequently creating a new database with that name also failed. Something in your setup is broken.'. mysql_error()); $sql = "CREATE TABLE `".Database."`.`users` ( `email` VARCHAR( 128 ) NOT NULL , `password` VARCHAR( 32 ) NOT NULL , `active` TINYINT( 1 ) NULL , PRIMARY KEY ( `email` ) ) ENGINE = MYISAM DEFAULT CHARSET=utf8 COMMENT = 'The table containing the site administrators and their encrypted passwords';"; mysql_query($sql) or die('Selecting the database joypeak failed and subsequently creating a new table with the name <b>users</b> in the database joypeak. Something in your setup is broken.'. mysql_error()); $sql = "CREATE TABLE `".Database."`.`pages` ( `index` TINYINT NOT NULL COMMENT 'A unique number, the order of links', `title` TEXT NOT NULL COMMENT 'The shown title', `JStitle` TEXT NOT NULL COMMENT 'The cleaned title for code', PRIMARY KEY ( `index` ) ) ENGINE = MYISAM COMMENT = 'The table containing the pages of the website';"; mysql_query($sql) or die('Selecting the database joypeak failed and subsequently creating a new table with the name <b>pages</b> in the database joypeak. Something in your setup is broken.'. mysql_error()); $sql = "CREATE TABLE `".Database."`.`verification` ( `email` VARCHAR( 64 ) NOT NULL COMMENT 'The email adress', `token` VARCHAR( 32 ) NOT NULL COMMENT 'The verification code' ) ENGINE = MYISAM COMMENT = 'Table used for verifying accounts';"; mysql_query($sql) or die('Selecting the database joypeak failed and subsequently creating a new table with the name <b>verification</b> in the database joypeak. Something in your setup is broken.'. mysql_error()); mysql_select_db(Database) or die('Selecting the database '.Database.' after creating it failed in ../lib/libAuth.php'. mysql_error()); } } function checkLogin(){ makeMySQLConnection(); if (isset($_POST["email"])) login(); if (isset($_SESSION["email"]) && isset($_SESSION["password"])){ $sql = "SELECT * FROM users WHERE email='{$_SESSION['email']}' AND password='{$_SESSION['password']}'"; $result = mysql_query($sql); $array = mysql_fetch_assoc($result); if($_SESSION["email"] == $array["email"] && $_SESSION["password"] == $array["password"]){ return true; } } else return false; } function login(){ global $loggedIn; if($loggedIn) return; if(isset($_POST["email"]) && isset($_POST["password"])){ $password = mysql_real_escape_string($_POST["password"]); $user = mysql_real_escape_string($_POST["email"]); $md5password = md5($password); $sql = "SELECT * FROM users WHERE email='{$user}' AND password='{$md5password}'"; $result = mysql_query($sql) or //Run query and continue if it succeeds, or print the error. print "Falken anfaller! Följande SQL-sats är felaktig:<br />". $sql. '<br /><br /> Följande felmeddelande gavs:'. mysql_error(); if (mysql_num_rows($result) == 1){ $_SESSION["email"] = $_POST["email"]; $_SESSION["password"] = $md5password; } else echo "<br />Du loggades inte in. Detta är en ful svart text."; } } ?>
agpl-3.0
stephaneperry/Silverpeas-Components
whitepages/whitepages-jar/src/main/java/com/silverpeas/whitePages/service/MixedSearchService.java
2147
/** * Copyright (C) 2000 - 2011 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.whitePages.service; import java.util.Collection; import java.util.Hashtable; import java.util.List; import com.stratelia.silverpeas.contentManager.GlobalSilverContent; import com.stratelia.silverpeas.pdc.model.SearchContext; import com.stratelia.webactiv.util.indexEngine.model.FieldDescription; public interface MixedSearchService { public Collection<GlobalSilverContent> search(String spaceId, String componentId, String userId, String queryString, // standard search SearchContext pdcContext, // PDC filter Hashtable<String,String> xmlFields, String xmlTemplate, // xml fields filter List<FieldDescription> fieldsQuery, // ldap and silverpeas fields filter String language) throws Exception; }
agpl-3.0
miguel76/SWOWS
swows/src/main/java/org/swows/xmlinrdf/DomDecoder.java
70491
/* * Copyright (c) 2011 Miguel Ceriani * [email protected] * This file is part of Semantic Web Open datatafloW System (SWOWS). * SWOWS is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * SWOWS 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 Affero General Public License for more details. * You should have received a copy of the GNU Affero General * Public License along with SWOWS. If not, see <http://www.gnu.org/licenses/>. */ package org.swows.xmlinrdf; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import org.apache.jena.graph.Graph; import org.apache.jena.graph.Node; import org.apache.jena.graph.Triple; import org.apache.jena.sparql.expr.NodeValue; import org.apache.jena.util.iterator.ExtendedIterator; import org.apache.jena.vocabulary.RDF; import org.apache.jena.vocabulary.RDFS; import org.apache.log4j.Logger; import org.swows.graph.events.DynamicGraph; import org.swows.graph.events.GraphUpdate; import org.swows.graph.events.Listener; import org.swows.runnable.RunnableContext; import org.swows.util.GraphUtils; import org.swows.util.Utils; import org.swows.vocabulary.SWI; import org.swows.vocabulary.XML; import org.w3c.dom.Attr; import org.w3c.dom.Comment; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventTarget; public class DomDecoder implements Listener, RunnableContext, EventListener { private static String VOID_NAMESPACE = "http://www.swows.org/xml/no-namespace"; private static final Logger logger = Logger.getLogger(DomDecoder.class); private static final Comparator<Node> nodeComparator = new Comparator<Node>() { @Override public int compare(Node node1, Node node2) { return (node1 == null) ? ( (node2 == null) ? 0 : -1 ) : ( (node2 == null) ? 1 : NodeValue.compareAlways( NodeValue.makeNode(node1), NodeValue.makeNode(node2))); // TODO check > semantics in sparql } }; private static final String specialXmlNamespacesSeparator = "#"; private static final Set<String> specialXmlNamespaces = new HashSet<>(50); static { specialXmlNamespaces.add(VOID_NAMESPACE); specialXmlNamespaces.add("http://www.w3.org/XML/1998/namespace"); specialXmlNamespaces.add("http://www.w3.org/2000/xmlns/"); specialXmlNamespaces.add("http://www.w3.org/1999/xhtml"); specialXmlNamespaces.add("http://www.w3.org/1999/xlink"); specialXmlNamespaces.add("http://www.w3.org/2001/XInclude"); specialXmlNamespaces.add("http://www.w3.org/1999/XSL/Format"); specialXmlNamespaces.add("http://www.w3.org/1999/XSL/Transform"); specialXmlNamespaces.add("http://www.w3.org/XSL/Transform/1.0"); specialXmlNamespaces.add("http://www.w3.org/TR/WD-xsl"); specialXmlNamespaces.add("http://icl.com/saxon"); specialXmlNamespaces.add("http://xml.apache.org/xslt"); specialXmlNamespaces.add("http://xmlns.opentechnology.org/xslt-extensions/common/"); specialXmlNamespaces.add("http://xmlns.opentechnology.org/xslt-extensions/functions"); specialXmlNamespaces.add("http://xmlns.opentechnology.org/xslt-extensions/math"); specialXmlNamespaces.add("http://xmlns.opentechnology.org/xslt-extensions/sets"); specialXmlNamespaces.add("http://www.w3.org/2001/08/xquery-operators"); specialXmlNamespaces.add("http://www.w3.org/2000/svg"); specialXmlNamespaces.add("http://www.w3.org/2001/SMIL20/"); specialXmlNamespaces.add("http://www.w3.org/TR/REC-smil"); specialXmlNamespaces.add("http://www.w3.org/1998/Math/MathML"); } // private static String specialNamespace(String ) private DocumentReceiver docReceiver; private DOMImplementation domImplementation; private DynamicGraph graph; // private Set<DomEventListener> domEventListeners; private Map<String, Set<DomEventListener>> domEventListeners; private Document document; private RunnableContext updatesContext; private Map<Node, Set<org.w3c.dom.Node>> graph2domNodeMapping = new HashMap<Node, Set<org.w3c.dom.Node>>(); private Map<Node, org.w3c.dom.Node> graph2domNodeMappingRef = new HashMap<Node, org.w3c.dom.Node>(); private Map<org.w3c.dom.Node, Node> dom2graphNodeMapping = new HashMap<org.w3c.dom.Node, Node>(); private Node docRootNode; private Map<Element,NavigableMap<Node, Vector<org.w3c.dom.Node>>> dom2orderedByKeyChildren = new HashMap<Element, NavigableMap<Node,Vector<org.w3c.dom.Node>>>(); private Map<Element,Map<org.w3c.dom.Node, Node>> dom2childrenKeys = new HashMap<Element, Map<org.w3c.dom.Node, Node>>(); private Set<Element> dom2descendingOrder = new HashSet<Element>(); private Map<Element, Node> dom2childrenOrderProperty = new HashMap<Element, Node>(); private Map<Element, String> dom2textContent = new HashMap<Element, String>(); private static EventManager DEFAULT_EVENT_MANAGER = new EventManager() { public void removeEventListener( Node targetNode, org.w3c.dom.Node target, String type, EventListener listener, boolean useCapture) { if (target instanceof EventTarget) ((EventTarget) target).removeEventListener(type, listener, useCapture); } public void addEventListener( Node targetNode, org.w3c.dom.Node target, String type, EventListener listener, boolean useCapture) { if (target instanceof EventTarget) ((EventTarget) target).addEventListener(type, listener, useCapture); } }; private EventManager eventManager;// = DEFAULT_EVENT_MANAGER; // private Map<String, Set<Element>> eventType2elements = new HashMap<String, Set<Element>>(); // private Map<Element, Set<String>> element2eventTypes = new HashMap<Element, Set<String>>(); public void addDomEventListener(String eventType, DomEventListener l) { synchronized(this) { if (domEventListeners == null) domEventListeners = new HashMap<String, Set<DomEventListener>>(); } synchronized(domEventListeners) { Set<DomEventListener> domEventListenersForType = domEventListeners.get(eventType); if (domEventListenersForType == null) { domEventListenersForType = new HashSet<DomEventListener>(); domEventListeners.put(eventType, domEventListenersForType); } domEventListenersForType.add(l); } } public void removeDomEventListener(String eventType, DomEventListener l) { if (domEventListeners != null) { synchronized(domEventListeners) { domEventListeners.remove(l); } } } public synchronized void handleEvent(Event evt) { logger.debug("In DOM decoder handling event " + evt + " of type " + evt.getType()); // System.out.println("In DOM decoder handling event " + evt + " of type " + evt.getType()); org.w3c.dom.Node eventCurrentTargetDomNode = (org.w3c.dom.Node) evt.getCurrentTarget(); Node eventCurrentTargetGraphNode = dom2graphNodeMapping.get(eventCurrentTargetDomNode); org.w3c.dom.Node eventTargetDomNode = (org.w3c.dom.Node) evt.getTarget(); Node eventTargetGraphNode = dom2graphNodeMapping.get(eventTargetDomNode); if (domEventListeners != null) { synchronized (domEventListeners) { Set<DomEventListener> domEventListenersForType = domEventListeners.get(evt.getType()); for (DomEventListener l : domEventListenersForType) { logger.debug("Sending to " + l + " the event " + evt); l.handleEvent(evt, eventCurrentTargetGraphNode, eventTargetGraphNode); } } } } public static Document decode(DynamicGraph graph, Node docRootNode) { try { return decode(graph, docRootNode, DOMImplementationRegistry.newInstance().getDOMImplementation("XML 1.0")); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } } public static Document decodeOne(DynamicGraph graph) { return decodeAll(graph).next(); } public static ExtendedIterator<Document> decodeAll(final DynamicGraph graph) { return graph .find(Node.ANY, RDF.type.asNode(), XML.Document.asNode()) .mapWith(triple -> decode(graph, triple.getSubject())); } private static String specialName(final Node elementNode) { if (elementNode.isURI()) { String uriStr = elementNode.getURI(); int sepPos = uriStr.indexOf(specialXmlNamespacesSeparator); if ( sepPos > 0 && specialXmlNamespaces.contains(uriStr.substring(0,sepPos))) return uriStr.substring(sepPos+1); } return null; } private static String specialNamespace(final Node elementNode) { if (elementNode.isURI()) { String uriStr = elementNode.getURI(); int sepPos = uriStr.indexOf(specialXmlNamespacesSeparator); if ( sepPos > 0 && specialXmlNamespaces.contains(uriStr.substring(0,sepPos))) return uriStr.substring(0,sepPos); } return null; } private static String qNameElement(final Graph graph, final Node elementNode) { Node elementType = GraphUtils.getSingleValueProperty(graph, elementNode, RDF.type.asNode()); String specialName = specialName(elementType); if (specialName != null) return specialName; return GraphUtils .getSingleValueProperty( graph, elementType, XML.nodeName.asNode() ) .getLiteralLexicalForm(); } private static String namespaceElement(final Graph graph, final Node elementNode) { Node elementType = GraphUtils.getSingleValueProperty(graph, elementNode, RDF.type.asNode()); String specialNamespace = specialNamespace(elementType); if (specialNamespace != null) return specialNamespace; try { return graph.find( elementType, XML.namespace.asNode(), Node.ANY) .next().getObject().getURI(); } catch (NoSuchElementException e) { return null; } } private static boolean predicateIsAttr(final Graph graph, final Node predicate) { if (predicate.isURI()) { String uriStr = predicate.getURI(); int sepPos = uriStr.indexOf(specialXmlNamespacesSeparator); if ( sepPos > 0 && specialXmlNamespaces.contains(uriStr.substring(0,sepPos))) return true; } return graph.contains( predicate, RDFS.subClassOf.asNode(), XML.Attr.asNode()); } private static boolean nodeIsRootDocument(final Graph graph, Node nodeType, Node node) { return nodeType.equals(XML.Document.asNode()) && graph.contains(SWI.GraphRoot.asNode(), XML.document.asNode(), node); } private static boolean nodeTypeIsElementType(final Graph graph, final Node nodeType) { if (nodeType.isURI()) { String uriStr = nodeType.getURI(); int sepPos = uriStr.indexOf(specialXmlNamespacesSeparator); if ( sepPos > 0 && specialXmlNamespaces.contains(uriStr.substring(0,sepPos))) return true; } return graph.contains(nodeType, RDFS.subClassOf.asNode(), XML.Element.asNode()); } private static String qNameAttr(final Graph graph, final Node elementNode) { String specialName = specialName(elementNode); if (specialName != null) return specialName; return GraphUtils .getSingleValueProperty( graph, elementNode, XML.nodeName.asNode() ) .getLiteralLexicalForm(); } private static String namespaceAttr(final Graph graph, final Node elementNode) { String specialNamespace = specialNamespace(elementNode); if (specialNamespace != null) return specialNamespace; try { return graph.find( elementNode, XML.namespace.asNode(), Node.ANY) .next().getObject().getURI(); } catch (NoSuchElementException e) { return null; } } private static String value(final Graph graph, final Node elementNode) { try { return graph.find(elementNode, XML.nodeValue.asNode(), Node.ANY) .next().getObject().getLiteralLexicalForm(); } catch (NoSuchElementException e) { return null; } } private Text decodeText(Graph graph, Node elementNode) { return document.createTextNode(value(graph, elementNode)); } @SuppressWarnings("unused") private Comment decodeComment(Graph graph, Node elementNode) { return document.createComment(value(graph, elementNode)); } @SuppressWarnings("unused") private ProcessingInstruction decodeProcessingInstruction(Graph graph, Node elementNode) { return document.createProcessingInstruction( qNameElement(graph, elementNode), value(graph, elementNode) ); } private Attr decodeAttr(Node elementNode) { String nsUri = namespaceAttr(graph, elementNode); if (nsUri == null) throw new RuntimeException("Namespace not found for attribute " + elementNode + " in graph " + graph); return (nsUri.equals(VOID_NAMESPACE)) ? document.createAttribute( qNameAttr(graph, elementNode) ) : document.createAttributeNS( nsUri, qNameAttr(graph, elementNode) ); } private void removeAttr(Element element, Node elementNode) { String nsUri = namespaceAttr(graph, elementNode); if (nsUri == null) throw new RuntimeException("Namespace not found for attribute " + elementNode + " in graph " + graph); if (nsUri.equals(VOID_NAMESPACE)) element.removeAttribute( qNameAttr(graph, elementNode) ); else element.removeAttributeNS( nsUri, qNameAttr(graph, elementNode) ); } public String md5(String md5) { try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(md5.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { } return null; } private void reorder( // Set<org.w3c.dom.Node> noKeyChildren, boolean ascendingOrder, Element element, NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren ) { // if (ascendingOrder) { // for (org.w3c.dom.Node child : noKeyChildren) { // element.appendChild(child); // } // } String textContent = dom2textContent.get(element); if (textContent != null) element.setTextContent(textContent); for (Node orderKeyNode : ascendingOrder ? orderedByKeyChildren.keySet() : orderedByKeyChildren.descendingKeySet() ) { for (org.w3c.dom.Node child : orderedByKeyChildren.get(orderKeyNode)) { element.appendChild(child); } } // if (!ascendingOrder) { // for (org.w3c.dom.Node child : noKeyChildren) { // element.appendChild(child); // } // } } private int elementCount = 0; private synchronized String newElementId() { return "n_" + Integer.toHexString(elementCount++); } private void putChildByKey(Element parent, org.w3c.dom.Node node, Node orderKeyNode) { Map<org.w3c.dom.Node, Node> childrenKeys = dom2childrenKeys.get(parent); NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren = dom2orderedByKeyChildren.get(parent); Vector<org.w3c.dom.Node> sameKeyBag = orderedByKeyChildren.get(orderKeyNode); if (sameKeyBag == null) { sameKeyBag = new Vector<org.w3c.dom.Node>(); orderedByKeyChildren.put(orderKeyNode, sameKeyBag); } sameKeyBag.add(node); childrenKeys.put(node, orderKeyNode); } private void removeChildByKey(Element parent, org.w3c.dom.Node node) { Map<org.w3c.dom.Node, Node> childrenKeys = dom2childrenKeys.get(parent); NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren = dom2orderedByKeyChildren.get(parent); Node prevOrderKeyNode = childrenKeys.get(node); if (prevOrderKeyNode != null) { Vector<org.w3c.dom.Node> oldKeyBag = orderedByKeyChildren.get(prevOrderKeyNode); oldKeyBag.remove(node); if (oldKeyBag.isEmpty()) orderedByKeyChildren.remove(prevOrderKeyNode); } childrenKeys.remove(node); } private void updateChildByKey(Element parent, org.w3c.dom.Node node, Node orderKeyNode) { Map<org.w3c.dom.Node, Node> childrenKeys = dom2childrenKeys.get(parent); NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren = dom2orderedByKeyChildren.get(parent); Node prevOrderKeyNode = childrenKeys.get(node); Vector<org.w3c.dom.Node> oldKeyBag = orderedByKeyChildren.get(prevOrderKeyNode); if (oldKeyBag != null) { oldKeyBag.remove(node); if (oldKeyBag.isEmpty()) orderedByKeyChildren.remove(prevOrderKeyNode); } Vector<org.w3c.dom.Node> sameKeyBag = orderedByKeyChildren.get(orderKeyNode); if (sameKeyBag == null) { sameKeyBag = new Vector<org.w3c.dom.Node>(); orderedByKeyChildren.put(orderKeyNode, sameKeyBag); } sameKeyBag.add(node); childrenKeys.put(node, orderKeyNode); } private void setupElementChildren(Node elementNode, Element element) { Node childrenOrderProperty = GraphUtils.getSingleValueOptProperty(graph, elementNode, XML.childrenOrderedBy.asNode()); if (childrenOrderProperty != null) dom2childrenOrderProperty.put(element, childrenOrderProperty); boolean ascendingOrder = !graph.contains(elementNode, XML.childrenOrderType.asNode(), XML.Descending.asNode()); if (!ascendingOrder) dom2descendingOrder.add(element); ExtendedIterator<Node> children = GraphUtils.getPropertyValues(graph, elementNode, XML.hasChild.asNode()); { NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren = new TreeMap<Node, Vector<org.w3c.dom.Node>>(nodeComparator); Map<org.w3c.dom.Node, Node> childrenKeys = new HashMap<org.w3c.dom.Node, Node>(); dom2orderedByKeyChildren.put(element, orderedByKeyChildren); dom2childrenKeys.put(element, childrenKeys); } // Set<org.w3c.dom.Node> noKeyChildren = new HashSet<org.w3c.dom.Node>(); while (children.hasNext()) { Node child = children.next(); // if (!orderedChildren.contains(child)) { org.w3c.dom.Node domChild = decodeNode(child); if (domChild != null) { // addNodeMapping(child, domChild); Node orderKeyNode = ( childrenOrderProperty != null ) ? GraphUtils.getSingleValueOptProperty(graph, child, childrenOrderProperty) : GraphUtils.getSingleValueOptProperty(graph, child, XML.orderKey.asNode()); // if (orderKeyNode == null) { //// noKeyChildren.add(domChild); // orderKeyNode = Node.NULL; // } //else { updateChildByKey(element, domChild, orderKeyNode); // Vector<org.w3c.dom.Node> sameKeyBag = orderedByKeyChildren.get(orderKeyNode); // if (sameKeyBag == null) { // sameKeyBag = new Vector<org.w3c.dom.Node>(); // orderedByKeyChildren.put(orderKeyNode, sameKeyBag); // } // sameKeyBag.add(domChild); // } } // } } Iterator<Node> textContentNodes = GraphUtils.getPropertyValues(graph, elementNode, XML.textContent.asNode()); if (textContentNodes.hasNext()) { String textContent = ""; while (textContentNodes.hasNext()) { Node textContentNode = textContentNodes.next(); if (textContentNode.isLiteral()) textContent += textContentNode.getLiteralLexicalForm(); } dom2textContent.put(element, textContent); } else if (dom2textContent.containsKey(element)) { dom2textContent.remove(element); element.setTextContent(""); } reorder(/*noKeyChildren, */ascendingOrder, element, dom2orderedByKeyChildren.get(element)); } private void setAttr(Element element, Node attrNode, Node object) { Attr attr = decodeAttr(attrNode); if (object.isLiteral()) attr.setValue(object.getLiteralLexicalForm()); else if (object.isURI()) { org.w3c.dom.Node domNode = decodeIfNode(object,true); if (domNode != null && (domNode instanceof Element)) { attr.setValue("#" + ((Element) domNode).getAttribute("id")); } else { attr.setValue(object.getURI()); } } element.setAttributeNodeNS(attr); } private void decodeElementAttrsAndChildren(final Element element, final Node elementNode) { ExtendedIterator<Triple> triples = graph.find(elementNode, Node.ANY, Node.ANY); while (triples.hasNext()) { Triple t = triples.next(); if ( predicateIsAttr(graph, t.getPredicate()) ) { setAttr(element, t.getPredicate(), t.getObject()); } } if (elementNode.isURI()) { element.setAttribute("resource", elementNode.getURI()); if (!element.hasAttribute("id")) element.setAttribute("id", newElementId()); // element.setAttribute("id", elementNode.getURI()); } // Set<Node> orderedChildren = new HashSet<Node>(); // { // Node child = GraphUtils.getSingleValueOptProperty(graph, elementNode, XML.firstChild.asNode()); // while (child != null) { // orderedChildren.add(child); // org.w3c.dom.Node newChild = decodeNode(graph, child); // if (newChild != null) { // addNodeMapping(child, newChild); // element.appendChild(newChild); // } // child = GraphUtils.getSingleValueOptProperty(graph, child, XML.nextSibling.asNode()); // } // } // System.out.println("Looking for eventListeners in element " + element + " (" + elementNode + ")"); Iterator<Node> eventTypeNodes = GraphUtils.getPropertyValues(graph, elementNode, XML.listenedEventType.asNode()); while (eventTypeNodes.hasNext()) { Node eventTypeNode = eventTypeNodes.next(); if (eventTypeNode.isLiteral()) { String eventType = eventTypeNode.getLiteralLexicalForm(); // System.out.println("Registering eventListener for type " + eventTypeNode.getLiteralLexicalForm() + " in element " + element + " (" + elementNode + ")"); // ((EventTarget) element).addEventListener(eventType, this, false); logger.trace("Calling addEventListener() for new node"); eventManager.addEventListener(elementNode, element, eventType, this, false); // Set<Element> elemsForEventType = eventType2elements.get(eventType); // if (elemsForEventType == null) { // elemsForEventType = new HashSet<Element>(); // eventType2elements.put(eventType, elemsForEventType); // ((EventTarget) document).addEventListener(eventType, this, false); // } // elemsForEventType.add(element); // // Set<String> eventTypesForElement = element2eventTypes.get(element); // if (eventTypesForElement == null) { // eventTypesForElement = new HashSet<String>(); // element2eventTypes.put(element, eventTypesForElement); // } // eventTypesForElement.add(eventType); } } setupElementChildren(elementNode, element); } private Element decodeElement(final Node elementNode, boolean forRef) { Element element = document.createElementNS( namespaceElement(graph, elementNode), qNameElement(graph, elementNode) ); if (forRef) addNodeRefMapping(elementNode, element); else addNodeMapping(elementNode, element); decodeElementAttrsAndChildren(element, elementNode); return element; } private org.w3c.dom.Node decodeIfNode(Node elementNode, boolean forRef) { org.w3c.dom.Node domNode = graph2domNodeMappingRef.get(elementNode); if (domNode != null) { if (!forRef) { Set<org.w3c.dom.Node> domeNodeSet = graph2domNodeMapping.get(elementNode); if (domeNodeSet == null) { domeNodeSet = new HashSet<org.w3c.dom.Node>(); graph2domNodeMapping.put(elementNode, domeNodeSet); } domeNodeSet.add(domNode); graph2domNodeMappingRef.remove(elementNode); } return domNode; } if (forRef) { Set<org.w3c.dom.Node> domNodeSet = graph2domNodeMapping.get(elementNode); if (domNodeSet != null && !domNodeSet.isEmpty()) return domNodeSet.iterator().next(); } ExtendedIterator<Node> nodeTypes = GraphUtils.getPropertyValues(graph, elementNode, RDF.type.asNode()); Node nodeType; while(nodeTypes.hasNext()) { nodeType = nodeTypes.next(); if ( nodeTypeIsElementType(graph, nodeType) ) return decodeElement(elementNode, forRef); if ( nodeType.equals( XML.Text.asNode() ) ) return decodeText(graph, elementNode); } return null; } private org.w3c.dom.Node decodeNode(Node elementNode) { org.w3c.dom.Node node = decodeIfNode(elementNode, false); if (node == null) throw new RuntimeException("DOM Type not found for node " + elementNode); else return node; } private void decodeDocument(Node docRootNode) { Iterator<Node> possibleDocs = GraphUtils.getPropertyValues(graph, docRootNode, XML.hasChild.asNode()); while (possibleDocs.hasNext()) { // try { Node elementNode = possibleDocs.next(); document = domImplementation.createDocument( namespaceElement(graph, elementNode), qNameElement(graph, elementNode), null); if (docRootNode.isURI()) document.setDocumentURI(docRootNode.getURI()); Element docElement = document.getDocumentElement(); addNodeMapping(docRootNode, document); addNodeMapping(elementNode, docElement); decodeElementAttrsAndChildren( docElement, elementNode ); // } catch(RuntimeException e) { } } } private void redecodeDocument(Node docRootNode) { graph2domNodeMapping = new HashMap<Node, Set<org.w3c.dom.Node>>(); graph2domNodeMappingRef = new HashMap<Node, org.w3c.dom.Node>(); dom2graphNodeMapping = new HashMap<org.w3c.dom.Node, Node>(); // eventType2elements = new HashMap<String, Set<Element>>(); // element2eventTypes = new HashMap<Element, Set<String>>(); decodeDocument(docRootNode); if (docReceiver != null) docReceiver.sendDocument(document); } private void redecodeDocument() { redecodeDocument( graph .find(SWI.GraphRoot.asNode(), XML.document.asNode(), Node.ANY) .mapWith(t -> t.getObject()) .andThen( graph .find(Node.ANY, RDF.type.asNode(), XML.Document.asNode()) .mapWith(t-> t.getSubject()) ) .next()); } private void decodeWorker(DynamicGraph graph, Node docRootNode) { logger.debug("decoding document from " + Utils.standardStr(graph) + " ..."); decodeDocument(docRootNode); logger.debug("registering as listener of " + Utils.standardStr(graph) + " ..."); graph.getEventManager2().register(this); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl) { return (new DomDecoder(graph, docRootNode, domImpl)).getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, EventManager eventManager) { return (new DomDecoder(graph, docRootNode, domImpl, eventManager)).getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext) { return (new DomDecoder(graph, docRootNode, domImpl, updatesContext)).getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext, EventManager eventManager) { return (new DomDecoder(graph, docRootNode, domImpl, updatesContext, eventManager)).getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, DocumentReceiver docReceiver) { return (new DomDecoder(graph, docRootNode, domImpl, docReceiver)).getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, DocumentReceiver docReceiver, EventManager eventManager) { return (new DomDecoder(graph, docRootNode, domImpl, docReceiver, eventManager)).getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext, DocumentReceiver docReceiver) { return (new DomDecoder(graph, docRootNode, domImpl, updatesContext, docReceiver)).getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext, DocumentReceiver docReceiver, EventManager eventManager) { return (new DomDecoder(graph, docRootNode, domImpl, updatesContext, docReceiver, eventManager)).getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, Map<String,Set<DomEventListener>> domEventListeners) { DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl); if (domEventListeners != null) for (String eventType : domEventListeners.keySet()) for (DomEventListener listener : domEventListeners.get(eventType)) domDecoder.addDomEventListener(eventType, listener); return domDecoder.getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, eventManager); if (domEventListeners != null) for (String eventType : domEventListeners.keySet()) for (DomEventListener listener : domEventListeners.get(eventType)) domDecoder.addDomEventListener(eventType, listener); return domDecoder.getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext, Map<String,Set<DomEventListener>> domEventListeners) { DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, updatesContext); if (domEventListeners != null) for (String eventType : domEventListeners.keySet()) for (DomEventListener listener : domEventListeners.get(eventType)) domDecoder.addDomEventListener(eventType, listener); return domDecoder.getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, updatesContext, eventManager); if (domEventListeners != null) for (String eventType : domEventListeners.keySet()) for (DomEventListener listener : domEventListeners.get(eventType)) domDecoder.addDomEventListener(eventType, listener); return domDecoder.getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, DocumentReceiver docReceiver, Map<String,Set<DomEventListener>> domEventListeners) { DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, docReceiver); if (domEventListeners != null) for (String eventType : domEventListeners.keySet()) for (DomEventListener listener : domEventListeners.get(eventType)) domDecoder.addDomEventListener(eventType, listener); return domDecoder.getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, DocumentReceiver docReceiver, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, docReceiver, eventManager); if (domEventListeners != null) for (String eventType : domEventListeners.keySet()) for (DomEventListener listener : domEventListeners.get(eventType)) domDecoder.addDomEventListener(eventType, listener); return domDecoder.getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext, DocumentReceiver docReceiver, Map<String,Set<DomEventListener>> domEventListeners) { DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, updatesContext, docReceiver); if (domEventListeners != null) for (String eventType : domEventListeners.keySet()) for (DomEventListener listener : domEventListeners.get(eventType)) domDecoder.addDomEventListener(eventType, listener); return domDecoder.getDocument(); } public static Document decode( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext, DocumentReceiver docReceiver, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, updatesContext, docReceiver, eventManager); if (domEventListeners != null) for (String eventType : domEventListeners.keySet()) for (DomEventListener listener : domEventListeners.get(eventType)) domDecoder.addDomEventListener(eventType, listener); return domDecoder.getDocument(); } public static Document decodeOne(DynamicGraph graph, DOMImplementation domImpl) { return decodeAll(graph, domImpl).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, EventManager eventManager) { return decodeAll(graph, domImpl, eventManager).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, RunnableContext updatesContext) { return decodeAll(graph, domImpl, updatesContext).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, RunnableContext updatesContext, EventManager eventManager) { return decodeAll(graph, domImpl, updatesContext, eventManager).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, DocumentReceiver docReceiver) { return decodeAll(graph, domImpl, docReceiver).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, DocumentReceiver docReceiver, EventManager eventManager) { return decodeAll(graph, domImpl, docReceiver, eventManager).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, RunnableContext updatesContext, DocumentReceiver docReceiver) { return decodeAll(graph, domImpl, updatesContext, docReceiver).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, RunnableContext updatesContext, DocumentReceiver docReceiver, EventManager eventManager) { return decodeAll(graph, domImpl, updatesContext, docReceiver, eventManager).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, Map<String,Set<DomEventListener>> domEventListeners) { return decodeAll(graph, domImpl, domEventListeners).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { return decodeAll(graph, domImpl, domEventListeners, eventManager).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, RunnableContext updatesContext, Map<String,Set<DomEventListener>> domEventListeners) { return decodeAll(graph, domImpl, updatesContext, domEventListeners).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, RunnableContext updatesContext, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { return decodeAll(graph, domImpl, updatesContext, domEventListeners, eventManager).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, DocumentReceiver docReceiver, Map<String,Set<DomEventListener>> domEventListeners) { return decodeAll(graph, domImpl, docReceiver, domEventListeners).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, DocumentReceiver docReceiver, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { return decodeAll(graph, domImpl, docReceiver, domEventListeners, eventManager).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, RunnableContext updatesContext, DocumentReceiver docReceiver, Map<String,Set<DomEventListener>> domEventListeners) { return decodeAll(graph, domImpl, updatesContext, docReceiver, domEventListeners).next(); } public static Document decodeOne( DynamicGraph graph, DOMImplementation domImpl, RunnableContext updatesContext, DocumentReceiver docReceiver, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { return decodeAll(graph, domImpl, updatesContext, docReceiver, domEventListeners, eventManager).next(); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl) { return decodeAll(graph, domImpl, (RunnableContext) null); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, EventManager eventManager) { return decodeAll(graph, domImpl, (RunnableContext) null, eventManager); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final DocumentReceiver docReceiver) { return decodeAll(graph, domImpl, null, docReceiver); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final DocumentReceiver docReceiver, EventManager eventManager) { return decodeAll(graph, domImpl, null, docReceiver, eventManager); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final RunnableContext updatesContext) { return decodeAll(graph, domImpl, updatesContext, (DocumentReceiver) null); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final RunnableContext updatesContext, EventManager eventManager) { return decodeAll(graph, domImpl, updatesContext, (DocumentReceiver) null, eventManager); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final RunnableContext updatesContext, final DocumentReceiver docReceiver) { return decodeAll(graph, domImpl, updatesContext, docReceiver, (EventManager) null); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final RunnableContext updatesContext, final DocumentReceiver docReceiver, EventManager eventManager) { return decodeAll(graph, domImpl, updatesContext, docReceiver, null, eventManager); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, Map<String,Set<DomEventListener>> domEventListeners) { return decodeAll(graph, domImpl, (RunnableContext) null, domEventListeners); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { return decodeAll(graph, domImpl, (RunnableContext) null, domEventListeners, eventManager); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final DocumentReceiver docReceiver, Map<String,Set<DomEventListener>> domEventListeners) { return decodeAll(graph, domImpl, null, docReceiver, domEventListeners); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final DocumentReceiver docReceiver, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { return decodeAll(graph, domImpl, null, docReceiver, domEventListeners, eventManager); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final RunnableContext updatesContext, Map<String,Set<DomEventListener>> domEventListeners) { return decodeAll(graph, domImpl, updatesContext, null, domEventListeners); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final RunnableContext updatesContext, Map<String,Set<DomEventListener>> domEventListeners, EventManager eventManager) { return decodeAll(graph, domImpl, updatesContext, null, domEventListeners, eventManager); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final RunnableContext updatesContext, final DocumentReceiver docReceiver, final Map<String,Set<DomEventListener>> domEventListeners) { return decodeAll(graph, domImpl, updatesContext, docReceiver, domEventListeners, null); } public static ExtendedIterator<Document> decodeAll( final DynamicGraph graph, final DOMImplementation domImpl, final RunnableContext updatesContext, final DocumentReceiver docReceiver, final Map<String,Set<DomEventListener>> domEventListeners, final EventManager eventManager) { return graph .find(SWI.GraphRoot.asNode(), XML.document.asNode(), Node.ANY) .mapWith(t -> t.getObject()) .andThen( graph .find(Node.ANY, RDF.type.asNode(), XML.Document.asNode()) .mapWith(t -> t.getSubject()) ) .mapWith( node -> decode( graph, node, domImpl, updatesContext, docReceiver, domEventListeners, eventManager) ); } private void addNodeMapping(Node graphNode, org.w3c.dom.Node domNode) { // System.out.println(this + ": adding mapping ( " + graphNode + " -> " + domNode + " )"); Set<org.w3c.dom.Node> domeNodeSet = graph2domNodeMapping.get(graphNode); if (domeNodeSet == null) { domeNodeSet = new HashSet<org.w3c.dom.Node>(); graph2domNodeMapping.put(graphNode, domeNodeSet); } domeNodeSet.add(domNode); dom2graphNodeMapping.put(domNode, graphNode); } private void addNodeRefMapping(Node graphNode, org.w3c.dom.Node domNode) { // System.out.println(this + ": adding mapping ( " + graphNode + " -> " + domNode + " )"); graph2domNodeMappingRef.put(graphNode, domNode); dom2graphNodeMapping.put(domNode, graphNode); } private void removeNodeMapping(org.w3c.dom.Node domNode) { Node graphNode = dom2graphNodeMapping.get(domNode); if (graphNode != null) { dom2graphNodeMapping.remove(domNode); Set<org.w3c.dom.Node> domeNodeSet = graph2domNodeMapping.get(graphNode); domeNodeSet.remove(domNode); if (domeNodeSet.isEmpty()) { graph2domNodeMapping.remove(graphNode); } // graph2domNodeMappingRef.remove(graphNode); // } else // if (graph2domNodeMappingRef.get(graphNode).equals(domNode)) // graph2domNodeMappingRef.put(graphNode, domeNodeSet.iterator().next()); } dom2orderedByKeyChildren.remove(domNode); dom2childrenOrderProperty.remove(domNode); dom2descendingOrder.remove(domNode); dom2textContent.remove(domNode); } private void removeSubtreeMapping(org.w3c.dom.Node domNode) { // System.out.println(this + ": removing subtree mapping of " + domNode ); removeNodeMapping(domNode); NamedNodeMap attrMap = domNode.getAttributes(); if (attrMap != null) { for (int i = 0; i < attrMap.getLength(); i++) { removeSubtreeMapping(attrMap.item(i)); } } NodeList children = domNode.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { removeSubtreeMapping(children.item(i)); } } // if (domNode instanceof Element) { // Element element = (Element) domNode; // Set<String> eventTypesForElement = element2eventTypes.get(element); // if (eventTypesForElement != null) { // for (String eventType : eventTypesForElement) { // Set<Element> elementsForEventType = eventType2elements.get(eventType); // elementsForEventType.remove(element); // if (elementsForEventType.isEmpty()) { // eventType2elements.remove(eventType); // ((EventTarget) document).removeEventListener(eventType, DomDecoder2.this, false); // } // } // element2eventTypes.remove(element); // } // } } // private DomDecoder(DynamicGraph graph) { // this.graph = graph; // this.updatesContext = this; // } // private DomDecoder(DomDecoder domDecoder) { this.graph = domDecoder.graph; this.elementCount = domDecoder.elementCount; this.docRootNode = domDecoder.docRootNode; this.domImplementation = domDecoder.domImplementation; this.dom2childrenKeys = domDecoder.dom2childrenKeys; this.dom2childrenOrderProperty = domDecoder.dom2childrenOrderProperty; this.dom2textContent = domDecoder.dom2textContent; this.dom2descendingOrder = domDecoder.dom2descendingOrder; this.dom2graphNodeMapping = domDecoder.dom2graphNodeMapping; this.dom2orderedByKeyChildren = domDecoder.dom2orderedByKeyChildren; this.eventManager = domDecoder.eventManager; this.updatesContext = this; } private DomDecoder( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl) { this(graph, docRootNode, domImpl, (DocumentReceiver) null); } private DomDecoder( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, EventManager eventManager) { this(graph, docRootNode, domImpl, (DocumentReceiver) null, eventManager); } private DomDecoder( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, DocumentReceiver docReceiver) { this(graph, docRootNode, domImpl, null, docReceiver); } private DomDecoder( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, DocumentReceiver docReceiver, EventManager eventManager) { this(graph, docRootNode, domImpl, null, docReceiver, eventManager); } private DomDecoder( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext) { this(graph, docRootNode, domImpl, updatesContext,DEFAULT_EVENT_MANAGER); } private DomDecoder( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext, EventManager eventManager) { this(graph, docRootNode, domImpl, updatesContext, null, eventManager); } private DomDecoder( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext, DocumentReceiver docReceiver) { this(graph, docRootNode, domImpl, updatesContext, docReceiver, DEFAULT_EVENT_MANAGER); } private DomDecoder( DynamicGraph graph, Node docRootNode, DOMImplementation domImpl, RunnableContext updatesContext, DocumentReceiver docReceiver, EventManager eventManager) { this.graph = graph; this.domImplementation = domImpl; this.updatesContext = ( updatesContext == null ? this : updatesContext ); this.docReceiver = docReceiver; this.eventManager = eventManager; this.docRootNode = docRootNode; decodeWorker(graph, docRootNode); } public void run(Runnable runnable) { runnable.run(); } private Document getDocument() { return document; } private void orderChild(org.w3c.dom.Node node, Element parent, Node orderKeyNode) { putChildByKey(parent, node, orderKeyNode); NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren = dom2orderedByKeyChildren.get(parent); if (!dom2descendingOrder.contains(parent)) { Entry<Node, Vector<org.w3c.dom.Node>> nextEntry = orderedByKeyChildren.higherEntry(orderKeyNode); if (nextEntry == null) { parent.appendChild(node); } else { parent.insertBefore(node, nextEntry.getValue().firstElement()); } } else { Entry<Node, Vector<org.w3c.dom.Node>> nextEntry = orderedByKeyChildren.lowerEntry(orderKeyNode); if (nextEntry == null) { parent.appendChild(node); } else { parent.insertBefore(node, nextEntry.getValue().firstElement()); } } } private void reorderChild(org.w3c.dom.Node node, Element parent, Node orderKeyNode) { orderChild(node, parent, orderKeyNode); } private void insertChildInOrder(org.w3c.dom.Node child, Node childNode, Element parent) { Node childrenOrderProperty = dom2childrenOrderProperty.get(parent); Node orderKeyNode = ( childrenOrderProperty != null ) ? GraphUtils.getSingleValueOptProperty(graph, childNode, childrenOrderProperty) : GraphUtils.getSingleValueOptProperty(graph, childNode, XML.orderKey.asNode()); orderChild(child, parent, orderKeyNode); } private void removeChild(org.w3c.dom.Node node, Element parent) { removeChildByKey(parent, node); parent.removeChild(node); } private boolean mustReorderAllChildrenOf(Element parent, GraphUpdate update) { Node parentNode = dom2graphNodeMapping.get(parent); return update.getAddedGraph().contains(parentNode, XML.childrenOrderedBy.asNode(), Node.ANY) || update.getAddedGraph().contains(parentNode, XML.childrenOrderType.asNode(), Node.ANY) || update.getDeletedGraph().contains(parentNode, XML.childrenOrderedBy.asNode(), Node.ANY) || update.getDeletedGraph().contains(parentNode, XML.childrenOrderType.asNode(), Node.ANY); } public synchronized void notifyUpdate(final Graph sourceGraph, final GraphUpdate update) { logger.debug("Begin of Notify Update in DOM Decoder"); if (!update.getAddedGraph().isEmpty() || !update.getDeletedGraph().isEmpty()) { updatesContext.run( new Runnable() { @SuppressWarnings("unchecked") public void run() { ExtendedIterator<Triple> addEventsIter = update.getAddedGraph().find(Node.ANY, Node.ANY, Node.ANY); DomDecoder newDom = new DomDecoder(DomDecoder.this); newDom.dom2graphNodeMapping = (Map<org.w3c.dom.Node, Node>) ((HashMap<org.w3c.dom.Node, Node>) dom2graphNodeMapping).clone(); // newDom.graph2domNodeMapping = (Map<Node, Set<org.w3c.dom.Node>>) ((HashMap<Node, Set<org.w3c.dom.Node>>) graph2domNodeMapping).clone(); for (Node key : graph2domNodeMapping.keySet()) { newDom.graph2domNodeMapping.put(key, (Set<org.w3c.dom.Node>) ((HashSet<org.w3c.dom.Node>) graph2domNodeMapping.get(key)).clone()); } newDom.document = document; // newDom.document = (Document) document.cloneNode(true); while (addEventsIter.hasNext()) { final Triple newTriple = addEventsIter.next(); // org.w3c.dom.Node xmlSubj = nodeMapping.get(newTriple.getSubject()); //System.out.println("Checking add event " + newTriple); Set<org.w3c.dom.Node> domSubjs = graph2domNodeMapping.get(newTriple.getSubject()); // if (domSubjs == null) // logger.warn(this + ": managing add event " + newTriple + ", domSubjs is null"); if (domSubjs != null) { logger.trace("Managing add event " + newTriple + " for domSubjs " + domSubjs); Set<org.w3c.dom.Node> domSubjsTemp = new HashSet<org.w3c.dom.Node>(); domSubjsTemp.addAll(domSubjs); Iterator<org.w3c.dom.Node> domSubjIter = domSubjsTemp.iterator(); // Basic properties: DOM node must be recreated if (newTriple.getPredicate().equals(RDF.type.asNode()) || newTriple.getPredicate().equals(XML.nodeName.asNode())) { //org.w3c.dom.Node parentNode = null; Node nodeType = newTriple.getObject(); if ( nodeTypeIsElementType(graph,nodeType) ) { while (domSubjIter.hasNext()) { org.w3c.dom.Node domSubj = domSubjIter.next(); org.w3c.dom.Node parentNode = domSubj.getParentNode(); if (parentNode != null) { org.w3c.dom.Node newNode = newDom.decodeNode(newTriple.getSubject()); parentNode.replaceChild(newNode, domSubj); newDom.removeSubtreeMapping(domSubj); // newDom.addNodeMapping(newTriple.getSubject(), newNode); } } } else if (nodeIsRootDocument(graph,nodeType,newTriple.getSubject())) { redecodeDocument(newTriple.getSubject()); return; } // Predicate is a DOM Attribute } else if ( predicateIsAttr(graph, newTriple.getPredicate()) ) { while (domSubjIter.hasNext()) { Element element = (Element) domSubjIter.next(); // Attr newAttr = newDom.decodeAttr(newTriple.getPredicate()); // newDom.addNodeMapping(newTriple.getPredicate(), newAttr); setAttr(element, newTriple.getPredicate(), newTriple.getObject()); // newAttr.setValue(newTriple.getObject().getLiteralLexicalForm()); // element.setAttributeNodeNS(newAttr); } // Predicate is xml:hasChild } else if ( newTriple.getPredicate().equals(XML.hasChild.asNode()) ) { Node nodeType = graph .find(newTriple.getSubject(), XML.nodeType.asNode(), Node.ANY) .next().getObject(); logger.trace("Managing add hasChild (" + newTriple + ") for domSubjs " + domSubjs + " and node type " + nodeType); if (nodeTypeIsElementType(graph,nodeType)) { while (domSubjIter.hasNext()) { Element element = (Element) domSubjIter.next(); org.w3c.dom.Node newChild = newDom.decodeNode(newTriple.getObject()); // newDom.addNodeMapping(newTriple.getObject(), newChild); // element.appendChild(newChild); insertChildInOrder(newChild, newTriple.getObject(), element); } } else if (nodeIsRootDocument(graph,nodeType,newTriple.getSubject())) { redecodeDocument(newTriple.getSubject()); return; } // Predicate is xml:nodeValue } else if ( newTriple.getPredicate().equals(XML.nodeValue.asNode()) ) { logger.trace("Managing add nodeValue (" + newTriple + ") for domSubjs " + domSubjs); while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); node.setNodeValue(newTriple.getObject().getLiteralLexicalForm()); } // Predicate is orderKey } else if ( newTriple.getPredicate().equals(XML.orderKey.asNode()) ) { logger.trace("Managing add orderKey (" + newTriple + ") for domSubjs " + domSubjs); while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); org.w3c.dom.Node parent = node.getParentNode(); if ( parent != null && parent instanceof Element && !mustReorderAllChildrenOf((Element) parent, update) ) { Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent); if ( childrenOrderProperty == null || childrenOrderProperty.equals(XML.orderKey.asNode()) ) { Node orderKeyNode = newTriple.getObject(); reorderChild(node, (Element) parent, orderKeyNode); } } } // Predicate xml:childrenOrderType and object xml:Descending } else if ( newTriple.getPredicate().equals(XML.childrenOrderType.asNode()) && newTriple.getObject().equals(XML.Descending) && !update.getAddedGraph().contains(newTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY)) { logger.trace("Managing add childrenOrderType (" + newTriple + ") for domSubjs " + domSubjs); while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); if (node instanceof Element) { NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren = dom2orderedByKeyChildren.get(node); if (!dom2descendingOrder.contains(node)) { dom2descendingOrder.add((Element) node); reorder(false, (Element) node, orderedByKeyChildren); } } } // Predicate xml:childrenOrderedBy } else if ( newTriple.getPredicate().equals(XML.childrenOrderedBy.asNode()) ) { logger.trace("Managing add childrenOrderedBy (" + newTriple + ") for domSubjs " + domSubjs); while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); if (node instanceof Element) setupElementChildren(newTriple.getSubject(), (Element) node); } // Predicate textContent } else if ( newTriple.getPredicate().equals(XML.textContent.asNode()) ) { logger.trace("Managing add textContent (" + newTriple + ") for domSubjs " + domSubjs); while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); if (node instanceof Element) setupElementChildren(newTriple.getSubject(), (Element) node); } // Predicate is xml:listenedEventType } else if ( newTriple.getPredicate().equals(XML.listenedEventType.asNode()) ) { Node eventTypeNode = newTriple.getObject(); if (eventTypeNode.isLiteral()) { while (domSubjIter.hasNext()) { Element element = (Element) domSubjIter.next(); logger.trace("On add, registering eventListener for type " + eventTypeNode.getLiteralLexicalForm() + " in element " + element /*+ " (" + elementNode + ")"*/); // ((EventTarget) element).addEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false); eventManager.addEventListener( newTriple.getSubject(), element, eventTypeNode.getLiteralLexicalForm(), DomDecoder.this, false); // Set<Element> elemsForEventType = eventType2elements.get(eventType); // if (elemsForEventType == null) { // elemsForEventType = new HashSet<Element>(); // eventType2elements.put(eventType, elemsForEventType); // ((EventTarget) document).addEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false); // } // elemsForEventType.add(element); // // Set<String> eventTypesForElement = element2eventTypes.get(element); // if (eventTypesForElement == null) { // eventTypesForElement = new HashSet<String>(); // element2eventTypes.put(element, eventTypesForElement); // } // eventTypesForElement.add(eventType); } } } // Predicate is the childrenOrderedBy for some parent while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); org.w3c.dom.Node parent = node.getParentNode(); if ( parent != null && parent instanceof Element ) { Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent); if ( childrenOrderProperty != null && childrenOrderProperty.equals(newTriple.getPredicate()) && !mustReorderAllChildrenOf((Element) parent, update) ) { logger.trace("Managing add predicate is the childrenOrderedBy for some parent (" + newTriple + ")"); Node orderKeyNode = newTriple.getObject(); reorderChild(node, (Element) parent, orderKeyNode); } } } } } ExtendedIterator<Triple> deleteEventsIter = update.getDeletedGraph().find(Node.ANY, Node.ANY, Node.ANY); while (deleteEventsIter.hasNext()) { Triple oldTriple = deleteEventsIter.next(); //org.w3c.dom.Node xmlSubj = nodeMapping.get(oldTriple.getSubject()); Set<org.w3c.dom.Node> domSubjs = graph2domNodeMapping.get(oldTriple.getSubject()); //System.out.println("Checking for " + oldTriple.getSubject() + " contained in " + sourceGraph); if (domSubjs != null && graph.contains(oldTriple.getSubject(), RDF.type.asNode(), Node.ANY)) { //System.out.println("Found " + oldTriple.getSubject() + " contained in " + sourceGraph); //System.out.println("Managing " + oldTriple.getPredicate() + "/" + oldTriple.getObject()); Iterator<org.w3c.dom.Node> domSubjIter = domSubjs.iterator(); if ( ( oldTriple.getPredicate().equals(XML.nodeName.asNode()) && !update.getAddedGraph().contains(oldTriple.getSubject(), XML.nodeName.asNode(), Node.ANY) ) || ( oldTriple.getPredicate().equals(XML.nodeType.asNode()) && !update.getAddedGraph().contains(oldTriple.getSubject(), XML.nodeType.asNode(), Node.ANY) ) ) { while (domSubjIter.hasNext()) { org.w3c.dom.Node domSubj = domSubjIter.next(); switch (domSubj.getNodeType()) { case org.w3c.dom.Node.ATTRIBUTE_NODE: Attr oldAttr = (Attr) domSubj; Element ownerElement = oldAttr.getOwnerElement(); ownerElement.removeAttributeNode(oldAttr); newDom.removeSubtreeMapping(oldAttr); break; case org.w3c.dom.Node.DOCUMENT_NODE: if ( oldTriple.getSubject().equals(docRootNode) ) { redecodeDocument(); return; } break; default: org.w3c.dom.Node parentNode = domSubj.getParentNode(); if (parentNode != null) { parentNode.removeChild(domSubj); newDom.removeSubtreeMapping(domSubj); } } } } else if ( oldTriple.getPredicate().equals(XML.nodeValue.asNode()) && !graph.contains(oldTriple.getSubject(), XML.nodeValue.asNode(), Node.ANY)) { while (domSubjIter.hasNext()) { org.w3c.dom.Node domSubj = domSubjIter.next(); domSubj.setNodeValue(""); } } else if ( predicateIsAttr(graph, oldTriple.getPredicate()) && !update.getAddedGraph().contains(oldTriple.getSubject(), oldTriple.getPredicate(), Node.ANY) ) { while (domSubjIter.hasNext()) { Element element = (Element) domSubjIter.next(); newDom.removeAttr(element, oldTriple.getPredicate()); } // Set<org.w3c.dom.Node> domObjsOrig = graph2domNodeMapping.get(oldTriple.getObject()); // if (domObjsOrig != null) { // Set<org.w3c.dom.Node> domObjs = new HashSet<org.w3c.dom.Node>(); // domObjs.addAll(domObjsOrig); // while (domSubjIter.hasNext()) { // Element element = (Element) domSubjIter.next(); // Iterator<org.w3c.dom.Node> domObjsIter = domObjs.iterator(); // while (domObjsIter.hasNext()) { // try { // Attr oldAttr = (Attr) domObjsIter.next(); // if ( oldAttr.getNamespaceURI() == null // ? element.hasAttribute(oldAttr.getName()) // : element.hasAttributeNS(oldAttr.getNamespaceURI(), oldAttr.getLocalName())) // element.removeAttributeNode(oldAttr); // newDom.removeSubtreeMapping(oldAttr); // } catch(DOMException e) { // if (!e.equals(DOMException.NOT_FOUND_ERR)) // throw e; // } // } // } // } } else if ( oldTriple.getPredicate().equals(XML.hasChild.asNode()) ) { while (domSubjIter.hasNext()) { org.w3c.dom.Node domSubj = domSubjIter.next(); if ( domSubj.getNodeType() == org.w3c.dom.Node.DOCUMENT_NODE && oldTriple.getSubject().equals(docRootNode) ) { redecodeDocument(); return; } Set<org.w3c.dom.Node> domObjs = graph2domNodeMapping.get(oldTriple.getObject()); if (domObjs != null) { Element element = (Element) domSubj; Iterator<org.w3c.dom.Node> domObjsIter = domObjs.iterator(); while (domObjsIter.hasNext()) { try { org.w3c.dom.Node domObj = domObjsIter.next(); removeChild(domObj, element); newDom.removeSubtreeMapping(domObj); } catch(DOMException e) { if (!e.equals(DOMException.NOT_FOUND_ERR)) throw e; } } } } // Predicate is orderKey } else if ( oldTriple.getPredicate().equals(XML.orderKey.asNode()) && !update.getAddedGraph().contains(oldTriple.getSubject(), XML.orderKey.asNode(), Node.ANY) ) { logger.trace("Managing delete orderKey (" + oldTriple + ") for domSubjs " + domSubjs); while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); org.w3c.dom.Node parent = node.getParentNode(); if ( parent != null && parent instanceof Element && !mustReorderAllChildrenOf((Element) parent, update) ) { Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent); if ( childrenOrderProperty == null || childrenOrderProperty.equals(XML.orderKey.asNode()) ) { Node orderKeyNode = oldTriple.getObject(); reorderChild(node, (Element) parent, orderKeyNode); } } } // Predicate xml:childrenOrderType and object xml:Descending } else if ( oldTriple.getPredicate().equals(XML.childrenOrderType.asNode()) && oldTriple.getObject().equals(XML.Descending) && !update.getAddedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY) && !update.getDeletedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY) ) { logger.trace("Managing delete childrenOrderType (" + oldTriple + ") for domSubjs " + domSubjs); while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); if (node instanceof Element) { NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren = dom2orderedByKeyChildren.get(node); if (dom2descendingOrder.contains(node)) { dom2descendingOrder.remove((Element) node); reorder(true, (Element) node, orderedByKeyChildren); } } } // Predicate xml:childrenOrderedBy } else if ( oldTriple.getPredicate().equals(XML.childrenOrderedBy.asNode()) && !update.getAddedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY) ) { logger.trace("Managing delete childrenOrderedBy (" + oldTriple + ") for domSubjs " + domSubjs); while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); if (node instanceof Element) setupElementChildren(oldTriple.getSubject(), (Element) node); } // Predicate xml:textContent } else if ( oldTriple.getPredicate().equals(XML.textContent.asNode()) && !update.getAddedGraph().contains(oldTriple.getSubject(), XML.textContent.asNode(), Node.ANY) && !update.getAddedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY) ) { logger.trace("Managing delete textContent (" + oldTriple + ") for domSubjs " + domSubjs); while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); if (node instanceof Element) setupElementChildren(oldTriple.getSubject(), (Element) node); } } else if ( oldTriple.getPredicate().equals(XML.listenedEventType.asNode()) ) { Node eventTypeNode = oldTriple.getObject(); if (eventTypeNode.isLiteral()) { while (domSubjIter.hasNext()) { Element element = (Element) domSubjIter.next(); // System.out.println("Registering eventListener for type " + eventTypeNode.getLiteralLexicalForm() + " in element " + element + " (" + elementNode + ")"); // ((EventTarget) element).removeEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false); eventManager.removeEventListener( oldTriple.getSubject(), element, eventTypeNode.getLiteralLexicalForm(), DomDecoder.this, false); // Set<Element> elemsForEventType = eventType2elements.get(eventType); // elemsForEventType.remove(element); // if (elemsForEventType.isEmpty()) { // eventType2elements.remove(eventType); // ((EventTarget) document).removeEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false); // } // // Set<String> eventTypesForElement = element2eventTypes.get(element); // eventTypesForElement.remove(eventType); // if (eventTypesForElement.isEmpty()) { // element2eventTypes.remove(element); // } } } } // Predicate is the childrenOrderedBy for some parent while (domSubjIter.hasNext()) { org.w3c.dom.Node node = domSubjIter.next(); org.w3c.dom.Node parent = node.getParentNode(); if ( parent != null && parent instanceof Element ) { Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent); if ( childrenOrderProperty != null && childrenOrderProperty.equals(oldTriple.getPredicate()) && !update.getAddedGraph().contains(oldTriple.getSubject(), childrenOrderProperty, Node.ANY) && !mustReorderAllChildrenOf((Element) parent, update) ) { logger.trace("Managing delete predicate that is the childrenOrderedBy for some parent (" + oldTriple + ")"); reorderChild(node, (Element) parent, null); } } } } // System.out.println("End of notifyEvents() in " + this); } dom2graphNodeMapping = newDom.dom2graphNodeMapping; graph2domNodeMapping = newDom.graph2domNodeMapping; // document = newDom.document; } }); } logger.debug("End of Notify Update in DOM Decoder"); } }
agpl-3.0
crosslink/xowa
dev/400_xowa/src/gplx/xowa/xtns/mapSources/Map_dd2dms_func_tst.java
1395
/* XOWA: the XOWA Offline Wiki Application Copyright (C) 2012 [email protected] This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package gplx.xowa.xtns.mapSources; import gplx.*; import gplx.xowa.*; import gplx.xowa.xtns.*; import org.junit.*; public class Map_dd2dms_func_tst { @Before public void init() {fxt.Reset();} private Xop_fxt fxt = new Xop_fxt(); @Test public void Example() {fxt.Test_parse_tmpl_str_test("{{#dd2dms: 14.58|precision=4}}" , "{{test}}" , "14° 34' 48&quot;");} @Test public void Plus() {fxt.Test_parse_tmpl_str_test("{{#dd2dms: 14.58|precision=4|plus=pos}}" , "{{test}}" , "14° 34' 48&quot; pos");} @Test public void Ws() {fxt.Test_parse_tmpl_str_test("{{#dd2dms: 14.58| precision = 4 | plus = pos }}" , "{{test}}" , "14° 34' 48&quot; pos");} }
agpl-3.0
asm-products/codes-snippet-manager
protected/modules/user/models/UserLogin.php
2241
<?php /** * LoginForm class. * LoginForm is the data structure for keeping * user login form data. It is used by the 'login' action of 'SiteController'. */ class UserLogin extends CFormModel { public $username; public $password; public $rememberMe; /** * Declares the validation rules. * The rules state that username and password are required, * and password needs to be authenticated. */ public function rules() { return array( // username and password are required array('username, password', 'required'), // rememberMe needs to be a boolean array('rememberMe', 'boolean'), // password needs to be authenticated array('password', 'authenticate'), ); } /** * Declares attribute labels. */ public function attributeLabels() { return array( 'rememberMe'=>UserModule::t("Remember me next time"), 'username'=>UserModule::t("username or email"), 'password'=>UserModule::t("password"), ); } /** * Authenticates the password. * This is the 'authenticate' validator as declared in rules(). */ public function authenticate($attribute,$params) { if(!$this->hasErrors()) // we only want to authenticate when no input errors { $identity=new UserIdentity($this->username,$this->password); $identity->authenticate(); switch($identity->errorCode) { case UserIdentity::ERROR_NONE: $duration=$this->rememberMe ? 3600*24*30 : 3600*24; // 30 days Yii::app()->user->login($identity,$duration); break; case UserIdentity::ERROR_EMAIL_INVALID: $this->addError("username",UserModule::t("Email is incorrect.")); break; case UserIdentity::ERROR_USERNAME_INVALID: $this->addError("username",UserModule::t("Username is incorrect.")); break; case UserIdentity::ERROR_STATUS_NOTACTIV: $this->addError("status",UserModule::t("You account is not activated.")); break; case UserIdentity::ERROR_STATUS_BAN: $this->addError("status",UserModule::t("You account is blocked.")); break; case UserIdentity::ERROR_PASSWORD_INVALID: $this->addError("password",UserModule::t("Password is incorrect.")); break; } } } }
agpl-3.0
zeropingheroes/lanager
routes/web.php
3412
<?php /** * Current LAN */ Route::get('/', 'CurrentLanController@show') ->name('home'); Route::get('/guides', 'CurrentLanController@guides') ->name('guides'); Route::get('/events', 'CurrentLanController@events') ->name('events'); Route::get('/schedule', 'CurrentLanController@schedule') ->name('schedule'); Route::get('/users', 'CurrentLanController@users') ->name('users'); Route::get('/user-achievements', 'CurrentLanController@userAchievements') ->name('users'); /** * Login */ Route::get('login', 'AuthController@showLoginForm') ->middleware(['guest']) ->name('login'); Route::get('auth/{provider}', 'AuthController@redirectToProvider') ->middleware(['guest']) ->name('auth'); Route::get('auth/{provider}/callback', 'AuthController@handleProviderCallback') ->middleware(['guest']) ->name('auth.callback'); /** * Logout */ Route::post('logout', 'AuthController@logout') ->middleware(['auth']) ->name('logout'); /** * Roles & Role Assignments */ Route::resource('role-assignments', 'RoleAssignmentController', ['except' => ['show', 'edit', 'update']]); /** * Logs */ Route::resource('logs', 'LogController', ['only' => ['index', 'show']]); Route::patch('logs', 'LogController@patch') ->name('logs.patch'); /** * Games */ Route::get('/games/in-progress', 'GameController@inProgress') ->name('games.in-progress'); Route::get('/games/recent', 'GameController@recent') ->name('games.recent'); Route::get('/games/owned', 'GameController@owned') ->name('games.owned'); Route::get('/games/fullscreen', function () { return view('pages.games.fullscreen'); })->name('games.fullscreen'); /** * LANs */ Route::resource('lans', 'LanController'); /** * Guides */ Route::resource('lans.guides', 'GuideController', ['except' => 'show']); Route::get('lans/{lan}/guides/{guide}/{slug?}', 'GuideController@show') ->name('lans.guides.show'); /** * Events */ Route::resource('lans.events', 'EventController'); Route::resource('lans.events.signups', 'EventSignupController', ['only' => ['store', 'destroy']]); Route::get('/events/fullscreen', function () { return view('pages.events.fullscreen'); })->name('events.fullscreen'); /** * Users & Attendees */ Route::resource('users', 'UserController', ['only' => ['show', 'destroy']]); Route::resource('lans.attendees', 'AttendeeController', ['only' => ['index']]); /** * Achievements */ Route::resource('achievements', 'AchievementController'); Route::resource('lans.user-achievements', 'UserAchievementController', ['except' => ['show', 'edit', 'update']]); /** * Navigation Links */ Route::resource('navigation-links', 'NavigationLinkController', ['except' => 'show']); /** * Images */ Route::resource('images', 'ImageController', ['only' => ['index', 'store', 'edit', 'update', 'destroy']]); /** * Venues */ Route::resource('venues', 'VenueController'); /** * Slides */ Route::get('lans/{lan}/slides/play', function (Zeropingheroes\Lanager\Lan $lan) { return view('pages.slides.play', ['lan' => $lan]); })->name('lans.slides.play'); Route::resource('lans.slides', 'SlideController'); /** * Whitelisted IP Ranges */ Route::resource('whitelisted-ip-ranges', 'WhitelistedIpRangeController', ['only' => ['index', 'create', 'store', 'edit', 'update', 'destroy']]); Route::fallback(function () { return view('errors.404'); })->name('fallback');
agpl-3.0
nextstrain/auspice
src/components/tree/infoPanels/click.js
11200
import React from "react"; import styled from 'styled-components'; import { isValueValid } from "../../../util/globals"; import { infoPanelStyles } from "../../../globalStyles"; import { numericToCalendar } from "../../../util/dateHelpers"; import { getTraitFromNode, getFullAuthorInfoFromNode, getVaccineFromNode, getAccessionFromNode, getUrlFromNode, collectMutations } from "../../../util/treeMiscHelpers"; export const styles = { container: { position: "absolute", width: "100%", height: "100%", pointerEvents: "all", top: 0, left: 0, zIndex: 2000, backgroundColor: "rgba(80, 80, 80, .20)", /* FLEXBOX */ display: "flex", justifyContent: "center", alignItems: "center", wordWrap: "break-word", wordBreak: "break-word" } }; export const stopProp = (e) => { if (!e) {e = window.event;} // eslint-disable-line no-param-reassign e.cancelBubble = true; if (e.stopPropagation) {e.stopPropagation();} }; /* min width to get "collection date" on 1 line: 120 */ const item = (key, value, href) => ( <tr key={key}> <th style={infoPanelStyles.item}>{key}</th> <td style={infoPanelStyles.item}>{href ? ( <a href={href} target="_blank" rel="noopener noreferrer">{value}</a> ) : value }</td> </tr> ); const Link = ({url, title, value}) => ( <tr> <th style={infoPanelStyles.item}>{title}</th> <td style={infoPanelStyles.item}> <a href={url} target="_blank" rel="noopener noreferrer">{value}</a> </td> </tr> ); const Button = styled.button` border: 0px; background-color: inherit; cursor: pointer; outline: 0; text-decoration: underline; `; /** * Render a 2-column table of gene -> mutations. * Rows are sorted by gene name, alphabetically, with "nuc" last. * Mutations are sorted by genomic position. * todo: sort genes by position in genome * todo: provide in-app links from mutations to color-bys? filters? */ const MutationTable = ({node, geneSortFn, isTip}) => { const mutSortFn = (a, b) => { const [aa, bb] = [parseInt(a.slice(1, -1), 10), parseInt(b.slice(1, -1), 10)]; return aa<bb ? -1 : 1; }; const displayGeneMutations = (gene, muts) => { if (gene==="nuc" && isTip && muts.length>10) { return ( <div key={gene} style={{...infoPanelStyles.item, ...{fontWeight: 300}}}> <Button onClick={() => {navigator.clipboard.writeText(muts.sort(mutSortFn).join(", "));}}> {`${muts.length} nucleotide mutations, click to copy to clipboard`} </Button> </div> ); } return ( <div key={gene} style={{...infoPanelStyles.item, ...{fontWeight: 300}}}> {gene}: {muts.sort(mutSortFn).join(", ")} </div> ); }; let mutations; if (isTip) { mutations = collectMutations(node, true); } else if (node.branch_attrs && node.branch_attrs.mutations && Object.keys(node.branch_attrs.mutations).length) { mutations = node.branch_attrs.mutations; } if (!mutations) return null; const title = isTip ? "Mutations from root" : "Mutations on branch"; // we encode the table here (rather than via `item()`) to set component keys appropriately return ( <tr key={"Mutations"}> <th style={infoPanelStyles.item}>{title}</th> <td style={infoPanelStyles.item}>{ Object.keys(mutations) .sort(geneSortFn) .map((gene) => displayGeneMutations(gene, mutations[gene])) }</td> </tr> ); }; const AccessionAndUrl = ({node}) => { /* If `gisaid_epi_isl` or `genbank_accession` exist as node attrs, these preempt normal use of `accession` and `url`. These special values were introduced during the SARS-CoV-2 pandemic. */ const gisaid_epi_isl = getTraitFromNode(node, "gisaid_epi_isl"); const genbank_accession = getTraitFromNode(node, "genbank_accession"); let gisaid_epi_isl_url = null; let genbank_accession_url = null; if (isValueValid(gisaid_epi_isl)) { const gisaid_epi_isl_number = gisaid_epi_isl.split("_")[2]; // slice has to count from the end of the string rather than the beginning to deal with EPI ISLs of different lengths, eg // https://www.epicov.org/acknowledgement/67/98/EPI_ISL_406798.json // https://www.epicov.org/acknowledgement/99/98/EPI_ISL_2839998.json if (gisaid_epi_isl_number.length > 4) { gisaid_epi_isl_url = "https://www.epicov.org/acknowledgement/" + gisaid_epi_isl_number.slice(-4, -2) + "/" + gisaid_epi_isl_number.slice(-2) + "/" + gisaid_epi_isl + ".json"; } else { gisaid_epi_isl_url = "https://gisaid.org"; } } if (isValueValid(genbank_accession)) { genbank_accession_url = "https://www.ncbi.nlm.nih.gov/nuccore/" + genbank_accession; } if (isValueValid(gisaid_epi_isl) && isValueValid(genbank_accession)) { return ( <> <Link title={"GISAID EPI ISL"} value={gisaid_epi_isl} url={gisaid_epi_isl_url}/> <Link title={"Genbank accession"} value={genbank_accession} url={genbank_accession_url}/> </> ); } else if (isValueValid(gisaid_epi_isl)) { return ( <Link title={"GISAID EPI ISL"} value={gisaid_epi_isl} url={gisaid_epi_isl_url}/> ); } else if (isValueValid(genbank_accession)) { return ( <Link title={"Genbank accession"} value={genbank_accession} url={genbank_accession_url}/> ); } const {accession, url} = getAccessionFromNode(node); if (accession && url) { return ( <Link url={url} value={accession} title={"Accession"}/> ); } else if (accession) { return ( item("Accession", accession) ); } else if (url) { return ( <Link title={"Strain URL"} url={url} value={"click here"}/> ); } return null; }; const VaccineInfo = ({node, t}) => { const vaccineInfo = getVaccineFromNode(node); if (!vaccineInfo) return null; const renderElements = []; if (vaccineInfo.selection_date) { renderElements.push( <tr key={"seldate"}> <th>{t("Vaccine selected")}</th> <td>{vaccineInfo.selection_date}</td> </tr> ); } if (vaccineInfo.start_date) { renderElements.push( <tr key={"startdate"}> <th>{t("Vaccine start date")}</th> <td>{vaccineInfo.start_date}</td> </tr> ); } if (vaccineInfo.end_date) { renderElements.push( <tr key={"enddate"}> <th>{t("Vaccine end date")}</th> <td>{vaccineInfo.end_date}</td> </tr> ); } if (vaccineInfo.serum) { renderElements.push( <tr key={"serum"}> <th>{t("Serum strain")}</th> <td/> </tr> ); } return renderElements; }; const PublicationInfo = ({node, t}) => { const info = getFullAuthorInfoFromNode(node); if (!info) return null; const itemsToRender = []; itemsToRender.push(item(t("Authors"), info.value)); if (info.title && info.title !== "?") { if (info.paper_url && info.paper_url !== "?") { itemsToRender.push(item(t("Title"), info.title, info.paper_url)); } else { itemsToRender.push(item(t("Title"), info.title)); } } if (info.journal && info.journal !== "?") { itemsToRender.push(item(t("Journal"), info.journal)); } return (itemsToRender.length === 1 ? itemsToRender[0] : itemsToRender); }; const StrainName = ({children}) => ( <p style={infoPanelStyles.modalHeading}>{children}</p> ); const SampleDate = ({isTerminal, node, t}) => { const date = getTraitFromNode(node, "num_date"); if (!date) return null; const dateUncertainty = getTraitFromNode(node, "num_date", {confidence: true}); if (date && dateUncertainty && dateUncertainty[0] !== dateUncertainty[1]) { return ( <> {item(t(isTerminal ? "Inferred collection date" : "Inferred date"), numericToCalendar(date))} {item(t("Date Confidence Interval"), `(${numericToCalendar(dateUncertainty[0])}, ${numericToCalendar(dateUncertainty[1])})`)} </> ); } /* internal nodes are always inferred, regardless of whether uncertainty bounds are present */ return item(t(isTerminal ? "Collection date" : "Inferred date"), numericToCalendar(date)); }; const getTraitsToDisplay = (node) => { // TODO -- this should be centralised somewhere if (!node.node_attrs) return []; const ignore = ["author", "div", "num_date", "gisaid_epi_isl", "genbank_accession", "accession", "url"]; return Object.keys(node.node_attrs).filter((k) => !ignore.includes(k)); }; const Trait = ({node, trait, colorings, isTerminal}) => { let value = getTraitFromNode(node, trait); const confidence = getTraitFromNode(node, trait, {confidence: true}); if (typeof value === "number") { if (!Number.isInteger(value)) { value = Number.parseFloat(value).toPrecision(3); } } if (!isValueValid(value)) return null; if (confidence && value in confidence) { /* if it's a tip with one confidence value > 0.99 then we interpret this as a known (i.e. not inferred) state */ if (!isTerminal || confidence[value]<0.99) { value = `${value} (${(100 * confidence[value]).toFixed(0)}%)`; } } const name = (colorings && colorings[trait] && colorings[trait].title) ? colorings[trait].title : trait; const url = getUrlFromNode(node, trait); if (url) { return <Link title={name} url={url} value={value}/>; } return item(name, value); }; /** * A React component to display information about a tree tip in a modal-overlay style * @param {Object} props * @param {Object} props.tip tip node selected * @param {function} props.goAwayCallback * @param {object} props.colorings */ const NodeClickedPanel = ({selectedNode, clearSelectedNode, colorings, geneSortFn, t}) => { if (selectedNode.event!=="click") {return null;} const panelStyle = { ...infoPanelStyles.panel}; panelStyle.maxHeight = "70%"; const node = selectedNode.node.n; const isTip = selectedNode.type === "tip"; const isTerminal = node.fullTipCount===1; const title = isTip ? node.name : isTerminal ? `Branch leading to ${node.name}` : "Internal branch"; return ( <div style={infoPanelStyles.modalContainer} onClick={() => clearSelectedNode(selectedNode)}> <div className={"panel"} style={panelStyle} onClick={(e) => stopProp(e)}> <StrainName>{title}</StrainName> <table> <tbody> {!isTip && item(t("Number of terminal tips"), node.fullTipCount)} {isTip && <VaccineInfo node={node} t={t}/>} <SampleDate isTerminal={isTerminal} node={node} t={t}/> {!isTip && item("Node name", node.name)} {isTip && <PublicationInfo node={node} t={t}/>} {getTraitsToDisplay(node).map((trait) => ( <Trait node={node} trait={trait} colorings={colorings} key={trait} isTerminal={isTerminal}/> ))} {isTip && <AccessionAndUrl node={node}/>} {item("", "")} <MutationTable node={node} geneSortFn={geneSortFn} isTip={isTip}/> </tbody> </table> <p style={infoPanelStyles.comment}> {t("Click outside this box to go back to the tree")} </p> </div> </div> ); }; export default NodeClickedPanel;
agpl-3.0
ryo33/Yayaka19
web/static/js/plugins/emoji.js
107
import emoji from 'node-emoji' export default { transform(text) { return emoji.emojify(text) } }
agpl-3.0
lrlopez/moodle-mod_lessonplan
locallib.php
665
<?php /** * Internal library of functions for module lessonplan * * All the lessonplan specific functions, needed to implement the module * logic, should go here. Never include this file from your lib.php! * * @package mod_lessonplan * @copyright 2011 Luis-Ramon Lopez Lopez * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero GPL 3 */ defined('MOODLE_INTERNAL') || die(); require_once("$CFG->dirroot/mod/lessonplan/lib.php"); /** * Does something really useful with the passed things * * @param array $things * @return object */ //function lessonplan_do_something_useful(array $things) { // return new stdClass(); //}
agpl-3.0
irina-mitrea-luxoft/k3po
driver/src/test/java/org/kaazing/k3po/driver/internal/behavior/handler/event/ChildOpenedHandlerTest.java
15162
/* * Copyright 2014, Kaazing Corporation. 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. */ package org.kaazing.k3po.driver.internal.behavior.handler.event; import static java.lang.System.currentTimeMillis; import static org.jboss.netty.channel.ChannelState.CONNECTED; import static org.jboss.netty.channel.ChannelState.INTEREST_OPS; import static org.jboss.netty.channel.Channels.fireChannelBound; import static org.jboss.netty.channel.Channels.fireChannelClosed; import static org.jboss.netty.channel.Channels.fireChannelConnected; import static org.jboss.netty.channel.Channels.fireChannelDisconnected; import static org.jboss.netty.channel.Channels.fireChannelInterestChanged; import static org.jboss.netty.channel.Channels.fireChannelUnbound; import static org.jboss.netty.channel.Channels.fireExceptionCaught; import static org.jboss.netty.channel.Channels.fireMessageReceived; import static org.jboss.netty.channel.Channels.fireWriteComplete; import static org.jboss.netty.channel.Channels.pipeline; import static org.jboss.netty.channel.Channels.succeededFuture; import static org.jboss.netty.handler.timeout.IdleState.ALL_IDLE; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.kaazing.k3po.lang.internal.RegionInfo.newSequential; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.ChildChannelStateEvent; import org.jboss.netty.channel.DefaultChildChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.WriteCompletionEvent; import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory; import org.jboss.netty.channel.local.LocalAddress; import org.jboss.netty.handler.timeout.DefaultIdleStateEvent; import org.jboss.netty.handler.timeout.IdleStateEvent; import org.junit.Before; import org.junit.Test; import org.kaazing.k3po.driver.internal.behavior.handler.TestChannelEvent; import org.kaazing.k3po.driver.internal.behavior.handler.prepare.PreparationEvent; import org.kaazing.k3po.driver.internal.jmock.Expectations; import org.kaazing.k3po.driver.internal.jmock.Mockery; public class ChildOpenedHandlerTest { private Mockery context; private ChannelUpstreamHandler upstream; private ChannelPipeline pipeline; private ChannelFactory channelFactory; private ChildOpenedHandler handler; private boolean blockChannelOpen = true; @Before public void setUp() throws Exception { context = new Mockery() { { setThrowFirstErrorOnAssertIsSatisfied(true); } }; upstream = context.mock(ChannelUpstreamHandler.class); handler = new ChildOpenedHandler(); handler.setRegionInfo(newSequential(0, 0)); pipeline = pipeline(new SimpleChannelHandler() { @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // block implicit channel open? if (!blockChannelOpen) { ctx.sendUpstream(e); } } }, handler, new SimpleChannelHandler() { @Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { upstream.handleUpstream(ctx, e); super.handleUpstream(ctx, e); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { // prevent console error message } }); channelFactory = new DefaultLocalClientChannelFactory(); } @Test public void shouldConsumeUpstreamChildOpenedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel parentChannel = channelFactory.newChannel(pipeline); Channel childChannel = channelFactory.newChannel(pipeline(new SimpleChannelUpstreamHandler())); // child channel is open pipeline.sendUpstream(new DefaultChildChannelStateEvent(parentChannel, childChannel)); ChannelFuture handlerFuture = handler.getHandlerFuture(); assertTrue(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamChildClosedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel parentChannel = channelFactory.newChannel(pipeline); Channel childChannel = channelFactory.newChannel(pipeline(new SimpleChannelUpstreamHandler())); childChannel.close().sync(); // child channel is closed pipeline.sendUpstream(new DefaultChildChannelStateEvent(parentChannel, childChannel)); ChannelFuture handlerFuture = handler.getHandlerFuture(); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamInterestOpsEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(channelState(INTEREST_OPS))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelInterestChanged(channel); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamIdleStateEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(IdleStateEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); pipeline.sendUpstream(new DefaultIdleStateEvent(channel, ALL_IDLE, currentTimeMillis())); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamWriteCompletionEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(WriteCompletionEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); fireWriteComplete(channel, 1024); ChannelFuture handlerFuture = handler.getHandlerFuture(); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamExceptionEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(ExceptionEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireExceptionCaught(channel, new Exception().fillInStackTrace()); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamUnknownEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(TestChannelEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); pipeline.sendUpstream(new TestChannelEvent(channel, succeededFuture(channel))); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamOpenedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); blockChannelOpen = false; channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamBoundEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelBound(channel, new LocalAddress("test")); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamConnectedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(channelState(CONNECTED))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelConnected(channel, new LocalAddress("test")); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamMessageEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(MessageEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireMessageReceived(channel, new Object()); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamDisconnectedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(channelState(CONNECTED, null))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelDisconnected(channel); assertFalse(handlerFuture.isDone()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamUnboundEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelUnbound(channel); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldConsumeUpstreamClosedEvent() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); } }); Channel channel = channelFactory.newChannel(pipeline); ChannelFuture handlerFuture = handler.getHandlerFuture(); fireChannelClosed(channel); assertTrue(handlerFuture.isDone()); assertFalse(handlerFuture.isSuccess()); context.assertIsSatisfied(); } @Test public void shouldPropagateUpstreamChildOpenedEventAfterFutureDone() throws Exception { context.checking(new Expectations() { { oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class))); oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(ChildChannelStateEvent.class))); } }); Channel parentChannel = channelFactory.newChannel(pipeline); Channel childChannel = channelFactory.newChannel(pipeline(new SimpleChannelUpstreamHandler())); // child channel is open pipeline.sendUpstream(new DefaultChildChannelStateEvent(parentChannel, childChannel)); pipeline.sendUpstream(new DefaultChildChannelStateEvent(parentChannel, childChannel)); context.assertIsSatisfied(); } }
agpl-3.0
vivekdevrari/litecrm
cache/modules/Bugs/language/en_us.lang.php
3959
<?php // created: 2016-12-18 14:52:45 $mod_strings = array ( 'LBL_ID' => 'ID', 'LBL_DATE_ENTERED' => 'Date Created:', 'LBL_DATE_MODIFIED' => 'Date Modified:', 'LBL_MODIFIED' => 'Modified By', 'LBL_MODIFIED_ID' => 'Modified By Id', 'LBL_MODIFIED_NAME' => 'Modified By Name', 'LBL_CREATED' => 'Created By', 'LBL_CREATED_ID' => 'Created By Id', 'LBL_DESCRIPTION' => 'Description:', 'LBL_DELETED' => 'Deleted', 'LBL_NAME' => 'Name', 'LBL_CREATED_USER' => 'Created by User', 'LBL_MODIFIED_USER' => 'Modified by User', 'LBL_LIST_NAME' => 'Name', 'LBL_EDIT_BUTTON' => 'Edit', 'LBL_REMOVE' => 'Remove', 'LBL_ASSIGNED_TO_ID' => 'Assigned To:', 'LBL_ASSIGNED_TO_NAME' => 'Assigned to', 'LBL_SECURITYGROUPS' => 'Security Groups', 'LBL_SECURITYGROUPS_SUBPANEL_TITLE' => 'Security Groups', 'LBL_NUMBER' => 'Number:', 'LBL_STATUS' => 'Status:', 'LBL_PRIORITY' => 'Priority:', 'LBL_RESOLUTION' => 'Resolution:', 'LBL_LAST_MODIFIED' => 'Last Modified', 'LBL_WORK_LOG' => 'Work Log:', 'LBL_CREATED_BY' => 'Created by:', 'LBL_DATE_CREATED' => 'Create Date:', 'LBL_MODIFIED_BY' => 'Last Modified by:', 'LBL_ASSIGNED_USER' => 'Assigned User:', 'LBL_SYSTEM_ID' => 'System ID', 'LBL_TYPE' => 'Type:', 'LBL_SUBJECT' => 'Subject:', 'LBL_MODULE_NAME' => 'Bugs', 'LBL_MODULE_TITLE' => 'Bug Tracker: Home', 'LBL_MODULE_ID' => 'Bugs', 'LBL_SEARCH_FORM_TITLE' => 'Bug Search', 'LBL_LIST_FORM_TITLE' => 'Bug List', 'LBL_NEW_FORM_TITLE' => 'New Bug', 'LBL_CONTACT_BUG_TITLE' => 'Contact-Bug:', 'LBL_BUG' => 'Bug:', 'LBL_BUG_NUMBER' => 'Bug Number:', 'LBL_CONTACT_NAME' => 'Contact Name:', 'LBL_BUG_SUBJECT' => 'Bug Subject:', 'LBL_CONTACT_ROLE' => 'Role:', 'LBL_LIST_NUMBER' => 'Num.', 'LBL_LIST_SUBJECT' => 'Subject', 'LBL_LIST_STATUS' => 'Status', 'LBL_LIST_PRIORITY' => 'Priority', 'LBL_LIST_RELEASE' => 'Release', 'LBL_LIST_RESOLUTION' => 'Resolution', 'LBL_LIST_LAST_MODIFIED' => 'Last Modified', 'LBL_INVITEE' => 'Contacts', 'LBL_LIST_TYPE' => 'Type', 'LBL_RELEASE' => 'Release:', 'LNK_NEW_BUG' => 'Report Bug', 'LNK_BUG_LIST' => 'View Bugs', 'NTC_REMOVE_INVITEE' => 'Are you sure you want to remove this contact from the bug?', 'NTC_REMOVE_ACCOUNT_CONFIRMATION' => 'Are you sure you want to remove this bug from this account?', 'ERR_DELETE_RECORD' => 'You must specify a record number in order to delete the bug.', 'LBL_LIST_MY_BUGS' => 'My Assigned Bugs', 'LNK_IMPORT_BUGS' => 'Import Bugs', 'LBL_FOUND_IN_RELEASE' => 'Found in Release:', 'LBL_FIXED_IN_RELEASE' => 'Fixed in Release:', 'LBL_LIST_FIXED_IN_RELEASE' => 'Fixed in Release', 'LBL_SOURCE' => 'Source:', 'LBL_PRODUCT_CATEGORY' => 'Category:', 'LBL_DATE_LAST_MODIFIED' => 'Modify Date:', 'LBL_LIST_EMAIL_ADDRESS' => 'Email Address', 'LBL_LIST_CONTACT_NAME' => 'Contact Name', 'LBL_LIST_ACCOUNT_NAME' => 'Account Name', 'LBL_LIST_PHONE' => 'Phone', 'NTC_DELETE_CONFIRMATION' => 'Are you sure you want to remove this contact from this bug?', 'LBL_DEFAULT_SUBPANEL_TITLE' => 'Bug Tracker', 'LBL_ACTIVITIES_SUBPANEL_TITLE' => 'Activities', 'LBL_HISTORY_SUBPANEL_TITLE' => 'History', 'LBL_CONTACTS_SUBPANEL_TITLE' => 'Agents', 'LBL_ACCOUNTS_SUBPANEL_TITLE' => 'Companies', 'LBL_CASES_SUBPANEL_TITLE' => 'Trips', 'LBL_PROJECTS_SUBPANEL_TITLE' => 'Projects', 'LBL_DOCUMENTS_SUBPANEL_TITLE' => 'Documents', 'LBL_LIST_ASSIGNED_TO_NAME' => 'Assigned User', 'LBL_BUG_INFORMATION' => 'Overview', 'LBL_FOUND_IN_RELEASE_NAME' => 'Found In Release Name', 'LBL_PORTAL_VIEWABLE' => 'Portal Viewable', 'LBL_EXPORT_ASSIGNED_USER_NAME' => 'Assigned User Name', 'LBL_EXPORT_ASSIGNED_USER_ID' => 'Assigned User ID', 'LBL_EXPORT_FIXED_IN_RELEASE_NAMR' => 'Fixed in Release Name', 'LBL_EXPORT_MODIFIED_USER_ID' => 'Modified By ID', 'LBL_EXPORT_CREATED_BY' => 'Created By ID', 'LBL_ACCOUNTS' => 'Companies', 'LBL_CASES' => 'Trips', 'LBL_CONTACTS' => 'Agents', );
agpl-3.0
NicolasEYSSERIC/Silverpeas-Core
lib-core/src/main/java/com/silverpeas/util/comparator/AbstractComplexComparator.java
3763
/* * Copyright (C) 2000 - 2012 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.util.comparator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author Yohann Chastagnier * @param <C> */ public abstract class AbstractComplexComparator<C> extends AbstractComparator<C> { /** * Value list to compare * @param object * @return */ protected abstract ValueBuffer getValuesToCompare(final C object); /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public int compare(final C o1, final C o2) { // Value lists to compare final ValueBuffer baseValues = getValuesToCompare(o1); final ValueBuffer comparedValues = getValuesToCompare(o2); // Tests int result = 0; final Iterator<Object> it1 = baseValues.getValues().iterator(); final Iterator<Object> it2 = comparedValues.getValues().iterator(); final Iterator<Integer> itSens = baseValues.getSens().iterator(); Object curO1; Object curO2; Integer sens; while (it1.hasNext()) { curO1 = it1.next(); curO2 = it2.next(); sens = itSens.next(); // Instance result = compareInstance(curO1, curO2); if (result != 0) { return result * sens.intValue(); } // Value if (areInstancesComparable(curO1, curO2)) { result = compare((Comparable) curO1, curO2); if (result != 0) { return result * sens.intValue(); } } } // The two objects are identical return result; } /** * A value * @author yohann.chastagnier */ public class ValueBuffer { /** Sens */ final private List<Integer> sens = new ArrayList<Integer>(); /** Valeur */ final private List<Object> values = new ArrayList<Object>(); /** * Default constructor */ public ValueBuffer() { // NTD } /** * Adding a value * @param object * @param isAscending * @return */ public ValueBuffer append(final Object object, final boolean isAscending) { values.add(object); if (isAscending) { sens.add(1); } else { sens.add(-1); } return this; } /** * Adding a value * @param object * @return */ public ValueBuffer append(final Object object) { return append(object, true); } /** * @return the sens */ public List<Integer> getSens() { return sens; } /** * @return the values */ public List<Object> getValues() { return values; } } }
agpl-3.0
BenjaminThirion/webPLM
public/app/components/convert-to-number.directive.js
511
(function(){ 'use strict'; angular .module('PLMApp') .directive('convertToNumber', convertToNumber); function convertToNumber() { return { require: 'ngModel', link: function(scope, element, attrs, ngModel) { ngModel.$parsers.push(function(val) { return parseInt(val, 10); }); ngModel.$formatters.push(function(val) { return '' + val; }); } }; } })();
agpl-3.0
owly/wok
app/controllers/quizzes_controller.rb
31514
# # Copyright (C) 2011 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas 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 Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # class QuizzesController < ApplicationController include Api::V1::Quiz include Api::V1::QuizStatistics include Api::V1::AssignmentOverride before_filter :require_context add_crumb(proc { t('#crumbs.quizzes', "Quizzes") }) { |c| c.send :named_context_url, c.instance_variable_get("@context"), :context_quizzes_url } before_filter { |c| c.active_tab = "quizzes" } before_filter :get_quiz, :only => [:statistics, :edit, :show, :reorder, :history, :update, :destroy, :moderate, :filters, :read_only, :managed_quiz_data] before_filter :set_download_submission_dialog_title , only: [:show,:statistics] # The number of questions that can display "details". After this number, the "Show details" option is disabled # and the data is not even loaded. QUIZ_QUESTIONS_DETAIL_LIMIT = 25 def index if authorized_action(@context, @current_user, :read) return unless tab_enabled?(@context.class::TAB_QUIZZES) @quizzes = @context.quizzes.active.include_assignment.sort_by{|q| [(q.assignment ? q.assignment.due_at : q.lock_at) || Time.parse("Jan 1 2020"), q.title || ""]} @unpublished_quizzes = @quizzes.select{|q| !q.available?} @quizzes = @quizzes.select{|q| q.available?} @assignment_quizzes = @quizzes.select{|q| q.assignment_id} @open_quizzes = @quizzes.select{|q| q.quiz_type == 'practice_quiz'} @surveys = @quizzes.select{|q| q.quiz_type == 'survey' || q.quiz_type == 'graded_survey' } @submissions_hash = {} @submissions_hash @current_user && @current_user.quiz_submissions.where('quizzes.context_id=? AND quizzes.context_type=?', @context, @context.class.to_s).includes(:quiz).each do |s| if s.needs_grading? s.grade_submission(:finished_at => s.end_at) s.reload end @submissions_hash[s.quiz_id] = s end log_asset_access("quizzes:#{@context.asset_string}", "quizzes", 'other') end end def attachment_hash(attachment) {:id => attachment.id, :display_name => attachment.display_name} end def new if authorized_action(@context.quizzes.new, @current_user, :create) @assignment = nil @assignment = @context.assignments.active.find(params[:assignment_id]) if params[:assignment_id] @quiz = @context.quizzes.build @quiz.title = params[:title] if params[:title] @quiz.due_at = params[:due_at] if params[:due_at] @quiz.assignment_group_id = params[:assignment_group_id] if params[:assignment_group_id] @quiz.save! # this is a weird check... who can create but not update??? if authorized_action(@quiz, @current_user, :update) @assignment = @quiz.assignment end redirect_to(named_context_url(@context, :edit_context_quiz_url, @quiz)) end end # student_analysis report def statistics if authorized_action(@quiz, @current_user, :read_statistics) respond_to do |format| format.html { all_versions = params[:all_versions] == '1' add_crumb(@quiz.title, named_context_url(@context, :context_quiz_url, @quiz)) add_crumb(t(:statistics_crumb, "Statistics"), named_context_url(@context, :context_quiz_statistics_url, @quiz)) if [email protected]_roster? @statistics = @quiz.statistics(all_versions) user_ids = @statistics[:submission_user_ids] @submitted_users = User.where(:id => user_ids.to_a).order_by_sortable_name @users = Hash[ @submitted_users.map { |u| [u.id, u] } ] #include logged out users @submitted_users += @statistics[:submission_logged_out_users] end js_env :quiz_reports => QuizStatistics::REPORTS.map { |report_type| report = @quiz.current_statistics_for(report_type, :includes_all_versions => all_versions) json = quiz_statistics_json(report, @current_user, session, :include => ['file']) json[:course_id] = @context.id json[:report_name] = report.readable_type json[:progress] = progress_json(report.progress, @current_user, session) if report.progress json } } end end end def edit if authorized_action(@quiz, @current_user, :update) add_crumb(@quiz.title, named_context_url(@context, :context_quiz_url, @quiz)) @assignment = @quiz.assignment @quiz.title = params[:title] if params[:title] @quiz.due_at = params[:due_at] if params[:due_at] @quiz.assignment_group_id = params[:assignment_group_id] if params[:assignment_group_id] student_ids = @context.student_ids @banks_hash = {} bank_ids = @quiz.quiz_groups.map(&:assessment_question_bank_id) unless bank_ids.empty? AssessmentQuestionBank.active.find_all_by_id(bank_ids).compact.each do |bank| @banks_hash[bank.id] = bank end end if @has_student_submissions = @quiz.has_student_submissions? flash[:notice] = t('notices.has_submissions_already', "Keep in mind, some students have already taken or started taking this quiz") end sections = @context.course_sections.active js_env :ASSIGNMENT_ID => @assigment.present? ? @assignment.id : nil, :ASSIGNMENT_OVERRIDES => assignment_overrides_json(@quiz.overrides_visible_to(@current_user)), :QUIZ => quiz_json(@quiz, @context, @current_user, session), :SECTION_LIST => sections.map { |section| { :id => section.id, :name => section.name } }, :QUIZZES_URL => polymorphic_url([@context, :quizzes]) render :action => "new" end end def read_only @assignment = @quiz.assignment if authorized_action(@quiz, @current_user, :read_statistics) add_crumb(@quiz.title, named_context_url(@context, :context_quiz_url, @quiz)) render end end def setup_attachments if @submission @attachments = Hash[@submission.attachments.map do |attachment| [attachment.id,attachment] end ] else @attachments = {} end end def show if @quiz.deleted? flash[:error] = t('errors.quiz_deleted', "That quiz has been deleted") redirect_to named_context_url(@context, :context_quizzes_url) return end if authorized_action(@quiz, @current_user, :read) # optionally force auth even for public courses return if value_to_boolean(params[:force_user]) && !force_user @quiz = @quiz.overridden_for(@current_user) add_crumb(@quiz.title, named_context_url(@context, :context_quiz_url, @quiz)) setup_headless if @quiz.require_lockdown_browser? && @quiz.require_lockdown_browser_for_results? && params[:viewing] return unless check_lockdown_browser(:medium, named_context_url(@context, 'context_quiz_url', @quiz.to_param, :viewing => "1")) end if @quiz.require_lockdown_browser? && refresh_ldb = value_to_boolean(params.delete(:refresh_ldb)) return render(:action => "refresh_quiz_after_popup") end @question_count = @quiz.question_count if session[:quiz_id] == @quiz.id && !request.xhr? session.delete(:quiz_id) end @locked_reason = @quiz.locked_for?(@current_user, :check_policies => true, :deep_check_if_needed => true) @locked = @locked_reason && [email protected]_right?(@current_user, session, :update) @context_module_tag = ContextModuleItem.find_tag_with_preferred([@quiz, @quiz.assignment], params[:module_item_id]) @sequence_asset = @context_module_tag.try(:content) @quiz.context_module_action(@current_user, :read) if !@locked @assignment = @quiz.assignment @assignment = @assignment.overridden_for(@current_user) if @assignment @submission = @quiz.quiz_submissions.find_by_user_id(@current_user.id, :order => 'created_at') rescue nil if !@current_user || (params[:preview] && @quiz.grants_right?(@current_user, session, :update)) user_code = temporary_user_code @submission = @quiz.quiz_submissions.find_by_temporary_user_code(user_code) end @just_graded = false if @submission && @submission.needs_grading?(!!params[:take]) @submission.grade_submission(:finished_at => @submission.end_at) @submission.reload @just_graded = true end if @submission upload_url = api_v1_quiz_submission_create_file_path(:course_id => @context.id, :quiz_id => @quiz.id) js_env :UPLOAD_URL => upload_url end setup_attachments submission_counts if @quiz.grants_right?(@current_user, session, :grade) || @quiz.grants_right?(@current_user, session, :read_statistics) @stored_params = (@submission.temporary_data rescue nil) if params[:take] && @submission && (@submission.untaken? || @submission.preview?) @stored_params ||= {} log_asset_access(@quiz, "quizzes", "quizzes") js_env :QUIZZES_URL => polymorphic_url([@context, :quizzes]), :IS_SURVEY => @quiz.survey?, :QUIZ => quiz_json(@quiz,@context,@current_user,session), :LOCKDOWN_BROWSER => @quiz.require_lockdown_browser?, :ATTACHMENTS => Hash[@attachments.map { |_,a| [a.id,attachment_hash(a)]}] if params[:take] && can_take_quiz? # allow starting the quiz via a GET request, but only when using a lockdown browser if request.post? || (@quiz.require_lockdown_browser? && !quiz_submission_active?) start_quiz! else take_quiz end end @padless = true end end def managed_quiz_data extend Api::V1::User if authorized_action(@quiz, @current_user, [:grade, :read_statistics]) students = @context.students_visible_to(@current_user).order_by_sortable_name.to_a.uniq @submissions_from_users = @quiz.quiz_submissions.for_user_ids(students.map(&:id)).not_settings_only.all @submissions_from_users = Hash[@submissions_from_users.map { |s| [s.user_id,s] }] #include logged out submissions @submissions_from_logged_out = @quiz.quiz_submissions.logged_out.not_settings_only @submitted_students, @unsubmitted_students = students.partition do |stud| @submissions_from_users[stud.id] end if @quiz.anonymous_survey? @submitted_students = @submitted_students.sort_by do |student| @submissions_from_users[student.id].id end submitted_students_json = @submitted_students.map &:id unsubmitted_students_json = @unsubmitted_students.map &:id else submitted_students_json = @submitted_students.map { |u| user_json(u, @current_user, session) } unsubmitted_students_json = @unsubmitted_students.map { |u| user_json(u, @current_user, session) } end @quiz_submission_list = { :UNSUBMITTED_STUDENTS => unsubmitted_students_json, :SUBMITTED_STUDENTS => submitted_students_json }.to_json render :layout => false end end def lockdown_browser_required plugin = Canvas::LockdownBrowser.plugin if plugin @lockdown_browser_download_url = plugin.settings[:download_url] end render end def publish if authorized_action(@context, @current_user, :manage_assignments) @quizzes = @context.quizzes.active.find_all_by_id(params[:quizzes]).compact.select{|q| !q.available? } @quizzes.each(&:publish!) flash[:notice] = t('notices.quizzes_published', { :one => "1 quiz successfully published!", :other => "%{count} quizzes successfully published!" }, :count => @quizzes.length) respond_to do |format| format.html { redirect_to named_context_url(@context, :context_quizzes_url) } format.json { render :json => {}, :status => :ok } end end end def unpublish if authorized_action(@context, @current_user, :manage_assignments) @quizzes = @context.quizzes.active.find_all_by_id(params[:quizzes]).compact.select{|q| q.available? } @quizzes.each(&:unpublish!) flash[:notice] = t('notices.quizzes_unpublished', { :one => "1 quiz successfully unpublished!", :other => "%{count} quizzes successfully unpublished!" }, :count => @quizzes.length) respond_to do |format| format.html { redirect_to named_context_url(@context, :context_quizzes_url) } format.json { render :json => {}, :status => :ok } end end end def filters if authorized_action(@quiz, @current_user, :update) @filters = [] @account = @quiz.context.account if @quiz.ip_filter @filters << { :name => t(:current_filter, 'Current Filter'), :account => @quiz.title, :filter => @quiz.ip_filter } end while @account (@account.settings[:ip_filters] || {}).sort_by(&:first).each do |key, filter| @filters << { :name => key, :account => @account.name, :filter => filter } end @account = @account.parent_account end render :json => @filters.to_json end end def reorder if authorized_action(@quiz, @current_user, :update) items = [] groups = @quiz.quiz_groups questions = @quiz.quiz_questions order = params[:order].split(",") order.each_index do |idx| name = order[idx] obj = nil id = name.gsub(/\A(question|group)_/, "").to_i obj = questions.detect{|q| q.id == id.to_i} if id != 0 && name.match(/\Aquestion/) obj.quiz_group_id = nil if obj.respond_to?("quiz_group_id=") obj = groups.detect{|g| g.id == id.to_i} if id != 0 && name.match(/\Agroup/) items << obj if obj end root_questions = @quiz.quiz_questions.where("quiz_group_id IS NULL").all items += root_questions items.uniq! question_updates = [] group_updates = [] items.each_with_index do |item, idx| if item.is_a?(QuizQuestion) question_updates << "WHEN id=#{item.id} THEN #{idx + 1}" else group_updates << "WHEN id=#{item.id} THEN #{idx + 1}" end end QuizQuestion.where(:id => items.select{|i| i.is_a?(QuizQuestion)}).update_all("quiz_group_id=NULL,position=CASE #{question_updates.join(" ")} ELSE NULL END") unless question_updates.empty? QuizGroup.where(:id => items.select{|i| i.is_a?(QuizGroup)}).update_all("position=CASE #{group_updates.join(" ")} ELSE NULL END") unless group_updates.empty? Quiz.mark_quiz_edited(@quiz.id) render :json => {:reorder => true} end end def history if authorized_action(@context, @current_user, :read) add_crumb(@quiz.title, named_context_url(@context, :context_quiz_url, @quiz)) if params[:quiz_submission_id] @submission = @quiz.quiz_submissions.find(params[:quiz_submission_id]) else user_id = params[:user_id].presence || @current_user.id @submission = @quiz.quiz_submissions.find_by_user_id(user_id, :order => 'created_at') rescue nil end if @submission && [email protected]_id && logged_out_index = params[:u_index] @logged_out_user_index = logged_out_index end @submission = nil if @submission && @submission.settings_only? @user = @submission && @submission.user if @submission && @submission.needs_grading? @submission.grade_submission(:finished_at => @submission.end_at) @submission.reload end setup_attachments if @quiz.deleted? flash[:error] = t('errors.quiz_deleted', "That quiz has been deleted") redirect_to named_context_url(@context, :context_quizzes_url) return end if !@submission flash[:notice] = t('notices.no_submission_for_user', "There is no submission available for that user") redirect_to named_context_url(@context, :context_quiz_url, @quiz) return end if @quiz.muted? && [email protected]_right?(@current_user, session, :grade) flash[:notice] = t('notices.cant_view_submission_while_muted', "You cannot view the quiz history while the quiz is muted.") redirect_to named_context_url(@context, :context_quiz_url, @quiz) return end if params[:score_updated] js_env :SCORE_UPDATED => true end if authorized_action(@submission, @current_user, :read) dont_show_user_name = @submission.quiz.anonymous_submissions || ([email protected] || @submission.user == @current_user) add_crumb((dont_show_user_name ? t(:default_history_crumb, "History") : @submission.user.name)) @headers = !params[:headless] unless @headers @body_classes << 'quizzes-speedgrader' end @current_submission = @submission @version_instances = @submission.submitted_versions.sort_by{|v| v.version_number } params[:version] ||= @version_instances[0].version_number if @submission.untaken? && !@version_instances.empty? @current_version = true @version_number = "current" if params[:version] @version_number = params[:version].to_i @unversioned_submission = @submission @submission = @version_instances.detect{|s| s.version_number >= @version_number} @submission ||= @unversioned_submission.versions.get(params[:version]).model @current_version = (@current_submission.version_number == @submission.version_number) @version_number = "current" if @current_version end log_asset_access(@quiz, "quizzes", 'quizzes') if @quiz.require_lockdown_browser? && @quiz.require_lockdown_browser_for_results? && params[:viewing] return unless check_lockdown_browser(:medium, named_context_url(@context, 'context_quiz_history_url', @quiz.to_param, :viewing => "1", :version => params[:version])) end end end end def delete_override_params # nil represents the fact that we don't want to update the overrides return nil unless params[:quiz].has_key?(:assignment_overrides) overrides = params[:quiz].delete(:assignment_overrides) overrides = deserialize_overrides(overrides) # overrides might be "false" to indicate no overrides through form params overrides.is_a?(Array) ? overrides : [] end def create if authorized_action(@context.quizzes.new, @current_user, :create) params[:quiz][:title] = nil if params[:quiz][:title] == "undefined" params[:quiz][:title] ||= t(:default_title, "New Quiz") params[:quiz].delete(:points_possible) unless params[:quiz][:quiz_type] == 'graded_survey' params[:quiz][:access_code] = nil if params[:quiz][:access_code] == "" if params[:quiz][:quiz_type] == 'assignment' || params[:quiz][:quiz_type] == 'graded_survey' params[:quiz][:assignment_group_id] ||= @context.assignment_groups.first.id if (assignment_group_id = params[:quiz].delete(:assignment_group_id)) && assignment_group_id.present? @assignment_group = @context.assignment_groups.active.find_by_id(assignment_group_id) end if @assignment_group @assignment = @context.assignments.build(:title => params[:quiz][:title], :due_at => params[:quiz][:lock_at], :submission_types => 'online_quiz') @assignment.assignment_group = @assignment_group @assignment.saved_by = :quiz @assignment.save params[:quiz][:assignment_id] = @assignment.id end params[:quiz][:assignment_id] = nil unless @assignment params[:quiz][:title] = @assignment.title if @assignment end @quiz = @context.quizzes.build @quiz.content_being_saved_by(@current_user) @quiz.infer_times overrides = delete_override_params @quiz.transaction do @quiz.update_attributes!(params[:quiz]) batch_update_assignment_overrides(@quiz,overrides) unless overrides.nil? end @quiz.did_edit if @quiz.created? @quiz.reload render :json => @quiz.to_json(:include => {:assignment => {:include => :assignment_group}}) end rescue render :json => @quiz.errors.to_json, :status => :bad_request end def update n = Time.now.to_f if authorized_action(@quiz, @current_user, :update) params[:quiz] ||= {} params[:quiz][:title] = t(:default_title, "New Quiz") if params[:quiz][:title] == "undefined" params[:quiz].delete(:points_possible) unless params[:quiz][:quiz_type] == 'graded_survey' params[:quiz][:access_code] = nil if params[:quiz][:access_code] == "" if params[:quiz][:quiz_type] == 'assignment' || params[:quiz][:quiz_type] == 'graded_survey' #'new' && params[:quiz][:assignment_group_id] if (assignment_group_id = params[:quiz].delete(:assignment_group_id)) && assignment_group_id.present? @assignment_group = @context.assignment_groups.active.find_by_id(assignment_group_id) end @assignment_group ||= @context.assignment_groups.first # The code to build an assignment for a quiz used to be here, but it's # been moved to the model quiz.rb instead. See Quiz:build_assignment. params[:quiz][:assignment_group_id] = @assignment_group && @assignment_group.id end params[:quiz][:lock_at] = nil if params[:quiz].delete(:do_lock_at) == 'false' @quiz.with_versioning(false) do @quiz.did_edit if @quiz.created? end # TODO: API for Quiz overrides! respond_to do |format| @quiz.transaction do overrides = delete_override_params if !@domain_root_account.enable_draft? && params[:activate] @quiz.with_versioning(true) { @quiz.publish! } end notify_of_update = value_to_boolean(params[:quiz][:notify_of_update]) params[:quiz][:notify_of_update] = false old_assignment = nil if @quiz.assignment.present? old_assignment = @quiz.assignment.clone old_assignment.id = @quiz.assignment.id end auto_publish = @domain_root_account.enable_draft? && @quiz.published? @quiz.with_versioning(auto_publish) do # using attributes= here so we don't need to make an extra # database call to get the times right after save! @quiz.attributes = params[:quiz] @quiz.infer_times @quiz.content_being_saved_by(@current_user) if auto_publish @quiz.generate_quiz_data @quiz.workflow_state = 'available' @quiz.published_at = Time.now end @quiz.save! end batch_update_assignment_overrides(@quiz,overrides) unless overrides.nil? # quiz.rb restricts all assignment broadcasts if notify_of_update is # false, so we do the same here if @quiz.assignment.present? && old_assignment && (notify_of_update || old_assignment.due_at != @quiz.assignment.due_at) @quiz.assignment.do_notifications!(old_assignment, notify_of_update) end @quiz.reload @quiz.update_quiz_submission_end_at_times if params[:quiz][:time_limit].present? end flash[:notice] = t('notices.quiz_updated', "Quiz successfully updated") format.html { redirect_to named_context_url(@context, :context_quiz_url, @quiz) } format.json { render :json => @quiz.to_json(:include => {:assignment => {:include => :assignment_group}}) } end end rescue respond_to do |format| flash[:error] = t('errors.quiz_update_failed', "Quiz failed to update") format.html { redirect_to named_context_url(@context, :context_quiz_url, @quiz) } format.json { render :json => @quiz.errors.to_json, :status => :bad_request } end end def destroy if authorized_action(@quiz, @current_user, :delete) respond_to do |format| if @quiz.destroy format.html { redirect_to course_quizzes_url(@context) } format.json { render :json => @quiz.to_json } else format.html { redirect_to course_quiz_url(@context, @quiz) } format.json { render :json => @quiz.errors.to_json } end end end end def moderate if authorized_action(@quiz, @current_user, :grade) @all_students = @context.students_visible_to(@current_user).order_by_sortable_name if @quiz.survey? && @quiz.anonymous_submissions @students = @all_students.paginate(:per_page => 50, :page => params[:page], :order => :uuid) else @students = @all_students.paginate(:per_page => 50, :page => params[:page]) end last_updated_at = Time.parse(params[:last_updated_at]) rescue nil @submissions = @quiz.quiz_submissions.updated_after(last_updated_at).for_user_ids(@students.map(&:id)) respond_to do |format| format.html format.json { render :json => @submissions.to_json(:include_root => false, :except => [:submission_data, :quiz_data], :methods => ['extendable?', :finished_in_words, :attempts_left]) } end end end def force_user if !@current_user session[:return_to] = polymorphic_path([@context, @quiz]) redirect_to login_path end return @current_user.present? end def setup_headless # persist headless state through take button and next/prev questions session[:headless_quiz] = true if value_to_boolean(params[:persist_headless]) @headers = !params[:headless] && !session[:headless_quiz] end protected def get_quiz @quiz = @context.quizzes.find(params[:id] || params[:quiz_id]) @quiz_name = @quiz.title @quiz end # if this returns false, it's rendering or redirecting, so return from the # action that called it def check_lockdown_browser(security_level, redirect_return_url) return true if @quiz.grants_right?(@current_user, session, :grade) plugin = Canvas::LockdownBrowser.plugin.base if plugin.require_authorization_redirect?(self) redirect_to(plugin.redirect_url(self, redirect_return_url)) return false elsif !plugin.authorized?(self) redirect_to(:action => 'lockdown_browser_required', :quiz_id => @quiz.id) return false elsif !session['lockdown_browser_popup'] && @query_params = plugin.popup_window(self, security_level) @security_level = security_level session['lockdown_browser_popup'] = true render(:action => 'take_quiz_in_popup') return false end @lockdown_browser_authorized_to_view = true @headers = false @show_left_side = false @padless = true return true end # use this for all redirects while taking a quiz -- it'll add params to tell # the lockdown browser that it's ok to follow the redirect def quiz_redirect_params(opts = {}) return opts if [email protected]_lockdown_browser? || @quiz.grants_right?(@current_user, session, :grade) plugin = Canvas::LockdownBrowser.plugin.base plugin.redirect_params(self, opts) end helper_method :quiz_redirect_params def start_quiz! can_retry = @submission && (@quiz.unlimited_attempts? || @submission.attempts_left > 0 || @quiz.grants_right?(@current_user, session, :update)) preview = params[:preview] && @quiz.grants_right?(@current_user, session, :update) if !@submission || @submission.settings_only? || (@submission.completed? && can_retry && !@just_graded) || preview user_code = @current_user user_code = nil if preview user_code ||= temporary_user_code @submission = @quiz.generate_submission(user_code, !!preview) end if quiz_submission_active? if request.get? # currently, the only way to start_quiz! with a get request is to use the LDB take_quiz else # redirect to avoid refresh issues redirect_to polymorphic_url([@context, @quiz, 'take'], quiz_redirect_params(:preview => params[:preview])) end else flash[:error] = t('errors.no_more_attempts', "You have no quiz attempts left") unless @just_graded redirect_to named_context_url(@context, :context_quiz_url, @quiz, quiz_redirect_params) end end def take_quiz return unless quiz_submission_active? log_asset_access(@quiz, "quizzes", "quizzes", 'participate') flash[:notice] = t('notices.less_than_allotted_time', "You started this quiz near when it was due, so you won't have the full amount of time to take the quiz.") if @submission.less_than_allotted_time? if params[:question_id] && !valid_question?(@submission, params[:question_id]) redirect_to course_quiz_url(@context, @quiz) and return end @quiz_presenter = TakeQuizPresenter.new(@quiz, @submission, params) render :action => 'take_quiz' end def valid_question?(submission, question_id) submission.has_question?(question_id) end def can_take_quiz? return false if @locked return false unless authorized_action(@quiz, @current_user, :submit) return false if @quiz.require_lockdown_browser? && !check_lockdown_browser(:highest, named_context_url(@context, 'context_quiz_take_url', @quiz.id)) quiz_access_code_key = @quiz.access_code_key_for_user(@current_user) if @quiz.access_code.present? && params[:access_code] == @quiz.access_code session[quiz_access_code_key] = true end if @quiz.access_code.present? && !session[quiz_access_code_key] render :action => 'access_code' false elsif @quiz.ip_filter && [email protected]_ip?(request.remote_ip) render :action => 'invalid_ip' false else true end end def quiz_submission_active? @submission && (@submission.untaken? || @submission.preview?) && !@just_graded end # counts of submissions queried in #managed_quiz_data def submission_counts submitted_with_submissions = @context.students_visible_to(@current_user). joins(:quiz_submissions). where("quiz_submissions.quiz_id=? AND quiz_submissions.workflow_state<>'settings_only'", @quiz) @submitted_student_count = submitted_with_submissions.count(:id, :distinct => true) #add logged out submissions @submitted_student_count += @quiz.quiz_submissions.logged_out.not_settings_only.count @any_submissions_pending_review = submitted_with_submissions.where("quiz_submissions.workflow_state = 'pending_review'").count > 0 end def set_download_submission_dialog_title js_env SUBMISSION_DOWNLOAD_DIALOG_TITLE: I18n.t('#quizzes.download_all_quiz_file_upload_submissions', 'Download All Quiz File Upload Submissions') end end
agpl-3.0
rockcesar/odoo_addons
first_module/models/res_partner_h.py
383
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models from odoo import tools, _ from odoo.exceptions import ValidationError class res_partner(models.Model): _name = "res.partner" _description = "Res Partner" _inherit = ['res.partner'] partner_number = fields.Char('Partner number')
agpl-3.0
gaelenh/python-reprints
reprints/service.py
2048
# -*- coding: utf-8 -*- # # This file is part of reprints released under the AGPLv3 license. # See the NOTICE for more information. # future compatibilty from __future__ import absolute_import # Pre-importer monkey patching from gevent import monkey monkey.patch_all() # standard from argparse import ArgumentParser import argparse # third party from gevent.wsgi import WSGIServer # local from reprints.server import ImageServer from reprints.settings import init_settings from reprints.iohandler import get_iohandler class AppContainer(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): return self.app.handle_request(environ, start_response) def create_app(config_file): settings = init_settings(config_file) iohandler = get_iohandler(settings) server = ImageServer(iohandler) app = AppContainer(server) return app def get_server(bind_ip, port, config_file): app = create_app(config_file) http_server = WSGIServer((bind_ip, port), app, spawn='default') print ' * Running under gevent on http://%s:%s/' % (bind_ip, port) try: http_server.serve_forever() except KeyboardInterrupt: print ' * Stopped server' return http_server def parse_args(): parser = ArgumentParser(usage='python -m %(prog)s PORT CONFIG [-h] [--debug] [--bind BIND_IP]', prog='reprints.service', description='Start reprints http service') parser.add_argument('port', nargs=1, default=10110, type=int, metavar='PORT') parser.add_argument('config', nargs=1, type=argparse.FileType('rb'), metavar='CONFIG_FILE', help='YAML config file') parser.add_argument('--debug', action=u'store_true') parser.add_argument('--bind', dest='bind_ip', default='0.0.0.0') args = parser.parse_args() return args def main(): args = parse_args() server = get_server(bind_ip=args.bind_ip, port=args.port, config_file=args.config[0]) server.serve_forever() if __name__ == '__main__': main()
agpl-3.0
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc2x3tc1/impl/IfcVaporPermeabilityMeasureImpl.java
4969
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bimserver.models.ifc2x3tc1.impl; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import org.bimserver.emf.IdEObjectImpl; import org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package; import org.bimserver.models.ifc2x3tc1.IfcVaporPermeabilityMeasure; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Vapor Permeability Measure</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.bimserver.models.ifc2x3tc1.impl.IfcVaporPermeabilityMeasureImpl#getWrappedValue <em>Wrapped Value</em>}</li> * <li>{@link org.bimserver.models.ifc2x3tc1.impl.IfcVaporPermeabilityMeasureImpl#getWrappedValueAsString <em>Wrapped Value As String</em>}</li> * </ul> * * @generated */ public class IfcVaporPermeabilityMeasureImpl extends IdEObjectImpl implements IfcVaporPermeabilityMeasure { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcVaporPermeabilityMeasureImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc2x3tc1Package.Literals.IFC_VAPOR_PERMEABILITY_MEASURE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected int eStaticFeatureCount() { return 0; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getWrappedValue() { return (Double) eGet(Ifc2x3tc1Package.Literals.IFC_VAPOR_PERMEABILITY_MEASURE__WRAPPED_VALUE, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setWrappedValue(double newWrappedValue) { eSet(Ifc2x3tc1Package.Literals.IFC_VAPOR_PERMEABILITY_MEASURE__WRAPPED_VALUE, newWrappedValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void unsetWrappedValue() { eUnset(Ifc2x3tc1Package.Literals.IFC_VAPOR_PERMEABILITY_MEASURE__WRAPPED_VALUE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isSetWrappedValue() { return eIsSet(Ifc2x3tc1Package.Literals.IFC_VAPOR_PERMEABILITY_MEASURE__WRAPPED_VALUE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getWrappedValueAsString() { return (String) eGet(Ifc2x3tc1Package.Literals.IFC_VAPOR_PERMEABILITY_MEASURE__WRAPPED_VALUE_AS_STRING, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setWrappedValueAsString(String newWrappedValueAsString) { eSet(Ifc2x3tc1Package.Literals.IFC_VAPOR_PERMEABILITY_MEASURE__WRAPPED_VALUE_AS_STRING, newWrappedValueAsString); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void unsetWrappedValueAsString() { eUnset(Ifc2x3tc1Package.Literals.IFC_VAPOR_PERMEABILITY_MEASURE__WRAPPED_VALUE_AS_STRING); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isSetWrappedValueAsString() { return eIsSet(Ifc2x3tc1Package.Literals.IFC_VAPOR_PERMEABILITY_MEASURE__WRAPPED_VALUE_AS_STRING); } } //IfcVaporPermeabilityMeasureImpl
agpl-3.0
abramhindle/UnnaturalCodeFork
python/testdata/launchpad/lib/lp/services/webapp/publication.py
32930
# Copyright 2009-2011 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). __metaclass__ = type __all__ = [ 'LoginRoot', 'LaunchpadBrowserPublication', ] import re import sys import thread import threading import traceback import urllib from lazr.restful.utils import safe_hasattr from lazr.uri import ( InvalidURIError, URI, ) from psycopg2.extensions import TransactionRollbackError from storm.database import STATE_DISCONNECTED from storm.exceptions import ( DisconnectionError, IntegrityError, ) from storm.zope.interfaces import IZStorm import tickcount import transaction from zc.zservertracelog.interfaces import ITraceLog import zope.app.publication.browser from zope.authentication.interfaces import IUnauthenticatedPrincipal from zope.component import ( getGlobalSiteManager, getUtility, queryMultiAdapter, ) from zope.error.interfaces import IErrorReportingUtility from zope.event import notify from zope.interface import ( implements, providedBy, ) from zope.publisher.interfaces import ( IPublishTraverse, Retry, StartRequestEvent, ) from zope.publisher.interfaces.browser import ( IBrowserRequest, IDefaultSkin, ) from zope.publisher.publish import mapply from zope.security.management import newInteraction from zope.security.proxy import removeSecurityProxy from zope.traversing.interfaces import BeforeTraverseEvent from lp.app.interfaces.launchpad import ILaunchpadCelebrities import lp.layers as layers from lp.registry.interfaces.person import ( IPerson, IPersonSet, ITeam, ) from lp.services import features from lp.services.config import config from lp.services.database.interfaces import ( IDatabasePolicy, IStoreSelector, MASTER_FLAVOR, ) from lp.services.database.policy import LaunchpadDatabasePolicy from lp.services.features.flags import NullFeatureController from lp.services.oauth.interfaces import IOAuthSignedRequest from lp.services.osutils import open_for_writing import lp.services.webapp.adapter as da from lp.services.webapp.interfaces import ( FinishReadOnlyRequestEvent, ILaunchpadRoot, IOpenLaunchBag, IPlacelessAuthUtility, IPrimaryContext, NoReferrerError, OffsiteFormPostError, ) from lp.services.webapp.opstats import OpStats from lp.services.webapp.vhosts import allvhosts METHOD_WRAPPER_TYPE = type({}.__setitem__) OFFSITE_POST_WHITELIST = ('/+storeblob', '/+request-token', '/+access-token', '/+hwdb/+submit', '/+openid') def maybe_block_offsite_form_post(request): """Check if an attempt was made to post a form from a remote site. This is a cross-site request forgery (XSRF/CSRF) countermeasure. The OffsiteFormPostError exception is raised if the following holds true: 1. the request method is POST *AND* 2. a. the HTTP referer header is empty *OR* b. the host portion of the referrer is not a registered vhost """ if request.method != 'POST': return if (IOAuthSignedRequest.providedBy(request) or not IBrowserRequest.providedBy(request)): # We only want to check for the referrer header if we are # in the middle of a request initiated by a web browser. A # request to the web service (which is necessarily # OAuth-signed) or a request that does not implement # IBrowserRequest (such as an XML-RPC request) can do # without a Referer. return if request['PATH_INFO'] in OFFSITE_POST_WHITELIST: # XXX: jamesh 2007-11-23 bug=124421: # Allow offsite posts to our TestOpenID endpoint. Ideally we'd # have a better way of marking this URL as allowing offsite # form posts. # # XXX gary 2010-03-09 bug=535122,538097 # The one-off exceptions are necessary because existing # non-browser applications make requests to these URLs # without providing a Referer. Apport makes POST requests # to +storeblob without providing a Referer (bug 538097), # and launchpadlib used to make POST requests to # +request-token and +access-token without providing a # Referer. # # XXX Abel Deuring 2010-04-09 bug=550973 # The HWDB client "checkbox" accesses /+hwdb/+submit without # a referer. This will change in the version in Ubuntu 10.04, # but Launchpad should support HWDB submissions from older # Ubuntu versions during their support period. # # We'll have to keep an application's one-off exception # until the application has been changed to send a # Referer, and until we have no legacy versions of that # application to support. For instance, we can't get rid # of the apport exception until after Lucid's end-of-life # date. We should be able to get rid of the launchpadlib # exception after Karmic's end-of-life date. return if request['PATH_INFO'].startswith('/+openid-callback'): # If this is a callback from an OpenID provider, we don't require an # on-site referer (because the provider may be off-site). This # exception was added as a result of bug 597324 (message #10 in # particular). return referrer = request.getHeader('referer') # Match HTTP spec misspelling. if not referrer: raise NoReferrerError('No value for REFERER header') # XXX: jamesh 2007-04-26 bug=98437: # The Zope testing infrastructure sets a default (incorrect) # referrer value of "localhost" or "localhost:9000" if no # referrer is included in the request. We let it pass through # here for the benefits of the tests. Web browsers send full # URLs so this does not open us up to extra XSRF attacks. if referrer in ['localhost', 'localhost:9000']: return # Extract the hostname from the referrer URI try: hostname = URI(referrer).host except InvalidURIError: hostname = None if hostname not in allvhosts.hostnames: raise OffsiteFormPostError(referrer) class ProfilingOops(Exception): """Fake exception used to log OOPS information when profiling pages.""" class LoginRoot: """Object that provides IPublishTraverse to return only itself. We anchor the +login view to this object. This allows other special namespaces to be traversed, but doesn't traverse other normal names. """ implements(IPublishTraverse) def publishTraverse(self, request, name): if not request.getTraversalStack(): root_object = getUtility(ILaunchpadRoot) view = queryMultiAdapter((root_object, request), name=name) return view else: return self class LaunchpadBrowserPublication( zope.app.publication.browser.BrowserPublication): """Subclass of z.a.publication.BrowserPublication that removes ZODB. This subclass undoes the ZODB-specific things in ZopePublication, a superclass of z.a.publication.BrowserPublication. """ # This class does not __init__ its parent or specify exception types # so that it can replace its parent class. root_object_interface = ILaunchpadRoot def __init__(self, db): self.db = db self.thread_locals = threading.local() def annotateTransaction(self, txn, request, ob): """See `zope.app.publication.zopepublication.ZopePublication`. We override the method to simply save the authenticated user id in the transaction. """ # It is possible that request.principal is None if the principal has # not been set yet. if request.principal is not None: txn.setUser(request.principal.id) return txn def getDefaultTraversal(self, request, ob): superclass = zope.app.publication.browser.BrowserPublication return superclass.getDefaultTraversal(self, request, ob) def getApplication(self, request): end_of_traversal_stack = request.getTraversalStack()[:1] if end_of_traversal_stack == ['+login']: return LoginRoot() else: return getUtility(self.root_object_interface) # The below overrides to zopepublication (callTraversalHooks, # afterTraversal, and _maybePlacefullyAuthenticate) make the # assumption that there will never be a ZODB "local" # authentication service (such as the "pluggable auth service"). # If this becomes untrue at some point, the code will need to be # revisited. def beforeTraversal(self, request): notify(StartRequestEvent(request)) request._traversalticks_start = tickcount.tickcount() threadid = thread.get_ident() threadrequestfile = open_for_writing( 'logs/thread-%s.request' % threadid, 'w') try: request_txt = unicode(request).encode('UTF-8') except Exception: request_txt = 'Exception converting request to string\n\n' try: request_txt += traceback.format_exc() except: request_txt += 'Unable to render traceback!' threadrequestfile.write(request_txt) threadrequestfile.close() # Tell our custom database adapter that the request has started. da.set_request_started() newInteraction(request) transaction.begin() # Now we are logged in, install the correct IDatabasePolicy for # this request. db_policy = IDatabasePolicy(request) getUtility(IStoreSelector).push(db_policy) getUtility(IOpenLaunchBag).clear() # Set the default layer. adapters = getGlobalSiteManager().adapters layer = adapters.lookup((providedBy(request),), IDefaultSkin, '') if layer is not None: layers.setAdditionalLayer(request, layer) principal = self.getPrincipal(request) request.setPrincipal(principal) self.maybeRestrictToTeam(request) maybe_block_offsite_form_post(request) def getPrincipal(self, request): """Return the authenticated principal for this request. If there is no authenticated principal or the principal represents a personless account, return the unauthenticated principal. """ auth_utility = getUtility(IPlacelessAuthUtility) principal = None # +opstats and +haproxy are status URLs that must not query the DB at # all. This is enforced by webapp/dbpolicy.py. If the request is for # one of those two pages, don't even try to authenticate, because it # may fail. We haven't traversed yet, so we have to sniff the request # this way. Even though PATH_INFO is always present in real requests, # we need to tread carefully (``get``) because of test requests in our # automated tests. if request.get('PATH_INFO') not in [u'/+opstats', u'/+haproxy']: principal = auth_utility.authenticate(request) if principal is not None: assert principal.person is not None else: # This is an unauthenticated user. principal = auth_utility.unauthenticatedPrincipal() assert principal is not None, "Missing unauthenticated principal." return principal def maybeRestrictToTeam(self, request): restrict_to_team = config.launchpad.restrict_to_team if not restrict_to_team: return restrictedlogin = '+restricted-login' restrictedinfo = '+restricted-info' # Always allow access to +restrictedlogin and +restrictedinfo. traversal_stack = request.getTraversalStack() if (traversal_stack == [restrictedlogin] or traversal_stack == [restrictedinfo]): return principal = request.principal team = getUtility(IPersonSet).getByName(restrict_to_team) if team is None: raise AssertionError( 'restrict_to_team "%s" not found' % restrict_to_team) elif not ITeam.providedBy(team): raise AssertionError( 'restrict_to_team "%s" is not a team' % restrict_to_team) if IUnauthenticatedPrincipal.providedBy(principal): location = '/%s' % restrictedlogin else: # We have a team we can work with. user = IPerson(principal) if (user.inTeam(team) or user.inTeam(getUtility(ILaunchpadCelebrities).admin)): return else: location = '/%s' % restrictedinfo non_restricted_url = self.getNonRestrictedURL(request) if non_restricted_url is not None: location += '?production=%s' % urllib.quote(non_restricted_url) request.response.setResult('') request.response.redirect(location, temporary_if_possible=True) # Quash further traversal. request.setTraversalStack([]) def getNonRestrictedURL(self, request): """Returns the non-restricted version of the request URL. The intended use is for determining the equivalent URL on the production Launchpad instance if a user accidentally ends up on a restrict_to_team Launchpad instance. If a non-restricted URL can not be determined, None is returned. """ base_host = config.vhost.mainsite.hostname production_host = config.launchpad.non_restricted_hostname # If we don't have a production hostname, or it is the same as # this instance, then we can't provide a nonRestricted URL. if production_host is None or base_host == production_host: return None # Are we under the main site's domain? uri = URI(request.getURL()) if not uri.host.endswith(base_host): return None # Update the hostname, and complete the URL from the request: new_host = uri.host[:-len(base_host)] + production_host uri = uri.replace(host=new_host, path=request['PATH_INFO']) query_string = request.get('QUERY_STRING') if query_string: uri = uri.replace(query=query_string) return str(uri) def constructPageID(self, view, context, view_names=()): """Given a view, figure out what its page ID should be. This provides a hook point for subclasses to override. """ if context is None: pageid = '' else: # ZCML registration will set the name under which the view # is accessible in the instance __name__ attribute. We use # that if it's available, otherwise fall back to the class # name. if safe_hasattr(view, '__name__'): view_name = view.__name__ else: view_name = view.__class__.__name__ names = [ n for n in [view_name] + list(view_names) if n is not None] context_name = context.__class__.__name__ # Is this a view of a generated view class, # such as ++model++ view of Product:+bugs. Recurse! if ' ' in context_name and safe_hasattr(context, 'context'): return self.constructPageID(context, context.context, names) view_names = ':'.join(names) pageid = '%s:%s' % (context_name, view_names) # The view name used in the pageid usually comes from ZCML and so # it will be a unicode string although it shouldn't. To avoid # problems we encode it into ASCII. return pageid.encode('US-ASCII') def callObject(self, request, ob): """See `zope.publisher.interfaces.IPublication`. Our implementation make sure that no result is returned on redirect. It also sets the launchpad.userid and launchpad.pageid WSGI environment variables. """ request._publicationticks_start = tickcount.tickcount() if request.response.getStatus() in [301, 302, 303, 307]: return '' request.setInWSGIEnvironment( 'launchpad.userid', request.principal.id) # The view may be security proxied view = removeSecurityProxy(ob) # It's possible that the view is a bound method. view = getattr(view, 'im_self', view) context = removeSecurityProxy(getattr(view, 'context', None)) pageid = self.constructPageID(view, context) request.setInWSGIEnvironment('launchpad.pageid', pageid) # And spit the pageid out to our tracelog. tracelog(request, 'p', pageid) # For status URLs, where we really don't want to have any DB access # at all, ensure that all flag lookups will stop early. if pageid in ( 'RootObject:OpStats', 'RootObject:+opstats', 'RootObject:+haproxy'): request.features = NullFeatureController() features.install_feature_controller(request.features) # Calculate the hard timeout: needed because featureflags can be used # to control the hard timeout, and they trigger DB access, but our # DB tracers are not safe for reentrant use, so we must do this # outside of the SQL stack. We must also do it after traversal so that # the view is known and can be used in scope resolution. As we # actually stash the pageid after afterTraversal, we need to do this # even later. da.set_permit_timeout_from_features(True) da._get_request_timeout() if isinstance(removeSecurityProxy(ob), METHOD_WRAPPER_TYPE): # this is a direct call on a C-defined method such as __repr__ or # dict.__setitem__. Apparently publishing this is possible and # acceptable, at least in the case of # lp.services.webapp.servers.PrivateXMLRPCPublication. # mapply cannot handle these methods because it cannot introspect # them. We'll just call them directly. return ob(*request.getPositionalArguments()) return mapply(ob, request.getPositionalArguments(), request) def afterCall(self, request, ob): """See `zope.publisher.interfaces.IPublication`. Our implementation calls self.finishReadOnlyRequest(), which by default aborts the transaction, for read-only requests. Because of this we cannot chain to the superclass and implement the whole behaviour here. """ assert hasattr(request, '_publicationticks_start'), ( 'request._publicationticks_start, which should have been set by ' 'callObject(), was not found.') ticks = tickcount.difference( request._publicationticks_start, tickcount.tickcount()) request.setInWSGIEnvironment('launchpad.publicationticks', ticks) # Calculate SQL statement statistics. sql_statements = da.get_request_statements() sql_milliseconds = sum( endtime - starttime for starttime, endtime, id, statement, tb in sql_statements) # Log publication tickcount, sql statement count, and sql time # to the tracelog. tracelog(request, 't', '%d %d %d' % ( ticks, len(sql_statements), sql_milliseconds)) # Annotate the transaction with user data. That was done by # zope.app.publication.zopepublication.ZopePublication. txn = transaction.get() self.annotateTransaction(txn, request, ob) # Abort the transaction on a read-only request. # NOTHING AFTER THIS SHOULD CAUSE A RETRY. if request.method in ['GET', 'HEAD']: self.finishReadOnlyRequest(request, ob, txn) elif txn.isDoomed(): # The following sends an abort to the database, even though the # transaction is still doomed. txn.abort() else: txn.commit() # Don't render any content for a HEAD. This was done # by zope.app.publication.browser.BrowserPublication if request.method == 'HEAD': request.response.setResult('') try: getUtility(IStoreSelector).pop() except IndexError: # We have to cope with no database policy being installed # to allow doc/webapp-publication.txt tests to pass. These # tests rely on calling the afterCall hook without first # calling beforeTraversal or doing proper cleanup. pass def finishReadOnlyRequest(self, request, ob, txn): """Hook called at the end of a read-only request. By default it abort()s the transaction, but subclasses may need to commit it instead, so they must overwrite this. """ notify(FinishReadOnlyRequestEvent(ob, request)) txn.abort() def callTraversalHooks(self, request, ob): """ We don't want to call _maybePlacefullyAuthenticate as does zopepublication """ # In some cases we seem to be called more than once for a given # traversed object, so we need to be careful here and only append an # object the first time we see it. if ob not in request.traversed_objects: request.traversed_objects.append(ob) notify(BeforeTraverseEvent(ob, request)) def afterTraversal(self, request, ob): """See zope.publisher.interfaces.IPublication. This hook does not invoke our parent's afterTraversal hook in zopepublication.py because we don't want to call _maybePlacefullyAuthenticate. """ # Log the URL including vhost information to the ZServer tracelog. tracelog(request, 'u', request.getURL()) assert hasattr(request, '_traversalticks_start'), ( 'request._traversalticks_start, which should have been set by ' 'beforeTraversal(), was not found.') ticks = tickcount.difference( request._traversalticks_start, tickcount.tickcount()) request.setInWSGIEnvironment('launchpad.traversalticks', ticks) def _maybePlacefullyAuthenticate(self, request, ob): """ This should never be called because we've excised it in favor of dealing with auth in events; if it is called for any reason, raise an error """ raise NotImplementedError def handleException(self, object, request, exc_info, retry_allowed=True): # Uninstall the database policy. store_selector = getUtility(IStoreSelector) if store_selector.get_current() is not None: db_policy = store_selector.pop() else: db_policy = None orig_env = request._orig_env ticks = tickcount.tickcount() if (hasattr(request, '_publicationticks_start') and ('launchpad.publicationticks' not in orig_env)): # The traversal process has been started but hasn't completed. assert 'launchpad.traversalticks' in orig_env, ( 'We reached the publication process so we must have finished ' 'the traversal.') ticks = tickcount.difference( request._publicationticks_start, ticks) request.setInWSGIEnvironment('launchpad.publicationticks', ticks) elif (hasattr(request, '_traversalticks_start') and ('launchpad.traversalticks' not in orig_env)): # The traversal process has been started but hasn't completed. ticks = tickcount.difference( request._traversalticks_start, ticks) request.setInWSGIEnvironment('launchpad.traversalticks', ticks) else: # The exception wasn't raised in the middle of the traversal nor # the publication, so there's nothing we need to do here. pass # Log an OOPS for DisconnectionErrors: we don't expect to see # disconnections as a routine event, so having information about them # is important. See Bug #373837 for more information. # We need to do this before we re-raise the exception as a Retry. if isinstance(exc_info[1], DisconnectionError): getUtility(IErrorReportingUtility).raising(exc_info, request) def should_retry(exc_info): if not retry_allowed: return False # If we get a LookupError and the default database being # used is a replica, raise a Retry exception instead of # returning the 404 error page. We do this in case the # LookupError is caused by replication lag. Our database # policy forces the use of the master database for retries. if (isinstance(exc_info[1], LookupError) and isinstance(db_policy, LaunchpadDatabasePolicy)): if db_policy.default_flavor == MASTER_FLAVOR: return False else: return True # Retry exceptions need to be propagated so they are # retried. Retry exceptions occur when an optimistic # transaction failed, such as we detected two transactions # attempting to modify the same resource. # DisconnectionError and TransactionRollbackError indicate # a database transaction failure, and should be retried # The appserver detects the error state, and a new database # connection is opened allowing the appserver to cope with # database or network outages. # An IntegrityError may be caused when we insert a row # into the database that already exists, such as two requests # doing an insert-or-update. It may succeed if we try again. if isinstance(exc_info[1], (Retry, DisconnectionError, IntegrityError, TransactionRollbackError)): return True return False # Re-raise Retry exceptions ourselves rather than invoke # our superclass handleException method, as it will log OOPS # reports etc. This would be incorrect, as transaction retry # is a normal part of operation. if should_retry(exc_info): if request.supportsRetry(): # Remove variables used for counting ticks as this request is # going to be retried. orig_env.pop('launchpad.traversalticks', None) orig_env.pop('launchpad.publicationticks', None) # Our endRequest needs to know if a retry is pending or not. request._wants_retry = True if isinstance(exc_info[1], Retry): raise raise Retry(exc_info) superclass = zope.app.publication.browser.BrowserPublication superclass.handleException( self, object, request, exc_info, retry_allowed) # If it's a HEAD request, we don't care about the body, regardless of # exception. # UPSTREAM: Should this be part of zope, # or is it only required because of our customisations? # - Andrew Bennetts, 2005-03-08 if request.method == 'HEAD': request.response.setResult('') def beginErrorHandlingTransaction(self, request, ob, note): """Hook for when a new view is started to handle an exception. We need to add an additional behavior to the usual Zope behavior. We must restart the request timer. Otherwise we can get OOPS errors from our exception views inappropriately. """ super(LaunchpadBrowserPublication, self).beginErrorHandlingTransaction(request, ob, note) # XXX: gary 2008-11-04 bug=293614: As the bug describes, we want to # only clear the SQL records and timeout when we are preparing for a # view (or a side effect). Otherwise, we don't want to clear the # records because they are what the error reporting utility uses to # create OOPS reports with the SQL commands that led up to the error. # At the moment, we can only distinguish based on the "note" argument: # an undocumented argument of this undocumented method. if note in ('application error-handling', 'application error-handling side-effect'): da.clear_request_started() da.set_request_started() def endRequest(self, request, object): superclass = zope.app.publication.browser.BrowserPublication superclass.endRequest(self, request, object) da.clear_request_started() getUtility(IOpenLaunchBag).clear() # Maintain operational statistics. if getattr(request, '_wants_retry', False): OpStats.stats['retries'] += 1 else: OpStats.stats['requests'] += 1 # Increment counters for HTTP status codes we track individually # NB. We use IBrowserRequest, as other request types such as # IXMLRPCRequest use IHTTPRequest as a superclass. # This should be fine as Launchpad only deals with browser # and XML-RPC requests. if IBrowserRequest.providedBy(request): OpStats.stats['http requests'] += 1 status = request.response.getStatus() if status == 404: # Not Found OpStats.stats['404s'] += 1 elif status == 500: # Unhandled exceptions OpStats.stats['500s'] += 1 elif status == 503: # Timeouts OpStats.stats['503s'] += 1 # Increment counters for status code groups. status_group = str(status)[0] + 'XXs' OpStats.stats[status_group] += 1 # Increment counter for 5XXs_b. if is_browser(request) and status_group == '5XXs': OpStats.stats['5XXs_b'] += 1 # Make sure our databases are in a sane state for the next request. thread_name = threading.currentThread().getName() for name, store in getUtility(IZStorm).iterstores(): try: assert store._connection._state != STATE_DISCONNECTED, ( "Bug #504291: Store left in a disconnected state.") except AssertionError: # The Store is in a disconnected state. This should # not happen, as store.rollback() should have been called # by now. Log an OOPS so we know about this. This # is Bug #504291 happening. getUtility(IErrorReportingUtility).raising( sys.exc_info(), request) # Repair things so the server can remain operational. store.rollback() # Reset all Storm stores when not running the test suite. # We could reset them when running the test suite but # that'd make writing tests a much more painful task. We # still reset the slave stores though to minimize stale # cache issues. if thread_name != 'MainThread' or name.endswith('-slave'): store.reset() class InvalidThreadsConfiguration(Exception): """Exception thrown when the number of threads isn't set correctly.""" class DefaultPrimaryContext: """The default primary context is the context.""" implements(IPrimaryContext) def __init__(self, context): self.context = context _browser_re = re.compile(r"""(?x)^( Mozilla | Opera | Lynx | Links | w3m )""") def is_browser(request): """Return True if we believe the request was from a browser. There will be false positives and false negatives, as we can only tell this from the User-Agent: header and this cannot be trusted. Almost all web browsers provide a User-Agent: header starting with 'Mozilla'. This is good enough for our uses. We also add a few other common matches as well for good measure. We could massage one of the user-agent databases that are available into a usable, but we would gain little. """ user_agent = request.getHeader('User-Agent') return ( user_agent is not None and _browser_re.search(user_agent) is not None) def tracelog(request, prefix, msg): """Emit a message to the ITraceLog, or do nothing if there is none. The message will be prefixed by ``prefix`` to make writing parsers easier. ``prefix`` should be unique and contain no spaces, and preferably a single character to save space. """ tracelog = ITraceLog(request, None) if tracelog is not None: tracelog.log('%s %s' % (prefix, msg.encode('US-ASCII')))
agpl-3.0
ONLYOFFICE/core
UnicodeConverter/icubuilds-mac/icu/icu/layout/SingleSubstitutionSubtables.cpp
2343
/* * * (C) Copyright IBM Corp. 1998-2013 - All Rights Reserved * */ #include "LETypes.h" #include "LEGlyphFilter.h" #include "OpenTypeTables.h" #include "GlyphSubstitutionTables.h" #include "SingleSubstitutionSubtables.h" #include "GlyphIterator.h" #include "LESwaps.h" U_NAMESPACE_BEGIN le_uint32 SingleSubstitutionSubtable::process(const LEReferenceTo<SingleSubstitutionSubtable> &base, GlyphIterator *glyphIterator, LEErrorCode &success, const LEGlyphFilter *filter) const { switch(SWAPW(subtableFormat)) { case 0: return 0; case 1: { const LEReferenceTo<SingleSubstitutionFormat1Subtable> subtable(base, success, (const SingleSubstitutionFormat1Subtable *) this); return subtable->process(subtable, glyphIterator, success, filter); } case 2: { const LEReferenceTo<SingleSubstitutionFormat2Subtable> subtable(base, success, (const SingleSubstitutionFormat2Subtable *) this); return subtable->process(subtable, glyphIterator, success, filter); } default: return 0; } } le_uint32 SingleSubstitutionFormat1Subtable::process(const LEReferenceTo<SingleSubstitutionFormat1Subtable> &base, GlyphIterator *glyphIterator, LEErrorCode &success, const LEGlyphFilter *filter) const { LEGlyphID glyph = glyphIterator->getCurrGlyphID(); le_int32 coverageIndex = getGlyphCoverage(base, glyph, success); if (coverageIndex >= 0) { TTGlyphID substitute = ((TTGlyphID) LE_GET_GLYPH(glyph)) + SWAPW(deltaGlyphID); if (filter == NULL || filter->accept(LE_SET_GLYPH(glyph, substitute))) { glyphIterator->setCurrGlyphID(substitute); } return 1; } return 0; } le_uint32 SingleSubstitutionFormat2Subtable::process(const LEReferenceTo<SingleSubstitutionFormat2Subtable> &base, GlyphIterator *glyphIterator, LEErrorCode &success, const LEGlyphFilter *filter) const { LEGlyphID glyph = glyphIterator->getCurrGlyphID(); le_int32 coverageIndex = getGlyphCoverage(base, glyph, success); if (coverageIndex >= 0) { TTGlyphID substitute = SWAPW(substituteArray[coverageIndex]); if (filter == NULL || filter->accept(LE_SET_GLYPH(glyph, substitute))) { glyphIterator->setCurrGlyphID(substitute); } return 1; } return 0; } U_NAMESPACE_END
agpl-3.0